text:
Q: jQuery Drag and Drop issue - div id and class dependent I have two draggable images, 1 man and 1 woman. When I drag the man into one of two divs I want to hide the image that is there and show a new specific image. When I drag the woman into that same div I want to hide the existing image and to show a separate different image.
There are two separate divs of the above example. Two draggable images into two separate divs. The incoming image will determine what hides and what shows.  I have my code so far below. It's not working.  I know the && is out of place.
    $('#drag-woman').draggable({helper:'clone'});
$('#drag-man').draggable({helper:'clone'});  // makes top images draggable

$("#drop-area-contain").droppable({  //makes contents in div droppable
  drop: function(e, ui) {
    if((ui.draggable.attr("id")) == 'drag-woman') && (class == "quid-contain"){  //if id is dragged do this

       $('.quid-empty').hide();
       $('.quid-with-woman').show();

    }else if((ui.draggable.attr("id")) == 'drag-woman') && (class == "hostile-contain"){  // else if dragged do this

       $('.hostile-empty').hide();
       $('.hostile-with-woman').show();

    }else if((ui.draggable.attr("id")) == 'drag-man') && (class == "quid-contain"){  // else if dragged do this

       $('.quid-empty').hide();
       $('.quid-with-man').show();

    }else if((ui.draggable.attr("id")) == 'drag-man') && (class == "hostile-contain"){  // else if dragged do this

       $('.hostile-empty').hide();
       $('.hostile-with-man').show();

    }
  }
});

JSFIDDLE

A: Fixed the syntax errors in the JSFiddle.
$('#drag-woman').draggable({helper:'clone'});
$('#drag-man').draggable({helper:'clone'});  // makes top images draggable

$("#drop-area-contain").droppable({  //makes contents in div droppable
  drop: function(e, ui) {
    if(((ui.draggable.attr("id")) == 'drag-woman') && ($(this).hasClass("quid-contain"))){  //if id is dragged do this

       $('.quid-empty').hide();
       $('.quid-with-woman').show();

    }else if(((ui.draggable.attr("id")) == 'drag-woman') && ($(this).hasClass("hostile-contain"))){  // else if dragged do this

       $('.hostile-empty').hide();
       $('.hostile-with-woman').show();

    }else if(((ui.draggable.attr("id")) == 'drag-man') && ($(this).hasClass("quid-contain"))){  // else if dragged do this

       $('.quid-empty').hide();
       $('.quid-with-man').show();

    }else if(((ui.draggable.attr("id")) == 'drag-man') && ($(this).hasClass("hostile-contain"))){  // else if dragged do this

       $('.hostile-empty').hide();
       $('.hostile-with-man').show();

    }
  }
});

https://jsfiddle.net/svz0bax5/
EDIT
I have added a closing to the parantheses for the conditions at the if and else if parts. Also, instead of comparing a nonexistent class variable .hasClass() is being called.
EDIT2
Simplified if-else:
$('#drag-woman').draggable({helper:'clone'});
$('#drag-man').draggable({helper:'clone'});  // makes top images draggable

$("#drop-area-contain").droppable({  //makes contents in div droppable
  drop: function(e, ui) {
    var idArray = ["drag-woman", "drag-man"];
    if((idArray.indexOf(ui.draggable.attr("id")) + 1) && $(this).hasClass("quid-contain")) {  //if id is dragged do this

       $('.quid-empty').hide();
       $('.quid-with-' + this.id.substring(5)).show();

    }else if ((idArray.indexOf(ui.draggable.attr("id")) + 1) && $(this).hasClass("hostile-contain")){  // else if dragged do this

       $('.hostile-empty').hide();
       $('.hostile-with-' + this.id.substring(5)).show();
    }
  }
});

EDIT3
In the new fiddle: https://jsfiddle.net/1btx6rfp/
We can see the solution:
$('#drag-woman').draggable({helper:'clone'});
$('#drag-man').draggable({helper:'clone'});  // makes top images draggable

$(".quid-contain, .hostile-contain").droppable({  //makes contents in div droppable
  drop: function(e, ui) {
    var idArray = ["drag-woman", "drag-man"];$('#drag-woman').draggable({helper:'clone'});
$('#drag-man').draggable({helper:'clone'});  // makes top images draggable
    if((idArray.indexOf(ui.draggable.attr("id")) + 1) && $(this).hasClass("quid-contain")) {  //if id is dragged do this

       $('.quid-with-' + ui.draggable.attr("id").substring(5)).show().siblings().hide();

    }else if ((idArray.indexOf(ui.draggable.attr("id")) + 1) && $(this).hasClass("hostile-contain")){  // else if dragged do this

       $('.hostile-with-' + ui.draggable.attr("id").substring(5)).show().siblings().hide();
    }
  }
});

We have a simplified if and the drop event is handled correctly.


text:
Q: How to place dynamically items in form? Is there in c# something like in css - "float: left | right | none | inherit"?
I want to display in my Form - TextBox and below each TextBox - PictureBox. So I don't know the size of each TextBox, it can be different, and in result my PictureBoxes cover TextBoxes....
 static int k = 1;

 for (int att = 0; att < feed.response.items[i].attachments.Count(); att++)
 {
     string switchCase = feed.response.items[i].attachments[att].type;
     switch (switchCase)
     {
         case "photo":
             TextBox text = new TextBox();
             text.Text =Encoding.UTF8.GetString(Encoding.Default.GetBytes(feed.response.items[i].text));
             Point p = new Point(20, 30 * k);
             text.Location = p;
             this.Controls.Add(text);

             PictureBox mypic = new PictureBox();
             mypic.ImageLocation =  feed.response.items[i].attachments[att].photo.photo_130;
             mypic.Size = new Size(100, 100);
             Point g = new Point(40, 160 * k);
             mypic.Location = g;
             this.Controls.Add(mypic);
             k++;
             break;
....
    }
}

A: As indicated by Peter Duniho you can use two TableLayoutPanels, one added at design-time to your form. The other is dynamically created and populated with the right controls to achieve what you want. Your code would look like this:
private void AddOne()
{
    // create a new tablelayoutpanel
    // with 2 rows, 1 column
    var table = new TableLayoutPanel();
    table.RowCount = 2;
    table.RowStyles.Add(new RowStyle());
    table.RowStyles.Add(new RowStyle());
    table.ColumnCount = 1;
    table.Dock = DockStyle.Fill; // take all space

    // create a label, notice the Anchor setting
    var lbl = new Label();
    lbl.Text = "lorem ipsum\r\nnext line\r\nthree";
    lbl.Anchor = AnchorStyles.Left | AnchorStyles.Right;
    lbl.AutoSize = true;
    // add to the first row
    table.Controls.Add(lbl, 0, 0);

    // create the picturebox
    var pict = new PictureBox();
    pict.Image = Bitmap.FromFile(@"demo.png");
    pict.Anchor = AnchorStyles.Left | AnchorStyles.Right;
    pict.SizeMode = PictureBoxSizeMode.Zoom;
    // add to the second row
    table.Controls.Add(pict, 0, 1);

    //add the table to the main table that is on the form
    mainTable.Controls.Add(table, 0, mainTable.RowCount);
    // increase the rowcount...
    mainTable.RowCount++;

}

You'll have use the Dock and Anchor properties as well as the AutoSize property to have the Layout engine of the framework do all the heavy lifting for you.
You'll end-up with something that looks like this:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Could not load type 'Microsoft.AspNetCore.Mvc.Formatters.JsonSerializerSettingsProvider I had a project .net core 2.2 and I switch to 3.1
after that when call a api I have Exception
public override void OnActionExecuted(Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext context)
{
    var response = context.Result as ObjectResult;

    if (response?.Value == null)
        return;
}

context.Result is always null and shows me below exception:

"Could not load type
'Microsoft.AspNetCore.Mvc.Formatters.JsonSerializerSettingsProvider'
from assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json,
Version=3.1.6.0, Culture=neutral,
PublicKeyToken=adb9793829ddae60'.":"Microsoft.AspNetCore.Mvc.Formatters.JsonSerializerSettingsProvider"

Please guide me.

A: Try to restore npm packages, and make sure you have installed the "Microsoft.AspNetCore.Mvc.Formatters.Json" package.
Besides, please check the Migrate from ASP.NET Core 2.2 to 3.0 document:
As part of the work to improve the ASP.NET Core shared framework, Newtonsoft.Json (Json.NET) has been removed from the ASP.NET Core shared framework. the default JSON serializer for ASP.NET Core is now System.Text.Json
So, you could try to use the System.Text.Json Or using the Newtonsoft.Json in an ASP.NET Core.
More detail information, please check the following links:
Newtonsoft.Json (Json.NET) support
Change the JSON serialization settings of a single ASP.NET Core controller


text:
Q: Rotate UIImageView inside compass like iOS compass I would like to include in my application a compass and labels cardinal gravitationally rotate and maintain its position as the compass of iOS application.

I've done some code and separately running, but when they work together goes crazy.
This is part of the code I use:
UIImageView * imgCompass;
UIImageView * north;
- (void)viewDidLoad
{
    [super viewDidLoad];

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.headingFilter = 1;
[locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
[locationManager startUpdatingHeading];

motionManager = [[CMMotionManager alloc] init];
motionManager.accelerometerUpdateInterval = 0.01;
motionManager.gyroUpdateInterval = 0.01;

[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
                                    withHandler:^(CMAccelerometerData  *accelerometerData, NSError *error) {
                                        if (!error) {
                                            [self outputAccelertionData:accelerometerData.acceleration];
                                        }
                                        else{
                                            NSLog(@"%@", error);
                                        }
                                    }];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {

    // Convert Degree to Radian and move the needle
    newRad =  -newHeading.trueHeading * M_PI / 180.0f;

    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.viewCompass.transform = CGAffineTransformMakeRotation(newRad);

    } completion:nil];
}

- (void)outputAccelertionData:(CMAcceleration)acceleration{
    //UIInterfaceOrientation orientationNew;

    // Get the current device angle
    float xx = -acceleration.x;
    float yy = acceleration.y;
    float angle = atan2(yy, xx);

    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        // Add 1.5 to the angle to keep the image constantly horizontal to the viewer.
        [self.north setTransform:CGAffineTransformMakeRotation(angle - 1.5)];
    } completion:nil];

}

Any ideas? Thank You. I'm desperate...

A: I solved. Simply subtract the radius of the compass and add the result to the object you want. in my case north, east, west and south are UIImageView.
 - (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
    self.lblGrados.text = [NSString stringWithFormat:@"%.0f°", newHeading.magneticHeading];

    // Convert Degree to Radian and move the needle
    newRad =  -newHeading.trueHeading * M_PI / 180.0f;

    [UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        compassView.transform = CGAffineTransformMakeRotation(newRad);
    } completion:nil];

    [UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self.north setTransform:CGAffineTransformMakeRotation(-newRad)];
        [self.south setTransform:CGAffineTransformMakeRotation(-newRad)];
        [self.east setTransform:CGAffineTransformMakeRotation(-newRad)];
        [self.west setTransform:CGAffineTransformMakeRotation(-newRad)];
    } completion:nil];
}


text:
Q: kubernetes persistent volume for bare metal accessible on all nodes and pods I was trying the local or host path volumes on a LAN bare metal servers.
tried local but each node was having there own copy of the data.
How can i use volumes across all the nodes and pods.

A: Persistent Volumes have access semantics. Example on GCE if you are using a Persistent Disk, can either be mounted as writable to a single pod or to multiple pods as read-only. If you want multi writer semantics, you need to setup NFS or some other storage that let's you write from multiple pods. NFS can support multiple read/write clients.
In case you are interested in running NFS take a look: nfs-setup.
The NFS persistent volume and NFS claim gives an indirection that allow multiple pods to refer to the NFS server using a symbolic name rather than the hardcoded server address.
Take a look: pv-multiple-pods.

A: If you want to share data through your cluster, then you need to use network storage.
You can't expect kubernetes to just share your data accross all the nodes of your cluster. So local storage and host path won't work in that case.
As @MaggieO said, you can setup and use a NFS server.
If you just want to try it out, you can also use your favorite cloud provider storage solution (AWS S3, GCP Bucket, Azure Disk, etc). You can see the full list here


text:
Q: What's a word for marrying someone of similar status? Hypergamy is an action of marrying someone of a higher socio-economic class while hypogamy is doing the same for a person of lower socio-economic class. What is it called, if you marry someone of a similar class?

A: One word used here is isogamy:

Marriage customs in which the partners are of different social
statuses (see anisogamy).
In hypergamy, the woman is typically of lower social status than the
man; hypogamy is the opposite. Isogamy designates marriage between
social equals.

[Oxford Reference]

*

*Besides the two types of hypergamy, isogamy and hypogamy are also sparingly found.

Anthrosource: Hierarchy and Hypergamy ... R S Khare
This is not the default sense. As with 'homogamy', there is a sense used in biology.

A: It is called homogamy:

marriage between people from similar sociological or educational backgrounds.

(Lexico)


text:
Q: How can i solve a Dotnet build Error "namespace name 'Azure' could not be found"? I am running a simple .NET application that connects to Azure Event Hubs and send sample data.
Unfortunately when i hit " dotnet run" i get the following errors:
C:\Users\[...]\EventHubSampleSendData\Program.cs(1,7): error CS0246: The type or namespace name 'Azure' could not be found (are you missing a using directive or an assembly reference?) [C:\Users\[...]\SendSampleData.csproj]

It looks like dotnet cannot recognize the Azure library "(using) Azure.Messaging.EventHubs) inside the Program.cs
I tried the command "dotnet add package Azure.Messaging.EventHubs" but it gives also errors ( The project does not support adding package references through the add package command.)
project:
https://github.com/Azure-Samples/event-hubs-dotnet-ingest/tree/master/EventHubSampleData/EventHubSampleSendData

A: The solution is to re-intsall or restore all the packages that you have installed while creating your project. The way to do it is:

A: restore the dotnet packages, run dotnet restore in your src directory. If that doesn't solve the issue check if the specified package is added otherwise you can add it through nuget.


text:
Q: how to add all of these values in a python dictionary last one for the night, want to see what clever ways there are with python to add all of the 'count' values from the following type of dictionary:
{0: {'count': 1000}, 1: {'count': 2000}}

so the end result should be an int value of 3000.

A: >>> x = {0: {'count': 1000}, 1: {'count': 2000}}
>>> sum(v['count'] for v in x.values())
3000

A: A shorter one:
sum(d[k]['count'] for k in d)

A: sum(i['count'] for i in d.values())

A: How about using reduction in python?
reduce(lambda x,y: x+y, [v['count'] for v in a.values()])


text:
Q: Minimum area bounding rectangle contains minimum distance track of convex hull I am working on some project and I have stuck at proving that minimum area bounding rectangle contains 2 edges ( have 2 edges identical) same as minimum distance track of convex hull ( that contains all points of convex hull). Minimum distance track of convex hull is found by: From all edges find the point of convex hull with the most distance of that point and store it in the vector dist. Then take the edge and point that have min value from dist. At the end make parallel line to selected edge trough the selected point.
Now I have to prove that minimum bounding rectangle contains 2 edges, that I got in min distance track. Any Idea how to do that is very welcome.
Minimum track in blue line:

Minimum bounding rectangle:

A: You can't prove it, because it's not true.  Here's a counter-example:

The area of Triangle 1 is its base*height/2.  Let's consider the 3 possible bases: A, B, and C.
For each base, you can form a bounding box for Triangle 1 that includes that base.
In each case, the bounding box of Triangle 1 has area base*height, and Triangle 1 takes up exactly half of it, so all of those bounding boxes are the same size.
However, only in one case -- base A, does that bounding box include the entire figure, including Triangle 2.  Therefore any bounding box for the entire figure that includes line C must be bigger.  Similarly, any bounding box that includes D must be bigger.
However, the minimum width track that includes the entire figure obviously does include C or D, so the minimum width track does not share edges with the minimum bounding box.

A: Hint:
If the rectangle that you determine is the same as that obtained by rotating calipers (which I believe is true), then that rectangle contains a side and three other vertices.
Then it should be possible to show that if a rectangle contains four vertices but no side, you can rotate it slightly so that the area decreases (in other terms, the derivative of the area on the angle is nonzero).


text: Q: The underlying provider failed on Open in WCF IIS I have an app which connects fine to my WCF service in my test computer. When i deploy to IIS and run the application, i get the error message above. The WCF service pulls from SQL Server. I have tried this but I still get the same error. Please help


text:
Q: Importing modules in Python - recommended position This is a question regarding good python coding and positioning.
I have a somewhat large code for which I use lots of external modules/packages/functions. Currently I load all of them at the very top of the code because that's how I've seen it done. This is bothersome for example when I need to comment out a block of the code for testing because then I need to go up, look for the modules that block was using and comment them out too. I know I don't have to do this last part, but I do it for consistency since I don't like to import things I won't be using.
If the imported modules where listed right above the block that makes use of them, this process would be easier and the code would be easier to follow, at least for me.
My question is whether it is recommended to import all modules at the beginning of the code or should I do it throughout the code as necessary?

A: Its officially recommended to import at the beginning, see PEP8:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
Imports should be grouped in the following order:

*

*standard library imports

*related third party imports

*local application/library specific imports

*You should put a blank line between each group of imports.

Put any relevant __all__ specification after the imports.

A: Well, I would say do it however is easiest for you. But I think following the PEP8 recommendation (already referenced in another answer) is generally the best method. It's easier to see everything your module references this way all in one place, and that's where new programmers will look to add their imports to your code later.
As an aside, this page gives one reason why you might violate this convention, https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Import_Statement_Overhead:

Note that putting an import in a function can speed up the initial loading of the module, especially if the imported module might not be required. This is generally a case of a "lazy" optimization -- avoiding work (importing a module, which can be very expensive) until you are sure it is required.

If the import of a module is expensive (it's huge, or has side effects), then you might want to put it later. In short, if you want to follow this part of 'The Zen of Python':

Although practicality beats purity.

wrt to your import placement, then do so.


text:
Q: .NET 4.5 parallel processing and for loop I am trying to create a list of tasks which depend on the number of processors available.  I have a for loop which which seems to be behaving strangely.  I am aware of the concept of closures in javascript, and it seems like something similar could be happening here:
 var tasks = new Task[Environment.ProcessorCount];
 for(int x = 0; x < Environment.ProcessorCount; x ++)
 {
      tasks[x] = Task.Run(() => new Segment(SizeOfSegment, x * SizeOfSegment, listOfNumbers).generateNewList());
 }

What I am finding is when I break on the line in the for loop, the variable x seems to be correct, so it starts at 0 and ends at 3 (number of processors is 4).  But when I put the break point within the constructor for Segment, I am finding that x was actually 4 when stepping back in the Call Stack.
Any help would be greatly appreciated.

A: You're capturing x within your lambda expression - but you've got a single x variable which changes values across the course of the loop, so by the time your task actually runs, it may well have a different value. You need to create a copy of the variable inside the loop, creating a new "variable instance" on each iteration. Then you can capture that variable safely:
for(int x = 0; x < Environment.ProcessorCount; x ++)
{
    int copy = x;
    tasks[x] = Task.Run(() => new Segment(SizeOfSegment,
                                          copy * SizeOfSegment,
                                          listOfNumbers).generateNewList());
}

(I'd also advise you to rename generateNewList to GenerateNewList to comply with .NET naming conventions.)


text:
Q: Error: Property access must assign to the property or use its value Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Shell("Shutdown /s /t 60 /c See_You_Again!!!")
    If ComboBox1.Text = "IKWAS-JATI1" Then
        Button1("See_You_Again")
    End If
End Sub

A: I think you are trying to set the button Text based on ComboBox1.Text if so you have to use Button1.Text, Hence your snippet will be:
If ComboBox1.Text = "IKWAS-JATI1" Then
    Button1.Text = "See_You_Again"
End If


text:
Q: Powershell string to 2d string array- not char array Updated: I am trying to take a user input values(string) into a 2d array. For testing purpose, I assigned a string to variable.
Goal: Later I want my program to look at each row for column 1 of my array and do something like install printer software if it says Printer and don't install software if noPrinter. I can do this for 1d array but I want anywhere from 1 to 10 rows. That is why 2d array thought would be complexity.
I want to learn to do this and not ask you to write all my code.
Thank you.
Here is my code.
#set user input to a string variable
$UserInputVar = "computer1,noPrinter,Computer2,Printer,Computer3,Printer"

#this is my 2d array; Declare. i want to be able to use anywhere from 1 to 10 rows and always 2 columns
$my2d=[object[]]::(,2)

$my2d.clear #for testing purpose

#assign values of sting to 2 dimensional array
#split the string at each comma(,)
$my2d = $UserInputVar.Split(",")

#show me the values in this array
"`n #my2d[0][0] "
$my2d[0][0]   #expect value 'computer1'
$my2d[0][1]   #expect value 'noPrinter'
$my2d[0][2]
$my2d[0][3]

"`n #my2d[1][0] "
$my2d[1][0]   #expect value 'computer2'
$my2d[1][1]   #expect value 'Printer'
$my2d[1][2]
$my2d[1][3]

"`n #my2d[2][0] "
$my2d[2][0]   #expect value 'computer3'
$my2d[2][1]   #expect value 'Printer'
$my2d[2][2]
$my2d[2][3]

"`n #array with no 2nd index"
$my2d[0]
$my2d[1]
$my2d[2]

A: I'm not sure if you want an object as output, but if so, this is a simple way to do it:
$z = 0
$UserInputVar = "This,is,my,strg,to,test".Split(',')

for($z=0; $z -lt $UserInputVar.Count; $z=$z+2)
{
    [pscustomobject]@{
        1 = $UserInputVar[$z]
        2 = $UserInputVar[$z+1]
    }
}

Output
1    2
-    -
This is
my   strg
to   test

Edit
Looking again at the question, this may be what you're looking for:
$z = 0
$UserInputVar = "This,is,my,strg,to,test".Split(',')
$result = [System.Collections.Generic.List[object]]::new()
for($z=0; $z -lt $UserInputVar.Count; $z=$z+2)
{
    $result.Add(@($UserInputVar[$z],$UserInputVar[$z+1]))
}

Some Testing
PS /> $result[0]
This
is

PS /> $result[0][0]
This

PS /> $result[0][1]
is

PS /> $result[0][2]

PS /> $result[1][0]
my

A: You may also use regex matching to return your groups of 2 elements. Then you can split each of those returned pairs into a single array (because of the unary operator ,). All the returned single arrays are then wrapped automatically into Object[] array.
$UserInputVar = "computer1,noPrinter,Computer2,Printer,Computer3,Printer"
$my2d = [regex]::Matches($UserInputVar,'[^,]+(,[^,]+|$)') |
    Foreach-Object {,($_.Value -split ',')}


text:
Q: Execute multiple shell commands synchronously in Node I have working code that does exactly what I want but I'm not happy with the method I've used because it doesn't scale well.
Say I want to execute 4 commands, one after the other, to clone a repo and checkout a release to a local folder:
//shell command
var cmd = "cd /Users/xxxx/Documents/DESIGN" +
          " && git clone https://github.com/xxxx/xxxx.git testing" +
          " && cd testing" +
          " && git checkout 4.0";

//execute shell command
var exec = require("child_process").exec;
exec(cmd, function(err, stdout, stderr){
  if (err) console.log(err);
  console.log(stdout);
});

Is there a way to cleanly execute multiple commands and make this more scalable without just adding more to the original command string with the && to join them?

A: There is a lot of stuff you could do. the simplest one would be to use execSync, and execute one command after each other.
as you need commands to be executed one after the other, that would be the solution I would go with.
If you want to stick to an asynchronous pattern, use a control-flow-lib like step or async.
You could even promisify exec with a lib like bluebird.
it all depends on personal coding preferences and the task you need to do.


text:
Q: Dropping parallel postulate and infinitude of straight line I was reading an article about back ground of Killing's work by Thomas Hawkins from Historia mathematica $1980$ (doi: 10.1016/0315-0860(80)90027-0). It was written that Killing stated that if one drop assumptions infinitude of straight line and parallel postulates four possibilities arise, which we can judge. I got only one which is very simple. Lines which has a transverse need not intersect at a point on the side where sum of interior angles is less than two right angles.
Is it correct?
Then what are the other possibilities Killing suggests?

A: The cited statement appears on page 301 of the article.  I believe the answer to your question is given on page 311, where the following appears: "Just as previous generations of mathematicians had offered proofs of the parallel postulate, those of the second half of the 19th century provided many proofs that there are only three, or in some cases, four geometries compatible with experience: Euclidean and Lobachevskian geometry, the spherical geometry of Riemann, and elliptic geometry."  This statement is in reference to the prevailing late 19th century opinion that, pace Riemann, geometry meant manifolds of constant curvature.
Lobachevsky's geometry is the geometry of constant negative curvature, which has the property you mention.  The sphere has constant positive curvature.  There are no parallel lines, and lines perpendicular to a given line will meet at two antipodal points.  (As a consequence, two points do not always uniquely determine a line.)  Elliptic geometry is the geometry of the sphere with antipodal points identified, which has the topology of the projective plane.  Like spherical geometry, this has constant positive curvature, but lines perpendicular to a given line meet at only one point, and the property that two points uniquely determine a line is restored.
Some of the historical background for the above is given in the pages preceding page 301 of the article.  Page 298 explains how Riemann's suggestion of a surface of constant positive curvature was initially widely understood to be spherical geometry, until the independent discovery of elliptic geometry by Klein and Newcomb had time to sink in.


text:
Q: iTunes connect update limited to some countries? I have an app available for multiple countries; and now I need to release an update only to some of this countries.
Example
An app available for the whole world, is going to get an update, but it should only be available for USA users for instance.
Is it possible to release this update only to the USA store, or somehow limit it?
Thanks in advance.

A: If you limit the app to any geographical extent, then current users will be able to use it, but it won't appear to anyone on iTunes.
So, if you wanted an update for some region while having the previous version available, the answer is no, there's no way to do that.
@skorulis I find many reasons why you could want to do so, e.g. incremental release of the app update amongst many others.


text:
Q: Vue.js Why 2 objects are linked? I have two data objects called items and itemsOrg
var vm = new Vue({
      el: '#divVM',
      mixins: [mix],
      data: {
            items: [],
            itemsOrg:[],
            // ....
           },

When the page loads, I make an AJAX call to fetch data from MySQL table and assign it to items and itemsOrg object.
function getMustacheVariables()
{
    $.ajax({
       type: "POST",
       url: "adminAjax.php",
        data: {
            actionID: 'GET_DATA',
        },
        dataType: "json",

        success: function(data)
        {
            vm.items= data;
            vm.itemsOrg = data;
        }
        // ...

However, when I update Vm.items, vm.itemsOrg is also automatically updated and don't know why these the two are linked. Here is a snapshot of console.log
vm.items[0]["key"]
"agent"
vm.itemsOrg[0]["key"]
"agent"
vm.items[0]["key"] = "new_key"
"new_key"
vm.itemsOrg[0]["key"]
"new_key"
vm.itemsOrg[0]["key"] = "updated_key"
"updated_key"
vm.items[0]["key"]
"updated_key"

Is there a reason that these two objects are linked? I even tried assigning vm.items to vm.itemsOrg using vm.items.slice() as well as push() but the two objects are always linked.
I appreciate any help.

A: After playing with your example I noticed that we can simplify your AJAX fetched object as data = { 0: { key: 'agent'} and it has this property data[0] assigned to a reference of the object { key: 'agent'} (data can be called a nested object)
So it seems that even if you're copying the data object with Object.assign you'll still have every referenced object in it. As said here :

But be aware that this makes a shallow copy only. Nested objects are still copied as references.

So you have two options that would work without JQuery:
1. Using JSON.parse and JSON.stringify like JSON.parse(JSON.stringify(data)) to stringify then parse your object
2. Making a loop to manually deep copy the object (as in the outdated answer of the thread referenced above)
And if using JQuery you can write jQuery.extend(true ,{}, data) with the deep option set to true

A: Yes there is a reason here. this code means that's vm.items and vm.itemsOrg are the same ref (data).
use chrome devtools to see the Trace
    vm.items= data;
    vm.itemsOrg = data;


text:
Q: How can I check if a date falls between two other dates? I have a dataframe with 7 columns of date variables: start.date, end.date, date1, date2, date3, date4, date5. The dates are in the format yyyy-mm-dd.
I want to create a new variable that tells me how many of date1, date2, date3, date4, date5 fall between start.date and end.date using R, is this possible?

A: Hi you could use %within% from lubridate:
Data I use:
library(dplyr)
library(lubridate)
df <- nycflights13::flights |>
  mutate(start = as_date(time_hour),
         end = start + days(5)) |>
  slice(1:2) |>
  select(start, end) |>
  mutate(test_date = c("2013-01-10", "2013-01-03") |> ymd())

# A tibble: 2 × 3
  start      end        test_date
  <date>     <date>     <date>
1 2013-01-01 2013-01-06 2013-01-10
2 2013-01-01 2013-01-06 2013-01-03

Testing:
df |>
  mutate(log_test = test_date %within% interval(start, end))

Output is:
# A tibble: 2 × 4
  start      end        test_date  log_test
  <date>     <date>     <date>     <lgl>
1 2013-01-01 2013-01-06 2013-01-10 FALSE
2 2013-01-01 2013-01-06 2013-01-03 TRUE


text:
Q: A carwash is for clean up
*

*A carwash is for clean up.

*A carwash is for cleaning up.

Is #1 corrct to say?
(A carwash where you take your car for clean up(cleaning up)

A: "A car wash is for cleaning your car." Or : "A car wash is (a place) where you take your car to be cleaned."
You use of the terms "cleanup" and "cleaning up" are both incorrect.
As PE Dant points out, "cleanup" is a process of dealing with environmental pollution, such as an oil spill.
You use "cleaning up" when you are referring to the mess which has been made. So you could say "I am cleaning up after having a party" or you could say "A mop and bucket are used for cleaning up the mud from the kitchen floor."
You use "clean" on its own without the "up" when you are referring to a space or object, rather than the mess or dirt on or in it. So you clean the kitchen or the windows, or you clean the car.
http://www.phrasemix.com/answers/whats-the-difference-between-clean-away-clean-up-clean-out-e


text:
Q: Exception: "can't multiply sequence by non-int of type 'float' I'm trying to write very simple code to calculate the discount on a article. Following is the code and it throws the exception on the 3rd line in the code. The exception is:
Traceback (most recent call last):
  File "C:/Users/basam/AppData/Local/Programs/Python/Python35/discounts.py", line 3, in <module>
    discount=0.1*price
TypeError: can't multiply sequence by non-int of type 'float'

The code:
price=input('how much is your item?')
if int(price) <= 10:
    discount=0.1*price

Can someone advise on what the problem is?

A: The key is int(price). The input command returns a string which is stored in the variable price.
In the second line, price is converted to a number by the call int(price), but that result is not stored anywhere. It is used for the comparison and then discarded. So when you go to multiply in the third line, you're trying to multiply a number times a string.

A: As @Silvio Mayolo has stated, the problem is that your price variable is of type String. You can wrap your input() call to cast the input value to an integer which should allow for the calculation to work
price = int(input('how much is your item?'))
if price <= 10:
    discount = 0.1 * price

print(discount)
>> 0.5

or better yet - considering you're dealing with 'money' which can have decimal values, use a 'float' type rather than 'int'
price = float(input("how much is item 2?"))
if price <= 10:
    discount = 0.1 * price

print(discount)
>> 0.5

A: Change to
discount=0.1*float(price)


text:
Q: Android - Issue in receiving JSonObject String having length more than 1000 characters in mobile device My android app accesses a (.NET) WCF service (deployed at separate machine on IIS7) to retrieve customers' data to show on a mobile device but when JSon string data size increases to 1000 characters, then the exception handler catches it with the error "string terminated with invalid character", which is supposed to be "}]", but due to string truncation, it doesn't find it.
The confusing thing is that it happens only when I execute the app from my mobile device (i.e. Lenovo S960), but works perfectly from Android Studio, so I couldn't find anything by debugging the source code. Initially, I thought it could be a JSon size issue, but I get the full json string when I access same WCF service through the browser (URL) from the client machine, which shows that IIS is returning full data.
My question is this: why is only the mobile device (production environment) unable to get the JSon string having more than 1000 characters? Following is the code which consumes data from the WCF for your reference.
private synchronized static boolean getRawXML(String URL,
        SerializedObject responseOut,ErrMsgOut errMsgOut) {

    try {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(URL);
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");

        HttpResponse response = client.execute(request);

        HttpEntity entity = response.getEntity();

        if (entity.getContentLength() != 0) {
            Reader reader = new InputStreamReader(response.getEntity().getContent());
            char[] buffer = new char[(int) response.getEntity().getContentLength()];
            reader.read(buffer);
            reader.close();

            responseOut.setResponse(new String(buffer));
        }
        else {
            errMsgOut.setErrorDescription("Unable to get raw data!");
            return false;
        }
    } catch(Exception ex) {
        ex.printStackTrace();
        errMsgOut.setErrorDescription("getRawXML( )\n" + ex.getMessage());
        return false;
    }
    return true;
}

A:
i get full json string when I access same WCF service thru (URL) browser from client machine which shows that IIS is returning full data.

Check the content length header coming back from the server.  IIRC, you really can't count on the content length being exactly the length of the data returned because of things like compression and chunked response data.
Also, instead of trying to divine the buffer size, reading the output stream into a string and processing the string, just process the output stream.  Check out android.util.JsonReader for a way to do that.  It's better on memory usage that way as well.


text:
Q: NSInternalInconsistencyException with legacy ObjC code in Xcode 9 I've just began learning swift and I can't seem to figure out how to fix the following legacy code from a music app my company launched in 2016. I working towards updating the platform, but the app crashes each time I select My Profile, so I assume it's somewhere in UITableViewCell, however, this is inferred due to the following:

"Assertion failure in -[UITableView
  _dequeueReusableCellWithIdentifier:forIndexPath:usingPresentationValues:],
  /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3698.33.7/UITableView.m:7883
  2018-01-16 21:41:01.168538-0500 Gleamy[4101:1978203] *** Terminating
  app due to uncaught exception 'NSInternalInconsistencyException',
  reason: 'Attempted to dequeue multiple cells for the same index path,
  which is not allowed. If you really need to dequeue more cells than
  the table view is requesting, use the
  dequeueReusableCellWithIdentifier: method (without an index path).
  Cell identifier: cell, index path:
  {length = 2, path = 0 - 0}'

*** First throw call stack:

(0x181c3a364 0x180e80528 0x181c3a238 0x1825d57f4 0x18b51a44c
  0x18b353570 0x100b53334 0x18b52bac4 0x18b52c028 0x18b50a8ac
  0x18b2c133c 0x18b1edf00 0x185c7d998 0x185c81b20 0x185bee36c
  0x185c15b90 0x185c169d0 0x181be1edc 0x181bdf894 0x181bdfe50
  0x181affe58 0x1839acf84 0x18b25467c 0x100b7d2b8
  0x18161c56c)libc++abi.dylib: terminating with uncaught exception of
  type NSException"

Thread 1: signal SIGABRT:
int main(int argc, char * argv[]) {
@autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}

}
 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

if (indexPath.row==0)
{
    HeaderCell *cell=[tableView dequeueReusableCellWithIdentifier:@"headercell" forIndexPath:indexPath];
    objectForKey:@"profile_pic"]  , @"cover_pic":[response objectForKey:@"cover_pic"],  @"follow_count":[response objectForKey:@"follow_count"],  @"following_count":[response objectForKey:@"following_count"]   ,   @"user_name":[response objectForKey:@"user_name"], @"name":[response objectForKey:@"name"],};

    NSMutableDictionary *data= response;

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(GalleryClicked)];
    tapGesture.numberOfTapsRequired = 1;
    [cell.img_gallery setUserInteractionEnabled:YES];
    [cell.img_gallery addGestureRecognizer:tapGesture];

    UITapGestureRecognizer *viewProfilepic = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(showProfilePic)];
    viewProfilepic.numberOfTapsRequired = 1;
    [cell.img_profilepic setUserInteractionEnabled:YES];
    [cell.img_profilepic addGestureRecognizer:viewProfilepic];

    UITapGestureRecognizer *viewcoverpic = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(showCoverPic)];
    viewcoverpic.numberOfTapsRequired = 1;
    [cell.img_coverPic setUserInteractionEnabled:YES];
    [cell.img_coverPic addGestureRecognizer:viewcoverpic];

    [cell.btn_message addTarget:self action:@selector(myMessages) forControlEvents:UIControlEventTouchUpInside];
    [cell.btn_notification addTarget:self action:@selector(notifications) forControlEvents:UIControlEventTouchUpInside];

        [cell setUpHeaderCellWithData:data];

    if ([data objectForKey:@"profile_pic"])
    {
        if ([[data objectForKey:@"profile_pic"] containsString:@"http"])
            profilPicUrl=[data objectForKey:@"profile_pic"];
        else
            profilPicUrl=@"http://gleamedm.com/reb/img/fans/profile_pic/default.jpg";
    }

    if ([data objectForKey:@"cover_pic"])
    {
        if ([[data objectForKey:@"cover_pic"] containsString:@"http"])
            coverPicUrl=[data objectForKey:@"cover_pic"];

        else
            coverPicUrl=[NSString stringWithFormat:@"http://gleamedm.com/reb/img/fans/cover_pic/%@",[data objectForKey:@"cover_pic"]];
    }
    else
        coverPicUrl=@"http://gleamedm.com/reb/img/fans/cover_pic/default.jpg";

    return cell;
}
else
{
    int index=(int)indexPath.row-1;    // bcoz 0 is for header
    indexPath=[NSIndexPath indexPathForRow:index inSection:0];

    SinglePost *postObj = (SinglePost *)[posts objectAtIndex:index];

    if (postObj.msg_postImgStr .length >0)
    {
        MyProfileDataCell2 *cell=(MyProfileDataCell2*)[tableView dequeueReusableCellWithIdentifier:@"dataCell2" forIndexPath:indexPath];

        [cell setupCellWithPostObject:postObj];
        [cell.textView setDelegate: self];
        cell.textView.tag=index;

        UITapGestureRecognizer *tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(Postclicked:)];
        [cell.topView setUserInteractionEnabled:YES];
        [cell.topView addGestureRecognizer:tapGesture2];
        [cell.topView setTag:index];

        [cell.btn_comment addTarget:self action:@selector(commentClicked:) forControlEvents:UIControlEventTouchUpInside];
        [cell.btn_likeUnlike addTarget:self action:@selector(likeUnlikeClicked:) forControlEvents:UIControlEventTouchUpInside];

        cell.btn_likeUnlike.tag=cell.btn_comment.tag=index;

        UITapGestureRecognizer *viewcoverpic = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(PostPictureClicked:)];
        viewcoverpic.numberOfTapsRequired = 1;
        [cell.img_messagePic setUserInteractionEnabled:YES];
        [cell.img_messagePic addGestureRecognizer:viewcoverpic];
        [cell.img_messagePic setTag:index];

        return cell;
    }
    else
    {
        DataCell1 *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell setupCellWithPostObject:postObj];

        [cell.textView setDelegate: self];
        cell.textView.tag=index;

        UITapGestureRecognizer *tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(Postclicked:)];
        [cell.topView setUserInteractionEnabled:YES];
        [cell.topView addGestureRecognizer:tapGesture2];
        [cell.topView setTag:index];

        [cell.btn_comment addTarget:self action:@selector(commentClicked:) forControlEvents:UIControlEventTouchUpInside];
        [cell.btn_likeUnlike addTarget:self action:@selector(likeUnlikeClicked:) forControlEvents:UIControlEventTouchUpInside];

        cell.btn_likeUnlike.tag=cell.btn_comment.tag=index;
        return cell;
    }
}

}

A: Because of these lines:
int index=(int)indexPath.row-1;    // bcoz 0 is for header
indexPath=[NSIndexPath indexPathForRow:index inSection:0];

when the cellForRowAt method is called with indexPath 0-1, the dequeue call in your code is using indexPath 0-0, for which a cell has already been dequeued (when cellForRowAt was called with indexPath 0-0).  Hence the error.  (I can only assume that this internal consistency check is new in a recent release of iOS, and was not present when the code was first written.)
The code doesn't seem to use the indexPath except for the dequeue calls, so I think you can just delete the second line above: you should keep the first line, as it remaps your array index to the correct row, to allow for the header at row 0.


text:
Q: Pushing message into JMS queue from Junit I am trying to push messages to a JMS Queue from a Junit testcase, but I keep getting the error:
javax.naming.NameNotFoundException: Name [ConnectionFactory] not bound

Here is the testcase code:
public void testPushMessagesIntoQueue() {
    JmsTemplate jmsTemplate = (JmsTemplate) getBean("batchMessageTemplate"); //ERROR HERE
    assertNotNull(jmsTemplate);
    try {
        jmsTemplate.convertAndSend("batchQueue", messageList);
    } catch(Exception ex ) {
        ex.printStackTrace();
    }

}

public ApplicationContext getContext() {
    return new FileSystemXmlApplicationContext("/src/main/webapp/WEB-INF/service-context.xml");
}

public Object getBean(String beanName) {
    return getContext().getBean(beanName);
}

Here is my connection factory bean in service-context.xml file :
<bean name="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate" ref="jndiTemplate"/>
    <property name="jndiName" value="ConnectionFactory" />
</bean>

And my jndiTemplate bean :
<bean id="jndiTemplate" class="com.xxx.batch.common.util.CustomJndiTemplate">
</bean>

In class customJndiTemplate, I set the properties as
       public CustomJndiTemplate() throws JobException {
          Properties environment = new Properties();
       environment.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
       environment.setProperty("java.naming.provider.url", "jnp://localhost:1099");
       environment.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
       setEnvironment(environment);
       }

My batchMessageTemplate bean:
  <bean name="batchMessageTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="jmsConnectionFactory" />
    <property name="defaultDestination" ref="batchDestination" />
    <property name="receiveTimeout" value="1" />
</bean>

In my Jbossmq-destinations-service.xml in my Jboss4, i have defined the queue :
<mbean code="org.jboss.mq.server.jmx.Queue"
 name="jboss.mq.destination:service=Queue,name=batchQueue">
<depends optional-attribute-name="DestinationManager">jboss.mq:service=DestinationManager</depends>

When i run the testcase after starting jboss 4, I get the error:
Error creating bean with name 'jmsConnectionFactory' defined in file [service-context.xml]: Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: Name [ConnectionFactory] not bound;

This problem happens only when i run my Junit testcase.  have defined a servlet which runs within Jboss to add messages to the queue and it works fine
I'm new to JMS, so any help will be appreciated.


text:
Q: Sendgrid set up on Rails 4 I have a rails 4 app. I set up ActionMailer and I can send order confirmation emails via localhost and gmail.
I installed Sendgrid on Heroku and followed the set up instructions. I get a  Net::SMTPSyntaxError (501 Syntax error
my environment.rb (i have sendgrid user/pwd in application.yml)
ActionMailer::Base.smtp_settings = {
  :address        => 'smtp.sendgrid.net',
  :port           => '587',
  :authentication => :plain,
  :user_name      => ENV['SENDGRID_USERNAME'],
  :password       => ENV['SENDGRID_PASSWORD'],
  :domain         => 'heroku.com',
  :enable_starttls_auto => true
}

in production.rb - the only actionamailer setting i have is this. I have this as a placeholder to put the real domain in later. I'm currently using herokuapp.com.
config.action_mailer.default_url_options = { host: 'localhost:3000' }

in my orders_controller within the order create method, I call the below.
AutoNotifier.orderconf_email(current_user, @order).deliver

auto_notifier.rb
class AutoNotifier < ActionMailer::Base
  default from: "Test Email"

  def orderconf_email(current_user, order)
        @buyer = current_user
        @order =  order
        mail(to: @buyer.email, subject: 'Thank you for your order.')
  end
end

What am I missing? It works on localhost with gmail so I'm missing something in the sendgrid settings or in the default_url in production.rb file.

A: Change default from: "Test Email" to valid email address, even example@example.com.

A: For posterity, here's a working setup for external SMTP in Rails on Heroku:
#config/environments/production.rb
config.action_mailer.smtp_settings = {
    :address   => "smtp.sendgrid.net",
    :port      => 587, # ports 587 and 2525 are also supported with STARTTLS
    :enable_starttls_auto => true, # detects and uses STARTTLS
    :user_name => ENV["SENDGRID_USERNAME"],
    :password  => ENV["SENDGRID_PASSWORD"], # SMTP password is any valid API key, when user_name is "apikey".
    :authentication => 'login',
    :domain => 'yourdomain.com', # your domain to identify your server when connecting
}

A: I would just like to point out, this is for sending emails via SMTP. While this method is totally ok, you should also consider sending via the API.
To do this, you need to specify an interceptor. Luckily, there's a Gem that helps with that. Here's a good article showing how to use it.
https://rubyplus.com/articles/561-Sending-Emails-using-SendGrid-API-in-Rails-4-1

A: It took us a long time to resolve the issue when we tried to deploy the SMTP relay on heroku. It worked perfectly fine on local but when pushed we received socket errors and time out issues. Eventually got it working.
Important note: Make sure not to use starttls_auto and SSL/or TLS this causes open SSL issue.


text:
Q: How to test if it is a non-multiplexed (static) LCD? I got some static LCD's from an old cheap clock, calculator and the like and now I would like to use them for displaying simple things like temperature. They are connected with those pink with grey connector bars, if you know what I mean.
I found this article: http://www.ubasics.com/driving_static_lcds but he talks about non-multiplexed LCD's. How can I see/test/check what for static LCD I have?
It would be great if I could use these static LCD's, do you guys got more info on how to use these things (multiplexed or not)? Can I use it with an ATtiny2313?
Thanks.

A: Try counting the number of pins compared to the number of LCD display segments? That should be one way to possibly determine. There should be at least as many pins as segments, plus a one or more extra for the common pin(s). If there are significantly fewer pins than display segments, it must be multiplexed.

A: You can hook up the LCD as described in that article, and start testing pins by hooking the common up to one pin, and the drive up to another pin.  Map out the whole LCD this way and you should soon see which segments go to which pins.
A static LCD will have one pin, common, that will drive all other segments (should be easy to find) and another pin for each segment on the display.
A multiplexed display will have 2 or more common pins that each drive a number of segments, an each other pin will drive a few segments.


text:
Q: Handling a method in integration flow I have created an application that uses Spring MVC to add ftp servers through a web page. When I add a server with details, it will start a flow polling a directory on the sever for specific csv file, once that file is there it will pull it to my local folder then a method is created to read that csv file and generate a new csv that will be sent back to the server, now this is accomplished, my issue is that when I add a new ftp server to poll and it finds a csv file on the second server, the application is pulling that file to my local as it should do but the handling method is being triggered again for both csv files while it should only do so for the second server since it is already triggered for the first server, so when I add the second server then again another file for server 1 generated and sent back to ftp and new one for the second server is send to the second ftp, at the end I have two files sent to first serve and one file to the second server, below is the coding and the output consol of the app, please assist on pinpointing my issue.
@Configuration
@EnableIntegration
@ComponentScan
public class FTIntegration {

public static final String TIMEZONE_UTC = "UTC";
public static final String TIMESTAMP_FORMAT_OF_FILES = "yyyyMMddHHmmssSSS";
public static final String TEMPORARY_FILE_SUFFIX = ".part";
public static final int POLLER_FIXED_PERIOD_DELAY = 5000;
public static final int MAX_MESSAGES_PER_POLL = 100;

//private static final Logger LOG = LoggerFactory.getLogger(FTIntegration.class);
private static final Logger LOG1 = Logger.getLogger(FTIntegration.class);
private static final String CHANNEL_INTERMEDIATE_STAGE = "intermediateChannel";

private static final String OUTBOUND_CHANNEL = "outboundChannel";

/* pulling the server config from postgres DB*/

private final BranchRepository branchRepository;

@Autowired
private CSVToCSVNoQ csvToCSVNoQ;

@Value("${app.temp-dir}")
private String localTempPath;

public FTIntegration(BranchRepository branchRepository) {
    this.branchRepository = branchRepository;
}

@Bean
public Branch myBranch(){
    return new Branch();
}

/**
 * The default poller with 5s, 100 messages, RotatingServerAdvice and transaction.
 *
 * @return default poller.
 */
@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller(){
    return Pollers
            .fixedDelay(POLLER_FIXED_PERIOD_DELAY)
            .maxMessagesPerPoll(MAX_MESSAGES_PER_POLL)
            .transactional()
            .get();
}

/**
 * The direct channel for the flow.
 *
 * @return MessageChannel
 */
@Bean
public MessageChannel stockIntermediateChannel() {
    return new DirectChannel();
}
/**
 * Get the files from a remote directory. Add a timestamp to the filename
 * and write them to a local temporary folder.
 *
 * @return IntegrationFlow
 */

@Bean
public PropertiesPersistingMetadataStore store() {
    PropertiesPersistingMetadataStore store = new PropertiesPersistingMetadataStore();
    return store;
}
 public IntegrationFlow fileInboundFlowFromFTPServer(Branch myBranch) throws IOException {

    final FtpInboundChannelAdapterSpec sourceSpecFtp = Ftp.inboundAdapter(createNewFtpSessionFactory(myBranch))
            .preserveTimestamp(true)
          //.patternFilter("*.csv")
            .maxFetchSize(MAX_MESSAGES_PER_POLL)
            .remoteDirectory(myBranch.getFolderPath())
            .regexFilter("FEFOexport"+myBranch.getBranchCode()+".csv")
            .deleteRemoteFiles(true)
            .localDirectory(new File(myBranch.getBranchCode()))
            .temporaryFileSuffix(TEMPORARY_FILE_SUFFIX)

            /*.localFilenameExpression(new FunctionExpression<String>(s -> {
                final int fileTypeSepPos = s.lastIndexOf('.');
                return DateTimeFormatter
                        .ofPattern(TIMESTAMP_FORMAT_OF_FILES)
                        .withZone(ZoneId.of(TIMEZONE_UTC))
                        .format(Instant.now())
                        + "_"
                        + s.substring(0,fileTypeSepPos)
                        + s.substring(fileTypeSepPos);
            }))*/;

    // Poller definition
    final Consumer<SourcePollingChannelAdapterSpec> stockInboundPoller = endpointConfigurer -> endpointConfigurer
            .id("stockInboundPoller")
            .autoStartup(true)
            .poller(poller());

    IntegrationFlow flow = IntegrationFlows
            .from(sourceSpecFtp, stockInboundPoller)

            .transform(File.class, p ->{
                // log step
                LOG1.info("flow=stockInboundFlowFromAFT, message=incoming file: " + p);
                return p;
            })
            .channel(CHANNEL_INTERMEDIATE_STAGE)
            .handle(m -> {
                try {
                    this.csvToCSVNoQ.writeCSVfinal("test", myBranch.getBranchCode() + "/final" + myBranch.getBranchCode() + ".csv", myBranch.getBranchCode() + "/FEFOexport" + myBranch.getBranchCode() + ".csv");
                    LOG1.info("Writing final file .csv " + m);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            })
            //.handle(m -> this.csvToCSVNoQ.writeCSVfinal(m.getPayload(),m.getHeaders().get("csv", "FEFOexport"+myBranch.getBranchCode()+".csv")))
            .get();

    return flow;
}

@Bean
public IntegrationFlow stockIntermediateStageChannel() {
    IntegrationFlow flow = IntegrationFlows
            .from(CHANNEL_INTERMEDIATE_STAGE)
            .transform(p -> {
                //log step
                LOG1.info("flow=stockIntermediateStageChannel, message=rename file: " + p);

                return p;
            })
            //TODO
            .channel(new NullChannel())
            .get();

    return flow;

}

/*
* Creating the outbound adaptor to send files from local to FTP server
*
* */

public IntegrationFlow localToFtpFlow(Branch myBranch){
    return IntegrationFlows.from(Files.inboundAdapter(new File(myBranch.getBranchCode()))

                .filter(new ChainFileListFilter<File>()
                        .addFilter(new RegexPatternFileListFilter("final" + myBranch.getBranchCode() +".csv"))
                        .addFilter(new FileSystemPersistentAcceptOnceFileListFilter(new SimpleMetadataStore(), "foo"))),
                        e -> e.poller(Pollers.fixedDelay(10_000)))
            .transform( p ->{
                LOG1.info("Sending file " + p + " to FTP branch " + myBranch.getBranchCode());

                return p;
            })

            .log()
            .handle(Ftp.outboundAdapter(createNewFtpSessionFactory(myBranch),FileExistsMode.REPLACE)
                    .useTemporaryFileName(true)
                    .autoCreateDirectory(false)
                    .remoteDirectory(myBranch.getFolderPath()))
            .get();
}

public DefaultFtpSessionFactory createNewFtpSessionFactory(Branch branch){
    final DefaultFtpSessionFactory factory = new DefaultFtpSessionFactory();
    factory.setHost(branch.getHost());
    factory.setUsername(branch.getUsern());
    factory.setPort(branch.getFtpPort());
    factory.setPassword(branch.getPassword());
    return factory;
}

Console Output:
Saved Branch : BEY
Hibernate: select branch0_._id as _id1_0_0_, branch0_.branch_code as branch_c2_0_0_, branch0_.folder_path as folder_p3_0_0_, branch0_.ftp_port as ftp_port4_0_0_, branch0_.host as host5_0_0_, branch0_.password as password6_0_0_, branch0_.usern as usern7_0_0_ from branch branch0_ where branch0_._id=?
2018-12-20 07:58:39.218  INFO 6668 --- [nio-8081-exec-5] o.s.integration.channel.DirectChannel    : Channel 'application.intermediateChannel' has 2 subscriber(s).
2018-12-20 07:58:39.218  INFO 6668 --- [nio-8081-exec-5] o.s.i.endpoint.EventDrivenConsumer       : started 1.org.springframework.integration.config.ConsumerEndpointFactoryBean#1
2018-12-20 07:58:39.218  INFO 6668 --- [nio-8081-exec-5] o.s.i.endpoint.EventDrivenConsumer       : Adding {transformer} as a subscriber to the '1.channel#0' channel
2018-12-20 07:58:39.218  INFO 6668 --- [nio-8081-exec-5] o.s.integration.channel.DirectChannel    : Channel 'application.1.channel#0' has 1 subscriber(s).
2018-12-20 07:58:39.218  INFO 6668 --- [nio-8081-exec-5] o.s.i.endpoint.EventDrivenConsumer       : started 1.org.springframework.integration.config.ConsumerEndpointFactoryBean#0
2018-12-20 07:58:39.229  INFO 6668 --- [nio-8081-exec-5] o.s.i.e.SourcePollingChannelAdapter      : started stockInboundPoller
2018-12-20 07:58:39.417  INFO 6668 --- [nio-8081-exec-5] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler} as a subscriber to the '1o.channel#2' channel
2018-12-20 07:58:39.417  INFO 6668 --- [nio-8081-exec-5] o.s.integration.channel.DirectChannel    : Channel 'application.1o.channel#2' has 1 subscriber(s).
2018-12-20 07:58:39.418  INFO 6668 --- [nio-8081-exec-5] o.s.i.endpoint.EventDrivenConsumer       : started 1o.org.springframework.integration.config.ConsumerEndpointFactoryBean#1
2018-12-20 07:58:39.418  INFO 6668 --- [nio-8081-exec-5] o.s.i.endpoint.EventDrivenConsumer       : Adding {transformer} as a subscriber to the '1o.channel#0' channel
2018-12-20 07:58:39.418  INFO 6668 --- [nio-8081-exec-5] o.s.integration.channel.DirectChannel    : Channel 'application.1o.channel#0' has 1 subscriber(s).
2018-12-20 07:58:39.418  INFO 6668 --- [nio-8081-exec-5] o.s.i.endpoint.EventDrivenConsumer       : started 1o.org.springframework.integration.config.ConsumerEndpointFactoryBean#0
2018-12-20 07:58:39.419  INFO 6668 --- [nio-8081-exec-5] o.s.i.e.SourcePollingChannelAdapter      : started 1o.org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean#0
2018-12-20 07:59:41.165  INFO 6668 --- [sk-scheduler-10] o.s.integration.ftp.session.FtpSession   : File has been successfully transferred from: /ftp/erbranch/EDMS/FEFO/FEFOexportBEY.csv
2018-12-20 07:59:49.446  INFO 6668 --- [ask-scheduler-1] o.s.i.file.FileReadingMessageSource      : Created message: [GenericMessage [payload=BEY\finalBEY.csv, headers={file_originalFile=BEY\finalBEY.csv, id=7f0cccb7-a070-bd4c-d468-977a265ceb2e, file_name=finalBEY.csv, file_relativePath=finalBEY.csv, timestamp=1545285589446}]]
2018-12-20 07:59:49.448  INFO 6668 --- [ask-scheduler-1] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=BEY\finalBEY.csv, headers={file_originalFile=BEY\finalBEY.csv, id=d857130a-d4a0-eaeb-19ea-f819924d94e2, file_name=finalBEY.csv, file_relativePath=finalBEY.csv, timestamp=1545285589447}]
2018-12-20 07:59:50.488  INFO 6668 --- [ask-scheduler-1] o.s.integration.ftp.session.FtpSession   : File has been successfully transferred to: /ftp/erbranch/EDMS/FEFO/finalBEY.csv.writing
2018-12-20 07:59:50.899  INFO 6668 --- [ask-scheduler-1] o.s.integration.ftp.session.FtpSession   : File has been successfully renamed from: /ftp/erbranch/EDMS/FEFO/finalBEY.csv.writing to /ftp/erbranch/EDMS/FEFO/finalBEY.csv
Hibernate: select branch0_._id as _id1_0_, branch0_.branch_code as branch_c2_0_, branch0_.folder_path as folder_p3_0_, branch0_.ftp_port as ftp_port4_0_, branch0_.host as host5_0_, branch0_.password as password6_0_, branch0_.usern as usern7_0_ from branch branch0_
Hibernate: insert into branch (branch_code, folder_path, ftp_port, host, password, usern) values (?, ?, ?, ?, ?, ?)
Hibernate: select currval('branch__id_seq')
Saved Branch : JNB
Hibernate: select branch0_._id as _id1_0_0_, branch0_.branch_code as branch_c2_0_0_, branch0_.folder_path as folder_p3_0_0_, branch0_.ftp_port as ftp_port4_0_0_, branch0_.host as host5_0_0_, branch0_.password as password6_0_0_, branch0_.usern as usern7_0_0_ from branch branch0_ where branch0_._id=?
2018-12-20 08:02:24.966  INFO 6668 --- [nio-8081-exec-8] o.s.integration.channel.DirectChannel    : Channel 'application.intermediateChannel' has 3 subscriber(s).
2018-12-20 08:02:24.966  INFO 6668 --- [nio-8081-exec-8] o.s.i.endpoint.EventDrivenConsumer       : started 2.org.springframework.integration.config.ConsumerEndpointFactoryBean#1
2018-12-20 08:02:24.966  INFO 6668 --- [nio-8081-exec-8] o.s.i.endpoint.EventDrivenConsumer       : Adding {transformer} as a subscriber to the '2.channel#0' channel
2018-12-20 08:02:24.966  INFO 6668 --- [nio-8081-exec-8] o.s.integration.channel.DirectChannel    : Channel 'application.2.channel#0' has 1 subscriber(s).
2018-12-20 08:02:24.966  INFO 6668 --- [nio-8081-exec-8] o.s.i.endpoint.EventDrivenConsumer       : started 2.org.springframework.integration.config.ConsumerEndpointFactoryBean#0
2018-12-20 08:02:24.966  INFO 6668 --- [nio-8081-exec-8] o.s.i.e.SourcePollingChannelAdapter      : started stockInboundPoller
2018-12-20 08:02:24.992  INFO 6668 --- [nio-8081-exec-8] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler} as a subscriber to the '2o.channel#2' channel
2018-12-20 08:02:24.992  INFO 6668 --- [nio-8081-exec-8] o.s.integration.channel.DirectChannel    : Channel 'application.2o.channel#2' has 1 subscriber(s).
2018-12-20 08:02:24.992  INFO 6668 --- [nio-8081-exec-8] o.s.i.endpoint.EventDrivenConsumer       : started 2o.org.springframework.integration.config.ConsumerEndpointFactoryBean#1
2018-12-20 08:02:24.992  INFO 6668 --- [nio-8081-exec-8] o.s.i.endpoint.EventDrivenConsumer       : Adding {transformer} as a subscriber to the '2o.channel#0' channel
2018-12-20 08:02:24.992  INFO 6668 --- [nio-8081-exec-8] o.s.integration.channel.DirectChannel    : Channel 'application.2o.channel#0' has 1 subscriber(s).
2018-12-20 08:02:24.992  INFO 6668 --- [nio-8081-exec-8] o.s.i.endpoint.EventDrivenConsumer       : started 2o.org.springframework.integration.config.ConsumerEndpointFactoryBean#0
2018-12-20 08:02:24.992  INFO 6668 --- [nio-8081-exec-8] o.s.i.e.SourcePollingChannelAdapter      : started 2o.org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean#0
Hibernate: select branch0_._id as _id1_0_, branch0_.branch_code as branch_c2_0_, branch0_.folder_path as folder_p3_0_, branch0_.ftp_port as ftp_port4_0_, branch0_.host as host5_0_, branch0_.password as password6_0_, branch0_.usern as usern7_0_ from branch branch0_
2018-12-20 08:03:00.225  INFO 6668 --- [ask-scheduler-8] o.s.integration.ftp.session.FtpSession   : File has been successfully transferred from: /ftp/erbranch/EDMS/FEFO/FEFOexportJNB.csv
2018-12-20 08:03:00.929  INFO 6668 --- [ask-scheduler-5] o.s.i.file.FileReadingMessageSource      : Created message: [GenericMessage [payload=BEY\finalBEY.csv, headers={file_originalFile=BEY\finalBEY.csv, id=6ed554eb-f553-0293-f042-d633155357c0, file_name=finalBEY.csv, file_relativePath=finalBEY.csv, timestamp=1545285780929}]]
2018-12-20 08:03:00.930  INFO 6668 --- [ask-scheduler-5] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=BEY\finalBEY.csv, headers={file_originalFile=BEY\finalBEY.csv, id=b2d76ac5-fb85-1313-a37e-8849714a545e, file_name=finalBEY.csv, file_relativePath=finalBEY.csv, timestamp=1545285780930}]
2018-12-20 08:03:01.958  INFO 6668 --- [ask-scheduler-5] o.s.integration.ftp.session.FtpSession   : File has been successfully transferred to: /ftp/erbranch/EDMS/FEFO/finalBEY.csv.writing
2018-12-20 08:03:02.373  INFO 6668 --- [ask-scheduler-5] o.s.integration.ftp.session.FtpSession   : File has been successfully renamed from: /ftp/erbranch/EDMS/FEFO/finalBEY.csv.writing to /ftp/erbranch/EDMS/FEFO/finalBEY.csv
2018-12-20 08:03:05.033  INFO 6668 --- [ask-scheduler-7] o.s.i.file.FileReadingMessageSource      : Created message: [GenericMessage [payload=JNB\finalJNB.csv, headers={file_originalFile=JNB\finalJNB.csv, id=4514e132-5684-9e82-28e7-f75c5c3dcf91, file_name=finalJNB.csv, file_relativePath=finalJNB.csv, timestamp=1545285785033}]]
2018-12-20 08:03:05.034  INFO 6668 --- [ask-scheduler-7] o.s.integration.handler.LoggingHandler   : GenericMessage [payload=JNB\finalJNB.csv, headers={file_originalFile=JNB\finalJNB.csv, id=59e62375-f1da-461d-ee61-d105ac3159a0, file_name=finalJNB.csv, file_relativePath=finalJNB.csv, timestamp=1545285785034}]
2018-12-20 08:03:07.530  INFO 6668 --- [ask-scheduler-7] o.s.integration.ftp.session.FtpSession   : File has been successfully transferred to: /ftp/erbranch/EDMS/FEFO/finalJNB.csv.writing
2018-12-20 08:03:08.539  INFO 6668 --- [ask-scheduler-7] o.s.integration.ftp.session.FtpSession   : File has been successfully renamed from: /ftp/erbranch/EDMS/FEFO/finalJNB.csv.writing to /ftp/erbranch/EDMS/FEFO/finalJNB.csv

A: .addFilter(new FileSystemPersistentAcceptOnceFileListFilter(new SimpleMetadataStore(), "foo"))),

The SimpleMetadataStore() is in-memory - using a new store for each flow means it starts empty each time - you need to use a shared metadata store across all the flows.
Also, if you need to prevent duplicates across server restarts, you need to use a persistent shared store, e.g. Redis, JDBC etc.


text:
Q: How to Prevent Reload of WebView Page [Android React Native] I have created app in which i have a 3 tabs to display webpages using  React Native. Every time i switch to tab 2 from tab 1, and then back to tab 1, the webview its still working and not reload, but when i switch to tab 3, the tab 1 and 2 is reloaded when i back to tab 1 or tab 2 from tab 3. So, i think its not working for 3 tabs with WebView?
Im using react-native-router-flux for make a tabbar.
<Scene key="root" tabs={true}>
    <Scene key="menus">
        <Scene key="tabbar" tabs={true} tabBarStyle={{backgroundColor:'#f7f7f7'}}>
            <Scene key="Schedule" component={Schedule} title="Schedule" icon={TabIcon} hideNavBar={true}/>
            <Scene key="Chatbox" component={Chatbox} title="Chatbox" icon={TabIcon} hideNavBar={true}/>
            <Scene key="Home" component={Home} title="Home" icon={TabIcon} hideNavBar={true}/>
            <Scene key="Podcast" component={Podcast} title="Podcast" icon={TabIcon} hideNavBar={true}/>
            <Scene key="About" component={About} title="About" icon={TabIcon} hideNavBar={true}/>
        </Scene>
    </Scene>
</Scene>

And this is the code for WebView from the 1 of 3 pages:
var sourceChatbox = {uri: 'URL_HERE'};
return(
     <Container>
         {this.renderHeader()}

         <Content contentContainerStyle={{flex: 1, margin: 10, marginBottom: 60}}>
             <WebView source={sourceChatbox}/>
         </Content>
     </Container>
);

Thanks for your help.

A: I've never used react-native-router-flux before and currently more people are using react-navigation more, maybe you should check that out


text:
Q: How prevalent is UTF-8 really? How wide-spread is the use of UTF-8 for non-English text, on the WWW or otherwise? I'm interested both in statistical data and the situation in specific countries.
I know that ISO-8859-1 (or 15) is firmly entrenched in Germany - but what about languages where you have to use multibyte encodings anyway, like Japan or China? I know that a few years ago, Japan was still using the various JIS encodings almost exclusively.
Given these observations, would it even be true that UTF-8 is the most common multibyte encoding? Or would it be more correct to say that it's basically only used internally in new applications that specifically target an international market and/or have to work with multi-language texts? Is it acceptable nowadays to have an app that ONLY uses UTF-8 in its output, or would each national market expect output files to be in a different legacy encoding in order to be usable by other apps.
Edit:
I am NOT asking whether or why UTF-8 is useful or how it works. I know all that. I am asking whether it is actually being adopted widely and replacing older encodings.

A: I don't think it's acceptable to just accept UTF-8 - you need to be accepting UTF-8 and whatever encoding was previously prevalent in your target markets.
The good news is, if you're coming from a German situation, where you mostly have 8859-1/15 and ASCII, additionally accepting 8859-1 and converting it into UTF-8 is basically zero-cost.  It's easy to detect: using 8859-1-encoded ö or ü is invalid UTF-8, for example, without even going into the easily-detectable invalid pairs.  Using characters 128-159 is unlikely to be valid 8859-1.  Within a few bytes of your first high byte, you can generally have a very, very good idea of which encoding is in use.  And once you know the encoding, whether by specification or guessing, you don't need a translation table to convert 8859-1 to Unicode - U+0080 through to U+00FF are exactly the same as the 0x80-0xFF in 8859-1.

A:
Is it acceptable nowadays to have an
  app that ONLY uses UTF-8 in its
  output, or would each national market
  expect output files to be in a
  different legacy encoding in order to
  be usable by other apps.

Hmm, depends on what kind of apps and output we're talking about... In many cases (e.g. most web-based stuff) you can certainly go with UTF-8 only, but, for example, in a desktop application that allows user to save some data in plain text files, I think UTF-8 only is not enough.
Mac OS X uses UTF-8 extensively, and it's the default encoding for users' files, and this is the case in most (all?) major Linux distributions too. But on Windows... is Windows-1252 (close but not same as ISO-8859-1) still the default encoding for many languages? At least in Windows XP it was, but I'm not sure if this has changed? In any case, so long as significant number of (mostly Windows) users have the files on their computers encoded in Windows-1252 (or something close to that), supporting UTF-8 only would cause grief and confusion for many.
Some country specific info: in Finland ISO-8859-1 (or 15) is likewise still firmly entrenched. As an example, Finnish IRC channels use, afaik, still mostly Latin-1. (Which means Linux guys with UTF-8 as system default using text-based clients (e.g. irssi) need to do some workarounds / tweak settings.)

A: I tend to visit Runet websites quite often. Many of them still use Windows-1251 encoding. Also it's the default encoding in Yandex Mail and Mail.ru (two largest webmail services in CIS countries). It's also set as a the default content encoding in Opera browser (2nd after Firefox by popularity in the region) when one downloads it from Russian ip address. I'm not quite sure about other browsers though.
The reason for that is quite simple: UTF-8 requires two bytes to encode Cyrillic letters. Non-unicode encodings require 1 byte only (unlike most Eastern alphabets Cyrillic ones are quite small). They are also fixed-length and easily processable by old ASCII-only tools.

A: Users of CJK characters are biassed against UTF-8 naturally because their characters become 3 bytes each instead of two. Evidently, in China the preference is for their own 2-byte GBK encoding, not UTF-16.
Edit in response to this comment by @Joshua :
And it turns out for most web work the pages would be smaller in UTF-8 anyway as the HTML and javascript characters now encode to one byte.
Response:
The GB.+ encodings and other East Asian encodings are variable length encodings. Bytes with values up to 0x7F are mapped mostly to ASCII (with sometimes minor variations). Some bytes with the high bit set are lead bytes of sequences of 2 to 4 bytes, and others are illegal. Just like UTF-8.
As "HTML and javascript characters" are also ASCII characters, they have ALWAYS been 1 byte, both in those encodings and in UTF-8.

A: Here are some statistics I was able to find:

*

*This page shows usage statistics for character encodings in "top websites".

*This page is another example.

Both of these pages seem to suffer from significant problems:

*

*It is not clear how representative their sample sets are, particularly for non English speaking countries.

*It is not clear what methodologies were used to gather the statistics.  Are they counting pages or counts of page accesses?  What about downloadable / downloaded content.

More important, the statistics are only for web-accessible content.  Broader statistics (e.g. for encoding of documents on user's hard drives) do not seem to be obtainable.  (This does not surprise me, given how difficult / costly it would be to do the studies needed across many countries.)
In short, your question is not objectively answerable.  You might be able to find studies somewhere about how "acceptable" a UTF-8 only application might be in specific countries, but I was not able to find any.
For me, the take away is that it is a good idea to write your applications to be character encoding agnostic, and let the user decide which character encoding to use for storing documents.  This is relatively easy to do in modern languages like Java and C#.

A: UTF-8 is popular because it is usually more compact than UTF-16, with full fidelity.  It also doesn't suffer from the endianness issue of UTF-16.
This makes it a great choice as an interchange format, but because characters encode to varying byte runs (from one to four bytes per character) it isn't always very nice to work with.  So it is usually cleaner to reserve UTF-8 for data interchange, and use conversion at the points of entry and exit.
For system-internal storage (including disk files and databases) it is probably cleaner to use a native UTF-16, UTF-16 with some other compression, or some 8-bit "ANSI" encoding.  The latter of course limits you to a particular codepage and you can suffer if you're handling multi-lingual text.  For processing the data locally you'll probably want some "ANSI" encoding or native UTF-16.  Character handling becomes a much simpler problem that way.
So I'd suggest that UTF-8 is popular externally, but rarer internally.  Internally UTF-8 seems like a nightmare to work with aside from static text blobs.
Some DBMSs seem to choose to store text blobs as UTF-8 all the time.  This offers the advantage of compression (over storing UTF-16) without trying to devise another compression scheme.  Because conversion to/from UTF-8 is so common they probably make use of system libraries that are known to work efficiently and reliably.
The biggest problems with "ANSI" schemes are being bound to a single small character set and needing to handle multibyte character set sequences for languages with large alphabets.

A: While it does not specifically address the question -- UTF-8 is the only character encoding mandatory to implement in all IETF track protocols.
http://www.ietf.org/rfc/rfc2277.txt

A: You might be interested in this question. I've been trying to build a CW about the support for unicode in various languages.

A:
I'm interested both in statistical
  data and the situation in specific
  countries.

On W3Techs, we have all these data, but it's perhaps not easy to find:
For example, you get the character encoding distribution of Japanese websites by first selecting the language: Content Languages > Japanese, and then you select Segmentation > Character Encodings. That brings you to this report: Distribution of character encodings among websites that use Japanese. You see: Japanese sites use 49% SHIFT-JIS and 38% UTF-8. You can do the same per top level domain, say all .jp sites.

A: We use UTF-8 in our service-oriented web-service world almost exclusively - even with "just" Western European languages, there are a enough "quirks" to using various ISO-8859-X formats to make our heads spin - UTF-8 really just totally solves that.
So I'd put in a BIG vote for use of UTF-8 everywhere and all the time ! :-) I guess in a service-oriented world and in .NET and Java environments, that's really not an issue or a potential problem anymore.
It just solves so many problems that you really don't need to have to deal with all the time......
Marc

A: As of 11 April 2021 UTF-8 is used on 96.7% of websites.

A: Both Java and C# use UTF-16 internally and can easily translate to other encodings; they're pretty well entrenched in the enterprise world.
I'd say accepting only UTF as input is not that big a deal these days; go for it.

A:
I'm interested both in statistical
  data and the situation in specific
  countries.

I think this is much more dependent on the problem domain and its history, then on the country  in which an application is used.
If you're building an application for which all your competitors are outputting in e.g. ISO-8859-1 (or have been for the majority of the last 10 years), I think all your (potential) clients would expect you to open such files without much hassle.
That said, I don't think most of the time there's still a need to output anything but UTF-8 encoded files. Most programs cope these days, but once again, YMMV depending on your target market.


text:
Q: Confusion With React Router I am trying to use the router object in child component but unable to do so. My main goal is to change the route after successful login. In react router v4 I can not use the history object directly.
My main goal is to use this.context.router so I cam make the route transition.
Here is my application code ( I stripped out most of them just added what I think is needed) If you need more information please comment.
Router
I have doubts about how I am adding components to route. But this is the only way I have found to use layout. So if you have any advice on this I will appreciate it.
<Router>
    <Switch>

        <Route path="/login" render={ () => ( <LayoutEmpty {...data} children={ <Login user={this.props.user} /> }  /> ) } />

        <Route exact path="/" render={ () => ( <LayoutApp {...data} children={ <Dashboard user={this.props.user} /> }  /> ) } />

        <Route path="*" component={LayoutNotFound} />

    </Switch>
</Router>

Now Lets just talk about the login component. Inside the component there is not context object passed.
I have added contextTypes like this
Login.contextTypes = {
  router: PropTypes.object
};

But that gives me only empty object as constant. Not route object is passed.
( let me know if you need code for login component but I think I have problem how I used <Route>)

A: I have ended up refactoring my code and passing the history object down to the Smart component (container) level.
My Refactored router looks like this
<Router>
    <Switch>

        <Route path="/login" component={Login} />

        <Route exact path="/" component={Dashboard} />

        <Route path="*" component={LayoutNotFound} />

    </Switch>
</Router>

After that I am importing my Layout component to containers ( Login, Dashboard ) and pass down history object as a props to those containers if they are requiring it.
Container (Smart component)
import React from 'react';
import LayoutApp from '../containers/LayoutApp'

    class Dashboard extends React.Component{
    ...
    render(){
            return (
            <LayoutApp history={this.props.history} title="Dashboard">
             ...


text:
Q: Why is fscanf reading 0? I am making a simple program that can read a file line by file. Each line of the file is in the format: integer, integer, character. For example, with a file that looks like:
1 2 A
2 3 B

The expected output from the program should be:
1 2 A
2 3 B

But it is printing
0 2 A
0 3 B

How can I fix it?
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stdint.h>
#include <time.h>

int main(int argc, char** argv) {

    char const* const fileName = argv[1];
    FILE* file = fopen(fileName, "r");

    char str[1];
    int key;
    int val;

    while (fscanf(file, "%d %d %s\n", &key, &val, str) != EOF) {

        printf("Read Integer %d \n", key );
        printf("Read Integer %d \n", val );
        printf("Read String %s \n", str );
    }

   fclose(file);

   return(0);
}

A: You declared str as char [1] which is wrong.
You need to allocate a larger str to accommodate '\0'. Changing declaration as below should fix the problem.
char str[2];  /* Or may be larger */
/*       ^    */

Also it would be a good idea to remove '\n' from format string of scanf as:
while (fscanf(file, "%d %d %s", &key, &val, str) == 3)
/*                           ^                   ^^^^  */

A: You need a bigger string, you need to check argc value and you need a better format for your fscanf(). Also better to check fscanf() return is 3.
#include <stdio.h>

#define N 500
#define XSTR(n) STR(n)
#define STR(n) #n

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        fprintf(stderr, "I need one argument.\n");
        return 1;
    }

    char const* const fileName = argv[1];
    FILE* file = fopen(fileName, "r");

    char str[N + 1];
    int key;
    int val;

    // "%d %d %" XSTR(N) "s" expands as "%d %d %500s"
    while (fscanf(file, "%d %d %" XSTR(N) "s", &key, &val, str) == 3)
    {

        printf("Read Integer %d \n", key );
        printf("Read Integer %d \n", val );
        printf("Read String %s \n", str );
    }

   fclose(file);

   return(0);
}

Edit: I added macros so that format is updated when changing N.


text:
Q: How can i insert other option inside an option tag I am trying to have a selection tag with some of this options in this order
House
   Bedroom
   Bathroom
   Kitchen
Technology
   Android
   Ios
but this doesnt seem to work
                   <select class="industry" required>
                        <option value="" disabled selected>industry</option>

                        <option value="">Home
                            <option value="">Bedroom</option>
                            <option value="">Bathroom</option>
                            <option value="">Kitchen</option>
                        </option>

                        <option value="">Technology
                            <option value="">Android</option>
                            <option value="">Ios</option>
                        </option>

                    </select>

is there a way to make it work?

A: You can use  optgroup for this

<select class="industry" required>

    <option value="" disabled selected>industry</option>

        <optgroup label="Home">
            <option value="">Bedroom</option>
            <option value="">Bathroom</option>
            <option value="">Kitchen</option>
        </optgroup>

        <optgroup label="Technology">
            <option value="">Android</option>
            <option value="">Ios</option>
        </optgroup>

</select>


text:
Q: PHP filtering an associative array based on a value found in a subarray I have an associative array with a subarray (data provided by our CRM in a JSON file.) The structure is like this:
$deals[0] = array(
    'stage_id' => '31',
    'title' => 'Deal Title 1',
    'creator_user_id' => array(
        'id' => 11409745,
        'name' => 'Salesperson A',
        'email' => 'a@email.com',
        'has_pic' => 0,
    ),
    'value' => 8990,
    'pipeline_id' => 2,
);

and so forth (3200+ records) and 10 or so salespeople.
I want to filter that array for only deals for Salesperson A, then Salesperson B, etc.  The solutions I've tried only return the subarray creator_user_id[]. Not all of the deal fields.
Any thoughts would be very much appreciated.


text:
Q: como puedo agregar un mensaje de confirmacion? Estoy desarrollando un login pero quiero agregarle mensajes a la app por ejemplo que cuando un usuario se registre le muestre un mensaje de que se ha registrado correctamente, he intentado mediante un viewbag pero no me funciono el mensaje, alguna sugerencia? he estado investigando pero no he logrado encontrar algun caso similar. Agradezco cualquier ayuda soy nuevo en esto y no tengo mucho conocimiento del tema. gracias
controlador:
    [HttpPost]
    public ActionResult Login(Usuario u, string ReturnUrl)
    {
        if (ModelState.IsValid)
        {
            string clave = u.Password;
            string encrip = Encriptar.Hash(clave);
            var user = db.Usuario.Where(x => x.Correo == u.Correo && x.Password == encrip).FirstOrDefault();
            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(u.Correo, false);
                Session["uname"] = (u.Nombre + u.Apellido1).ToString();
                if (ReturnUrl != null)
                {
                    return Redirect(ReturnUrl);
                }
                return Redirect("~/Home/Index");
            }
        }
        return View();

    }

vista:
            @using (Html.BeginForm())
            {
                @Html.AntiForgeryToken()
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    @Html.EditorFor(model => model.Correo, new { htmlAttributes = new { @class = "form-control", placeholder = "Digite su correo" } })
                    @Html.ValidationMessageFor(model => model.Correo, "", new { @class = "text-danger" })

                    @Html.PasswordFor(model => model.Password, new { @class = "form-control", placeholder = "Digite su contraseña" })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

                    <button type="submit" class="btn btn-primary btn-danger">login</button>

            }

A: Intenta utilizando TempData antes de redirigir a tu vista. en este temporal
almacenas el mensaje.
Ejemplo:
if (ReturnUrl != null)
                {
                    TempData["msg"] = "Operación correcta";
                    return Redirect(ReturnUrl);
                }
                return Redirect("~/Home/Index");

En tu vista agregas al inicio
@{
    TempData.Keep("msg");
}

y el acceso
TempData["msg"].ToString()


text:
Q: Perisistent in-memory database in Apache Spark I have a custom foreach writer for Spark streaming. For each row I write to JDBC source.  I also want to do somekind of fast lookup before I perform a JDBC operation and update the value after I perform JDBC operations, like "Step-1" and "Step-3" in below sample code ...
I don't want to use external databases like REDIS, MongoDB. I want something with low foot print like RocksDB, Derby, etc ...
I'm okay with storing one-file per application, just like checkpointing , I'll create a internal-db folder ...
I could not see any in-memory DB for Spark ..
def main(args: Array[String]): Unit = {

val brokers = "quickstart:9092"
val topic = "safe_message_landing_app_4"

val sparkSession = SparkSession.builder().master("local[*]").appName("Ganesh-Kafka-JDBC-Streaming").getOrCreate();

val sparkContext = sparkSession.sparkContext;
sparkContext.setLogLevel("ERROR")
val sqlContext = sparkSession.sqlContext;

val kafkaDataframe = sparkSession.readStream.format("kafka")
  .options(Map("kafka.bootstrap.servers" -> brokers, "subscribe" -> topic,
    "startingOffsets" -> "latest", "group.id" -> " Jai Ganesh", "checkpoint" -> "cp/kafka_reader"))
  .load()

kafkaDataframe.printSchema()
kafkaDataframe.createOrReplaceTempView("kafka_view")
val sqlDataframe = sqlContext.sql("select concat ( topic, '-' , partition, '-' , offset) as KEY, string(value) as VALUE from kafka_view")

val customForEachWriter = new ForeachWriter[Row] {
  override def open(partitionId: Long, version: Long) = {
    println("Open Started ==> partitionId ==> " + partitionId + " ==> version ==> " + version)
    true
  }

  override def process(value: Row) = {
    // Step 1 ==> Lookup a key in persistent KEY-VALUE store

    // JDBC operations

    // Step 3 ==> Update the value in persistent KEY-VALUE store
  }

  override def close(errorOrNull: Throwable) = {
    println(" ************** Closed ****************** ")
  }
}

val yy = sqlDataframe
  .writeStream
  .queryName("foreachquery")
  .foreach(customForEachWriter)
  .start()

yy.awaitTermination()

sparkSession.close();

}

A: Manjesh,
What you are looking for, "Spark and your in-memory DB as one seamless cluster, sharing a single process space", with support for MVCC is exactly what SnappyData provides. With SnappyData, the tables that you want to do a fast lookup on are in the same process that is running your Spark streaming job. Check it out here
SnappyData has a Apache V2 license for the core product and the specific use that you are referring to is available in the OSS download.
(Disclosure: I am a SnappyData employee and it makes sense to provide a product specific answer to this question because the product is the answer to the question)


text:
Q: Balloon rubbing; where do the electrons go? If you rubbed a balloon with a towel, where would the electrons go: the balloon or the towel? Why?
I'm guessing the electrons would go to the object with a larger mass, but it's just a guess. :)

A: This article on triboelectricity gives a triboelectric  series, listing materials according to whether they will expel electrons or acquire them , when rubbed or in contact.
Towel is not in there :) but cotton is, with 0 but it is more positive than rubber. So the answer is that the electrons will move to the balloon, if you manage to get cotton to give up its electrons :) . Did you do the experiment? A woolen towel would be much better. Maybe it was your hand that gave up the electrons after all.
This is what wikipedia has to say on the causes:

After coming into contact, a chemical
bond is formed between some parts of
the two surfaces, called adhesion, and
charges move from one material to the
other to equalize their
electrochemical potential. This is
what creates the net charge imbalance
between the objects. When separated,
some of the bonded atoms have a
tendency to keep extra electrons, and
some a tendency to give them away,
though the imbalance will be partially
destroyed by tunneling or electrical
breakdown (usually corona discharge).
In addition, some materials may
exchange ions of differing mobility,
or exchange charged fragments of
larger molecules.

Hence the need of a table.


text:
Q: Big O - Nested loops void bar(int N){
  int c=0;
  for (int i=0; i<N*N; i++)
    for (int j= i; j< N; j++)
      c++;
}

The outer (and inner) loops above never get past N. Would this mean the Big O is N*N (N for the outer and N/2 for the inner)?

A: If you do this
for (int i = 0; i < N; i++)
  for (int j = i; j < N; j++)
    …

you will iterate N times in the inner loop first, then N-1, then N-2, etc., which sums to N(N-1)/2. This loop runs in O(N²), that is the square of the outer loop.
In your case, your code is equivalent to
for (int i = 0; i < N; i++)
  for (int j = i; j < N; j++)
    c++;

since for every positive integer we have N² ≥ N and the compiler should be clever enough to notice that it makes no sense to continue running the outer loop if i is greater than N. So the complexity is indeed O(N²).
If you print N and c after your program runs, you will notice that when N gets doubled, c is almost multiplied by 4 (2²):
N = 1, c = 1
N = 2, c = 3
N = 4, c = 10
N = 8, c = 36
N = 16, c = 136
N = 32, c = 528
N = 64, c = 2080
N = 128, c = 8256
N = 256, c = 32896
N = 512, c = 131328
N = 1024, c = 524800
N = 2048, c = 2098176

A: To know formally the number of iterations and the order of growth:


text:
Q: Let experienced users silently edit their posts
Possible Duplicate:
Is there a way to edit a question without bumping it to the front page?

How feasible and desirable would it be to allow users with some minimal rep—say, 2K?  5K?—to edit their own posts without bumping them?
Often times after reading and responding to a comment on an hour-old answer I'll, being an anal retentive person, re-read my post and correct some defective some grammar or punctuation.  Before clicking the save button I sometimes get a queasy feeling that the eyes of the internet are upon me, judging me as a dirty little rep whore for bumping an old post to get some new eyes on it.
How much sense would it make to put in a little check box allowing you to make the edit "silently"—without bumping?
I know there are some odd edge cases where users can potentially write inappropriate things in their own stale posts and then save them without anyone seeing, but surely requiring at least 2K rep would ameliorate that?

A:
surely requiring at least 2K rep would ameliorate that?

Oh, how I wish that was true...
Here's a scenario I've seen entirely too often: someone says something mean to Ye Olde User, YOU decides that any site on which he might be criticized without due respect isn't the site for him OR HIS AWESOME POSTS, and embarks on a campaign to "remove" them by editing out the text and replacing it with something unhelpful ("screw you guys, I'm going home").
This usually gets caught sooner or later, someone notifies a moderator, the user gets suspended to cool down a bit, and his edits get rolled back. Everyone feels sad and dirty. Life goes on, minus the time wasted by insta-drama-queen...
Disabling bumping means making this harder to detect. Making it harder to detect means more posts vandalized. More vandalized posts, more wasted time cleaning up.


text:
Q: Has anyone already written JavaScript versions of Zend Validators? I've built my Zend Forms to push validation params to the client for JS validation. I'm not excited about having to re-write many of Zend's Validators in JS however. I don't want to reinvent the wheel if it's not necessary.
Has anyone found or written a jQuery-based set of validators that reproduce the Zend Validators' functionality for client-side validation?

A: As mentioned by @AurelioDeRosa in the comment you can use an ajax-call of your current form to validate the fields. The video-cast goes into field-by-field validation, however you can easily adjust the code to validate on submit only or on-whatever you need.
Listen to it, it has great advice - read comments, too http://www.zendcasts.com/ajaxify-your-zend_form-validation-with-jquery/2010/04/