Is it safe to have an additional load before a switch first circuit?

Question: I have a circuit going to the bathroom that is a switch first. It's only load after the switch is a simple light and bathroom fan.
Is it possible and safe to have an additional outlet before the switch that is independent of the light's on/off state?
Comment: Is this going to be for the bathroom?
Comment: It's going to be for the room next to the bathroom. The cable reaches the point where I would like to put an additional receptacle before it reaches the bathroom.

Is it not up to code if I have a "pre" load before the light circuit?
Comment: Is there a separate circuit for the bathroom receptacle(s)?
Comment: @ThreePhaseEel yes the bathroom receptacles are on a separate circuit. Only the bathroom light and fan are on the circuit that are controlled by a switch. The outlets in the bathroom itself are separate.
Answer: 2014 NEC, 210.11.C.3 Bathroom branch circuits. 1 20 amp shall be provided and have no other outlets. So it would be a code violation if not in the bathroom.
Comment: Thank you, I didn't know that the technical term is a `branch circuit` - will use that from now on for my research. Hopefully I can find another way to get the additional outlet.
Comment: @DylanPierce -- if your branch circuit isn't running the bathroom receptacles, then it doesn't fall under the 210.11(C)(3) stuff as that's for the bathroom *receptacle* small appliance branch circuit (think hairdryer)
Comment: @ThreePhaseEel ohhh ok. This branch circuit would just be used for adding one receptacle that will power a small propane oven's ignition. It would be in the room adjacent to the bathroom.
Comment: @ThreePhaseEel looking at figure 3 - http://ecmweb.com/nec/code-basics/101ecmCBfig3.jpg

  My extra outlet outside of the bathroom would break code. Woof. Guess I have to move a receptacle.
Comment: @DylanPierce -- that illustration doesn't refer to your case though
Answer: Go ahead and add it
Since this receptacle is being installed to the bathroom general lighting branch circuit, and not the bathroom small appliance receptacle branch circuit, 210.11(C)(3) and its exception don't apply to it as that Code section deals with bathroom receptacle branch circuits:

(3) Bathroom Branch Circuits. In addition to the number
  of branch circuits required by other parts of this section, at
  least one 120-volt, 20-ampere branch circuit shall be provided to supply a bathroom receptacle outlet(s). Such circuits shall have no other outlets.
Exception: Where the 20-ampere circuit supplies a single
  bathroom, outlets for other equipment within the same
  bathroom shall be permitted to be supplied in accordance
  with 210.23(A)(1) and (A)(2).

Also, the exception doesn't come into play as the OP's bathroom receptacles don't share a branch circuit with the OP's bathroom lights.
Comment: The section of code you reference "shall be provided to supply a bathroom receptacle outlet(s). Such circuits shall have no other outlets." says no other outlets.
Comment: @EdBeal -- the circuit he's putting the new outlet on has no bathroom receptacles on it
Comment: If there are no receptacles then it could be added.
Answer: The way I read the link below the 20-A circuit for one bathroom can have the receptacle, the lights and the fan all on the same circuit. "As long as no single load exceeds 10 A." Of course a 1600 W hairdryer exceeds 10 A, but you could provide a 1200 W hairdryer and claim that is the intended load.  Picky, picky . . .  http://ecmweb.com/code-basics/branch-circuits-part-1 See Fig. 4.
Editing But one cannot have a "non-bathroom" load (receptacle or otherwise) on the 20-A circuit for the bathroom receptacle. Apparently one can have a single 20-A circuit that powers receptacles only in two (or more?!) bathrooms . . . What the heck?
Comment: My reaction is somewhat heightened by the fact that I live in a tract home with two bathrooms built in 1970. As built, each had one receptacle, one integrated ceiling unit (exhaust fan, one incandescent flood, one heat lamp with fan blowing over it) and three porcelain lamp bases in a box over the lavatory.  The bathrooms are on **the same 15-A breaker** (new 15-A GE GFCI) and wired in 12 AWG aluminum. Presumably this was the code in Dallas in 1970, I dunno. One of the people in the house uses a hairdryer (1200 W lo / 1500 W hi) for short periods. We never have had the breaker trip.
Comment: The 10 amp limit is for fixed devices only. This is to prevent an electric heater or jacuzzi tub from using two much power and creating a problem. I was an apprentice in the 70's and AL wire was really being pushed , 12 gauge on a 15 amp would have been code. Also if there was a common wall the outlets could be on the same circuit.
Comment: In my case there is no common wall between the bathrooms. Unfortunately my panel is full. If I had a slot left, I would consider separating the two bathrooms on two different 15-A circuits.
Comment: Will your panel accept tandem breakers? If the listing states more possible breakers than slots you could add a tandem. Example 20/30 20 slots but 10 would accept tandem breakers or 20/40. These are not very expensive if the panel will accept them it will give you more circuits.
Comment: @Ed Beal my old GE panel accepts individual 1/2" wide breakers for the lower part for branch circuits. (The upper part has spaces for full-size 2-pole breakers for ele dryer, a/c condenser, ele range and a 60-A "main section", a feeder breaker for the lower part.  It has room for 16 1/2" breakers and there are 10 of these (5 are 15 A and 5 are 20 A).  There are two GFCI breakers which are 1" wide, and there is one 2-pole 50-A breaker to which the Eaton whole house surge protector is connected. I really need to put in a sub-panel.


How do I get Vidalia Tor to work on 14.04?

Question: A.S.: Complete Linux noob here.
I'm trying to install Vidalia from the Software Centre, and apparently everyone says that it doesn't work on 14.04.
However someone posts a link to a fix package
I manage to install the package with dpkg, but when I try to start Tor from Vidalia, it gives me this error:

Vidalia was unable to start Tor. Check your settings to ensure the
  correct name and location of your Tor executable is specified.

The location appears to be /usr/sbin/tor
Answer: Just follow up these steps

Open up /etc/apparmor.d/usr.bin.vidalia file with root permissions. For this you can run sudo gedit /etc/apparmor.d/usr.bin.vidalia in a Terminal.
Add this line /usr/bin/tor Ux, anywhere inside the /usr/bin/vidalia {...} block. Place of this line in that block does not matter.
Run sudo apparmor_parser --replace /etc/apparmor.d/usr.bin.vidalia in a Terminal.

Okay, now you're done!


When you fire do bushes become invisible for your allies?

Question: I've just watched a very helpful video about camouflage and how bushes work, one thing stated was that "When you fire bushes become invisible within 50m of you."
So if I'm next to an enemy tank that's behind a shrubbery so my allies can't see it, if I fire at said enemy tank will the shrubberies vanish so that my allies can see my target?
A crude diagram to illustrate:
<code>     M
A    SE
</code>
A = Ally
M = My Tank
S = Shrubbery
E = Enemy
Answer: If you can see your enemy and your ally is within radio distance of you and view range of the enemy, they can see the enemy regardless of bush status.
Comment: Doh, completely forgot about that!
Comment: Nevertheless, in rare circumstances the ally can have view radius wider than radio range! In that case this might be useful - they won't receive your radio report but will see the enemy directly!


how to get absolute X/Y coordinates for a display object nested within Display Groups in Corona?

Question: For fault finding, how can I print out the Absolute co-ordinates of a display object (e.g. image) that is buried within Display Groups? (i.e. don't want the relative position)
That is position relative to the actual display resolution, so say: Xleft, Xright, Ytop, Ybottom co-ordinates type thing.
Answer: Yup - what you're looking for is object:localToContent()


Can/does the (forward) pipe operator prevent tail call optimization?

Question: For a parameter optimization problem at work I wrote a genetic algorithm to find some good settings because a brute-force solution is unfeasible. Unfortunately, when I return in the morning, most of the time I'm presented with a StackOverflowException.
I've been using F# for quite some time now so I'm aware of TCO and the need for functions with accumulator arguments and generally use that form.
After a lot of searching I think I was able to nail to the code that triggered the exception:
breedPopulation alive |> simulate (generation + 1) lastTime ewma

breedPopulation generates a new generation from the individuals in the current alive one. Then the next round/generation is started with the call to simulate. When I look at the disassembly (total noob) I spot some pop and a ret, so it does not look like a regular (non-tail) call to me.
mov         rcx,qword ptr [rbp+10h]
mov         rcx,qword ptr [rcx+8]
mov         rdx,qword ptr [rbp-40h]
cmp         dword ptr [rcx],ecx
call        00007FFA3E4905C0
mov         qword ptr [rbp-0F0h],rax
mov         r8,qword ptr [rbp-0F0h]
mov         qword ptr [rbp-80h],r8
mov         r8,qword ptr [rbp-78h]
mov         qword ptr [rsp+20h],r8
mov         r8d,dword ptr [rbp+18h]
inc         r8d
mov         rdx,qword ptr [rbp+10h]
mov         r9,qword ptr [rbp-20h]
mov         rcx,7FFA3E525960h
call        00007FFA3E4A5040
mov         qword ptr [rbp-0F8h],rax
mov         rcx,qword ptr [rbp-0F8h]
mov         rdx,qword ptr [rbp-80h]
mov         rax,qword ptr [rbp-0F8h]
mov         rax,qword ptr [rax]
mov         rax,qword ptr [rax+40h]
call        qword ptr [rax+20h]
mov         qword ptr [rbp-100h],rax
mov         rax,qword ptr [rbp-100h]
lea         rsp,[rbp-10h]
pop         rsi
pop         rdi
pop         rbp
ret

After throwing away the pipe operator and putting the breeding in a normal parameter position, the disassembly is different.
//    simulate (generation + 1) lastTime ewma (breedPopulation alive)
mov         ecx,dword ptr [rbp+18h]
inc         ecx
mov         dword ptr [rbp-30h],ecx
mov         rcx,qword ptr [rbp-20h]
mov         qword ptr [rbp-38h],rcx
mov         rcx,qword ptr [rbp-80h]
mov         qword ptr [rbp-0F0h],rcx
mov         rcx,qword ptr [rbp+10h]
mov         rcx,qword ptr [rcx+8]
mov         rdx,qword ptr [rbp-48h]
cmp         dword ptr [rcx],ecx
call        00007FFA3E4605C0
mov         qword ptr [rbp-0F8h],rax
mov         rax,qword ptr [rbp-0F8h]
mov         qword ptr [rbp+30h],rax
mov         rax,qword ptr [rbp-0F0h]
mov         qword ptr [rbp+28h],rax
mov         rax,qword ptr [rbp-38h]
mov         qword ptr [rbp+20h],rax
mov         eax,dword ptr [rbp-30h]
mov         dword ptr [rbp+18h],eax
nop
jmp         00007FFA3E47585B

That's definitely shorter and with the final jmp even better that a tail call.
Therefore I want to understand if and why the |> seems to be the problem and when it does make a difference—after all, this is the first time it bites me after years. Under what circumstances does it happen and what do we have to watch out for?

Update: After Guy pointed out that my listings are not IL but assembly, I first reworded the question. This is what I found out with ILSpy:
With the |> operator
Looking at the decompiled C#, the code seems to jump back and forth between
internal static FSharpFunc<Types.Genome[], System.Tuple<System.Tuple<float, float>, LbpArea[]>[]> simulate@265-1(Universe x, System.Threading.ManualResetEvent pleaseStop, int generation, System.DateTime lastTime, FSharpOption<double> ewma)
{
    return new $Universe.simulate@267-2(x, pleaseStop, generation, lastTime, ewma);
}

and
// internal class simulate@267-2
public override System.Tuple<System.Tuple<float, float>, LbpArea[]>[] Invoke(Types.Genome[] population)
{
    LbpArea[][] array = ArrayModule.Parallel.Map<Types.Genome, LbpArea[]>(this.x.genomeToArray, population);
    FSharpFunc<System.Tuple<System.Tuple<float, float>, LbpArea[]>, float> accessFitness = this.x.accessFitness;
    System.Tuple<System.Tuple<float, float>, LbpArea[]>[] array2 = ArrayModule.Filter<System.Tuple<System.Tuple<float, float>, LbpArea[]>>(new $Universe.alive@274(accessFitness), ArrayModule.Parallel.Map<LbpArea[], System.Tuple<System.Tuple<float, float>, LbpArea[]>>(new $Universe.alive@273-1(this.x), array));
    if (array2 == null)
    {
        throw new System.ArgumentNullException("array");
    }
    System.Tuple<System.Tuple<float, float>, LbpArea[]>[] array3 = ArrayModule.SortWith<System.Tuple<System.Tuple<float, float>, LbpArea[]>>(new $Universe.alive@275-2(), array2);
    this.x.Population = array3;
    System.Tuple<System.DateTime, FSharpOption<double>> tuple = this.x.printProgress<float, LbpArea[]>(this.lastTime, this.ewma, this.generation, array3);
    System.DateTime item = tuple.Item1;
    FSharpOption<double> item2 = tuple.Item2;
    if (this.pleaseStop.WaitOne(0))
    {
        return array3;
    }
    Types.Genome[] func = this.x.breedPopulation(array3);
    return $Universe.simulate@265-1(this.x, this.pleaseStop, this.generation + 1, item, item2).Invoke(func);
}

In the IL of the new call there is no tail. op to be found. On the other hand, the IL of the last lines of the Invoke read
IL_00d3: call class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2<class BioID.GeneticLbp.Types/Genome[], class [mscorlib]System.Tuple`2<class [mscorlib]System.Tuple`2<float32, float32>, valuetype [BioID.Operations.Biometrics]BioID.Operations.Biometrics.LbpArea[]>[]> '<StartupCode$BioID-GeneticLbp>.$Universe'::'simulate@265-1'(class BioID.GeneticLbp.Universe, class [mscorlib]System.Threading.ManualResetEvent, int32, valuetype [mscorlib]System.DateTime, class [FSharp.Core]Microsoft.FSharp.Core.FSharpOption`1<float64>)
IL_00d8: ldloc.s 7
IL_00da: tail.
IL_00dc: callvirt instance !1 class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2<class BioID.GeneticLbp.Types/Genome[], class [mscorlib]System.Tuple`2<class [mscorlib]System.Tuple`2<float32, float32>, valuetype [BioID.Operations.Biometrics]BioID.Operations.Biometrics.LbpArea[]>[]>::Invoke(!0)
IL_00e1: ret

I don't know what to make of that.
Without |> operator
The other version is indeed very different. Starting with
internal static System.Tuple<System.Tuple<float, float>, LbpArea[]>[] simulate@264(Universe x, System.Threading.ManualResetEvent pleaseStop, Unit unitVar0)
{
    FSharpFunc<int, FSharpFunc<System.DateTime, FSharpFunc<FSharpOption<double>, FSharpFunc<Types.Genome[], System.Tuple<System.Tuple<float, float>, LbpArea[]>[]>>>> fSharpFunc = new $Universe.simulate@265-2(x, pleaseStop);
    (($Universe.simulate@265-2)fSharpFunc).x = x;
    (($Universe.simulate@265-2)fSharpFunc).pleaseStop = pleaseStop;
    System.Tuple<System.Tuple<float, float>, LbpArea[]>[] population = x.Population;
    Types.Genome[] func;
    if (population != null && population.Length == 0)
    {
        func = x.lengthRandomlyIncreasing(firstname.lastname@example.com@);
        return FSharpFunc<int, System.DateTime>.InvokeFast<FSharpOption<double>, FSharpFunc<Types.Genome[], System.Tuple<System.Tuple<float, float>, LbpArea[]>[]>>(fSharpFunc, 0, System.DateTime.Now, null).Invoke(func);
    }
    FSharpFunc<LbpArea[], Types.Genome> arrayToGenome = x.arrayToGenome;
    func = ArrayModule.Parallel.Map<System.Tuple<System.Tuple<float, float>, LbpArea[]>, Types.Genome>(new $Universe.simulate@296-3(arrayToGenome), population);
    return FSharpFunc<int, System.DateTime>.InvokeFast<FSharpOption<double>, FSharpFunc<Types.Genome[], System.Tuple<System.Tuple<float, float>, LbpArea[]>[]>>(fSharpFunc, 0, System.DateTime.Now, null).Invoke(func);
}

it goes to
// internal class simulate@265-2
public override System.Tuple<System.Tuple<float, float>, LbpArea[]>[] Invoke(int generation, System.DateTime lastTime, FSharpOption<double> ewma, Types.Genome[] population)
{
    return $Universe.simulate@265-1(this.x, this.pleaseStop, generation, lastTime, ewma, population);
}

and finally
internal static System.Tuple<System.Tuple<float, float>, LbpArea[]>[] simulate@265-1(Universe x, System.Threading.ManualResetEvent pleaseStop, int generation, System.DateTime lastTime, FSharpOption<double> ewma, Types.Genome[] population)
{
    while (true)
    {
        // Playing evolution...
        if (pleaseStop.WaitOne(0))
        {
            return array3;
        }
        // Setting up parameters for next loop...
    }
    throw new System.ArgumentNullException("array");
}

tl;dr
So definitely, the usage of the pipe operator drastically changed the program flow. My guess is that the back and forth between the two function is what eventually causes the exception.
I had already read Tail Calls in F# but I don't think it applies to this situation, as I'm not using a first-class function returning unit as value (in my F# code).
So the question remains: Why does the pipe operator have this destructive effect here? How could I've known beforehand/what do I need to watch out for?

Update 2:
You can find a reduced version of the example at GitHub. Please see for yourself that the inline operator |> changes the produces IL, which is not what I would expect.
While reducing the example, with a little luck I was able to find the real source of the exception. You can check the branch for the much more minimal variant. After all, it doesn't have anything to do with the pipe, but I still don't get it because IMHO there is tail recursion.
But my original questions remain. I'm just adding one more. :)
Comment: Have you seen: [Tail calls in F#](https://blogs.msdn.microsoft.com/fsharpteam/2011/07/08/tail-calls-in-f/)
Comment: That is assembly level code not .NET IL code. How did you get it? What was the build instructions? Did you misstate and say IL?
Comment: You can also use [Ildasm.exe (IL Disassembler)](https://msdn.microsoft.com/en-us/library/f7dy01k1.aspx)
Comment: Could you post your full F# code (or, better, a smaller representative repro)?  `(|>)` is defined as an `inline` function, so I wouldn't expect it to affect TCO.
Comment: If I run your minimum example from GitHub in 64-bit it causes a stack overflow. If I run your minimum example from GitHub in 32-bit it works. I think I know of a work around and am checking it now.
Comment: Oops, as I said: noob. I used "Go To Disassembly" thinking that for .NET I will get IL. So how do I get the IL?
Comment: For TCO it is does not matter what the final form is, being either IL or assembly code, what matters is whither or not the the stack size is growring. For the question I don't even know if you need to show the code since you are asking if `|>` can effect TCO. To get the IL you can use [ilspy](http://ilspy.net/)
Comment: Are you running in release mode or debug mode? Do you have optimizations on or off? Do you have tail call optimization on or off?
Comment: All release mode with standard settings, i.e. optimizations on. I'm currently trying to put together a minimal repo.
Comment: Interesting (and unexpected) fact, @Guy; the same on my machine. Shouldn't 64 bit (RyuJIT) be better when it comes to TCO?
Comment: @primfaktor You should ask `Shouldn't 64 bit (RyuJIT) be better when it comes to TCO?` as a new question. It is a good one with insight to be gained. I won't answer as I have had my fill on this one for now, and because I am interested to see what other say and in particular kvb; I might learn something more.
Comment: @primfaktor I don't on plan on adding anything more to the answer. AFAIK you should be able to run your code with out a stack overflow in 64-bit and release mode. If you still have some holes in the reasoning let me know and I will try and resolve them.
Comment: @GuyCoder: This is what I created for the 32-64-bit issue: https://stackoverflow.com/questions/35751350/
Answer: Based on the minimal case as provided, if the code is run in release mode in 64-bit it fails with a stack overflow. If the code is run in release mode in 32-bit mode it succeeds.
Note: The option to choose between 32-bit and 64-bit is Prefer 32-bit as seen in the images below.
Increasing the stack size will result in the code succeeding in release mode in 64-bit. This is done via the use of the Thread constructor.
[<EntryPoint>]
let main _ =

    let test () =
        let r = KissRandom()
        let n = r.Normal()
        Seq.item 20000 n |> printfn "%f"

    /// The greatest maximum-stack-size that should be used
    /// with the 'runWithStackFrame' function.
    let STACK_LIMIT = 16777216

    /// Run a function with a custom maximum stack size.
    /// This is necessary for some functions to execute
    /// without raising a StackOverflowException.
    let runWithCustomStackSize maxStackSize fn =
        // Preconditions
        if maxStackSize < 1048576 then
            invalidArg "stackSize" "Functions should not be executed with a \
                maximum stack size of less than 1048576 bytes (1MB)."
        elif maxStackSize > STACK_LIMIT then
            invalidArg "stackSize" "The maximum size of the stack frame should \
                not exceed 16777216 bytes (16MB)."

        /// Holds the return value of the function.
        let result = ref Unchecked.defaultof<'T>

        // Create a thread with the specified maximum stack size,
        // then immediately execute the function on it.
        let thread = System.Threading.Thread ((fun () -> result := fn()), maxStackSize)
        thread.Start ()

        // Wait for the function/thread to finish and return the result.
        thread.Join ()
        !result

    /// Runs a function within a thread which has an enlarged maximum-stack-size.
    let inline runWithEnlargedStack fn =
        runWithCustomStackSize STACK_LIMIT fn

//    test ()       // Fails with stack overflow in 64-bit mode, Release
                    // Runs successfully in 32-bit mode, Release

    runWithEnlargedStack test

    printf "Press any key to exit: "
    System.Console.ReadKey() |> ignore
    printfn ""

    0

This code is from FSharp-logic-examples and in particular Anh-Dung Phan
While I have not checked for the root cause, I suspect it is because of the size of the items for 64-bit is larger that the size of the items for 32-bit and even though the number of items put into the stack and the stack size remains the same for both versions, the item size increase pushes the memory needed for the stack over the 1 megabyte limit.
TL;DR
This has been a fun and enlightening question to answer. I am glad it was asked.
Originally the problem appeared to be related to the use of |> and TCO and since that is still of value I am leaving it in the answer. I would also like to thank the OP for being response and helpful, it is a pleasure to help someone who works with you and not against you.
In the following code which is recursive and has |> is run in Debug mode within Visual Studio it causes a StackOverflow.
If it is started from the command line from the bin\release directory it does NOT cause a StackOverflow.
Using Visual Studio 15 Community
[<EntryPoint>]
let main argv =

    let largeList =
        printfn "Creating large list"
        [
            for i in 1 .. 100000000 do
                yield i
        ]

    // causes StackOverflow in Debug
    // No StackOverflow in Release
    let sum4 l =
        printfn "testing sum4"
        let rec sumInner4 l acc =
            match l with
            | h::t ->
                let acc = acc + h
                acc |> sumInner4 t
            | [] -> acc
        sumInner4 l 0

    let result4 = sum4 largeList
    printfn "result4: %A" result4

Where Release or Debug is set in the Visual Studio toolbar

and the options for the project in Debug mode are

and the options for the project in Release mode are

tldr;
In the process of testing this I created 16 different test and built them in both debug and release mode and verified if they ran to completion or threw a stack overflow. The 16 are broken down into a set of 4 with 4 cases each. The cases 1,5,9,13 are a negative and produce a stack overflow to ensure that a stack overflow can be created. Cases 2,6,10,14 are a positive to show that the tail call is working and not causing a stack overflow. Cases 3,7,11,15 show a tail call with an operation done in the same statement as the tail call, and to be one factorization away from the test cases using |>; these work as expected. Cases 4,8,12,16 use |> and shows when it does and does not work in debug mode, which is probably a surprise to many. Cases 1-4 and 9-12 use a function of the form f x y, cases 8-11 use a function of the form f x and cases 12-16 use a function of the form f x y z. I originally did the first 8 test cases but after Keith's comment did 4 more which don't use a list but still use a function of the from f x y and present the unexpected result and then did 4 more that use a function of the form f x y z.
To run a test you will have to comment out all but the one test you plan to run and the build it once in debug mode, which can then be run from within Visual Studio, and then again build it in release mode and run it. I run it from a command line to ensure I am running the release version.
[<EntryPoint>]
let main argv =

    let largeList =
        printfn "Creating large list"
        [
            for i in 1 .. 100000000 do
                yield i
        ]

    // causes StackOverflow in Debug
    // causes StackOverflow in Release
    //   Negative confirmation
    //   A supposed tail call that DOES cause a stack overflow in both debug and release mode
    //   options: f x y
    let sum1 l =
        printfn "test 01: "
        let rec sum1Inner l acc =
            match l with
            | h::t ->
                let acc = acc + h
                1 + sum1Inner t acc
            | [] -> acc
        sum1Inner l 0

    // No StackOverflow in Debug
    // No StackOverflow in Release
    //   Positive confirmation
    //   A tail call that DOES NOT cause a stack overflow in both debug and release mode
    //   options: f x y
    let sum2 l =
        printfn "test 02: "
        let rec sum2Inner l acc =
            match l with
            | h::t ->
                let acc = acc + h
                sum2Inner t acc
            | [] -> acc
        sum2Inner l 0

    // No StackOverflow in Debug
    // No StackOverflow in Release
    //   A test case
    //   options: f x y and no |>
    let sum3 l =
        printfn "test 03: "
        let rec sum3Inner l acc =
            match l with
            | h::t ->
                sum3Inner t (acc + h)
            | [] -> acc
        sum3Inner l 0

    // causes StackOverflow in Debug
    // No StackOverflow in Release
    //   A test case
    //   options: f x y and |>
    let sum4 l =
        printfn "test 04: "
        let rec sum4Inner l acc =
            match l with
            | h::t ->
                let acc = acc + h
                acc |> sum4Inner t
            | [] -> acc
        sum4Inner l 0

    // causes StackOverflow in Debug
    // causes StackOverflow in Release
    //   Negative confirmation
    //   A supposed tail call that DOES cause a stack overflow in both debug and release mode
    //   options: f x
    let sum5 () =
        printfn "test 05: "
        let rec sum5Inner x =
            match x with
            | 10000000 -> x
            | _ ->
                let acc = x + 1
                1 + sum5Inner acc
        sum5Inner 0

    // No StackOverflow in Debug
    // No StackOverflow in Release
    //   Positive confirmation
    //   A tail call that DOES NOT cause a stack overflow in both debug and release mode
    //   options: f x
    let sum6 () =
        printfn "test 06: "
        let rec sum6Inner x =
            match x with
            | 10000000 -> x
            | _ ->
                let acc = x + 1
                sum6Inner acc
        sum6Inner 0

    // No StackOverflow in Debug
    // No StackOverflow in Release
    //  A test case
    //  options: f x and no |>
    let sum7 l =
        printfn "test 07: "
        let rec sum7Inner x =
            match x with
            | 10000000 -> x
            | _ -> sum7Inner (x + 1)
        sum7Inner 0

    // No StackOverflow in Debug
    // No StackOverflow in Release
    //   A test case
    //   options: f x and |>
    let sum8 () =
        printfn "test 07: "
        let rec sumInner8 x =
            match x with
            | 10000000 -> x
            | _ ->
                let acc = x + 1
                acc |> sumInner8
        sumInner8 0

    // causes StackOverflow in Debug
    // causes StackOverflow in Release
    //   Negative confirmation"
    //   A supposed tail call that DOES cause a stack overflow in both debug and release mode"
    //   options: f x y"
    let sum9 () =
        printfn "test 09: "
        let rec sum9Inner x y =
            match y with
            | 10000000 -> y
            | _ ->
                let acc = x + y
                1 + sum9Inner x acc
        sum9Inner 1 0

    // No StackOverflow in Debug
    // No StackOverflow in Release
    //   Positive confirmation
    //   A tail call that DOES NOT cause a stack overflow in both debug and release mode
    //   options: f x y
    let sum10 () =
        printfn "test 10: "
        let rec sum10Inner x y =
            match y with
            | 10000000 -> y
            | _ ->
                let acc = x + y
                sum10Inner x acc
        sum10Inner 1 0

    // No StackOverflow in Debug
    // No StackOverflow in Release
    //   A test case
    //   options: f x y and no |>
    let sum11 () =
        printfn "test 11: "
        let rec sum11Inner x y =
            match y with
            | 10000000 -> y
            | _ ->
                sum11Inner x (x + y)
        sum11Inner 1 0

    // causes StackOverflow in Debug
    // No StackOverflow in Release
    //   A test case
    //   options: f x y and |>
    let sum12 () =
        printfn "test 12: "
        let rec sum12Inner x y =
            match y with
            | 10000000 -> y
            | _ ->
                let acc = x + y
                acc |> sum12Inner x
        sum12Inner 1 0

    // causes StackOverflow in Debug
    // No StackOverflow in Release
    //   A test case"
    //   options: f x y and |>"
    let sum12 () =
        printfn "test 12: "
        let rec sum12Inner x y =
            match y with
            | 10000000 -> y
            | _ ->
                let acc = x + y
                acc |> sum12Inner x
        sum12Inner 1 0

    // causes StackOverflow in Debug
    // causes StackOverflow in Release
    //   Negative confirmation"
    //   A supposed tail call that DOES cause a stack overflow in both debug and release mode"
    //   options: f x y"
    let sum13 () =
        printfn "test 13: "
        let rec sum13Inner x z y =
            match y with
            | 10000000 -> y
            | _ ->
                let acc = x + y
                1 + sum13Inner x z acc
        sum13Inner 1 "z" 0

    // No StackOverflow in Debug
    // No StackOverflow in Release
    //   Positive confirmation"
    //   A tail call that DOES NOT cause a stack overflow in both debug and release mode"
    //   options: f x y"
    let sum14 () =
        printfn "test 14: "
        let rec sum14Inner x z y =
            match y with
            | 10000000 -> y
            | _ ->
                let acc = x + y
                sum14Inner x z acc
        sum14Inner 1 "z" 0

    // No StackOverflow in Debug
    // No StackOverflow in Release
    //   A test case"
    //   options: f x y and no |>"
    let sum15 () =
        printfn "test 15: "
        let rec sum15Inner x z y =
            match y with
            | 10000000 -> y
            | _ ->
                sum15Inner x z (x + y)
        sum15Inner 1 "z" 0

    // causes StackOverflow in Debug
    // No StackOverflow in Release
    //   A test case"
    //   options: f x y and |>"
    let sum16 () =
        printfn "test 16: "
        let rec sum16Inner x z y =
            match y with
            | 10000000 -> y
            | _ ->
                let acc = x + y
                acc |> sum16Inner x z
        sum16Inner 1 "z" 0

    let result1 = sum1 largeList
    printfn "result1: %A" result1

    let result2 = sum2 largeList
    printfn "result2: %A" result2

    let result3 = sum3 largeList
    printfn "result3: %A" result3

    let result4 = sum4 largeList
    printfn "result4: %A" result4

    let result5 = sum5 ()
    printfn "result5: %A" result5

    let result6 = sum6 ()
    printfn "result6: %A" result6

    let result7 = sum7 ()
    printfn "result7: %A" result7

    let result8 = sum8 ()
    printfn "result8: %A" result8

    let result9 = sum9 ()
    printfn "result9: %A" result9

    let result10 = sum10 ()
    printfn "result10: %A" result10

    let result11 = sum11 ()
    printfn "result11: %A" result11

    let result12 = sum12 ()
    printfn "result12: %A" result12

    let result13 = sum13 ()
    printfn "result13: %A" result13

    let result14 = sum14 ()
    printfn "result14: %A" result14

    let result15 = sum15 ()
    printfn "result15: %A" result15

    let result16 = sum16 ()
    printfn "result16: %A" result16

    printf "Press any key to exit: "
    System.Console.ReadKey() |> ignore
    printfn ""

    0 // return an integer exit code

Additional, new info
EDIT: This thread on Github has Don Syme, creator of F#, specifically mention that:

[...] Second, you are correct, we don't guarantee to optimize uses of f <| x or x |> f or any similar to first-calling tailcalls even if f x is a tailcall.
Comment: I think the upshot is that if you have `y |> f x` then in debug mode the compiler may apply the function `f` in two discrete steps (first to `x` then to `y`), which prevents the compiler from turning direct recursive calls into a loop.  If you have `f x y` instead, then the compiler will compile the direct recursive call into a loop (in debug or release mode).
Comment: I did all tests and also the IL/disassembly inspection in Release mode, I know the story is different in Debug.
Comment: You put a lot of work in your answer and I'm tempted to accept it. But even with 16 mb stack I still get the exception (see master branch). And the (original) issue of totally different code because of the pipe remains. Maybe I should extract the pipe question to a new (simpler) one instead of rewriting everything.
Comment: @primfaktor I still get the exception (see master branch). Then your minimal code example to reproduce the problem was not correct or it is due to a different problem, as such I don't see that as a reason to withhold an accept. And the (original) issue of totally different code because of the pipe remains.  I don't see an issue, in your original question without a code example I gave an answer with working code that reproduced the problem and showed the different ways that `|>` would and would not work, e.g. `f x` or `f x y` which was pointed out by kvb.
Comment: Maybe I should extract the pipe question to a new (simpler) one instead of rewriting everything. The original question was `Can/does the (forward) pipe operator prevent tail call optimization?` and `Under what circumstances does it happen and what do we have to watch out for?` which I showed in the answer. Then you changed the question and gave a minimal example which in the answer I showed how to resolve and gave a reason. If you keep changing questions after they have been asked people will notice and avoid your questions.
Comment: You are now expecting an analysis of your full code and a working solution with a detailed reason why. If that was a question by itself it would most likely get closed with the reason `OP expects us to debug code` which is not an acceptable question for StackOverflow.


Error : invalid operands to binary ^ (have 'float' and 'int' )

Question: i'm doing a code using function, but when i try to run it i have the error "invalid operands to binary ^ (have 'float' and 'int' )". The operation that i want to do is: Vo*((1-(1+I)^-N)/I).     Here's the code. Thanks!
#include <stdlib.h>

float func(int anios, float tipointeres){

    float interes_mod, func, porcen;
    int n=0;

    porcen = tipointeres/100; //El interes es porcentaje, así que hacemos esto para que sea uno.

    for(n;n<anios;n++){

         interes_mod = (1+porcen)^(-anios);
         func = ((1-interes_mod)/porcen);

    }
       return func;
}

int main()
{
    int anios;
    float valortotal, constrenta, tipointeres;

    printf("Ingresa el importe constante de la renta (Vo): ");
    scanf("%f", &constrenta);
    fflush(stdin);

    printf("Ingresa el tipo de interes (I): ");
    scanf("%f", &tipointeres);
    fflush(stdin);

    printf("Ingresa el numero de años (N): ");
    scanf("%d", &anios);
    fflush(stdin);

    valortotal = func(anios, tipointeres)* constrenta; //Aquí multplico Vo por toda la fracción.

    printf("El valor actual de la renta es: %f", valortotal);

    return 0;
}

Comment: C is not a language you can successfully use by typing in stuff you guess will work.  Please do yourself a favor and read through at least the first few chapters of a good introductory book or tutorial.
Comment: ^ is the exclusive-or operator, and your equation doesn't look like that's what you want (hint: take a look at the pow() function in math.h)
Answer: The ^ operator is not the power operator but the bitwise XOR operator.  This operator expects both operands to be integer types, which is why you're getting the error.
To perform exponentiation you want the pow or powf function, which raises the first argument to the power of the second.  In your case you'll want to use the latter since you're only using float as opposed to double:
interes_mod = powf(1+porcen,-anios);

Note that you'll also need to #include <math.h> to get the declaration of the function and compile with the -lm flag to link in the math library.
Comment: @AndresGards Glad I could help.  Feel free to [accept this answer](https://stackoverflow.com/help/accepted-answer) if you found it useful.


OpenCV 3 KNN implementation

Question: As you may know, many things changed in OpenCV 3. In previous verion of OpenCV I used to do it that way:
Mat trainData(classes * samples, ImageSize, CV_32FC1);
Mat trainClasses(classes * samples, 1, CV_32FC1);
KNNLearning(&trainData, &trainClasses); //learning function
KNearest knearest(trainData, trainClasses); //creating

//loading input image
Mat input = imread("input.jpg");

//digital recognition
learningTest(input, knearest);//test

Also I found an example how to figured it out, but I still have errors in create function:
Ptr<KNearest> knearestKdt = KNearest::create(ml::KNearest::Params(10, true, INT_MAX, ml::KNearest::KDTREE));
knearestKdt->train(trainData, ml::ROW_SAMPLE, trainLabels);
knearestKdt->findNearest(testData, 4, bestLabels);

Can you please provide me with information, how to rewrite the actual code of KNearest to openCV 3 properly?
Answer: The API has changed once again since @aperture-laboratories answer. I hope they keep up with the documentation when they release new features or changes in the future.
A working example is as follows
using namespace cv::ml;

//Be sure to change number_of_... to fit your data!
Mat matTrainFeatures(0,number_of_train_elements,CV_32F);
Mat matSample(0,number_of_sample_elements,CV_32F);

Mat matTrainLabels(0,number_of_train_elements,CV_32F);
Mat matSampleLabels(0,number_of_sample_elements,CV_32F);

Mat matResults(0,0,CV_32F);

//etcetera code for loading data into Mat variables suppressed

Ptr<TrainData> trainingData;
Ptr<KNearest> kclassifier=KNearest::create();

trainingData=TrainData::create(matTrainFeatures,
                        SampleTypes::ROW_SAMPLE,matTrainLabels);

kclassifier->setIsClassifier(true);
kclassifier->setAlgorithmType(KNearest::Types::BRUTE_FORCE);
kclassifier->setDefaultK(1);

kclassifier->train(trainingData);
kclassifier->findNearest(matSample,kclassifier->getDefaultK(),matResults);

//Just checking the settings
cout<<"Training data: "<<endl
    <<"getNSamples\t"<<trainingData->getNSamples()<<endl
    <<"getSamples\n"<<trainingData->getSamples()<<endl
    <<endl;

cout<<"Classifier :"<<endl
    <<"kclassifier->getDefaultK(): "<<kclassifier->getDefaultK()<<endl
    <<"kclassifier->getIsClassifier()   : "<<kclassifier->getIsClassifier()<<endl
    <<"kclassifier->getAlgorithmType(): "<<kclassifier->getAlgorithmType()<<endl
    <<endl;

//confirming sample order
cout<<"matSample: "<<endl
    <<matSample<<endl
    <<endl;

//displaying the results
cout<<"matResults: "<<endl
    <<matResults<<endl
    <<endl;

//etcetera ending for main function

Answer: KNearest::Params params;
params.defaultK=5;
params.isclassifier=true;
    //////// Train and find with knearest
        Ptr<TrainData> knn;
        knn= TrainData::create(AmatOfFeatures,ROW_SAMPLE,AmatOfLabels);
        Ptr<KNearest> knn1;
        knn1=StatModel::train<KNearest>(knn,params);
        knn1->findNearest(AmatOfFeaturesToTest,4,ResultMatOfNearestNeighbours);
        /////////////////

The names of these functions will help you find them in the documentation.
However, the documentation might be a little confusing until it is fully updated, so the best way to do exactly what you want is to make a small toy example and use the trial-and-error way of things.
This is a working example, pasted right out of my own code, which is proven to be working.  Hope that helps.

OpenCV 3 KNN implementation


XML Serializer not serializing property which has public getter but no setter

Question: I am wondering if I am missing anything here... My understanding is that I should be able to get the ID property (but not set it) after deserializing. As it stands, the ID property is not brought along at all:
<code>namespace CableSolve.Orders.Core.Dto
{
    [Serializable]
    [XmlRoot("Task"), SoapType("Task")]
    public class TaskDto : IDto
    {
        // ReSharper disable ConvertToAutoPropertyWithPrivateSetter
        private int _id;
        public int ID { get { return _id; } }
        // ReSharper restore ConvertToAutoPropertyWithPrivateSetter
        public int TaskSequence { get; set; }

        public TaskDto()
        {
        }
    }
}
</code>
Ideally my ID would not be settable. If I give the ID property an automatic, private setter -- XML Serializer throws a fit. I thought the workaround for that was described here, but it does not appear to work for non-collections? I would prefer to not have to rewrite using DataContract at this point in time.

'CableSolve.Web.Api.WorkflowServicesProxy.TaskDto' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'CableSolve.Web.Api.WorkflowServicesProxy.TaskDto' could be found
Comment: I'm assuming the Dto here means this is your Data Transfer Objects library. If that's the case then why don't you want a setter for your property? In this case it would be necessary for Deserialization.
Comment: It's the ID field of an object representing an entry in a DB. I'm not sure why we would want this modifiable. Bad things would happen if the user modified a Task's ID property and then called Save -- it would overwrite another Task's properties in the DB.
Comment: Naturally, that's why it should only be modifiable in your DTO library. Not for the user to modify but for the XmlSerializer to modify during deserialization. Once the DTO object is constructed (in your data transfer layer) you create an instance of the actual object it represents. This instance has ID as a read only field and is accessible to user code. That's the idea behind the DTO design pattern. Your DTO objects aren't for user manipulation they are strictly for data transfer.
Comment: possible duplicate of [Why are properties without a setter not serialized](http://stackoverflow.com/questions/13401192/why-are-properties-without-a-setter-not-serialized)
Answer: The deserialiser is just C# code.  It requires a setter for a serialised property.  Thus you must have a getter and setter for every property that is to be serialised by XML serializer; it also requires the property to be public.
Also you do not need an empty constructor for the class.
<code>[Serializable]
[XmlRoot("Task"), SoapType("Task")]
public class TaskDto : IDto
{
    public int ID { get; set; }
    public int TaskSequence { get; set; }
}
</code>
For more info, see http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx


Django populating ChoiceField with attributes from a ForeignKey

Question: please go easy on me because I am just starting out. I am making an instrument website where people can post their instruments for sale. On the form, I want them to use a drop-down menu that helps facilitate the selection of a category (e.g. trombone, trumpet, saxophone, etc...)
When I use the following code, I get something like this in the dropdown:

Category Object
Category Object
Category Object
and these seem to be the correct Category Objects, but what I need is for them to say "Trumpet", "Trombone", "Saxophone" etc. from the database.
Form
class InventoryForm(forms.Form):
  description = forms.CharField(required=False)
  instrumentCategory = forms.ModelChoiceField(queryset=pmod.Category.objects.all())

Model
class Category(models.Model):
    instrumentCategory=models.CharField(max_length=50,blank=True,null=True)

class Instrument(models.Model):
    description=models.CharField(max_length=1000,blank=True,null=True)
    instrumentCategory=models.ForeignKey(Category)

Again, how do I get the dropdown to display the instrument category instead of "Category Object" for each option? Thanks in advance
Answer: Implement __unicode__ (__str__ in python 3) on your models to return what you want to see in the choice list:
class Category(models.Model):
    instrumentCategory=models.CharField(max_length=50,blank=True,null=True)

    def __unicode__(self):
        return self.instrumentCategory

This is because Django doesn't automatically know how you want to represent each object.
Check out the python_to_unicode_compatible decorator mentioned here: https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#model-style
Answer: Perfect! The above code was correct, but I just had to add this onto my model:
def __str__(self):
    return self.instrumentCategory

Comment: That's because you're using Python 3, as Robert mentioned in his answer, remember to mark the answer as correct :)


how to make hero animation in a datatable widget?

Question: Hello everybody I have a datatable in which I filled with some data I want to  add hero tag to each row in the datatable so when I click on that row it will open another MaterialPageRoute which contains a widget with the same hero tag of that particular row.
The problem is that the hero animation is not working properly it shows the
MaterialPageRoute normally without animation.
import 'package:art_sweetalert/art_sweetalert.dart';
import 'package:flutter/material.dart';
import 'package:global_flutter_lib/I18n-Helper.dart';
import 'package:provider/provider.dart';
import 'package:shopping_cart_data/Data/Models/Setting.dart';
import 'package:shopping_cart_project/App-Widgets/App-Colors.dart';
import 'package:shopping_cart_project/Helpers/App-UI-Helper.dart';
import 'package:shopping_cart_project/States/States.dart';

import 'CustomRect-Tween.dart';
import 'hero-tags.dart';

class SettingTableWidget extends StatefulWidget {
  const SettingTableWidget({Key? key}) : super(key: key);

  @override
  State<SettingTableWidget> createState() => _SettingTableWidgetState();
}

class _SettingTableWidgetState extends State<SettingTableWidget> {
  GlobalKey<ArtDialogState>? _artDialogKey;

  final Map<int, GlobalKey> _buttonMapKeys = {};

  Setting? _selectedSetting;
  String? companyHeaderText;

  String? nameArabicHeaderText;
  String? nameEnglishHeaderText;
  String? yearHeaderText;
  String? ipHeaderText;
  String? portHeaderText;

  String? defaultHeaderText;

  String? addSettingText;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    companyHeaderText ??= I18nHelper.t(context, "setting.company");

    nameArabicHeaderText ??= I18nHelper.t(context, "setting.nameArabic");
    nameEnglishHeaderText ??= I18nHelper.t(context, "setting.nameEnglish");
    yearHeaderText ??= I18nHelper.t(context, "setting.year");
    ipHeaderText ??= I18nHelper.t(context, "setting.ip");
    portHeaderText ??= I18nHelper.t(context, "setting.port");

    defaultHeaderText ??= I18nHelper.t(context, "setting.default");

    addSettingText ??= I18nHelper.t(context, "global.add");
  }

  @override
  Widget build(BuildContext context) {
    SettingState settingState = Provider.of<SettingState>(context);

    return Column(
      children: [
        Row(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 8.0),
              child: ElevatedButton(
                  style:
                      ElevatedButton.styleFrom(primary: AppColors.primaryColor),
                  onPressed: _addNewRow,
                  child: Text(addSettingText!)),
            )
          ],
        ),
        const SizedBox(
          height: 10,
        ),
        Expanded(
          child: DataTable(
              headingRowColor: MaterialStateColor.resolveWith(
                  (states) => Colors.grey.shade300),
              showBottomBorder: true,
              showCheckboxColumn: false,
              columns: _createColumns(),
              rows: _createRows()),
        ),
      ],
    );
  }

  final TextStyle _columnHeaderStyle =
      const TextStyle(fontWeight: FontWeight.bold);

  _createColumns() {
    List<DataColumn> colList = [];
    colList.add(const DataColumn(label: Text("")));
    colList.add(DataColumn(
        label: Text(
      companyHeaderText!,
      // I18nHelper.t(context, "setting.company"),
      style: _columnHeaderStyle,
    )));
    colList.add(DataColumn(
        label: Text(
      nameArabicHeaderText!,
      style: _columnHeaderStyle,
    )));
    colList.add(DataColumn(
        label: Text(
      nameEnglishHeaderText!,
      style: _columnHeaderStyle,
    )));
    colList.add(DataColumn(
        label: Text(
      yearHeaderText!,
      style: _columnHeaderStyle,
    )));
    colList.add(DataColumn(
        label: Text(
      ipHeaderText!,
      style: _columnHeaderStyle,
    )));
    colList.add(DataColumn(
        label: Text(
      portHeaderText!,
      style: _columnHeaderStyle,
    )));

    colList.add(const DataColumn(
        label: SizedBox(
      width: 0,
      height: 0,
    )));
    return colList;
  }

  _createRows() {
    SettingState settingState =
        Provider.of<SettingState>(context, listen: false);
    List<DataRow> rowList = [];
    for (Setting s in settingState.list) {
      rowList.add(DataRow(
          color: settingState.current == s
              ? MaterialStateProperty.all(Colors.grey.shade300)
              : MaterialStateProperty.all(Colors.white),
          onSelectChanged: (selected) => _onSelectChanged(s, selected),
          cells: [
            DataCell(_createActions(s)),
            DataCell(Text(s.company ?? "")),
            DataCell(Text(s.nameArabic ?? "")),
            DataCell(Text(s.nameEnglish ?? "")),
            DataCell(Text(s.year.toString())),
            DataCell(Text(s.ip.toString())),
            DataCell(Text(s.port.toString())),
            DataCell(Row(
              children: [
                settingState.defaultSetting?.id == s.id
                    ? Icon(
                        Icons.check,
                        color: AppColors.primaryColor,
                      )
                    : Container(),
                ElevatedButton(
                    onPressed: () async {
                      // I18nHelper.setLocale(context, SessionVariables.language!);
                      await settingState.setSettingAsDefault(setting: s);
                    },
                    child: Text(defaultHeaderText!))
              ],
            )),
          ]));
    }
    return rowList;
  }

  _onSelectChanged(Setting s, bool? selected) {
    //=================
    // print("_onSelectChanged Selected ;$selected - Setting: ${s.nameArabic}");
    SettingState settingState =
        Provider.of<SettingState>(context, listen: false);
    settingState.setCurrent(s);
    // _selectedSetting = s;
  }

  _createActions(Setting setting) {
    if (_buttonMapKeys.containsKey(setting.id) == false) {
      _buttonMapKeys[setting.id as int] = GlobalKey();
    }
    return Row(children: [
      Hero(
        tag:setting.id,
        createRectTween: (begin, end) {
          return CustomRectTween(begin: begin!, end: end!);
        },
        child: IconButton(
          key: _buttonMapKeys[setting.id],
          color: AppColors.primaryColor,
          onPressed: () => _editRow(setting),
          icon: const Icon(Icons.edit),
        ),
      ),
      IconButton(
        color: AppColors.primaryColor,
        onPressed: () => _deleteRow(setting),
        icon: const Icon(Icons.delete),
      )
    ]);
  }

  _addNewRow() {
    Setting s = Setting.create();
    AppUIHelper.showSettingFormDialog(context, s);
  }

  void _editRow(Setting s) async {
    RenderBox? renderBox =
        _buttonMapKeys[s.id]?.currentContext?.findRenderObject() as RenderBox?;

    SettingState settingState =
        Provider.of<SettingState>(context, listen: false);

    settingState.setCurrent(s);

    // AppUIHelper.showSettingFormDialog(context, s,
    //     offset: renderBox?.localToGlobal(const Offset(0, 0)) as Offset);

    showSettingFormDialog(
      context,
      s,
    );
  }

  void _deleteRow(Setting s) async {
    SettingState settingState =
        Provider.of<SettingState>(context, listen: false);

    settingState.setCurrent(s);
    AppUIHelper.showConfirmDelete(context, onConfirm: () async {
      await settingState.deleteRow();
    });
  }

   showSettingFormDialog(){
        showSettingFormDialog(BuildContext context, Setting setting,
      {String title = ""}) {
    Navigator.push(
        context,
        HeroDialogRoute(
            horizPadding: 370,
            tag: setting.id,
            title: title,
            builder: (_) => SettingFormWidget(
                  setting: setting,
                )));
  }
    }
}

//======================HeroTagDialog

/// {@template hero_dialog_route}
/// Custom [PageRoute] that creates an overlay dialog (popup effect).
///
/// Best used with a [Hero] animation.
/// {@endtemplate}
class HeroDialogRoute<T> extends PageRoute<T> {
  final double? vertPadding;
  final double? horizPadding;

  final String? tag;
  final String? title;

  /// {@macro hero_dialog_route}
  HeroDialogRoute(
      {required WidgetBuilder builder,
      RouteSettings? settings,
      bool fullscreenDialog = false,
      this.vertPadding = 80,
      this.horizPadding = 80,
      this.tag,
      this.title})
      : _builder = builder,
        super(settings: settings, fullscreenDialog: fullscreenDialog);

  final WidgetBuilder _builder;

  @override
  bool get opaque => false;

  @override
  bool get barrierDismissible => false;

  @override
  Duration get transitionDuration => const Duration(milliseconds: 600);

  @override
  Duration get reverseTransitionDuration => const Duration(milliseconds: 900);

  @override
  bool get maintainState => true;

  @override
  Color get barrierColor => Colors.black54;

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation, Widget child) {
    return ScaleTransition(scale: animation, child: child);
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(
            vertical: vertPadding ?? 80.0, horizontal: horizPadding ?? 80.0),
        child: Hero(
          tag: tag ?? "HeroTag",
          createRectTween: (begin, end) {
            return CustomRectTween(begin: begin!, end: end!);
          },
          child: Container(
            decoration: BoxDecoration(
                borderRadius: const BorderRadius.all(Radius.circular(20)),
                border: Border.all(color: AppColors.primaryColor, width: 4)),
            child: ClipRRect(
              clipBehavior: Clip.antiAliasWithSaveLayer,
              borderRadius: const BorderRadius.all(Radius.circular(20)),
              child: Scaffold(
                appBar: AppBar(
                    backgroundColor: AppColors.primaryColor,
                    title: AppUIHelper.dialogTitle(title: title ?? "No Title")),
                body: _builder(context),
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  String get barrierLabel => 'Popup dialog open';
}

Comment: Far too much code. Please read [mre] and then [edit] your post to the absolute minimum number of lines that demonstrate the issue.
Answer: I found out the problem I wrapped the SettingTableWidget with AlertDialog and any child widgets inside the AlertDialog does not support the hero tag so instead of using showDialog method I used
Navigator.of(context).push(MaterialPageRoute(builder(_)=>SettingTableWidget()))

and it works like charm,thanks.


Does the laziness of vendors affect how the rides/shops run?

Question: I was looking through some of the menus and I noticed that vendors have a significantly high laziness.

Does this affect how any of the rides or shops run and does training them/giving them discipline do anything to affect the productivity of the rides or shops (like when you train mechanics or janitors)?
Comment: I'm not sure about ride vendors, but shop stalls would take longer to go through customers the lazier they were, but since guests in line just throw money at the vendor then go on the ride, it doesn't seem like they are affected.
Comment: @Rapitor You can go ahead and post an answer anyways, I didn't know that about the shop stalls which answers most of my question. The ride vendor answer makes sense as well.
Answer: Yes - laziness effects the productivity of your staff.
Laziness is reduced through training which in turn increases the productivity of your staff (ie: janitors will actively seek out the nearest mess, entertainers will actively seek out the saddest guest, vendors will process customers faster, etc).


ASP.NET getting an error when trying to insert into MSAccess DB

Question: I have a school project due soon, it is a web app in ASP.NET and I thought I had finished and had it working as intended using a local mysql database. My professor has recently instructed us to change our database to MS Access and I have most of my classes working (ones like login where it only checks the data already in the table). The last one i'm having issues with is my registration page, i'm getting an error regarding my insert statement. (An exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll but was not handled in user code
Additional information: Syntax error in INSERT INTO statement.)
I have tried tweaking various things based on other posts/youtube videos but nothing has worked thus far. I'd greatly appreciate someone pointing out where i'm going wrong! Thanks in advance.
protected void submitBtn_Click(object sender, EventArgs e)
    {
        OleDbConnection connect = new OleDbConnection(ConfigurationManager.ConnectionStrings["newregDBConnectionString"].ConnectionString);
        {
            if (parentRadBtn.Checked)
            {
                if (firstNameBox.Text == "" || surnameBox.Text == "" || postcodeBox.Text == "" || teleBox.Text == "" || emailBox.Text == "" || userBox.Text == "" || passwordBox.Text == "")
                {
                    Response.Write("");
                    successLabel.Text = ("");
                    userBox.Text = "";
                    firstNameBox.Text = "";
                    surnameBox.Text = "";
                    postcodeBox.Text = "";
                    teleBox.Text = "";
                    emailBox.Text = "";
                    passwordBox.Text = "";
                }
                else
                {
                    OleDbCommand pa = new OleDbCommand("INSERT INTO parent(parentID, firstname, surname, postcode, telephone, email, password) VALUES (@parentID, @firstname, @surname, @postcode, @telephone, @email, @password)", connect);
                    pa.Parameters.AddWithValue("@parentID", userBox.Text);
                    pa.Parameters.AddWithValue("@firstname", firstNameBox.Text);
                    pa.Parameters.AddWithValue("@surname", surnameBox.Text);
                    pa.Parameters.AddWithValue("@postcode", postcodeBox.Text);
                    pa.Parameters.AddWithValue("@telephone", teleBox.Text);
                    pa.Parameters.AddWithValue("@email", emailBox.Text);
                    pa.Parameters.AddWithValue("@password", passwordBox.Text);

                    connect.Open();
                    pa.ExecuteNonQuery();
                    connect.Close();
                }

                if (IsPostBack)
                {
                    userBox.Text = "";
                    firstNameBox.Text = "";
                    surnameBox.Text = "";
                    postcodeBox.Text = "";
                    teleBox.Text = "";
                    emailBox.Text = "";
                    passwordBox.Text = "";
                }

            }
            else if (childRadBtn.Checked)
            {
                if (firstNameBox.Text == "" || dayDobList.Text == "" || monthDobList.Text == "" || yearDobList.Text == "" || genderList.Text == "" || userBox.Text == "" || passwordBox.Text == "")
                {
                    Response.Write("");
                    successLabel.Text = ("");
                    userBox.Text = "";
                    firstNameBox.Text = "";
                    dayDobList.Text = "";
                    monthDobList.Text = "";
                    yearDobList.Text = "";
                    genderList.Text = "";
                    passwordBox.Text = "";
                }
                else
                {
                    OleDbParameter dob = new OleDbParameter("@dob", OleDbType.DBDate);
                    dob.Value = new DateTime(Int32.Parse(yearDobList.Text), Int32.Parse(monthDobList.Text), Int32.Parse(dayDobList.Text));

                    OleDbCommand ca = new OleDbCommand("INSERT INTO children(childID, firstname, dob, gender, password) VALUES (@childID, @firstname, @dob, @gender, @password)", connect);
                    ca.Parameters.AddWithValue("@childID", userBox.Text);
                    ca.Parameters.AddWithValue("@firstname", firstNameBox.Text);
                    ca.Parameters.Add(dob);
                    ca.Parameters.AddWithValue("@gender", genderList.Text);
                    ca.Parameters.AddWithValue("@password", passwordBox.Text);

                    connect.Open();
                    ca.ExecuteNonQuery();
                    connect.Close();
                }
                if (IsPostBack)
                {
                    userBox.Text = "";
                    firstNameBox.Text = "";
                    dayDobList.Text = "";
                    monthDobList.Text = "";
                    yearDobList.Text = "";
                    genderList.Text = "";
                    passwordBox.Text = "";
                }
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("ViewDelete.aspx");
    }

    protected void backBtn_Click(object sender, EventArgs e)
    {
        Response.Redirect("Home.aspx");
    }

    protected void emailBox_TextChanged(object sender, EventArgs e)
    {

    }

    protected void userBox_TextChanged(object sender, EventArgs e)
    {

    }

    protected void firstNameBox_TextChanged(object sender, EventArgs e)
    {

    }
}

}
Answer: From MSDN:

The OLE DB .NET Provider does not support named parameters for passing
  parameters to an SQL statement or a stored procedure called by an
  OleDbCommand when CommandType is set to Text. In this case, the
  question mark (?) placeholder must be used. Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

By default OleDbCommandType is set to Text, hence your parent & children query should be changed to this (note that all OleDbParameter should declared in their proper order):
// insert parent command
OleDbCommand pa = new OleDbCommand("INSERT INTO parent(parentID, firstname, surname, postcode, telephone, email, [password]) VALUES (?, ?, ?, ?, ?, ?, ?)", connect);

// insert children command
OleDbCommand ca = new OleDbCommand("INSERT INTO children(childID, firstname, dob, gender, [password]) VALUES (?, ?, ?, ?, ?)", connect);

NB: All column names which potentially conflicted with Access OLE DB reserved words should put into square brackets to prevent accidental usage of either Access JET SQL keyword or Access ACE SQL keyword (i.e. PASSWORD).
SO related issues:
What's wrong with these parameters?
insert into access database
Comment: Thank you so much, putting square brackets on password worked. I did look at reserved words briefly but didn't see password when glancing over! Again, thank you :)


Why do I get not allowed access when using keycloak JavaScript adapter?

Question: I have a Django app authenticating via Keycloak as described here. From this Django app I now wants to call a microservice also protected by Keycloak using the same login. I don't want the suer to have to login again. I am trying to yse the JavaScript adapter. I am trying to configure it something like:

But when I load the page I get this sort of error messages:
Failed to load http://keycloak.FOO.com/auth/realms/toxhq/protocol/openid-connect/token: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myapp.Foo.com' is therefore not allowed access.
I am not fully sure why this is but I am beginning to wonder if it is because of same-origin policy in some way.
How can I set up the functionality I want with Keycloak protected microservices sharing one Keycloak authentication?
Answer: You have to set the allowed origin for myclientin the Keycloak console. (check the last input box on the client details screen)


Why does C++23 ranges::to not constrain the container type C to be a range?

Question: C++23 introduced the very powerful ranges::to for constructing an object (usually a container) from a range, with the following definition ([range.utility.conv.to]):
template<class C, input_range R, class... Args> requires (!view<C>)
  constexpr C to(R&& r, Args&&... args);

Note that it only constrains the template parameter C not to be a view, that is, C may not even be a range.
However, its implementation uses range_value_t<C> to obtain the element type of C, which makes C at least a range given the range_value_t constraint that the template parameter R must model a range.
So, why is ranges::to so loosely constrained on the template parameter C?
I noticed that the R3 version of the paper used to constrain C to be input_range, which was apparently reasonable since input_range guaranteed that the range_value_t to be well-formed, but in R4 this constraint was removed. And I didn't find any comments about this change.
So, what are the considerations for removing the constraint that C must be input_range?
Is there a practical example of the benefits of this constraint relaxation?
Comment: I would think `requires(input_range)` = "shall not participate in overload resolution if not input_range, SFINAE/concepts friendly", but [being ill-formed if not range](https://eel.is/c++draft/range.utility.conv.to#1.3) allows a `static_assert`, like in [this implementation](https://github.com/microsoft/STL/blob/82c81e8fb12fa457344c7c7f8a2f0a7e38263a77/stl/inc/ranges#L6924). Unsure how this interacts with your `range_value_t` point.
Answer: This is a problem with the wording that we'll need to address, I'll open an issue later today. This is LWG 3785.

So, what are the considerations for removing the constraint that C must be input_range?

The goal of ranges::to is to collect a range into... something. But it need not be an actual range. Just something which consumes all the elements. Of course, the most common usage will be an actual container type, and the most common actual container type will be std::vector.
There are other interesting use-cases though, that there really isn't much reason to reject.
Let's say we have a range of std::expected<int, std::exception_ptr>, call it results. Maybe we ran a bunch of computations and maybe some of them failed. I could collect that into a std::vector<std::expected<int, std::exception_ptr>>, and that might be useful. But there's another alternative: I could collect it into a std::expected<std::vector<int>, std::exception_ptr>. That is, if all of the computations succeeded, I get as a value type all of the results. However, if any of them failed, I get the first error. That's a very useful thing to be able to do, that is very much conceptually in line with what ranges::to is doing to its input - so this could support:
auto processed = results | ranges::to<std::expected>();
if (not processed) {
    std::rethrow_exception(processed.error());
}

std::vector<int> values = std::move(processed).value();
// go do more stuff

This is quite useful to support - especially since it doesn't really cost anything to not support it. We just have to not prematurely reject it.
Comment: @康桓瑋 That doesn't really make any sense? You wouldn't `to>`, you'd `to>`. `to` isn't really fallible, so what would `to>` do if the range wasn't exactly one element? And then the rest are even less meaningful.
Comment: Thanks for the comprehensive answer, which solved my confusion. But what I don't quite understand is why `C` can't be a `view` (such as `owning_view` or `single_view` which actually owns elements). What potential problems does it bring?
Comment: I thought it might still be useful to remove the constraint that `C` is not a view, I often need to convert `subrange`s to a `string_view`s, and this relaxation allows me to spell `rng | views::transform(ranges::to())`.


get topic of sentence from pre-trained model

Question: I have a list of 10 sentences from a text file.
I want to use an existing topics model to get the topics of every sentence.
In all the tutorials I found - they trained the topic model on their corpus. I want to use one that was trained in existing corpus and just apply it on my sentences.
Is this possible?
Comment: I can't escape the feeling that this question belongs more to [CrossValidated](https://stats.stackexchange.com/) SO community than StackOverflow...
Answer: Yes, it is possible as long as the language of your sentences matches the language of the corpus and, to a smaller degree, as long as the vocabulary of both intersect (particularly among the most distinctive words for each of the topics). Also, if there is a large divergence between human topics of your sentences and those captured in the corpus then you may end up with a not clear attribution of topics to sentences (e.g. neither of the topics will be found particularly similar to a sentence or to put it differently: all will be similar but degree of similarity will be small for all of them).
I encourage you to reuse the models you can find with the sentences you have and see experimentally if they work for you as expected.
Comment: Show us the code you tried so that we could help you (see: [MWE](https://stackoverflow.com/help/minimal-reproducible-example) ).
Comment: I haven't try any way to do it beside downloading mallet, but I want to use a pythoon-package and not have to install softwares


Help with understanding aliasing phenomena

Question: I am following these notes on signals and systems. Following is the paragraph from page 25 which I am having a difficulty with.

Discrete-time sinusoids have the obvious form $s(n) = A\cos(2πfn + φ)$. As opposed to analog complex exponentials and sinusoids that can have their frequencies be any real value, frequencies of their discrete-time counterparts yield unique waveforms only when $f$ lies in the interval $(-1/2, 1/2]$ This property can be easily understood by noting that adding an integer to the frequency of the discrete-time complex exponential has no effect on the signal's value.
$$e^{i 2 \pi (f+m) n}=e^{i 2 \pi f n}e^{i 2 \pi mn}=e^{i 2 \pi f n} $$
This derivation follows because the complex exponential evaluated at an integer multiple of $2π$ equals one.

I don't understand how can $e^{i 2 \pi mn }$ be always $1$.
Suppose $f'=f+m=0.75$ where $-1/2<f \le 1/2$,
then $f=1/2$ and $m=0.25$ but $e^{i 2 \pi 0.75 n}\neq1 \forall n \in \mathbb{Z}$
Comment: m is an integer, therefore the exponent $2\pi m n$ is a multiple of $2\pi$.
Comment: But $m$ is not always an integer if $f$ lies in $(1/2, 1/2]$
Comment: Or I must be doing something incorrect, can you point out what is wrong with my counter example at the end of my question?
Comment: $m$ is, it's $m+f$ that can be non-integer. The text says "... by noting that *adding an integer* [...] has no effect", and $m$ is that integer. Your counterexample does not use an integer for $m$.
Comment: Okay so why does $f$ has to lie in $(1/2,1/2]$ for a unique waveform?
Answer: The point of the paragraph is to show that replacing $f$ with $f+m$ does not change the waveform, for any integer m.
This would imply that it is only relevant to choose values of $f$ in an interval of length $1$, since going any wider would result in duplicates. The author of the text chooses the interval $(-\frac12, \frac12]$: you can see that there is no way to get more than one point of this set, if we only add integers; moreover, for any real number we may choose, by adding an integer we can always get to one (and only one) point of this set.
To prove this, we must show that this relation holds:
$$ e^{i2\pi (f+m) n}=e^{i2\pi f n}$$
Starting from the left side, simply distribute the exponent:
$$ e^{i2\pi (f+m) n}=e^{i2\pi f n+i2\pi m n}$$
Then, apply a property of the exponential function:
$$e^{i2\pi f n+i2\pi m n}=e^{i2\pi f n}e^{i2\pi m n}$$
Since we chose $m$ as an integer, and $n$ is also integer, then $2\pi m n$ is an integer multiple of $2\pi$, and therefore $e^{i2\pi m n}=e^0=1$.
Thus we have proved our claim.
Comment: If $f =0.75$ which does not lie in $(-1/2, 1/2]$, what is it a duplicate of?
Comment: $-0.25$, which does :) you get it by adding the integer $-1$.


bash function implement python command

Question: I have this
python -c "import sys, urllib as ul; \
    print ul.quote('sample hihi ')"

How can I wrap it into a bash function, so I can call it like a function like so:
urlencode('sample hihi ')

Thanks
Comment: This question should asked on stackoverflow, the possibility to receive an answer is higher then here.
Comment: @AtomiX84 shell scripting is perfectly on topic here. Please don't recommend moving on topic questions.
Answer: You should pass the function arguments into your Python code as regular shell arguments, which can be accessed there through the sys.argv array. In the Bash function, its call arguments can be accessed e.g. through "$*", which returns all arguments as a single, space separated string argument (as if it were quoted as a whole, not separate tokens).
Here's an example that follows your original code:
urlquote() { python -c 'import sys, urllib as ul; print ul.quote(sys.argv[1])' "$*" ;}

However, as Python 2 support will end soon, here's the better Python 3 equivalent:
urlquote() { python3 -c 'import sys, urllib.parse as ul; print(ul.quote(sys.argv[1]))' "$*" ;}

The invocation is the same for both, type the function name followed by the string you want to encode as argument. Don't forget to quote it appropriately:
$ urlquote "roses are red, violets are blue..."
roses%20are%20red%2C%20violets%20are%20blue...

Note: Don't ever directly inject shell arguments into your Python code string, like python -c "print('$x')", as this could lead to easily exploitable security risks if you ever plan to run your function on untrusted input, allowing people to run arbitrary commands!
Have a look at this shell example, where I craft the argument in the variable x in a way to run the system command uname (which is harmless and just prints "Linux", but you can do everything here):
$ x="');import os;os.system('uname');('"

$ python3 -c "print('$x')"
Linux

bash function implement python command


Characters get trimmed when sending values from one page to another in asp.net

Question: I am sending some values from one page to another in asp.net using javascript. I have declared JS in parent page and the values are being sent to child page and fetched in code behind page using Request.Querystring. Look to my previous question here
To give you a detailed look, See below example
chStatusReport.Attributes.Add("onclick", "javascript:return Navigate( '" + varTrimmed+ "' );");

JS to open a child page is under

Code fetching the value pass from parent to child page.
 if (Request.QueryString.Count!=0)

 { svar1= Request.QueryString["status"];
   }

Values that are being passed are like 1 )Tom & Peter 2 ) Laurence & Hardy
The values that i get are 1 ) Tom  2) Laurence
Why the remaining text get trimmed?
Comment: I believe there is a specific usage of `&` in a query string, you gotta encode for it and the spaces... URLEncode and URLDecode is what you should look at
Answer: Are you actually passing Tom & Peter?  I.e., ChildPage.aspx?status=Tom & Peter?
If you are, then the query string will have:
QueryString["Status"] with Tom and QueryString["Peter"].

The & is a delmiter between value pairs in the query string.
You'll need to URL Encode the URI.  Take a look at JavaScript encodeURIComponent.
Answer: You can't use & directly in querystring.
You have to either encode or change & to another unicode manually and translate it back.
Here is a link for explanation.
http://www.kamath.com/codelibrary/cl006_url.asp


Combinatorial proof of $k\binom{n}{k} = n\binom{n-1}{k-1}$

Question: I'm trying to prove this combinatorially. $$k\binom{n}{k} = n\binom{n-1}{k-1}$$
I know the first step is to relate a question to the equation. My question was if you have $n$ friends how many ways can you choose $k$ of them. I know this isn't correct because that would be the question if the left side wasn't being multiplied by k. Can anyone help me figure out what multiplying ${n \choose k}$ by $k$ means?
Comment: See http://math.stackexchange.com/questions/299598/combinatorial-argument-for-the-identity-k-binomnk-n-binomn-1k-1?rq=1
Comment: Algebraic approach can be found here (and probably in several other posts): http://math.stackexchange.com/questions/743261/prove-k-binom-nk-n-binomk-1-n-1-algebraically
Answer: The standard example is that you have a group of $n$ people, and want to pick a committee of $k$, including a designated committee Chair. We count the number of ways to do this in two ways.
(a) You can pick $k$ people, and then pick one of these to be Chair. This can be done in $\binom{n}{k}\cdot k$ ways.
(b) You can pick a Chair, and pick $k-1$ people to join her. This can be done in $n\binom{n-1}{k-1}$ ways.
Remark: A less bureaucratic example would be nice. You have $n$ friends and a large van, and want to pick $k$ friends to go drinking, with one of them the designated driver.


Getting applications with 2 or more activities

Question: I'm writing an Launcher app for android.
I can get the list of all applications and launch able activities with
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = ctx.getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES);

final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(ctx.getPackageManager());

Collections.sort(packs, new Comparator<PackageInfo>() {
    @Override
    public int compare(PackageInfo lhs, PackageInfo rhs) {
        return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
    }
});

for (int i = 0; i < packs.size(); i++) {
    PackageInfo p = packs.get(i);
    if (p.packageName != null && ctx.getPackageManager().getLaunchIntentForPackage(p.packageName) != null ) {
        PInfo newInfo = new PInfo();
        if (p.applicationInfo.loadLabel(ctx.getPackageManager()).toString().length() > 15) {
            newInfo.appname = p.applicationInfo.loadLabel(ctx.getPackageManager()).toString().substring(0, 15);
        } else {
            newInfo.appname = p.applicationInfo.loadLabel(ctx.getPackageManager()).toString();
        }
        newInfo.packageName = p.packageName;
        newInfo.icon = p.applicationInfo.loadIcon(ctx.getPackageManager());
        res.add(newInfo);
    }
}

this.
But, the problem is, there is 2 launch able activities included like phone and contacts app.
I mean for example samsung included contacts launch able activity and phone launch able activity in same package. But with this code i can only get the contacts application into my view, phone app is missing. how other launchers are handling this?
or what am i missing?
Answer: Don't look for apps. Look for launchable activities, using queryIntentActivities() on PackageManager.
For example, this activity (from this sample project) implements a home screen-style launcher using this technique:
/***
  Copyright (c) 2008-2012 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    http://commonsware.com/Android
*/

package com.commonsware.android.launchalot;

import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;

public class Launchalot extends ListActivity {
  AppAdapter adapter=null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    PackageManager pm=getPackageManager();
    Intent main=new Intent(Intent.ACTION_MAIN, null);

    main.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> launchables=pm.queryIntentActivities(main, 0);

    Collections.sort(launchables,
                     new ResolveInfo.DisplayNameComparator(pm));

    adapter=new AppAdapter(pm, launchables);
    setListAdapter(adapter);
  }

  @Override
  protected void onListItemClick(ListView l, View v,
                                 int position, long id) {
    ResolveInfo launchable=adapter.getItem(position);
    ActivityInfo activity=launchable.activityInfo;
    ComponentName name=new ComponentName(activity.applicationInfo.packageName,
                                         activity.name);
    Intent i=new Intent(Intent.ACTION_MAIN);

    i.addCategory(Intent.CATEGORY_LAUNCHER);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    i.setComponent(name);

    startActivity(i);
  }

  class AppAdapter extends ArrayAdapter<ResolveInfo> {
    private PackageManager pm=null;

    AppAdapter(PackageManager pm, List<ResolveInfo> apps) {
      super(Launchalot.this, R.layout.row, apps);
      this.pm=pm;
    }

    @Override
    public View getView(int position, View convertView,
                          ViewGroup parent) {
      if (convertView==null) {
        convertView=newView(parent);
      }

      bindView(position, convertView);

      return(convertView);
    }

    private View newView(ViewGroup parent) {
      return(getLayoutInflater().inflate(R.layout.row, parent, false));
    }

    private void bindView(int position, View row) {
      TextView label=(TextView)row.findViewById(R.id.label);

      label.setText(getItem(position).loadLabel(pm));

      ImageView icon=(ImageView)row.findViewById(R.id.icon);

      icon.setImageDrawable(getItem(position).loadIcon(pm));
    }
  }
}