text:
Keyboard vs Code-Golf?
If you've come here, you probably know what code-golf is, and that's what I'm going to assume.
Story
(I guess)

Keyboards are input devices we use all the time. They existed before mice and touch screen, etc.
Their fundamentals have not changed: when you press a key down, a signal is sent to the computer. When you release it, another signal is sent.
So here's the challenge: calculate the minimum number of signals(length of a signal does not matter) depending on the input string.
Example:
Input:
test

Output:
8

Explanation:
  All keys have to be pressed down and released

Input2:
TEst

Output2:
10

Explanation:
  Shift has to be pressed, then T, down, up, E, down, up, then release shift, then s down, up, then t down, up, totalling up to 10.

Rules
Any language is accepted.
This is code-golf, so shortest code in bytes wins.
Programs with incorrect outputs will be disqualified.
Happy golfing!
Edit:
The keyboard layout used should be this: http://dry.sailingissues.com/keyboard-US-International.png
Only characters in this keyboard layout will be used (+lowercase letters).
Using Caps-Lock is ok, since it DOES have an advantage: numbers remain numbers while letters become uppercase.

Please specify what keyboard you are using for scoring this challenge, with a picture/diagram, if possible.

What is expected output for tttttt? Since I can hold the button down. Personally you should score this on key presses.

Welcome to PPCG! This looks like a great first challenge, but as you may have noted from the questions in the comments: it might need some tweaking. We've got the Sandbox for Proposed Challenges for that exact purpose. There you can post it, let other people leave feedback to perfect your challenge, and when it's ready (and at least 48 hours has passed) it can be posted on the main. Just something to keep in mind for next time. Again, welcome, and nice challenge! :)

@StephenS it is considered as 12 signals.

If characters in that keyboard will be used, can you include testcases with those special characters?

So, we can choose if Caps Lock is on or off? Also, should we use Caps Lock or shift for a case like A.B.C.D.E.F.G.H.I.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z., assuming Caps Lock is off by default? Using Caps Lock is fewer signals in this case. Also what about the special chars?

What happens when Shift is pressed, CapsLock is on, and you press a letter?

This is an awesome challenge, rewrite it in the sandbox and we'll help.

I really like this challenge, still you need to specify the keyboard + layout in detail. For example I use Neo2, so things like ∀ε>0:∃n∈ℕ ... take me a maximum of 3*(press + release) = 6 signals for each character.


text:
Magnanimous numbers
Given an positive integer as input determine if it is a magnanimous number.
A magnanimous number is a number such that any insertion of a + sign between any two digits in base 10 results in an expression of a prime integer.
For example 40427 is magnanimous because
4+0427  = 431  is prime
40+427  = 467  is prime
404+27  = 431  is prime
4042+7  = 4049 is prime

Output
You should output two distinct values, one when the input is magnanimous and one when the input is not.
Scoring
The goal of this contest will be to make the size of the source code written to solve this task, given in bytes, as small as possible.
Test Cases
1       -> True
2       -> True
4       -> True
10      -> False
98      -> True
101     -> True
109     -> False
819     -> False
4063    -> True
40427   -> True
2000221 -> True

OEIS 253996

I'm just confused by the definition of the challenge how 1 and 2 are even valid inputs. Let alone the fact that 1 with a plus sign inserted between any two characters (no inserting) can only result in 1, which itself is not prime.

@MagicOctopusUrn The plus must be inserted between two digits, thus since 1 and 2 don't have two digits the set of expressions is empty.  All of the members of the empty set are prime.  In addition none of them are, but thats besides the point.  It is a bit confusing, I'll give you that but I think it makes more sense than the alternatives.

05AB1E, 10 bytes
Code
η¨¹.s¨R+pP

Uses the 05AB1E encoding. Try it online! or Verify all test cases!
Explanation
η¨             # Take the prefixes of the input and remove the last element
  ¹.s¨         # Take the suffixes of the input and remove the last element
      R        # Reverse the array of suffixes
       +       # Vectorized addition
        p      # Check if each element is prime
         P     # Product of the array

How does it work for 1 - 9. The product of an empty set is 1? Why?

@MagicOctopusUrn Empty product always equals 1.

@MagicOctopusUrn Taking the product is basically starting with 1 and multiplying it by each item in the set, so...

Ah, mathematically makes sense. Guess just like how sum on [] is equivalent to 0, using the induction property when implementing was pretty smart.

@jontro Yes, in UTF-8, it is 14 bytes. However, 05AB1E uses the 05AB1E code page, where this is 10 bytes.

C (gcc), 83 84 85 83 84 86 75 111 bytes
All optimizations turned off and only on GCC 32-bit.
-1 byte thanks to @ceilingcat
+some bytes for 1 case.
+some bytes for reusable functions.
i,j,r,s;f(a){for(i=10,r=1;a/i;i*=10)for(s=a%i+a/i,r*=s-1,j=2;j<s;)r*=s%j++>0;a=!r;}

Takes input as an integer. Return 1 for false cases, 0 for true cases.
Try it online!
See my another answer for Mathematica code (55 bytes).

This should be two separate answers. Also, the Mathematica solution gives incorrect results for 1, 98, and 4063.

Retina, 38 bytes
\B
$`$*_$'$*_
S`\d
G`^_$|^(__+)\1+$
^$

Try it online!
Prints 1 for magnanimous numbers and 0 otherwise.
Explanation
\B
$`$*_$'$*_

We start by matching each position between two digits (positions that aren't word boundaries) and inserting both the prefix and the suffix of that match in unary, using _ as the unary digit. So instead of inserting +s, we directly insert the unary result of the sum there.
S`\d

Now we split the string around digits, so that each sum goes on its own line and we get rid of those digits (there'll be an empty leading and trailing line as well, but that's not important).
G`^_$|^(__+)\1+$

This is the standard regex to match non-prime numbers in unary. Using a Grep stage here means that we simply keep all lines that contain positive non-primes (discarding the empty lines).
^$

Finally we check whether the string is empty. If the input was magnanimous, the previous stage will have discarded all lines (because they were all primes), and this gives us 1. Otherwise, if any line wasn't a prime, it will remain in the string and the regex fails, giving 0.

Python 2, 82 79 78 bytes
f=lambda n,d=10:n<d or d/n<all((n/d+n%d)%k*f(n,10*d)for k in range(2,n/d+n%d))

This is slow and can only cope with the test cases with memoization.
Try it online!
Alternate version, 79 bytes
f=lambda n,d=10:n<d or f(n,10*d)>d/n<all((n/d+n%d)%k for k in range(2,n/d+n%d))

Sped up at the cost of one byte.
Try it online!

Jelly, 12 bytes
DJ⁵*⁸dṖS€ÆPẠ

Try it online!
Verify all test cases.

Clever use of d!

@EriktheOutgolfer it's the third alternative I tried, after "all partition -> filter for length 2" and "J, untruth, partition each"

Java 8, 175 171 94 88 bytes
n->{long d=10,r=0,i,t;for(;d<=n;d*=10,r|=t-i)for(t=n/d+n%d,i=1;t%++i%t>0;);return r==0;}

-77 thanks to @PeterTaylor by using an arithmetic (instead of String with .substring) and getting rid of the separate method to check if the integer is a prime.
-6 bytes using @SaraJ's prime-checking method, so make sure to upvote her!
Try it here.
Explanation:
n->{                  // Method with long as both parameter and return-type
  long d=10,r=0,i,t;  //  Some temp longs
  for(;d<=n           //  Loop as long as `d` is below or equal to input `n`
                      //  (inclusive instead of exclusive due to special case 10)
      ;               //    After every iteration:
       d*=10,         //     Multiple `d` by 10
       r|=t-i)        //     and Bitwise-OR `r` with `t-i`
    for(t=n/d+n%d,    //   Set `t` to `n` integer-divided by `d` plus `n` modulo-`d`
        i=1;          //   Set `i` to 1
        t%++i%t>0;);  //   Inner oop as long as `t` modulo `i+1` modulo `t` is not 0 yet
                      //   (after we've first increased `i` by 1 with `++i`)
                      //   (if `t` equals `i` afterwards, it means `t` is a prime)
  return r==0;}       //  Return if `r` is still 0

I think there are at least two ways to shorten this: firstly, replace the loop in p with recursion; secondly, accumulate the results such that the main function only requires one return statement by making the sentinel value from p be -1 and using & to check that all the returned values are -1.

Actually, the big one is: don't use strings.

n->{for(long d=10,m=1;d<n;d*=10)m|=p(n/d+n%d,2)-2;return m>0;}long p(long n,int i){return i<n?p(n%i<1?1:n,i+1):n;}

@PeterTaylor Thanks for the suggestions! As for your suggested function at the end, are you sure it's correct? I currently gives incorrect results, unless I'm doing something wrong.

@PeterTaylor Correction: The last test case is too big resulting in a StackOverflowError, and it gives an incorrect result for the special test-case 10. Everything else works.

Ok, d<=n to handle 10. Stack overflow isn't a problem (the spec doesn't give a range of input which must be handled), but can be fixed and more savings obtained by reverting to a loop and inlining.

Japt, 23 bytes
Takes input as a string.
Dang it; beaten to the punch on a much shorter alternative I was working on.
¬£i+YÃÅe@OxXr"%+0+"'+)j

Test it

@ETHproductions, no, you were right; the original version was wrong; only checking for magnanimous primes. ¬£i+YÄÃe@OxX j

I knew I hadn't lost my mind ;P

Fails on 4063 (should be true, is false). The trick here is that JS thinks a leading 0 means you want octal...

Hmmm ... OK, think I have an alternative - will take a few minutes to test it & golf it.

I think this will fail now on some case that contains two 0s followed by two other digits... (40043, for example) Just add a + after the 0 to fix this.

Python 2, 104 102 98 96 103 bytes

Thanks to @Wheat Wizard for 2 bytes: made i completely anonymous since it is called only once.
Thanks to @Hyperneutrino for 4 bytes: smarter way of obtaining the numbers from the main number instead of slicing
@Hyperneutrino saved another 2 bytes: x-1 to just x for the prime checking rarnge.
Fixed failure for case x=10,thus adding 7 Bytes, thanks to @Dennis and @Wheat Wizard for spotting it: my earlier version was considering 1 a prime

lambda x:all((lambda x:x>1and all(x%j for j in range(2,x)))(x/10**j+x%10**j)for j in range(1,len(`x`)))

Try it online!

98 bytes

Cool, thanks @HyperNeutrino

96 bytes: You don't need the x-1 at the end of the range; range is exclusive on the right.

This fails for 10 (new test case).

This fails for 10.  I also believe that 10 is the only number this fails for.

Fixed. Check it.

CJam, 22 bytes
r:L,({)_L<i\L>i+mp!},!

Try it online!
Prints positive integer for truthy, zero for falsy.
-1 thanks to a clever trick by Peter Taylor.
-3 thanks to another tip by Peter Taylor.

0&! is shorter than 1+:*

@PeterTaylor Ooh that's clever...you abused the fact that ! returns a boolean and used set-intersection with the falsy value 0 so that you can do 0&! in 3 instead of 1&!!...

You can save a further 3 bytes by assigning the input to a variable, which simplifies the stack manipulations, and using the , filter operator instead of f.

PS I don't see any abuse in using ! to convert to a Boolean: that was standard in GolfScript and is standard in CJam. And 1&!! would be incorrect: 0&! is the obvious test because the requirement is forall, not exists.

@PeterTaylor That's not what I meant...:P

@PeterTaylor OK, implemented those changes...now it doesn't return a consistent truthy/falsy value, but still appropriate.

Actually what I had in mind was r:R,({)_R<i\R>i+mp!},! which does return a consistent truthy/falsy value (as required by the spec). Again: the requirement is forall, not exists. Your current code is buggy, giving 1 for input 121 because 12+1=13 is prime, even though 1+21=22 is not.

Let us continue this discussion in chat.

Pyth, 14 bytes
.AmP_ssMcQ]dtU

Try it online! Will display True if the number is magnanimous, False otherwise. Takes the number as a string.
Explanations
.AmP_ssMcQ]dtU

              Q    # Implicit input Q
            tU     # Generate the range [1, 2, ..., len(Q)-1]
  m                # For each index d in the above range...
        cQ]d       # Split Q at index d
      sM           # Convert the two parts to integers
     s             # Sum
   P_              # Check it is a prime
.A                 # ...end for. Check all elements are True

Japt, 24 16 bytes
This was pretty much a collaboration between @Shaggy, @ETHproduction, and myself.
¬£[YîU UtY]xÃÅej

Try it online!
Takes input as a string.

Gah! Almost identical to the alternative solution I was working on! Here's the 22 bytes I had it down to so far. EDIT: Got it down to 20 bytes by combining stuff from both.

@Shaggy Funny enough, I'm working on my edit right now...It's shockingly similar to yours: http://ethproductions.github.io/japt/?v=1.4.5&code=bCDGW1juVSBVdFhdrm7DeMNlag==&input=IjIwMDAyMjEi

Hint: x automatically converts the items in the array to numbers ;-)

Yup, that's where I'd go to too, @ETHproductions: 16 bytes.

Also, XîU is genius. I think U¯X works for the same length, but still

@ETHproductions Thanks for the tip!

@obarakon; I hate you for beating me to this! :p But have a +1 anyway :D

I wish £[YîU UtY] worked

@obarakon Prepend a ¬ and it will

£[°YîU UtY] will work, though ;)

Oh shoot, does x fail if one of the numbers starts with a 0?

@ETHproductions, it seemed to be working fine for the 2 numbers that my solution was failing on.

Hmm, then @obarakon why did you revert?

I think you're just missing a Å. ¬£[YîU UtY]xÃÅej works on all the test cases for me (test it online)

Pip, 25 24 bytes
$&0N_%,_=1M$+(a^@_)M1,#a

Try it online!
Explanation
a is the first command-line argument. 1,#a generates a Range containing numbers 1 through len(a)-1. To this, we map a lambda function:
$+(a^@_)
   a^@_   Split a at this index
$+(    )  Fold the resulting 2-element list on +

Next, we map another lambda function, 0N_%,_=1, that tests for primality. I took it from this answer; you can read the explanation there. Finally, we fold the list on logical AND ($&). The result is 1 iff all the sums were prime, 0 if any of them weren't.
Example, with input of 4063:
                    1,#a   [1; 2; 3]
           $+(a^@_)M       [67; 103; 409]
  0N_%,_=1M                [1; 1; 1]
$&                         1

Plain English 4,204 341 315 251 241 240 bytes
(Re-)incorporated primality testing into Plain English's library, by moving 3,863 bytes into Plain English's library.  Deleted 26 bytes of white space.  Saved 64 bytes by abbreviating local variables.  Saved 10 bytes by abbreviating the interface.  Per RosLuP's suggestion, saved 1 byte by changing how m is initialized and incremented.
To decide if a n number is g:
Put 1 in a m number.
Loop.
Multiply the m by 10.
If the m is greater than the n, say yes.
Divide the n by the m giving a q quotient and a r remainder.
Add the q to the r.
If the r is not prime, say no.
Repeat.

Ungolfed version of final code:
To decide if a number is magnanimous:
  Put 1 in another number.
  Loop.
    Multiply the other number by 10.
    If the other number is greater than the number, say yes.
    Divide the number by the other number giving a quotient and a remainder.
    Add the quotient to the remainder.
    If the remainder is not prime, say no.
  Repeat.

Notes:  The Plain English IDE is available at github.com/Folds/english.  The IDE runs on Windows.  It compiles to 32-bit x86 code.
The Osmosian Order's dynamic fork of Plain English already had primality testing in version 4700, but it used a very inefficient algorithm (as of January through June 2017).  Versions 4001-4011 of the GitHub site's dynamic fork omitted primality testing.  Version 4013 of the GitHub site's dynamic fork includes primality testing.  The code to perform the primality testing was developed as part of previous revisions of this answer.

Mathematica, 75 bytes
And@@Table[PrimeQ@ToExpression@StringInsert[#,"+",n],{n,2,StringLength@#}]&

Function which expects a String. PrimeQ@ToExpression@StringInsert[#,"+",n] returns whether inserting a + after the nth digit gives a prime number. Table[...,{n,2,StringLength@#}] gives the list of these values as n ranges from 2 to the length of the string. We then take And of each of the elements of that list. Conveniently, if StringLength@#<2, then Table[...] is the empty list, for which And@@{}==True

Mathematica, 55 50 45 49 50 54 62 bytes
It seems I should post it separately.
+6 bytes for code length remeasured.
+5 bytes thanks to ngenisis.
And@@(qPrimeQ[#~Mod~q+⌊#/q⌋])@Rest@PowerRange@#&

Takes input as an integer and return regular True and False. The  in-between is unicode 0xF4A1, short for Function[,]. Code length is measured on file size (UTF-8 without BOM), comment if it is not correct.
PowerRange[x] returns 1, 10, 100... no greater than x, which is introduced in Mathematica 10.

Perl 6, 58 bytes
{?(10,10* *...^*>$_).map({$_ div$^a+$_%$^a}).all.is-prime}

Try it online!
10, 10 * * ...^ * > $_ is the geometric sequence of multiples of ten, taken until one before the element that exceeds the input parameter $_.  Then we just check that for each power of ten, the sum of the input parameter taken div and mod that power is prime.

Haskell, 114 110 bytes
p x=[x]==[i|i<-[2..x],x`mod`i<1]
i!x|i<1=0<1|0<1=p(uncurry(+)$divMod x$10^i)&&(i-1)!x
f x=(length(show x)-1)!x

Ungolfed with explanation:
-- Check if x is a prime number
p x = [x] == [i | i<-[2..x], x`mod`i < 1]
-- Checks all pairs of numbers a '+' can be put in between
i ! x | i<1 = 0<1                                -- Single-digit numbers are always truthy
      | 0<1 = p (uncurry (+) $ divMod x $ 10^i)  -- Does x split at i digits from right sum up to a prime?
           && (i-1) ! x                          -- If so, check next pair
-- Start (!) with the number of digits in x minus one
f x = (length (show x)-1) ! x

If you use p x=[x]==[i|i<-[2..x],x\mod`i<1]` as your prime check you can save 2 bytes.

You can also use divMod x$10^i instead of x\divMod`(10^i)`

@WheatWizard: I knew the prime test could still be improved somehow. ;) Thanks!

Axiom, 88 bytes
f(n:PI):Boolean==(i:=10;repeat(q:=n quo i;q=0 or ~prime?(q+n rem i)=>break;i:=i*10);q=0)

test and results
(10) -> [[i,f(i)]  for i in [1,2,4,10,98,101,109,819,4063,40427,2000221,999999999999999999999999999999999999999999999]]
   (10)
   [[1,true], [2,true], [4,true], [10,false], [98,true], [101,true],
    [109,false], [819,false], [4063,true], [40427,true], [2000221,true],
    [999999999999999999999999999999999999999999999 ,false]]

Brachylog, 11 bytes
{~cĊℕᵐ+}ᶠṗᵐ

Try it online!
{      }ᶠ      Find every
      +        sum of
   Ċ           two
    ℕᵐ         whole numbers
 ~c            which concatenate to the input,
          ᵐ    and assert that all of them
         ṗ     are prime.

Perl 6, 35 bytes
{m:ex/^(.+)(.+)$/.all.sum.is-prime}

Try it online!
Explanation:
{                                 }     # Anonymous code block that
 m:ex/^        $/                         # Match all
       (.+)(.+)                           # Splits of the input number
                 .all                     # Are all of them
                     .sum                   # When summed
                         .is-prime          # Prime?

Husk, 13 bytes
Λȯṗṁd§e↑↓d¹ḣL

Try it online!
-1 byte from user.

14 bytes using combin. Using x might yield a shorter solution by removing that weird ohh ott part, but I haven't tried it yet

ah, this one was when I was a Husk beginner. I found a 13 byter.

Risky, 44 bytes
*0!?+0-_1+0___?+0+_1+0___?{?}_*+0+__?[?}_*+0_!\?+0+1111:!111111111+111111111111111111111

Try it online!
Takes input as an array of digits (which is allowed by default). Outputs 1 for true and 0 for false.

Vyxal 3 g, 10 bytes
ṗΩL2=]“⌊ṠṄ

Try it Online!

Stacked, 51 bytes
[tostr:#'1-~>splitat tr['+',' '#`#~prime]map 1,all]

Try it online!
This is a function. It works by converting its argument to a string (tostr), duplicating it and obtaining its length (:#'), subtracting 1 (1-), making a range from 1 to that number (~>). The stack looks something like this, for input 40427:
('40427' (1 2 3 4))

We perform vectorized splitat, resulting in the following array to be at the top of the stack:
(('4' '40' '404' '4042') ('0427' '427' '27' '7'))

Transposing this with tr, we get:
(('4' '0427') ('40' '427') ('404' '27') ('4042' '7'))

Then, we map the function ['+',' '##~prime](withmap`). This function does:
['+',' '#`#~prime]
 '+',                concatenate a plus sign (string)    `('4' '0427' '+')
     ' '#`           join by spaces                      `'4 0427 +'`
          #~         evaluate                            `431`
            prime    check primality                     `1`

Then, after the map, we concatenate 1. This is since all returns undef for an empty list.

JavaScript (ES6), 70 bytes
P=(n,x=2)=>n%x?P(n,x+1):n==x
f=(n,i=10)=>i>n||P((n/i|0)+n%i)&f(n,i*10)

Fails on the last case in my browser due to a "too much recursion" error while calculating P(200023). Hopefully this doesn't invalidate it.

QBIC, 38 bytes
_L;|[a-1|q=q*µ!_sA,b|!+!_sA,b+1,a|!}?q

Explanation
_L |     Create a variable a and set it to the length of
  ;      the input string (A$)
[a-1|    FOR b = 1 to a-1
q=q*     multiply q by
 µ       -1 if prime, 0 if not, of
  !        a cast of
   _s       a substring of
     A,       A$
     b        from index 1 to index b (only one index is given, so that is assumed to be the req. length from 1)
      |!   to number
 +         plus
 !         a cast of
  _s         a substring of
    A,         A$
    b+1        from index b+1
    ,a         for the length of a (does not error if it exceeds the end of the string)
      |!   to number
 }       NEXT
 ?q      PRINT q, which is eitrher -1 or 1 for all-prime sums, or 0 otherwise

Pyth, 15 14 bytes
.AmP_svcz]dtUz

Test suite
Saved a byte using Pyth's newest change.

CJam (21 bytes)
r:R,({RiA@)#md+mp!},!

Online demo, online test suite
Dissection
r:R       e# Take a token of input and assign it to R
,(        e# Take the length of R minus one
{         e# Filter i = 0 to (length of R minus two)
  Ri      e#   Push R as an integer value
  A@)#    e#   Push 10 to the power of (i + 1)
  md      e#   divmod
  +mp!    e#   Add, primality test, negate result
},        e# The result of the filter is a list of splits which give a non-prime
!         e# Negate result, giving 0 for false and 1 for true

APL(NARS), chars 35, bytes 70
{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k}

test:
  f←{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k}
  f¨1 2 4 10 98 101 109 819 4063 40427 2000221
1 1 1 0 1 1 0 0 1 1 1

This would be the translation in APL from Axiom post algo here...
{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k}
 0≥k←¯1+≢⍕⍵:1⋄  assign to k the length as array of argument return 1 if that is <=0
 ∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k
              m←10*⍳k  m is the array pow(10,1..k)
           ⌊⍵÷m       the array of quotient of argumet with m
          +           sum
     (m∣⍵)            with array of remander
   0π                 build the binary array of "are prime each"
 ∧/                   and that array

PHP, 100 bytes
for(;++$k<strlen($a=$argn);$x+=$i==1)for($i=$n=substr($a,$k)+$b.=$a[$k-1];--$i&&$n%$i;);echo$x+2>$k;

prints 1 if input is magnanimous, empty output if not. Run as pipe with -nR or try it online.

Perl 5 -p, 42 bytes
$\=1;s//map$\&&=($`+$')%$_,2..$`+$'-1/ge}{

Try it online!

source: Stack Exchange

license: 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/

sort: votes


text:
Are there N consecutive occurrences of a number in a row/column in a matrix?
Take a matrix A consisting positive integers, and a single positive integer N as input, and determine if there are at least N consecutive occurrences of the same number in any row or column in the matrix.
You need only test horizontally and vertically.
Test cases
N = 1
A =
1
Result: True
----------------
N = 3
A =
1 1 1
2 2 3
Result: True
----------------
N = 4
A =
1 1 1
2 2 3
Result: False
----------------
N = 3
A =
3 2 3 4 2 1
4 1 4 2 4 2
4 2 3 3 4 1
1 1 2 2 3 4
3 2 3 1 3 1
1 1 2 2 3 4
Result: True
----------------
N = 1
A =
5 2 3 8
Result: True
----------------
N = 3
111   23  12    6
111   53   2    5
112  555   5  222
Result: False
----------------
N = 2
 4  2  6  2  1  5
 2  3  3  3  3  3
11 34  4  2  9  7
Result: True

Explanations are always a good thing :)

You seem to love matrixes.

Well, I'm a MATLAB guy... Matrix Laboratory =)

Is it enough to return a truthy/falsy value?

@Dennis of course :)

Annoyingly, because you are a Matlab guy, you make challenges that seem easy in MATLAB but have a slight twist that rule out the obvious solution...

Jelly, 9 8 bytes
;ZjṡƓE€S

Takes the matrix as arguments and reads the integer from STDIN.
Try it online!
How it works
;ZjṡƓE€S  Main link. Argument: M (matrix / row array)

 Z        Zip/transpose M.
;         Concatenate the row array with the column array.
  j       Join the rows and columns, separating by M.
    Ɠ     Read an integer n from STDIN.
   ṡ      Split the result to the left into overlapping slices of length 2.
     E€   Test the members of each resulting array for equality.
       S  Take the sum.

Example run
;ZjṡƓE€S  Argument: [[1, 2], [3, 2]]. STDIN: 2

 Z        [[1, 3], [2, 2]]

;         [[1, 2], [3, 2], [1, 3], [2, 2]]

  j       [1, 2, [1, 2], [3, 2], 3, 2, [1, 2], [3, 2], 1, 3, [1, 2], [3, 2], 2, 2]

    Ɠ     2

   ṡ      [[1, 2],             [2, [1, 2]],        [[1, 2], [3, 2]],   [[3, 2], 3],
           [3, 2],             [2, [1, 2]],        [[1, 2], [3, 2]],   [[3, 2], 1],
           [1, 3],             [3, [1, 2]],        [[1, 2], [3, 2]],   [[3, 2], 2],
           [2, 2]                                                                 ]

     E€   [     0,                       0,                       0,             0,
                0,                       0,                       0,             0,
                0,                       0,                       0,             0,
                1                                                                 ]

       S  1

I had the same idea with ;Z, though in Japt rather than Jelly...

Now I see why you asked about truthy/falsy values. That definition in Jelly was inspired by MATLAB (or MATL) wasn't it?

No, Jelly uses Python's conditionals internally. The Ȧ atom was inspired by MATL though.

Oh well mine was way too long >.< Right, the E builtin was the way to do it. Nice :)

Husk, 9 bytes
≤▲mLṁgS+T

Takes a 2D array and a number, returns 0 for falsy instances and a positive number for truthy instances.
Try it online!
Explanation
Husk is a functional language, so the program is just a composition of several functions.
≤▲mLṁgS+T
        T  Transpose the array
      S+   and concatenate with original.
           We get a list of the rows and columns of the input array.
    ṁ      Map and concatenate
     g     grouping of equal consecutive elements.
           This gives all consecutive runs on rows and columns.
  mL       Map length over the runs,
 ▲         take the maximum of the results
≤          and see if it's at least the second input.

Dyalog APL, 27 25 23 bytes
{1∊∊⍷∘⍵¨(⊢,⍪¨)⍺/¨⍳⌈/∊⍵}

Try It Online!
Thanks to @MartinEnder and @Zgarb for -2 bytes each (composition removes the need to use w and pointless parens)
Alert me if there are any problems and/or bytes to golf. Left argument is N, right argument is A.
Explanation:
{1∊∊⍷∘⍵¨(⊢,⍪¨)⍺/¨⍳⌈/∊⍵}
                     ⍵    - Right argument
                    ∊     - Flatten the array
                 ⍳⌈/      - 1 ... the maximum (inclusive)
              ⍺/¨         - Repeat each item ⍺ (left argument) times.
        (⊢,⍪¨)            - Argument concatenated with their transposes.
    ⍷∘⍵¨                  - Do the patterns occur in ⍵?
   ∊                      - Flatten (since we have a vector of arrays)
 1∊                       - Is 1 a member?
{                     }   - Function brackets

MATL, 12 bytes
t!YdY'wg)>~a

Try it online! Or verify all test cases.
Explanation
A non-square matrix cannot be properly concatenated to its transpose, either vertically or horizontally. So the code concatenates them diagonally, by creating a block-diagonal matrix.
The resulting matrix is linearized in column-major order and run-length encoded. The zeros resulting from the block-diagonal concatenation serve to isolate the runs of actual values.
The results from run-length encoding are an array of values and an array of run-lengths. The run-lengths corresponding to non-zero values are kept. The output is 1 if some of those lengths is greater than or equal to the input number, and 0 otherwise.
Let's see the intermediate results to make it clearer. Consider inputs
[10 10 10;
 20 20 30]

and
3

The block diagonal matrix containing the input matrix and its transpose (code t!Yd) is:
10 10 10  0  0
20 20 30  0  0
 0  0  0 10 20
 0  0  0 10 20
 0  0  0 10 30

This matrix is implicit linearized in column-major order (down, then across):
10 20  0  0  0 10 20  0  0  0 10 30  0  0  0  0  0 10 10 10  0  0 20 20 30

Run-length encoding (code Y') gives the following two vectors (shown here as row vectors; actually they are column vectors): vector with values
10 20  0 10 20  0 10 30  0 10  0 20 30

and vector with run lengths
1 1 3 1 1 3 1 1 5 3 2 2 1

Keeping only the lengths correspoinding to non-zero values (code wg)) gives
1 1 1 1 1 1 3 2 1

Comparing to see which lengths are greater than or equal to the input number (code >~) produces the vector
0 0 0 0 0 0 1 0 0

Finally, the output should be true (shown as 1) if the above vector contains at least a true entry (code a). In this case the result is
1

Octave, 77 70 bytes
@(A,N)any(([x y]=runlength([(p=padarray(A,[1 1]))(:);p'(:)]))(!!y)>=N)

Try it online!
Explanation:
Since tha matrix only contains non-zero integers we can add a border of 0s around the matrix and compute runlength encoding of the matrix(reshaped to a vector)
@(A,N)any(([x y]=runlength([(p=padarray(A,[1 1]))(:);p'(:)]))(!!y)>=N)
                             p=padarray(A,[1 1])                        % add a border of 0s around the matrix
                            (                   )(:)                    % reshape the matrix to a column vector
                                                     p'(:)              % transpose of the matrix reshaped to a column vector
                           [                        ;     ]             % concatenate two vectors vertically
           [x y]=runlength(                                )            % runlength encoding of the vector[x=count,y=value]
          (                                                 )           % take x,counts.
                                                             (!!y)      % extrect those counts that their valuse aren't 0
      any(                                                        >=N)  % if we have at least a count that is greater than or equal to N

I really like your solutions (not only this one), but they could definitely benefit from some explanations! :) I didn't know Octave had runlength... Learn something new everyday...

Thanks for reminding me about runlength! Being more focused on Matlab, I didn't remember that existed in Octave

@StewieGriffin Thanks, answer updated after waking up!

@LuisMendo After one of your posts I became aware of a function named runlength.

Perl 6, 60 bytes
{(@^m|[Z,] @^m).map(*.rotor($^n=>$^n-1).map({[==] $_}).any)}

Try it online!

@^m is the input matrix (first argument) and $^n is the number of consecutive occurrences to check for (second argument).
[Z,] @^m is the transpose of the input matrix.
(@^m | [Z,] @^m) is an or-junction of the input matrix and its transpose.  The following map evaluates to a truthy value if $^n consecutive equal values occur in any row of the invocant.  Applied to the input matrix OR its transpose, it evaluates to a truthy value if either the input matrix or its transpose contain $^n consecutive equal values in any row; if the transpose meets that condition, that means the input matrix has $^n consecutive equal values in one of its columns.
*.rotor($^n => $^n - 1) turns each row into a sequence of $^n-element slices.  For example, if $^n is 3 and a row is <1 2 2 2 3>, this evaluates to (<1 2 2>, <2 2 2>, <2 2 3>).
.map({ [==] $_ }) turns each slice into a boolean that indicates whether all elements of the slice are equal.  Continuing the previous example, this becomes (False, True, False).
.any turns that sequence of booleans into an or-junction which is truthy if any of the booleans are true.

The output is a truthy or-junction value which is true if either the input matrix OR its transpose have ANY row where $^n consecutive values are equal.

Python 3, 129 128 125 120 104 101 bytes
Huge thanks to @Zachary T, @Stewie Griffin, @Mr. Xcoder, @Rod, @totallyhuman for improving this by a lot.
def f(n,m):
 a=b=c=0;m+=zip(*m)
 for r in m:
  for i in r:b,a=[1,b+1][a==i],i;c=max(c,b)
 return n<=c

Try it online!

You don't need a space between 1 and if.

Save four bytes by replacing a=b;b=0;c=0 with a=b=c=0

(I'm not sure) but I think that you could use m+zip(*m) instead mon the 4th line, and drop entirely the 1st line, moving the n<=max() to the last line as n<=c

120 bytes

Instead of b=b+1 use b+=1... Ahh, Ninja'd by @StewieGriffin

You also don't need the space between else and 1

Japt, 18 15 14 bytes
cUy)d_ò¦ d_Ê¨V

Test it

3 bytes saved with some help from ETHproductions.

Explanation
    :Implicit input of 2D array U and integer V
c   :Append to U...
Uy  :U transposed.
d   :Check if any of the elements (sub-arrays) in U return true when...
_   :Passed through a function that...
ò   :Partitions the current element by...
¦   :Checking for inequality.
d   :Check if any of the partitions return true when...
_   :Passed through a function that checks if...
Ê   :The length of the current element...
¨V  :Is greater than or equal to V.
    :Implicit output of resulting boolean.

Oh wow, I didn't see this before posting mine. You could save 2 bytes with cUy)®ò¦ d_l ¨V\nd, and another with cUy)d_ò¦ d_l ¨V, and then you practically have my (deleted) solution.

Ha-Ha; great minds ..., @ETHproductions :) I'm shocked I was fastest finger after obarakon beating me all day today! Thanks for those tips, had spotted one already but not the other yet.

Python 2, 60 92 91 bytes
def f(n,x):x=[map(str,i)for i in x];print any(`[i]*n`[1:-1]in`x+zip(*x)`for i in sum(x,[]))

Try it online!
Instead of counting, a list with size n (for each element in the matrix) is generated and checked if it's on the matrix
Without strings, 94 bytes
lambda n,x:any((e,)*n==l[i:i+n]for l in x+zip(*x)for i in range(len(l)-n+1)for e in sum(x,()))

Try it online!

I think this can give false positives with multidigit numbers.

@xnor there, fixed

Octave, 59 bytes
@(A,N)any({[l,v]=runlength(blkdiag(A,A')(:)),l(v>=0)}{2}>=N)

Try it online! Or verify all test cases.
This uses the same approach as my MATL answer (see explanation there).

blkdiag(A,A'). Very nice!

CJam, 16 bytes
q~_z+N*e`:e>0=>!

Try it online!
Explanation
q~    e# Read and eval input.
_z+   e# Append the matrix's transpose to itself.
N*    e# Join with linefeeds to flatten without causing runs across rows.
e`    e# Run-length encode.
:e>   e# Get maximum run (primarily sorted by length).
0=    e# Get its length.
>!    e# Check that it's not greater than the required maximum.

I always wondered why  CJam's RLE gives run-length, then value. Well, it turns out to be useful here :-)

@LuisMendo I guess because that's the way you'd say it "3 a's, 5 b's, 2 c's". I actually find this order useful quite often.

Actually, Octave's runlength function gives outputs in that order too. But somehow I feel the order value, length more natural

05AB1E, 16 14 12 bytes
Døìvyγ€gM²‹_

Try it online!
Dø           # Duplicate the input and transpose one copy
  ì          # Combine the rows of both matrixes into one array
   vy        #   For each row...
     γ       #     Break into chunks of the same element
      €g     #     get the length of each chunk
        M    #     Get the largest length so far
         ²‹_ #     Check if that is equal to or longer than required

@MagicOctopusUrn I'm not sure what you mean. That example has 3 consecutive 0s in the second row, so it should be true.

@MagicOctopusUrn If you break up that run (TIO) it returns false.

Doesn't the third command concatenate the transposed rows to the original rows?

Also, I thought it was supposed to only return true for 3 when there is [3,3,3]. I misread the challenge in that case, so I think I'm wrong here.

@MagicOctopusUrn The first 3 commands will create an array that contains each row and each column as individual elements.

Ahhh, I misunderstood which command it was too; wow, I apologize. I thought that was direct prepend.

@MagicOctopusUrn I thought so too, but I guess it prepends each element instead of the whole array.

Jelly, 18 bytes
ŒrFUm2<⁴$ÐḟL
ZÇo³Ç

Try it online!
ŒrFUm2<⁴$ÐḟL  Helper Link
Œr            Run-length encode
  F           Flatten the whole thing, giving the numbers in the odd indices and the lengths of the runs in the even indices
   U          Reverse
    m2        Take every other element (thus only keeping the run lengths)
         Ðḟ   Discard the elements that are
      <⁴$                                   less than the required run length
           L  And find the length
ZÇo³Ç         Main Link
Z             Zip the matrix
 Ç            Call the helper link on it
   ³Ç         Call the helper link on the original matrix
  o           Are either of these truthy?

Returns 0 for false and a non-zero integer for truthy.
Ew, this is bad. And very long. Golfing tips would be appreciated :)

JavaScript (ES6), 99 bytes
Takes the matrix m and the expected number of occurrences n in currying syntax (m)(n). Returns a boolean.
m=>n=>[',',`(.\\d+?){${m[0].length-1}}.`].some(s=>m.join`|`.match(`(\\b\\d+)(${s}\\1){${n-1}}\\b`))

How?
This code is not particularly short, but I wanted to try an approach purely based on regular expressions.
Conversion of the matrix to a string
We use m.join('|') to transform the 2D-array into a string. This first causes an implicit coercion of the matrix rows to comma-separated strings.
For instance, this input:
[
  [ 1, 2, 3 ],
  [ 4, 5, 6 ]
]

will be transformed into:
"1,2,3|4,5,6"

Row matching
We look for consecutive occurrences in a row with:
/(\b\d+)(,\1){n-1}\b/

This is matching:

\b a word boundary
\d+ followed by a number
(){n-1} followed n-1 times by:

, a comma
\1 followed by our reference: a word boundary + the first number

\b followed by a word boundary

Column matching
We look for consecutive occurrences in a column with:
/(\b\d+)((.\d+?){L-1}.\1){n-1}\b/

where L is the length of a row.
This is matching:

\b a word boundary
\d+ followed by a number
(){n-1} followed n-1 times by:

(){L-1} L-1 times:

. any character (in effect: either a comma or a pipe)
\d+? followed by a number (this one must be non-greedy)

. followed by any character (again: either a comma or a pipe)
\1 followed by our reference: a word boundary + the first number

\b followed by a word boundary

Test cases

let f=

m=>n=>[',',`(.\\d+?){${m[0].length-1}}.`].some(s=>m.join`|`.match(`(\\b\\d+)(${s}\\1){${n-1}}\\b`))

console.log(f([
  [ 1 ]
])(1))

console.log(f([
  [ 1, 1, 1 ],
  [ 2, 2, 3 ]
])(3))

console.log(f([
  [ 1, 1, 1 ],
  [ 2, 2, 3 ]
])(4))

console.log(f([
  [ 3, 2, 3, 4, 2, 1 ],
  [ 4, 1, 4, 2, 4, 2 ],
  [ 4, 2, 3, 3, 4, 1 ],
  [ 1, 1, 2, 2, 3, 4 ],
  [ 3, 2, 3, 1, 3, 1 ],
  [ 1, 1, 2, 2, 3, 4 ]
])(3))

console.log(f([
  [ 5, 2, 3, 8 ]
])(1))

console.log(f([
  [ 111,  23,  12,   6 ],
  [ 111,  53,   2,   5 ],
  [ 112, 555,   5, 222 ]
])(3))

console.log(f([
  [  4,  2,  6,  2,  1,  5 ],
  [  2,  3,  3,  3,  3,  3 ],
  [ 11, 34,  4,  2,  9,  7 ]
])(2))

Octave, 58 bytes
f=@(A)runlength([A;nan*A](:))
F=@(A,n)max([f(A),f(A')])>=n

Try it online!

BQN, 21 bytes
-⊸≢1=⊣≠∘⍷˘∘↕˘⎊0¨⋈⟜⍉∘⊢

Anonymous tacit function; takes the number n as left argument and the 2D array a as right argument. Try it at BQN online!
Explanation
So. Many. Modifiers. ○_○
-⊸≢1=⊣≠∘⍷˘∘↕˘⎊0¨⋈⟜⍉∘⊢
                      ∘⊢  With the right argument (a),
                 ⋈⟜⍉     pair it with its transpose
                ¨         Apply this function to each of those arrays
     ⊣                    and the original left argument (n):
             ˘              Within each row of the array,
            ↕               get all sublists of length n
          ˘∘                Then, with each of those sublists,
       ≠∘⍷                  uniquify and get the length (1 iff all elements are equal)
              ⎊0           If that function errored because n is too big, use 0 instead
                          We now have a list of two elements, each of which is either
                          an array of integers or a 0
   1=                     Compare each integer to 1 (0 if not equal, 1 if equal)
 ⊸≢                      Is that nested list different from
-                         the same list with each integer negated?

If there are no sublists where all items are identical, we'll get a nested list containing only zeros, which remains the same under negation; thus, ≢ will return 0. If there is at least one sublist with identical items, we'll get a nested list that contains a 1 somewhere, which changes under negation; thus, ≢ will return 1.

Vyxal, 9 bytes
:∩JvøĖ≤fa

Try it Online!

Python 2, 64 bytes
lambda M,n:(', 0'*n)[5:]in`[map(cmp,l,l[1:])for l in M+zip(*M)]`

Try it online!

Clojure, 77 bytes
#((set(for[I[%(apply map vector %)]i I p(partition %2 1 i)](count(set p))))1)

Creates all consecutive partitions p of length N (symbol %2) and counts how many distinct values it has. Then it forms the set of these lengths and returns 1 if it is found from the set and nil otherwise. for construct was the perfect fit for this, my original attempt used flatten, concat or something of that short.

Julia, 90,84 70 bytes
A\n=(~X=occursin("0"^(n-1),[X;0X[1,:]'][:]|>diff.|>sign|>join);~A|~A')
(A>0 is exploited.)
Attempt This Online!
and a StatsBase-based vari:
16+54 bytes
using StatsBase
A\n=(~X=any(eachrow(X).|>x->any(rle(x)[2].≥n));~A|~A')

05AB1E, 8 bytes
Dø«δÅγ›ß

First input is the matrix \$A\$, second is the integer \$N\$.
Outputs an inverted boolean: 0 for truthy and 1 for falsey.
Try it online or verify all test cases.
Explanation:
D         # Duplicate the (implicit) input-matrix
 ø        # Zip/transpose its copy; swapping rows/columns
  «       # Merge it to the input-matrix
          # (we now have a list of all rows and all columns)
          #  e.g. input=[[1,1,1],[2,2,3]] → [[1,1,1],[2,2,3],[1,2],[1,2],[1,3]]
   δ      # Map† over each inner list:
    Åγ    #  Run-length encode it; pushing the list of items and list of lengths
          #  separately to the stack, only leaving the top list of lengths
          #   → [[3],[2,1],[1,1],[1,1],[1,1]]
       ›  # Check for each inner-most length if it's smaller than the second (implicit)
          # input-integer
        ß # Pop and push the flattened minimum to check if any was falsey
          # (after which the result is output implicitly)

† δ is technically an 'apply double-vectorized', which also uses the second (implicit) input-integer as argument. It's usually used to create tables from two lists, or to apply a builtin that takes a single argument on each inner item of a list.
In this case, the implicit input-integer is simply ignored since builtin Åγ takes no arguments, and δ therefore acts as a map. We use this, because map εÅγ} is 1 byte longer and map €Åγ would also keep the lists of items (so the example above would become [[3],[1],[2,1],[2,3],[1,1],[1,2],[1,1],[1,2],[1,1],[1,3]] instead).

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


text:
Generate a US License Plate
Given one of the following as input:
AK,AR,AS,AZ,CA,CT,DC,FL,GA,IL,IN,IA,KS,KY,LA,MD,MI,MN,MS,NV,NH,NJ,NM,NY,NC,ND,MP,OH,OK,OR,PA,PR,RI,SC,TN,TX,UT,VT,VA,WA,WI

(with quotes)
"AK","AR","AS","AZ","CA","CT","DC","FL","GA","IL","IN","IA","KS","KY","LA","MD","MI","MN","MS","NV","NH","NJ","NM","NY","NC","ND","MP","OH","OK","OR","PA","PR","RI","SC","TN","TX","UT","VT","VA","WA","WI"

Generate and output a (uniformly) random license plate of the format matching the input. If there are multiple (comma separated) formats, use a (uniformly) random format:
AK, IA, MS, MP, VT: AAA 000
AS: 0000
AZ, GA, WA: AAA0000
AR, KS, KY, LA, ND, OR: 000 AAA
CA: 0AAA000
CT: AA-00000
DC: AA-0000
FL: AAA A00
IL: AA 00000
IN: 000A,000AA,000AAA,AAA000
MD: 0AA0000
MI: AAA 0000,0AA A00,AAA 000
MN: 000-AAA
NV: 00A-000
NH: 000 0000
NJ: A00-AAA
NM: 000-AAA,AAA-000
NY, NC, PA, TX, VA, WI: AAA-0000
OH: AAA 0000
OK: 000AAA
PR: AAA-000
RI: 000-000
SC: AAA 000,000 0AA
TN: A00-00A
UT: A00 0AA

Where A means a random character in the uppercase alphabet minus IOQ and 0 means a random single digit number (0 to 9).
All information from Wikipedia. These (states) were all of the ones that I understood and that didn't have wonky rules.
This is code-golf, so shortest answer in bytes wins!

Sandbox; Related, but has several important differences, especially in license format and output specifics, not to mention that it is tagged [tag:popularity-contest]

Wow, so THAT'S how they decide that... Interesting.

@MagicOctopusUrn if you look at the Wikipedia article, it's quite interesting; I haven't implemented nearly all of what you would have to. Some have different stuff about what characters can be adjacent, about ending/beginning chars if your inspection date or county is x y or z, etc. It's crazy. Plus each state changes the pattern every ten years or so.

I've always wondered what's up with LP numbers ever since I got pulled over when I got new plates. They said it was because the plates on my car had a number similar to that of a stolen vehicle.

@MagicOctopusUrn heh, about that, different states with the same format don't keep tabs on each other, so they can both issue the same number, and cops would have to look to see what state the plate is from

The size number space for each state varies.  Do we 1) consider the combined number space for all states and uniformly pick from that (which will more heavily weight states with larger number spaces)?  Or do we 2) first uniformly pick one of the 50 states and then uniformly pick a number from that state's number space (which will weight all states equally)?

@DigitalTrauma you uniformly use one of the formats to the right of the state name in the third code block. For example, for input SC, you should randomly generate either AAA 000 or 000 0AA. Is that (match input to format in list) unclear in my post? You're not randomly selecting a state, that's the input. You're randomly selecting which format to use, and which characters to include.

Oh sorry I didn't read it properly. State is input.

Ok, similar question for states that have multiple formats, e.g. IN.  Do we uniformly pick a format (one of 000A, 000AA, 000AAA or AAA000), then pick a number from that format (each format weighted equally).  Or do we consider the number space for all formats for that state and pick from that entire number space (larger formats weighted greater)?

@DigitalTrauma first option (pick out of number of options of plates, not number of options of permutations), although in hindsight the second option might have been interesting

I think you left out "AR" and "OR" from the list of inputs, even though you describe their plate formats below.

@Notatree We were recently trained to remove "OR" from our state lists. ;-) As for "AR", I'm clueless...

@Notatree oops, thanks. It was late when I made this.

@DLosc Sorry, a large block of states either don't have their exact license specs on Wikipedia, or have really weird rules based on inspection month or county or origin, that would make this challenge too complicated :P

There is a quotation mark missing in the list of inputs after AR.

I had a standard A00AA Michigan plate not too long ago. Weird that Wikipedia doesn't list it.

Perl 6, 492 350 bytes
{$_=('AKIAMSMPVT:7 3AS:4AZGAWA:74ARKSKYLANDOR:3 7CA:173CT:6-5DC:6-4FL:7 52IL:6 5IN:35,36,37,73MD:164MI:7 4,16 52,7 3MN:3-7NV:25-3NH:3 4NJ:52-7NM:3-7,7-3NYNCPATXVAWI:7-4OH:7 4OK:37PR:7-3RI:3-3SC:7 3,3 16TN:52-25UT:52 16'~~/$^a
[..]*?\:(<[\d]+[-\ ]>+)+%\,/)[0].pick;s:g/<[567]>/{[~]
(('A'..'Z')∖<I O Q>).pick xx($/-4)}/;S:g/\d/{[~] (^10).pick xx$/}/}

Try it online!
I was so far ahead after my first attempt, I didn't make much of an effort to pare the code down.  Now I have.
In my encoding of the license plate patterns, the numbers 1-4 indicate a run of that many random digits, and the numbers 5-7 indicate of run of random permitted letters, of length four less than the number.

Do you handle the spaces?

Ah, no indeed, I removed spaces from the rest of the text too enthusiastically before.  I've put back the spaces for twelve extra bytes.

Python3, 861 821 819 714 678 674 670 662 661 658 596 591 561 555 551 536 bytes.
-8 bytes thanks to @DestructibleLemon (b=a+... and d=B...), -15 bytes thanks to @Felipe Nardi Batista (useless lambda and variable)
And thanks to everyone over in chat who helped golf this!
from random import*
C=choice
Z='000'
A='AAA'
B=A+'-0'+Z
a=A+' '+Z
b=A+'0'+Z
c=a[::-1]
d=B[1:]
print(C(''.join(C(['ABCDEFGHJKLMNPRSTUVWXYZ','0123456789',i]['A0'.find(i)])for i in([a]*5+[Z+'0',b,b,b]+[c]*6+['0'+A+Z,d,d+'0',A+' A00','AA 00'+Z,Z+'A,000AA,000AAA,'+A+Z,'0AA0'+Z,a+'0,0AA A00,'+a,Z+'-'+A,'00A-'+A,Z+' 0'+Z,'A00-'+A,Z+'-AAA,AAA-'+Z]+[B]*6+[a+'0',Z+A,B[:-1],Z+'-'+Z,a+','+c,'A00-00A','A00 0AA'])[[*zip('AIMMVAAGWAKKLNOCDCFIIMMMNNNNNNPTVWOOPRSTU','KASPTSZAARSYADRACTLLNDINVHJMYCAXAIHKRICNT')].index(tuple(input()))]).split(',')))

Try it online
Any golfing suggestions are welcome (and wanted). And, please, if you spot any errors, just tell me via the comments!

Is there any way to set an item in a python list to the previous item, or another item in the list? Like, set IA to list[0] or something like that ( I don't know python )

No. It's a dictionary, and I didn't assign a name to the dictionary, so there's no way to reference it.

couldn't b assignment be b= a+"0"? d could be =B[1:]?

b can't be a+'0', as I screwed up the license plates.

561 down to 541 bytes by removing the lambda and adding repetition to lists

Thanks, I already got the repetition, and the variable s was unneeded entirely.

@ZacharyT as was the lambda function :P

JavaScript (ES6), 374 368 bytes
s=>(P=n=>parseInt(n,36),R=Math.random,g=F=>F?(' -'+(R()*10|0)+'ABCDEFGHJKLMNPRSTUVWXYZ'[R()*23|0])[F&3]+g(F>>2):'')(P('8cf,4q,8fz,ch6,8hq,xpb,8f3,8jj,xov,6i|ru|356|24f,8fy,xmn|8ji|8cf,ciy,8e2,xm2,ciz,ciy|8e7,xof,xmn,356,8e7,8dm,8cf|ca2,bjf,ca3'.split`,`[P('1k3600d2mha35h7bi00jc000o03000000809l002003n0h3032e0fh4g0h'[P(s)%159%131%70%58])].split`|`.sort(_=>R()-.5)[0]))

Formatted and commented
In the following code, data sections have been truncated. Missing parts are marked with (...).
s => (                                  // given the state s
  P = n => parseInt(n, 36),             // P = base-36 parsing function
  R = Math.random,                      // R = random generator
  g = F =>                              // g = recursive function taking an encoded format F
    F ?                                 // if the format has not been yet fully processed:
      (                                 //   build a string consisting of:
        ' -' +                          //     0: space, 1: hyphen
        (R() * 10 | 0) +                //     2: a random digit
        'ABCD(...)YZ'[R() * 23 | 0]     //     3: a random uppercase letter (minus I, O, Q)
      )[F & 3] +                        //   pick the next character from this string
      g(F >> 2)                         //   recursive call, dropping the 2 consumed bits
    :                                   // else:
      ''                                //   stop recursion
  )(                                    // initial call to g():
    P(                                  //   base-36 decoding of a format picked from
      '8cf,4q,(...),ca3'.split`,`[      //     a list of binary encoded formats
        P(                              //       accessed through a base-36 decoded index
          '1k36(...)0h'[                //         picked from a lookup-table of 58 entries
            P(s) % 159 % 131 % 70 % 58  //           based on a hash of the state
          ]                             //         end of lookup-table access
        )                               //       end of lookup-table index decoding
      ].split`|`                        //     end of list access / split it on '|'
      .sort(_ => R() - .5)[0]           //     randomly pick a format from this list
    )                                   //   end of format decoding
  )                                     // end of call

Demo

let f =

s=>(P=n=>parseInt(n,36),R=Math.random,g=F=>F?(' -'+(R()*10|0)+'ABCDEFGHJKLMNPRSTUVWXYZ'[R()*23|0])[F&3]+g(F>>2):'')(P('8cf,4q,8fz,ch6,8hq,xpb,8f3,8jj,xov,6i|ru|356|24f,8fy,xmn|8ji|8cf,ciy,8e2,xm2,ciz,ciy|8e7,xof,xmn,356,8e7,8dm,8cf|ca2,bjf,ca3'.split`,`[P('1k3600d2mha35h7bi00jc000o03000000809l002003n0h3032e0fh4g0h'[P(s)%159%131%70%58])].split`|`.sort(_=>R()-.5)[0]))

;[
  'AK','AR','AS','AZ','CA','CT','DC','FL','GA','IL','IN','IA','KS','KY',
  'LA','MD','MI','MN','MS','NV','NH','NJ','NM','NY','NC','ND','MP','OH',
  'OK','OR','PA','PR','RI','SC','TN','TX','UT','VT','VA','WA','WI'
]
.forEach(s => console.log(s + ' --> ' + f(s)))

T-SQL, 1104 1100 797 657 bytes
DECLARE @ CHAR(8)SELECT @=STUFF(value,1,2,'')FROM STRING_SPLIT(CAST(DECOMPRESS(CAST('H4sIAAAAAAAEAEWPUQ6DMAiGr2JCwlM9BKnZ7LTV2E7n7n+QlRbYC3yl8PNDCyIOAOACKcVstCudRYkytPSthUZPUrqM6KhxqC+3ZKNbaSWlNCltNuEJuozzdekITXDygu6xshNkx2u3xJhqREmWGUQqTiDWYpBLGEGkrOgij47N21k1eKdLM3trI+mF+h2tMSJK441qM3nDnQzLx/D8V69guM3mblvkiP1Q/SPwTqbs1XD2zVztKwnbL7p3wV77AcxSbMHfAQAA'as XML).value('.','varbinary(max)'))AS varchar(max)),','),t WHERE s=LEFT(value,2)ORDER BY NEWID()WHILE CHARINDEX('&',@)>0SET @=STUFF(@,CHARINDEX('&',@),1,SUBSTRING('ABCDEFGHJKLMNPRSTUVWXYZ',CAST(1+23*RAND()AS INT),1))WHILE CHARINDEX('#',@)>0SET @=STUFF(@,CHARINDEX('#',@),1,CAST(10*RAND()AS INT))PRINT @

EDIT 1: Saved over 300 bytes by changing VALUES() to STRING_SPLIT() (only available in SQL 2016 and later)
EDIT 2: Saved another 140 bytes by using GZIP compression as described here. We've already restricted ourselves to SQL 2016 and later, so these functions are available.
Input is via pre-existing table t with the State code in column s, per our IO standards.
After expanding the compressed string, here's the formatted code, with the super long list of states snipped:
DECLARE @ CHAR(8)
SELECT @=STUFF(value,1,2,'')
FROM STRING_SPLIT('AK&&& ###,IA&&& ###,MS&&& ###,...
                         (long string continues)
                   ...,SC### #&&,TN&##-##&,UT&## #&&',','),t
WHERE s=LEFT(value,2)ORDER BY NEWID()

WHILE CHARINDEX('&',@)>0
    SET @=STUFF(@,CHARINDEX('&',@),1,
        SUBSTRING('ABCDEFGHJKLMNPRSTUVWXYZ',CAST(1+23*RAND()AS INT),1))

WHILE CHARINDEX('#',@)>0
    SET @=STUFF(@,CHARINDEX('#',@),1,
        CAST(10*RAND()AS INT))

PRINT @

So I created a huge in-memory table consisting of all the possible pairs of (state, pattern). Note that I'm not combining rows, each state is separate, and states like IN will have 4 rows, one for each pattern.
When I join that in-memory table to the input table, I sort by NEWID(), which randomizes the order and returns a random matching pattern to the variable @.
I then just replace each & with a random letter, and each # with a random digit and return the result.

><>, 967 860 851 bytes
</b:++d**d85-*i9*i2
v\+?\"00A AAA"
 /5:/
v\+?\"00000 AA"
 /4:/\
v\+?\x"000-AAA"
 /f:/
v\+?\>"AAA-000"
 /1:/
v\+ ?\"A00-00A"
v/cb:/\/"A000"
v\++?\xx"AA000"
v/88:/\x"000AAA"
v\+-?\ >"AAA000"
 /2f:/v\
v\*-?\xx"0000 AAA"
v/8c:/\x"00A AA0"
v\*-?\x>"000 AAA"
v/7c:/\"AA0 000"
v\*+?\"0000"
 /6b:/
v\*-?\"0000-AA"
 /5f:/
v\*-?\"0000AA0"
 /bc:/
v\+-?\"AAA-00A"
 /59:/
v\*+?\"000-AAA"
 /4a:/
v\*- ?\"000-000"
 /*a8:/
v\2+-?\"000AAA0"
 /*a8:/
v\9++?\"00000-AA"
 /*a8:/
v\5++?\"000-A00"
 /*a4:/
v\1+-?\"0000 000"
 /*a4:/
v\3+-?\"0000 AAA"
 /*a5:/
v\3++?\"AA0 00A"
 :63*+\:9a*4+-:aa*6++:73*+
 /*+9:/
v\***?\"000 AAA"
 8*-*$\::9a*-:4
 /7*ae/
v\++*?\"0000AAA"
 :4a*3\:aa*-:cb++:ca*4++:a7++:b+
v/**++/"0000-AAA"
v\***?/"AAA 000"
<ov?="A":v?="0":;?=1l
~!/0\v[0<
 l<1x/?=]!5
 +*2_/?= 1l
 -8::/*(~!*d2$**-2:-6:
^    >?!^"A"+o]
]~</0\v[0<
 l <1x/?=4
 + *2_<v?=1l
^n^?)9:<

Try it online, or watch it at the fish playground!
This code has two parts: matching the state to the pattern, then replacing the pattern with the random characters. Neither of these things is easy in ><>.
First of all, we read in two characters, and compute 2 c1 - 9 c2 + 533, where c1 and c2 are the two character codes. The 2 and the 9 were chosen so that the formula gives each state a unique value, and the offset of 533 was chosen to maximise the number of these values that can be made using only 3 ><> instructions — it ended up being 28 out of 41 of them. We then send the fish zig-zagging down through the code until it finds the right value, at which point it escapes the zig-zag, reads the appropriate pattern and enters the fast stream in the leftmost column down to Part 2. Some of the states, particularly the ones with a choice of multiple patterns, needed some special consideration, but I managed to reuse some pieces of the code to save a few bytes.
Next, aka Part 2, we have to replace the "A"s and "0"s with random letters and numbers respectively. The only random command in ><> is x, which sets the fish's direction randomly out of up, down, left and right — not conducive to choosing something uniformly out of 10 digits or 23 letters. Let's look at the numbers bit to see how the fish does it:
]~</0\v[0<
 l <1x<v?=4
 l 1=_?\2*+
^n^?)9:<

The fish enters from the top right. The fish sets up an empty stack — 0[ — then randomly pushes 1 or 0 with equal probability until the stack has length 4:
   /0\v
 l <1x<v?=4
     _

It then combines the four 1s and 0s together as if they were binary digits — l1=?\2*+ — giving a number from 0 to 15. If the result is greater than 9, it discards all the work it just did and tries again; otherwise, it prints the number and continues:
]~<   v[0<
     x<

^n^?)9:<

Making the random letters is much the same, except we also check that the result isn't "I", "O" or "Q" with ::8-:6-:2-**.

Mathematica, 635 507 470 bytes
p=RandomChoice;a_±b_:=a<>b;r=""±Characters@"ABCDEFGHJKLMNPRSTUVWXYZ"~p~#&;j=""±ToString/@0~Range~9~p~#&;m=r@3;o=j@3;x=r@2;u=j@2;z=r@1;t=j@1;k=z±u±"-";w=m±" ";AS=y=j@4;AZ=GA=WA=m±y;CT=x±"-"±j@5;DC=x±"-"±y;FL=w±z±u;IL=x±" "±j@5;IN=p@{o±z,o±x,OK=o±m,s=m±o};CA=t±s;MD=t±x±y;MI=p@{OH=w±y,t±x±" "±z±u,AK=IA=MS=MP=VT=w±o};NV=u±z±"-"±o;NH=o±" "±y;NM=p@{MN=o±"-"±m,PR=m±"-"±o};NY=NC=PA=TX=VA=WI=m±"-"±y;RI=o±"-"±j@3;SC=p@{AR=KS=KY=LA=ND=OR=o±" "±m,VT};NJ=k±m;TN=k±u±z;UT=k±t±x;#&

-165 bytes from @JungHwanMin
input form

[NV]

I didn't use Alphabet[] because we have to exclude 3 letters (IOQ)

Whoops, my last one didn't work. Working version: 507 bytes: https://pastebin.com/4YkkkQrC

470 bytes (CP-1252) by using \[PlusMinus]: https://pastebin.com/cGHvSJRi

PHP (Phar), 495 bytes
The binary Phar file can be downloaded here and can be run with php uslic.phar <state code>.
The base code used to generate the Phar is as follows (820 bytes):
<?$f=[AK=>'AAA 111',IA=>'AAA 111',MS=>'AAA 111',MP=>'AAA 111',VT=>'AAA 111','AS'=>'1111',AZ=>'AAA1111',GA=>'AAA1111',WA=>AAA1111,AR=>'111 AAA',KS=>'111 AAA',KY=>'111 AAA',LA=>'111 AAA',ND=>'111 AAA','OR'=>'111 AAA',CA=>'1AAA111',CT=>'AA-11111',DC=>'AA-1111',FL=>'AAA A11',IL=>'AA 11111',IN=>'111AX111AAX111AAAXAAA111',MD=>'1AA1111',MI=>'AAA 1111X1AA A11XAAA 111',MN=>'111-AAA',NV=>'11A-111',NH=>'111 1111',NJ=>'A11-AAA',NM=>'111-AAAXAAA-111',NY=>'AAA-1111',NC=>'AAA-1111',PA=>'AAA-1111',TX=>'AAA-1111',VA=>'AAA-1111',WI=>'AAA-1111',OH=>'AAA 1111',OK=>'111AAA',PR=>'AAA-111',RI=>'111-111',SC=>'AAA 111X111 1AA',TN=>'A11-11A',UT=>'A11 1AA'];$a=str_split(ABCDEFGHJKLMNPQRSTUVWXYZ);$n=range(0,9);$p=explode(X,$f[$argv[1]]);shuffle($p);for(;$i<strlen($p[0]);){$c=$p[0][$i++];echo$c==A?$a[rand(0,22)]:($c>0?$n[rand(0,9)]:$c);}

If you want to generate the Phar yourself from that code, you will need to do the following:
<?php
$phar = new Phar('uslic.phar', 0, 'u');
$phar->setSignatureAlgorithm(Phar::MD5);
$phar->addFile('s');
$phar['s']->compress(Phar::GZ);
$phar->setStub('<?include"phar://u/s";__HALT_COMPILER();');

Interestingly enough, this compresses better than a more golfed version.
The hexdump of the file is:
3C 3F 69 6E 63 6C 75 64 65 22 70 68 61 72 3A 2F
2F 75 2F 73 22 3B 5F 5F 48 41 4C 54 5F 43 4F 4D
50 49 4C 45 52 28 29 3B 20 3F 3E 0D 0A 30 00 00
00 01 00 00 00 11 00 00 00 01 00 01 00 00 00 75
00 00 00 00 01 00 00 00 73 34 03 00 00 26 C8 A9
59 76 01 00 00 E3 82 AE C9 B6 11 00 00 00 00 00
00 55 90 5D 6F 82 30 14 86 FF 8A 17 4D 0A B1 26
E2 9D 43 34 1D 4C 45 04 19 20 A2 84 2C 04 41 4D
0C 12 74 CB 92 65 FF 7D A5 AD A3 DC 34 7D CE C7
FB 9E 73 26 33 50 68 31 B6 B4 29 C4 18 F7 14 45
81 C8 C4 22 D9 7E 87 5C 91 C2 40 24 88 7D 48 58
A1 80 0F 2C C5 68 81 45 DA 11 E2 80 B0 C7 5A 7A
24 00 91 E5 77 68 2F D2 1A 8B E4 18 22 C1 8D 07
45 D6 69 2D F3 20 C4 C6 1C 28 CC DE D0 5B 84 68
BE E6 3B 60 BA 3B A3 1E 2F 35 1D A6 8A A3 E6 E1
2F 8E 9E C2 B6 C1 6C 58 B1 6D B6 D7 50 22 85 49
46 ED E9 B8 D6 80 CD 1F 52 A2 53 10 5A F2 E9 99
92 B3 6A 94 FE 4B ED B6 B1 91 E3 2D 7B E6 C6 D7
70 F4 0E BA B8 83 41 D4 C1 B0 9B DD 99 1D DC 2C
85 3D 08 5A FC 06 CD 2C AE D7 96 42 E4 99 7C 32
4A BE DE F6 45 74 99 A6 23 70 F8 2E 44 01 A2 6D
C0 88 E6 12 15 A4 DA FD 51 7F DC AB EB E5 21 E1
57 DD 78 9B 2F 96 2B 6B 6D 3B EE BB E7 07 DB 70
17 ED 0F B2 0A 4A AD 4E CB 53 2E 0D D1 98 50 A5
E5 DF D5 F5 76 CC A5 08 81 22 06 69 7D FA 8A 95
24 91 D5 FB F9 B3 28 AE B9 04 2A 59 2D 6E B5 A4
82 CB 84 18 5C F3 92 84 E2 21 A9 90 7F 40 A6 D1
7F 0C 2E FD 7E A2 E6 D9 F9 46 42 1A 9E 81 34 26
2E 47 62 32 1A C9 C9 8B 04 B2 E9 70 06 CA 67 70
4C 62 20 93 D5 DF 3F A0 DB 74 9C 07 ED A5 F7 4D
BA 32 97 A2 E7 9C 83 01 00 00 00 47 42 4D 42

PHP, 609 bytes
<?$k='9 3';$l='3 9';$m='9-4';$f=[AK=>$k,IA=>$k,MS=>$k,MP=>$k,VT=>$k,'AS'=>4,AZ=>94,GA=>94,WA=>94,AR=>$l,KS=>$l,KY=>$l,LA=>$l,ND=>$l,'OR'=>$l,CA=>193,CT=>'8-5',DC=>'8-4',FL=>'9 72',IL=>'8 5',IN=>'37X38X39X93',MD=>184,MI=>'9 31X18 72X9 3',MN=>'3-9',NV=>'27-3',NH=>'3 4',NJ=>'72-9',NM=>'3-9X9-3',NY=>$m,NC=>$m,PA=>$m,TX=>$m,VA=>$m,WI=>$m,OH=>"$k1",OK=>39,PR=>'9-3',RI=>'3-3',SC=>"$kX3 18",TN=>'72-27',UT=>'72 18'];$a=str_split(ABCDEFGHJKLMNPRSTUVWXYZ);$n=range(0,9);$p=explode(X,$f[$argv[1]]);shuffle($p);for(;$c=$p[0][$i++];){if($c<1)echo$c;else for($j=0;$j<$c%6;$j++){echo$c>5?$a[rand(0,22)]:$n[rand(0,9)];}}

The main idea is to encode the license plate pattern with digits that indicate how many repetitions of a digit or letter follow. 1 to 5 refer to the number of digits while 7, 8 and 9 refer to 1, 2 or 3 letters, respectively. Multiple patterns are separated by an X, spaces and dashes are kept as-is.
The state lookup is a simple array key lookup, redundant strings are put into variables to save space.
Ungolfed:
<?php
$f=[
    AK=>'9 3',
    IA=>'9 3',
    MS=>'9 3',
    MP=>'9 3',
    VT=>'9 3',
    'AS'=>4,
    AZ=>94,
    GA=>94,
    WA=>94,
    AR=>'3 9',
    KS=>'3 9',
    KY=>'3 9',
    LA=>'3 9',
    ND=>'3 9',
    'OR'=>'3 9',
    CA=>193,
    CT=>'8-5',
    DC=>'8-4',
    FL=>'9 72',
    IL=>'8 5',
    IN=>'37X38X39X93',
    MD=>184,
    MI=>'9 31X18 72X9 3',
    MN=>'3-9',
    NV=>'27-3',
    NH=>'3 4',
    NJ=>'72-9',
    NM=>'3-9X9-3',
    NY=>'9-4',
    NC=>'9-4',
    PA=>'9-4',
    TX=>'9-4',
    VA=>'9-4',
    WI=>'9-4',
    OH=>'9 31',
    OK=>39,
    PR=>'9-3',
    RI=>'3-3',
    SC=>'9 3X3 18',
    TN=>'72-27',
    UT=>'72 18'
];
$a=str_split(ABCDEFGHJKLMNPRSTUVWXYZ);
$n=range(0,9);
$p=explode('X',$f[$argv[1]]);
shuffle($p);
for ($i = 0; $i < strlen($p[0]); $i++) {
    $c=$p[0][$i];
    if ($c < 1)
        echo $c;
    else {
        for ($j = 0; $j < $c % 6; $j++){
            echo $c > 5 ? $a[rand(0,22)] : $n[rand(0,9)];
        }
    }
}

C (gcc), 473 469 bytes
Thanks to ceilingcat for -4 bytes.
A first feeble attempt. I suspect there is a way to shorten the strings substantially.
n,c,d,i;f(char*s){n=0;for(s=strstr("AKnIAnMSnMPnVTnAS`AZrGArWArARfKSfKYfLAfNDfORfCAlCTtDCsFLpILmINbcdqMDkMInojMNhNViNHgNJuNMhxNYyNCyPAyTXyVAyWIyOHoOKdPRxRIaSCoeTNvUTw",s)+2;s[n]>90;n++);for(s="4    3-3  3A   3B   3C   3 1B 3 C  3 4  3-C  2A-3 1B A21B4  1BA3 B 5  C 3  C 4  C A2 C3   C4   B-4  B-5  A2-C A2-2AA2 1BC-3  C-4  "+(s[rand()%n]-96)*5,n=5;d=c=*s++,n--;)for(c>57?i=c-64,c=65:c>47?i=c-48,c=48:(i=1);i--;putchar(d))while(i&&index("IOQ",d=rand()%(c>57?26:10)+c));}

Try it online!

@ceilingcat Nice, cheers!

Clojure, 502 501 bytes
#(apply str(for[E[repeatedly]c(rand-nth(cond('#{AK IA MS MP VT}%)["D 3"]('#{AR KS KY LA ND OR}%)["3 D"]('#{AZ GA WA}%)["D4"]1(case % AS["4"]CA["1D3"]CT["C-5"]DC["C-3"]FL["D B1"]IL["C 4"]IN["3B""3C""3D""D2"]MD["1C3"]MI["D 4""1C B2""D 2"]MN["3-C"]NV["2B-2"]NH["3 3"]NJ["B2-C"]NM["3-D""D-2"]OH["D 3"]OK["3C"]PR["D-2"]RI["3-2"]SC["D 3""3 1B"]TN["B2-2"]UT["B2 1B"]["D-4"])))r(cond((set"BCD")c)(E(-(int c)65)(fn[](rand-nth"ABCDEFGHJKLMNPRSTUVWXYZ")))((set"1234")c)(E(-(int c)48)(fn[](rand-int 10)))1[c])]r))

The input argument is a symbol, not a string. This let me avoid many double-quotes. B - D encode repetitions A - AAA, 1 - 4 encode repetitions 0 - 0000.

Python 2, 438 bytes
import re,random
lambda s,R=range,C=random.choice:re.sub('\d',lambda c:''.join(C(['0123456789','ABCDEFGHJKLMNPRSTUVWXYZ'][c.group()>'4'])for _ in R(int(c.group())%5+1)),C("063;6-3;072;3;7 2,2 06;6-4;51-15;2-7,7-2;7 2;;7 3;;6 4;2 7;2 7;2-2;25,26,27,72;2 7;;7 3,06 51,7 2;7 2;73;;2 3;;7 51;;73;7 2;2 7;;27;2 7;;7 2;7-2;;73;;51-7;;51 06;;2-7;15-2;7 2;;7-3".split(";")["MDCASCTNMSOHILARINDMIAZNHFLWAKSOKYMPRGANJUTMNVTOR".find(s)].split(",")))

Try it online!
Readable version: Try it online!
Note how the states string is only 49 letters long. I folded overlapping letters into one as much as possible (MD → DC → CA → AS → SC…) and omitted NY, NC, PA, TX, VA, WI which thus all map to -1.
In the list of codes, 12345 mean that many digits and 678 mean (that−5) many letters.

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


text:
Find the Closest Double Palindrome
Given a double-precision float, find the closest double-precision float whose binary representation is a palindrome.
Input
A floating point number x. You may use any format you like for input, but the format you chose must be able to represent every possible IEEE 754 binary64 value, including denormals, distinct representations for +0 and -0, and +Inf, -Inf, and NaN.
Output
A floating point number y. You may use any format you like for output, with the same restrictions as the input format.
The Task
y is any value such that:

The IEEE 754 binary64 bitstring for y is a palindrome. That is, the first 32 bits are the reverse of the last 32 bits.
abs(x-y) is minimal by the totalOrder predicate.

Notes

abs(x-y) must be computed with strict IEEE 754 double-precision floating point arithmetic.
totalOrder puts non-numeric values and signed zeroes in this order: - NaN < -Inf < -1 < -0 < +0 < +1 < +Inf < +NaN. Otherwise it behaves like the normal < operator.
The rules for performing arithmetic on non-numeric values can be found at this website
For an overview of how binary64 floats work, see wikipedia.
If there is more than one value for y that satisfies the conditions, output any one of them. Note that this can only occur if abs(x-y1) == abs(x-y2), or if they are both NaN.
The input and output formats may be different if desired; both formats still need to obey all the rules.
It may be convenient to use a raw binary format for IO; this is permitted.
For the purposes of this challenge you may consider all NaN values as equivalent, since NaN payload behavior is implementation defined.
It is not sufficient to just mirror the first 32 bits. See test cases 2, 4, 5, and 7 for examples.
Any non-NaN double palindrome is valid output for x=+Inf or x=-Inf, since the distance is still just +Inf. Reversing the first 32 bits would not be correct though since the resulting NaN value would have a distance of +NaN > +Inf from the input.
A NaN though, any double palindrome would be correct.

Test Cases
Input:  0x8A2B_7C82_A27D_6D8F = -1.1173033799881615e-259
Output: 0x8A2B_7C82_413E_D451 = -1.1173031443752871e-259

Input:  0x5000_0000_0000_0001 = 2.3158417847463244e+77
Output: 0x4FFF_FFFF_FFFF_FFF2 = 2.3158417847463203e+77

Input:  0x5000_0000_0000_0002 = 2.315841784746325e+77
Output: 0x5000_0000_0000_000A = 2.315841784746329e+77

Input:  0x7FF0_0000_0000_0000 = +Inf
Output: 0x0000_0000_0000_0000 (others are possible)

Input:  0xFFF0_0000_0000_0000 = -Inf
Output: 0x0000_0000_0000_0000 (others are possible)

Input:  0x7FFC_0498_90A3_38C4 = NaN
Output: 0x0000_0000_0000_0000 (others are possible)

Input:  0x8000_0000_0000_0000 = -0
Output: 0x0000_0000_0000_0000 = +0

Input:  0x0000_0000_0000_0000 = +0
Output: 0x0000_0000_0000_0000 = +0

Input:  0x8A2B_7C82_413E_D451 = -1.1173031443752871e-259
Output: 0x8A2B_7C82_413E_D451 = -1.1173031443752871e-259

Input:  0x000F_FFFF_FFFF_FFFF = 2.225073858507201e-308
Output: 0x000F_FFFF_FFFF_F000 = 2.2250738585051777e-308

Input:  0x0000_B815_7268_FDAF = 1e-309
Output: 0x0000_B815_A81D_0000 = 1.0000044514797e-309

code-golf scoring, Standard Loopholes forbidden.

Can you please define or add a reference to IEEE 754 binary64 bitstring?

@Mr.Xcoder https://en.wikipedia.org/wiki/Double-precision_floating-point_format

C (gcc), 172 bytes
#define D double
i;D f(D x){unsigned a[]={0,0};D*A=&a;D c=0;do{for(i=0;i<32;++i){*a=*a&~(1<<i)|!!(a[1]&1<<(31-i))<<i;};c=fabs(x-*A)<fabs(x-c)?*A:c;}while(++a[1]);return c;}

(Almost) purely brute-force; takes about 24 minutes per run on my machine.
f is a function that takes a double and returns the closest palindromic double. It iterates over every palindromic 64-bit sequence (as a double), storing the closing one, and returns it at the end.
This solution uses gcc on Ubuntu 16.04 32-bit, on a little-endian 32-bit single-core Pentium 4 2.8 GHz CPU.
Explanation/Ungolfed:
int i;
double f(double x) {
    unsigned int a[]={0, 0}; // a 2-array of ints is much easier to maipulate bitwise
    double *A = &a; // than a double, so refer to the same memory
    // in two different ways, a as int[2], A as double*
    double current = 0.0;
    do {
        for(i = 0; i < 32; ++i) {
            *a = ( *a&~(1<<i) )|( (!!( (a[1]&1)<<(31-i) ))<<i);
            // reverse the bits of the second half into the first half
            // (*a is shorter than a[0])
        }
        current = fabs(x-*A)<fabs(x-current) ? *A : current;
        // if *A is closer to x than current, replace c with *A
    } while (++a[1]);
    // do-while instead of while to ensure each value is tried
    // at UINT32_MAX, overflows to 0, ending the loop.
    return current;
}

A C float (binary32) version that takes ~0.0015% as long to run (about 0.02 seconds on my machine) because it checks 1/65536 as many values: (185 179 bytes)
#define F float
i;F f(F x){unsigned short a[]={0,0};F*A=&a;F c=0;do{for(i=0;i<16;++i){*a=*a&~(1<<i)|!!(a[1]&1<<(15-i))<<i;};c=fabsf(x-*A)<fabsf(x-c)?*A:c;}while(++a[1]);return c;}


text:
Reindent Java/C/C++/etc. code
Write a program that adds or removes whitespace to format code nicely. Rules for what the code should look like when you're done:

No line should contain more than one of { and }.
A { should always be the last thing on a line.
A } should always be the only thing on a line (besides whitespace that comes before it).
The amount of whitespace in front of each line should be a fixed multiple of the current nesting count. (You can use any amount of indentation you want, as long as it doesn't change.)
No whitespace should be inserted or removed that doesn't contribute to satisfying one of these rules.

The nesting count for the first line is 0. The nesting count of any other line is the nesting count of the previous line, plus one if the previous line contains a {, minus one if the current line contains a }.
{ and } inside string literals and comments don't count in the above rules. A string literal is text enclosed in single or double quotes, where single or double quotes with an odd number of backslashes immediately before them aren't interpreted as the end of the string literal. A comment is text enclosed in /* and */, or text going from // to the end of the line. In a line multiple comment start markers, only the first one counts. Comments are not parsed inside string literals.
Examples
    main() {printf("Hello!"); // I don't care about the world...
        }

becomes:

main() {
    printf("Hello!"); // I don't care about the world...
}

int main(){
    puts("a");
        puts("b");
}

becomes:

int main(){
    puts("a");
    puts("b");
}

main()
{ printf("{"); /* }
} */
     printf("}//}"); ///*
    }

becomes:

main()
{
    printf("{"); /* }
} */
    printf("}//}"); ///*
}

int test[] = {1, 2, 3};

becomes:

int test[] = {
    1, 2, 3
}
;

Comments are not for extended discussion; this conversation has been moved to chat.

JavaScript (ES6), 376 373 378 393 bytes
This was... quite the challenge...

let f =

s=>{F=(i,l=1)=>[a=a.map(([q,y])=>[q,ya.unshift(b=[q,y])&0))b=l=0
s=s[e=1,r](/[{}](?=.)|.(?=})/g,(c,i)=>F(i)&&c+`
`)[e=0,r](/.+/g,(x,i)=>x[r](/^\s*/,y=>" ".repeat(q=/{/.test(x)?l++:/}/.test(x)?--l:l,F(i,q-y.length))))
a.map(([q,y])=>s=s.slice(0,y)+q+s.slice(-~y))
return s}
<textarea rows=7 cols=50 oninput=O.innerText=f(value)>    main() {printf("Hello!"); // I don't care about the world...
    }</textarea>

Let me know if there's anything wrong with the output, though I couldn't find anything can't find anything more.
Ungolfed version
I golfed the code as I wrote it, so let's see how this goes...

function prettify(code) {
  let excerpts = [], extras, level;

  // Extract comments and strings for easy parsing
  // This has to be done recursively because of the nested comments
  for (let done = false; !done; ) {
    done = true;
    code = code.replace(/\/\*(?:(?!\/\*|\*\/)[^])*\*\/|\/\/.+|("|')(?:\\.|(?!\1).)*\1/, (excerpt, _, index) => {
      excerpts.unshift([excerpt, index]);
      done = false;
      return "0";
    });
  }

  // Update the indices of the excerpts when the code is changed
  let adjustIndices = (index, length) => {
    index += extras;
    excerpts = excerpts.map(([string, oldIndex]) => {
      var newIndex = oldIndex;
      if (oldIndex >= index) newIndex += length;
      return [string, newIndex];
    });
    extras += length;
  }

  // Add extra newlines where necessary:
  // - After a { or a } if there isn't one already
  // - Before a } if there isn't one already (note: already-indented '}'s will get an extra newline)
  extras = 0;
  code = code.replace(/[{}](?=.)|.(?=})/g, (char, index) => {
    adjustIndices(index + 1, 1);
    return char + "\n";
  });

  // Remove extra whitespace at the beginning of each line,
  // and the same time apply the necessary number of tabs
  extras = 0;
  level = 0;
  code = code.replace(/.+/g, (line, index) =>
    line.replace(/^\s*/, spaces => {
      let tabs;
      if (line.indexOf('{') > -1)
        tabs = level, level += 1;
      else if (line.indexOf('}') > -1)
        level -= 1, tabs = level;
      else
        tabs = level;

      adjustIndices(index, tabs - spaces.length);
      return "\t".repeat(tabs);
    })
  );

  // Add back in the excerpts
  for ([excerpt, index] of excerpts)
    code = code.slice(0, index) + excerpt + code.slice(index + 1);

  return code;
}
<textarea rows = 7 cols = 50 oninput = "O.innerText = prettify(this.value)">    main() {printf("Hello!"); // I don't care about the world...
    }</textarea>

looks good to me

I golfed the code as I wrote it that means you're a true golfer...

JavaScript (ES6), 260 259 bytes
Parses the input character by character. Uses 4-space indentation.
s=>s.replace(/[^]/g,(x,n)=>(p=s[n-1],a=!l&!c&!e,l|x!='/'?a&x=='*'&p=='/'?c=x:!c&!e&x=='"'?(l^=1,x):x==`
`?(i=e=0,x):a&x=='}'?d--&&i?`
`+x:i=x:a&x=='{'?s[i=!++d,n+1]==`
`?x:x+`
`:i?x:x==' '?'':' '.repeat(!c*d*4,i=1)+x:p==x?e=x:!e&p=='*'?(c=0,x):x),d=i=l=c=e=0)

This is still a WIP and was basically tested only against the provided examples. If you find any bug, please let me know in the comments.
The state of the parser is fully described by the following variables:

d → current nesting depth
i → flag telling that we're located 'inside' the code (i.e. after the leading spaces of the line)
l → string literal flag
c → block comment flag
e → line comment flag

Obligatory indented version
s => s.replace(
  /[^]/g,
  (x, n) => (
    p = s[n - 1],
    a = !l & !c & !e,
    l | x != '/' ?
      a & x == '*' & p == '/' ?
        c = x
      :
        !c & !e & x == '"' ?
          (l ^= 1, x)
        :
          x == `\n` ?
            (i = e = 0, x)
          :
            a & x == '}' ?
              d-- && i ? `\n` + x : i = x
            :
              a & x == '{' ?
                s[i = !++d, n + 1] == `\n` ? x : x + `\n`
              :
                i ?
                  x
                :
                  x == ' ' ? '' : ' '.repeat(!c * d * 4, i = 1) + x
    :
      p == x ?
        e = x
      :
        !e & p == '*' ? (c = 0, x) : x
  ),
  d = i = l = c = e = 0
)

Test cases

let f =

s=>s.replace(/[^]/g,(x,n)=>(p=s[n-1],a=!l&!c&!e,l|x!='/'?a&x=='*'&p=='/'?c=x:!c&!e&x=='"'?(l^=1,x):x==`
`?(i=e=0,x):a&x=='}'?d--&&i?`
`+x:i=x:a&x=='{'?s[i=!++d,n+1]==`
`?x:x+`
`:i?x:x==' '?'':' '.repeat(!c*d*4,i=1)+x:p==x?e=x:!e&p=='*'?(c=0,x):x),d=i=l=c=e=0)

console.log(f(
  `    main() {printf("Hello!"); // I don't care about the world...\n` +
  `        }`
))

console.log(f(
  `int main(){\n` +
  `    puts("a");\n` +
  `        puts("b");\n` +
  `}`
))

console.log(f(
  `main()\n` +
  `{ printf("{"); /* }\n` +
  `} */\n` +
  `     printf("}//}"); ///*\n` +
  `    }`
))

console.log(f(
  `int test[] = {1, 2, 3};`
))


text:
Degree of Unsaturation
Degree of Unsaturation
This is not a particularly hard code puzzle - but I'm interested to see your multiple ways of solving it.
The Degree of Unsaturation is the number of double chemical bonds between atoms, and/or the number rings in a chemical compound.
You will be given the molecular formula of a chemical compound in the form XaYbZc (where a, b and c are the number of atoms of X, Y or Z in the compound) - the formula could be of any length and contain any chemical element in the periodic table (though elements other than C, H, N, F, Cl, Br, I may be ignored as they do not feature in the formula). The compound will contain at least one atom of carbon. You must calculate and display its Degree of Unsaturation.
For example, the compound benzene (pictured below) has a DoU of 4 as it has three double bonds (shown by a double line between atoms), and a single ring (a number of atoms connected in a loop):

As defined by LibreTexts:

DoU = (2C + 2 + N − X − H ) / 2

Where:

C  is the number of carbon atoms
N  is the number of nitrogen atoms
X  is the number of halogen atoms (F, Cl, Br, I)
H  is the number of hydrogen atoms

Test cases:
C6H6 --> 4
C9H2O1 --> 0
C9H9N1O4 --> 6
U1Pt1 --> Not a valid input, no carbon
Na2O1 --> Not a valid input, no carbon
C1H1 --> 1.5, although in practice this would be one, but is a part of a compound rather than a compound in entirety.
N1H3 would return 0 - though in practice it isn't an organic compound (in other words it contains no carbon) so the formula wouldn't apply and it isn't a valid input

For an explanation of CH see here
In essence, you must identify if there are any of the above elements (C, H, N, F, Cl, Br, I) in the compound, and if so how many there are. Then, calculate the Degree of Unsaturation using the above formula.
Only C, H, N, F, Cl, Br, and I are valid inputs for the DoU formula. For the purposes of this puzzle, any other elements may be completely ignored (eg if the compound were C6H6Mn the result would still be 4). If there are none of the above compounds the answer would be zero.
You may assume that all the compounds input are chemically possible, contain at least one atom of carbon, and are known to exist. If the input is invalid, the program may output either 0 or -1, or produce no result.
Rules
Standard IO rules and loopholes apply. Input must be a standard string, and you can assume the input won't be empty. This is codegolf - so the shortest code in bytes wins.

Proposed test cases: Sodium oxide: Na2O and Methylidyne: CH and CCl4He. These are some corner cases that may break a few solutions. By the way, not that it matters for anyone other than Mathematica (probably), but can we assume that the compounds (can) exist?

I don't understand C9H2O1 --> 0. Shouldn't it be 9? (2*9+2+0-0-2)/2

according to last paragraph, do you mean the code must be able to deal with invalid inputs? By the way, is it guaranteed that every single element in the compound has a trailing '1' as in C1H1?

@KeyuGan yes and yes.

Python 3, 142 151 148 bytes
import re
l=dict(re.findall("(\D+)(\d+)",input()))
m=lambda k:int(l.get(k,0))
print(m("C")and m("C")+1+(m("N")-sum(map(m,"F I H Cl Br".split())))/2)

Returns 0 on error.
Thanks to @HyperNeutrino bringing the bytes down.
Try it online!

oops - test cases updated!

Does't quite work

@HyperNeutrino Test cases were unclear for a bit. Now has no output on invalid input.

148 bytes

Nice use of dict there!

146 bytes

JavaScript (ES6), 117 112 bytes
Returns 0 for invalid inputs.
s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,s|=n==2,n>2?3:n],1)*s

Test cases

let f =

s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,s|=n==2,n>2?3:n],1)*s

console.log(f("C6H6"))     // --> 4
console.log(f("C9H20"))    // --> 0
console.log(f("C9H9N1O4")) // --> 6
console.log(f("U1Pt1"))    // --> 0 (invalid)
console.log(f("Na2O1"))    // --> 0 (invalid)
console.log(f("C1H1"))     // --> 1.5
console.log(f("N1H3"))     // --> 0 (invalid)

Alternate version, 103 bytes
If the input was guaranteed to be valid -- as the challenge introduction is misleadingly suggesting -- we could just do:
s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,n>2?3:n],1)

Demo

let f =

s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,n>2?3:n],1)

console.log(f("C6H6"))     // --> 4
console.log(f("C9H20"))    // --> 0
console.log(f("C9H9N1O4")) // --> 6
console.log(f("C1H1"))     // --> 1.5

Pip, 70 67 bytes
`C\d`Na&1+/2*VaR+XDs._R['C'NC`H|F|I|Cl|Br`].s["+2*"'+'-]RXU.XX"+0*"

Takes the chemical formula as a command-line argument. Outputs 0 for invalid inputs. Try it online!
Explanation
Uses a series of regex replacements to turn the chemical formula into a mathematical formula, evals it, and makes a couple tweaks to get the final value.
The replacements (slightly ungolfed version):
aR+XDs._R"C ""+2*"R"N "'+R`(H|F|I|Cl|Br) `'-RXU.XX"+0*"

a                    Cmdline arg
 R+XD                 Replace runs of 1 or more digits (\d+)
     s._               with a callback function that prepends a space
                       (putting a space between each element and the following number)
 R"C "                Replace carbon symbol
      "+2*"            with +2* (add 2* the number of carbon atoms to the tally)
 R"N "                Replace nitrogen symbol
      '+               with + (add the number of nitrogen atoms to the tally)
 R`(H|F|I|Cl|Br) `    Replace hydrogen or halogen symbol
                  '-   with - (subtract the number of atoms from the tally)
 RXU.XX               Replace uppercase letter followed by another char ([A-Z].)
       "+0*"           with +0* (cancel out numbers of all other kinds of atoms)

We eval the resulting string with V. This gives us 2C + N − X − H. To get the correct value, we make the following adjustments:
`C\d`Na&1+/2*V...

             V...  Value of expression calculated above
          /2*      multiplied by 1/2
        1+         plus 1
`C\d`Na            Is carbon in the original formula? (i.e. C followed by a digit)
       &           Logical AND: if no carbon, return 0, otherwise return the formula value

C (gcc), 195 197 202 bytes
Probably the longest answer.
d,c,b,e,n;f(char*a){for(c=d=0;b=*a;d+=e?e-1?b-66?b-67?0:e-2?0:-n:e-3?0:-n:b-67?b-78?b/70*73/b?-n:0:n:(c=2*n):0)e=*++a>57?*a-108?*a-114?0:3:2:1,a+=e>1,n=strtol(a,&a,10);printf("%.1f",c?d/2.+1:0);}

Try it online!
Returns 0 on error.

187 bytes


text:
Make me a fence!
Challenge
This is a simple challenge. Given two positive integers w and h create an ASCII fence with a width of w and a height of h. The fence should be constructed using the following rules:

The + character will represent a post.
The - character will be used to represent the width of the fence.
The | will be used to represent the height of the fence.
After exactly three - characters have been outputted, a + character must be outputted afterward. Excluding the four corners, any other time you output a + would be invalid. You are allowed to follow this rule starting either from the left or the right (see examples), but you must be consistent.
After exactly two | characters have been outputted, a + character must be outputted afterward. Excluding the four corners, any other time you output a + would be invalid.  You are allowed to follow this rule starting either from the top or bottom (see examples), but you must be consistent.
Each fence will have exactly four corners, and each corner will be represented with a +.

In other words: At every three - characters, you must output a +. And at every two | characters, you must output a +.
You can assume that the fence will always be a rectangle, and that both w and h will never be greater than 100 or less than 1. Trailing and/or preceding whitespace is allowed.
Examples/Test Cases
w = 1
h = 1

+-+
| |
+-+

w = 3
h = 2

+---+
|   |
|   |
+---+

w = 5
h = 7

+---+--+ or +--+---+
|      |    |      |
|      |    +      +
+      +    |      |
|      |    |      |
|      |    +      +
+      +    |      |
|      |    |      |
|      |    +      +
+      +    |      |
|      |    |      |
+---+--+    +--+---+

w = 10
h = 5

+---+---+---+-+  or +-+---+---+---+
|             |     |             |
|             |     +             +
+             +     |             |
|             |     |             |
|             |     +             +
+             +     |             |
|             |     |             |
+---+---+---+-+     +-+---+---+---+

w = 4
h = 4

+---+-+ or +-+---+
|     |    |     |
|     |    |     |
+     +    +     +
|     |    |     |
|     |    |     |
+---+-+    +-+---+

Rules

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

related

Am I right to understand there may not be two +'s touching?

@xnor Yes, that is correct.

Great first challenge, by the way.

@StephenS Thanks. I'll remember that. Also since I'm here, how long do you guys usually wait before accepting an answer? I don't want to annoy anyone be waiting to long or not waiting long enough before selecting an answer.

Does the 6 bullet points mean that a + symbol can be inserted between every two -?

@ChristianDean in other words, can the top line be +-+-+-+-+-+?

@ChristianDean but +-+-+-+-+-+ violates none of your 6 rules.

@LeakyNun Your right. That's a case I didn't have in mind when making my rules. I added a rule to state why +-+-+-+-+-+ is invalid. Sorry for the confusion.

Can I choose whether to output +---+-+ or +-+---+? Can I output different strings on the top and bottom, as long as the three - rule is applied?

Your last rule doesn't make sense, "at least 3" isn't right, since we certainly can't have more than 3. Did you mean something like "as many segments as possible must be of length 3"?. (For example: if w=4, this would make +---+-+ and +-+---+ valid options, but +--+--+ and +-+-+-+-+ invalid). Or did you mean you should only add the minimum number of extra posts (which would make +--+--+ valid but +-+-+-+-+ invalid)?

@ChristianDean Thanks for clarifying. Don't forget you can work these clarifications into the premise of the question, too ("posts cost money and time to dig, so you want to minimize the number of extra posts, but fence lengths can't be longer than...").

C, 131 bytes
#define L for(i=0,j=w;j;)putchar(i++%4?--j,45:43);puts("+")
f(w,h,i,j,c){L;for(j=1;h;printf("%c%*c\n",c,i,c))c=j++%3?--h,124:43;L;}

Try it online!
Explanation:
// The first and the last line are always similar, so let's use a macro
// to avoid code duplication.
#define L

// Let's initialize 'i' and 'j'. 'i' will be used to keep track of which
// character ('+' or '-') we should print, whereas 'j' starts from the
// input width and the loop terminates when 'j' reaches zero.
for(i=0,j=w;j;)

// We post-increment 'i' and take a modulo 4 of its previous value.
// If i%4 == 0, we print '+' (ASCII 43), otherwise we decrement 'j'
// and print '-' (ASCII 45).
putchar(i++%4?--j,45:43);

// After the loop we print one more '+' and newline.
puts("+")

// The function declaration which takes the two input parameters, and
// also declares three integer variables. These three variables could
// also be declared as global variables with the same bytecount.
f(w,h,i,j,c)

// The start of the function body. We use the macro 'L' to print the
// first line along with a newline.
{L;

// This loop prints all the lines between the first and the last. 'j'
// keeps track of when we should output a '+' instead of a '|'. 'h',
// which is the input parameter for height, serves as a terminator
// for the loop as it reaches zero.
for(j=1;h;<stuff missing from here>)

// We post-increment 'j' and check if its previous value is divisible
// by three, and if it isn't, we decrement 'h' and assign 124 (ASCII
// value for '|') to 'c'. Otherwise we assign '+' (ASCII 43) to 'c'.
c=j++%3?--h,124:43;

// The following is inside the 'increment' part of the 'for' loop.
// We print the character corresponding to the value of 'c', then
// the same character again, but padded with i-1  spaces before it
// ('i' hasn't been touched since the first loop, so it still stores
// the length of the first line), then a newline.
printf("%c%*c\n",c,i,c)

// Lastly we print the first line again using the same macro 'L'.
L;}

Suggest for(;h;printf("%c%*c\n",c,i,c=++j%3?--h,124:43)); instead of for(j=1;h;printf("%c%*c\n",c,i,c))c=j++%3?--h,124:43;

Python 3, 140 137 128 119 106 105 bytes
def f(w,h):a=~-w//3-~w;b=("+---"*w)[:a]+'+';print(b,*[i+' '*~-a+i for i in"||+"*h][:h+~-h//2],b,sep='\n')

Try it online!

It's longer now but the issue has been fixed.

You could save a byte by removing the space between in and [w+1+(w-1)//3]] in the last part.

Welcome to Programming Puzzles & Code Golf! Nice first answer. :D

Welcome to PPCG! You can remove the space in '\n') for as well. Also, you can change (w-1) to ~-wwhich allows you to remove the parentheses since unary operators have a higher precedence than binary ones. Same for (h-1) -> ~-h and (a-1) -> ~-a. Try it online - 128 bytes

Also since all of your output is printed, def f(w,h) is the same length as lambda w,h, but allows you to use multiple lines if that helps you golf your code further

Thanks for the advice, everyone! @ovs should your code be a separate answer or do you think it would be better to replace this one?

@ovs The Python 3 code is now shorter anyway so never mind.

a=~-w//3-~w; to save 1 byte

@FelipeNardiBatista Thanks!

Pip, 38 bytes
37 bytes of code, +1 for -n flag.
Ph:'-Xa<>3JW'+PsX#h-2WR:'|Xb<>2J'+^xh

Takes width and height as command-line arguments. Try it online!
Explanation
                         a,b are cmdline args; s is space; x is empty string (implicit)
Ph:'-Xa<>3JW'+
   '-Xa                  String of hyphens of length a
       <>3               grouped into substrings of (maximum) length 3
          JW'+           Join on +, also wrapping the result in +
 h:                      Assign that string to h (mnemonic: "header")
P                        and print it (with newline)

PsX#h-2WR:'|Xb<>2J'+^xh
          '|Xb           String of pipes of length b
              <>2        grouped into substrings of (maximum) length 2
                 J'+     joined on +
                    ^x   and split on empty string (i.e. converted to list of chars)
 sX#h-2                  String of len(h)-2 spaces
       WR:               Wrap the spaces with the list of chars
                         Note 1: WR operates itemwise on lists, so the result is a list,
                          each item of which consists of the spaces wrapped in an item
                          from the list of chars
                         Note 2: the : compute-and-assign meta-operator is here abused
                          to give WR: lower precedence than J and ^ and avoid parentheses
P                        Print that list, newline-separated (-n flag)
                      h  Autoprint the header a second time as the footer

Charcoal, 47 45 40 bytes
Ｆ⁴«¿﹪ι³ＦＩη↓⁺×+¬﹪κ²|ＦＩθ⁺×+¬﹪κ³-Ｐ+¿⁼ι¹Ｊ⁰¦⁰

Explanation: Works by drawing each side's -s/|s in turn, inserting +s where necessary, then finishing with a +. After drawing the top and right sides, jumps back to the start to draw them in reverse order, effectively drawing the left and bottom sides. I don't know whether rotational symmetry is permitted, but if so, then for 27 25 bytes:
Ｆ⁴«ＦＩ⎇﹪ι²ηθ⁺×+¬﹪κ⁻³﹪ι²-⟲Ｔ

Takes the above idea to the extreme by drawing the top side, rotating left, drawing the right side, rotating again, and then repeating to draw the bottom and left sides in reverse.

@LeakyNun Last time I beat Pyth was for Double up some diamonds, and even then it was only just shorter.

Mathematica, 165 bytes
v=Column;d[w_,y_,m_,n_]:=Table[If[Mod[i,y]==0&&i!=w,m,n],{i,w}];(a="+"<>d[#,3,"-+","-"]<>"+";b=v@d[#2,2,"|\n+","|"];v[{a,Row[{b,""<>Table[" ",#+Floor[#/3]],b}],a}])&

JavaScript (ES6), 133 132 bytes
w=>h=>(a="-".repeat(w).replace(/--?-?/g,"+$&")+`+`)+(`
|`.padEnd(a.length)+`|`).repeat(h).replace(/(\|( +)\|\n)\1/g,`$&+$2+
`)+`
`+a

Takes input in currying syntax: f(width)(height).
Test Snippet

f=
w=>h=>(a="-".repeat(w).replace(/--?-?/g,"+$&")+`+`)+(`
|`.padEnd(a.length)+`|`).repeat(h).replace(/(\|( +)\|\n)\1/g,`$&+$2+
`)+`
`+a
O.innerHTML=f(W.value=5)(H.value=10)

W <input id=W type=number min=1> H <input id=H type=number min=1>

Pyth, 40 bytes
AQj++KjJj\+c*\-G3"++"m++d*lJ;dj\+c*\|H2K

Test suite.

Java (OpenJDK 8), 178 177 bytes
w->h->{int i=0;String t="",m,r;for(;i<w;)t+=i++%3<1?"+-":"-";r=t+="+\n";m=t.format("|%"+(t.length()-3)+"s|\n","");for(i=0;i<h;)r+=i++%2<1&i>1?m.replace("|","+")+m:m;return r+t;}

Try it online!
-1 byte thanks to @KevinCruijssen

You can save a byte by currying the parameters: w->h-> Try it here.

Yep, I constantly forget about currying... It's not something I find natural :s

Charcoal, 47 45 37 bytes
Ａ…+---÷⁺²×⁴Ｎ³αＡ…+||÷⁺¹×³Ｎ²βＰα↓βα+↖↑⮌β

Try it online!

2 bytes saved after playing with the signs in the string creation.
8 bytes saved thanks to Neil, who came up with a much simpler way to calculate the lengths of the fences.

A different approach from @Neil's: first I create the strings α and β containing the chars in the horizontal and vertical borders, using the Range operator that creates a repetition of a string until a given length is reached. Then I print them in the proper order:

Print α without moving the cursor.
Print β downwards.
Print α.
Print a "+".
Move the cursor up and to the left.
Print β upwards, reversed.

Link to a verbose version.

Thanks for reminding me about Range, that saves 3 bytes on my second approach!

@Neil that's nice because I have just outgolfed you and I just can't believe it. :-)

Better still, I managed to optimise your expressions, saving 8 bytes: Ａ…+---÷⁺²×⁴Ｎ³αＡ…+||÷⁺¹×³Ｎ²βＰα↓βα+↖↑⮌β.

@Neil Wow. Such optimization. Very Charcoal.

05AB1E, 58 bytes
D3/ó+DU'-×'+.ø©'|DXú«²D2/ó+.D®»'-4×D'+3ǝ.:¶¡ø'|3×D'+2ǝ.:ø»

Try it online!
Harder in 05AB1E than I thought.