text:
Tell me my console dimensions!
Output terminal dimensions (columns and rows) in any two-number decimal format*. For example, an output could be 80x25.

Inspiration. Prompt.
* Output must have both measures on a single or two consecutive lines, and there may be no more than one leading and/or trailing line of output (optionally followed by a newline). The (up to four) lines must be no longer than max(cols,1+len(str(cols))+len(str(rows))).

I have never seen a shorter upvoted challenge. Congrats!

@Mr.Xcoder I specialise in one-liners…

You are about to get a degree in one-lining posts! You are indeed good, no, very good at that :))...

what does 'consistent format' exactly means?

@FelipeNardiBatista Same style no matter what. E.g. you cannot output [1024,768] on one machine, and 600x400 on another.

can there be other information along side the answer?

@FelipeNardiBatista No, because then one could just do a complete memory dump (the answer must be in there).

that would not be consistent tho :D

what i mean is, does os.terminal_size(columns=80, lines=24) counts as a constintent format (that's the output)?

@FelipeNardiBatista I'll say yes for now, but revert if this leads to absurdities.

@Adám I guess just answering mode for cmd is one of these absurdities? Its output is localized thought, so you might consider it not to be consistent.

@Aaron Exactly. But if you just output lines 4 and 5, you're ok.

@FelipeNardiBatista Maybe like this: Output must have both measures on a single or two consecutive lines, and there may be no more than one leading and/or trailing line of output. The (up to four) lines must be no longer than the terminal width.

@Adám 'The lines must not be longer than the terminal width' what if one was to shrunk the terminal to width 4 as an example? were you refering to the default terminal width?

@Adám Doesn't len(str(cols)) already do log_10? Doesn't this mean that you're logging twice?

@wizzwizz4 Nicely spotted. Fixed.

*sh, 9
stty size

Output:
97 364

Also works in bash.

Or any other shell on a posix-like system.

Given the names of some languages seen on this site, it takes longer to figure out that *sh here refers to "bash, zsh, csh, dash, etc." rather than a language whose name consists of an asterisk followed by the letters s and h :-)

Technically you don't even need a shell to run a program. So the sh designation doesn't really make sense anyway.

8086 machine code, 11 bytes (as a function, non-competing)
Not really competing since it doesn't have visible output. This is just showing the shortest way to find the current screen dimensions, without the boilerplate code required for printing.
00000000  6a 40 1f a0 84 00 40 8a  26 4a 00                 |j@....@.&J.|
0000000b

How it works:
6a 40           |   push 0x40       ; bios data segment
1f              |   pop ds
a0 84 00        |   mov al, [0x84]  ; console rows - 1
40              |   inc ax
8a 26 4a 00     |   mov ah, [0x4a]  ; console columns

8086 machine code, 48 bytes (as a complete program)
00000000  1f bf 30 01 a0 84 04 40  e8 1a 00 b0 78 aa a0 4a  |..0....@....x..J|
00000010  04 e8 11 00 8d 8d d0 fe  8d 75 ff 06 1f fd ac cd  |.........u......|
00000020  29 e2 fb cd 20 d4 0a 0c  30 aa c1 e8 08 75 f6 c3  |)... ...0....u..|
00000030

How it works:
                |   org 0x100
                |   use16
1f              |       pop ds              ; clear ds (the stack always contains 0 on entry)
bf 30 01        |       mov di, d           ; set destination ptr
a0 84 04        |       mov al, [0x484]     ; console rows - 1
40              |       inc ax
e8 1a 00        |       call to_ascii       ; convert to ascii
b0 78           |       mov al, 'x'
aa              |       stosb
a0 4a 04        |       mov al, [0x44a]     ; console columns
e8 11 00        |       call to_ascii
8d 8d d0 fe     |       lea cx, [di-d]      ; number of characters to print
8d 75 ff        |       lea si, [di-1]      ; set source ptr
06              |       push es
1f              |       pop ds
fd              |       std                 ; reverse direction flag
ac              |   @@: lodsb               ; load (al = *si--)
cd 29           |       int 0x29            ; print al to console, bypassing stdout
e2 fb           |       loop @b             ; repeat while (--cx != 0)
cd 20           |       int 0x20            ; terminate
                |
                |   to_ascii:
d4 0a           |       aam 10              ; ah = (al / 10), al = (al % 10)
0c 30           |       or al, 0x30         ; convert al to ascii number
aa              |       stosb               ; store (*di++ = al)
c1 e8 08        |       shr ax, 8           ; shift ah to al
75 f6           |       jnz to_ascii        ; repeat if non-zero
c3              |       ret
                |
                |   d rb 0

I'm pretty sure a function submission would need a ret? Also, I'm not sure that you're allowed to clobber ds. This might need to be taken to Meta, as the function does work more than once, it just has unwanted side effects.

Why does "the stack always contain 0 on entry"? I don't know of any rule that the stack gets zeroed. I guess you're talking about popping the return value and thinking that's going to be 0? Is that guaranteed for a COM binary?

@CodyGray: in a COM program, the stack initially contains a near pointer to the start of the PSP (offset 0), so RET will jump back to PSP:0, which contains a call to EXIT. http://stackoverflow.com/a/12593311/371250

Ah, thanks for the clarification, @ninjalj. (Great answer you linked, BTW. I'd forgotten virtually all of the details about the PSP, despite having reverse-engineered its implementation many years ago.) But if you pop that pointer off the stack without pushing it back, don't you break the RET instruction at the end of the function?

@CodyGray: you'll note that the program exits via INT 20h, not via RET, exactly because after POPing exiting via RET no longer works.

@ais523, The function entry isn't really competing (and I should probably mark it as such...) since I think OP's question implies printing the result. In any case you could think of it as an inline function which doesn't need a ret :). About clobbering ds, I'm not aware of any rules that prohibit such side-effects, but feel free to discuss it on meta if you think this should be clarified.

Bash, 22 20 characters
echo $COLUMNS $LINES

Thanks to:

Doorknob for optimal output format (2 characters)

Sample run:
bash-4.3$ echo $COLUMNS $LINES
80 24

With just 1 more byte, echo $COLUMNS\x$LINES can o/p 80x24

@Pandya True, but not necessary.

Not sure if this complies with the new output format requirements, but you could just have $COLUMNS\x$LINES to output "bash: 90x50: command not found". Suppose that doesn't work with localisation though, or if that command actually exists!.

xterm, 6 bytes
As you don't need specific formate, you can simply use the resize (6 character) command of xterm:
$ resize
COLUMNS=120;
LINES=31;
export COLUMNS LINES;

Nice. But you may want to write a standard header, like #xterm, 6 bytes.

@Adám Is this type of output acceptable according to question?

Yes; https://codegolf.stackexchange.com/questions/118636/tell-me-my-console-dimensions/118673?noredirect=1#comment290692_118636.

@Adám ok. Just added header :)

This is not xterm-specific. Note also that the output depends on your shell.

sh, 20 bytes
tput lines;tput cols

.. Too obvious, maybe..

tput cols; !:0 cols saves one byte in bash

@marcos you mean tput lines;!:0 cols, right ?

Python 3, 30 bytes
import os
os.get_terminal_size

As it does not work in TIO, an alternative is used there:
Try it online!

Why not just os?

...it wont work on TIO, due to the operating system, so need to specify. It does work on Windows. Also import os and os. is shorter than from....

I can confirm it works on Window 10 without any modifications

Works on mac too

Technically Python 3.3+

@matsjoyce There's no need to specify that, since the current version is fine.

os.get_terminal_size is a function; you need to add () to get the actual output.

@jwodder https://codegolf.meta.stackexchange.com/a/7615/66418

Saying there's no need to specify version is silly - in the future this might not work with Python4, and future readers would like to know what version they need to make it work.

@JonathanHartley it's the current version of python 3, as it says in the title

@FelipeNardiBatista, I guess it does say 3 in the title, I kinda spaced on that.

C (linux only), 63 61
short m[4];main(){ioctl(0,21523,m);printf("%dx%d",*m,m[1]);}

You could win two bytes by replacing m[0] by *m.

You can save one byte by making m an argument of main: main(short m){ioctl(0,21523,&m);printf("%dx%d",m,(&m)[1]);}

main(int m){ioctl(0,21523,&m);printf("%x",m);} would be 46 bytes, with sizes printed in base 16 and no separator (other than possible leading zeroes) between cols and rows.

C#, 59 bytes
using c=System.Console;_=>c.WindowWidth+"x"+c.WindowHeight;

Compiles to a Func<int, string, however, the input is not used.

Does not work; I found this returns the size the console would be if AllocConsole() were called, not the size the console standard input and output are actually connected to. Question here: http://stackoverflow.com/questions/35688348/how-do-i-determine-size-of-ansi-terminal  What I held back when asking the question is I was actually running on a Windows environment with stdin & stdout connected to a ssh pipeline. The win32 ssh implementation does not provide the necessary.

APL (Dyalog), 3 bytes
(Posting an answer already since this really isn't my challenge.)
⎕SD Screen Dimensions
Sample run:
      ⎕SD
25 79

NodeJS, 50 48 46 bytes
> s=process.stdout;console.log(s.columns,s.rows)
80 25

Uses process.stdouts columns and rows values.

Thanks @ETHproductions, added console.log to output to console :)

No problem :-) The output can be in any consistent format, so I think you can save a couple bytes by doing console.log([s.columns,s.rows]).

If space between is consistent, then console.log(s.columns,s.rows) saves two more! Thanks again!

1 byte off: with(process.stdout)console.log(columns,rows)

And a few more bytes off (if this counts): with(process.stdout)write(columns+[rows]). Or, if it doesn't count: with(process.stdout)write(columns+' '+rows)

@Markasoftware Ooh, that's clever. I don't think the first one should count, though.

Ruby, 41 36 21 + 13 = 34 bytes
Run with the command line flag -rio/console
p IO.console.winsize

This is my first Ruby golf, so tell me if there is anything I can do better.
5 bytes saved thanks to SztupY
2 bytes saved thanks to manatwork

This outputs height then width as a length two list.
Example output:
[25, 80]

you can potentially move the requires into the -r command line parameter which is only 2 extra bytes

No need for the single quotes around io/console, no shell will perform undesired expansion on it if left unquoted.

GNU Forth, 7 bytes
form .s

form       – urows ucols        gforth       “form”
The number of lines and columns in the terminal.

Sample Output
<2> 24 80

Try It Online !

PowerShell + Mode, 11 Bytes?
Output may not be acceptable in current form.
the mode command is a default windows utility
Meta Post regarding usage of mode without specifying con
(mode)[3,4]

gets the output of mode:
<Whitespace>
Status for device CON:
----------------------
    Lines:          3000
    Columns:        120
    Keyboard rate:  31
    Keyboard delay: 1
    Code page:      850

then the 4th & 5th lines ([3,4]) outputting:
PS H:\> (mode)[3,4]
    Lines:          3000
    Columns:        120

Save two bytes: (mode)[3,4]-replace"\D"

for this to work here, i need to use (mode con)[3..4]

Ah @FelipeNardiBatista is probably right that you need con.

is the -replace"\D+" necessary?

@FelipeNardiBatista is con neccessary? this gets the first lines absolutely, and I believe con is always first? i'd say a standard system will also only have one output for mode, which is what we should assume?

in my system, con is the last one, i get LPT1, COM3, COM2, COM1 and then CON

@FelipeNardiBatista I think since a fresh install of windows with no strange hardware ~should~ only have one it probably isn't required? at least a brand new win10 vm with only the basics has nothing, my work laptop and home PC only display con too.

that's not my call, just stating what happens here

@FelipeNardiBatista I can't find a meta post that clears this up at all, might make one myself regarding system architecture/hardware/assumptions.

@ConnorLSW It's just that my system does work fine, but your answer simply doesn't work here

C# 94 bytes (whole app)
MetaColon's whole app answer can be shortened quite a lot:
using c=System.Console;class P{static void Main(){c.Write(c.WindowWidth+' '+c.WindowHeight);}}

Swift, 99 bytes
import Foundation;var w=winsize();ioctl(STDOUT_FILENO,UInt(TIOCGWINSZ),&w);print(w.ws_col,w.ws_row)

Thanks to the guys at Vapor for their Console package.

C#, 85 Bytes
()=>System.Console.Write(System.Console.WindowWidth+"x"+System.Console.WindowHeight);

If you want a whole application code, we'd have 115 101 94 Bytes:
using C=System.Console;class P{static void Main()=>C.Write(C.WindowWidth+"x"+C.WindowHeight);}

However you could mean the Buffer size as well, we'd have 85 Bytes again
()=>System.Console.Write(System.Console.BufferWidth+"x"+System.Console.BufferHeight);

Or as a whole application code (obviously 115 101 94 Bytes again):
using C=System.Console;class P{static void Main()=>C.Write(C.BufferWidth+"x"+C.BufferHeight);}

Saved 14 Bytes in the whole application code with the help of Caius Jard

104 bytes whole app, perhaps you can extend the logic to your other variations: using c=System.Console;class P{static void Main(){c.WriteLine(c.WindowWidth);c.Write(c.WindowHeight);}}

(I'm not sure how to golf if I have a shorter answer; do i edit yours, comment yours, or post my own?)

@CaiusJard You could post your own answer or comment an improvement and let the answerer decide if they want to incorporate it or not.

I wanted to, just couldn't edit my comment in time... Posted my own answer (that included it) virtually simultaneously though so I prmise I wasn't nicking your inspiration :). Not too sure whether I feel it's cheating to essentially be writing a function that returns the answer, rather than a whole app - all the other answers are pretty much a whole app, but then again CSharppPad.com will accept your "sole function" version and run it.. should look up the rules on golfing i guess

@CaiusJard Functions/methods are allowed implicitly unless explicitly disallowed in the challenge itself. Therefore, an anonymous function is fine, see my answer for a version that works well.

@CaiusJard You're right. I hope you don't consider it cheated if I update my answer to your version.

if you using System you can shorten your answer

@FelipeNardiBatista the problem is, that it wouldn't be a lambda expression anymore then - I'm not sure, wether it'd be allowed.

@MetaColon it is

Batch, 25 19 18 17 bytes
Saved 6 bytes by piping directly to the "find" command.
Saved 1 byte thanks to Adám / OP.
Saved 1 byte thanks to comment by OP.
mode con|find "n"

This outputs the command itself since echo is on but, as commented by OP, a leading line is OK.

Depending on your setup, it may work with only 13 bytes. However, it seems that having anything using COM ports will cause overly verbose output.
mode|find "n"

Save a byte s: → n.

@FelipeNardiBatista Yeah, and mine says I've got 9001 lines. It's just a setting: Properties>Layout>Screen Buffer Size.

@FelipeNardiBatista Windows console dimensions are not the same as the window dimensions. That's why scroll bars show up when you make the window smaller. Per OP, this exact solution is OK.

@Adám Dangit, I looked for a shorter string and don't know how I overlooked it. It's probably because I started with just mode but found that adding  con was shorter than looking for two different sets of characters with findstr.

@Adám Based on your comment, would this be valid: @mode|find "L" /i ? It returns Lines, Columns, and Keyboard Delay with 17 bytes instead of the 18 above. Do those leading / trailing lines need to be empty?

Yes, but better is: mode|find/i"n" at only 14 bytes.

@mode|find "L" /i outputs 11 lines for me, and @mode|find/i"n"output 25 lines, with info of other devices

@FelipeNardiBatista Ah, it probably depends on connected devices. mode con|find "n" it is, then.

@EngineerToast You can remove the @, no?

This prints the screen buffer dimensions, not those of the console window.

is con definitely required? I've been using mode from multiple cli's on multiple devices for years and never gotten output other than the single device, If a 'standard' system can run it without con that's -4, and I think it makes sense.

@ConnorLSW It seems to also output information for anything on COM ports. as Felipe Nardi Batista pointed out, their systems outputs a ton on information. I prefer solutions that are robust versus those that require specific setups to work, so I'll leave it as is. However, it's worth noting.

@Adám OVER 9000?!

Java + *nix, 113
interface B{static void main(String[] a)throws Exception{new ProcessBuilder("stty","size").inheritIO().start();}}

Ungolfed:
interface B{
    static void main(String[] a)throws Exception{
        new ProcessBuilder("stty","size").inheritIO().start();
    }
}

ProcessBuilder.inheritIO causes a child process input/output to be inherited; this is the default in C with exec. In Java, the default is "piped." As you can see, this is way shorter than using Runtime.getRuntime().exec() (which is also deprecated) and constructing a BufferedReader through a long and convoluted call that is the result of the Java API designers' apparent unwillingness to add an overload for convenience.

I wish ProcessBuilder would work on Windows, but the mode command outputs more than 4 lines :(

Java 8 (no libraries), Windows, 270 bytes
Posting seperately by recommendation of Adam.
interface B{static void main(String[] a)throws Exception{Object[]r=new java.io.BufferedReader(new java.io.InputStreamReader(Runtime.getRuntime().exec("cmd /c mode").getInputStream())).lines().toArray();System.out.print(r[3]+"\n"+r[4]);}}

Ungolfed:
interface B {
    static void main(String[] a) throws Exception {
        Object[] r = new java.io.BufferedReader(new java.io.InputStreamReader(
                Runtime.getRuntime().exec("cmd /c mode").getInputStream())
        ).lines().toArray();
        System.out.print(r[3] + "\n" + r[4]);
    }
}

Try cmd/c mode instead of cmd /c mode.

Just tried, Runtime.exec() interprets that as trying to execute cmd/c resulting in CreateProcess error=2. :(

8th, 24 16 12 bytes
Revised after Anders Tornblad comment.
con:size? .s

Returns the current size of the console in rows and columns printing stack content.
Output:
2  n: 000000000285e5e0 1   300
1  n: 000000000285e4c0 1   90

Since the question allows any output format, do you really need swap?

@Anders Tornblad - Thank you for your wise comment. I improved my code.

Stacked, 7 bytes
termdim

Leaves output on the stack, as is allowed per default. Example usage:
λ stacked -pe "termdim"
(117 26)

Bonus: termdim'x'#` to have it 117x26.

C (linux, C89 only), 45 41
inspired by https://codegolf.stackexchange.com/a/118696/42186 by @dieter
main(m){ioctl(0,21523,&m);write(1,&m,4);}

this outputs the size as binary data. Not sure if this counts as "any format". You would need something extra (less, hexdump, od, ascii table) (or an esoteric terminal emulator that automatically does this for you) to make it human readable. Example usage:
$ ./a.out | od -sAn
     58    204

The terminal size is 204 cols by 58 rows.
Thanks to @Random832 for using od instead of hexdump.

I think hex is pushing it. All other answers use decimal, so I'm going to add this requirement to OP. Sorry.

od -s will do it in decimal and is shorter than hexdump

@Random832 Cool, didn't know that, +1! But this answer became invalid anyway, when the rules changed from "any format" to a very specific format (something like: base 10 in ascii in mainstream terminal emulators)

Red, 19 Bytes
system/console/size

Output:
>> system/console/size
== 106x26

Can also get the screen resolution as in the previous question

Kotlin + Jline 2, 58 bytes
{print(jline.TerminalFactory.get().run{"$width $height"})}

Because why not. Turns out the standard lib actually has no way to determine console size so pulling in a library is required, lest you want to gold launching another process and parsing the input stream... would be a shame if somebody did that..

Don't put two answers in one post.

@Adám It's more of an afterthought, so I think it's fine. You have enough rep to edit it directly, do so if you really believe a 270b with arbitary restrictions should be a seperate answer.

Each submission competes against other submissions in the same language. Java is inherently verbose, but yours is the shortest (and only) Java submission. Also, while I can edit your post, I cannot post a separate answer in your name.

I was implicating that if you remove my Java answer, I will repost it myself. And while you have a point that the answer is currently the shortest Java answer, it is coded under restriction of using no external libraries. In order to address your argument, I will mark it as non-competing and code a proper Java answer later.

Post it as Java (no libraries) and make another submission called Java with …. That will get you three upvotes from me.

Posting 3 answers doesn't sound right for me. I already feel as if I'm violating implict conduct by planning to post a second one. This meta post suggests that I should post seperate answers if they're interesting enough. Java in general doesn't sound interesting to me.

Oh yes it is. I find the Java answers the most entertaining answers on PPCG. The sheer amount of typing to do simple things! And now, without libraries‽ This is great!

Let us continue this discussion in chat.

Commodore 64 BASIC, 7 bytes
?"40x25

The C64 has a fixed-size text console of 40 x 25 characters.  It is not necessary to query the console size, which is a good thing, as there is no way to query it.

This seems like cheating, although to be fair, the question (nor its inspiration) does not specifically prohibit it.

Relevant: https://codegolf.meta.stackexchange.com/a/1063/43319


text:
When will SE be down?
SE will be down/read only today 2017-05-04 at 00:00 UTC until 00:20 UTC.
Your challenge is to output a truthy value if SE is down/read only and a falsy value if SE is not. You may not have any input, and you must use date builtins to determine if SE is down/read only (no actually querying the SE api!) Example output:
12:34 UTC 03 May 2017 -> false

00:00 UTC 04 May 2017 -> true

00:20 UTC 20 May 2017 -> undefined, see below

That's undefined behavior, because it's too far after the window of time.
 To be clear, you can assume your program will be run from UTC 8:00 today (5/3/17) to UTC 1:00 tomorrow (5/4/17).
00:21 UTC 04 May 2017 -> false

00:20 UTC 04 May 2017 -> true

00:10 UTC 04 May 2017 -> true

Note that any truthy or falsy values are allowed, not just true and false. You must be accurate to the nearest second, and no changing the system clock! You may assume that your program is being run on a machine on the +0 UTC time zone.

sudo time <insert time here> && echo true

@Okx no changing the time!

I'd suggest updating the test cases to use a universal date format rather than American.

Why do I have twice as many answers as upvotes?

@programmer5000 Not everyone upvotes when answering. Sometimes I answer a question but don't upvote it because it wasn't that interesting. I wouldn't downvote unless it was actually a bad challenge. (By the way, I upvoted, but I might not be answering. :P)

I'm not sure what you mean by You must be accurate to the nearest minute. Should we round the time somehow? Do we have to look at the seconds at all? What should be displayed at 00:20:01?

Step #1, trigger bot army to DDoS SE, Step #2, return "1"

First, as the SO SRE Manager, I want to say that I love this question.  Good work!  However, I do want to remind people that the site won't be hard down... just in read-only mode.  That said, I will be selecting on answer to this question to help me determine when to start the procedure.

@TomOnTime Thanks! And is that more clear?

@programmer5000 That is better. Thanks. (I actually didn't expect you to change anything, but thanks for the edit!) Much appreciated!

@programmer5000 Could you please answer Dennis question above?

@Dennis you must be accurate to the nearest second. For example, 00:20:01 should be falsey.

That would mean your own answer is invalid, no? So would many other answers; neither your original revision nor the current test cases mention seconds.

Relevant chat conversation.

05AB1E,  32 26 11 9 8 bytes
žažb«21‹

Explanation:
ža          Is the current hour &
  žb        current minute
     «      concatenated
        ‹   less than
      21    twenty one?

Try it online!

JavaScript (ES6), 26 24 23 22 21 bytes
Saved 3 bytes thanks to Shaggy and 1 byte thanks to Luke.
_=>new Date/12e5%72<1

Checks if time passed in current day is less than 1200000ms (1200s or 20min). Assumes downtime to be 20 minutes not 21, which appears to be the case in the linked post. 00:20UTC is the exclusive upper bound.

Save 2 bytes by using new Date instead of new Date().

<2 to save another byte.

You don't need the +; / automatically converts new Date to a Number.

Is the function declaration (_=>) needed?  JavaScript can run globally.

@Brilliand Yes, otherwise output would be needed, the shortest being alert which is a lot longer

Python 2, 41 39 bytes
Saved 2 bytes thanks to Erik the Outgolfer
import time
print time.time()/1200%72<1

Try it online!
Uses the same algorithm as my JS and Charcoal answers.

Is /72<1 different from <72?

@xnor whoops sorry copied it wrong, fixed now

No, I mean that I think print time.time()/1200<72 would be a shorter way to express the same thing.

@xnor I'm pretty sure that only works on the first day of the epoch though

Oops, I meant %1200/72<1 -> %1200<72. Your TIO links to the %1200/72<1 version -- is that a mistake?

@xnor Yeah, sorry

Jelly, 9 bytes
6ŒT|0Ḍ<21

Requires TZ to be set to UTC, which is the case for TIO.
Try it online!
How it works
6ŒT|0Ḍ<21  Main link. No arguments.

6ŒT        Get the current time as a string, in the format HH:MM.
   |0      Bitwise OR each character with 0. This casts the characters to int and
           maps the non-digit character : to 0.
     Ḍ     Undecimal; convert from base 10 to integer.
      <21  Compare the result with 21, so 00:00 to 00:20 return 1, all others
           return 0.

(Everyone was) Outgolfed by Dennis! Nice job!

Not everyone...

If the downtime latest 'til 00:21, I could save a byte...

Japt, 32 11 bytes
K/12e5%72<1

Try it online!

JS (ES6), 52 50 49 bytes
y=>(x=new Date).getUTCMinutes()<21&&!x.getUTCHours()

Why is Date so long? Just gets the minutes past 00:00 and returns true if they are < 21, and false otherwise.

Save 2 bytes by using new Date instead of  new Date().

-1 this doesn't check the date

@ASCII-only the question says it dosen't have to.

Save another byte with y=>(x=new Date).getUTCMinutes()<21&&!x.getUTCHours().

@Shaggy thanks again! My golfing isn't great.

Save another 6 bytes by using local time instead of UTC - the question says you may assume local time is UTC.

zsh, 38 37 bytes:
date +%H\ %M|read h m;((h==0&&m<21))

bash, 40 bytes:
read h m< <(date +%H\ %M);((h==0&&m<21))

Alice, 17 bytes
/o
\T@/4&;'-.C+n

Try it online!
Assumes to be run on a machine whose timezone is set to UTC (like the TIO server).
Explanation
While in Ordinal mode, the IP bounces diagonally up and down through the program. While in Cardinal mode, the IP wraps around the edges like most other Fungeoids.
/   Reflect to SE. Switch to Ordinal.
T   Push a string representing the current date and time, in the format:
    YYYY-MM-DDTHH:MM:SS.mmm±AA:BB
/   Reflect to E. Switch to Cardinal.
4&  Run the next command 4 times.
;   Discard four elements from the top of the stack. Since we're in Cardinal mode,
    this attempts to discard four integers. But the top stack value is a string so
    it gets implicitly converted to all the integers contained in the string. So
    year, month, day, hour, minute, seconds, milliseconds, timezone hour,
    timezone minute will be pushed separately. Then the last four of these
    will be discarded, so that we end up with the minute and the hour on
    top of the stack.
'  Push 21.
-   Subtract it from the minutes. Gives something negative for minutes 0 to 20.
.C  Compute the binomial coefficient n-choose-n. This gives 0 for negative
    results and 1 for non-negative ones. SE is down if both this value and
    the current hour are zero.
+   Add the two values. Iff they are both zero, we still get a zero.
n   Logical NOT of the value. Turns 0 into 1 and everything else into 0.
\   Reflect to NE. Switch to Ordinal.
o   Implicitly convert the result to a string and print it.
@   Terminate the program.

APL (Dyalog), 14 bytes
∧/1 20>2↑3↓⎕TS

∧/ is it all-true (AND reduction) that
1 20> these numbers are greater than
2↑ the first two elements of
3↓⎕TS the current Time Stamp with three elements dropped

What character is the ⎕?

@programmer5000 ⎕ (Quad) is a prefix for system names in APL. It is supposed to be an empty rectangle.

Python 3 (NON-REPL) + time, 81 77 bytes
-4 bytes thanks to Bahrom
import time;e=str(time.strftime('%H:%M'));print(e[:2]=='00'and int(e[3:])<21)

A naïve approach, turning the current date to string and analysing its characters.

You can save a whole bunch of bytes by using a different format string, and if you're using the shell, you don't need the print function: import time;e=str(time.strftime('%H:%M'));e[:2]=='00'and int(e[2:])<21. This can probably be golfed even further too.

(pretty new to golfing and the rules) but in the shell this also seems to output the correct results: import time;time.localtime();_.tm_hour==0 and _.tm_min<21. We're not beating ASCII-only anyway lol

Ok, I cannot edit now, maybe later

Charcoal, 25 bytes
‹﹪÷ＵＰtime.time⟦⟧¹²⁰⁰¦⁷²¦¹

Prints - for truthy, nothing for falsy.
Explanation
    ＵＰtime.time⟦⟧          Python function time.time()
   ÷               ¹²⁰⁰      Divided by 1200
 ﹪                    ¦⁷²   Modulo 72
‹                         ¦¹ Less than 1

Try it online!

What does the ⟦⟧ do here? Do you need a list or arrowlist literal?

Yeah, a list is required here, but now that I think about it I should make it optional

Oh, so it's a list of arguments? Yeah, you should make it optional, calling the function without arguments by default.

@EriktheOutgolfer Done

MATL, 10 bytes
Thanks to Dennis for several corrections
Z'1\480*7<

Try it online!
Explanation
Z'    % Push current date and time as a float. Integer part is day, decimal part is time
1\    % Modulo 1. This gives the time, in units of one day
480*  % Multiply by 480
7<    % Less than 7? Note that 21 minutes / one day equals 7 / 480. Implicitly display.

Should that be l72 rather than 171 in your explanation?

@Dennis Yes, thanks for catching that!

It's still 72 vs 71. Also wouldn't this return 0 at 00:20?

@Dennis Yes, this would return 0 at 00:20, but would return 1 at 00:20 minus a small fraction of a second (given by the machine epsilon for double data type times 86400). The challenge says "you must be accurate to the nearest minute", so I understand it's acceptable

That's probably what the post on Mother Meta meant, but the challenge has 00:20 -> true as a test case. Left a comment on the question.

@Dennis Thanks, I hadn't seen that test case. I've corrected to use 00:21 as threshold.

Hm, looking at the other answers, it seems like most interpreted the challenge the same way you did. Let's hope the OP clarifies soon.

@Dennis Or, if "accurate to the nearest minute" means 30-second precision I could save 1 byte with current interpretation using 1/70 or 1/71 as threshold; let's wait for clarification

Bash, 55 53 51 50 bytes
-1 byte from @robbie0630's comment.
a=`date +%s`;echo $[1493856000<a&a<1493857200?1:0]

Try it online!
The advantage of this solution is that it works for any date (so will return 1 only for the period defined in the challenge, as it uses epoch time).

Shave off a byte by replacing $(...) with \...``

Pyth, 11 bytes
&g20.d7!.d6

Online interpreter link

R, 65 bytes
library(lubridate)
x=Sys.time()
print(all(!hour(x)&minute(x)<21))

Checks if the hour == 0 and the minute < 21.

PostgreSQL, 43 characters
select now()between'170503'and'170503 0:20'

Just because I prefer SQL for date/time calculations.
Sample run:
bash-4.3$ psql -c "select now()between'170503'and'170503 0:20'"
 ?column?
----------
 f
(1 row)

Swift + Foundation, 178 bytes
import Foundation;var d=String(describing:Date());func g(_ s:Int)->String{return String(d[d.index(d.startIndex,offsetBy:s)])};print(g(11)+g(12)=="00" ?Int(g(14)+g(15))!<21:false)

Quite short by swift standards. Check it out!
As in my Python answer, I basically converted the current Date to a string and have analysed its digits, depending on which I printed the bool.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Swap the parity
Task
Given a positive integer n, output n+1 if n is odd, and output n-1 if n is even.
Input
A positive integer. You may assume that the integer is within the handling capability of the language.
Output
A positive integer, specified above.
Testcases
input output
    1      2
    2      1
    3      4
    4      3
    5      6
    6      5
    7      8
    8      7
  313    314
  314    313

Scoring
This is code-golf, so shortest answer in bytes wins.
Standard loopholes apply.
References

OEIS A103889

May we take input as unary?

This would be, surprisingly, a lot easier if it was the other way around in some languages

@MistahFiggins That's well known enough that I'm pretty sure OP did it like this on purpose.

C, 20 bytes
f(x){return-(-x^1);}

Try it online.

f(x){x=-(-x^1);}

@LeakyNun I am not writing a function lacking a return statement.

@feersum When I saw this question I knew that this approach was the way to go.

@feersum Yes you do write one, since assigning to the first argument is equivalent to using a return statement.

@EriktheOutgolfer No. Nope. Nuh-uh. No.

@feersum Try it online! (are you serious?)

@EriktheOutgolfer I don't think it's a good idea to omit the return statement. It invokes undefined behavior and while it may work sometimes it's very fragile (for example on my machine compiling with gcc -O3 it breaks)

@Sisyphus But this is [tag:code-golf], and it works on my TIO link, so it's valid.

@EriktheOutgolfer What I am saying is that your statement ("assigning to the first argument is equivalent to a return statement" ) is factually incorrect. Whether such code may generate a working answer under certain circumstances is another question (which I have addressed in my first comment by stating that I plan not to post any such code).

@EriktheOutgolfer If an answer relies on implementation specific behavior, it should specify an implementation. This answer doesn't, so that code would be invalid.

Stack Cats, 3 + 3 (-n) = 6 bytes
-*-

Try it online!
Needs the -n flag to work with numeric input and output.
Explanation
Stack Cats is usually far from competitive, because of its limited set of commands (all of which are injections, and most of which are involutions) and because every program needs to have mirror symmetry. However, one of the involutions is to toggle the least-significant bit of a number, and we can offset the value with unary negation which also exists. Luckily, that gives us a symmetric program, so we don't need to worry about anything else:
-   Multiply the input by -1.
*   Toggle the least significant bit of the value (i.e. take it XOR 1).
-   Multiply the result by -1.

Input and output are implicit at the beginning and end of the program, because taking input and producing output is not a reversible operation, so they can't be commands.

Are flags always counted with the additional space, I don't think I've seen other answers using flags (like Perl) do that? EDIT: Ok nvm, found the relevant meta post. "I count those as a difference in character count to the shortest equivalent invocation without them." ... "perl -nle 'stuff' is 2 characters more than perl -e 'stuff', so it counts for 2 more characters". So (space)-n is 3 bytes more than without the flag.

@KevinCruijssen It depends on how many bytes you actually need to add to a usual invocation. In Perl and many other production languages, you can invoke the code with -e "code" and then insert additional flags before the e, e.g. -pe "code". Then the -p flag is only one byte. However, Stack Cats has no such -e argument, so you always need to add the full <sp>-n to the command, and hence it's three bytes.

x86 Assembly, 9 bytes (for competing entry)
Everyone who is attempting this challenge in high-level languages is missing out on the real fun of manipulating raw bits. There are so many subtle variations on ways to do this, it's insane—and a lot of fun to think about. Here are a few solutions that I devised in 32-bit x86 assembly language.
I apologize in advance that this isn't the typical code-golf answer. I'm going to ramble a lot about the thought process of iterative optimization (for size). Hopefully that's interesting and educational to a larger audience, but if you're the TL;DR type, I won't be offended if you skip to the end.
The obvious and efficient solution is to test whether the value is odd or even (which can be done efficiently by looking at the least-significant bit), and then select between n+1 or n−1 accordingly. Assuming that the input is passed as a parameter in the ECX register, and the result is returned in the EAX register, we get the following function:
F6 C1 01  |  test  cl, 1                      ; test last bit to see if odd or even
8D 41 01  |  lea   eax, DWORD PTR [ecx + 1]   ; set EAX to n+1 (without clobbering flags)
8D 49 FF  |  lea   ecx, DWORD PTR [ecx - 1]   ; set ECX to n-1 (without clobbering flags)
0F 44 C1  |  cmovz eax, ecx                   ; move in different result if input was even
C3        |  ret

(13 bytes)
But for code-golf purposes, those LEA instructions aren't great, since they take 3 bytes to encode. A simple DECrement of ECX would be much shorter (only one byte), but this affects flags, so we have to be a bit clever in how we arrange the code. We can do the decrement first, and the odd/even test second, but then we have to invert the result of the odd/even test.
Also, we can change the conditional-move instruction to a branch, which may make the code run more slowly (depending on how predictable the branch is—if the input alternates inconsistently between odd and even, a branch will be slower; if there's a pattern, it will be faster), which will save us another byte.
In fact, with this revision, the entire operation can be done in-place, using only a single register. This is great if you're inlining this code somewhere (and chances are, you would be, since it's so short).
    48     |  dec  eax          ; decrement first
    A8 01  |  test al, 1        ; test last bit to see if odd or even
    75 02  |  jnz  InputWasEven ; (decrement means test result is inverted)
    40     |  inc  eax          ; undo the decrement...
    40     |  inc  eax          ; ...and add 1
  InputWasEven:                 ; (two 1-byte INCs are shorter than one 3-byte ADD with 2)

(inlined: 7 bytes; as a function: 10 bytes)
But what if you did want to make it a function? No standard calling convention uses the same register to pass parameters as it does for the return value, so you'd need to add a register-register MOV instruction to the beginning or end of the function. This has virtually no cost in speed, but it does add 2 bytes. (The RET instruction also adds a byte, and there is a some overhead introduced by the need to make and return from a function call, which means this is one example where inlining produces both a speed and size benefit, rather than just being a classic speed-for-space tradeoff.) In all, written as a function, this code bloats to 10 bytes.
What else can we do in 10 bytes? If we care at all about performance (at least, predictable performance), it would be nice to get rid of that branch. Here is a branchless, bit-twiddling solution that is the same size in bytes. The basic premise is simple: we use a bitwise XOR to flip the last bit, converting an odd value into an even one, and vice versa. But there is one niggle—for odd inputs, that gives us n-1, while for even inputs, it gives us n+1— exactly opposite of what we want. So, to fix that, we perform the operation on a negative value, effectively flipping the sign.
8B C1     |  mov eax, ecx   ; copy parameter (ECX) to return register (EAX)
          |
F7 D8     |  neg eax        ; two's-complement negation
83 F0 01  |  xor eax, 1     ; XOR last bit to invert odd/even
F7 D8     |  neg eax        ; two's-complement negation
          |
C3        |  ret            ; return from function

(inlined: 7 bytes; as a function: 10 bytes)
Pretty slick; it's hard to see how that can be improved upon. One thing catches my eye, though: those two 2-byte NEG instructions. Frankly, two bytes seems like one byte too many to encode a simple negation, but that's the instruction set we have to work with. Are there any workarounds? Sure! If we XOR by -2, we can replace the second NEGation with an INCrement:
8B C1     |  mov eax, ecx
          |
F7 D8     |  neg eax
83 F0 FE  |  xor eax, -2
40        |  inc eax
          |
C3        |  ret

(inlined: 6 bytes; as a function: 9 bytes)
Another one of the oddities of the x86 instruction set is the multipurpose LEA instruction, which can do a register-register move, a register-register addition, offsetting by a constant, and scaling all in a single instruction!
8B C1        |  mov eax, ecx
83 E0 01     |  and eax, 1        ; set EAX to 1 if even, or 0 if odd
8D 44 41 FF  |  lea eax, DWORD PTR [ecx + eax*2 - 1]
C3           |  ret

(10 bytes)
The AND instruction is like the TEST instruction we used previously, in that both do a bitwise-AND and set flags accordingly, but AND actually updates the destination operand. The LEA instruction then scales this by 2, adds the original input value, and decrements by 1. If the input value was odd, this subtracts 1 (2×0 − 1 = −1) from it; if the input value was even, this adds 1 (2×1 − 1 = 1) to it.
This is a very fast and efficient way to write the code, since much of the execution can be done in the front-end, but it doesn't buy us much in the way of bytes, since it takes so many to encode a complex LEA instruction. This version also doesn't work as well for inlining purposes, as it requires that the original input value be preserved as an input of the LEA instruction. So with this last optimization attempt, we've actually gone backwards, suggesting it might be time to stop.

Thus, for the final competing entry, we have a 9-byte function that takes the input value in the ECX register (a semi-standard register-based calling convention on 32-bit x86), and returns the result in the EAX register (as with all x86 calling conventions):
           SwapParity PROC
8B C1         mov eax, ecx
F7 D8         neg eax
83 F0 FE      xor eax, -2
40            inc eax
C3            ret
           SwapParity ENDP

Ready to assemble with MASM; call from C as:
extern int __fastcall SwapParity(int value);                 // MSVC
extern int __attribute__((fastcall)) SwapParity(int value);  // GNU

Wouldn't just dec eax; xor eax, 1; inc eax work and save one byte more?

Jelly, 3 bytes
-*ạ

Try it online!
Pseudocode: abs((-1)**n - n)

I was actually planning to (ab)use -1.

Sorry for that.

There isn't any sorry, well done! I didn't figure out how to do it quickly enough...

Python3, 20 18 bytes
lambda n:n-1+n%2*2

Pretty simple. First we calculate n-1 and decide whether to add 2 to it, or not.
If n is even --> n mod 2 will be 0, thus we'll add 2*0 to n-1, resulting in n-1.
If n is odd --> n mod 2 will be 1, thus we'll add 2*1 to n-1, resulting in n+1.
I prefer an explanation that I made with MS paint & a laptop touchpad...

Python, 16 bytes
lambda x:-(-x^1)

Try it online!

Brute forcing doesn't find any shorter solution using characters in "x+-012~|&^()*/%".

@xnor Good thing I got it then!

And it looks like there are no other same-length solutions except the trivial rearrangement -(1^-x).

MATL, 7 bytes
Q:HePG)

This avoids any arithmetical operations. Try it online!
Explanation
Consider input 4 as an example.
Q    % Implicit input. Add 1
     % STACK: 5
:    % Range
     % STACK: [1 2 3 4 5]
He   % Reshape with 2 rows in column-major order. Pads with a zero if needed
     % STACK: [1 3 5;
               2 4 0]
P    % Flip vertically
     % STACK: [2 4 0;
               1 3 5]
G    % Push input again
     % STACK: [2 4 0;
               1 3 5], 4
)    % Index, 1-based, in column major order. Implicitly display
     % STACK: 3

Nice! Like it !

Python, 68 bytes
lambda x:[m.floor(x-m.cos(m.pi*x)) for m in [__import__('math')]][0]

In the spirit of a unique approach. The following graph shows the function (with purple dots representing the first 10 cases). It should in theory be possible to construct a solution for this question based on most (all?) periodic functions (e.g. sin, tan, sec). In fact, substituting cos for sec in the code as is should work.

Braingolf v0.1, 11 10 bytes
.1>2,%?+:-

Try it online! (Second argument is the Braingolf code, third argument is the input)
Saved a byte thanks to Neil
First ever competing braingolf answer :D
Explanation:
.            Duplicate the top of the stack
 1>          Push 1 to the bottom of the stack
   2         Push 2 to stack
    ,%       Pop last 2 items, mod them and push result
      ?      If last item > 0
       +     Add the 1 to the input
        :    Else
         -   Subtract the 1 from the input

             No semicolon in code so print last item

Braingolf v0.2, 9 bytes
.2%?1+:1-

Try it online! (Second argument is the Braingolf code, third argument is the input)
See above for explanation. Only difference is in Braingolf v0.2, the default behaviour of diadic operators, and the function of the , modifier, are reversed, meaning the 2 commas in the v0.1 answer are no longer needed.

Congratulations on your new language!

Does .1<2,%?+:- do what I think it does?

@Neil not quite, you'd need a comma before the - to make it perform the operation the correct way around, in which case it'd still be the same length as my answer

@Mayube I was expecting the < to rotate the 1 below the input, so that it would be in the correct place already.

@Neil if the input is an even number, by the time it reaches the - the stack looks like this: [n,1] braingolf operators are reversed, so it would perform 1 - n, which would result in -(n-1), wheras the desired result is simply n-1

Of course if I updated braingolf to not reverse operators by default (which I should), this could be shortened to 9 bytes by removing both commas, but then the shorter answer would be non-competing. I might do that anyway though

Well, if you're going to do that, then never mind, but my point is, my stack is the opposite way around to your stack, so I don't need the ,.

@Neil Nope, in your code the stack right before the - is [n,1], if you hit the v0.1 TIO link you can test it by inserting = anywhere in the code to print the stack at that point

Ah, I misunderstood the way the > and < operators worked, so .1>2,%?+:- is now the correct BrainGolf v0.1 answer.

@Neil So it is!

By the way, I think , would be more useful as an operator that exchanges the top two elements of the stack.

@Neil yeah definitely agree

Cubix, 10 9 bytes
cO1)I(//@

Try it online
Explanation
Net version
    c O
    1 )
I ( / / @ . . .
. . . . . . . .
    . .
    . .

The executed characters are
I(1c)O@
I          Input
 (         Decrement
  1c       XOR with 1
    )      Increment
     O@    Output and exit

APL (Dyalog Unicode), 6 bytes
-2 thanks to Razetime
⊢-¯1*⊢

Try it online!
Explanation:
 ⊢-¯1*⊢
   ¯1*⊢  ⍝ calculate ¯1*⍵ - for even ⍵: 1, for odd ⍵: ¯1.
 ⊢-      ⍝ subtract 1 for even, subtract ¯1 (add 1) for odd.

-2

JavaScript (ES6), 14 13 12 10 bytes
n=>-(-n^1)

1 byte saved thanks to Luke.
2 bytes saved by porting feersum's C solution. (If that's frowned upon, please let me know and I'll roll back to my previous solution below)

Try It

f=
n=>-(-n^1)
i.addEventListener("input",_=>o.innerText=f(+i.value))
<input id=i type=number>

Original, 12 bytes
n=>n-1+n%2*2

Javascript, 17 12 bytes
x=>x-(-1)**x

f=x=>x-(-1)**x;
<input id=i oninput=o.innerText=f(this.value) type=number>

Another approach, 10 bytes stolen from the C answer (sssshhh)
x=>-(-x^1)

f=x=>-(-x^1)
<input id=i oninput=o.innerText=f(this.value) type=number>

you don't need to include the semicolon; 2. x=>x-(-1)**x

Why the |0? Both solutions look as if they should automatically convert strings to numbers. (For the first solution, if you want to avoid decimals, use <input type=number>.)

@Neil Thanks for notifying me!

PHP, 15 bytes
<?=-(-$argn^1);

How do I run this? I'm trying to test whether the ; is required, and have tried using a .php file and also echoing directly into php (php7 cli.) Each time I'm told that $argn is an undefined variable.

@Andrakis With the F flag and a pipeline: echo 42 | php -F script.php.

Cubix, 11 bytes
u%2!I(/+@O<

Try it online!
Explanation
Net version:
    u %
    2 !
I ( / + @ O < .
. . . . . . . .
    . .
    . .

Characters are executed in following order:
I(2%!+O@
I        # Take a number as input
 (       # Decrement it
  2%     # Take the parity of the decremented number
         # (0 if the input is odd, 1 if it's even)
    !    # If that number is zero:
     +   #   Add 2
      O  # Output the number
       @ # Terminate the program

Brain-Flak, 36 bytes
(({})(())){({}[()]<([{}])>)}{}({}{})

Try it online!
I'm personally really happy with this answer because it is a lot shorter than what I would deem a traditional method of solving this problem.
Explanation
The first bit of code
(({})(()))

converts the stack from just n to
n + 1
  1
  n

Then while the top of the stack is non zero, we decrement it and flip the sign of the number under it
{({}[()]<([{}])>)}

The we remove the zero and add the two remaining numbers
{}({}{})

Vyxal r, 4 bytes
‹ue+

Try it Online!
Me and the boys porting risky be like
Explained
‹ue+
‹    # input - 1
 u   # -1
  e  # ^^ ** ^
   + # ^ + input

Huh, why doesn't N1^N work?

@user most probably because ^ doesn't do exponation like you think it might. That's e

No, bitwise xor is what I was looking for. The most upvoted answer (in C) just does -(-x^1), so I was trying to turn that into Vyxal. I'm not sure what's going wrong, though.

@user then you need the right caret: ꘍

Wise, 8 bytes
-::^~-^-

Try it online!
Explanation
If this were the other way around, (decrement if odd, increment if even), it would be quite easy to do this.
We would just flip the last bit.
::^~-^

The fix here is that we flip the last bit while negative.  The negative numbers are 1 off from the negation of the numbers ~ so this creates an offset resolving the problem.
So we just take out program and wrap it in -.
-::^~-^-

Python, 20 bytes
lambda n:n+(n%2or-1)

n%2or-1 will return 1 if it's odd, but if it's even, n%2 is "false" (0), so it instead returns -1. Then we simply add that to n.
Previous solution, 23 bytes
lambda n:[n-1,n+1][n%2]

n%2 calculates the remainder when n is divided by 2. If it's even, this returns 0, and element 0 in this list is n-1. If it's odd, this returns 1, and element 1 in this list is n+1.

Use a lambda: lambda n:[n-1,n+1][n%2]

Ah yes, so it was shorter in this case. Done, thanks!

Mathematica, 22 19 bytes
Saved 3 bytes thanks to Greg Martin!
#-1[-1][[#~Mod~2]]&

Previous answer, 22 bytes
#+{-1,1}[[#~Mod~2+1]]&

Explanation (for previous answer)
Mathematica has the nice feature that operations such as arithmetic automatically thread over lists.
In this case, we take Mod[#,2] which will return 0 or 1, but we need to add 1 because Mathematica lists are 1-indexed. If it's even, this comes out to 1, so #-1 is returned. If it's odd, this comes out to 2, so #+1 is returned.

You can save three bytes by abusing Mathematica's [[0]] capability: #-1[-1][[#~Mod~2]]&.

That's insane, never would've thought of that. Done, thanks!

Retina, 21 bytes
.+
$*
^11(?=(11)*$)

Try it online! My first Retina answer with two trailing newlines! Explanation: The first two lines convert from decimal to unary. The third and fourth lines subtract two from even numbers. The last line converts back to decimal, but adds one too.

05AB1E, 4 bytes
(1^(

Try it online!

Alternative 4 byte solution: Try it online!.

But Èi>ë< is so pretty ;_;.

R, 17 bytes
(n=scan())-(-1)^n

where n=scan() takes the digit value.

I think you need -(-1)^n rather than +(-1)^n since we need to return n-1 if n is even

@Giuseppe oh, yes, of course, foolish mistake

brainfuck (8-bit), 51 bytes
,[->>++>+<<<]+++[->>[-<++>]<[->++<]<]>>[>++<[-]]>-.

Try it online!
Requires a fixed 8-bit cell size.
Decided to do something entirely on my own.
Inspired by some meme ARM code I wrote to check if it is a multiple of 4 (screenshot)
Instead of modulo, negate+xor, or binary AND, I shift out all the bits but the lowest to determine if it is even or odd.
// Checks parity by shifting n << 7.
// Requires 8-bit cells
,             // [  n    0    0   0]
              // copy loop, shifting one once
[->>++>+<<<]  // [  0    0 n<<1   n]
              // n <<= 6
+++           // c = 3
[-            // loop 3 times, shifting twice
    >>[-<++>] // [  c n<<1    0   n]
     <[->++<] // [  c    0 n<<1   n]
<]            // end loop
              // if even:
              //   tape[2]==0
              // else:
              //   tape[2]==0x80
>>[           // if tape[2] != 0:
    >++<[-]   //   n += 2
]
>-            // n -= 1
.             // print n

Equivalent C:
uint8_t parity(uint8_t n)
{
    uint8_t is_odd = n << 7;
    if (is_odd != 0)
        n += 2;
    return n - 1;
}

The input is a byte from stdin, and the output is a byte printed to stdout. 0-255 only.
The demo uses ASCII arithmetic.
boolfuck (joke), 3 bytes
,+;

Try it online!
For a real Boolfuck solution, see here
Operation works on 1-bit integers from stdin, prints to stdout. Obviously a joke.

Factor, 15 bytes
[ -1 over ^ - ]

Try it online!
Uses x-(-1)^x method as in many other answers (specifically inspired by the APL one).
In Factor, it is usually better (code-golf-wise) to minimize the number of conditionals, then minimize the number of functions overall (especially when the answer can be found with arithmetic, where all the functions have short names). The top answer beats a different arithmetic answer x+x%2*2-1 (23 bytes)
[ dup 2 mod 2 * + 1 - ]

Try it online!
and a conditional-based answer x+(x.odd()?1:-1) (21 bytes)
[ dup odd? 1 -1 ? + ]

Try it online!

Risky, 4 bytes
?+0--2?

Try it online!
Explanation
?        The input number
 +0      plus 0
   -     minus
    -    -1
     2   to the power of
      ?  the input number

Ruby, 12 bytes
->n{-(-n^1)}

J-uby, 12 bytes
:-@|:^&1|:-@

Explanation
:-@|            negate n
    :^&1|       XOR it with 1
         :-@    negate that

With a change I just pushed to GitHub (inspired by this question, but overall useful), it becomes 10 bytes:
:-|:^&1|:-

Java 8, 16 10 bytes
n->-(-n^1)

Java 7, 34 28 bytes
int c(int n){return-(-n^1);}

Boring ports of @feersum's amazing C answer.
Try it here.

Old answers:
Java 8, 16 bytes
n->n%2<1?n-1:n+1

Java 7, 34 bytes
int c(int n){return--n%2>0?n:n+2;}

Explanation (of old Java 7 answer):
Try it here.
The answer above is a shorter variant of int c(int n){return n%2<1?n-1:n+1;} by getting rid of the space.
int c(int n){     // Method with integer parameter and integer return-type
  return--n%2>0?  //  If n-1 mod-2 is 1:
    n             //   Return n-1
   :              //  Else:
    n+2;          //   Return n+1
}                 // End of method

braingasm, 8 bytes
;o[++]-:

; reads a number, o[++] increments twice if the number is odd, -decrements once, : prints.
edit: changed to p to o to retrofit to a breaking change in the language.

Befunge 93, 18 bytes
&:2%#v_1+.@
@.-1 <

I am not done golfing this yet (I hope).

Golfing tips: Befunge 98 has the ability to use kv (or jv if it is strictly 1 or 0) instead of #v_. Also, if you are using Try it online (and I recommend it), you can end the program with another & (although it will take 60 seconds), so you can get rid of the @ on the first line if you use that. here is the full list of commands for Befunge-98, although they might not all be correctly implemented in TIO, like & ending the program instead of reversing on EOF.

Also, It looks like you're using befunge 93 instead of 98, which has fewer commands. You might want to fix your link name if it is indeed 93 and not 98

@MistahFiggins, ah yes you are correct I was using 93.

Python, 20 bytes
lambda n:n+(n&1)*2-1

Japt, 6 bytes
n ^1 n

Try it online!

AWK, 15 bytes
{$1+=$1%2*2-1}1

Try it online!
I could save 1 byte by using (-1)^$1, but then it would be pretty much the same as everyone else, and this is what I came up with before looking at other answers. :)

Groovy, 17 bytes
print x%2?x+1:x-1

Just substitute x for desired number. Try it online here -> https://tio.run/nexus/groovy and copy the code.

Chip, 61 bytes
  * *
A~#-#a
B~#~#b
C~#~#c
D~#~#d
E~#~#e
F~#~#f
G~#~#g
H~#~#h

Try it online!
Since Chip natively handles only byte-sized integers, this solution reads in and writes out bytes. The TIO is set up to use the \x00 notation for this.
This Chip solution uses a straightforward approach where the columns are the operations, and the rows are for each bit:
Read in an octet
|Invert all bits
||Increment
|||Invert all bits except the lowest bit
||||Increment
|||||Output the octet
||||||

  * *
A~#-#a
B~#~#b
C~#~#c
D~#~#d
E~#~#e
F~#~#f
G~#~#g
H~#~#h

Klein, 21 + 3 bytes, (non-competing)
Uses the 000 topology.
:(1-(\))++@
1-+:?\)-(

Explanation
The first bit executed is :(1-(. This puts a copy of the input and a -1 in the scope to be recalled later.  This is just required set up for future computation.
The two mirrors \\ then move the ip down a level into the main loop.  The main loop, unfolded, is:
)-(1-+:?\

This recalls the first number of the scope and flips its sign then decrements the tos.  It will continue to flip the sign back and forth until it reaches zero.  This way it will be -1 if our input was even and 1 if it was odd.  Once the counter has reached zero ? stops jumping over the mirror and the pointer wraps around to the top.  Now the mirror we used earlier deflects the ip to the right causing it to run the code ))++@.
This code recalls the two things from the scope (the copy of the input and the number we have been flipping) with )). And adds the top three items with ++.  Since the counter is at zero the result is just the sum of the number we built and the input.  Since it can be either -1 or 1 depending on the parity of the input this will flip the sign of the input.
Finally @ ends execution.

Casio-Basic, 27 bytes
piecewise(mod(n,2),1,-1)+n

26 bytes for the function, +1 to enter n in the parameters box.

Ly, 8 bytes
n:2%2*+,

Try it online!
Explanation:
n:2%2*+,

n        # take input
 :2%     # modulo two
    2*   # multiply by two
      +  # add to input
       , # decrement

Perl 5, 12 bytes
$_+=$_%2||-1

Try it online!

x86-16 machine code, 5 bytes
Binary:
00000000: 4834 0140 c3                             H4.@.

Listing:
48      DEC  AX             ; decrement input (parity now inverted)
34 01   XOR  AL, 1          ; if LSb is 0 (odd input) add 1, otherwise subtract 1
40      INC  AX             ; increment
C3      RET                 ; return to caller

Callable function, input/output is AL.
Explanation:
Classic XOR shenanigans to accomplish this equivalent if/else pseudocode:
AL = AL - 1
if ( AL & 1 == 0 ) AL = AL + 1
else AL = AL - 1
AL = AL + 1

Edit:
Well heck:
Silly me for not looking at existing submissions before starting.  This approach was suggested by Ilmari Karonen in 2017!

tinylisp, 38 bytes
(load library
(q((N)((i(odd? N)a s)N 1

Try it online! (Adds 4 bytes to bind the lambda function to a name for ease of testing.)
Ungolfed
(load library)
(lambda (N)
  ((if (odd? N) add2 sub2) N 1))

Pretty straightforward implementation of the spec: if N is odd, add 1 to N; if not, subtract 1 from N. The main trick is that the if needs only swap out which function we're calling (addition vs. subtraction); the arguments (N and 1) are the same in either case.

MAWP, 18 bytes
%@!!2P2WA{M:}<1A:>

Try it!

Zsh, 14 bytes
<<<$[-(-$1^1)]

Try it online!

Python 3, 18 bytes
lambda n:n+n%2*2-1

Try it online!
Explanation:
Take the modulo of "n" and double it
Subtract that off the original "n" and subtract another 1
Basically, the same but easier to understand:
lambda n:n-(1-n%2*2)

Boolfuck, 91 57 56 bytes
,>,>,>,>,>,>,>+<<<<<<<+[>+]<[<]>+[>]+<[+<]>;>;>;>;>;>;>;

Try it online!
Yes, a real solution using Boolfuck.
Works on 7-bit integers, reads and writes in raw semibytes.
There might still be some optimization room here.
I mostly wanted to avenge my ,+; meme.
,>,>,>,>,>,>,       read 7 bits
>+<<<<<<<+[>+]<[<]> decrement
+                   xor 1
[>]+<[+<]           increment
>;>;>;>;>;>;>;      print

Python 3, 36 31 bytes
def f(n):return n+(-1)**(n%2+1)

Welcome to Code Golf! You can save a ton by removing whitespace and using a lambda as well as modifying the algorithm a little: lambda n:abs((-1)**n-n).

@Makonede Thanks for commenting, how do you remove whitespace?

You just... don't use whitespace. That's literally it. You don't need to make a function on multiple lines: def f(n):return n+(-1)**(n%2+1) works

Actually, 6 bytes
;0Dⁿ@-

Try it online, or run all test cases at once!
Explanation:
;0Dⁿ@-
;0Dⁿ    (-1)**n
    @-  n - (above)

Tcl, 30
proc s n {expr $n%2?$n+1:$n-1}

demo

Tcl, 24
based on @feersum's answer
 proc s n {expr -(-$n^1)}

demo

Tcl, 23
If it is a program instead of a function I can shave one byte off.
puts [expr -(-$argv^1)]

demo

Befunge-93, 11 bytes
&:2%2*1-+.@

[Try it online!]
Explanation:
Stack representation: bottom  [A, B, C  top
&:             Pushes 2 copies of the input, N:                   [N, N
  2%           Mods the top copy by 2, so it's either 1 or 0:     [N, (N % 2)
    2*         Multiplies that by 2, so that it's either 2 or 0:  [N, ((N % 2) * 2)
      1-       Subtracts 1, so it's either 1 or -1:               [N, (((N % 2) * 2) - 1)
        +      Adds the 2 together. -1 for evens, and 1 for odds: [(N-1) or [(N+1)
         .@    Prints and ends

Befunge-98 Variant, 10 bytes
This program can be trivially modified for Befunge-98 by removing the @, meaning the program will wrap around to the & and end:
&:2%2*1-+.

Try it online!

x86 machine code, 8 bytes
Load register al with an 8 bit integer
A8 01 (test al, 1; and whatever is in al with one, fast and small method for checking odd/even)
74 04 (jz 8; jump to even code if zf (zero flag, will be set if above instruction returns 0) is set)
04 02 (add al, 2; Two, because the next instruction will subtract one again, as if I incremented and jumped past the dec but shorter and faster)
FE C8 (dec al; Explained above, this is the code that is jumped to if input is even)

If you want, here is some actual assembly in boot-sector format. Just assemble this with nasm filename.asm and run qemu-system-i386 filename to test it. Press a key, and you will see that it will be the next letter if the ascii code was odd, or previous if it was even.
[ORG 0x7C00]

start:
xor ah, ah ;bios keyboard: get character (xoring a register with itself is a fast way to set it to 0 which is what we need)
int 0x16 ; keyboard io bios interrupt
mov ah, 0x0e ;bios graphics: display character (get ready)

test al, 0x01
jz even

add al, 2
even:
dec al
int 0x10 ; we already set al to 0E: display character, which takes a character from al and outputs that.

jmp start ; just go back to the start and get another character

times 510-($-$$) db 0 ; bootsector padding/signature
db 0x55
db 0xAA

Almost forgot, I should probably add the original assembly code that I used to create the bytes above
test al, 0x01
jz even

;odd code
add al, 2
even:
dec al

Clojure, 21 bytes
#(+(if(odd? %)1 -1)%)

It is quite difficult to get creative with this.

Pyth, 4 bytes
I'm new to Pyth, so please tell me if there are any things I can golf.
_x1_

Explanation:
   _    Negate input
 x1     Bitwise XOR with 1
_       Negate

Welcome to Pyth! Hope you'll have a great time golfing in Pyth.

Excel VBA 27 bytes
[a2]=iif(n mod 2=0,n-1,n+1)

I don't think taking input from a variable is legal on PPCG (the question's worded a bit weirdly, but I don't think that permits it). You'd have to write a program or function. (Also, although it's optional, I recommend writing an explanation or brief description of how your code works; posts like this one which are just a code block have a tendency to set off the low-quality-posts filter, which can cause trouble sometimes.)

Pyth, 10 bytes
+Q?%Q2 1_1

Try it online
As simple as using modulo of input with 2 and the ternary operator.

Golfed

Golfed.

How long did I search for standard short circuit D: only found reverse.. nice one though

Welcome to PPCG, and welcome to Pyth. Hope you have a great time golfing in PPCG with Pyth.

Jelly, 4 bytes
‘’Ḃ?

Try it online!

C, 29 bytes
a(int b){return b%2?b+1:b-1;}

C#, 34 11 bytes
n=>-(-n^1);

Port of @feersum's amazing C answer.
Try it here.

Batch, 20 bytes
@cmd/cset/a"-(1^-%1)

Independently rediscovered @feersum's algorithm, honest!

CJam, 7 6 bytes
{(1^)}

Try it online!
-1 thanks to Martin Ender. ...............OOOO

Swift, 29 bytes
var f={(i)->Int in i-1+i%2*2}

Try it here

Fourier, 17 bytes
I~x^ox%2{0}{@xvo}

Try it on FourIDE!
Explanation:
I~x                 - Stores input in a variable called x
   x^o              - Increments x and outputs
      x%2{0}{    }  - If x mod 2 == 0, do code inside brackets
             @      - Clear screen
              xvo   - Decrements x and outputs

QBIC, 15 10 bytes
:?a-(-1)^a

Saved a lot by using a different calculation.
Explanation:
:           Get a number frm the cmd line as var a
?           PRINT
 a-(-1)^a   a decreased by 1 for when even, or -1 (adding one) when odd.

QBasic (and QBIC) need the parenteses around (-1), because code like -1^2 is otherwise seen as negate 1*1 = negate 1 = -1...

05AB1E, 7 bytes
D1(sm-Ä

Try it online!
Explanation:
D1(sm-Ä
               Input (implicit). Is 3 for example. Stack: [3]
D              Duplicate input. Stack: [3, 3]
  1            Push 1. Stack: [3, 3, 1]
    (          Push opposite of top of stack. Stack: [3, 3, -1]
      s        Swap the top 2 items on the stack. Stack: [3, -1, 3]
        m      Push -1**3. Stack: [3, -1]
           -   Subtract. Stack: [4].
            Ä  Absolute value. Stack: [4].
               Implicit output.

Excel, 11 bytes
=A1-(-1)^A1

Assumes input in A1.

SAS, 72 bytes
%macro t(n);%put%eval(&n+%sysfunc(ifn(%sysfunc(mod(&n,2)),1,-1)));%mend;

dc, 10
?d2%2*+1-p

Uses the same formula as @TuukkaX's python answer.
Try it online.

@REXX 35 Bytes
arg a
x=pos(".",a/2)-1
say a+abs(x)/x

Explanation:
Explanation: There is no distinction in Rexx between numbers and strings. The action you perform is what defines the type. The "typing" applies just to that action and can change at any time.
So, after dividing the number by 2 we then search for the decimal point.
Subtract 1 from its position giving -1 if it was not found and a value in the range 1-n if it was.
(Note that 1/2 returns 0.5 and not .5 so pos can never be 1 and therefore x can never be 0).
Try it here
REXX functions and instructions

,,,, 4 bytes
_1^_

Yay.
Explanation
_1^_

      input by command-line args
_     negate
 1    push 1
  ^   pop input and 1 and push input ^ 1 (bitwise XOR)
   _  negate
      implicit output

Common Lisp, 24 bytes
(lambda(x)(- x(expt -1 x)))

Try it online!

Haskell, 21 bytes
f x|odd x=x+1|0<1=x-1

I have no idea why I'm doing this xD

J, 9 bytes
(22 b.)&1

22 b. is XOR. Port of Cyoce's ruby answer.
Try it online!
Alternative straightforward answer:
+1:`_1:@.(2&|)
Try it online!

Japt, 4 bytes
aJpU

Try it (includes all test cases)
aJpU     :Implicit input of integer U
a        :Absolute difference with
 J       :  -1
  pU     :  Raised to the power of U

Keg, -hr, 7 bytes
:2%[;|⑨

Try it online!

Lua (40 bytes)
Using a table in order to avoid math.ceil or math.floor
function m(n)return n+({-1,1})[1+n%2]end

BRASCA, 7 bytes
ig{1_}n

Try it online!
Explanation
i       - Turn ASCII codepoints 48-57 to numbers 0-9
 g      - Concatenate stack
  {     - Decrement
   1_   - XOR by 1
     }  - Increment
      n - Output as number

TI-Basic, 7 bytes
Ans-i^(2Ans

Takes input in Ans. Output is stored in Ans and is displayed.

Alternatively, 9 bytes:
Ans-cos(2πfPart(Ans/2

><> (Fish), 10 bytes
:2%2*+1-n;

Try it

Thunno 2, 5 bytes
Ṅ1Æ^Ṅ

Attempt This Online!
Explanation
Ṅ1Æ^Ṅ  # Implicit input
    Ṅ  # -(        )
Ṅ      #   -input
  Æ^   #         ^
 1     #          1
       # Implicit output

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Binary Puzzle Solver
Introduction
Rules of the puzzle:
The puzzle Binary (also known as Takuzu or Subiku) is very simple to understand, and has only a few rules:
Since the name of the game is binary it's pretty obvious, but you can only fill in zeros and ones.

No more than two of the same digit can be vertically or horizontally adjacent to each other
Each row and each column must contain an equal amount of zeros and ones (this implicitly means every binary game will always have even dimensions).
There may be no duplicated rows and no duplicated columns (with the exact same order of zeros and ones).

You can play the game at www.binarypuzzle.com if you want to.
Tactics:
Due to rule 1, we can always fill in a digit if:
- There are already two of the same digit vertically or horizontally adjacent to each other, in which case we can fill in the opposite digit at both sides. I.e. .11... → 0110...
- There are two of the same digit vertically or horizontally with only one gap in between them. I.e. .1.1.. → .101..
Due to rule 1, when three gaps are left and we cannot have three adjacent of the same digit, we can fill in one of the gaps. I.e. .0.1.0 → 10.1.0 (We still have to fill in two ones, and we cannot have three adjacent ones in the middle, so the first gap has to be a 1.)
Due to rule 2, we can always fill in the remaining gaps in a row or column if halve of them is already filled in with the opposite digit. I.e. .1.011 → 010011
Due to rule 3, we can always fill in the opposite digits if only two are left to solve on an equally ordered line. I.e. 101100 & 1..100 → 101100 & 110100
Due to rule 3, we can sometimes fill in a gap when three gaps are left on an equally ordered line. I.e. 010011 & .1.01. → 010011 & .1.010 (Here we cannot fill in a 1 at the end, because that would mean we have to fill in zeros at the other two gaps, making both lines equal in order.)
Example:
We start with the following 6x6 grid with some ones and zeros filled in (and the dots are gaps we have yet to fill in):
.1....
.10.0.
1.11..
.1....
...1.0
......

Due to rules 1 & 2 we can fill in these digits:
.1.01.
.1010.
101100
010011
.0.1.0
.010..

Due to rule 1 we can fill in a 1 at row 5, column 1:
.1.01.
.1010.
101100
010011
10.1.0
.010..

Due to rule 3 we can fill in a 0 at row 1, column 6 (when looking at row 4):
.1.010
.1010.
101100
010011
10.1.0
.010..

Now we can continue to fill gaps with digits due to rules 1 & 2:
.1.010
010101
101100
010011
10.1.0
.010.1

Now we can finish row 5 due to rule 3 (when looking at row 3):
.1.010
010101
101100
010011
100110
.010.1

And then we can finish the puzzle due to rules 1 & 2:
011010
010101
101100
010011
100110
101001

Challenge:
The challenge is simply: given the starting grid, output the solved puzzle.
NOTE: You don't have to implement the rules above. You of course can, and it should give you hints on how to implement this challenge, but bruteforcing the solution with the rules in mind is completely fine.
How you solve it is up to you, but the challenge is to output the solved puzzle.
Challenge rules:

Input and output format for the grid is flexible, but please state what you use. (I.e. 2D byte-array; String with newlines; etc.)
This above also applies to the characters used. In the example I've used 01., but if you want you can use ABx instead. Please state what input/output format and characters you've used.
You can assume only the following grid sizes will be used: 6x6; 8x8; 10x10; 12x12; 14x14; 16x16.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:
The dots are only added for readability, feel free to use spaces or anything else you prefer for gaps instead. Both in and output format is flexible.
Input:
1..0..
..00.1
.00..1
......
00.1..
.1..00

Output:
101010
010011
100101
011010
001101
110100

Input:
.1....
.10.0.
1.11..
.1....
...1.0
......

Output:
011010
010101
101100
010011
100110
101001

Input:
.......1..
.00..0..1.
.0..1..0.0
..1...1...
1.1......1
.......1..
.0..1...0.
....11...0
.0.0..1..0
0...0...1.

Output:
0110010101
1001100110
1001101010
0110011001
1010100101
0101010110
1001101001
0110110100
1010011010
0101001011

It's been in the sandbox since April 4th. - Related: A 4x4 Challenge

Related OEIS entry.

Brachylog, 34 bytes
{ℕ<2}ᵐ²&≜{d?ọᵐctᵐ=&{ḅlᵐ⌉<3}ᵐ}&\↰₂&

Try it online!
This is pretty damn slow, so the test case on TIO is 4x4. I am currently running the 6x6 test case on my computer to see how much time it takes.
This takes a list of lists as input. The unknown values should be indicated with variables, that is with all-uppercase strings (and they should all be different, as otherwise you would be indicating that some cells must have the same value)
Explanation
We constrain the values to be in {0,1}, then we try instantiations of the variables until one respects all 3 rules. This is why this is so slow (because it will try all of them until finding one; and because in that case Brachylog is not implemented well enough so that constraints can be imposed before trying a possible matrix).
                                 &  Output = Input
{   }ᵐ²                             Map two levels on the Input (i.e. each cell):
 ℕ<2                                  The cell is either 0 or 1
       &≜                           Assign values to all cells
         {                  }       Define predicate 2:
          d?                          The Input with no duplicates is still the Input
                                        (i.e. all rows are different)
           ?ọᵐctᵐ=                    All occurences of 1s and 0s for each rows are equal
                  &{      }ᵐ          Map on rows:
                    ḅlᵐ                 Get the lengths of runs of equal values
                       ⌉<3              The largest one is strictly less than 3
                             &\↰₂   Apply predicate 2 on the transpose of the Input
                                      (i.e. do the same checks but on columns)

Out of curiosity, how does Brachylog indicate variables beyond the capital alphabet? So let's say your solution would work faster, it won't be able to fill in all empty spaces on a 14x14 grid with A through Y (with Z as output-parameter). Does it continue with AA, AB, etc?

@KevinCruijssen Any all-uppercase identifier is a variable, so yes AA is a variable and KEVINCRUIJSSEN is also a variable.

As I suspected, a challenge made for Brachylog :D

JavaScript (ES6), 274 270 bytes
Takes input as a 2D array, where empty cells are marked with 2. Prints all possible solutions to the console.
f=(a,x=0,y=0,w=a.length,p,R=a[y])=>(M=z=>!a.some((r,y)=>/(0|1),\1,\1/.exec(s=r.map((v,x)=>(v=z?v:a[x][y],b-=v&1,c-=!v,m|=v&2,v),b=c=w/2))||b*c<0|o[b*c||s]&(o[s]=1),o={}))(m=0)&M(1)&&(m?R&&[0,1].map(n=>(p=R[x])==n|p>1&&(R[x]=n,f(a,z=(x+1)%w,y+!z),R[x]=p)):console.log(a))

How it works
The first part of the code uses the M() function to check the validity of the current board, both horizontally and vertically.
M = z =>
  !a.some((r, y) =>
    /(0|1),\1,\1/.exec(
      s = r.map((v, x) =>
        (
          v = z ? v : a[x][y],
          b -= v & 1,
          c -= !v,
          m |= v & 2,
          v
        ),
        b = c = w / 2
      )
    ) ||
    b * c < 0 |
    o[b * c || s] &
    (o[s] = 1),
    o = {}
  )

It maps a full row or column to the string s. This is actually an array coerced to a string, so it looks like "1,2,2,0,2,2".
It uses:

The regular expression /(0|1),\1,\1/ to detect 3 or more consecutive identical digits.
The counters b and c to keep track of the number of ones and zeros. Both counters are initialized to w / 2 and decremented each time a one or a zero (respectively) is encountered. This leads to either:

b = c = 0 → b * c = 0 → the line is complete and correct (as many zeros as ones)
b > 0 AND c > 0 → b * c > 0 → the line is not complete but correct so far (we don't have more than w / 2 zeros or more than w / 2 ones)
b < 0 OR c < 0 → b * c < 0 → the line is invalid

The flag m (for 'missing') which is non-zero if there's at least one remaining two on the board.
The object o to keep track of all line patterns encountered so far.

If the board is invalid, we stop immediately. If the board is valid and complete, we print it to the console. Otherwise, the second part of the code attempts to replace each 2 with either a zero or a one with recursive calls:
[0, 1].map(n =>
  (p = a[y][x]) == n |
  p > 1 && (
    a[y][x] = n,
    f(a, z = (x + 1) % w, y + !z),
    a[y][x] = p
  )
)

Demo

f=(a,x=0,y=0,w=a.length,p,R=a[y])=>(M=z=>!a.some((r,y)=>/(0|1),\1,\1/.exec(s=r.map((v,x)=>(v=z?v:a[x][y],b-=v&1,c-=!v,m|=v&2,v),b=c=w/2))||b*c<0|o[b*c||s]&(o[s]=1),o={}))(m=0)&M(1)&&(m?R&&[0,1].map(n=>(p=R[x])==n|p>1&&(R[x]=n,f(a,z=(x+1)%w,y+!z),R[x]=p)):console.log(a))

console.log('Example #1')
f([
  [1,2,2,0,2,2],
  [2,2,0,0,2,1],
  [2,0,0,2,2,1],
  [2,2,2,2,2,2],
  [0,0,2,1,2,2],
  [2,1,2,2,0,0]
])

console.log('Example #2')
f([
  [2,2,2,2,2,2,2,1,2,2],
  [2,0,0,2,2,0,2,2,1,2],
  [2,0,2,2,1,2,2,0,2,0],
  [2,2,1,2,2,2,1,2,2,2],
  [1,2,1,2,2,2,2,2,2,1],
  [2,2,2,2,2,2,2,1,2,2],
  [2,0,2,2,1,2,2,2,0,2],
  [2,2,2,2,1,1,2,2,2,0],
  [2,0,2,0,2,2,1,2,2,0],
  [0,2,2,2,0,2,2,2,1,2]
])

Thanks for adding the explanation. And I like how you print all possible outputs, instead of just one!

@KevinCruijssen This is probably far from optimal but was fun to write. Nice challenge!

Jelly, 53 51 bytes
ṡ€3ḄFf0,7L
SḤnLṀȯÇ
⁻QȯÇ
Fṣ©2L’0,1ṗż@€®F€s€LÇÐḟZÇ$Ðḟ

Takes a list of lists representing the grid, containing 0, 1, and 2 (the spaces). Returns a list of lists of lists, each list of lists is in the same format (although with no 2s) and represents a possible solution to the input.
Try it online! (this wont run any of the question's test cases due to memory limitations - all 2nSpaces grids are created as a list of list of lists of integers - but I've put a relatively hefty case there with a single solution). The footer separates out and formats the grids.
Pure brute force method - implements the rules and checks them for each grid that could be formed by replacing any of the 2s with 1s or 0s.
ṡ€3ḄFf0,7L - Link 1, # of runs of 3 1s or 3 0s by row: list of lists
ṡ€3        - all contiguous slices of length 3 for €ach list
   Ḅ       - convert all results from binary
    F      - flatten into one list
     f     - filter keep values in:
      0,7  -   0 paired with 7: [0,7]
         L - length

SḤnLṀȯÇ - Link 2, unequal counts of 1s and 0s by column ...or link 1: list of lists
S       - sum (vectorises, hence "by column", counts 1s since only 1s or 0s appear)
 Ḥ      - double
   L    - length (number of rows - OK since square)
  n     - not equal? (vectorises)
    Ṁ   - maximum (1 if any not equal)
     ȯÇ - ... or last link (1) as a monad

⁻QȯÇ - Link 3, rows are unique ...or link 2: list of lists
 Q   - unique
⁻    - not equal?
  ȯÇ - ... or last link (2) as a monad

Fṣ©2L’0,1ṗż@€®F€s€LÇÐḟZÇ$Ðḟ - Main link: list of lists
F                           - flatten
 ṣ©2                        - split at 2s and copy the result to the register
    L                       - length (# of such slices)
     ’                      - decrement (# of 2s)
      0,1                   - 0 paired with 1
         ṗ                  - Cartesian power (all binary lists of length # of 2s)
             ®              - recall value from register (the flat version split at 2s)
          ż@€               - zip (reversed @rguments) for €ach (1s & 0s where 2s were)
              F€            - flatten €ach
                s€L         - split €ach into chunks of length length(input) (into rows)
                    Ðḟ      - filter discard if:
                   Ç        -   call last link(3) as a monad
                         Ðḟ - filter discard if:
                        $   -   last two links as a monad:
                      Z     -     transpose
                       Ç    -     call last link(3) as a monad


text:
Find the coterminal angle on [0, 2π)
This challenge is very simple:
Given an angle measure in degrees or radians (your choice), output the angle between 0 and 2π non-inclusive  [0º, 360º) that is coterminal with it.
Input
A positive or negative angle measure. You can pick if you want to take it in degrees or in radians.
Output
The angle on [0, 2π) that is coterminal with the input angle. If you take the input in degrees, the output must also be in degrees; if you take it in radians, the output must be in radians too. The coterminal angle is essentially a the angle mod 360°.
Examples (in degrees)
745 -> 25
1728 -> 288
90 -> 90
0 -> 0
360 -> 0
-50 -> 310
-543.21 -> 176.79

Please define "coterminal".

I'm guessing on the basis of the examples that answers have to support floating point or fixed point input, but it would be good to have that in the spec (and rule out the GolfScript answer I would otherwise submit)

For reference of what a coterminal angle is: http://www.softschools.com/math/trigonometry/coterminal_angles/

The test cases converted to radians: https://pastebin.com/hUuUkqqg

I feel like this challenge is too trivial. Honestly, a a % b challenge would be more interesting, although I feel like we've had that before.

Your link took several minutes to open. It would be better to simply explain that you want us to take the input positive modulo 360 and output it.

@LevelRiverSt, took a couple seconds for me

Regardless of how long it takes to open, you should still put the meaning if coterminality (?) in the body of the question

05AB1E, 4 bytes
360%

Try it online!
360  # push 360
   % # pop a,b: push (a % b)

Python 3, 14 bytes
lambda n:n%360

Try it online!

Wait, % always returns positive?

@HyperNeutrino As long as the divisor is positive, yes

Oh, cool! (I'm still used to Java where it's the same sign lol).

R, 11 bytes
takes input from stdin in degrees
scan()%%360

Try it online!

MATL, 5 4 bytes
360\

Try it online!
My first attempt with MATL!
-1 byte, just realised i is not necessary for recording the input...

...How on earth does this work? :o

@BetaDecay: Likely just a modulo with mathematically well-behaved behaviour for negative numbers. That's basically what the question is asking for.

Yeap, basically it uses Matlab's mod() function I think.

Python 3, 13 bytes
360..__rmod__

Explanation:
num.__rmod__(x) is equivalent to x%num (rmod is modulo from the right.).

Do not works for the last test case -543.21 (or any other float number) -> NotImplemented

360..__rmod__ works for floats as well.

05AB1E, 4 bytes
Just because there were no answers using radians.
žq·%

Try it online!

CJam, 12 bytes
rd360:X%X+X%

All those extra bytes because CJam gives negative results for mods...
Try it online!

C, 69 43 bytes
This seems like an excessively trivial challenge, and indeed in many languages it is. The trick is in the implementation details of the modulo operator.
When both modulo operands are positive, nothing interesting happens. But when one of the operands is negative, then the results start depending on your interpretation of what should happen. You can either always return a positive result, return a result whose sign depends on the dividend, or return a result whose sign depends on the divisor.
Programming languages are quite divided on which behavior they choose to implement. The lucky ones for this challenge are the ones that always return a positive result, since that's what the test cases call for.
If you happen to be golfing in a language that implements modulo dependent on the sign of the dividend, then you have to do extra work to compensate for negative inputs—and to make sure that this compensation does not break positive inputs!
Here's a further golfed implementation in C (thanks to ais523):
f(double*n){*n=fmod(fmod(*n,360)+360,360);}

Try it online!
Notice that C is also hobbled here by the unfortunate omission of a modulo operator (a la %) for floating-point operations. Instead, you have to call a library function.

Several possible improvements: remove the #include (it's not required for the code to work, as all arguments to fmod have non-autopromoted types); remove the space after n,; instead of returning via the return value, take a float* as your argument, and return via assigning back to the argument (i.e. *n=…fmod(*n,360), not return…fmod(n,360)).

My poor golfing skills are showing. Thanks for the suggestions, @ais523! I've incorporated them into my answer. I still feel incredibly dirty writing code like this. It's one thing to make things small and correct, but I'm not sure how I feel about making them small and dubious, taking advantage of implicit int with no actual return value.

Jelly, 4 bytes
%360

Try it online!
I was kind of hoping Æ°° would do it for 3.

Java 7, 44 43 bytes
Crossed out 44 is still regular 44 ;(
float c(float n){return(n%=360)<0?n+360:n;}

Explanation:
Java uses remainder instead of actual modulo for negative numbers (source). So we'll have to manually fix the negative cases.
float c(float n){    // Method with float input and float return-type
  return(n%=360)<0?  //  If input mod-360 is negative
   n+360             //   Return input mod-360 + 360
  :                  //  Else:
   n;                //   Return input mod-360
}                    // End of method

Test code:
Try it here.
class M{
  static float c(float n){return(n%=360)<0?n+360:n;}

  public static void main(String[] a){
    System.out.print(c(745) + "; ");
    System.out.print(c(1728) + "; ");
    System.out.print(c(90) + "; ");
    System.out.print(c(0) + "; ");
    System.out.print(c(360) + "; ");
    System.out.print(c(-50) + "; ");
    System.out.print(c(-543.21f));
  }
}

Output:
25.0; 288.0; 90.0; 0.0; 0.0; 310.0; 176.78998

float c(float n){return(n<0&&360)+n%360;} for 41 bytes.

@Luke That doesn't work in Java, unlike JavaScript for example, because n<0 is a boolean and 360 is an integer. So it gives this error: "The operator && is undefined for the argument type(s) boolean, int".

Ah, yeah. Shouldn't have expected every language is as loosely typed as JS...

@Luke That doesn't work for -360 either.

On the other hand, I think (n%360+360)%360 is good.

Japt, 14 11 10 4 bytes
u#Ũ

Try it online!
Takes input in degrees.
Explanation
 u#Ũ
Uu360
U     # (implicit input)
 u    # modulo
  360 # 360
      # (implicit output)

Numbers have a u function for just this purpose, if I recall correctly, so u#Ũ) should work :-) (Also, Ũ is actually two bytes)

Both TIO and your transpiler say it's just one byte...

x86 Assembly (targeting the x87 FPU), 23 bytes
As is standard with 32-bit calling conventions, the double-precision floating-point parameter is passed on the stack, and returned at the top of the x87 FPU stack. Assemble with MASM:
.MODEL flat
.686                              ; fucomip requires a Pentium Pro or later CPU

CONST SEGMENT
divisor  DD  043b40000r           ; 360.0f
CONST ENDS

PUBLIC _CoterminalAngle
_TEXT SEGMENT
_CoterminalAngle PROC
   fld      DWORD PTR [divisor]   ; single-precision takes fewer bytes to store; we don't need the precision
   fld      QWORD PTR [esp + 4]   ; load parameter from stack

   fprem                          ; st(0) = parameter % 360
                                  ; st(1) = 360

   fldz
   fucomip  st(0), st(1)          ; st(0) < 0?
   jbe      Finished
   fadd     st(0), st(1)          ; fixup negative modulo by adding 360
Finished:

    fstp    st(1)                 ; discard st(1); result is left in st(0)
    ret
_CoterminalAngle ENDP
_TEXT ENDS

END

To call from C:
extern double CoterminalAngle(double value);

In bytes:
43B40000

D9 05 00 00 00 00
DD 44 24 04
D9 F8
D9 EE
DF E9
76 02
D8 C1
DD D9
C3

Notes:
As the comment indicates, to minimize code size, I've stored the divisor constant (360.0f) as a single-precision floating-point value. This means it is half the length it would be if it were a double-precision value, and we don't need the precision to store a proper representation of the value. Upon loading, the x87 FPU will implicitly extend it to its native ten-byte extended-precision format.
We're also playing it fast-and-lose with the FPREM instruction for golfing purposes, assuming it does not need to reduce the exponent of the input value by more than 63. The careful (read: correct) way to call it would be iteratively, in a loop, continuing to execute it as long as the "parity" flag is set.
For example:
RemainderLoop:
   fprem
   fstsw  ax
   sahf
   jp     RemainderLoop

That would add 6 bytes to the total.

x86 Assembly (targeting AVX), 47 bytes
By way of comparison (and for completeness), here's an AVX implementation. It's more bytes, but also more efficient. The parameter is passed in XMM0, and the result is returned in the same register, as with any x86-64 or vector x86-32 calling convention.
43 B4 00 00    | divisor  DD  043b40000r           ; 360.0f

               | ; Load single-precision FP value, and convert it to double-precision.
C5 EA 5A 15 00 | vcvtss2sd  xmm2, xmm2, DWORD PTR [divisor]
    00 00 00   |
               | ; Divide input parameter (XMM0) by divisor (XMM2), and store result in XMM1.
C5 FB 5E CA    | vdivsd     xmm1, xmm0, xmm2
               |
               | ; Truncate the result of the division to the nearest integer.
C5 FB 2C C1    | vcvttsd2si eax, xmm1
C5 F3 2A C8    | vcvtsi2sd  xmm1, xmm1, eax
               |
               | ; Multiply the truncated result by divisor (XMM2).
C5 F3 59 CA    | vmulsd     xmm1, xmm1, xmm2
               |
               | ; Subtract this temporary value (XMM1) from the original input (XMM0).
C5 FB 5C C1    | vsubsd     xmm0, xmm0, xmm1
               |
               | ; See if the result is negative.
C5 F1 57 C9    | vxorpd     xmm1, xmm1, xmm1   ; xmm1 = 0
C5 F9 2F C8    | vcomisd    xmm1, xmm0         ; result < 0?
76 04          | jbe        Finished
C5 FB 58 C2    | vaddsd     xmm0, xmm0, xmm2   ; fixup negative modulo by adding divisor (XMM2)
               |
               | Finished:
C3             | ret

Of course, it would be even more efficient to multiply by the reciprocal, instead of dividing. But that means more precision is required to store the divisor, and would thus slightly increase the size of the code.

JavaScript (ES6), 21 19 18 bytes
Takes input in degrees.
n=>(n%360+360)%360

Saved 2 bytes thanks to Luke.
Saved 1 byte thanks to Neil.

Try it

f=
n=>(n%360+360)%360
i.addEventListener("input",_=>o.innerText=f(+i.value))
console.log(f(745)) // 25
console.log(f(1728)) // 288
console.log(f(90)) // 90
console.log(f(0)) // 0
console.log(f(360)) // 0
console.log(f(-50)) // 310
console.log(f(-543.21)) // 176.79
<input id=i type=number><pre id=o>

Beat me by 50 secs... 19 bytes: n=>n%360+(n<0&&360)

And you beat me to that improvement! Thanks, @Luke.

I don't think that works for -360, but try (n%360+360)%360.

You're right. And you saved me a byte. Thanks, @Neil.

Fourier, 22 14 6 bytes
I%360o

Try it online!
Simply outputs the input modulo 360.
Note that since the interpreter for TIO is written in Python, this will not work on http://beta-decay.github.io/editor

Mathematica, 10 bytes
#~Mod~360&

Pure function taking any type of numerical input in degrees. Does what it says on the tin.

Python 2 REPL - 11 bytes
input()%360

If we've got a wierd input function, we might as well abuse it, right?

+6 bytes for printing the output

@JulianWolf Or cheat and say use the REPL :)

Pyth - 5 bytes
%Q360

Would be shorter if %360 meant Q%360 instead of 360%Q, but oh well...

PHP, 29 Bytes
<?=($v=$argn%360)>=0?:$v+360;


text:
Period 2 Reversed Quine
Your task is to write a program that outputs its own source code in reverse. However, when the reversed code is run, it should output the source code, facing the correct direction.
Example
Say your program is abc. When run, it should output cba. cba, when run, should output abc.
Rules
Your program should follow all the rules of a proper quine (except for outputting the source code).
Palindromes are disallowed.
Random note:
I am aware of this but I believe that this challenge is different because the transformed code must have the same properties.

Related

Also related.

RProgN, 3 bytes
1
2

Thanks to @MartinEnder for reminding me about this answer.
Try it online!
How it works
This exploits a potential flaw in our definition of proper quine:

It must be possible to identify a section of the program which encodes a different part of the program. ("Different" meaning that the two parts appear in different positions.)
Furthermore, a quine must not access its own source, directly or indirectly.

That's obviously the case here, as the output is the reverse of the code and the code is not a palindrome.
RProgN – reverse programmer notation – uses a LIFO stack and prints the items on it in the order they are popped. The two tokens 1 and 2, separated by spaces and/or newlines, get popped in reverse order and are printed separated by a newline.
This prints the reversed program
2
1

which, in turn, prints the original one.
!enilno ti yrT

I like the URL.

We should get this fixed... I'd post a new answer (based on this comment) on the meta question, but it probably wouldn't get enough attention to compete with the existing answers.

@ETHproductions: Do it. I feel there are several problems with our current proper quine definition. (Arguably, my language 7 is a study in edge cases for proper quineness; in addition to this particular case, it can handle quite a few others.) FWIW, I'm not sure this is a proper reverse-quine even by our current definition; the 1 and 2 are clearly encoded by themselves, so the only potential interest is as to what's encoding the newline. (This is different from a 1\n1, in which the two 1s encode each other; that's possibly a proper quine but not a proper reverse-quine.)

Befunge-98, 33 bytes
b3*>1#;-:0g,:#;_@_;#:,g0:-;#1>*b3

Try it online!

Nice first answer. But use the # to make you header. Also go to Tryitonline.net and get a online interpreter

Also go under the save button and use the codegolf submission one.

I edited it on TIO in the first place I just forgot to add the link but now its added and thanks for the Header tip

Note that the "codegolf submission" option on TIO gives you a starting template, including the header.

I thought g was disallowed in Befunge quines, as it reads the program's source directly from memory?

I'm not sure but the Quines on wikipedia use it so I quess its allowed

Wikipedia doesn't care about PPCG's Proper Quine definition.

Fission 2, 10 bytes
"L;L'!+!'_

Try it online!
This prints:
_'!+!'L;L"

Try it online!
And vice versa.
Explanation
This is a modification of the reverse quine. It's working to our advantage here that ! is used for printing and is also only one code point away from the the quote ". That makes it easier to make the quote printing section palindromic (the '!+!'). Let's start with the first code:
"L;L'!+!'_

This program has two entry points at the Ls, which each creates a left-going atom. However, the right one immediately hits the ; which destroys it. The left one enters string mode and wraps around to the end, so that it prints the entire code (except the ") from back to front. That already gives us _'!+!'L;L. All that's left is to print the ". _ can be ignored, '! sets the atom's mass to 33 (the code point of !), + increments it to ", and ! prints it. That's all the output done. The 'L sets the atoms mass to the code point of L but that's irrelevant. ; destroys this atom as well and since no atoms are left, the program terminates.
Now the other way round:
_'!+!'L;L"

Again, we have two entry points but one atom is immediately destroyed. This time we move through the !+!' section first, so we start by printing a quote. The '_ is again irrelevant, but we need the _ (or some other useless character) here to avoid ' escaping the ". The atom wraps to the end, traverses the source code once in string mode to print the rest of the program in reverse, the L is then ignored and ; destroys the atom and terminates the program.

<><, 19 bytes
"rf2+2*rol?!;70.05;!?lor*d3r'

Try it
Reversed
'r3d*rol?!;50.07;!?lor*2+2fr"

it yrT
So I'm not super sure if this is a proper quine. Let me know what your opinion is, I'll delete the post if people think it's invalid.
I use the ' to switch into quoting mode that will push the code raw into the stack. Then when the pointer wraps around it will exit the quote again. However, I do need to manually add the ' quote character at the end as d3*, and " as rf2+2. These would count as "code that encodes a different part of the program".