Best way to distribute tasks considering latency and efficiency

Question: I'm looking for an algorithm to distribute some tasks. The problem is as follows:
Say I have a central task producer and some client consumers. The producer generates tasks and consumers take tasks (for starters, one at a time), process them, and when they are done, take new tasks (I already have a task queue).
The thing is, if you consider latency for a task to get from the producer to the consumer, it might make sense to group tasks together. For example, say we have 10 tasks in total and 2 consumers. If each of the tasks take 5 ms to get processed and the network latency is also 5 ms, sending 2 groups of 5 tasks each to each consumer will take 5ms + 5*5ms = 30ms, while sending the tasks individually would take 5*5ms + 5*5ms = 50ms, because the latency overhead appears for every task.
It's not as simple as grouping since some tasks will probably take longer, and it would make sense to send them separate as to let the other tasks that take a shorter time get processed in parallel by the other consumers. I'm planning on doing some statistics regarding the type of tasks. The number of consumers is also not constant.
Any idea of a good algorithm or a good read that can help me in achieving this?
Comment: Why not just prefetching the next task as soon as you start working on the current?
Comment: @CAFxX that might be inefficient, a consumer that's already done could have already started processing it, instead I'm waiting for the current consumer to be done.
Comment: By prefetching I obviously mean popping off the next task from the task queue, so that the latency is effectively hidden. Since the task is removed from the queue, it's impossible for another consumer to start working on it.
Comment: So will that task be lost? Where does it go when it is popped?
Comment: Your question doesn't address whether local queues are feasible.  That's rather important...  Bidirectional or multidirectional task transfer is also important to consider.
Answer: Ahhh... the classic decision between fine-grained parallelism (which gives better load balancing but relatively higher overhead for synchronizing) versus coarse-grained parallelism (which obviously gives the opposite). Sorry but there's no easy answer...
Some thoughts:

Do lots of profiling, that's a good way to find a suitable number of tasks to group together. Just good old trial and error :)
Consider making a local task queue at each client. This can enable some sort of pre-fetch, e.g. when task n finishes, request task n+5 and start task n+1. Not sure if you are using multithreading or if task n+1 will be interrupted to accept task n+5.
Try to compact the task representation as much as possible. This may mean using char instead of int (this does make a difference for arrays). Maybe some parts of the task can be recalculated when it gets to the consumer.
Consider using some sort of timer on each consumer as feedback to adjust the number of tasks to take as a group next time. If you spend too much time, then grab fewer tasks next time. Beware a fancy heuristic may have some non-trivial overhead to it.
Answer: At the moment a producer generates a task, not sending it right away will only increase that task's latency. Therefore I will assume that the task dispatcher works on snapshots of the current task queue: it takes all the tasks in the queue, sends them immediately in all directions, goes back to the queue, again takes all the tasks accumulated in the meantime, lather, rinse, repeat.
The dispatcher maintains an estimate of the completion time of each consumer. It orders the consumers according to increasing completion time and adds a task to the batch of the consumer with earliest completion time. Then it adds the average task time to that consumers completion time estimate, thus obtaining  new estimate, then reorders the consumers according to the new estimates (in O(log n) using a heap) and goes to the next task. After all the tasks of the current snapshot are processed, send batches to the consumers and go make a new snapshot.
This policy will achieve equal consumer load on average. It can be improved:

if each consumer is able to provide some feedback about the estimated completion time: it's the average task time multiplied by the number of tasks pending in the consumer. It's more precise because the consumer will use the actual time of the completed tasks instead of the average
if the time to process each task is either known or can be estimated per-task, so the dispatcher will use a per-task estimate instead of an average.

EDIT: Forgot to mention:
The completion time is estimated as start-time + average-task-time * number-of-tasks-sent-to-a-consumer + latency * number-of-batches-sent-to-a-consumer.
Comment: This is a very good answer, thanks. But I do have some notes... The system indeed passes a whole bunch of task in the queue, so when the consumers start, it's safe to assume there are enough tasks in the queue to go around. Second, it's not about the processing power of the consumers, as those are more or less the same, but rather about the task types (there are different types of tasks, some take longer, some are slower). I will try an adapted version of your suggestion.
Answer: To clarify my comment to your question, let's suppose you have the following loop in your consumer:
while (keepConsuming) {
    Task t = Task::get();
    t.process();
}

you could rewrite it like this (supposing we can use OpenMP):
Task cur=NULL, next;
do {
    #pragma omp sections
    {
        #pragma omp section
        if (cur != NULL) cur.process();
        #pragma omp section
        next = keepConsuming ? Task::get() : NULL;
    }
    cur = next;
} while (cur != NULL);

This way, the process() and get() inside the while are executed in parallel (obviously, assuming those two functions don't share any state).
Answer: It seems that the main issue with the simple approach is that the consumer will stall for the amount of time it takes to fetch the next task. No useful work gets done during the stall.
Since latency -- rather than bandwidth -- is the main problem, one solution is to amortize the stall across multiple tasks, for example by grouping tasks into batches. To do this well, you need to have a good idea of how long each task will take to process.
An alternative is to fetch the next task in parallel with processing the current one. This can be easily done with two threads: thread A processing the current task and thread B fetching the next task. When A is done with the current task, the threads can either switch roles or pass the next task from B to A. This is a form of pipeline parallelism.
Comment: That's what I was saying - grouping the tasks in batches. But the question really is... how? How many tasks depending on the number of consumers, latency, average task processing time... should be grouped per batch? Pre-fetching will also not be efficient since a different consumer might already be ready to fetch the task, but it was fetched by a consumer that isn't yet processing it.
Comment: @LuchianGrigore: I think you need to move away from the idea that the algorithm should do the optimal thing in every possible (corner) case. What matters more is the performance *on average*, since this is what matters in the aggregate.
Comment: Of course, but I still don't know how to do the grouping considering the **average** times for a given type of tasks or the **average** latency. I know grouping is the way to go, but I still need to know how to do it.
Comment: @LuchianGrigore: Actually, the point of my answer was exactly the opposite. I think that prefetch is the way to go, despite the corner case that you've outlined in a previous comment.
Comment: But preferching doesn't solve anything, since it also implies latency. Even running on separate threads...
Answer: If your definition of latency can be augmented to 2 dimensions means that a cosumer can have different latency then you might try a space-filling-curve. A sfc subdivide the 2d and reduce the complexity to a 1 dimensiona. So you compute a number from f(x,y). Then you can sort this number and send the number in this order to the consumers. Of course you must write a SFC before you can use it I won't do it for you but I can help you if you have problems.
Comment: I didn't downvote, but I see two reasons: your answer is quite poorly written, and you didn't explain how the SFC will help solve the problem, only that one could create a SFC.
Comment: I wrote he can sort the numbers and send the number in this order to the consumers. What is unclear with this?


NSMutableAttributedString lost attribute with assign to a UITextView on iOS6

Question: I needs to develop a app that can do some syntax highlight for patch file, and it highly depends on NSMutableAttributedString which added in iOS6, so I create a master/detail view to show the file, with a processor class, which add highlight attribute for each line of text, but when I assign this attributeString to the UITextView.attributeString, I found all attribute that was lost.
My code is like this:
<code>- (IBAction)ColorIconClicked:(id)sender {

NSMutableAttributedString *str = [[NSMutableAttributedString alloc
                                   ] initWithAttributedString:self.textView.attributedText];
self.textView.text = nil;
[self.textView setEditable:YES];
[[processor processPatchText:str withTheme:COLOR_TEXT_THEME_DAY suggestFormat:@"diffu"] attributedSubstringFromRange:NSMakeRange(0, str.length)];

self.textView.attributedText = str;

NSLog(@"|||||||||||||||||||||||||||||||||");

NSLog(@"STD: %@", str);
NSLog(@"-----------------------------");
NSLog(@"%@", self.textView.attributedText);

[self.textView setEditable:NO];
}
</code>
The log I have capture is below:
This is the dump of "str" before assign:
<code>2012-10-19 01:12:42.863 ColorDiff[354:907] |||||||||||||||||||||||||||||||||
2012-10-19 01:12:42.883 ColorDiff[354:907] STD: diff --git a/ColorDiff/CDTextProcessor.m b/ColorDiff/CDTextProcessor.m{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}index 3e554fa..18723b2 100644{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}--- a/ColorDiff/CDTextProcessor.m{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+++ b/ColorDiff/CDTextProcessor.m{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}@@ -15,9 +15,19 @@{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
} // git format-patch or something like svn or raw diff output.{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
} //{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
} // then it should call the different render to do the actually render job.{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}-- (NSMutableAttributedString *) processPatchText:(NSMutableAttributedString*) attstring withTheme: (int) theme suggestFormat:(NSString *) format{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+- (NSMutableAttributedString *) processPatchText:(NSMutableAttributedString *) attstring{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+                                       withTheme:(int) theme{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}

{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+ * This function return the patch format for the input text.{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+ * return type should be like: diffu, diffc, etc, aligh with colordiff.pl{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+ */{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+- (NSString *) detechPatchFormatForText:(NSMutableAttributedString *) attstring{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+{{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+    {
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}+}{
    NSColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
</code>
But after assign:
The dump of textView's attribute like this
<code>"NSLog(@"%@", self.textView.attributedText);" is become:
2012-10-19 01:12:42.924 ColorDiff[354:907] -----------------------------
2012-10-19 01:12:42.991 ColorDiff[354:907] diff --git a/ColorDiff/CDTextProcessor.m b/ColorDiff/CDTextProcessor.m
index 3e554fa..18723b2 100644
--- a/ColorDiff/CDTextProcessor.m
+++ b/ColorDiff/CDTextProcessor.m
@@ -15,9 +15,19 @@
// git format-patch or something like svn or raw diff output.
//
// then it should call the different render to do the actually render job.
-- (NSMutableAttributedString *) processPatchText:(NSMutableAttributedString*) attstring withTheme: (int) theme suggestFormat:(NSString *) format
+- (NSMutableAttributedString *) processPatchText:(NSMutableAttributedString *) attstring
+                                       withTheme:(int) theme
+                                   suggestFormat:(NSString *) format
{

}

+/*
+ * This function return the patch format for the input text.
+ * return type should be like: diffu, diffc, etc, aligh with colordiff.pl
+ */
+- (NSString *) detechPatchFormatForText:(NSMutableAttributedString *) attstring
+{
+
+}
{
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0x210595f0> font-family: \".Helvetica NeueUI\"; font-weight: normal; font-style: normal; font-size: 14px";
    NSKern = 0;
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n), DefaultTabInterval 36, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
</code>
It's the attribute of str is lost when assign the self.textView.attributedText of textView.
Why ?
This is a BUG ?
How can I assign the attribute string of to a textView ?
Answer: These is no BUG in iOS, it's caused by my programming error, so the attribute actually not have right attributed with different color, after fix it, the program works again.


When is window.location.href = url gets executed?

Question: For the following code
window.location.href = url;
$(window.document.body).append(compiledTemplate);

I want $(window.document.body).append(compiledTemplate);
to be appended on the new Page which will get opened, but it appends thecompiledTemplate` in the existing window then loads the url specified
Is there a way to do that. ?
Note: url to be passed already has its Form load event defined. I do not want to override it.
Comment: If I understand correctly, why not simply have two scripts, one on the current page (to change to the new page) and one on the new page (to append the content).
Comment: This is not possible. You cannot directly amend the state of a subsequent page from the current. You could however send the information via the querystring, use localStorage or a cookie, or retrieve it from a server-side database. The next page could then act on that information.
Comment: If you want to change the contents of `document.body` and the URL visible in the browser you should look at `history.pushState()`
Answer:
When is window.location.href = url gets executed?

Very close to immediately. It tells the browser to start the process of loading the new page. The current page, and the code on it, will continue to run until the new page starts loading. More below.

I want $(window.document.body).append(compiledTemplate); to be apended on the new Page which will get open.

You can't. The code in the current page cannot act on the next page. To act on the next page, you have to have your code in that page.
Your best bet is to have the current page supply information to the new page in some other way:

Via a query string parameter
Via local storage or session storage
Via a cookie (blech)

...and then have code on the new page append the content.

If you're doing this in response to a user-generated event, you might be able to do this instead:
var wnd = window.open(url);
$(wnd).load(function() {
    $(this).append(compiledTemplate);
});

...but it would open the URL in a new page (probably a new tab) and leave the current window open, and it would only work for pages from the same origin.

For instance, if you had this on a page: Live Example
<input type="button" id="the-button" value="Click">

When you clicked the button, you'd see the code after the line setting location.href run, showing "Set, counter = 1" and then probably several more "counter = x" lines, and then eventually the page would be replaced by Stack Overflow. At that point, the code of the old page has been terminated. It can't do anything to the new page.
Comment: While the current code cannot act on the next page, if he is simply moving across his same domain, he could consider using ajax requests to better control the loading of data.

So instead of using a window location change, simply load the data using ajax and then append the content. Would probably make it lighter than loading two full pages.
Comment: used
var wnd = window.open(url);
$(wnd).load(function() {
    $(this).append(compiledTemplate);
});

still appends the the template on the same page
not on the new window open


Log-Cauchy Random Number Generation

Question: I need to draw random numbers from a log-cauchy distribution which has density: $$f(x;\mu,\sigma)=\frac{1}{x\pi\sigma\left[1+\left(\frac{ln(x)-\mu}{\sigma}\right)^2\right]}\qquad x>0.$$  Can anyone help me out or point me to a book/paper that could show me how?
Answer: A variable $X$ has a log-cauchy distribution if $\log(X)$ has a cauchy distribution. So, we just need to generate cauchy random variables and exponentiate them to get something that is log-cauchy distributed.
We can generate from the cauchy distribution using inverse transform sampling, which says that if you plug random uniforms into the inverse CDF of a distribution, then what you get out has that distribution. The cauchy distribution with location $\mu$ and scale $\sigma$ has CDF:
$$
F(x) = \frac{1}{\pi} \arctan\left(\frac{x-\mu}{\sigma}\right)+\frac{1}{2} $$
it is straightforward to invert this function to find that
$$
F^{-1}(y) =\mu + \sigma\,\tan\left[\pi\left(y-\tfrac{1}{2}\right)\right] $$
Therefore if $U \sim {\rm Uniform}(0,1)$ then $Y = \mu + \sigma\,\tan\left[\pi\left(U-\tfrac{1}{2}\right)\right]$ has a cauchy distribution with location $\mu$ and scale $\sigma$ and $\exp(Y)$ has a log-cauchy distribution. Some R code to generate from this distribution (without using rcauchy :))
rlogcauchy <- function(n, mu, sigma)
{
    u = runif(n)
    x = mu + sigma*tan(pi*(u-.5))
    return( exp(x) )
}

Note: since the cauchy distribution is very long tailed, when you exponentiate them on a computer you may get values that are numerically "infinite". I'm not sure there's anything to be done about that.
Also note that if you were to do inverse transform sampling using the log-cauchy quantile function directly, you'd have the same problem, since, after doing the calculation, you actually end up with the act same thing - $\exp \left( \mu + \sigma\,\tan\left[\pi\left(U-\tfrac{1}{2}\right)\right] \right)$

Log-Cauchy Random Number Generation


flutter bottomNavigationBar not changing screens

Question: I'm new to flutter, trying to implement BottomNavigationBar in a demo app. Bottom bar does show in app but can't change the current item on tapping, neither does the screen changes.
I've tried various methods to load screens but seems like the onTap function is not getting called.
Here is my code.
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {

    final Size screenSize = MediaQuery.of(context).size;

    int _currentTab = 0;

    Widget body() {
      switch (_currentTab) {
        case 0:
          return FeedScreen();
        case 1:
          return SearchScreen();
        case 2:
          return ProfileScreen();
        default:
          return FeedScreen();
      }
    }

    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        onTap: (newValue) {
          setState(() {
            _currentTab = newValue;
          });
        },
        currentIndex: _currentTab,
        items: [
          BottomNavigationBarItem(
            icon: ImageIcon(
              AssetImage('images/home.png'),
            ),
            title: SizedBox.shrink(),
          ),
          BottomNavigationBarItem(
            icon: ImageIcon(
              AssetImage('images/search.png'),
            ),
            title: SizedBox.shrink(),
          ),
          BottomNavigationBarItem(
            icon: CircleAvatar(
              radius: 15,
              backgroundImage: AssetImage('images/avatar.png'),
            ),
            title: SizedBox.shrink(),
          )
        ],
      ),
      appBar: PreferredSize(
        preferredSize: Size(screenSize.width, 50.0),
        child: CustomAppBar(),
      ),
      body: body(),
    );
  }
}

Answer: your int _currentTab = 0; is inside build method. put it outside.
everytime you trigger the setState, _currentTab will always be equal to 0 which is the FeedScreen because the variable is inside the build method
Comment: Build method called everytime when the state changes, so it always be 0 in your case, but while adding outside, then it will persist the value, As your Widget still on the screen
Answer:
Try the below code!

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

 int _currentTab = 0;

  @override
  Widget build(BuildContext context) {

    final Size screenSize = MediaQuery.of(context).size;

    Widget body() {
      switch (_currentTab) {
        case 0:
          return FeedScreen();
        case 1:
          return SearchScreen();
        case 2:
          return ProfileScreen();
        default:
          return FeedScreen();
      }
    }

    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        onTap: (newValue) {
          setState(() {
            _currentTab = newValue;
          });
        },
        currentIndex: _currentTab,
        items: [
          BottomNavigationBarItem(
            icon: ImageIcon(
              AssetImage('images/home.png'),
            ),
            title: SizedBox.shrink(),
          ),
          BottomNavigationBarItem(
            icon: ImageIcon(
              AssetImage('images/search.png'),
            ),
            title: SizedBox.shrink(),
          ),
          BottomNavigationBarItem(
            icon: CircleAvatar(
              radius: 15,
              backgroundImage: AssetImage('images/avatar.png'),
            ),
            title: SizedBox.shrink(),
          )
        ],
      ),
      appBar: PreferredSize(
        preferredSize: Size(screenSize.width, 50.0),
        child: CustomAppBar(),
      ),
      body: body(),
    );
  }
}

write int _currentTab = 0 in outside of build method, because when you update newValue into _currentTab also setState reassign 0 value.
Answer: Just to add a piece of information regarding the issue:
I  have used this part of code:
Widget body() {
  switch (_currentTab) {
    case 0:
      return FeedScreen(0);
    case 1:
      return FeedScreen(1);
    case 2:
      return FeedScreen(2);
    default:
      return FeedScreen();
  }
}

As I have a parameter to decide whether I show a part of the screen or not.
However it DOES NOT WORK, I do not know why.
So I had to create different class for each situation.
Widget body() {
  switch (_currentTab) {
    case 0:
      return Class1(0);
    case 1:
      return Class2(1);
    case 2:
      return Class3(2);
    default:
      return Class4();
  }
}

Inside each Class* I am able to call FeedScreen(n), with parameters. Otherwise the setState does not understand that something changed. It seems wierd , but happend. If someone has any trick to avoid it , please let me know.


How can I calculate common digits in daily numbers?

Question: We have daily numbers with 4 digits and 3 digits. These winning numbers often,but not always, have 1 or more digits the same. It would seem there should be a strategy to calculate the percent of time the daily numbers have common digits.
It would seem to be true for any two numbers given the number of digits in each number. The number of digits in the 2 "daily numbers" can be the same or different.
A program can be written to count them. A general formula would be more satisfying. It does not appear to be that simple though because you can have numbers with multiple digits that are the same.
Answer: The probability of having a $d$ digit number with no repeated digits is:
$$
p_{nr}(d) = \frac{\binom{10}{d}}{10^d}.
$$
Thus, the probability of having a digit with any repetition is:
$$
p_r(d) = 1 - \frac{\binom{10}{d}}{10^d}.
$$
For $d=3$ we would have $p_r(3) = 0.28$ and for $d=4$ we have $p_r(4) = 0.496$.
Comment: Please see
https://stats.meta.stackexchange.com/questions/6304/my-upvoting-policy,
when you find a question sufficiently clear to
write an answer, consider to upvote the question!
Answer: if i understand your question well
you need first find the common digit between two number say x,y
this step convert x,y  to string and then  compare .
then  you need to collect previous data say for an year
the percent =no of days with their is common digit/total number of days


Modal unica para linhas de uma DATA TABLE

Question: Tenho uma listagem de dados com aproximadamente 1200 clientes onde trago [CPF, NOME, TELEFONE, UM STATUS] e uma coluna com os botões de controle, a um ano fiz um mini-curso na faculdade para aprender a trabalhar com Laravel, o instrutor ensinou a fazer de uma forma que ao meu agora está inviável pelo tempo de carregamento!
PROBLEMA:
Para cada controle tenho um link que me leva a alguma ação no controller, como editar, remover e copiar, nesta DATA TABLE em questão tenho mais uma ação que é definir se aquele cliente paga ou não descarga de produtos. Para os botões de remover e o de pagamento de descarga tem uma modal para cada em cada linha então imagina o tamanho do código html!

Basicamente eu personalizo o titulo da modal, o corpo (com dados do objeto no foreach) e o botão de ação (id da linha enviando para o controller via rota do tipo get)
Código do botão e da modal (Remover) :

parc_cpf_cnpj}}">

parc_cpf_cnpj}}" tabindex="-1" role="dialog">

        <button type="button" class="close" data-dismiss="modal">
                                                                        </button>

   {{ \App\Http\Controllers\HelperMsgController::remove_registro() }}

          {{\App\Http\Controllers\HelperMsgController::msg_body_modal_selec_remove_exclamation()}}

Deseja realmente remover definitivamente o parceiro {{$c->parc_razao_social}} ?

        <button type="button" title="Cancelar operação" class="btn btn-default" data-dismiss="modal">  Cancelar
                                                                        </button>

        id}}" class="btn btn-small btn-danger" title="Remover este parceiro" href="{{action('ParceiroController@destroy', $c->parc_cpf_cnpj)}}">
            Remover

Tentei implementar o ajax, mas não consigo de forma satisfatória:
function geraModalConfDescarga(parc_cpf_cnpj) {
        var path = 'modal/confirma/'+parc_cpf_cnpj+'/pagamento/descarga';
        $.ajax({
            async: false,
            url: path,
            dataType: 'HTML',
            beforeSend: function () {
            },
            success: function (response) {
                //adiciona o modal (content do view na div .content)
                $(".content").append(response);
            }
        });
    }

No botão da DATA TABLE:

parc_cpf_cnpj}})" href="#modalConfPagDesc{{$c->parc_cpf_cnpj}}">

Na rota:
Route::group(['prefix' => 'modal', 'middleware' => 'auth'], function (){
Route::get('confirma/{id}/pagamento/descarga', 'ModalsController@modalParceiroPagaDescarga');});

No controller:
public function modalParceiroPagaDescarga($id)
{
    $parceiro = Parceiro::where("parc_cpf_cnpj", "=", intval($id))->get()->first();

    $parc_cpf_cnpj = $parceiro->parc_cpf_cnpj;
    $parc_razao_social = $parceiro->parc_razao_social;

    return view("modals.pag-descarga", compact('parc_cpf_cnpj', 'parc_razao_social'));
}

A modal em um arquivo php:

        <button type="button" class="close" data-dismiss="modal">
                </button>

   {{ \App\Http\Controllers\HelperMsgController::confirma() }}

Deseja realmente confirmar que o parceiro {{$parc_razao_social}} efetua pagamento de desscargas ?

        <button type="button" title="Cancelar operação" class="btn btn-default" data-dismiss="modal">  Cancelar
                </button>

            Confirmar

Comment: Ajax apenas um Modal, cria a url e coloca no action
Comment: Como? tentei implementar de uma forma que encontrei, se eu digito na URL o caminho com o parâmetro, executa, mas pleo ajax dá pagina 404!
Comment: Consegui! faltou uma "barra" antes do nome do modal
Answer: Para ter um resultado melhor no front end você pode tentar utilizar uma outra abordagem como usar o Vuejs que é recomendado pelo proprio laravel.
O vue permite que você crie aplicações mais dinamicas usando menos codigo e com uma maior facilidade.
Link da documentação do laravel usando vue
Esse video pode te ajudar


How do I know which right-hand fingers to use on classical guitar?

Question: So, coming from a violin background where the most the right side of your body does is move back-and-forth, the whole finger-picking thing on classical guitar has been throwing me for a loop.
The little "Teach Yourself" book has been phenomenal, but, as is "duh," you can't beat a live teacher. The pretty Aria duet that they have me learning is a little interesting. There are no fingerings written in for the right hand, but at the beginning in a little blurb, it says that your p finger should handle all of it.
That's fine. But some of the notes are on the third string. I was under the impression that your m and i fingers handled the top three strings, and bass was taken care of by the thumb. Is there a rule? The third string is as high as the song goes. They have me using my other fingers in different songs. What's the trick to knowing which fingers to pick a string with?
Comment: At least one major style of classical guitar assigns one finger per string, although that breaks down with 6 strings.  I prefer to strive for that where possible and also rotate fingers when repeatedly plucking one string.
Comment: The general rule is thumb for bass line, yes, but that's just an orientation. If you are self-learning, you should definitely get a sheet with full fingering. For example http://www.delcamp.net/pdf/Julio_Salvador_Sagreras_Las_Primeras_Lecciones_de_guitarra.pdf http://www.delcamp.net/pdf/Julio_Salvador_Sagreras_Las_Segundas_Lecciones_de_guitarra.pdf
Comment: Using just the p finger for 4 strings, and never using other fingers is very unusual. They probably have some special reason for it, like later you will have to improvise with your other fingers on strings 1 and 2. You may want to include a wider context in your question, so people here could determine or guess the reason for the special fingering.
Comment: Often beginner studies have the RH fingers marked - the `p,i,m,a` notation on the score.  But if there's a default pattern it's either to assign each finger to a string (with `p` taking the rest), or favor a finger for each voice (`p` for bass, `a` for melody, `i,m` for middle arpeggios is common) - often with the same results.
Answer: Generally, thumb gets used for the bass line, when it exists, and it's usually on 6and 5, sometimes 4. A reason, apart from the physical proximity is the sound. That leaves 1,2,3 and 4 to be played with fingers. Some players use i,m and a most of the time, but when I've taught, pinky comes into play (sic) when needed - most often on top string.
Like fingering for piano, recommendations are somewhat subjective, and won't work for all, so don't rely on being told everything! Work it out for yourself! Try different ways! Then you'll have a better idea in the future, when you'll play things spontaneously, without even thinking which finger plays which note. Ease of playing, speed, sound quality and which strings you need are all factors, so there will be compromises, and when you've found them, you own them!
Answer:
That's fine. But some of the notes are on the third string. I was
  under the impression that your m and i fingers handled the top three
  strings, and bass was taken care of by the thumb. Is there a rule? The
  third string is as high as the song goes. They have me using my other
  fingers in different songs. What's the trick to knowing which fingers
  to pick a string with?

Yes, these are all very much one of the types of right-hand picking techniques you should know as a classical guitarist. It is called strong free-stroke. It is where your thumb plucks the four low strings and your index and middle pluck the B and high E strings.
The one you mention is called regular free-stroke. The one where your thumb plays the E, A and D strings and the Index, Middle and Ring play the other three.
For more details on the various right hand picking techniques see my answer on this question.
Comment: This discusses free stroke, probably compared with rest stroke. Both of which can be played with any finger or thumb. It matters not which string is plucked, surely?
Comment: I may have been a little bit confused. I don't mean Apoyando and Tirando.
Answer: I was taught that as well. Generally, using that i m and a for the top 3 strings and the p for the bass strings is fundamental for the player to get familiar with where the strings are. However, once you get passed that point you can use any finger anywhere! Too, if this was the case, playing a quick scale passage would be, as you can image, pretty difficult. :)


Notation for a unit vector

Question: If I have a vector $\vec{v}$, is there a standard concise notation for the unit vector in the same direction of $\vec{v}$ that is $\frac{\vec{v}}{|\vec{v}|}$?
Comment: I don't think so...
Comment: You can simply define one. But, to me, there seems no need to have one such.
Answer: Sometimes the notation
$$\hat v = \frac{v}{\|v\|_2}$$
is used. I've especially seen it on wikipedia and 3D-Graphics related articles containing math.
Comment: Indeed, if I see any notation to signify a vector has unit length (or a normalized vector), it's \hat. Not to say it's standard, but it's the only one I can ever recall seeing.
Comment: Why is there a subscript 2 in the denominator?
Comment: @nosyarg To clarify that we are talking about the euclidean norm.
Comment: Ok so it means the same thing as$\frac{\vec{v}}{|\vec{v}|}$?
Comment: @nosyarg Yes, it's just cleaner.

Notation for a unit vector


Find the basis for the null space of the linear transformation

Question: The question is

$P_2$: the vector space of 2nd order polynomial. The linear transformation $T$ is defined as $T: P_2 \rightarrow \mathbb{R}$ where $T(p(x)) = p(2)$. Find the basis of $N(T)$.

The answer is $\left\{x^2-4, x-2\right\}$.
My approach:
$$N(T):=\left\{ p(x)\middle| T(p(x))=0 \right\}$$
=> $p(2) = 0$
$$\forall \alpha,\beta,\gamma \in \mathbb{R}, p(x) = \alpha x^2+\beta x + \gamma$$
$$P(2)=4\alpha +2\beta + \gamma$$
I got stuck here and wasn't able to proceed. The only hint I have on this question is the answer itself. And I also understand that the answer is correct. But I can't find a logical way of finding  $x^2-4$ and $x-2$ as the basis of $N(T)$. I guess that guessing can be an approach but guessing won't work on all problems so I want a more rigid solution.
Answer: $N(T)$ consists of polynomials $a+bx+cx^{2}$ such that $a+2b+4c=0$. This gives $a==-2b-4c$ so the polynomial becomes $p(x)=-2b-4c+bx+cx^{2}=b(x-2)+c(x^{2}-4)$ with $b$ and $c$ arbitrary. So $N(t)$ is spanned by $x^{2}-4$ and $x-2$. I will let you check  that these two polynomials are linearly independent which implies that they form a basis for $N(T)$.


Why must the rational numbers be fixed on any automorphism of $\mathbb R$?

Question: I'm studying Model theory using David Marker's "Model Theory: An Introduction".
In the first chapter he presents the following proposition:

Proposition 1.3.5:
Let $\cal M$ be an $\cal L$-structure. If $X\subseteq M^n$ is $A$-definable, then every $\cal L$-automorphism of $\cal M$ that fixes $A$ pointwise fixes $X$ setwise.

and after this, he gives an example that, in the languange of rings $\mathcal{ L }= \{+,-,\cdot, 0,1\}$, the only automorphism of $\mathcal{ M}=(\mathbb  R,+,-,\cdot,0,1)$ is the indentity. The argument is as follows:

"Any automorphism of the real field must fix the rational numbers. Because the order is $\emptyset$-definalbe it must be preserved by the automorphism. Because the rationals are dense, the only automorphism is the identity".

I understand why the order must be preserved, and I understand why "order being preserved" + "rationals being fixed" $\implies$ "any automorphism is the identity", but I'm having some trouble understanding why the rational numbers must be fixed by the automorphism.
Why is this the case?
Comment: ...because each rational number is (individually) $\emptyset$-definable, e.g., $2/3 = (1+1)/(1+1+1)$ (or if you insist $2/3$ is the unique real number $x$ such that $(1+1+1)x = 1+1$).
Answer: If it's a field automorphism it must fix $0$ and $1$ as those are the only two numbers equal to their own square.  That in turn fixes any two integers $n$ and $m$ as $1+1$ $n$ or $m$ times, which in turn fixes any rational $n/m$.
Comment: You are right. I was so focused on the Model-theoretic properties of the automorphism that I forgot that it's also a field isomorphism. thx
Comment: A simpler way to observe $0$ and $1$, is: group automorphisms always fix the identity.
Comment: Yes, but in this case, 0 and 1 are fixed by the definition of automorphism @MJD


DAX Need Power Pivot Measure to be SUM of ALL Columns in Each Column. How to ignore column context

Question: I have a Pivot Table with Salespeople as columns. I have income measures that correctly show (in the rows) the income each of them produced. However, I would like to show everyone's income in each column on some of the measures.
The reason is I want them to be paid on some income items (row measures) on the total of all salespeople not on their individual production.
Is there a way to make a measure ignore the column context?
Answer: DAX ALL
Try to use ALL function and give your column as a parameter.
It will clear currently applied filters.
Comment: Thanks. I was trying to put the measure in the ALL function instead of the Sales Person name column.


Find adjoint operator

Question: Let $\mathcal{H}$ be a separable Hilbert space with orthonormal basis $(e_n)$. Denote by $V$ the subspace of finite linear combinations of the basis-vectors. Define $T$ on $\mathcal{H}$ with $D(T) = V$ by $$T\left(\sum_{j=1}^n c_j e_j\right) = \sum_{j=1}^n c_j e_1$$
I want to find the adjoint operator $T^*$ and the closure of $G(T)$ the graph.
My problem is this: So for the first part. $\mathcal{H}^* = B(\mathcal{H}, \mathbb{C})$, $$D(T^*) =  \left\{y^*\in \mathcal{H}^*: |y^*(Tx)|\leq C_{y^*}\left\|x\right\|_{\mathcal{H}}, x\in V
 \right\}$$
(This is what i got from my definitions: So $D(T^*)$ consists of functionals for which the map $x\mapsto y^*(Tx)$ is continuous for all $x\in V$)
The adjoint transformation is defined by $$T^*y^* = x^* $$ for which $y^*(Tx)= x^*(x)$ for all $x\in V$. So then I first need to determine which functionals $y^*$ are in $D(T^*)$ right? But i havent been given a norm $\left\|\cdot\right\|_{\mathcal{H}}$...could someone help me out?
Comment: It is most likely $\sum c_j e_1$.
Comment: Yes, but someone edited it. :P Nvm...thought I wrote it down right.
Answer: Writing down the matrix of $T$, you find algebraically
$$
T^*:\sum_{n\geq 1} x_ne_n\longmapsto x_1\sum_{n\geq 1}e_n.
$$
But $\sum_{n\geq 1}e_n$ does not converge in $H$, so the domain of $T^*$ is $\{x\;;\; x_1=0\}$ and $T^*=0$.
Now let us do this less casually.
Check that the functional
$$
y\longmapsto (x,Ty)=\overline{x_1}\sum_{n\geq 0}y_j
$$
is bounded if and only if $x_1=0$ (otherwise, consider the partial sums of the harmonic series). It follows that
$$
D(T^*)=e_1^\perp=\{x\;;\; x_1=0\}.
$$
Now
$$
(x,Ty)=0\qquad \forall y\in V\quad\forall x\in e_1^\perp.
$$
So
$$
T^*=0.
$$
The graph of $T$ is
$$
G(T)=\{(x,\left(\sum_{n\geq 1}x_n\right)e_1)\;;\; x\in V\}.
$$
One sees that
$$
G(T)^\perp=\{0\}\times e_1^\perp
$$
hence
$$
\overline{G(T)}=G(T)^{\perp\perp}=H\times \mbox{Span} e_1.
$$
Comment: I used the usual isometric identification $B(H,\mathbb{C})\simeq H$ vie Riesz representtation theorem. When working with a Hilbert space, one (almost) always does that because it makes everything much easier to write. A functional is just $(x,\cdot)$, which has norm $\|x\|$. So it is identified with $x$.
Comment: There's something i dont quite understand though. Cause an adjoint sends maps to maps right? Here it is a map on $\mathcal{H}$. Istead of a map on $B(\mathcal{H},\mathbb{C})$ ? In linear algebra I know we talk about adjoint matrices this way...but it confuses me a little.

Find adjoint operator


client computer cannot connect to server via RDP after 30 minutes

Question: We have a Windows Server 2008. I am accessing the server via RDP. I can connect via RDP if I restart it, but after 15-30 mins without an RDP connection I get the following error:
<code>An internal error has occurred.
</code>
I don't know how to fix this. can you help me please.
Thank you in advance.
Comment: We had in the past some similar issues and where working with Microsoft in order to solve that. They send us a special pre-hotfix. This hotfix was then released to Windows updates. So are you sure your Windows OS is fully up to date?
Answer: The most common reason for a RDP connection to hang is unstable connectivity at client side.
*Can you ping the server? Check if the connection is broken (ping serverip -t).
*Are you trying to RDP the server by name or IP? If you can RDP by IP without issues, is a DNS related issue.
*Can you remote the server using another remote application (Like VNC) withour issues? If yes, definetly is a Firewall issue with RDP ports (TCP port 3389 and UDP port 3389).
*Are you using DHCP? If Yes, open CMD and run ipconfig /renew
*Is the Windows Firewall disabled (service)? Check and enable these inbound rules:
File and Printer Sharing (Echo Request - ICMPv4-In)
Remote Desktop (TCP-In)
*Check if the NIC Power Management Options --> Uncheck "Allow the computer to turn off this device to save power"
*Check the current Power Options on this server.
*Make sure your server is fully patched. Also check the following KB from Microsoft https://support.microsoft.com/en-us/kb/2571388


Can you override a library per environment?

Question: In my libraries.yml file, I have something like this, being used to define "foo-bar" as a library that can be pulled in from various parts of the site:
foo-bar:
  version: 0.0.x
  js:
    js/foo-dev.js: {}

This works well on my local environment, but on our production and QA environments, I would like for it to look more like this:
foo-bar:
  version: 0.0.x
  js:
    js/foo-prod.js: {}

(The prod version will include optimizations that normally don't appear with minification alone).
Currently, we are using the sites/<site>/settings.*.php files and the config-split module to have different configurations based on the environment, but is there a way to have the foo-bar library reference the dev-friendly version on one environment, and the production version on all others?
Comment: Possible duplicate of [Is there a way to override paths defined in \*.libraries.yml](https://drupal.stackexchange.com/questions/210959/is-there-a-way-to-override-paths-defined-in-libraries-yml)
Answer: Look at hook_page_attachments. In the sample snippet provided behind that link there is a simple if-request which attaches a certain library only when a certain condition is met. Do the same.
MYTHEME/MYMODULE.libraries.yml
foo-bar-dev:
  version: 0.0.x
  js:
    js/foo-dev.js: {}
foo-bar-prod:
  version: 0.0.x
  js:
    js/foo-prod.js: {}

MYTHEME.theme/MYMODULE.module
function MYTHEME/MYMODULE_page_attachments(array &$attachments) {

  // Conditionally attach an asset to the page.
  if (\Drupal::request()->getHost() == 'example.com') {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-prod';
  }
  else {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-dev';
  }
}

More info on base URL: how to get base url of a site?.
Comment: If you have attached the library already in other places and therefore want to keep the library name you could use `hook_library_info_alter` to alter only the js file name.
Comment: As noted [here](https://drupal.stackexchange.com/a/147366/3167)  if you want to put this logic in a theme, you cannot use `hook_page_attachments()` but can use [`hook_page_attachments_alter`](https://api.drupal.org/hook_page_attachments_alter) or `hook_preprocess_page`.
Comment: @4k4 – Gosh, you are so right. Found my own question when googling named hook: https://drupal.stackexchange.com/q/210959/15055


Repeat request to MySQL multiple times with different value if id

Question: here is my code
Please help to make it loop by  Array(0,100) for nav_tb_id
Aqtualy I have a SQL stored procedure that I need to execute several times with different parameters. and get difrent rows
However I tried different ways but no result:
<?php
$nav01=mysql_query("SELECT * FROM nav_tb WHERE nav_tb_id = '1'");
$row_1=mysql_fetch_object($nav01);

    if ($_SESSION ['lang']==1){
       $nav_m_b_01=$row_1->RU;
    }elseif ($_SESSION ['lang']==2){
       $nav_m_b_01=$row_1->UA;
    }elseif ($_SESSION ['lang']==3){
       $nav_m_b_01=$row_1->EN;
    }

echo $nav_m_b_01;

$nav02=mysql_query("SELECT * FROM nav_tb WHERE nav_tb_id = '2'");
$row_2=mysql_fetch_object($nav02);

    if ($_SESSION ['lang']==1){
       $nav_m_b_02=$row_2->RU;
    }elseif ($_SESSION ['lang']==2){
       $nav_m_b_02=$row_2->UA;
    }elseif ($_SESSION ['lang']==3){
       $nav_m_b_02=$row_2->EN;
    }

echo $nav_m_b_02;

...

Comment: no idea what you are asking
Answer: You can achieve this using MySQL query too but I'll continue your php code. You just need to wrap one of your snippets with a php do-while construct:
$i = 0;
do {
    $nav=mysql_query("SELECT * FROM nav_tb WHERE nav_tb_id = $i");
    $row=mysql_fetch_object($nav);

    if ($_SESSION ['lang']==1){

        $nav_m_b_01=$row->RU;

    } elseif ($_SESSION ['lang']==2){

        $nav_m_b_01=$row->UA;

    } elseif ($_SESSION ['lang']==3){

        $nav_m_b_01=$row->EN;
    }

} while ($i < 100);


Exploit agains metasploit system

Question: I'm working on an assignment using Kali Linux to exploit against the Metasploit system. A question in regards to my assignment is:
What application did it (the exploit I used) exploit on Metasploit?
I used samba/usermap_script.
I don't know how to tell which application was exploited.
Answer: According to this link:
https://www.rapid7.com/db/modules/exploit/multi/samba/usermap_script
"This module exploits a command execution vulnerability in Samba versions 3.0.20 through 3.0.25rc3"
So it's exploiting an application on Linux called "Samba".

Exploit agains metasploit system


Memory management when doing multitasking in iOS 4

Question: According to Apple... apps should reduce their memory footprint as much as possible when running in the "background" (suspended mode).  I reduce the memory footprint of my app by releasing a bunch of 2D textures in ApplicationDidEnterBackground and reloading the same textures in ApplicationWillEnterForeground.  Everything works for the most part.
Here is my question:  Why do I get a SIGABRT or EXEC_BAD_ACCESS when I move my app to/from the background rapidly?  The errors occur when the app is coming back into the foreground (textures are being reloaded).
I don't receive any errors when I move the app to/from the background less rapidly.  How can I prevent this?  Perhaps I should be checking if the resources are actually deallocated before I try to reload them?
How does one code defensively in this situation?
Comment: I have heard that will enter foreground can be called before did enter background on a rapid switch.  Code defensively.
Comment: i'm sure you already know, but you get that error when you send a message to a released object. it's hard to be specific with this example.
Comment: @drawnonward: If that's the case, you might consider keeping track of what's executed first. Not necessarily the best programming practice, but one that should work.
Comment: One defensive move that could help: set your textures = nil after deallocating, that way you're not in danger of sending messages to a garbage address.
Comment: try running with NSZombiesEnabled, it will at least tell you which object is being messaged, anything that gets released should be set to nil, as this way if you message it, nothing will happen, instead of your program blowing up.
Answer: I know this is an older question, but let me take a stab.  You mentioned releasing 2D textures.  Are you using Cocos2D perchance?
I had a similar issue to yours earlier this year - the issue wasn't with my code.  It was with Cocos2D's - there was a bug where textures could get purged at the same time as loading new textures asynchronously.
I've reported the issue, and it seems like a February commit to the Cocos2D project also addressed a similar problem.


Binary variable: split data into separate sets, or use binary as independent variable

Question: Let's say I have a classic dataset containing some data about participants. The data includes gender, weight, length, area code, income. Let's also assume that gender is binary encoded, whereas weight, length, income are numeric/continuous variables and the area codes are categorical.
I am trying to find some correlations between these variables with a simple Pearson test for each possible combination. You'll get the following pairs for which Pearson's is calculated:
gender - weight
gender - length
gender - income
gender - area
weight - length
weight - income
weight - area
length - income
length - area
income - area

When I showed these pairs (and their respective r-correlations and p-values), my promoter told me it seemed more logical to them to split up the dataset based on the binary variable, i.e., build two sets one where gender == 0 and one where gender == 1, and then calculate correlations for the remaining variables. So for each set, that would mean the following remaining pairs:
weight - length
weight - income
weight - area
length - income
length - area
income - area

When we have done this, we could then compare the results of both tests, they said. But I am confused, why would you do it like this? What is the benefit?
How I see it, in my approach you calculate the correlation between the gender variable and the other variables. You get a detailed analysis (r and p) so you know how big a role the gender variable plays for each variable. The proposed approach simply calculates something different: it will show whether the variables are correlated when gender is 0, and when it is 1 - but there is no information on how large the role is that the gender variable plays.
My question, then, is: what is the best approach if you are simply trying to find correlations between a set of independent variables? When should I split up my dataset in smaller datasets? And if I have split up my datasets, is there a way to find the impact of splitting up (i.e., the impact of the binary variable)?
Answer: Fundamentally, correlations are bivariate. With a single correlation matrix, you have an assessment of the strength of relation of each possible pairwise combination of variables, but not accounting for any other variables.
Splitting the data by gender allows the correlations between two other variables to vary by group. This is essentially allowing an interaction--a coefficient relating two variables that depends on the level of the third.
That said, just splitting the group and eyeballing differences doesn't tell you anything about the precision or significance with which you have observed a difference. If you are interested in this interaction, but want to keep the bivariate relations non-directional, I'd recommend a multiple-group model in path analysis software. That would let you directly estimate and test differences in the covariances between any other two variables as a function of gender.


I have this error: Uncaught SyntaxError: missing ) after argument list

Question: I keep getting this error, but I can not figure it out what the problem seems to be. Apparently the error is in the line of currentProduct.find()
var $productTemplate = $(".product-item");
$.ajax({
    url: 'data/applicationLayer.php',
    type: 'POST',
    dataType: 'json',
    contentType: "application/x-www-form-urlencoded",
    data: {
        action: "MOSTRARIMAGENES",
    },
})
.done(function(jsonResponse) {
    $.each(jsonResponse, function(index, val) {
        if (jsonResponse.length) {
            $("#initialProductMessage").remove();
            var $currentProduct = $productTemplate.clone(true);
            $currentProduct.find('.producto1').html(val.nombre + "
" + "");
            $currentProduct.show();
            $("#products-display").prepend($currentProduct);
        }
    });
})

Comment: You're missing some `+` to concatenate your string with the `val.foto`
Comment: Escape the quotes in the  html snippet you concatenate with val.nombre and ""
Comment: Should this question be moved to http://es.stackoverflow.com/?
Answer: You're missing some + to concatenate your string with the val.foto. You also should escape some quotes to wrap the values. Try this:
$currentProduct.find('.producto1').html(val.nombre + "
");

Or using single quotes to avoid escaping entirely:
$currentProduct.find('.producto1').html(val.nombre + '
');

Comment: Beat me by just a bit!!
Comment: Yup, but there's more escaping to do: the width and height attributes. Or simply use single quotes for these strings to avoid escaping.
Comment: @RoryMcCrossan you're welcome - We're all here to help!
Comment: @RoryMcCrossan actually, there's still one double quote unedited at the very end! I can't edit it because edits must have at least 6 characters :/


MySQL query igual a um valor ou outro

Question: Estou com uma duvida em uma query do MySQL.
Eu tenho esta query
select cor from cores where cor in('verde','vermelho');

O problema é que eu quero o verde, e Caso se não tenha verde eu quero o vermelho. mas não os 2 resultados.
Eu não posso usar o LIMIT 1, porque isto esta dentro de uma subquery mais complexa e o MySQL não deixa usar LIMIT em subquery.
Answer: Ao invés do operador IN, você pode usar o CASE para verificar se um registro existe. É como fazer um IF em uma linguagem estruturada.
Veja um exemplo:

SELECT
  CASE
     WHEN EXISTS(select cor from cores where cor = 'verde') THEN 'verde'
     ELSE (select cor from cores where cor = 'vermelho')
  END,
  CASE
     WHEN EXISTS(select cor from cores where cor = 'azul') THEN 'azul'
     WHEN EXISTS(select cor from cores where cor = 'verde') THEN 'verde'
     ELSE (select cor from cores where cor = 'vermelho')
  END

Alternativamente, você pode usar a função COALESCE, que vai retornar o primeiro parâmetro que não seja nulo, estabelecendo assim uma ordem de prioridade.
Veja o exemplo:
select
  COALESCE(
    (select cor from cores where cor = 'azul'),
    (select cor from cores where cor = 'verde'),
    (select cor from cores where cor = 'vermelho')
  )

Veja também o sqlfiddle com os exemplos funcionais.
Comment: Não sabia desse SQLFiddle, muito útil, obrigado :)
Comment: @FelipeAvelar Isso mesmo, ele deveria funcionar como um `if/else`: se existe 'azul', então retorna 'azul, senão faz o select por 'vermelho'.
Comment: @FelipeAvelar Mas note que você você ter vários 'WHEN' diferentes. Vou editar a resposta para exemplificar isso.
Comment: @FelipeAvelar *Acho* que agora entendi. No exemplo que coloquei o select vai executar os dois *cases*, seriam como duas colunas distintas e independentes.
Comment: Eu fiquei em dúvida no exemplo do `CASE`, ele vai executar os dois `CASE`s ou ele tenta executar um e, caso não retorne nada, ele executa o outro?
Comment: Valeu a query que eu estava usando era um `inner join on` e com o coalesce ficou perfeito. Usei da seguinte forma: `on coalesce((RIGHT(upper(c.filename), CHAR_LENGTH(b.value) + 4) = concat(b.value, '.PSD')), (RIGHT(upper(c.filename), CHAR_LENGTH(b.value) + 4) = concat(b.value, '.JPG')))`
Comment: Eu entendi o `WHEN`, o que eu não entendi foi o `CASE`. Tipo, tem dois `CASE`s no `SELECT`, mas a consulta sempre vai executar os dois `CASE`s ou só quando um não tiver retorno? Entendeu o que eu quis perguntar?
Comment: Era exatamente isso, obrigado.

MySQL query igual a um valor ou outro


Is there a maximum number of schemas allowed in SQL Server 2005?

Question: What is the maximum number of user schemas one can create in a single SQL Server 2005 database?
Is this figure different on SQL Server Express vs SQL Server Standard?
I've searched the MSDN documentation but can't find anything approaching an answer.  The max capacity page at MSDN doesn't mention schemas.
Answer: Schemas are just objects in the databases so they fall under the maximum objects counters which have a limit of 2,147,483,647.
It'll be the same for all editions of the engine.
Comment: slight nitpick, but wouldn't it be 2,147,483,648 ?  The total number of possible values with a 32 bit integer?
Comment: I copied the number from the MSDN page so its probably correct.
Comment: Maybe 0 is reserved.
Comment: Probably given that there are system objects created with positive object_ids you can't ever actually get that many as you can't create an object with an object_id of 1 or 2 as the system objects use sporadic numbers from 3 to 98.  Unless of course the object creating code is just grabbing a random number and using that so it will eventually fill in the holes.  But then we have to ask, why can't negative numbers be used.  There are many systems objects with a negative object_id already.


xml literal with string.format

Question: How can I use the vb xml literal within a string.format statement?
I want to achieve this but with vb xml literals
Dim test1 As String =
String.Format(<outer>
    <inner1>{0}</inner1>
    <inner2/>
</outer>,32)

Comment: XML literals are used to create `XElement`s. `String.Format` is used to create `String`s. What do you need, an XML string or an XElement?
Answer: I think you misunderstand what an xml literal is for...
    Dim xml = <outer><inner1></inner1><inner2/></outer>
    xml...<inner1>.First.Value = 32
    Console.WriteLine(xml.ToString)

Answer: This works (just needed to add .ToString() at the end of your XML).
Dim test1 As String = String.Format(<outer>
                                      <inner1>{0}</inner1>
                                      <inner2/>
                                    </outer>.ToString(), 32)

xml literal with string.format


Jest test with SpyOn

Question: How can I test this code in jest using spyOn? Can someone help me with a proper solution?
const controller = {};

controller.fetchCars = async (req, res) => {
  const result = await getCarsService(req.body);
  res.json(result);
};

I've tried this:
    it('fetchCars should call getCarsService', () => {
      const spy = jest.spyOn(carsController, 'getCarsService').mockImplementation(() => {});
      const req = {};
      const res = {};

      carsController.fetchCars(req, res);
      expect(spy).toBeCalled()
      spy.mockRestore();
    });

and gives me this error: Cannot spy the getCarsService property because it is not a function; undefined given instead
getCarsService() it's imported from /services and it looks like this:
export const getCarsService = async body => {
  const carsReqConfig = {
    headers: fetchApi.newHeaderWithToken(CAR_JWT, SITE_ID)
  };
  const result = await instance.post(
    `${API_GATEWAY_URL}${CAR_ENDPOINT}/search`,
    body,
    carsReqConfig
  );
  const cars = result?.data?.results.filter(
    car => car.orderType === 'AI'
  );
  const formatedResponse = formatCarSearchRes(cars);
  return formatedResponse;
};

Comment: The question doesn't contain the most important part, where getCarsService comes from. The error says what's wrong, you cannot spy it on random object it doesn't belong to.
Comment: I've edited this post, getCarsService looks like above
Answer: The easiest solution would be to separate your code into each file and then just use jest.mock to mock the getCarsService method.
index.js
import getCarsService from './getCarsService';

const controller = {
    fetchCars: async (req, res) => {
        const result = await getCarsService(req.body);
        return res.json(result);
    },
};

export default controller;

getCarsService.js
function getCarsService(body) {
    return new Promise(resolve => resolve(1));
}

export default getCarsService;

index.spec.js
import controller from './index';
import getCarsService from './getCarsService';

jest.mock('./getCarsService', () => jest.fn().mockResolvedValue(1));

it('fetchCars should call getCarsService', async () => {
    const req = {
        hello: 'world',
    };
    const res = {
        json: jest.fn(),
    };

    await controller.fetchCars(req, res);
    expect(getCarsService).toBeCalled();
    expect(res.json).toBeCalledWith(1);
});

If you are dead set on using a spy you can do it like this by spying on the default export.
import controller from './index';
import * as getCarsService from './getCarsService';

it('fetchCars should call getCarsService', async () => {
    const req = {
        hello: 'world',
    };
    const res = {
        json: jest.fn(),
    };

    const spy = jest.spyOn(getCarsService, 'default');
    spy.mockResolvedValue(2);

    await controller.fetchCars(req, res);
    expect(res.json).toBeCalledWith(2);
});

Comment: The question has been updated, it's already in another module.
Comment: I tried your solution and it gives me this error: "Cannot spyOn on a primitive value; undefined given". Any ideas what am I doing wrong?
Comment: @Christian have you exported `getCarsService` as the default export? You need to follow the setup directly as provided above or else it won't work.
Comment: hmm I think I can't export it as default since it's not the only service available, there are 4 more services, I tried your solution from index.spec.js and it gives me the above error..
Comment: @Christian you will need to restructure how you handle services e.g. by separating them into a file or combine them into a single object and then export them as an default export. The solutions have already been provided to you.
Comment: I will structure the services same as controllers, into an object, hope it works. Thank you very much for your time and knowledge.

Jest test with SpyOn


Given a closed set A, construct a continuously differentiable function that has A as its set of zeroes.

Question: Edit: I answered my own question. Please let me know if there's an error, and I will fix it. If it's right, I'd appreciate it if you let me know that.
First of all, does this function - $f(x) = inf\{(x-y)^2 : y \in A\}$ - work? I hope it does. Second, I'm trying to show this function is well-defined.
Let $f(x) = inf\{(x-y)^2 : y \in A\}$. We prove this function is well-defined. Grab an arbitrary $x$. It is either in $A$ or not. If it's in $A$, then $f(x) = 0$ because $f(x) = inf\{(x-y)^2 : y \in A\}$, and we can let $y = x$, so $f(x) = 0$. If it's not in $A$, then note that $(x-y)^2$ is smallest when $y$ is near $x$, so take the $y$ such $|x-y|$ is the smallest. We know that such a $y$ exists because if not ...
This is where I get stuck. Intuitively, I know that for closed sets, the endpoint is included in the set, and so we don't need to worry about points that get arbitrarily close to an endpoint but are not equal to an endpoint.
Regarding the continuously differentiable part, I'm intuitively imagining that we have a bunch of zeros on the line with these half parabolas connecting them?
Comment: What space are we working in? $\mathbb{R}^n$ or just $\mathbb{R}$?
Comment: @MatthewLeingang $\mathbb R$
Comment: Your function is not differentiable. If $A=\{-1,1\}$, then the graph of $f$ looks like two parabolas with vertices at $x=\pm 1$. When these parabolas come together "in the middle", you see a cusp at $x=0$.
Comment: Hint: find a differentiable function $g$ on the interval $[0, 1]$ that is non-zero on $(0, 1)$ and has $g(0) = g(1) = g'(0) = g'(1) = 0$. Now note that the complement of $A$ can be written as a disjoint union of open intervals and use $g$ with its argument suitably adjusted to define $f$ on each of those open intervals.
Comment: @RobArthan Very helpful hint. Would you say $cos(2x\pi) -1$ for the interval $[0,1]$ works? I think it does.
Comment: That looks good to me.
Answer: I don't think there's a problem with this function being well-defined. Every non-empty subset of real numbers which is bounded below has an infimum. If $x \notin A$, the set $\{(x-y)^2 : y \in A \}$ is bounded below by $0$, so there is definitely an infimum (and it's not zero, since the complement of $A$ is open).
I worry about the differentiability, though. If $A = \{-1,1\}$, then doesn't $f(x)$ simplify to $(x+1)^2$ if $x \leq 0$ and $(x-1)^2$ if $x \geq 0$? That's not going to be differentiable at $0$.


Interpretation of LASSO regression coefficients

Question: I'm currently working on building a predictive model for a binary outcome on a dataset with ~300 variables and 800 observations. I've read much on this site about the problems associated with stepwise regression and why not to use it.
I've been reading into LASSO regression and its ability for feature selection and have been successful in implementing it with the use of the "caret" package and "glmnet".
I am able to extract the coefficient of the model with the optimal lambda and alpha from "caret"; however, I'm unfamiliar with how to interpret the coefficients.

Are the LASSO coefficients interpreted in the same method as logistic regression?
Would it be appropriate to use the features selected from LASSO in logistic regression?

EDIT
Interpretation of the coefficients, as in the exponentiated coefficients from the LASSO regression as the log odds for a 1 unit change in the coefficient while holding all other coefficients constant.
https://stats.idre.ucla.edu/other/mult-pkg/faq/general/faq-how-do-i-interpret-odds-ratios-in-logistic-regression/
Comment: As far as I can tell, significance testing for coefficients has not been introduced in most LASSO implementations. So could a difference not be that while we can determine statistically significant variables in OLS, we cannot do so with LASSO except making a weaker statement that the LASSO coefficients of corresponding variables selected are the "important" variables to consider?
Comment: Can you fill in a little what you mean by "interpreted in the same way as logistic regression"?  I'd be very useful to know exactly what interpretations you'd like to generalize.
Comment: @Matthew Drury - Thank you so much for taking the time in assisting me, as my coursework never gone over LASSO. In general, from what I was taught during my graduate courses, the exponentiated coefficients from a logistic regression yields the log odds of a 1 unit increase in the coefficient while holding all the other coefficients constant.
Comment: In "caret" you select $\alpha$ and $\lambda$. Where does $\alpha$ come from? Is it probably a hyperparameter of an elastic net (the relative weight of LASSO versus ridge penalty) (in which case you would actually be using elastic net rather than LASSO)?
Answer:
Are the LASSO coefficients interpreted in the same method as logistic regression?

Let me rephrase: Are the LASSO coefficients interpreted in the same way as, for example, OLS maximum likelihood coefficients in a logistic regression?
LASSO (a penalized estimation method) aims at estimating the same quantities (model coefficients) as, say, OLS maximum likelihood (an unpenalized method). The model is the same, and the interpretation remains the same. The numerical values from LASSO will normally differ from those from OLS maximum likelihood: some will be closer to zero, others will be exactly zero. If a sensible amount of penalization has been applied, the LASSO estimates will lie closer to the true values than the OLS maximum likelihood estimates, which is a desirable result.

Would it be appropriate to use the features selected from LASSO in logistic regression?

There is no inherent problem with that, but you could use LASSO not only for feature selection but also for coefficient estimation. As I mention above, LASSO estimates may be more accurate than, say, OLS maximum likelihood estimates.
Comment: @Ben, If we assume an underlying statistical model, we can estimate its parameters in different ways, two popular ones being OLS and lasso. The estimated coefficients target the same targets, and both have some estimation error (which, if squared, can be decomposed into bias and variance), so in this sense their interpretation is the same. Now of course the methods are not the same, so you get different estimated coefficient values. If you care about the methods and their algebraic and geometrical interpretations, than these are not the same. But subject-matter interpretations are the same.
Comment: @Ben, I think we can separate the theoretical properties of the estimator from the subject-matter interpretation of the estimates as long as the estimands (the targets) are the same. Of course, the point estimates are not the end of the story; standard errors and confidence intervals play a role, too. But once we have point estimates and their standard errors / confidence intervals, we need no longer care how these estimates were obtained when interpreting them from the subject-matter perspective.
Comment: Thank you so much for this response! Makes alot of sense! Please excuse my limited knowledge in this matter. As you have mentioned in another comment that I may be using elastic net rather than LASSO via caret as it chooses the optimal lambda and alpha. Would the same apply in regards to the coefficients?
Comment: Yes, it would. The basic logic remains the same.
Comment: You write "interpretation remains the same". Could you help me understand this point? It seems to be me that the interpretation of OLS coefficients in a multiple regression setting relies on [partial regression plots](https://en.wikipedia.org/wiki/Partial_regression_plot). However, this property does not hold for lasso coefficients, leading me to believe the interpretation would be different.
Comment: @RichardHardy Ah, okay, I think I better understand what you're saying. It's certainly true that lasso may beat OLS in estimation error, but, at the end of the day, like you say, these are just estimators for the same target. Would any estimator be interpreted in the same way that OLS is interpreted? For instance, would the (nonrandom) estimator $(1, \dots, p)^T$ be interpreted that way? or the estimator with iid uniform(0,1) entries? (etc) It does seem (to me) that properties of the estimator need to be directly used in its interpretation, and even subject-matter interpretations would change.


Retrograde and Inverted songs

Question: I am looking for retrograde and inverted remakes of classical pieces. Even better if they are being played simultaneously with the origina, like Pachelbel's Canon, Original Version and Retrograde Inversion Played Simultaneously.
Comment: Disagree that this was marked as "off-topic". This question is not about a particular song, it is about a class of songs that use a particular, well-defined method of composition.
Comment: I added this to the meta: http://meta.music.stackexchange.com/questions/731/please-relax-the-policy-on-questions-that-ask-for-examples-of-a-particular-class
Comment: I think it would be helpful if you could go to http://meta.music.stackexchange.com/questions/731/please-relax-the-policy-on-questions-that-ask-for-examples-of-a-particular-class and explain how you thought of your question, and what your expectations were w/re to the answers. Would be great if you could give your feedback. Thanks in advance!
Comment: @Hans: It would help if you provide a bit more background info on why you want this answered. It would help in how to phrase the answers and what kind of examples to provide, and  to be more useful to others that might share your interest in this.
Answer: The earliest version I can think of is Bach's Musikalisches Opfer which is a series of canons Bach composed after given a theme by the King. The music can be played forwards and backwards simultaneously harmoniously in various ways (refer to the video).
I also remember reading a score of Mozart's violin duet piece called "The Mirror". To play this piece two violinists stand across from each other and play the same score from beginning to the end from their own angles.
In simplest words, for this kind of music to work the (roots of the) chords in the piece must be symmetrical, i.e. the first note(s) and last note(s) must be in the same chord, so that when they are played at the same time it will sound natural. Rhythm would be another key factor.
Answer: As @Menglan pointed out, the crab canon from Bach's musical offering is probably the most famous example. I transcribed it and put it on musecore:
http://musescore.com/rpbouman/scores/143009
The art of fuge (Also Bach) has 2 fugues which can be inverted. Look for Contrapunctus XII and XIII (there's a rectus and an inversus version for both of them)
I wrote some mirror canons myself. Of course, I'm nowhere close to the grand wig himself, but I had a lot of fun writing these:
http://musescore.com/rpbouman/sets/mirrorcanon1
http://musescore.com/rpbouman/sets/mirrorcanon2
Both these canons are written so that you can put the page upside down and get the same piece again. And because of this property, you can play each piece in inverse too. So playing the rectus and the inversus right after each other yields a palindrome.
Comment: Hi Hans, the mirror canons I posted here are both designed along the same plan: you have the original melody (rectus), then enters the retrograde, then enters the inverse, finally enteres the retrograde inverse. So you're already hearing all classical permutations all at the same time. And precisely because it was designed in this way, you can reverse or inverse the entire piece and get back a "new" one. However, it was not designed so as to sound both these pieces at the same time. You can certainly try but it'll sound horrendous.
Comment: Is there a way of playing the both of each mirror at a time?

Retrograde and Inverted songs


Post picture to Facebook using Python

Question: How can I post an image to Facebook using Python?
Comment: I think this question can help you: http://stackoverflow.com/questions/4009441/facebook-python-sdk-post-to-wall-attachment
Answer: You can use the facebook provided Python SDK to upload photos using an oauth key.
Once you get the oauth key, you can upload a picture with GraphAPI.put_object():
<code>graph = facebook.GraphAPI(oauth_access_token)
photo = open("picture.jpg", "rb")
graph.put_object("me", "photos", message="You can put a caption here", source=photo.read())
photo.close()
</code>
Answer: Unfortunately, the Python SDK is discontinued now. Will not work. Need to use Javascript / PHP / iOS / Android APIs
Answer: Fresh links of Facebook Platform Python SDK

https://github.com/pythonforfacebook/facebook-sdk
http://pypi.python.org/pypi/facebook-sdk

http://pythonforfacebook.com
Answer: Checkout this library: https://github.com/facebook/python-sdk/
Comment: The repo link is no more available, this time right now I check it.

Post picture to Facebook using Python


Form Rebuild by Ajax Call

Question: I have a form which is built using some data which is partially random. Unfortunately, at the first AJAX call (nothing has been submitted yet, neither AJAX, nor in the normal way) the form will be rebuilt so that all random inputs are lost. Is there any way to avoid it?
class AjaxTestForm extends FormBase {

  public function getFormId() {
    return 'ajax_text_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $options = $this->_getOptions();
    $form['select'] = [
      '#type' => 'select',
      '#title' => 'Select',
      '#options' => $options,
      '#ajax' => [
        'callback' => [$this, 'ajaxCallback'],
      ],
      '#empty_option' => 'Please select',
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Save',
    ];
    $form_state->set('ajaxoptions', $options);
    return $form;
  }

  private function _getOptions()
  {
    // Actually data from an external Controller
    // But those, too, are random
    $options = [
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
    ];
    return $options;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Do nothing
  }

  public function ajaxCallback($form, $form_state)
  {
    print_r($form_state->getValue('select'));
    echo "\n";
    print_r($form['select']['#options']);
    print_r($form_state->get('ajaxoptions'));
  }

}

When the user selects an option, in the Ajax callback (or Ajax submit, if I had one) I can't know which options were originally in the select box available.
Is there any way to preserve that information?
Comment: I think it's clear from the code, but it's better to add it's Drupal 8.
Comment: Why print statements? Use xdebug
Answer: Get the value from:
$_temp_var_ = $form_state->getUserInput('_field_name_');
Use getUserInput() instead of getValue().
And then set the value to:
$form['_field_name_'] = $_temp_var_;

Form Rebuild by Ajax Call