text:
Q: Best Layout Manager For Accomplishing This Task
I have (2) JTextAreas (input text & output text)
(2) JComboBoxes ( AutoDetect & TranslateTo)
Please see photo attached to see what the objective is.
I am trying to obtain this layout with a certain layout manager I have tried FlowLayout, SpringLayout and have not achieved desirable results with these. Here is my code
public class translate extends JFrame implements ActionListener{
/*
    Our Langauges of choice we can add more if desired in the future
    */

    String[] nativeString = { "Auto-Detect"};
    String[] translateString = { "Español", "中文", "Francais", "Italiano", "Deutsche" , "English" };
     JComboBox nativeLanguage;
     JComboBox translateTo;
     JButton execute;
      final JPanel topRight;
      final JPanel topLeft;
      final JPanel bottomLeft;
      JPanel bottomRight;
      JLabel tR;
       JLabel tL;
      JLabel bR;
       JLabel bL;

      JRadioButton local;
      JRadioButton mainArea;
      JTextArea input;
      JTextArea output;

    public translate() throws Exception{

      super("Translation Service");
      JOptionPane.showMessageDialog(null, "Translation Services Require A NetWork Function To Make Calls");
      Translate.setClientId("xxxxxxxxx");
      Translate.setClientSecret("Xxxxxxxxxxxx);
      setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      setSize(700,400);
      setLocationRelativeTo(null);
      setResizable(true);
      setLookAndFeel();
      SpringLayout spring = new SpringLayout();
      setLayout(spring);

       input= new JTextArea();
      JScrollPane inScroll = new JScrollPane();
      input.add(inScroll);
     input.setEditable(true);
     input.setLineWrap(true);

     execute = new JButton("Translate");
    execute.addActionListener(this);
     output = new JTextArea();
     JScrollPane outScroll = new JScrollPane();
     output.add(outScroll);
      output.setEditable(true);
     output.setLineWrap(true);
     output.setVisible(true);
      /*
      Our JComboBoxes for user to selct langauge they want to choose
      */
      nativeLanguage = new JComboBox(nativeString);
      translateTo = new JComboBox(translateString);

      nativeLanguage.addActionListener(this);
      translateTo.addActionListener(this);
      // JLabels

      tR = new JLabel("Auto-Detect");
      tL = new JLabel ("Target Langauge");
      // FlowLayout fl = new FlowLayout();
      SpringLayout sp = new SpringLayout();
      setLayout(sp);
      // setLayout(fl);
      //1
       topRight = new JPanel();
      // topRight.setLayout(new BoxLayout(topRight, BoxLayout.PAGE_AXIS));
       topRight.add(nativeLanguage);
       topRight.add(tR);

       //2
       topLeft = new JPanel();
      // topLeft.setLayout(new BoxLayout(topLeft, BoxLayout.PAGE_AXIS));
       topLeft.add(translateTo);
       topLeft.add(tL);

       //3

      bottomRight = new JPanel();
     // bottomRight.setLayout(new BoxLayout(bottomRight, BoxLayout.PAGE_AXIS));
      bottomRight.add(input);

       //4
      bottomLeft = new JPanel();
    //  bottomLeft.setLayout(new BoxLayout(bottomLeft, BoxLayout.LINE_AXIS));
     bottomLeft.add(output);

     add(topRight, SpringLayout.NORTH);
     add(topLeft, SpringLayout.NORTH);
     add(bottomRight, SpringLayout.SOUTH);
     add(bottomLeft, SpringLayout.SOUTH);

   setVisible(true);

    }

A: I think the GridLayout works for you. If you want even more flexibility you can also use the GridBagLayout. Here is a link to all Layout Managers and linked examples.
But do you really want to do this with swing? It seems that you are at the beginning with the GUI-part of your project, so maybe you should think about using javafx instead of swing.

A: 70% complete everything is in its place per say: (imports left out)
public class translate extends JFrame implements ActionListener{
/*
    Our Langauges of choice we can add more if desired in the future
    */
    DaWord mainArea = new DaWord();
    JMenuBar mainBar;
    JMenu menu;
    JMenuItem main,saveAs;

    String[] nativeString = { "Auto-Detect"};
    String[] translateString = { "Español", "中文", "Francais", "Italiano", "Deutsche" , "English" };
     JComboBox nativeLanguage;
     JComboBox translateTo;
     JButton execute;
      final JPanel topRight;
      final JPanel topLeft;
      final JPanel bottomLeft;
      JPanel bottomRight;
      JLabel tR;
       JLabel tL;
      JLabel bR;
       JLabel bL;
      JScrollPane scroll1;
      JScrollPane scroll2;

      JRadioButton local;
      JRadioButton mainAreas;
      JTextArea input;
      JTextArea output;

    public translate() throws Exception{

      super("Translation Service");
      JOptionPane.showMessageDialog(null, "Translation Services Require A NetWork Function To Make Calls");
      Translate.setClientId("MYID");
      Translate.setClientSecret("shhItsASecret");
      setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      setSize(900,450);
      setLocationRelativeTo(null);
      setResizable(true);
      setLookAndFeel();
      SpringLayout spring = new SpringLayout();
      setLayout(spring);
  javax.swing.border.Border blackline = BorderFactory.createLineBorder(Color.black);
  setBackground(new Color(128, 218, 235));
      TitledBorder title1 = BorderFactory.createTitledBorder(blackline, "Input Text");
      mainBar = new JMenuBar();
      menu = new JMenu("Options");

      main = new JMenuItem("Export To Main");
      saveAs = new JMenuItem("Save As");
      menu.add(main);
      menu.add(saveAs);
      mainBar.add(menu);
     // add(mainBar);

     input= new JTextArea(35,35);
    scroll1 = new JScrollPane(input);
    //  scroll1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scroll1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        //add("Center", scroll1);
     input.setEditable(true);
     input.setLineWrap(true);
  execute = new JButton("Translate");
    execute.addActionListener(this);

    TitledBorder title2 = BorderFactory.createTitledBorder(blackline, "Output Text");
     output = new JTextArea(35,35);
     scroll2 = new JScrollPane(output);
      // scroll2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
     scroll2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

     output.setEditable(true);
     output.setLineWrap(true);
     output.setVisible(true);
      /*
      Our JComboBoxes for user to selct langauge they want to choose
      */
      nativeLanguage = new JComboBox(nativeString);
      translateTo = new JComboBox(translateString);

      nativeLanguage.addActionListener(this);
      translateTo.addActionListener(this);
      // JLabels

      tR = new JLabel("Auto-Detect");
      tL = new JLabel ("Target Langauge");
      //  0,2 (2) rows across
     GridLayout flo = new GridLayout(0,2);
     setLayout(flo);
      // setLayout(fl);
      //1
       topRight = new JPanel();
      // topRight.setLayout(new BoxLayout(topRight, BoxLayout.PAGE_AXIS));
       topRight.add(nativeLanguage);
       topRight.add(tR);

       //2
       topLeft = new JPanel();
      // topLeft.setLayout(new BoxLayout(topLeft, BoxLayout.PAGE_AXIS));
       topLeft.add(translateTo);
       topLeft.add(tL);

       //3

      bottomRight = new JPanel();
     // bottomRight.setLayout(new BoxLayout(bottomRight, BoxLayout.PAGE_AXIS));
      bottomRight.add(input);

       //4
      bottomLeft = new JPanel();
    //  bottomLeft.setLayout(new BoxLayout(bottomLeft, BoxLayout.LINE_AXIS));
     bottomLeft.add(output);

     setJMenuBar(mainBar);
     add(topRight);
     add(topLeft);
     add(bottomRight);
     bottomRight.setBorder(title1);
     add(bottomLeft);
     bottomLeft.setBorder(title2);

   setVisible(true);

  saveAs.addActionListener(new java.awt.event.ActionListener(){
 public void actionPerformed(java.awt.event.ActionEvent evt){
        try {
            saveAsActionPerformed(evt);
        } catch (Exception ex) {
            Logger.getLogger(DaWord.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void saveAsActionPerformed(ActionEvent evt) throws Exception{
        Object trans = evt.getSource();
        if(trans==saveAs){
          save();
        }
    }
    private void save() throws FileNotFoundException {

       JFileChooser js2 = new JFileChooser();
       js2.setDialogTitle("Save As");
       js2.setCurrentDirectory(new File ("./"));
       int result = js2.showSaveDialog(null);
       if (result == JFileChooser.APPROVE_OPTION){
       String in1 = "This Is My Original Text:\n\n\n";
       String in2 = "This Is My Translated Text:\n\n\n";
       String content1 = input.getText();
       String content2 = output.getText();
       // all put in one
       String completa = in1+content1+in2+content2;
       File nef = js2.getSelectedFile();
       PrintWriter fw = new PrintWriter(nef.getPath());
       fw.write(completa);
       fw.flush();

       }
          }

});
  main.addActionListener(new java.awt.event.ActionListener(){
  public void actionPerformed(java.awt.event.ActionEvent evt){
        try {
            mainActionPerformed(evt);
        } catch (Exception ex) {
            Logger.getLogger(DaWord.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void mainActionPerformed(ActionEvent evt) throws Exception{
        Object mainS = evt.getSource();
        if(mainS==main){
          transfer();
        }
    }

          private void transfer() {
           String original = input.getText();
            String trans = output.getText();

            String intro1 = "This Is Your Original Text Below:\n\n\n";
            String intro2 = "This Is Your Translated Text Below:\n\n\n";

            mainArea.userField.append(intro1+original);
            mainArea.userField.append(intro2+trans);

          }

});

    }

  @Override
    public void actionPerformed(ActionEvent e) {

    Object source = e.getSource();
    /*
       JComboBox translateTo = (JComboBox)e.getSource();
    String box1 = (String) translateTo.getSelectedItem();

    */

   JComboBox nativeLanguage = (JComboBox) e.getSource();
   String newSelection = (String) translateTo.getSelectedItem();

   if (newSelection =="Español"){

        try {
            eng2spanish();
        } catch (Exception ex) {
            Logger.getLogger(translate.class.getName()).log(Level.SEVERE, null, ex);
        }
}else if(newSelection=="Italiano"){
        try {
            eng2ital();
        } catch (Exception ex) {
            Logger.getLogger(translate.class.getName()).log(Level.SEVERE, null, ex);
        }
}else if(newSelection=="Francais"){
        try {
            eng2french();
        } catch (Exception ex) {
            Logger.getLogger(translate.class.getName()).log(Level.SEVERE, null, ex);
        }
}else if(newSelection=="中文"){
        try {
            eng2chin();
        } catch (Exception ex) {
            Logger.getLogger(translate.class.getName()).log(Level.SEVERE, null, ex);
        }
}else if(newSelection=="Duetche"){
        try {
            eng2ger();
        } catch (Exception ex) {
            Logger.getLogger(translate.class.getName()).log(Level.SEVERE, null, ex);
        }

}else if(newSelection =="English"){
        try {
            eng2eng();
        } catch (Exception ex) {
            Logger.getLogger(translate.class.getName()).log(Level.SEVERE, null, ex);
        }
   }

    }

private void setLookAndFeel() {
try{
UIManager.setLookAndFeel("UIManager.getSystemLookAndFeelClassName");
}catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
UnsupportedLookAndFeelException e){
}
}

      private void eng2spanish() throws Exception {

String userIn = input.getText();
 String spanishTranslation = Translate.execute(userIn, Language.SPANISH);
output.setText(spanishTranslation);
System.out.println(spanishTranslation);

    }

    private void eng2french() throws Exception {

String userIn = input.getText();
 String frenchTranslation = Translate.execute(userIn, Language.FRENCH);
output.setText(frenchTranslation);

    }

    private void eng2chin() throws Exception {

String userIn = input.getText();
 String chinTranslation = Translate.execute(userIn, Language.CHINESE_TRADITIONAL);
output.setText(chinTranslation);

    }

    private void eng2ger() throws Exception {

String userIn = input.getText();
 String germanTranslation = Translate.execute(userIn, Language.GERMAN);
output.setText(germanTranslation);

    }

    private void eng2ital() throws Exception {

String userIn = input.getText();
 String italianTranslation = Translate.execute(userIn, Language.ITALIAN);
output.setText(italianTranslation);

    }
        private void eng2ind() throws Exception {

String userIn = input.getText();
 String hindiTranslation = Translate.execute(userIn, Language.HINDI);
output.setText(hindiTranslation);

    }

    private void eng2eng() throws Exception {

String userIn = input.getText();
 String engTranslation = Translate.execute(userIn, Language.ENGLISH);
output.setText(engTranslation);
    }
}


text:
Q: Why does Docker run so many processes to map ports though to my application? I have an application that runs in a container that requires a range of ports to be mapped to it.
docker run -p 2000-3000:2000-3000 myapp

When I run this docker command my development vm grinds to a halt.
Then looking at the processes, there is a docker-proxy running for every port
$ ps -ef
...
root     19796  7835  0 03:31 ?        00:00:00 docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 4000 -container-ip 172.17.0.4 -container-port 3000
root     19804  7835  0 03:31 ?        00:00:00 docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 3999 -container-ip 172.17.0.4 -container-port 2999
root     19812  7835  0 03:31 ?        00:00:00 docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 3998 -container-ip 172.17.0.4 -container-port 2998
...

$ ps -ef | grep -c docker-proxy
1003

They are all children of the docker daemon
root@default-docker:~# pstree -p
init(1)-+-VBoxService(1251)
        |-acpid(1277)
        |-crond(1235)
        |-docker(7835)-+-docker-containe(7841)-+-docker-containe(8031)---gitlab-ci-multi(8048)
        |              |                       |-docker-containe(9678)---mysqld(9693)
        |              |                       `-docker-containe(20577)---registry(20591)
        |              |-exe(19796)
        |              |-exe(19804)
        |              |-exe(19812)

Each process uses a chunk of private memory (Pss in /proc/$pid/smaps)
$ for pid in $(pgrep exe); do printf "pid:%5s mem:%5s\n" $pid $(awk '/^Pss:/{t=t+$2}END{print t}' /proc/$pid/smaps); done
...
pid:28534 mem: 4011
pid:28543 mem: 3817
pid:28552 mem: 4001

There are also DNAT rules in place for each port, which is how I would have expected this to be done on a Linux host with private networks.
root@default-docker:~# iptables -t nat -vnL DOCKER
Chain DOCKER (2 references)
 pkts bytes target     prot opt in     out     source               destination
...
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:4000 to:172.17.0.4:3000
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:3999 to:172.17.0.4:2999
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:3998 to:172.17.0.4:2998
...

Why is Docker launching a process per port?
Why does each process need 4-6MB of memory?
Why is Docker using a user space process at all?

A: Why is Docker using a user space process at all?
Nigel Brown has written a detailed article on The docker-proxy which explains the how and why.

The docker-proxy, then, is a 'catch all' method for allowing container
  port forwarding to the Docker host. However, it's generally considered
  that the docker-proxy is an inelegant solution to the problems
  highlighted above, and when a large range of container ports are
  exposed, it consumes considerable memory. An attempt was previously
  made to remove the dependency for the docker-proxy, but this fell foul
  of the limitations of the aged kernel in RHEL 6.x and CentOS 6.x,
  which the Docker project feels duty bound to support. Hence, the
  docker-proxy remains a major constituent part of the Docker experience
  in all Docker versions up to the current version 1.5. As I write,
  version 1.6 is due for imminent release, and there have been moves to
  remove the automatic requirement for the docker-proxy, which I'll
  cover in another article.

Docker now includes a daemon run time option to disable the userland proxy with --userland-proxy=false. This was introduced in v1.7.
There seems to be a few edge case bugs that exist when disabling the userland proxy. There are also IPV6 issues
There is an open GitHub issue for disabling the userland proxy by default (RHEL6 is no longer supported by Docker).
Why is Docker launching a process per port?
There doesn't appear to be a reason for this other than it was implemented this way. A single process should be capable of handling all of the port mappings for a container
Why does each process need 4-6MB of memory?
The proxy implementation and package looks clean and uses in built Go functionality so this might just be Go's initial garbage collection limits that allow it to grow to ~ 5MB.
EDIT: Memory usage has been improved in Docker 1.12. There is still a process per port but each process now only uses ~ 750k of private memory space.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unity Not accepting TCP connection, possibly refusing connection I've been stuck with this for too long.
My script isn't allowing any TCP connections to come through from my device that is emitting them. I have tested my emitting device with Socket Test and they do work and transmit as I need. However, Unity is not accepting my signal and I don't know why.
Could someone please look over my script and see if they can work out the reason why? I've omitted  most of the debug lines.
   public class TCP : MonoBehaviour
{
    string ip_address  = "192.168.0.87";
    int port = 54321;
    public GameObject GText;

    Thread listen_thread;
    TcpListener tcp_listener;
    Thread clientThread;

    volatile bool should_stop;

    public void CloseSocket(TcpListener Client)
    {
        //Client.Close();

    }

    public void Start()
    {
    IPAddress ip_addy = IPAddress.Parse(ip_address);

    tcp_listener = new TcpListener(ip_addy, 22);
    tcp_listener.Start();

    StartAccept();

    }
    private void StartAccept()
    {
    tcp_listener.BeginAcceptTcpClient(HandleAsyncConnection, tcp_listener);
    GText.GetComponent<GUIText>().text =("Listening Again");
        Debug.Log("listeneing again");
    }
    private void HandleAsyncConnection(IAsyncResult res)
    {
            Debug.Log("handle async");
     byte[] bytes = new byte[1024];
     string data;

    StartAccept(); //listen for new connections again
    TcpClient client = tcp_listener.EndAcceptTcpClient(res);
    NetworkStream stream = client.GetStream();
    //proceed

    int i;

    // Loop to receive all the data sent by the client.
    i = stream.Read(bytes, 0, bytes.Length);

                while (i != 0)
                {
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

                    // Process the data sent by the client.
                    data = data.ToUpper();

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                    // Send back a response.
                    stream.Write(msg, 0, msg.Length);

                    i = stream.Read(bytes, 0, bytes.Length);

                }
    GText.GetComponent<GUIText>().text =("Second Operation");
    //CloseSocket(tcp_listener);

    }
        void RequestStop()
    {
        should_stop = true;
    }
    // Use this for initialization
    /**
    void Start ()
    {
        try{
        IPAddress ip_addy = IPAddress.Parse(ip_address);
        tcp_listener = new TcpListener(ip_addy, port);
        listen_thread = new Thread(new ThreadStart(ListenForClients));
        listen_thread.Start();

        }
        catch(Exception e)
        {
            GText.GetComponent<GUIText>().text =(e.ToString());
        }

    }

    private void ListenForClients()
    {
        this.tcp_listener.Start();

        while(true)
        {
            //blocks until a client has connected to the server
            TcpClient client = this.tcp_listener.AcceptTcpClient();

            this.tcp_listener.Stop();

            client.Close();

        }

        this.tcp_listener.Stop();

    }

    */
    private void HandleClientComm(object client)
    {
        TcpClient tcp_client = (TcpClient)client;
        NetworkStream client_stream = tcp_client.GetStream();

        byte[] message = new byte[4096];
        int bytes_read;

        while(true)
        {
            bytes_read = 0;

            try
            {
                //blocks until a client sends a message
                bytes_read = client_stream.Read(message, 0, 4096);

            }
            catch (Exception e)
            {
              //a socket error has occured
              GText.GetComponent<GUIText>().text =(e.Message);
                    Debug.Log(e.Message);
              break;
            }

            if(bytes_read == 0)
            {
                //client has disconnected
                break;
            }

            ASCIIEncoding encoder = new ASCIIEncoding();
        }
        try
        {
            clientThread.Abort();
        }
        catch(Exception e)
        {
            GText.GetComponent<GUIText>().text =(e.Message);
            Debug.Log(e.Message);
        }
    }

Ive tried connecting to my unity app with socket test as well and I get an error saying the connection was refused. Can anyone see where in this code that happening?


text:
Q: How to configure app.config for TFS CI Test environment I have some integration tests that need to connect to a DB. In app.config I have a connection string which points to server '.' The tests run fine when I run them within VS on my workstation, as I have a SQL server instance also running locally.
We have a CI build & test set up to run on TFS, but in this environment the DB is not on the same machine, so the connectionstring in app.config is wrong and the tests fail to connect.
How can I configure a TFS CI build to update the app.config to point to a different DB? Or, is there a different way I should be solving this problem?

A: You can use XML transformation to modify the app.config when you build the application through the TFS build (meaning that you'll have two solution configurations: one for local build with VS and the second for the TFS build) or you can use a pre-build script on build that'll modify the app.config connection string.

A: You would be best moving integration tests out to a test environment. It's best if build are quick and don't need an instance of your application.
If you do a build and unit test you can have an automated release kick off in Release Management for Visual Studio which can be configured to also run integration and UI tests.
http://nakedalm.com/create-release-management-pipeline-professional-developers/
The release tool takes care of seeing connection strings and whatnot.

A: To solved this I choose the XML transformation route using the VS plug-in slowcheetah (idea taken here)
With this tool you create build configuration for each of your environments (ex: dev, QA, PP) and generate the XML transform of the app.config.
Replace the required section Example:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <SqlUnitTesting xdt:Transform="Replace">
    <DataGeneration ClearDatabase="true" />
    <ExecutionContext Provider="System.Data.SqlClient" ConnectionString="Data Source=sqspsqlxx;Initial Catalog=IC_RMI_Result;Integrated Security=True;Pooling=False;MultipleActiveResultSets=False"
        CommandTimeout="30" />
    <PrivilegedContext Provider="System.Data.SqlClient" ConnectionString="Data Source=sqpsqlxx;Initial Catalog=IC_RMI_Result;Integrated Security=True;Pooling=False;MultipleActiveResultSets=False"
        CommandTimeout="30" />
  </SqlUnitTesting>

For TFS integration there is probably a way to use the out of box nuget restore but I simply added the package to source control.
At teamp build queue (or harcode in your build deinition) simply specify the build configuration you want to target (dev, qa, PP).
(note: my team build agent uses windows crendentials so I made sure the account has the required rights on the target DBs)


text:
Q: Why can't file columns have a third dimension? I am writing code that handles large amounts of data each second.
I was going to use this method: essentially every time-period, usually around 30 seconds, around 3,000 files create a new column in a .csv file containing 3 entries. Is there anyway to condense this into one file with a "third dimension" for each file.
An example of one file with the program running for 3 time periods
I'm imagining the data being 3D as that is the best way to describe it. Any help or questions are welcome.


text:
Q: How to dynamically call overloaded methods inside .handle() with two arguments in spring integration? I want to make my spring integration flow generic for different type of requests that is coming through gateway and I want to have overloaded methods and want to call specific overloaded method for specific messaged that is coming though gateway.
flow.handle(validatorService, "validateRequest")

Something like the above code, where inside validatorService I have several overloaded methods to cater different requests that are coming to this flow. But what if along with the payload I want to send another argument to a method. Then how do I do that.
@Configuration
        public class IntegrationConfiguration {
          @Autowired LionsServiceImpl lionsService;

          long dbId = new SequenceGenerator().nextId();
      //   Main flow
      @Bean
  public IntegrationFlow flow() {
    return flow ->
        flow.handle(validatorService, "validateRequest")
            .split()
            .channel(c -> c.executor(Executors.newCachedThreadPool()))
            .scatterGather(
                scatterer ->
                    scatterer
                        .applySequence(true)
                        .recipientFlow(flow1())
                        .recipientFlow(flow2())
                        .recipientFlow(flow3()),
                gatherer ->
                    gatherer
                        .releaseLockBeforeSend(true)
                        .releaseStrategy(group -> group.size() == 2))
            .aggregate(prepareSomeRequest())
            .to(getDec());
  }

//gateway
 @Gateway(requestChannel = "flow.input")
  void processLionRequest(
      @Payload Message lionRequest, @Header("sourceSystem") SourceSystem sourceSystem);

So if u see in  flow.handle(validatorService, "validateRequest") we have a validatorService class which accepts LionRequest, CatRequest and dynamically calls the overloaded method.
Same way I have overloaded method which accepts 2 argument, one is either LionRequest or CatRequest and another value from header or from some variable.
My overloaded methods looks like below -
public LionRequest save(LionRequest lionreq, String dbID){}

public CatRequest save(CatRequest catReq, String dbID){}..

So that to the gateway I can pass LionRequest or CatRequest and I just have to call save method from a class and dynamically LionRequest/CatRequest overloaded method should be called.
Kindly suggest. One example code would help

A: We need to understand what is that "another argument", but if you talk just about a Message context, than it is possible like this:
Foo validateRequest(Foo payload, @Header("fooHeader") String fooHeader)

Bar validateRequest(Bar payload, @Header("barHeader") String barHeader)

See more info in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/configuration.html#annotations
The reference from the handle() in the flow definition is exactly as you have it now in the question.


text:
Q: Past tenses in sequence: former and latter past events I have a question about past tenses in sequence.
I studied that while describing connected past events in sequence:

*

*event 1: former event is in past-perfect

*event 2: latter event is in past-tense

For e.g. 1,

When I reached the platform, the train had already left.

Now, please consider this sentence: (e.g. 2)

Well, I couldn't find my classroom, so I got to the classroom a bit late and then I had to sing a song in front of the other students! source

In the above sentence, event 1 (reached classroom) is in past-tense and event 2 (sang a song) is in past-perfect tense.
Is the sequence of tenses wrong in this sentence? (Firstly, I reached my classroom and then I sang a song.)
Please help me understand.

A:
I had to sing a song in front of the other students!

It isn't in the past perfect tense, it's also the past simple.
You use have to (here, had to) to say that something is required or necessary (here, your performance in front of the other students was demanded).

I needed to sing a song in front of the other students!
I was forced to sing a song in front of the other students!

In your sentence, both events are mentioned in the past simple. The tense sets the order in which those events happened.

I got to the classroom a bit late [event 1] and then I had to sing a song in front of the other students [event 2]!

A: The order that verb phrases occur in a sentence is of only minor value in determining the order in which the events they described occurred.
In your first example, the main clause is "the train had already left". That is in the past perfect, or past-in-the-past, meaning it happened earlier than the overall time of the sentence. The prepositional phrase "when I reached the platform" indicates the overall time of the sentence - the point in time at which the speaker reached the platform. In addition, the adverb already indicates that the action of the principal verb was already complete at the time of the prepositional phrase. The sequence of the events is extremely clear - the one mentioned first occurred second.
However, you could swap the two over and the order of events would be exactly the same, as it is the grammar and the adverb that indicate the order:

The train had already left when I arrived at the platform.

The adverb already is redundant, and used for clarity or emphasis. You get the same overall meaning with:

The train had left when I arrived at the platform.

However, you can also get the same order of events with different grammar - though some might be non-standard, it is natural in my experience as a native speaker:

When I arrived at the platform, the train already left.

The order of events is clarified by the adverb. However, things become different if you don't have that adverb:

When I arrived at the platform, the train left.

That would mean the train left at the point of arrival on the platform, thanks to the preposition when.

I arrived at the platform, the train left.

With the lack of preposition, these become grammatically independent clauses, and have more or less the same meaning as having them as two sentences:

I arrived at the platform. The train left.

This does not grammatically tell us the order of events, but the very fact someone would say that might tend to make people think that the person had been unable to board the train, so it left either before or soon after their arrival at the platform. The fact they are said in that order would, in my experience, tend to make people think that the train left while they were on the platform. That could be made clearer by using a preposition to indicate the order of events:

I arrived at the platform, then the train left.

The train left after the person arrived at the platform, but most likely before they could get on it - otherwise they wouldn't be saying it like that.
Your second example has both verbs in the past simple, but the order is likewise indicated with then.

Well, I couldn't find my classroom, so I got to the classroom a bit late and then I had to sing a song in front of the other students!

The first clause sets a condition, why the rest of it happened, indicated by so. The second says they got to the classroom late, and the third says they were made to sing a song - had having its sense of compulsion, rather than acting as an auxiliary indicating the past perfect. The order of events would be clear without the then because the sentence makes more sense that way, but the then clarifies that it happened after getting to the classroom late.
The order of the clauses can be a sort of tie-breaker in determining the order in which the events described occurred, but grammar, adverbs and prepositions are the sure ways to do so.

A: sequence of tenses in Example 1, which is a very simple example of the use of the past perfect:

*

*When I reached the platform, the train had already left.

reached=simple past, had left = past perfect
The reason for this: the train leaves the platform in the past before the person reaches the platform.
On the imaginary timeline of tenses: the "had left" occurs at a point in time earlier than the point in time of "I reached the platform".
timelines of tenses with examples
Example 2:
- Well, I couldn't find my classroom, so I got to the classroom a bit late and then I had to sing a song in front of the other students! source
There is no past perfect there: there are three past tenses: could, got and had


text:
Q: How to avoid overfitting in TensorFlow machine learning model for stock price predictions? How do I avoid my machine learning model from producing a straight-line prediction and overfitting by using stock prices from the training data to predict stock prices on the test data? For instance, when assessing the model on Apple's stock (AAPL), which has a price of $150, the model might predict a value close to the training stock, such as Microsoft (MSFT) which has a price of $249, rather than recognizing patterns that are unique to Apple's stock.
picture of the chart
I have tried various methods to improve the accuracy of my stock prediction model. I attempted to adjust the model architecture, incorporate stock price indicators, normalize my data, and train the model with over half a million stock price data. Additionally, I implemented a lookback feature that allows the model to observe the last 10 or 20 prices. Initially, I expected these changes to improve the model's performance and provide more accurate predictions. However, after testing the model, I have found that it is still producing inaccurate predictions and displaying overfitting tendencies.


text:
Q: Cancel previous redux-saga task if a specific parameter is same GET_CHART_DATA is an action which calls and api to fetche the chart data based on chartId. Suppose GET_CHART_DATA is called with chartId='123' and api sends a request to server with that chartId. The request is in pending state. I dispatch same action GET_CHART_DATA with same chartId again i.e.123, in which case previous request of that same chartId should get cancelled. (Note: with chartId other parameters are going but those parameters are different, that is why I want to cancel old request which will have old parameters)
The catch is that there might be other requests to GET_CHART_DATA with different chartIds. Now I don't want to cancel those requests. I just want to cancel the previous request with same chart Id.
This is my action.js and sagas.js file. (sample)
   // action.js
    export function getChartData(params) {
      return {
        type: 'GET_CHART_DATA',
        params, // { chartid: '123' }
      };
    }

export function cancelPreviousDataCall(chartId) {
  return {
    type: 'CANCEL_PREVIOUS_DATA_CALL',
    chartId,
  };
}

// sagas.js
export function* getChartData(params) {
  try {
    const { result } = yield race({
      result: call(Api.getChartData, params.chartid),
      cancel: take('CANCEL_PREVIOUS_DATA_CALL'),
    });
  } catch (error) {}
}

   function* watchGetChartData() {
      while (true) {
        const { params } = yield take('GET_CHART_DATA');
        yield fork(getChartData, params);
      }
    }

A: You can keep track of the forked tasks for each particular chartId. You can then cancel the task if its still running. For example, your watchGetCharData could be something like this:
function* watchGetChartData() {
    let tasksByChartId = {}
    while (true) {
        const { params } = yield take('GET_CHART_DATA')
        if (tasksByChartId[params.chartId] && tasksByChartId[params.chartId].isRunning()) {
            tasksByChartId[params.chartId].cancel()
        }
        tasksByChartId[params.chartId] = yield fork(getChartData, params)
    }
}

With this you should no longer need the CANCEL_PREVIOUS_DATA_CALL action


text:
Q: Por que se me oculta el precio y añadir en carrito de todos los productos, al cambiar a un rol propio que cree en Wordpress como estan?
Basicamente el problema viene por ahi. Cree un sistema de suscripciones anuales, en la que cuando compran una suscripcion se les cambia el rol de cliente a oro (por ejemplo), teniendo descuentos en productos exclusivos. El problema viene que al hacer el pago, el rol se cambia bien, pero ya cambiado el rol no me deja ver los el precio y añadir al carrito de NINGUN producto del sitio.
Imaginé que a lo mejor seria algun conflicto con algun plugin o algo. Pero reviso y no encuentro el error.
Los plugins que tengo instalados sobre roles son:

*

*PublishPress Capabilities

*Product Visibility by User Role for WooCommerce

*User Role Editor

*WooCommerce Role Based Pricing by Meow Crew

*Woocommerce Role Pricing

*YITH WooCommerce Role Based Prices Premium

*Nav Menu Roles

Revisé cada uno y no hay nada que indique que el rol ORO no pueda ver precios o añadir al carrito de los productos.
Tambien hice:

*

*Ver en la base de datos si efectivamente al usuario se le habia cambiado el rol, y si, estaba actualizado correctamente.

*Revise en la base de datos las capacidades del rol ORO, y tiene la misma que el rol CLIENTE, por lo tanto por ese lado no deberia haber error.

*Probé de cambiar el rol de "Oro" a "oro" pensando que a lo mejor podia haber errores insertando roles uppercase en la base de datos.

*Revisé algunos archivos del sistema para ver si algun programador anterior realizo reglas en algun archivo de tema o plugin, pero no encontré nada.

No se si a alguien le pasó algo parecido, o sabe que pueda ser, me ayudaria bastante ya que es lo unico que me queda por resolver. Muchas gracias.

A: Resuelto: Se trataba del plugin YITH, que tiene unas opciones para que de acuerdo el rol del usuario, muestre o no por ej el precio de los productos, o bien el boton añadir al carrito, etc. Y como yo habia creado roles nuevos, por defecto el plugin los dejaba sin esas opciones, y por lo tanto era que no podia ver los precios ni añadir al carrito cuando el usuario cambiaba de rol cliente a uno que yo habia creado. Si quieren eliminen el debate, pero bueno a lo mejor a alquien le pase algo similar y le sirva. Saludos.


text:
Q: Selecting a fragment to start with in ViewPager - Android I am trying to make a Login screen where the Register, Login and Forgot Password screens are all fragments, placed like this:
Forgot Password | Login | Register
I found a simple video on YouTube showing me how to do this. The only issue I have is that when I start the Activity, it opens on the Forgot Password fragment since it is the first one, but I am wanting it to start in the middle, the Login fragment. Here is the code for the main activity. What should I change or add to this code or am I taking the wrong approach for what I am trying to achieve
Access.java
public class Access extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.access);

        initializePaging();
    }

    private void initializePaging() {
        List<Fragment> fragments = new Vector<>();
        fragments.add(Fragment.instantiate(this, AccessForgotPassword.class.getName()));
        fragments.add(Fragment.instantiate(this, AccessLogin.class.getName()));
        fragments.add(Fragment.instantiate(this, AccessRegister.class.getName()));

        PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);

        ViewPager accessViewPager = (ViewPager) findViewById(R.id.accessViewPager);
        accessViewPager.setAdapter(mPagerAdapter);
    }

}

access.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/accessMainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".access.Access">

    <android.support.v4.view.ViewPager
        android:id="@+id/accessViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

</LinearLayout>

AccessForgotPassword.java
public class AccessForgotPassword extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }
        return inflater.inflate(R.layout.access_forgot_password, container, false);
    }

}

access_forgot_password.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/accessForgotPasswordMainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#FF0000">
</LinearLayout>

AccessLogin.java
public class AccessLogin extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }
        return inflater.inflate(R.layout.access_login, container, false);
    }

}

access_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/accessLoginMainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#00FF00">
</LinearLayout>

AccessRegister.java
public class AccessRegister extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }
        return inflater.infalte(R.layout.access_register, container, false);
    }

}

access_register.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/accessRegisterMainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#0000FF">
</LinearLayout>

A: Set
accessViewPager.setCurrentItem(1);

A: Try adding  accessViewPager.setCurrentItem(1) in end of onCreate()

A: Try to set accessViewPager.setCurrentItem(1); in the onCreate() of your activity.

A: Just after setting adapter you can set manually set the second fragment to view pager
accessViewPager.setCurrentItem(1); // 0= ForgotPassword, 1=LoginScreen,...so on


text:
Q: Windows 8 upgrade on multiple PCs I bought windows 8 upgrade from microsoft, and i found on this page that:

*

*Offer valid from October 26, 2012 until January 31, 2013 and is for individuals and small businesses needing to upgrade up to five
  devices. If you are a business customer looking to upgrade more than
  five devices to Windows 8 Pro, contact your Microsoft partner for more
  information

Is that means that i Can upgrade up to five PCs using the same downloaded windows? or means that I can buy max 5 licences?

A: No, it means that if you have more than 5 devices, rather than paying for five retail upgrades you'll get better pricing by opening a volume licensing account.


text:
Q: Xmobar is "Updating" when attempting to run script My issue here is that my Xmobar says that it's "Updating..." when I provide the layout with a path to a C script (the executable)that I hacked together. I included Run Stdinreader and that made no dent on the issue.
I was under the impression that if a script can output to the terminal, it could to Xmobar. This C script is responsible for printing a quote to the terminal based on conditions specified. I don't need help with the script itself (although it is rushed and could be better constructed). I just want to know:
Is this an issue with an incompatibility with Xmobar and C? Or, did I forget to do something that will make the taskbar spit out the correct output?
My Xmobar Config is:
    Config {
--this is an edited dotfile from the example shown from the Archlinux wiki for the xmobarrc file. This is a good starting point (and may also serve as a regular status bar *as in my case it does)
--This is not my original work from scratch; these are merely my edits for my personal taste. For instance, I removed the Weather module and heavily edited the colors
   -- appearance
     font =         "-misc-fixed-*-*-*-*-10-*-*-*-*-*-*-*"
   , bgColor =      "#020616"
   , fgColor =      "#9e9e9e"
   , position =     Top
   , border =       BottomB
   , borderColor =  "#020616"

   -- behavior
   , lowerOnStart =     True    -- send to bottom of window stack on start
   , hideOnStart =      False   -- start with window unmapped (hidden)
   , allDesktops =      True    -- show on all desktops
   , overrideRedirect = True    -- set the Override Redirect flag (Xlib)
   , pickBroadest =     False   -- choose widest display (multi-monitor)
   , persistent =       True    -- enable/disable hiding (True = disabled)

   -- plugins
   --   Numbers can be automatically colored according to their value. xmobar
   --   decides color based on a three-tier/two-cutoff system, controlled by
   --   command options:
   --     --Low sets the low cutoff
   --     --High sets the high cutoff
   --
   --     --low sets the color below --Low cutoff
   --     --normal sets the color between --Low and --High cutoffs
   --     --High sets the color above --High cutoff
   --
   --   The --template option controls how the plugin is displayed. Text
   --   color can be set by enclosing in <fc></fc> tags. For more details
   --   see http://projects.haskell.org/xmobar/#system-monitor-plugins.
   , commands =
       [ Run Weather "RJTT" [ "--template", "<skyCondition> | <fc=#4682B4><tempC></fc>°C | <fc=#4682B4><rh></fc>% | <fc=#4682B4><pressure></fc>hPa"
                             ] 36000 --edits: Weather ia omitted from my layout
        -- network activity monitor (dynamic interface resolution)
        , Run DynNetwork     [ "--template" , "<dev>: <tx>kB/s|<rx>kB/s"
                             , "--Low"      , "1000"       -- units: B/s
                             , "--High"     , "5000"       -- units: B/s
                             , "--low"      , "#98b7d1"
                             , "--normal"   , "#98b7d1"
                             , "--high"     , "#98b7d1"
                             ] 10

        -- cpu activity monitor
        , Run MultiCpu       [ "--template" , "Cpu: <total0>%|<total1>%"
                             , "--Low"      , "50"         -- units: %
                             , "--High"     , "85"         -- units: %
                             , "--low"      , "#9e9e9e"
                             , "--normal"   , "#6f90c9"
                             , "--high"     , "#6f90c9"
                             ] 10
        ,  Run StdinReader
        -- cpu core temperature monitor
        , Run CoreTemp       [ "--template" , "Temp: <core0>°C|<core1>°C"
                             , "--Low"      , "70"        -- units: °C
                             , "--High"     , "80"        -- units: °C
                             , "--low"      , "#9e9e9e"
                             , "--normal"   , "#ead581"
                             , "--high"     , "#6f90c9"
                             ] 50

        -- memory usage monitor
        , Run Memory         [ "--template" ,"Mem: <usedratio>%"
                             , "--Low"      , "20"        -- units: %
                             , "--High"     , "90"        -- units: %
                             , "--low"      , "#9e9e9e"
                             , "--normal"   , "#ead581"
                             , "--high"     , "#f77647"
                             ] 10

        -- battery monitor
        , Run Battery        [ "--template" , "Batt: <acstatus>"
                             , "--Low"      , "10"        -- units: %
                             , "--High"     , "80"        -- units: %
                             , "--low"      , "#f77647"
                             , "--normal"   , "#dde298"
                             , "--high"     , "#b8e298"

                             , "--" -- battery specific options
                                       -- discharging status
                                       , "-o"    , " <left>% <fc=#efaf5b> (<timeleft>) </fc>"
                                       -- AC "on" status
                                       , "-O"    , "<fc=#dd5d6c>Currently Charging</fc>"
                                       -- charged status
                                       , "-i"    , "<fc=#60e9ff>Fully Charged</fc>"
                             ] 50

        -- time and date indicator
        --   (%F = y-m-d date, %a = day of week, %T = h:m:s time)
        , Run Date           "<fc=#C8E86A>%F (%a) %r</fc>" "date" 10

        ]
   }

   -- layout
   , sepChar =  "%"   -- delineator between plugin names and straight text
   , alignSep = "}{"  -- separator between left-right alignment
   , template = "Current User: <fc=#f77647> %whoami% </fc>| <fc=#787773> %~/scripting/taskbarquote% </fc> }{| <fc=#98b7d1> %dynnetwork% </fc>| %date% | %battery% ||%multicpu% | %coretemp% | %memory% "

Thanks.
This would be the C script. Above it is the problem:

A: Did more research today. The problem here is that %% counts as an argument to "run" something, but above it is where it's supposed to be defined. It's not.
I just used %diskspace% for a new script that outputs my Sink volume. It would work the same with the C script.

A: I see that you got an answer - though I did not understand. What you should be using is Run Com to execute your script.


text:
Q: Counting does not work properly in OpenMP I have the function
void collatz(int startNumber, int endNumber, int* iter, int nThreads)
{
    int i, n, counter;
    int isodd; /* 1 if n is odd, 0 if even */
    #pragma omp parallel for
    for (i = startNumber; i <= endNumber; i++)
    {
        counter = 0;
        n = i;
        omp_set_num_threads(nThreads);
        while (n > 1)
        {
            isodd = n%2;
            if (isodd)
                n = 3*n+1;
            else
                n/=2;
            counter++;
        }
        iter[i - startNumber] = counter;
    }
}

It works as I wish when running serial (i.e. compiling without OpenMP or commenting out #pragma omp parallel for and omp_set_num_threads(nThreads);). However, the parallel version produces the wrong result and I think it is because the counter variable need to be set to zero at the beginning of each for loop and perhaps another thread can work with the non-zeroed counter value. But even if I use #pragma omp parallel for private(counter), the problem still occurs. What am I missing?
I compile the program as C89.

A: Inside your OpenMP parallel region, you are assigning values to the counter, n and isodd scalar variables. These cannot therefore be just shared as they are by default. You need to pay extra attention to them.
A quick analysis shows that as their values is only meaningful inside the parallel region and only for the current thread, so it becomes clear that they need to be declared private.
Adding a private( counter, n, isodd ) clause to your #pragma omp parallel directive should fix the issue.


text:
Q: How can I use R to count frequency of elements (ie years of birth) in an excel spreadsheet I would like to know the code to use to determine the frequency of years in an excel spreadsheet.  I am new to using R and I can import the data and read the headings.

A: Say you have an Excel spreadsheet with columns years and col
years   col
2001    a
2002    b
2001    b
2002    c
2015    a
2014    c
2014    d

If you want to do a quick calculation in R, you can highlight the section from Excel to copy to R, including headers.  Then ctrl-c to copy.
Then in R, read the table
dat <- read.table("clipboard", header=TRUE)

And you can use table as akrun recommended
table(dat$years)
 2001 2002 2014 2015
  2    2    2    1


text:
Q: Howto find out if Laravel Command has been started via the scheduler? When the laravel scheduler starts a command like:
$schedule->command('test:testcommand')->hourly();
i need to find out, inside the command, if it has been started via
artisan test:testcommand
or
artisan schedule:run
i looked into $_SERVER['argv'] but i don´t see any info that helps me to
identify this.
maybe laravel has some fancy internal functions, but i wasn´t able to find them.

A: The only way to do this is to communicate through arguments. So you could do as follows:
$schedule->command('test:testcommand',['--scheduler'])->hourly();

A: You can do this with events:
php artisan make:event OnCommandRun
Then in the handle() of your testcommand class fire it:
event(new OnCommandRun());
Then within the event handle() function do whatever you want
More on Events


text:
Q: Python Django сайт работает без staticfiles писал проект на python django около недели, все было нормально, применялись все изменения в css файле, а сегодня проект перестал реагировать на изменения в styles.css и более того, проект начал работать и показывать верстку из того файла, который я уже удалил из staticfiles. Я слышал про то что django хранит данные в оперативной памяти, но я не знаю что с этим делать D:

A: помогло указание полной директории папки static, просто "/static/" не работало.


text:
Q: supervisorctl unable to reload virtual environment activate file I am trying to run a tornado api with supervisor service.
This is the configuration I have written to run my application using supervisor:
[program:tornado_main]
command=/home/ubuntu/env/bin/python /home/ubuntu/<repo>/__main__.py
directory=/home/ubuntu/<repo>
user=ubuntu
stdout_logfile = /var/log/supervisor/tornado_main.log
stderr_logfile = /var/log/supervisor/tornado_main_err.log
environment=PATH=/home/ubuntu/env/bin,PYTHONPATH=/home/ubuntu/<repo>,VIRTUAL_ENV=/home/ubuntu/env/

This runs perfectly.
There are some portions in the code which depend on some environment variables which are written in the virtual environment's activate file.
Now, the issue is that supervisor is not able to read those environment variables and throws error.
When I run it manually, it works fine.
What am I missing?

A: When you run env/bin/python, you are using the virtualenv without activating it. That's often enough, but if you really depend on the virtualenv being activated (e.g. because you want to launch subprocesses in that environment or use other environment variables), then you'll need to activate it in your supervisor config (and if you do this, you'll probably want to remove the environment line that duplicates what activate will do):
command=bash -c 'source /home/ubuntu/env/bin/activate && python /home/ubuntu/<repo>/__main__.py'


text:
Q: Web API 2 RequestContext.Principal returning previous username with Windows Authentication I have an API built with Web API 2 (VB.Net), running on IIS 7.5 that relies on Windows Authentication and is queried by an AngularJS app.  Everything has worked fine for a year or so but we now have a user that we've changed their username a couple of days ago as they have recently got married.
All normal Windows login processes work with the new username however the credentials that the API tries to use always refers to the old username.
AngularJS:
$http.get($rootScope.urlAPI + 'access/', {
  cache: false,
  withCredentials: true
}).success
...

Web API 2:
<HttpGet>
<Route("api/access")>
<ResponseType(GetType(UserAccessDTO))>
<NoCachePolicy>
<Authorize> _
Function GetStaffAccessForApp() As UserAccessDTO
  Dim objUser As System.Security.Principal.WindowsPrincipal = RequestContext.Principal
  Dim strUsername As String = objUser.Identity.Name
  ' strUsername is somehow returning their old username
...

strUsername is somehow returning their old username
Directly querying the API from the browser returns the same JSON result with the old username so I don't believe the issue is specifically with the AngularJS app but somewhere between the browser and the API...
This issue occurs from both IE11 and Google Chrome and I've tried clearing the browser cache, deleted cookies and also tried restarting the API's web-site service in IIS to reload the API.
We only have 2 domain controllers and it's been a couple of days so they are definitely synced and I've scrolled through the attributes of her account but can find no reference to her old username there so I'm at a loss as to where this is coming from :(

A: For anyone else with similar issue, it seems to have resolved only after a reboot of the servers.  We conducted regular monthly maintenance which involves progressive restart of all servers.  Somewhere between rebooting domain controllers, database server and API server it has resolved the issue for the user this morning.
A bit disappointing we couldn't nail down exactly where it was... but probably cached somewhere.


text:
Q: Equivalent of string Array in C# from php and converting it into JSON I have a piece of code that I've written in PHP like this:
$ids= array('12345','54321');
$post_data = array( 'token' => '******', 'goods_sn' => json_encode($ids) );

Before posting it to my server. I'm using .NET's restsharp library to achieve this. To replicate the PHP's array function i've created a string array in my application and then converted it into the JSON format like this:
string _token = loginToken;
string _goods_sn = new JavaScriptSerializer().Serialize(new string[] { "12345", "54321" });
var client = new RestClient("mysite.com");
var request = new RestRequest(Method.POST);
var post_data = new JavaScriptSerializer().Serialize(new { token= _token, goods_sn = _goods_sn });
request.AddBody(post_data);
request.RequestFormat = DataFormat.Json;
return client.Execute(request).Content;

But I keep getting reply that I have no token parameter in my request.. Am I doing something wrong here? Can someone help me out ?
Edit: guys so here is a format of data in PHP..
// example with goods_sn only element in JSON array

Array
(
    [token] => 4c4918
    [goods_sn] => "207833601"
)

//Example with multiple good_sn's ...
Array
(
    [token] => 4c4918
    [goods_sn] => ["207833601","118880101"]
)

And the output in C# with the following code:
string _token = loginToken;
 string[] _goodsSN = new string[] { "118880101", "207833601" };
 IDictionary<Object, Object> data = new Dictionary<Object, Object> {
 { "token", loginToken },
 { "goods_sn", new JavaScriptSerializer().Serialize(_goodsSN) }
 };

        var client = new RestClient("mysite.com");
        var request = new RestRequest(Method.POST);
        var post_data = new JavaScriptSerializer().Serialize(data);
        request.RequestFormat = DataFormat.Json;
        request.AddBody(post_data);

is:
{\"token\":\"4c4918\",\"goods_sn\":\"[\\\"118880101\\\",\\\"207833601\\\"]\"}

This 2nd version is a little bit modified version of C# code I wrote in first example... I'm using a dictionary now...


text:
Q: Creating contra values in the same column SQL Aim to write a statement to produce a table with a numeric column that contains contra values, e.g.
Ref     Value
a       100
b       75
c       50
c       -50
b       -75
a       -100

I am new to SQL but aware it works row by row, so the only way I could think of doing this is write an initial SELECT statement into a temporary table and INSERT into my temporary table with the contra values, i.e.
SELECT
  [Ref],
  [Value]
  INTO #Temp
FROM
  mytable
INSERT INTO #Temp ([Ref], [Value])
SELECT
  [Ref],
  0 - [Value]
FROM
  mytable

While this 'does the job' I fear it is 'messy' (could possibly cause problems when used for its intended purpose) and wondered if anyone would be able to provide a better solution.

A: Use Union ALL to combine the original and negative values. Then insert into temp table. Try this.
SELECT [Ref],
       [Value]
INTO   #Temp
FROM   (SELECT [Ref],
               [Value]
        FROM   mytable
        UNION ALL
        SELECT [Ref],
               [Value] * -1
        FROM   mytable) a

If you just want to view the result remove the into #temp table
SELECT [Ref],
       [Value]
FROM   (SELECT [Ref],
               [Value]
        FROM   mytable
        UNION ALL
        SELECT [Ref],
               [Value] * -1
        FROM   mytable) a


text:
Q: Python's requests_html render() function does not allow to persist CSRF token - cannot login to website I need to use .render() to get the entire DOM content off of a website managed by a dynamic front-end framework (JS or Ajax e.g.). That website stores a CSRF token in a hidden input field as usual. When I specify use r.html.render(send_cookies_session=True) or r.html.render(), the dynamic part of the DOM is rendered and I capture the CSRF token, but after I logged in and try to crawl a route behind the login page, the CSRF token changes and I am redirected to the login page.
Then when I use r.html.render(reload=False), the dynamic part of the DOM including the hidden div with the CSRF token is not rendered. I can obviously not login as I cannot capture the CSRF token.
I have tried a lot of options for render(), but nothing seems to work.
   def login(self):
        payload = json.loads(self.options.login_params)

        with HTMLSession() as session:
            r = session.get(self.login_url)

            # need to turn off reload or else a new CSRF token is captured when the page is reloaded
            # render the html to capture the CSRF token
            r.html.render(send_cookies_session=True)
            # r.html.render(reload=False)

            html = BeautifulSoup(
                r.html.html, "html.parser")

            # save CSRF token to payload dict
            payload = self.add_csrf_to_payload(html, payload)

            # login with CSRF token from payload
            p = session.post(self.login_url, data=payload)
            html = BeautifulSoup(r.html.html, "html.parser")

            # download HTML from target URL using CSRF => here it breaks down as the CSRF changes due to the render() function (unless set to reload=False)
            r = session.get(self.target_url)
            html = BeautifulSoup(r.html.html, "html.parser")
            payload = self.add_csrf_to_payload(html, payload)

            self.session = session
            self.payload = payload

            return html


text:
Q: What can I use to let users build their own avatar character? How would you go about providing users with the ability to build a custom avatar character, something like Yahoo! Avatars?
EDIT - Let me be more specific about what Yahoo! Avatars does:
It lets you create an avatar by selecting a face, hair style, eyes, etc.
This is what I'm looking for.
I am interested in:

*

*Libraries, free or paid

*Outsourcing to an external website, provided this can be well integrated into our website

*Any other suggestions

A: There are many web sites that let users build "cartoon character" or 3D rendered characters for avatars, but most sites don't allow users to use those avatars on other web sites.  This one does: http://www.moeruavatar.com/index_en.shtml, but it's up to the user to save the generated image and upload it to other web sites.  I don't know of any ready-made libraries of code you can install on your server to get such functionality on your own web site.
Suggestions for general avatar image / userid or email association:

*

*Gravatar.  http://en.gravatar.com/

*Identicon: http://en.wikipedia.org/wiki/Identicon, http://identicon.codeplex.com/

*Wavatar

*MonsterId

Gravatar is a web service.  Identicon is an algorithm you can implement locally on your server if you prefer.  The last two are kinda funny but I don't think I'd ever use them.

A: There's also My Avatar Editor which makes Wii-style (and Wii-compatible) avatars. It's Flash based and it's on googlecode with a MIT-license.

A: Try a Globally Recognized Avatar, or Gravatar.
http://en.gravatar.com/
Allows users to register and site developers to access Gravitars.

A: Gravatar.com
deviantart.com
MonsterId
www.dressupgames.com/avatars
Good luck!


text:
Q: VoiceOver does not repeat typed character on custom text view with UITextInput I have custom text view that implement UITextInput. Everything works except the voiceover does not repeat the characters I typed using soft keyboard.
Is there any additional API or services I need to implement in order to make it work?

A: Unfortunately, now it seems that VoiceOver cannot announce the soft keyboard feedback made by native code.
But it possible to get VoiceOver feedback at text field of WebView().
So, I'm making iOS App by this way.


text:
Q: Linux or Windows version of a library in Cygwin? I have developed some codes in Linux which use boost::serialization library. Now I want to copy my files into Cygwin and compile them to produce executable for Windows. I know that I should use Mingw-64 g++ compiler. But how about boost library? Should I download the Windows version or the Linux version of this library?

A: In Cygwin, you install Boost libraries as per Unix/Linux. From the documentation

Getting Started on Windows
A note to Cygwin and MinGW users
If you plan to use your tools from the Windows command prompt, you're in the right place.
If you plan to build from the Cygwin bash shell, you're actually running on a POSIX
platform and should follow the instructions for getting started on Unix variants.
Other command shells, such as MinGW's MSYS, are not supported—they may or may not work.


text:
Q: Angular 2 HTTP Headers not being added to request I have the following http request in which I add the header to the request, however the request fails and when I look in the Network tab of the browser the request headers don't include the Authorization header. What am I missing here?:
  public get(address: string, callback: any): Observable<any> {
    let headers: Headers = new Headers();
    headers.append('Authorization', 'Bearer <token>');
    return this.http.get(address, { 'Headers': headers })
      .map(callback)
      .catch((error: any) => this.handleError(error));
  }

Request Headers from the Network tab:
GET /v1/projects HTTP/1.1
Host: <host>
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Accept: */*
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

A: Headers should be headers
this.http.get(address, { headers: headers })


text:
Q: WL.nativepage.show crashes in ios 10 I am working on MFP Hybrid Project where some pages to be displayed in native pages.
To display the content in native page, we was handling it via wl.nativepage.show.
WL.NativePage.show("PDFViewController", backFromNativePage, params);

It works fine upto iOS 8,9. But it crashes with iOS 10 and we are getting the following error.
[PDFViewController parentViewController]: unrecognized selector sent to instance
Note: We are not using any method of "parentViewController" in native side.And it is not calling native methods also.
Please suggest how to resolve this?

A: My suggestion is that you should first upgrade from 6.3 build dated July 2015, to the latest 6.3 build dated September 2016... More than a year apart. You can download the iFix from IBM Fix Central.
Once you've upgraded the build, try again to see if WL.NativePage fails or not. If it fails still then I suggest that you'll open a PMR and supply a test project that can be debugged.


text:
Q: Vertical table line is missing (tabularx and multirow) Can anyone tell me, why my table is missing the vertical line on the right?
It has something to do with that \multirow, but i can't find it.

\documentclass[11pt, twocolumn, a4paper]{article}
\usepackage[left=1.5cm, text={18cm, 25cm}, top=2.5cm]{geometry}
\usepackage[latin2]{inputenc}
\usepackage[T1, IL2]{fontenc}
\usepackage[czech]{babel}
\usepackage{times}
\usepackage{multirow}
\usepackage{tabularx}
\usepackage{caption}
\begin{document}

\begin{table}[H]
\catcode`\-=12
\centering
\begin{tabularx}{0.9\textwidth}{|c|c|c|c|>{\raggedright\arraybackslash}X|}
\hline
\bfseries offset & \bfseries velikost & \bfseries typ & \bfseries název & \bfseries popis\\
\hline
0 & 8 &  & (hlavička) & slovo pro správu, odkaz na třídu \\
\hline
8 & 1 & byte & A.a & \\
\hline
9 & 3 & & (zarovnání) & následují členy B, zarovnání na 4b\\
\hline
12 & 2 & char & B.a & \multirow{3}{4cm}{B má double, vyplnění 4 bajtové mezery}\\
\cline{1-4}
14 & 1 & byte & B.b\\
\cline{1-4}
15 & 1 & & (zarovnání)\\
\hline
16 & 8 & double & B.d & \\
\hline
24 & 4 & A & B.c & \\
\hline
28 & 4 & & (zarovnání) & finální zarovnání na 8 bajtů\\
\hline
\end{tabularx}
\end{table}

\end{document}

A: You are missing a & at the end the two rows after your \multirow You need teh empty cells to carry the vertical rules.


text:
Q: In sysctl.conf settings, what is the difference between 'all' & 'default'? In context of  sysctl.conf settings,
what is the difference between (all vs. default) like net.ipv4.conf.all.accept_source_route & net.ipv4.conf.default.accept_source_route  in sysctl settings ?
If I added all values, is it necessary to add default as well ?

Using Ubuntu 12.04 LTS

A: Special thanks to Symantec and google:
When you change variables in the /proc/sys/net/ipv4/conf/all directory, the variable for all interfaces and default will be changed as well.
When you change variables in /proc/sys/net/ipv4/conf/default, all future interfaces will have the value you specify.
This should only affect machines that can add interfaces at run time, such as laptops with PCMCIA cards, or machines that create new interfaces via VPNs or PPP, for example.


text:
Q: Issue with multiple criteria in bindingsource.filter I am trying to filter  a binding source based on 2 comboboxes.  I have one of comboboxes filter just fine.  The second has me stumped as it uses the first combobox and then the second based on a switch statement:
    private void comboBox2_SelectedIndexChanged(object sender,
    System.EventArgs e)
    {
        string sItem;
        sItem = comboBox2.SelectedItem.ToString();

        switch (sItem)
        {
            case "Banks":
                propertyInformationBindingSource.Filter = ("ClientKey ='" + comboBox1.SelectedValue + "'" And "Search = -1");
                break;
            case "Exam":
                propertyInformationBindingSource.Filter = ("ClientKey ='" + comboBox1.SelectedValue + "'") And ("Exam = -1");
                break;
            case "Search Finished":
                propertyInformationBindingSource.Filter = ("ClientKey ='" + comboBox1.SelectedValue + "'") And ("Finished = -1;
                break;
            case "All":
                propertyInformationBindingSource.Filter = "ClientKey ='" + comboBox1.SelectedValue + "'";
                break;

        }
    }

I am having issues with the value after the AND in which it claims is wrong.  Any help would be great.
Thanks

A: I think there were some string concatenation issues and you were missing the closing parenthesis around Finisher = -1.
Try
 switch (sItem)
        {
            case "Banks":
                propertyInformationBindingSource.Filter = ("ClientKey ='" + comboBox1.SelectedValue + "' And Search = -1");
                break;
            case "Exam":
                propertyInformationBindingSource.Filter = ("ClientKey ='" + comboBox1.SelectedValue + "' And Exam = -1");
                break;
            case "Search Finished":
                propertyInformationBindingSource.Filter = ("ClientKey ='" + comboBox1.SelectedValue + "' And Finished = -1");
                break;
            case "All":
                propertyInformationBindingSource.Filter = "ClientKey ='" + comboBox1.SelectedValue + "'";
                break;

        }

Note if you have too much string concatenation going on, it's best that you use string.Format(). It improves readability and is more efficient that concatenation. As an example, you first case would look like this
propertyInformationBindingSource.Filter =
      string.Format("ClientKey ='{0}' And Search = -1", comboBox1.SelectedValue);


text:
Q: I want to close a specific excel file amongst more then 2 open without Killing Excel process I have three excel files (MS office 16) opened. My code check for a specific file if it is open then it try to closes it but it closes excel process which ultimately closes all the excel files.
What I noticed is in task manager there is only one EXCEL.EXE porcess for all the files and under Details tab I can see all my open excel file with name.
What I Tried is :

System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses("Excel");
  foreach (Process p in processes)
  {
      if (p.MainWindowTitle == "MyFile.xlsx - Excel")
      {
          p.Kill();
          break;
      }
  }

and below code does nothing :
 Microsoft.Office.Interop.Excel.Application xlApp = new icrosoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
            //xlWorkbook.Close(false);

            xlWorkbook.Close(true, Type.Missing, Type.Missing);
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
            xlWorkbook = null;
            xlApp = null;

            GC.Collect();

A: Instead of killing the process, send a close message to the window:
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses("Excel");
foreach (Process p in processes)
{
  if (p.MainWindowTitle == "MyFile.xlsx - Excel")
  {
    int hwnd = 0;

    //Get a handle for the Application main window
    hwnd = FindWindow(null, p.MainWindowTitle);

    //send WM_CLOSE system message
    if (hwnd != 0)
      SendMessage(hwnd, WM_CLOSE, 0, IntPtr.Zero);

    break;
  }
}


text:
Q: get array of column values in codeigniter i have a table with this structure:
ID int(11)
user_id int(11)
notification_event_id   int(11)
how can i get an array that contains all values of user_id column :
EX:
Array([0]=> 1,[1]=>2,[2]=>3,[3]=>4,[4]=>5,[5]=>6);

and without looping on the result_array() value and moving the user_ids to a new integers array
is that possible?

A: I did a research and found this:
Note: a 'magic' solution for that, for example: using a codeigniter custom function, I think doesn't exist in actual framework version. So, you need create a function in Model or in a Custom Helper.
Reference: Populate drop down list from database
Using your Model
// Controller
$data['city_list'] = $this->City_model->get_dropdown_list();
$this->load->view('my_view_file', $data);
Model:

// Model (or create a helper -- see below)
function get_dropdown_list()
{
  $this->db->from('city');
  $this->db->order_by('name');
  $result = $this->db->get();
  $return = array();
  if($result->num_rows() > 0) {
    foreach($result->result_array() as $row) {
      $return[$row['id']] = $row['name'];
    }
  }

  return $return;
}

// View
<?php echo form_dropdown('city_id', $city_list, set_value('city_id', $city_id));

Using a Helper
if ( ! function_exists('drop_down'))
{
    function drop_down($name, $match, $data)
    {
        $form = '<select name="'.$name.'"> ' ."\n";

        foreach($data as $key => $value)
        {
            $selected = ($match == $key) ? 'selected="selected"' : NULL ;
            $form .= '<option value="'. $key .'" '. $selected .'>'.$value.'' . "\n";
        }

        $form .= '</select>' . "\n";
        return $form;
    }
}
In the view

echo drop_down('mylist', 3, $data);

A: Each results row is itself an array so some looping is necessary! Why would you need to do it differently?
The most straightforward way to do what you want is:
// Model
function get_all_userid()
{
    $query = $this->db->get('table_name');
    $array = array();

    foreach($query->result() as $row)
    {
        $array[] = $row['user_id']; // add each user id to the array
    }

    return $array;
}

// Controller
function user_list()
{
    $data = $this->your_model->get_all_userid(); // get results array from model
    $this->load->view('your_view', $data); // pass array to view
}

Obviously you'll need to adjust the table/model names to match the ones you're using.


text:
Q: How can I optimize this function to animate more smoothly I have written this function to create a "reveal more" functionality for a card style layout. I originally wrote it to all be within a click function but then the scope changed and I needed to move the commands into their own function, and now the animation is very stuttery to more to ignore. I have a feeling that it has to do with the variable updating while animating and causing a conflict but I'm not sure how to bypass that or to set the variable as a constant after taking one height.
        //This function removes the reveal more trigger and slides "new-deals" down to auto height
function revealMore() {
    var containerHt = $("#new-deals").children().height; //set animation height for "reveal more" function

    //Reveal More function which handles animating container height to that of contained elements and removes the reveal more trigger element
    if (($("#new-deals").height) >= containerHt) {
        $("#new-deals").animate({height: containerHt}, 400, function() {
            $("#new-deals").css({height: 'auto'});
        });
        $("#new-deals").siblings('.reveal-more').remove();
    }
}
$(".reveal-more a").click( function() {
    revealMore();
    return false;
});

A: There are a number of things:

*

*Save your $("#new-deals") in a variable.

*Use CSS Animations rather than jquery's animate

*Use the tranzlateZ(0) hack (if you aren't using a lot of VRAM already).

Check out html5rocks for enlightenment.