text:
Tips for golfing in Haxe
What general tips do you have for golfing in Haxe? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Haxe (e.g. "remove comments" is not an answer).
Please post one tip per answer.
Haxe can be run online here!

I've used Haxe quite a bit in the past, but since I started golfing I haven't used it much. I'll have to try using it for golfing...

@ETHproductions Same here. Today, I golfed two times with it, and it was fun. It has some good golfing capabilities with (for example) its list comprehensions and iterators, so I decided to open the question up to see if anyone has tips to share.

String interpolation
Haxe supports string interpolation on single-quote strings. Like template strings in JavaScript ES6, you can include an expression in a string with ${...}:
trace('2 + 2 = ${2 + 2}');

Unlike ES6, however, you can omit the curly brackets when the expression is a single variable:
var x = 2 + 2;
trace('2 + 2 = $x');

Both of these examples print 2 + 2 = 4.

Array comprehensions
Haxe supports array comprehensions:
trace([for (i in 0...5) i]); // Prints 0,1,2,3,4

Unlike many other languages, you can also use while in comprehensions:
var i = 5;
trace([while (i > 0) i--]); // Prints 5,4,3,2,1

This can be very useful when you don't know how long of an array you need.
You can also chain for, while, and if statements:
trace([for (x in ['A','B','C','D'])
       for (y in ['x','y'])
       if (x + y != "Cx")
       x + y
]); // Prints Ax,Ay,Bx,By,Cy,Dx,Dy

Wow. I'll delete my answer. I literally built the same answer, just a minute late. Also, you may want to note that it actually prints square brackets around the the lists, so readers won't be confused, since some challenges require strict output formats.

@TuukkaX Haha, that happens sometimes :) I'll include one of your examples in here, if you don't mind. Also, try.haxe.org doesn't seem to print square brackets...

The one that calculates the cartesian product is neat. I think that would be a good addition to your post :)

Range operator
Haxe has a range operator ... which can be used to create ranges of integers. For example, instead of this:
var i = 0;
while (i < 10) trace(i++);

You can do this:
for (i in 0...10) trace(i++);

Specifics for x...y:

x and y must both be Ints.
x cannot be larger than y.
This returns an IntIterator object, which can be used in the same places as any Iterable.

Omit function brackets
Unlike most languages, everything in Haxe is an expression, including {blocks}. Thus, curly brackets anywhere in a Haxe program (with the exception of switch expressions) can be left off if they contain only a single statement. So instead of this:
function f(n){return Math.pow(3,n);}

You can do this:
function f(n)return Math.pow(3,n);

An easy two bytes saved on many functions.
Even if a function must contain multiple statements, you can often save a byte by moving the return outside the block:
function f(a){var b=a*a;return a<0?-b:b;}
function f(a)return{var b=a*a;a<0?-b:b;}

This works because a block evaluates to the last expression inside the block.

@TuukkaX Heh, thanks. I'll use Math.pow(3,n) instead ;-)

Use keywords in expressions
Another unusual feature of Haxe is that everything is an expression. For example, this code is perfectly valid:
function(n){while(n>0)n%4==1?return 6:n--;return 3;}

Okay, that's a fairly useless example, but hopefully you get my point. This works with most keywords:
function(n){while(n>0)n%4==1?break:n--;return n;}

This allows you to use if/else inline, like p=if(n>1)7else 4;, though of course p=n>1?7:4; is shorter.
Keywords you cannot use inline

var - The compiler will complain about trying to use Void as a value.
for/while - Same as above, though you can use them in array comprehensions.

Running a statement conditionally
Obviously you can run anything conditionally with if:
if(n>5)doSomething(n);

If, however, you have only one statement as above, you can use the ternary conditional operator to save a byte:
n>5?doSomething(n):0;

You can sometimes save another byte by using &&, though this is very rare because && only works if both expressions return booleans:
n>5&&doSomething(n);

One major exception to this is keywords: if Haxe runs into a return, break, or continue anywhere, it will immediately run it and quit whatever expression it was working on. This means that instead of this:
if(n>5)return n;

You can do this to save 2 bytes:
n>5&&return n;


text:
Compute the Carmichael function
Task description
In number theory, the Carmichael function λ takes a positive integer n and returns the least positive integer k so that the k-th power of each integer coprime to n equals 1 modulo n.
Given a positive integer n, your solution must compute λ(n). The shortest code in bytes wins.
Your program should theoretically work for arbitrarily large inputs, but doesn’t need to be efficient.
Tips
The sequence of all λ(n) is OEIS A002322.
An ungolfed Python implementation would look like
from fractions import gcd

def carmichael(n):
    coprimes = [x for x in range(1, n) if gcd(x, n) == 1]
    k = 1
    while not all(pow(x, k, n) == 1 for x in coprimes):
        k += 1
    return k

(In Python, pow(A, B, C) efficiently computes pow(A, B) % C.)
Test cases
Input    Output
1        1
2        1
3        2
10       4
35       12
101      100
530      52
3010     84
6511     3056
10000    500

What does theoretically mean here? Can I assume that the input n fits in a 16-bit integer? Can I assume that n^λ(n) fits in a double?

Yes and yes, I’d say. As in, the theoretically includes pretend your native types are arbitrarily precise and large (I thought that was consensus, but I’m not sure).

Mathematica, 16 bytes
CarmichaelLambda

Well...

..... really.  ._.

I don't like u mathematica

@acrolith yeah '-'

Python, 76 73 67 bytes
f=lambda n,k=1:1-any(a**-~k*~-a**k%n for a in range(n))or-~f(n,k+1)

Try it online!
A further byte could be saved by returning True instead of 1.
Alternative implementation
Using the same approach, there is also the following implementation by @feersum which doesn't use list comprehensions.
f=lambda n,k=1,a=1:a/n or(a**-~k*~-a**k%n<1)*f(n,k,a+1)or-~f(n,k+1)

Note that this implementation requires O(nλ(n)) time. Efficiency could be improved dramatically while actually decreasing score to 66 bytes, but the function would return True for input 2.
f=lambda n,k=1,a=1:a/n or~-a**k*a**-~k%n<1==f(n,k,a+1)or-~f(n,k+1)

Background
Definitions and notation
All employed variables will denote integers; n, k, and α will denote positive integers; and p will denote a positive prime.
a | b if b is divisible by a, i.e., if there is q such that b = qa.
a ≡ b (mod m) if a and b have the same residue modulo m, i.e., if m | a - b.
λ(n) is the smallest k such that ak ≡ 1 (mod n) – i.e., such that n | ak - 1 – for all a that are coprime to n.
f(n) is the smallest k such that a2k+1 ≡ ak+1 (mod n) – i.e., such that n | ak+1(ak - 1) – for all a.
λ(n) ≤ f(n)
Fix n and let a be coprime to n.
By the definition of f, n | af(n)+1(af(n) - 1). Since a and n do not have a common prime factor, neither do af(n)+1 and n, which implies that n | af(n) - 1.
Since λ(n) is the smallest integer k such that n | ak - 1 for all integers a that are coprime to n, it follows that λ(n) ≤ f(n).
λ(n) = f(n)
Since we've already established the inequality λ(n) ≤ f(n), it is sufficient to verify that k = λ(n) satisfies the condition that defines f, i.e., that n | aλ(n)+1(aλ(n) - 1) for all a. For this purpose, we'll establish that pα | aλ(n)+1(aλ(n) - 1) whenever pα | n.
λ(k) | λ(n) whenever k | n (source), so (aλ(k) - 1)(aλ(n)-λ(k) + aλ(n)-2λ(k) + ⋯ + aλ(k) + 1) = aλ(n) - 1 and, therefore, aλ(k) - 1 | aλ(n) - 1 | aλ(n)+1(aλ(n) - 1).
If a and pα are coprime, by the definition of λ and the above, pα | aλ(pα) - 1 | aλ(n)+1(aλ(n) - 1) follows, as desired.
If a = 0, then aλ(n)+1(aλ(n) - 1) = 0, which is divisible by all integers.
Finally, we must consider the case where a and pα have a common prime factor. Since p is prime, this implies that p | a. Carmichael's theorem establishes that λ(pα) = (p - 1)pα - 1 if p > 2 or α < 3 and that λ(pα) = pα - 2 otherwise. In all cases, λ(pα) ≥ pα - 2 ≥ 2α - 2 > α - 2.
Therefore, λ(n) + 1 ≥ λ(pα) + 1 > α - 1, so λ(n) + 1 ≥ α and pα | pλ(n)+1 | aλ(n)+1 | aλ(n)+1(aλ(n) - 1). This completes the proof.
How it works
While the definitions of f(n) and λ(n) consider all possible values of a, it is sufficient to test those that lie in [0, ..., n - 1].
When f(n, k) is called, it computes ak+1(ak - 1) % n for all values of a in that range, which is 0 if and only if n | ak+1(ak - 1).
If all computed residues are zero, k = λ(n) and any returns False, so f(n, k) returns 1.
On the other hand, while k < λ(n), 1-any(...) will return 0, so f is called recursively with an incremented value of k. The leading -~ increments the return value of f(n, k + 1), so we add 1 to f(n, λ(n)) = 1 once for every integer in [1, ..., λ(n) - 1]. The final result is thus λ(n).

You can save at least 4 with recursion instead of a list comprehension: f=lambda n,k=1,a=1:a/n or(a**k*~-a**k%n<1)*f(n,k,a+2-n%2)or-~f(n,k+1) (Add back one byte if you don't like it to take n**λ(n) time).

Thanks! In the meantime, I found an improvement to my algorithm that seems to nullify the benefit of recursing instead of using a list comprehension.

Mathematica without built-in, 58 57 bytes
Thanks to Martin Ender for finding an error, then saving me the bytes it took to fix it!
Thanks to miles for saving 1 byte! (which seemed like 2 to me)
Built-ins are totally fine ... but for those who want to implement it without using brute force, here's a formula for the Carmichael function:
LCM@@(EulerPhi[#^#2]/If[#==2<#2,2,1]&@@@FactorInteger@#)&

If p is a prime, the Carmichael function λ(p^r) equals φ(p^r) = (p-1)*p^(r-1)—except when p=2 and r≥3, in which case it's half that, namely 2^(r-2).
And if the prime-power factorization of n equals p1^r1 * p2^r2 * ..., then λ(n) equals the least common multiple of { λ(p1^r1), λ(p2^r2), ...}.
Runtime is one instant more than factoring the integer in the first place.

You can use EulerPhi to get LCM@@(EulerPhi[#^#2]/If[#==2<#2,2,1]&@@@FactorInteger@#)& for 57 bytes.

@miles nicely spotted! I count 56 bytes, can you check?

Yeah, it's 57 bytes.

clearly I even try to golf my counting.... :/

Templates Considered Harmful, 246 bytes
Fun<Ap<Fun<If<Eq<A<2>,T>,A<1>,And<Eq<Ap<Fun<If<A<1>,Ap<A<0>,Rem<A<2>,A<1>>,A<1>>,A<2>>>,A<1,1>,A<2>>,T>,Sub<Ap<Fun<Rem<If<A<1>,Mul<A<2,1>,Ap<A<0>,Sub<A<1>,T>>>,T>,A<1,2>>>,A<1>>,T>>,Ap<A<0>,Add<A<1>,T>,A<1,1>>,Ap<A<0>,A<1>,Sub<A<2>,T>>>>,T,A<1>>>

An unnamed function (not that there are named functions).
This is a forgotten esolang of mine which is interpreted by a C++ compiler instantiating templates. With the default max template depth of g++, it can do λ(35), but it can't do λ(101) (the lazy evaluation makes things worse).

Haskell, 57 56 bytes
f n=[k|k<-[1..],and[mod(m^k)n<2|m<-[1..n],gcd m n<2]]!!0

Jelly, 2 bytes
Æc

Thank you for the builtin, @Lynn

............. ._.

I never understand the point of implementing such ridiculously specific built-ins.

This is almost an addition to the language specifically made for this challenge. Commit by Lynn 2 days ago, challenge by @Lynn today

@edc65 Not to mention that this built-in is pretty much useless outside this challenge and derivatives of it.

Well, the Carmichael function is important in number theory (as the currently top answer reflects), so I wouldn't call it useless.

@Fatalize: Do you have 65536 other functions you'd be inclined to implement before this one?

Pyth - 19 18 17 bytes
One byte saved thanks to @TheBikingViking.
Straight up brute force.
f!sm*t.^dTQq1iQdQ

Try it online here.

f!smt is one byte shorter.

@TheBikingViking oh, yeah thanks

Hurts my eyes, how the heck is this python..? Loved it nonetheless haha :)

Ruby, 59 56 bytes
->x{a=1..x
a.detect{|k|a.all?{|y|x.gcd(y)>1||y**k%x<2}}}

J, 28 27 bytes
[:*./@(5&p:%2^0=8&|)2^/@p:]

The Carmichael function is λ(n) and the totient function is φ(n).
Uses the definition where λ(pk) = φ(pk)/2 if p = 2 and k > 2 else φ(pk). Then, for general n = p1k1 p2k2 ⋯ piki, λ(n) = LCM[ λ(p1k1) λ(p2k2) ⋯ λ(piki) ].
Usage
Extra commands used to format multiple input/output.
   f =: [:*./@(5&p:%2^0=8&|)2^/@p:]
   f 530
52
   (,.f"0) 1 2 3 10 35 101 530 3010 6511 10000
    1    1
    2    1
    3    2
   10    4
   35   12
  101  100
  530   52
 3010   84
 6511 3056
10000  500

Explanation
[:*./@(5&p:%2^0=8&|)2^/@p:]  Input: integer n
                          ]  Identity function, get n
                    2   p:   Get a table of prime/exponent values for n
                     ^/@     Raise each prime to its exponent to get the prime powers of n
[:    (            )         Operate on the prime powers
                8&|            Take each modulo 8
              0=               Test if its equal to 0, 1 if true else 0
            2^                 Raise 2 to the power of each
       5&p:                    Apply the totient function to each prime power
           %                   Divide it by the powers of 2
  *./@                       Reduce using LCM and return

This gives the wrong answer for 10000 (1000 instead of the correct 500), and indeed for every multiple of 8. 2 is a peculiar prime, and λ(2^a) = 2^{a-2} (not 2^{a-1}) when a≥3.

Thanks for catching that, seems I can't even read my own output

you're not alone sometimes.... :)

JavaScript (ES6), 143 135 bytes
Edit: saved 8 bytes thanks to Neil
An implementation using functional programming.
n=>(A=[...Array(n).keys()]).find(k=>k&&!c.some(c=>A.slice(0,k).reduce(y=>y*c%n,1)-1),c=A.filter(x=>(g=(x,y)=>x?g(y%x,x):y)(x,n)==1))||1

Ungolfed and commented
n =>                                          // Given a positive integer n:
  (A = [...Array(n).keys()])                  // Build A = [0 ... n-1].
  .find(k =>                                  // Try to find k in [1 ... n-1] such as
    k && !c.some(c =>                         // for each coprime c: c^k ≡ 1 (mod n).
      A.slice(0, k).reduce(y =>               // We use reduce() to compute
        y * c % n, 1                          // c^k mod n.
      ) - 1                                   // Compare it with 1.
    ),                                        // The list of coprimes is precomputed
    c = A.filter(x =>                         // before the find() loop is executed:
      (                                       // for each x in [0 ... n-1], keep
        g = (x, y) => x ? g(y % x, x) : y     // only integers that verify:
      )(x, n) == 1                            // gcd(x, n) = 1
    )                                         // (computed recursively)
  ) || 1                                      // Default result is 1 (for n = 1)

Demo
Although it does work for 6511 and 10000, I won't include them here as it tends to be a bit slow.

let f =
n=>(A=[...Array(n).keys()]).find(k=>k&&!c.some(c=>A.slice(0,k).reduce(y=>y*c%n,1)-1),c=A.filter(x=>(g=(x,y)=>x?g(y%x,x):y)(x,n)==1))||1

console.log(f(1));     // 1
console.log(f(2));     // 1
console.log(f(3));     // 2
console.log(f(10));    // 4
console.log(f(35));    // 12
console.log(f(101));   // 100
console.log(f(530));   // 52
console.log(f(3010));  // 84

JS can do 0..n-1 ranges quite easily: [...Array(n).keys()]. This requires not one but two special cases but I'm still ahead: n=>(a=[...Array(n).keys()]).find(k=>k&&!c.some(c=>a.slice(0,k).reduce(y=>y*c%n,1)-1),c=a.filter(x=>(g=(x,y)=>x?g(y%x,x):y)(x,n)==1))||1

Actually, 30 28 25 19 26 bytes
The Carmichael function, λ(n) where n = p_0**k_0 * p_1**k_1 * ... * p_a**k_a, is defined as the least common multiple (LCM) of λ(p_i**k_i) for the maximal prime powers p_i**k_i that divide into n. Given that for every prime power except where the prime is 2, the Carmichael function is equivalent to the Euler totient function, λ(n) == φ(n), we use φ(n) instead. For the special case of 2**k where k ≥ 3, we just check if 2**3 = 8 divides into n at the beginning of the program, and divide by 2 if it does.
Unfortunately, Actually doesn't currently have an LCM builtin, so I made a brute-force LCM. Golfing suggestions welcome. Try it online!
;7&Yu@\w`iⁿ▒`M╗2`╜@♀%ΣY`╓N

Ungolfing
         Implicit input n.
;        Duplicate n.
7&       n&7 == n%8.
Yu       Logical NOT and increment. If n%8 == 0, return 2. Else, return 1.
@\       Integer divide n by 2 if n%8==0, by 1 otherwise.
          Thus, we have dealt with the special case where p_i == 2 and e_i >= 3.
w        Full prime factorization of n as a list of [prime, exponent] lists.
`...`M   Map the following function over the prime factorization.
  i        Flatten the array, pushing exponent, then prime to the stack.
  ⁿ▒       totient(pow(prime, exponent)).
╗        Save that list of totients in register 0.
2`...`╓  Get the first two values of n where the following function f(n) is truthy.
         Those two numbers will be 0 and our LCM.
  ╜@       Push the list in register 0 and swap with our n.
  ♀%       Get n mod (every number in the list)
  Σ        Sum the modulos. This sum will be 0, if and only if this number is 0 or LCM.
  Y        Logical NOT, so that we only get a truthy if the sum of modulos is 0.
N        Grab the second number, our LCM. Implicit return.

Actually, I have no idea how you did this in only 19 bytes.

@TheBitByte With use of the totient and gcd builtins. This would be shorter if Actually had lcm directly, but I don't mind it that much and that would only knock off 4 bytes at most, anyway.

The assertion that lcm(*a) = product(*a)/gcd(*a) is true when *a is a list of exactly two numbers; however, it is false in general for longer lists (example: if *a is {6,10,15}, it gives 900 instead of the correct answer of 60). [For that matter, it's wrong is *a is a list of one number as well!] And you can check that you get the wrong answer for over half the test cases listed in the OP.

@GregMartin Thanks for the heads up. Fixed.

Ruby, 101 86 91 90 bytes
A Ruby port of my Actually answer. Golfing suggestions welcome.
Edit: -4 bytes from removing a but +9 bytes from fixing a bug where 1 returned nil. -1 byte thanks to Cyoce.
require'prime'
->n{((n%8<1?n/2:n).prime_division<<[2,1]).map{|x,y|x**~-y*~-x}.reduce :lcm}

Ungolfing
require 'prime'
def carmichael(n)
  if n%8 < 1
    n /= 2
  end
  a = []
  n.prime_division.do each |x,y|
    a << x**(y-1)*(x-1)
  end
  return a.reduce :lcm
end

You don't need a=. Unfortunately, you return nil for n = 1 :(. (n.prime_division<<[2,1]) fixes that. Not sure if there's a golfier way.

(n%8<1?n/2:n).prime_division... saves another 2 bytes.

@m-chrzan a is a remnant of an earlier golfing attempt. Thanks for the reminder about a and for heads up on 1.

You can save a byte by using .reduce :lcm instead of .reduce(:lcm).

Java, 209 207 202 194 192 bytes
Code (96 bytes):
n->{for(int x,k=1,a;;k++){for(a=1,x=0;++x<=n&&a<2;)a=g(x,n)<2?p(x,k,n):1;if(a<2||n<2)return k;}}

extra functions (96 bytes):
int g(int a,int b){return b<1?a:g(b,a%b);}int p(int n,int p,int m){return p<2?n:n*p(n,p-1,m)%m;}

Testing & ungolfed
import java.util.Arrays;
import java.util.function.IntUnaryOperator;

public class Main2 {

  static int g(int a,int b) { // recursive gcd
    return b < 1
        ? a
        : g(b,a%b);
  }

  static int p(int n, int p, int m) { // recursive modpow
    return p < 2
      ? n
      : n * p(n, p - 1, m) % m;
  }

  public static void main(String[] args) {

    IntUnaryOperator f = n -> {
      for(int x,k=1,a;;k++) { // for each k
        for(a=1,x=0;++x<=n&&a<2;) // for each x
          a=g(x,n)<2?p(x,k,n):1; // compute modpow(x,k,n) if g(x,n)
        if(a<2||n<2) // if all modpow(x,k,n)=1. Also check for weird result for n=1.
          return k;
      }
    };

    Arrays.stream(new int[]{1, 2, 3, 10, 35, 101, 530, 3010, 6511, 10000})
        .map(f)
        .forEach(System.out::println);
  }
}

Notes

the use of a being an int is shorter than if I had to use a boolean to perform my tests.
Yes, it's shorter to valueOf all new BigInteger than create a separate function (there are 5, plus the ONE constant is a freebie).
Algorithm is different than @Master_ex' algorithm, so it's not just a golfed repost. Also, this algorithm is much less efficient as gcd is computed again and again for the same values.

Shaves

209 -> 207 bytes:

if(...)a=...; -> a=...?...:1;
a==1 -> a<2

207 -> 202 bytes

Got rid of BigInteger by golfing gcd and modPow for int.

202 -> 194 bytes

looping modPow -> recursive

194 -> 192 bytes

==1 -> <2 (seems to work for all the test cases, don't know for other numbers.)

Hey! I've noticed that the output is not the expected. See the question for the expected results. Personally, I often write unit tests before starting golfing my code, it helps! I guess that the problem could be the modPow on integers, I had also this problem and that's why I used BigInteger at the end.

Hmmm... I'm surprised, I let my tests run at every change. I'll check what's wrong.

@Master_ex I fixed it. Going back to the previous version is ok.

I find your recursive modpow method p pretty clever. I tried to use only integers at first too, but as I've mentioned in my answer, I had precision issues and that's why I've moved to BigInteger (i.e. Math.pow(3, 100)%101 returned 60.0 instead of 1). Your implementation is immune to this because it performs the mod in each iteration. However, it still suffers from a bug. For large m p may still return wrong results. Also, because of the recursion, StackOverflowError may easily occur for large input with the default stack size.

@Master_ex Yes, that's a consequence of the restriction to int types. I could use longs instead of ints, that'd be 8 extra bytes. But in my view, all the test cases are valid so I leave it like that. StackOverflowError can happen, but that's how recursive works. Methods exist to limit to 32 stacks, but these use many many more bytes. This implementation is fragile, yes, you are totally right. But it's strong enough for the test cases.

JavaScript (ES 2016) 149
Python reference implementation ported to JS. Some fancy Pyhton builtin is missing in js, like gcd and pow, and the array comprehension is not standard in ES 6. This works in Firefox.
n=>eval('for(g=(a,b)=>b?g(b,a%b):a,p=(a,b,c)=>eval("for(r=1;b--;)r=r*a%c"),c=[for(_ of Array(i=n))if(g(i--,n)<2)i+1],k=1;c.some(x=>p(x,k,n)-1);)++k')

Less golfed
n=>{
  g=(a,b)=>b?g(b,a%b):a
  p=(a,b,c)=>{
    for(r=1;b--;)
      r=r*a%c
    return r
  }
  c=[for(_ of Array(i=n)) if(g(i--,n)<2) i+1]
  for(k=1;c.some(x=>p(x,k,n)-1);)
    ++k
  return k
}

recursive modpow is shorter: p=(a,b,c)=>b?a*p(a,b-1,c)%c:1;

Java8 38 19 + 287 295 253 248 241 = 325 333 272 267 260 bytes
BigInteger B(int i){return new BigInteger(""+i);}int c(int...k){int n=k[0];for(k[0]=1;n>1&!java.util.stream.IntStream.range(0,n).filter(i->B(n).gcd(B(i)).equals(B(1))).allMatch(x->B(x).modPow(B(k[0]),B(n)).equals(B(1)));k[0]++);return k[0];}

Imports, 19 bytes
import java.math.*;

Explanation
It is a straight forward implementation. The co-primes are calculated in the Set p and every one's kth power is used to check if it equals 1 modulo n.
I had to use BigInteger because of precision issues.
Usage
public static void main(String[] args) {
    Carmichael c = new Carmichael();
    System.out.println(c.c(3)); // prints 2
}

Ungolfed
// returns the BigInteger representation of the given interger
BigInteger B(int i) {
    return new BigInteger(""+i);
}
// for a given integer it returns the result of the carmichael function again as interger
// so the return value cannot be larger
int c(int... k) {
    int n = k[0];
    // iterate k[0] until for all co-primes this is true: (x^n) mod n == 1, if n==1 skip the loop
    for (k[0]=1;n > 1 && !java.util.stream.IntStream.range(0, n)
                .filter(i -> B(n).gcd(B(i)).equals(B(1)))
                .allMatch(x -> B((int) x).modPow(B(k[0]), B(n)).equals(B(1)));k[0]++);
    return k[0];
}

Any suggestions to golf it more are welcome :-)
Update

No elements outside the functions that keep the state
Followed Olivier Grégoire's advice and saved 1 byte from B()
Removed the k() method and p (co-primes) Set.
Removed not required casting to int.
Added varags and use for instead of while.

Can you have an ungolfed version (with linebreaks, comments here & there, etc.)

@OldBunny2800: Yeah, sure. However, I'll do it later today because now I am busy!

@OldBunny2800: I added an ungolfed version :-)

Hmmm... I'm not sure if this counts as it's neither a function nor a program. If it's a function, there are elements outside of it that keep the state, making it a de facto method (function is pure input->output without external state), if it's a program, the whole main method is missing. If my interpretations are incorrect, please tell me so! I think it's better to include k(int) in the loop as it's a one-liner and can be done. Plus, the constant O can be put in the c method as well. I guess you'll win bytes by doing so!

Concretely, while(n>1&&!p.stream().allMatch(x->B((int)x).modPow(B(k), B(n)).equals(O))) shaves bytes and fixes the issues I mentioned if you put the set and the constant back into the method. Also, you use O twice, replace by B(1) to shave bytes.

return new BigInteger(""+i); is shorter by one byte.

@OlivierGrégoire: Hey, thanks for the comments. I moved the "state" inside the methods. I don't think that while(n>1&&!p.stream().allMatch(x->B((int)x).modPow(B(k), B(n)).equals(O))) works as k variable has to be final. I am not sure that this can't be done in less code. I'll look into it with the first opportunity!

You are right. I'm sorry for that. k should be final, which is hard to do without putting it out (best case would be to write final int K = k; somewhere, hard given it's a parameter of a function, in the condition of a loop). Despite that, I totally disliked your answer because it was basically the initial algorithm, written in Java, and I was sure that we could do better in Java. So I answered it myself with another algorithm, much more "golfable", but much less efficient in terms of computer speed. I disliked, but +1'd still because you've made some pretty good work!

C++, 208 200 149 144 140 134 bytes
[](int n){int k=1,x,a,b,t,d=1;for(;d;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;t=b;a=t)b=a%b;for(t=1,b=k;b--;t=t*x%n);}return k;};

A port of my C implementation.
Try it on Ideone

Java, 165 163 158 152 143 bytes
int l(int n){int k=1,x,a,b,t,d=1;for(;d>0;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;b>0;b=a%b,a=t)t=b;for(t=b=1;b++<=k;t=t*x%n);}return k;}

Another port of my C implementation.
Try it on Ideone

C, 278 276 272 265 256 243 140 134 125 bytes
k,x,a,b,t,d;l(n){for(k=d=1;d;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;t=b;a=t)b=a%b;for(t=1,b=k;b--;t=t*x%n);}return k;}

This uses a slow modular exponentiation algorithm, computes the GCD too often and no longer leaks memory!
Ungolfed:
int gcd( int a, int b ) {
  int t;
  while( b ) {
    t = b;
    b = a%b;
    a = t;
  }
  return a;
}
int pw(int a,int b,int c){
  int t=1;
  for( int e=0; e<b; e++ ) {
    t=(t*a)%c;
  }
  return t;
}
int carmichael(int n) {
  int k = 1;
  for( ;; ) {
    int done = 1;
    for( int x=1; x<n; x++ ) {
      if( gcd(x,n)==1 && pw(x,k,n) != 1 ) {
        done = 0;
        k++;
      }
    }
    if( done ) break;
  }
  return k;
}

Try it on Ideone

Racket 218 bytes
(λ(n)(let((fl #f)(cl(for/list((i n) #:when(coprime? n i))i)))(for/sum((k(range 1 n))#:break fl)(set! fl #t)
(for((i(length cl))#:break(not fl))(when(not(= 1(modulo(expt(list-ref cl i)k)n)))(set! fl #f)))(if fl k 0))))

Ungolfed version:
(require math)
(define f
  (λ(n)
    (let ((fl #f)
          (cl (for/list ((i n) #:when (coprime? n i))
                i)))
             (for/sum ((k (range 1 n)) #:break fl)
               (set! fl #t)
               (for ((i (length cl)) #:break (not fl))
                 (when (not (= 1 (modulo (expt (list-ref cl i) k) n)))
                   (set! fl #f)))
               (if fl k 0)))))

Testing:
(f 2)
(f 3)
(f 10)
(f 35)
(f 101)
(f 530)
(f 3010)
(f 6511)
(f 10000)

Output:
1
2
4
12
100
52
84
3056
500

Axiom 129 bytes
c(n)==(r:=[x for x in 1..n|gcd(x,n)=1];(v,k):=(1,1);repeat(for a in r repeat(v:=powmod(a,k,n);v~=1=>break);v<=1=>break;k:=k+1);k)

less golfed
cml(n)==
 r:=[x for x in 1..n|gcd(x,n)=1];(v,k):=(1,1)
 repeat
   for a in r repeat(v:=powmod(a,k,n);v~=1=>break)
   v<=1=>break
   k:=k+1
 k

results
(3) -> [i,c(i)] for i in [1,2,3,10,35,101,530,3010,6511,10000]
   Compiling function c with type PositiveInteger -> PositiveInteger

   (3)
   [[1,1], [2,1], [3,2], [10,4], [35,12], [101,100], [530,52], [3010,84],
    [6511,3056], [10000,500]]
                                             Type: Tuple List PositiveInteger

source: Stack Exchange

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

sort: votes


text:
Words -> City Skyline
The challenge
Your program or function will accept a single string input from STDIN or a function parameter. You can assume the input will contain only alphabetic characters (a-zA-Z), spaces, and full stops. Input is case insensitive, so you should treat 'a' exactly the same as you would treat 'A'.
For each character in the string, you will output a representation of a building as per the following specification.
Each building must have a roof, designated by an underscore on the top line then a slash, space, backslash on the second line.
 _
/ \

You will then have a number of floors, matching the letter number (a=1, b=2, c=3 etc.) which are represented by a wall (|) on each side and a space in the middle. The bottom floor (and only the bottom floor) should have a foundation, which is an underscore between the walls. Like this...
|_|

So for example, 'b' would look like this
 _
/ \
| |
|_|

Now, we know that very tall, narrow buildings cannot stand and must get wider at the base, so no building can stand more than three storeys high without some additional support. So every three levels (no less) you should add a 'widening layer'. The widening layer consists of a slash and backslash directly above the walls of the section below it, and the section below should be two spaces wider than the section above. The extra layer does not count towards the height of the building.
Buildings should not overlap but should not have any unnecessary spaces between them, and the ground is always flat so all buildings should have their base on the same level.
For example, 'abcdefga' will look like this.
                           _
                          / \
                     _    | |
                _   / \   | |
           _   / \  | |   | |
          / \  | |  | |  /   \
       _  | |  | |  | |  |   |
    _ / \ | |  | | /   \ |   |
 _ / \| | | | /   \|   | |   |  _
/ \| || |/   \|   ||   |/     \/ \
|_||_||_||___||___||___||_____||_|

Spaces in the string input should be represented by a double space.
Full stops in the string input should be represented by rubble like this.
/\/\

Further examples
Input = Hello world.
Output =
                                                   _
                                                  / \
                                                  | |
                                                  | |
                                                  | |
                                                 /   \
                                                 |   |
                                                 |   |                       _
                                                 |   |                      / \
                                                /     \                     | |
                                                |     |                     | |
                                   _            |     |          _          | |
                                  / \           |     |         / \        /   \
                                  | |          /       \        | |        |   |
                                  | |          |       |        | |        |   |
                _        _        | |          |       |        | |        |   |        _
               / \      / \      /   \         |       |       /   \      /     \      / \
               | |      | |      |   |        /         \      |   |      |     |      | |
               | |      | |      |   |        |         |      |   |      |     |      | |
               | |      | |      |   |        |         |      |   |      |     |      | |
   _          /   \    /   \    /     \       |         |     /     \    /       \    /   \
  / \         |   |    |   |    |     |      /           \    |     |    |       |    |   |
  | |         |   |    |   |    |     |      |           |    |     |    |       |    |   |
  | |         |   |    |   |    |     |      |           |    |     |    |       |    |   |
  | |    _   /     \  /     \  /       \     |           |   /       \  /         \  /     \
 /   \  / \  |     |  |     |  |       |    /             \  |       |  |         |  |     |   _
 |   |  | |  |     |  |     |  |       |    |             |  |       |  |         |  |     |  / \
 |   |  | |  |     |  |     |  |       |    |             |  |       |  |         |  |     |  | |
 |   |  | | /       \/       \/         \   |             | /         \/           \/       \ | |
/     \/   \|       ||       ||         |  /               \|         ||           ||       | | |
|     ||   ||       ||       ||         |  |               ||         ||           ||       |/   \
|_____||___||_______||_______||_________|  |_______________||_________||___________||_______||___|/\/\

Input = lorem ipsum
                                                                                _
                                                                                / \
                                                                              _             | |
                                                                             / \            | |
                          _                                                  | |            | |
                         / \                                                 | |           /   \
                         | |                                    _            | |           |   |
                         | |                                   / \          /   \          |   |
              _          | |                                   | |          |   |          |   |
             / \        /   \                                  | |          |   |         /     \
             | |        |   |              _                   | |          |   |         |     |         _
             | |        |   |             / \                 /   \        /     \        |     |        / \
    _        | |        |   |             | |                 |   |        |     |        |     |        | |
   / \      /   \      /     \            | |                 |   |        |     |       /       \       | |
   | |      |   |      |     |            | |                 |   |        |     |       |       |       | |
   | |      |   |      |     |           /   \               /     \      /       \      |       |      /   \
   | |      |   |      |     |           |   |        _      |     |      |       |      |       |      |   |
  /   \    /     \    /       \          |   |       / \     |     |      |       |     /         \     |   |
  |   |    |     |    |       |          |   |       | |     |     |      |       |     |         |     |   |
  |   |    |     |    |       |         /     \      | |    /       \    /         \    |         |    /     \
  |   |    |     |    |       |         |     |      | |    |       |    |         |    |         |    |     |
 /     \  /       \  /         \   _    |     |     /   \   |       |    |         |   /           \   |     |
 |     |  |       |  |         |  / \   |     |     |   |   |       |    |         |   |           |   |     |
 |     |  |       |  |         |  | |  /       \    |   |  /         \  /           \  |           |  /       \
 |     |  |       |  |         |  | |  |       |    |   |  |         |  |           |  |           |  |       |
/       \/         \/           \ | |  |       |   /     \ |         |  |           | /             \ |       |
|       ||         ||           |/   \ |       |   |     | |         |  |           | |             | |       |
|       ||         ||           ||   |/         \  |     |/           \/             \|             |/         \
|_______||_________||___________||___||_________|  |_____||___________||_____________||_____________||_________|

Input = a.a.a.x.x.x.a.a.a
                             _                    _                    _
                            / \                  / \                  / \
                            | |                  | |                  | |
                            | |                  | |                  | |
                            | |                  | |                  | |
                           /   \                /   \                /   \
                           |   |                |   |                |   |
                           |   |                |   |                |   |
                           |   |                |   |                |   |
                          /     \              /     \              /     \
                          |     |              |     |              |     |
                          |     |              |     |              |     |
                          |     |              |     |              |     |
                         /       \            /       \            /       \
                         |       |            |       |            |       |
                         |       |            |       |            |       |
                         |       |            |       |            |       |
                        /         \          /         \          /         \
                        |         |          |         |          |         |
                        |         |          |         |          |         |
                        |         |          |         |          |         |
                       /           \        /           \        /           \
                       |           |        |           |        |           |
                       |           |        |           |        |           |
                       |           |        |           |        |           |
                      /             \      /             \      /             \
                      |             |      |             |      |             |
                      |             |      |             |      |             |
                      |             |      |             |      |             |
                     /               \    /               \    /               \
 _      _      _     |               |    |               |    |               |     _      _      _
/ \    / \    / \    |               |    |               |    |               |    / \    / \    / \
|_|/\/\|_|/\/\|_|/\/\|_______________|/\/\|_______________|/\/\|_______________|/\/\|_|/\/\|_|/\/\|_|

Rules

Of course this is code golf, lowest score in bytes wins
Standard loophole rules apply
Any number of additional blank lines before or after the output are allowed
You can choose to output the entire result in one string or offer the output as an array where each element represents one line of output, or send to STDOUT

Note
This is my first post to PPCG, so please go easy on me. It's been through the sandbox. Any negative points or possible improvements please post as a comment and I'll do what I can

Converting [a,z] and [A,Z] to [1,26] seems like a pointless requirement. It would be much better to just use a list integers as input (having 0 be the input for rubble). Also, posting your challenge after it's been in the Sandbox for only 21 hours, without waiting to get any votes or feedback from more than one user, does not count as it having "been through the sandbox". It's recommended to leave challenges in the Sandbox for 48-72 hours at the minimum, to give people plenty of time to review them.

My apologies, I read as many guidelines as I could but I saw no recommendation for the time I should wait. I took the lack of comments as a sign that nobody had much to say about it, as it seems a fairly active board. I clearly misread the situation

Reminds me of this. Nice first challenge, but I suggest you consider changing the [a,z],[1.26] parts the Mego mentioned. Having it optional is often the best (unless it's a key part of the challenge (it's not here).

I will say, this is a very nice first challenge. Welcome to the site!

I can understand the point about the a-z mapping to integers. It made sense in the first iteration of the challenge but since editing for clarity and brevity (there was a backstory which I have removed) the letters are no longer relevant. I will edit appropriately as soon as possible

I like the letters. They give opportunity for nice input. May I also build houses up from the ground (i.e. putting a narrowing layer after every three storeys) instead of down from roof?

Since this question is primarily about the output, I would indeed suggest using an input that is a choice. So if someone prefers a-z and . like yourself they can, but if someone prefers 0-25 and * instead then that is also valid input. As long as there is something for all 26 tower lengths (a-z, A-Z, 0-25, 1-26, etc.) and something for the rubble (., *, _, etc.) it doesn't change the challenge itself of outputting the towers. I must say it's a nice first challenge and good that you've used the Sandbox! Although next time 72+ hours. :) +1 and welcome to PPCG!

@KevinCruijssen: If numbers, I´d suggest 0 for blank (see Hello world. and lorem ipsum examples), 1 to 26 for houses, something else for rubble.

Are leading newlines allowed?

I prefer a-z, space, period, personally.

Given the time it's taken me to get round to reviewing the requirements I think it would be a bit unfair on those who have already attempted it to move the goalposts now. As was pointed out, the conversion to integer is simple enough and allows for some nicer and more meaningful inputs. Anyone wanting to take an input as an integer is welcome to but I'd suggest such an entry should be non-competing

@titus yes to both of your questions, these both fall within the guidelines

These look like multi-stage rockets from Kerbal Space Program.

JavaScript (ES6), 330 326 ... 315 309 bytes
Builds the ASCII art recursively, starting with the bottom floor and applying several regular expressions between each stage:
(a,l,R=(E,b)=>E.split`:`.map((e,i)=>l=(l||a).replace(RegExp(e,'g'),b?b.split`:`[i]:n=>(x=(n.charCodeAt()-65)%32)<0?x+1?'/y/y':n+n:x%3+'_'.repeat((x/3<<1)+1)+0)))=>(L=l)?(R('/y:_:/xy:1:2:/xx(x+)y:0(x+)0:3','  :x: _ :3:1: 2$10 :/$1y:0'),L==l?(l=a.join`
`,R('\\d:x:y','|: :\\'),l):f([l].concat(a),l)):f(R('.'),l)

How it works
1) Bottom floor
We start by translating the input string into a bottom floor such as:
"ab cd.df.hcab"  -->  "0_01_0  2_00___0/y/y0___02___0/y/y1_____02_00_01_0"

where:

y is a shorter alias for the backslash (which requires escaping)
The digit (0, 1 or 2) just before a sequence of _ is the left wall of the building. It represents the number of walls that must be placed above it before the next 'widening layer'.
The digit after a sequence of _ is the right wall of the building and is always set to 0.

2) Regular expressions applied between each stage
The recursive process consists of applying 9 replacements on the previous floor, using the following regular expressions:

/\/y/g => "  " (remove the rubble)
/_/g => "x" (replace the foundation or the top of the building with a solid block)
/\/xy/g => " _ " (replace the last widening layer with the top of the building)
/1/g => "3" (temporarily replace 1 with 3 -- see last step)
/2/g => "1" (replace 2 with 1)
/\/xx(x+)y/g => " 2$10 " (replace a widening layer with a new, narrower wall)
/0(x+)0/g => "/$1y" (replace the top of the wall with a widening layer)
/3/g => "0" (replace 3 with 0)

For instance, here are the successive transformations of 2___0 (bottom floor generated by a 'f'):
"2___0" > "1xxx0" > "0xxx0" > "/xxxy" > " 2x0 " > " 1x0 " > " 0x0 " > " /xy " > "  _  "

                                                                                _
                                                                        /xy       /xy
                                                              0x0       0x0       0x0
                                                    1x0       1x0       1x0       1x0
                                          2x0       2x0       2x0       2x0       2x0
                               /xxxy     /xxxy     /xxxy     /xxxy     /xxxy     /xxxy
                     0xxx0     0xxx0     0xxx0     0xxx0     0xxx0     0xxx0     0xxx0
           1xxx0     1xxx0     1xxx0     1xxx0     1xxx0     1xxx0     1xxx0     1xxx0
 2___0     2___0     2___0     2___0     2___0     2___0     2___0     2___0     2___0

NB: The top of the building is then replaced by a x. This is not shown in the above diagram.
3) Regular expressions applied to the final result
The recursion stops when there's nothing more to replace, which means that we are beyond the top of the highest building.
We now need to clean up everything with yet another few regular expressions:

/\d/g => "|" (replace digits with pipes)
/x/g => " " (replace solid blocks with spaces)
/y/g => "\" (replace y with backslashes)

For instance:
  _            _
 /xy          / \
 0x0          | |
 1x0          | |
 2x0   -->    | |
/xxxy        /   \
0xxx0        |   |
1xxx0        |   |
2___0        |___|

Demo

let f =

(a,l,R=(E,b)=>E.split`:`.map((e,i)=>l=(l||a).replace(RegExp(e,'g'),b?b.split`:`[i]:n=>(x=(n.charCodeAt()-65)%32)<0?x+1?'/y/y':n+n:x%3+'_'.repeat((x/3<<1)+1)+0)))=>(L=l)?(R('/y:_:/xy:1:2:/xx(x+)y:0(x+)0:3','  :x: _ :3:1: 2$10 :/$1y:0'),L==l?(l=a.join`
`,R('\\d:x:y','|: :\\'),l):f([l].concat(a),l)):f(R('.'),l)

console.log(f('ab cd.df.hcab'));

Contributors:
4 bytes saved thanks to Hedi
8 bytes saved thanks to Not that Charles

Anyone wanting to take an input as an integer is welcome to but I'd suggest such an entry should be non-competing

@mbomb007 - This is fixed. My current optimizations do not compensate for the the cost of the infamous .charCodeAt(), though.

You don't need new  in new RegExp(e,'g')

I like this approach a lot.  Some ideas that may help:  1. use a char like y that requires no escaping for your forward slash. 2. if you use _ for the ground floor, you can still differentiate the top with the regex: /_ /.

You also might be able to save space if you use an ascii point 99 above the baseline, so then your replace function just subtracts 99 from each char code.  That might be more expensive than what you have, though.

@NotthatCharles - Nice catch on the foundation! Replacing the top of the building with a x is perfectly fine, so we don't need an extra regex -- and we can actually remove one. About the forward slash: it doesn't require escaping because the regular expressions are stored in strings.

Oh!  One bug!  Your output only shows one space, not two, for a   in the input.

@NotthatCharles - I actually never noticed the "double space" rule. ;) This is fixed.

I think you can use parseInt(x, 36) to save a few bytes?

PHP, 386 376 367 364 362 358 356 bytes
first approach; may still be golfable.
foreach(str_split($argv[1])as$c)for($n=28,$w='.'!=$c?1+2*ceil(1/3*$n=31&ord($c)):4,$p=$y=0;$y<36;){$s=str_pad("",$w,$y||!$n?" ":_);if($n>26&&!$y){$s="/\\/\\";$n=-1;}elseif($n-->0){$s[$p]=$s[$w-$p-1]="|";if($n%3<1){$o[$y++].=$s;$s=str_pad("",$w);$s[$p]="/";$s[$w-++$p]="\\";}}$o[$y++].=$s;if(!$n)$o[$y++].=str_pad(_,$w," ",2);}for($y=36;$y--;)echo"$o[$y]
";

PHP, 366 362 361 360 357 bytes
similar approach with a subfunction:
function a($p,$r){global$o,$w,$y;$o[$y++].=str_pad(str_pad($r[0],2*$p,$r[1]).$r[2],$w," ",2);}foreach(str_split($argv[1])as$i=>$c)for($n=28,$w='.'!=$c?1+2*$p=ceil(1/3*$n=31&ord($c)):$p=4,$y=0;$y<36;)if($n>26&&!$y)$o[$n=$y++].="/\\/\\";elseif($n-->0){a($p,$y?"| |":"|_|");if($n%3<1)a($p--,"/ \\");if(!$n)a(1," _");}else a(0,"");for($y=36;$y--;)echo"$o[$y]
";

breakdown for the second approach
function a($p,$r)
{
    global$o,$w,$y;
    $o[$y++].=                  // 3. add result to current line, increase line counter
        str_pad(                // 2. pad ...
        str_pad($r[0],2*$p,$r[1]).$r[2]     // 1. A + inner width(=2*$p-1) times B + C
        ,$w," ",2);             // ... to $w with blanks on both sides # 2==STR_PAD_BOTH
}

foreach(str_split($argv[1])as$i=>$c)
    for(
    $n=28,
    $w='.'!=$c                          // $w=total width
        ?1+2*$p=ceil(1/3*$n=31&ord($c)) // $n=storey count, $p=(inner width+1)/2
        :$p=4                           // $n=28, $p <= $w=4 for rubble
    ,
    $y=0;$y<36;)                        // $y=line counter
        if($n>26&&!$y)
            $o[$n=$y++].="/\\/\\";      // bottom line=rubble, $n=0
        elseif($n-->0)
        {
            a($p,$y?"| |":"|_|");       // add storey
            if($n%3<1)a($p--,"/ \\");   // add widening layer/roof
            if(!$n)a(1," _");           // add roof top
        }
        else
            a(0,"");                    // idk why str_pad doesn´t yield a warning here

for($y=36;$y--;)if($s=rtrim($o[$y]))echo"$s\n"; // output

+16 bytes if leading newlines are not allowed:
Replace echo"$o[$y]\n; with if($s=rtrim($o[$y]))echo"$s\n";.
-3 bytes for any of ;<=>?[\]^_{|}~ as rubble:
Replace 1) ($n=31&ord($c)) with $n, 2) $n=28,$w='.'!=$c with ($n=31&ord($c))<27 and 3) 4 with ($n=28)/7.
Another -8 for >, ^ or ~ as rubble: Undo 3)

if(!$n){$o[$y++].=str_pad(_,$w," ",2);} -2 Bytes for the brackets

and output can be done 3 bytes shorter: for($y=36;$y--;)echo"$o[$y]\n";; but I have a new approach that saves an other 2 bytes.

http://www.php.net/manual/en/functions.anonymous.php for the second approach `function a($p,$r)use($o,$w,$y)' instead of global

@JörgHülsermann: use only works for anonymous functions. it would save 2 bytes; but I would have to store that function in a variable $a= instead of giving it a name (+3 bytes) and add a $ to each of the four calls.

Perl, 147 146 bytes
Includes +1 for -p
Run with input on STDIN, e.g.
citysky.pl <<< " abcdefgxyz."

citysky.pl:
#!/usr/bin/perl -p
s%.%@{[map chr~-ord(lc$&)*4/3-4*(abs||-9),-9..9]}%g;y/M\xa248
A|-\xc6\0-\xff/MA||
A}-\xc6A/d,$a=(lc$a).$_ for($_)x36;*_=a;s/\x9f.*?\K\x9f/\xa3/g;y%A\xc6\x9f-\xa3\x0b-\xff%__/|||\\ %

Works as shown, but replace the \xhh escapes by their literal value to get the claimed score. You can do that using this commandline:
perl -0pi -e 's/\\x(..)/chr hex $1/eg;s/\n$//' citysky.pl

I haven't really explored any other approaches, so this may be very beatable...

Pyth, 93 79 bytes
K"/\\"j_.tsm?hJxGdC_m.[hyNk\ +\_mj*hy/k4?nkJ\ \_?%k4"||"Kh=+J=Nh/J3[F*2|@d;Krz0

Try it online. Test suite.
Explanation
I hid this away by default since it's way too long.

<ul type="disc"><li>Initialize <code>K</code> to <code>"/\"</code>.</li><li>Lowercase (<code>r</code>…<code>0</code>) the input (<code>z</code>).</li><li>For each (<code>m</code>) character <code>d</code> in the lowercase input:</li><ul type="disc"><li>Find the index (<code>x</code>) of the character (<code>d</code>) in the alphabet (<code>G</code>). This results in a number 0-25 for the letters and -1 for anything else. Save the index to <code>J</code>.</li><li>Add one (<code>h</code>). This results in a positive number for the letters and 0 for anything else.</li><li>If the result was nonzero (<code>?</code>):</li><ul type="disc"><li>Int-divide (<code>/</code>) <code>J</code> by <code>3</code> and increment (<code>h</code>) and save (<code>=</code>) the result to <code>N</code>.</li><li>Increment (<code>=+</code>) <code>J</code> by that amount.</li><li>Add one (<code>h</code>). This yields the height of the house excluding the roof.</li><li>For each (<code>m</code>) number <code>k</code> from 0 to result-1:</li><ul type="disc"><li>Take <code>" "</code> (<code>\ </code>) if (<code>?</code>) the number (<code>k</code>) is not equal to (<code>n</code>) <code>J</code>, otherwise take <code>"_"</code> (<code>\_</code>).</li><li>Int-divide (<code>/</code>) the number (<code>k</code>) by <code>4</code>, double (<code>y</code>) and add one (<code>h</code>).</li><li>Multiply the string by the number (<code>*</code>).</li><li>Take <code>"||"</code> if (<code>?</code>) the number (<code>k</code>) is not divisible by 4 (<code>%</code>…<code>4</code>), otherwise take the string in <code>K</code>.</li><li>Join (<code>j</code>) that string by the previous one. This puts the previous string in the middle.</li></ul><li>Prepend (<code>+</code>) a <code>"_"</code> (<code>\_</code>) to the resulting list to add the roof.</li><li>For each line <code>k</code> in the list:</li><ul type="disc"><li>Take <code>N</code>, double (<code>y</code>) and add one (<code>h</code>).</li><li>Pad (<code>.[</code>) the line (<code>k</code>) to that length with spaces (<code>\ </code>).</li></ul><li>We now have the rows for this one house. Reverse (<code>_</code>) and transpose (<code>C</code>) the result to get the reversed columns.</li></ul><li>If the result was zero (all the way up there):</li><ul type="disc"><li>Take the intersection (<code>@</code>) of the character (<code>d</code>) and <code>" "</code> (<code>;</code>). This yields an empty string for periods and a space for itself.</li><li>Logical OR (<code>|</code>) that with the string in <code>K</code>. This yields that string for periods and a space for itself.</li><li>Repeat that string (<code>*</code>) <code>2</code> times and cast to array (<code>[F</code>). This yields the (reversed) columns for spaces and periods.</li></ul></ul><li>Concatenate (<code>s</code>) the resulting lists. This yields the total reversed columns for the output.</li><li>Transpose, padding with spaces (<code>.t</code>), reverse (<code>_</code>) and join by newline (<code>j</code>). Implicitly print the output.</li></ul>

Haskell, 289 bytes
c?l=c++l++c
c%s=("|"?(drop 2(r s)>>c)):s
g 46=["/\\"?""]
g 32=["  "]
g x="_"%h(mod x 32)
h 1=["/ \\"," _ "]
h x=(" "%h(x-1))!x
v!x|mod x 3/=1=v|z<-'/':r v++"\\"=z:map(" "?)v
r v=v!!0>>" "
f t|l<-map(g.fromEnum)t,m<-maximum(map length l)-1=unlines[l>>= \x->(x++cycle[r x])!!i|i<-[m,m-1..0]]

Ruby, 245
->s{a=['']*36
w=' '
s.chars{|c|a[u=0]+=c<?!?w*2:c<?/?"/\\"*2:(h=c.upcase.ord-64
1.upto(1+h+=(h-1)/3){|t|u=[u,l=1+2*((f=h-t)/4)].max
a[t]+=w*(a[0].size-a[t].size)+(f<-1?w:f<0??_:(f%4<1?[?/,?\\]:[?|]*2)*(w*l)).center(u+2)}
"|#{?_*u}|")}
a.reverse}

You allow as many extra newlines as you want, so I'm taking liberty with that.  Aside from that, the process is as follows:

Initialize an output array a.
For each char:

if it's ' ', add   to a[0]
if it's '.', add /\/\ to a[0]
otherwise:

calculate the height (c.upcase.ord + (c.upcase.ord-1)/3)
for each row in a:

pad the row with whitespace. a[t]+=w*(a[0].size-a[t].size)
if we're one above h, center a _
else if we're above height, center a
else if we're below height, center |  | or /  \ of the proper width (1+2*((h-t)/4), depending on if h-t%4==0
add "|___|" of the right width to a[0]

return a.reverse

I bet I can get it smaller if I work out the math to avoid reverse

PHP, 297 bytes
foreach(str_split($argv[1])as$c)for($j=0,$h=ord($c)-64,$g=$h+$f=ceil($h/3),$w=$v=$h<0?$h<-18?2:4:2*$f+1;$j<36;$j++,$g--,$v-=$h>0&&$v>1?($g%4||!$j)?0*$n="|$s|":2+0*$n="/$s\\":$v+0*$n=['','_','',0,'/\/\\'][$v],$o[$j].=str_pad($n,$w,' ',2))$s=str_repeat($j?' ':'_',$v-2);krsort($o);echo join($o,'
');

A more readable version:
foreach (str_split($argv[1]) as $character) {
    for (
        $line = 0,
        $buildingHeight = ord($character) - 64,
        $floorsLeft = $buildingHeight + $supportFloors = ceil($buildingHeight / 3),
        $buildingWidth = $widthOnThisFloor = $buildingHeight < 0
            ? $buildingHeight < -18
                ? 2
                : 4
            : 2 * $supportFloors + 1;

        $line < 36;

        // The body of the for-loop is executed between these statements

        $line++,
        $floorsLeft--,
        $widthOnThisFloor -= $buildingHeight > 0 && $widthOnThisFloor > 1
            ? ($floorsLeft % 4 || !$line)
                ? 0 * $floorString = "|$middleSpacing|"
                : 2 + 0 * $floorString = "/$middleSpacing\\"
            : $widthOnThisFloor + 0 * $floorString = ['', '_', '', 0, '/\/\\'][$widthOnThisFloor],
        $outputArray[$line] .= str_pad($floorString, $buildingWidth, ' ', 2)
    ) {
        $middleSpacing = str_repeat($line ? ' ' : '_', $widthOnThisFloor - 2);
    }
}
krsort($outputArray);
echo join($outputArray, '
');

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


text:
Mutilating the Query
I know you've always thought about the trials and tribulations of experiencing the joys of life as a web proxy. Honestly, who hasn't? Today you're tasked with realizing this goal (at least a part of it). Website X gets a lot of traffic on the daily and is looking for a PaaS (clearly this refers to Proxy as a Service) because of the large number of users who insist on passing sensitive information via query parameters (users are silly). Your task is to remove any and all sensitive query parameters from the request before forwarding the request through to its original destination.
Input

A well-formed absolute HTTP URL that follows the URI grammar in RFC3986 Section 3.

You can assume there is no fragment
Brief format example where anything in square brackets denotes optional: http[s]://[user:pass@]host.name.com[:port]/[?param1=value1&param2=value2...]

A list of query parameters to be removed.

Output
The modified HTTP URL without the parameters defined in the input list.
Examples
http://example.com/ [foo]
> http://example.com/

http://example.com/?foo=bar []
> http://example.com/?foo=bar

http://example.com/ []
> http://example.com/

http://example.com/?foo=1&bar=2&baz=3 [foo,baz]
> http://example.com/?bar=2

http://example.com/?foo=1&bar=2&baz=3 [foo,bar,baz]
> http://example.com/

http://example.com/?foo&bar=2&baz= [foo,baz]
> http://example.com/?bar=2

http://example.com/?abc=1&def=2&baz=foo [foo,bar]
> http://example.com/?abc=1&def=2&baz=foo

http://example.com/?foobar=baz [foo]
> http://example.com/?foobar=baz

http://foo:foo@foo.com:8080/?foo=1&bar=foo [foo]
> http://foo:foo@foo.com:8080/?bar=foo

Scoring
This is code-golf, so the shortest answer (in bytes) wins.

Can I get the URL and the query parameters each on separate lines?

Can & appear anywhere other than between parameters?

also can e.g. the password contain a ?? Also should the order be kept like it was?

@Riley No. If & is part of a query parameter it should be correctly urlencoded as %26

@KarlKastor ? is a reserved character to denote the beginning of the query parameters. It will not appear in the query string unless it's urlencoded as %3F

@Poke and & can't be part of the name correct? For example: http://exam&ple.com/

@Riley correct.

@seshoumara Input is not strictly a string and a list but you need to be able to support the absolute url and a list of query parameters of some sort.

Can the output contain the default port if it wasn't specified in the input? Eg if the input is http://example.com/ can the output be http://example.com:80/?

@milk As a web proxy you're trying to make as little impact as is required to the incoming request. If you do not receive a port in the url then your output should not have a port.

I repeat KarkKastor´s question: Can there be a ? in the password (or anywhere in URI except as delimiter for the query string)? The RFC does not mention that explicitly. (Or at least I could not find it; any time I browsed that.)

@Titus As to the RFC, you can find the pertinent section by searching for 3.4.  Query. On my reading, it says query strings can contain ? and /. As to this question, however, OP said in a previous comment, "? ... will not appear in the query string."

Apparently, http://foo:&foo=x@foo.com:8080/?foo=1&bar=foo is allowed by the RFC. This should break a bunch of the existing solutions. :D (The rule is userinfo can be expanded as unreserved or pct-escape or sub-delims, and sub-delims can have & and =)

GNU sed 98 96 88 80 77 74 69 59 54 (48 + 1 for -r) 49
:;s,(.+)(=[^&]*[& ]|&)(.*)\1,\3 ,
t;s,[?&]? .*,,

The list of parameters to remove are separated by spaces.
$ echo 'http://example.com/?foo=1&bar=2&baz=3 foo bar baz' | sed -rf sed.txt
http://example.com/

$ echo 'http://example.com/?foo&bar=2&baz= foo baz' | sed -rf sed.txt
http://example.com/?bar=2

$ echo 'http://example.com/' | sed -rf sed.txt
http://example.com/

In your current code edit, multiple tests from OP's question give a trailing & or ? character in the resulting URL.

@seshoumara I'm not sure how I missed that... Luckily it's only a 1 byte difference.

The 96, 77 and 59 byte code versions are not found in your edit history. Edit 7 title showed 10 bytes less compared to edit 6, but the code hadn't been changed. I'm nitpicking though, great golfing!

@seshoumara I think it combined some of the edits because they were minor (just deleting a few characters).

@seshoumara I guess it actually combined them because I made multiple edits within 5 minutes of each other.

JavaScript (ES6), 62 60 bytes

f=
(s,a,u=new URL(s))=>a.map(e=>u.searchParams.delete(e))&&''+u
;
s.value=document.URL;
<div oninput=o.textContent=f(s.value,a.value.split`\n`)><input id=s>
<textarea id=a></textarea>

Edit: Saved 2 bytes thanks to @Shaggy.

You can save 5 bytes by dropping the .href at the end.

@Shaggy That wouldn't return a string... I was assuming that wasn't allowed.

It depends how you output it. For example, if you alert it or use insert it into a (text) node, as you have, it will give you the href property of the object. If you log it to the console, though, it'll give you the full object. See this Fiddle.

@Shaggy Ah, so I can definitely save 2 bytes by stringifying it, thanks.

PHP, 90 Bytes
<?=trim(preg_replace("#(?<=\?|&)(".join("|",$_GET[r]).")(=.*)?(&|$)#U","",$_GET[u]),"?&");

-11 Bytes if ? or & is allowed at the end
Previous Version 140 Bytes
<?=substr($u=$_GET[u],0,strpos($u,"?")+!!$j=join("&",preg_grep("#^(".join("|",$_GET[r]).")(=|$)#",explode("&",parse_url($u)[query]),1))).$j;

+2 bytes: The alternatives must be parenthesized, or ^/(.*|$) will be part of the first/last alternative.

-2 bytes: remove .*. or replace (=.*|$) with \b (-5).

Your regexp will look like #^foo|bar(=.*|$)# which is identical to #(^foo)|(bar=.*|bar$))#. But it should be #(foo|bar)(=.*|$)#.

@Titus You are right my fault

nice! I didn´t think of assertions; that´s why I fell back to array_map (and I was surprised how short it can turn out).

P.S.: Very nice use of trim. I totally forgot about that!

C#, 377 336 330 328 bytes (173 alt)
string n(string u,string[]r){var s=u.Split('?');if(s.Length<2)return u;var a=s[1].Contains("&")?s[1].Split('&'):new string[]{s[1]};int B=a.Length,i=0,C=i,c=B;for(;i0?"?":"";for(i=0;i<a.Length;i++)if(a[i]!=""){t+=a[i];C++;if(C!=c)t+="&";}return t;}

Ungolfed full program:
using System;
class a
{
    static void Main()
    {
        string input = Console.ReadLine();
        string url = input.Split(' ')[0];
        string r = input.Split(' ')[1];
        r = r.Replace("[", "").Replace("]","");
        string[] remove = r.Split(',');
        a b = new a();
        Console.WriteLine(b.n(url, remove));
    }
    string n(string u,string[]r)
    {
        var s=u.Split('?');
        if(s.Length<2)return u;
        var a=s[1].Contains("&")?s[1].Split('&'):new string[]{s[1]};
        int B=a.Length,i=0,C=i,c=B;
        for(;i0?"?":"";
        for(i=0;i<a.Length;i++)
            if(a[i]!="")
            {
                t+=a[i];
                C++;
                if (C!=c)t+="&";
            }
        return t;
    }
}

Probably not very efficient, but it works I think.
Alternatively, there is a 173 byte solution using @Poke's method from Java.  Requires an import for Regex though, so probably can't be shorter.
using System.Text.RegularExpressions;string m(string a,string[]b){foreach(var c in b)a=Regex.Replace(a,$"(?<=[?&]){c}(=[^&]*)?(&|$)","");return Regex.Replace(a,"[?&]$","");}

Java 7, 127 bytes
String a(String a,String[]b){for(String c:b)a=a.replaceAll("(?<=[?&])"+c+"(=[^&]*)?(&|$)","");return a.replaceAll("[?&]$","");}

Explanation
String sanitize(String url, String[] params) {
    for (String param : params) {
        // please don't modify function parameters in real code
        url=url.replaceAll("(?<=[?&])" // Look for a leading ? or & but don't consume it
            + param                    // Consume the key of the query param (assuming key=value syntax)
            + "(=[^&]*)?"              // Consume the value of the query param if it exists
            + "(&|$)","");             // Consume the trailing & unless we're at the end of the url and replace with nothing
    }
    url = url.replaceAll("[?&]$",""); // If we remove all of the params then we'll have a trailing ? which needs to be removed
                                      // If we remove the last param only then we could have a trailing & which also needs to be removed
                                      // We will only run into one of these scenarios
    return url;
}

Ideone

This fails for me using your 4th, 5th, 6th, and 9th examples o.O.  I'm using Java 8 though, so that could be it.  Although tried the C# equivalent and it failed the same cases, so idunno.

Nevermind, messed up the way I was testing it.

PHP, 120 110 bytes
with preg_replace and array functions: (inspired by Jörg)
<?=preg_replace(array_map(function($s){return"#(\\?|&)$s(=.*)?(&|$)#U";},array_slice($argv,2)),"\1",$argv[1]);

save to file, call with php

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳


text:
Connect the pixels
Given a text like this:
# #### ## #
## #  ##  #
   ####  ##

Output the same text but by connecting the pixels with the characters ─│┌┐└┘├┤┬┴┼. If a pixel doesn't have any neighbours, don't change it.
So the output of the last text is:
│ ─┬── ┌─ │
└─ │  ┌┘  │
   └──┘  ─┘

You can take input as a boolean array.
The input will always contain at least 1 pixel.
You can count box-drawing chars as 1 byte.
You can assume the input is padded with spaces.

Test cases
## #
=>
── #

###
 #
=>
─┬─
 │

##### ##
 # #  #
########
=>
─┬─┬─ ┌─
 │ │  │
─┴─┴──┴─

 # #
#####
 # #
=>
 │ │
─┼─┼─
 │ │

# # # # #
 # # # #
# # # # #
 # # # #
# # # # #
=>
# # # # #
 # # # #
# # # # #
 # # # #
# # # # #

#####
#####
#####
#####
#####
=>
┌┬┬┬┐
├┼┼┼┤
├┼┼┼┤
├┼┼┼┤
└┴┴┴┘

Since this is code-golf, the shortest code wins.

Must I use the hash character as a pixel? Can I receive input as a boolean array?

Can there be trailing space(s )or newline(s)?

btw: -|r7LJE3TW+ is a suitable 1-byte-char replacement for the block characters.

Can wee use a different character, e.g. *?

Jelly, 60 52 51 50 49 48 bytes
ṖḤ0;+Ḋ×
“µ³Q~E!G⁸ṗṫ\’ḃ61+9471Ọ⁾# j
ZÑ€4×Z++Ñ€ị¢Y

Saved a byte thanks to @Dennis.
The input is a boolean array of 1's and 0's. Iterates over each column and each row converting the head and tail of each infix of size 3 from a pair of binary digits to a decimal, and multiplies that with the center of each infix. Then it sums it with itself to find the index into '#───│┌┐┬│└┘┴│├┤┼ '.
Try it online! (case 2) (case 3) (case 4)
Explanation
This relies on the same idea as my answer in J but instead of processing on each 3x3 subarray, I process over each row and each column while still obtaining the same table of indices.
Over half of the bytes are spent generating the list of box characters '#───│┌┐┬│└┘┴│├┤┼ '. String literals start with “ in Jelly and have different meanings depending on their terminator. Here the terminator ’ means that the string will be parsed as the code points of each character according to the Jelly code page, and convert from a list of base 250 digits to a decimal.
“µ³Q~E!G⁸ṗṫ\’ => 10041542192416299030874093
(bijective base 61) => [1, 1, 1, 3, 13, 17, 45, 3, 21, 25, 53, 3, 29, 37, 61]
(add 9471 and convert to char) => '───│┌┐┬│└┘┴│├┤┼'

Then convert that decimal to a list of digits in bijective base 61 and increment each by 9471 to move it into the range of the box characters and convert each using Python's chr. Then prepend it with a character literal ”# and append a space ⁶.
ṖḤ0;+Ḋ×  Helper link - Input: 1d list A
Ṗ        Get all of A except the last value
 Ḥ       Double each value in it
  0;     Prepend a 0
    +    Add elementwise with
     Ḋ     All of A except the first value
      ×  Multiply elementwise by A

“µ³Q~E!G⁸ṗṫ\’ḃ61+9471Ọ⁾# j  Nilad. Represents '#───│┌┐┬│└┘┴│├┤┼ '
“µ³Q~E!G⁸ṗṫ\’               Get the code points of each char in the string and
                            convert from a list of base 250 digits to decimal
             ḃ61            Convert that to a list of digits in bijective base 61
                +9471       Add 9400 to each
                     Ọ      Convert from ordinals to chars, gets '───│┌┐┬│└┘┴│├┤┼'
                      ⁾#    A pair of chars ['#', ' ']
                         j  Join the pair using the box characters

ZÑ€4×Z++Ñ€ị¢Y  Input: 2d list M
Z              Transpose
 Ñ€            Apply the helper link to each row of the transpose (each column of M)
   4×          Multiply each by 4
     Z         Transpose
      +        Add elementwise with M
       +       Add elementwise with
        Ñ€       The helper link applied to each row of M
          ị¢   Use each result as an index to select into the nilad
            Y  Join using newlines
               Return and print implicitly

JavaScript (ES6), 155 121 103 102 characters

let f =

s=>s.replace(/#/g,(c,p)=>'#│─┘─└─┴││┐┤┌├┬┼'[t=x=>s[p+x]==c,8*t(w=s.search`
`+1)+4*t(1)+2*t(-1)+t(-w)])

console.log(f(
  '# #### ## #\n' +
  '## #  ##  #\n' +
  '   ####  ##'
));

Edit: saved 18 bytes with the help of ETHproductions
Edit: saved 1 byte by using the 1st parameter of replace() as '#'
How it works
We iterate on all # characters found in the input string. For each of them, we test whether its neighbors are also # characters using the t() function:
t = x => s[p + x] == c  // where c = '#'

The parameter x of the t() function is the offset of the neighbor with respect to the current position p. We use -1/+1 to test left/right neighbors and -w/+w for top/bottom neighbors (where w is the width of a row, i.e. the position of the first line-break + 1).
Each neighbor is assigned a different weight (1, 2, 4 or 8) according to the following compass:
  1
2 + 4
  8

Each weight combination leads to unique value in [ 0 .. 15 ]. For instance, if both the neighbor at the top and the neighbor on the right are set, the sum will be 1 + 4 = 5, which is translated into └ using this table:
00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15
#  │  ─  ┘  ─  └  ─  ┴  │  │  ┐  ┤  ┌  ├  ┬  ┼

Therefore, '#│─┘─└─┴││┐┤┌├┬┼'[weight_sum] leads to the expected character.

Ha, we had basically the same idea ;)

@ETHproductions - Pretty much so. ^^

Really, really nice technique there. You've solidly out-golfed me :)

You can save 2 bytes like so: s=>(w=s[0].length+1,s=s.join`\n`).replace(/#/g,(_,p)=>'#│─┘─└─┴││┐┤┌├┬┼'[t=x=>s[p+x]>' ',t(-w)+2*t(-1)+4*t(1)+8*t(w)])

And it's actually far shorter to switch back to a multiline string: s=>s.replace(/#/g,(_,p)=>'#│─┘─└─┴││┐┤┌├┬┼'[t=x=>s[p+x]>' ',t(-w)+2*t(-1)+4*t(1)+8*t(w)],w=s.indexOf`\n`+1)

@ETHproductions - I had the same idea while including your first optimization. ;) Using search and embedding the declaration of w in the first call to t() saves a few more bytes.

J, 82 72 66 bytes
(ucp' #───│┌┐┬│└┘┴│├┤┼'){~]+]*3 3((2#.1 7 3 5{,);._3)0,.~0,.0,~0,]

The input is a boolean table of 1's and 0's. The rules state that the box characters each count as one byte, not three, and that has been applied here.
Usage
   f =: (ucp' #───│┌┐┬│└┘┴│├┤┼'){~]+]*3 3((2#.1 7 3 5{,);._3)0,.~0,.0,~0,]
   m =: 1 0 1 1 1 1 0 1 1 0 1 , 1 1 0 1 0 0 1 1 0 0 1 ,: 0 0 0 1 1 1 1 0 0 1 1
   m { ' #'
# #### ## #
## #  ##  #
   ####  ##
   f m
│ ─┬── ┌─ │
└─ │  ┌┘  │
   └──┘  ─┘
   ' #' {~ m =: 5 5 $ 1
   f m
┌┬┬┬┐
├┼┼┼┤
├┼┼┼┤
├┼┼┼┤
└┴┴┴┘
   ' #' {~ m =: 5 9 $ 1 0
# # # # #
 # # # #
# # # # #
 # # # #
# # # # #
   f m
# # # # #
 # # # #
# # # # #
 # # # #
# # # # #

Explanation
First the input is padded with 0's on all sides.
   ] m =: 1 0 1 1 1 1 0 1 1 0 1 , 1 1 0 1 0 0 1 1 0 0 1 ,: 0 0 0 1 1 1 1 0 0 1 1
1 0 1 1 1 1 0 1 1 0 1
1 1 0 1 0 0 1 1 0 0 1
0 0 0 1 1 1 1 0 0 1 1
   (0,.~0,.0,~0,]) m
0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 1 1 1 1 0 1 1 0 1 0
0 1 1 0 1 0 0 1 1 0 0 1 0
0 0 0 0 1 1 1 1 0 0 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0

Then each subarray of size 3 is selected
   3 3 <;._3 (0,.~0,.0,~0,]) m
┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│
│0 1 0│1 0 1│0 1 1│1 1 1│1 1 1│1 1 0│1 0 1│0 1 1│1 1 0│1 0 1│0 1 0│
│0 1 1│1 1 0│1 0 1│0 1 0│1 0 0│0 0 1│0 1 1│1 1 0│1 0 0│0 0 1│0 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│0 1 0│1 0 1│0 1 1│1 1 1│1 1 1│1 1 0│1 0 1│0 1 1│1 1 0│1 0 1│0 1 0│
│0 1 1│1 1 0│1 0 1│0 1 0│1 0 0│0 0 1│0 1 1│1 1 0│1 0 0│0 0 1│0 1 0│
│0 0 0│0 0 0│0 0 1│0 1 1│1 1 1│1 1 1│1 1 0│1 0 0│0 0 1│0 1 1│1 1 0│
├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
│0 1 1│1 1 0│1 0 1│0 1 0│1 0 0│0 0 1│0 1 1│1 1 0│1 0 0│0 0 1│0 1 0│
│0 0 0│0 0 0│0 0 1│0 1 1│1 1 1│1 1 1│1 1 0│1 0 0│0 0 1│0 1 1│1 1 0│
│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│0 0 0│
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘

Then only 5 of the values in each subarray is considered
┌───┐
│xAx│
│CED│
│xBx│
└───┘

The values ABCD are selected by flattening each subarray and selecting at indices 1 7 3 5. Those values are multiplied by E which is at index 4. It is then converted from a list of binary digits to a decimal, and incremented by E. The x values are not needed.
   3 3 (4&{([+2#.*)1 7 3 5&{)@,;._3 (0,.~0,.0,~0,]) m
 5 0 2  8 4 3  0  6 3 0  5
10 3 0 13 0 0  6 11 0 0 13
 0 0 0 10 4 4 11  0 0 2 11

This is used as an index to select which character to draw according to the table below (reordered a bit for golfing). The last column matches the output value of each subarray to a box character.
 0  (space)  0
 1  #        1
 2  ┌        6
 3  ┬        8
 4  ┐        7
 5  ├        14
 6  ┼        16
 7  ┤        15
 8  └        10
 9  ┴        12
10  ┘        11
11  │        5, 9, 13
12  ─        2, 3, 4

Also, in J, the string ' #───│┌┐┬│└┘┴│├┤┼' uses 8-bit characters making it have a length of 47 (for each byte) for the 17 characters needed. The command ucp converts it to 16-bit characters which allows it to be length 17.

Python 2.7, 318 315 bytes (270 267 chars)
I'm sure this can be golfed further (particularly I'd love to get rid of that annoying first-line comment) but here's my entry:
#encoding:utf-8
f=lambda t:(lambda l,s:'\n'.join(''.join((u'┼├┤│┬┌┐│┴└┘│───#'[(s==l[i][j-1])+2*(s==l[i][j+1])+4*(i<1 or s==l[i-1][j])+8*(i>len(l)-2 or s==l[i+1][j])],s)[s==l[i][j]]for j in range(len(l[i])-1))for i in range(len(l))))([l+' 'for l in t.split('\n')],' ')

Here's an explanation of how the whole thing works:
#encoding:utf-8 # Dammit, Python. This adds an extra 16 bytes!
f=lambda t:( # main lambda function
    lambda l,s: # inner lambda so we can pass it "local constants" (see last line)
        '\n'.join( # join each line
            ''.join( # join each char within the line
                (u'┼├┤│┬┌┐│┴└┘│───#'[ # string of all possible characters, indexed by binary 0-15 based on adjacent chars
                    (s==l[i][j-1])+ # left
                    2*(s==l[i][j+1])+ # right
                    4*(i<1 or s==l[i-1][j])+ # up ('i<1' just yields zero in case this is the first line, so that we don't get index problems)
                    8*(i>len(l)-2 or s==l[i+1][j])], # down ('i>len(l)-2' is same as above)
                s)[s==l[i][j]] # if original is space, choose space, else choose the previously chosen box-drawing char
                for j in range(len(l[i])-1)) # do this process for each char (excluding last, which is a space)
            for i in range(len(l))) # do this for each line
    )([l+' ' for l in t.split('\n')],' ') # call the inner lambda with two parameters: first, the text split into lines; second, a space char (actually makes code shorter)

EDIT: Removed some spaces before for ... in ...

Using Python 3 instead should solve your Unicode encoding problem, I think...

JavaScript (ES6), 150 139 133 131 chars
a=>a.map((q,y)=>q.replace(/#/g,(c,x)=>"#│─┘─└─┴││┐┤┌├┬┼"[g=(X,Y=0)=>(a[Y+y]||[])[X+x]==c,g(0,1)*8+g(1)*4+g(-1)*2+g(0,-1)])).join`
`

Takes input as an array of strings, e.g. f(["###", " # "]).
Test snippet

f=a=>a.map((q,y)=>q.replace(/#/g,(c,x)=>"#│─┘─└─┴││┐┤┌├┬┼"[g=(X,Y=0)=>(a[Y+y]||[])[X+x]==c,g(0,1)*8+g(1)*4+g(-1)*2+g(0,-1)])).join`
`
<textarea id=I rows=6># #### ## #
## #  ##  #
   ####  ##</textarea>

<button onclick="O.innerHTML=f(I.value.split('\n')).replace(/\n/g,'
')">Run</button>

ALPACA, 414 + 2 = 416  bytes
neighbourhoodV(^ v < >);states" ";statep"#"toA when4inV p,toB when3inV p andvs,toC when3inV p and^s,toD when3inV p and>s,toE when3inV p and<s,toF when2inV p and>s andvs,toG when2inV p andvs and<s,toH when2inV p and<s and^s,toI when2inV p and^s and>s,toJ when^p orvp,toK when
p;stateA"┼";stateB"┴";stateC"┬";stateD"┤";stateE"├";stateF"┘";stateG"└";stateH"┌";stateI"┐";stateJ"│";stateK"─".

Requires the -fI flags.
This solution uses a very large number of bytes, but it is unique in that it uses a cellular automaton. ALPACA is usually used as a metalanguage, but here I'm using it as a programming language.
Ungolfed version:
neighbourhood V (^ v < >);
state s " ";
state p "#" to A when 4 in V p,
to B when 3 in V p and v s,
to C when 3 in V p and ^ s,
to D when 3 in V p and > s,
to E when 3 in V p and < s,
to F when 2 in V p and > s and v s,
to G when 2 in V p and v s and < s,
to H when 2 in V p and < s and ^ s,
to I when 2 in V p and ^ s and > s,
to J when ^ p or v p,
to K when
 p;
state A "┼";
state B "┴";
state C "┬";
state D "┤";
state E "├";
state F "┘";
state G "└";
state H "┌";
state I "┐";
state J "│";
state K "─".

Python 3, 149 bytes
def f(s):S=' ';w=s.find('\n')+1;t=lambda i:(s+w*S)[i]>S;return[[c,'#│─┘─└─┴││┐┤┌├┬┼'[t(p-w)+2*t(p-1)+4*t(p+1)+8*t(p+w)]][c>S]for p,c in enumerate(s)]

Takes input like ##\n #\n and returns output like ['─', '┐', '\n', ' ', '│', '\n'].

Perl, 89 88 bytes
Includes +2 for -0p. The special characters are counted as 1 byte, but to make them actually display as single characters it's best to also add the -C option.
Give input on STDIN with the lines space padded so they all have the same length:
perl -C connect.pl
# #### ## #
## #  ##  #
   ####  ##
^D

connect.pl:
#!/usr/bin/perl -0p
/
/;$n=".{@-}";s%#%substr"#───│└┘┴│┌┐┬│├┤┼",/\G##/+2*/#\G/+4*/#$n\G/s+8*/\G#$n#/s,1%eg

PHP, 203 bytes
This can probably be done in a shorter way.
while($s=fgets(STDIN))$f[]=$s;foreach($f as$y=>&$s)for($x=strlen($s);$x--;)if($s[$x]>$b=" ")$s[$x]="#───│┘└┴│┐┌┬│┤├┼"[($s[$x-1]>$b)+2*($s[$x+1]>$b)+4*($f[$y-1][$x]>$b)+8*($f[$y+1][$x]>$b)];echo join($f);

reads input from STDIN. run with -r.

R, 199 212 bytes
EDIT: It's now a function, rather than a code snippet.
The input is a matrix m of 1s and 0s. This is pretty ugly and hacky.
function(m){
v=strsplit(" #─│┘│┐│┤──└┴┌┬├┼","")[[1]]
d=dim(m)+1
n=array(0,dim=d+1)
n[2:d[1],2:d[2]]=m
for(i in 0:(d[1]-2)){for(j in 0:(d[2]-2))cat(v[1+(p<-n[2+i,2+j])*sum(2^(0:3)*n[1:3+i,1:3+j][1:4*2])+p]);cat("\n")}
}

A couple of tests:
> m = matrix(c(1, 1, 1, 0, 1, 0), nrow=2, byrow=TRUE)
> v=strsplit(" #─│┘│┐│┤──└┴┌┬├┼","")[[1]]
> d=dim(m)+1
> n=array(0,dim=d+1)
> n[2:d[1],2:d[2]]=m
> for(i in 0:(d[1]-2)){for(j in 0:(d[2]-2))cat(v[1+(p<-n[2+i,2+j])*sum(2^(0:3)*n[1:3+i,1:3+j][1:4*2])+p]);cat("\n")}
─┬─
 │
> m = matrix(rep(1, 16), ncol=4)
> v=strsplit(" #─│┘│┐│┤──└┴┌┬├┼","")[[1]]
> d=dim(m)+1
> n=array(0,dim=d+1)
> n[2:d[1],2:d[2]]=m
> for(i in 0:(d[1]-2)){for(j in 0:(d[2]-2))cat(v[1+(p<-n[2+i,2+j])*sum(2^(0:3)*n[1:3+i,1:3+j][1:4*2])+p]);cat("\n")}
┌┬┬┐
├┼┼┤
├┼┼┤
└┴┴┘

Submission must be either a full program or a function. Reading from a existing variable is not an allowed form of input.

How do you get some of the unicode characters to work nicely with R? x = "\U253C" works but x = "┼" does not.

@TùxCräftîñg: Fixed now!

@Vlo utf-8 is my native OS encoding. x = "┼" works just fine for me.

MATL, 102 characters
I assign a neighbour a value (1, 2, 4 or 8); their sum will match a character in a string containing the drawing characters. I think there is still lots of room for improvements, but for a rough draft:
' #│││─┌└├─┐┘┤─┬┴┼' % String to be indexed
wt0J1+t4$(          % Get input, and append zeros at end of matrix (solely to avoid
                    %  indexing a non-existent second row/column for small inputs)
ttttt               % Get a whole load of duplicates to work on
3LXHY)              % Select rows 2:end from original matrix (one of the many dupes)
      w4LXIY)       % Select rows 1:end-1 from the 'destination' summing matrix)
             +HY(   % Add the neighbors below, store in 'destination' matrix
tIY)b3LY)2*+IY(     % +2* the neighbors above    +-------------------------------+
tHZ)b4LZ)4*+HZ(     % +4* the neighbors right    |(note: H and I contain 1:end-1 |
tIZ)b3LZ)8*+IZ(     % +8* the neighbors left     |  and 2:end respectively)      |
HH3$)               % Select the original matrix +-------------------------------+
*                % Make sure only cells that originally had a # get replaced
  1+)            % Add one because the original string is one-indexed. Index using ).

Improvements to be made:

Possibly replace the whole summing part with some kind of loop working on rotated copies of the matrix
Ditch the entire thing and make something based on a single loop working through the matrix
Use modular indexing to work on a flattened vector from the original array (?)

Try it Online! (may not have box drawing characters support)

APL (Dyalog Extended), 9 bytes
'#'⌂draw⊢

Try it online!
A built-in that solves the challenge (except that it accepts the '*' symbol as the default, so '#' needs to be supplied as an explicit argument). ¯\_(⍨)_/¯
Documentation is here.

A non-built-in solution, because a built-in is boring:
APL (Dyalog Extended), 43 bytes
' #│─┌─┐─┬││└├┘┤┴┼'⊇⍨⊢×0 0{1+⊥⊢/4 2⍴⍵}⌺3 3⊢

Try it online!
An anonymous function that takes the boolean matrix as its argument. Incidentally it wins over Jelly even without the built-in.
The approach is pretty similar to many other answers (base-2 conversion from the four neighbors and index into the target string).
One interesting thing to note is that the box-drawing characters are already part of the SBCS, so it is completely fine to use them in the code.
How it works
' #│─┌─┐─┬││└├┘┤┴┼'⊇⍨⊢×0 0{1+⊥⊢/4 2⍴⍵}⌺3 3⊢
  0 0{          }⌺3 3⊢  ⍝ Map over 3×3 submatrices, with zero padding...
           4 2⍴⍵        ⍝ Reshape 3×3 to 4×2:
                        ⍝ . A .   . A
                        ⍝ B . C → . B
                        ⍝ . D .   . C
                        ⍝         . D
         ⊢/  ⍝ Take the last column
        ⊥    ⍝ Convert base 2 to integer
      1+     ⍝ Offset 1 to distinguish between ' ' and '#'
⊢×  ⍝ Mask the places for blanks
' #│─┌─┐─┬││└├┘┤┴┼'⊇⍨  ⍝ Convert each value in the matrix to the char at that index

Charcoal, 45 bytes
ＷＳ⊞υιＰ⪫υ⸿Ｆ⪫υ⸿≡ι#§”y#─│┐──┌┬│┘│┤└┴├┼”↨ＥＫＶ›κ ²ι

Try it online! Link is to verbose version of code. Takes input as a newline-terminated list of strings. Scored using 15 1-byte box drawing characters (normally 3 bytes each). Explanation:
ＷＳ⊞υι

Read in the text.
Ｐ⪫υ⸿

Print it without moving the cursor.
Ｆ⪫υ⸿

Loop over the text again.
≡ι#

If the current character is a #...
§”y#─│┐──┌┬│┘│┤└┴├┼”↨ＥＫＶ›κ ²

... then look up the box drawing character based on the presence of neighbours.
ι

Otherwise just print the current character.

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