text:
Q: How can a JLabel containing only text be aligned within a JPanel? Normally, I would just create the JLabel using a string as the first parameter and JLabel.CENTER as the second parameter; adding the label to the panel using BorderLayout.CENTER would then cause the text in the label to be aligned in the center of the panel.
However, I'm using the 'RichJLabel' class in order to get a drop shadow on my text. To do this, it overrides Component.paintComponent in such a way that the alignment information is lost, and the label's text is drawn in the top left of the panel no matter what I do.
From what I understand, the workaround for this is to encase the label inside of another panel; that way, I can align the panel itself inside the parent panel, but I'm uncertain of how exactly to do this.
My complete goal is to:

*

*Figure out what font size a given string needs in order to fill up its parent JPanel

*Add a drop shadow to that text

*Center the text within its JPanel

Here's what I've got so far:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;

public class RichJLabel extends JLabel {

    private int tracking;

    public RichJLabel(String text, int tracking) {
        super(text, JLabel.CENTER);
        this.tracking = tracking;
    }

    private int left_x, left_y, right_x, right_y;
    private Color left_color, right_color;

    public void setLeftShadow(int x, int y, Color color) {
        left_x = x;
        left_y = y;
        left_color = color;
    }

    public void setRightShadow(int x, int y, Color color) {
        right_x = x;
        right_y = y;
        right_color = color;
    }

    public Dimension getPreferredSize() {
         String text = getText();
         FontMetrics fm = this.getFontMetrics(getFont());

         int w = fm.stringWidth(text);
         w += (text.length()-1)*tracking;
         w += left_x + right_x;
         int h = fm.getHeight();
         h += left_y + right_y;

         return new Dimension(w,h);
}

public void paintComponent(Graphics g) {

        ((Graphics2D)g).setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        char[] chars = getText().toCharArray();

        FontMetrics fm = this.getFontMetrics(getFont());

        int h = fm.getAscent();
        int x = 0;

        for(int i=0; i<chars.length; i++) {
            char ch = chars[i];
            int w = fm.charWidth(ch) + tracking;

            g.setColor(left_color);
            g.drawString(""+chars[i],x-left_x,h-left_y);

            g.setColor(right_color);
            g.drawString(""+chars[i],x+right_x,h+right_y);

            g.setColor(getForeground());
            g.drawString(""+chars[i],x,h);

            x+=w;
    }

        ((Graphics2D)g).setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);

    } // end paintComponent()

public static void main(String[] args) {

  JPanel panel1 = new JPanel( new BorderLayout() );
  panel1.setBackground( Color.BLUE );
  panel1.setBorder( BorderFactory.createBevelBorder( BevelBorder.LOWERED ));

  JPanel interiorPanel = new JPanel( new BorderLayout() );
  panel1.add(interiorPanel, BorderLayout.CENTER);
  RichJLabel label = new RichJLabel("100", 0);
  label.setHorizontalAlignment(JLabel.CENTER);
  label.setVerticalAlignment(JLabel.CENTER);
  label.setVisible( true );
  label.setForeground( Color.YELLOW );

  interiorPanel.add(label, BorderLayout.CENTER);
  label.setFont(new Font("Arial", Font.BOLD, 140));
  label.setFont(label.getFont().deriveFont(140f));

  //resize code
  Font labelFont = label.getFont();
  String labelText = label.getText();
  int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
  int componentWidth = interiorPanel.getWidth();

  // Find out how much the font can grow in width.
  double widthRatio = (double)componentWidth / (double)stringWidth;
  int newFontSize = (int)(labelFont.getSize() * widthRatio);
  int componentHeight = interiorPanel.getHeight();

  // Pick a new font size so it will not be larger than the height of label.
  int fontSizeToUse = Math.min(newFontSize, componentHeight);
  // Set the label's font size to the newly determined size.
  label.setFont(new Font(labelFont.getName(), Font.BOLD, fontSizeToUse));
  label.setLeftShadow(-3,-3,Color.BLACK);

  // drop shadow w/ highlight
  label.setRightShadow(2,3,Color.black);
  label.setForeground(Color.gray);

  JFrame frame = new JFrame("Label SSCCEE");
  frame.getContentPane().add(panel1);
  frame.pack();
  frame.setVisible(true);
 }
}

What it does right now is this:

A: The code was checking for the size of the container too soon.  Before it is displayed, it has a width/height of 0.

Altered code
import java.awt.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;

public class RichJLabel extends JLabel {

    private int tracking;

    public RichJLabel(String text, int tracking) {
        super(text, JLabel.CENTER);
        this.tracking = tracking;
    }

    private int left_x, left_y, right_x, right_y;
    private Color left_color, right_color;

    public void setLeftShadow(int x, int y, Color color) {
        left_x = x;
        left_y = y;
        left_color = color;
    }

    public void setRightShadow(int x, int y, Color color) {
        right_x = x;
        right_y = y;
        right_color = color;
    }

    public Dimension getPreferredSize() {
         String text = getText();
         FontMetrics fm = this.getFontMetrics(getFont());

         int w = fm.stringWidth(text);
         w += (text.length()-1)*tracking;
         w += left_x + right_x;
         int h = fm.getHeight();
         h += left_y + right_y;

         return new Dimension(w,h);
}

public void paintComponent(Graphics g) {

        ((Graphics2D)g).setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        char[] chars = getText().toCharArray();

        FontMetrics fm = this.getFontMetrics(getFont());

        int h = fm.getAscent();
        int x = 0;

        for(int i=0; i<chars.length; i++) {
            char ch = chars[i];
            int w = fm.charWidth(ch) + tracking;

            g.setColor(left_color);
            g.drawString(""+chars[i],x-left_x,h-left_y);

            g.setColor(right_color);
            g.drawString(""+chars[i],x+right_x,h+right_y);

            g.setColor(getForeground());
            g.drawString(""+chars[i],x,h);

            x+=w;
    }

        ((Graphics2D)g).setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);

    } // end paintComponent()

public static void main(String[] args) {

  JPanel panel1 = new JPanel( new BorderLayout() );
  panel1.setBackground( Color.BLUE );
  panel1.setBorder( BorderFactory.createBevelBorder( BevelBorder.LOWERED ));

  JPanel interiorPanel = new JPanel( new BorderLayout() );
  panel1.add(interiorPanel, BorderLayout.CENTER);
  RichJLabel label = new RichJLabel("100", 0);
  label.setLeftShadow(-3,-3,Color.BLACK);

  // drop shadow w/ highlight
  label.setRightShadow(2,3,Color.black);

  label.setHorizontalAlignment(JLabel.CENTER);
  label.setVerticalAlignment(JLabel.CENTER);
  label.setVisible( true );
  label.setForeground( Color.YELLOW );

  interiorPanel.add(label, BorderLayout.CENTER);
  label.setFont(new Font("Arial", Font.BOLD, 140));
  label.setFont(label.getFont().deriveFont(140f));

  //resize code
  Font labelFont = label.getFont();

  JFrame frame = new JFrame("Label SSCCEE");
  frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  frame.setContentPane(panel1);
  frame.pack();
  frame.setVisible(true);

  int componentWidth = interiorPanel.getWidth();
  String labelText = label.getText();
  int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
  // Find out how much the font can grow in width.
  double widthRatio = (double)componentWidth / (double)stringWidth;
  int newFontSize = (int)(labelFont.getSize() * widthRatio);
  int componentHeight = interiorPanel.getHeight();

  // Pick a new font size so it will not be larger than the height of label.
  int fontSizeToUse = Math.min(newFontSize, componentHeight);
  System.out.println("fontSizeToUse: " + fontSizeToUse);
  if (fontSizeToUse<1) {
      System.err.println("Font size less than 1!");
      System.exit(1);
  }

  // Set the label's font size to the newly determined size.
  label.setFont(new Font(labelFont.getName(), Font.BOLD, fontSizeToUse));
  label.setForeground(Color.gray);
 }
}

A: If it is this RichJLabel, then take a look at paintComponent. I would sugges making your own shadowed label, maybe consisting out of two shadow labels and one foreground label. I did not expect to see a 3 times drawing of every character. Problematic: inefficient and cannot do scripting languages like arabic or combining diacritic characters (one char letter, another accent).
At some points hacking around isn't worth it. If you had seen the sources, who knows.
I am not sure that I have the right code. It certainly might be of a very early version.

RichJLabel has a getPreferredSize() suitable for layouting. JPanel.setBounds(int, int, int, int) is the single method by which resizing is done. Hence you can use absolute layouting in a JPanel (null layout).
public class EPanel2 extends JPanel {

    private RichJLabel label = new RichJLabel("", 0);
    public EPanel2(String text) {
        super(null);
        setBackground(Color.GREEN.brighter().brighter());

        label.setFont(new Font("Univers", Font.BOLD, 48));
        label.setText(text);
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setVerticalAlignment(JLabel.CENTER);
        label.setForeground(Color.BLUE);
        label.setLeftShadow(2, 2, Color.RED);
        label.setRightShadow(2, 2, Color.ORANGE);
        label.setVisible(true);
        add(label);
    }

    @Override
    public void setBounds(int x, int y, int width, int height) {
        super.setBounds(x, y, width, height);
        Dimension labelSize = label.getPreferredSize();
        int labelX = (width - labelSize.width) / 2;
        int labelY = (height - labelSize.height) / 2;
        label.setBounds(labelX, labelY, labelSize.width, labelSize.height);
    }

}


text:
Q: How to send messages between 2 chrome tabs (from different origins) without a server or an extension? I am developing my web app in React on Chrome.
I have tried...

*

*To get a reference of the Window object of one tab from the other tab,
but I can do this only if I use window.open() witch opens a new tab and I need to get a reference to an existing tab.
Also changing window.name and then window.open('', 'windowName') didn't help.
Maybe there is a way to get the Window reference of an existing tab without opening a new one?

*To open a UDP socket but I failed to (I think it is not possible on Chrome).

*To open a TCP socket, but it requires a TCP server witch as far as I read, chrome client can't open one.

*Local storage is shareable only between tabs from same origin (or aren't they?).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tomcat load balacing/session replication performance with long polling All,
I have some doubts on the performance of clustering and session management in load balanced environnent especially when dealing with long polling where continuations are suspended and saved in the server. Here are my questions:

*

*Does all suspended connections are replicated to all tomcat instance like other session objects ?

*Does resuming a connection/continuation on one node update connections status in other nodes automatically ?

*Does keeping open connections in all nodes impact performance ? Does load distribution still have sense ?

Thanks in advance,


text:
Q: How to prevent redirect 301 I'm encountering a 301 problem from my pre-production site which is automatically redirected to my production site.
I know the problem comes from WP because I already launched a curl in order to see responses either :
1) targeting the WP pre-production-site :
> GET / HTTP/1.1
> Host: www.pre-production-site.com
> User-Agent: curl/7.53.1
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Date: Tue, 07 Mar 2017 11:51:19 GMT
< Server: Apache/2.2.22
< Location: http://www.production-site.com/
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: sameorigin
< Vary: Accept-Encoding
< Content-Length: 0
< Content-Type: text/html; charset=UTF-8
<
* Connection #0 to host www.pre-production-site.com left intact

2) targeting my own .php file uploaded on the pre-production-site :
> GET /up.php HTTP/1.1
> Host: www.pre-production-site.com
> User-Agent: curl/7.53.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 07 Mar 2017 11:54:29 GMT
< Server: Apache/2.2.22
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: sameorigin
< Vary: Accept-Encoding
< Content-Length: 2
< Content-Type: text/html; charset=UTF-8
<
42* Connection #0 to host www.pre-production-site.com left intact

I don't understand because I've already checked :

*

*.htaccess file : doesn't contain any kind of redirection

*Apache configuration files : seems OK too

*source code (if a plugin would sets a Location: header) with a recursive grep : didn't find anything

Where is set this 301 ?
I'm not sure if I left all informations that you need so feel free to ask me !
Thank you very much for your help !

A: Did you check the 'options' table in your WP databasse for the two instances of the domain name (something like 'http://www.example.com ' ).
Not clear if your pre-production site is hosted on a local machine, or networked server. Might be some firewall redirection rules causing issues.

A: Just a little clarification of @RickHellewell's answer:
To prevent Wordpress from redirecting to my live site when I copied the database to my local machine for development work, I updated two rows in the database with the following query:
UPDATE wp_options SET option_value='http://localhost' WHERE option_value='http://mylivesite.com';

This allowed me to load (and work on) my site locally by visiting http://localhost and http://localhost/wp-admin


text:
Q: HTML Form input into Javascript array My goal is to enter a single name into a html Text form. Each time I press submit
it will store that value into a javascript array.  Currently, I  am able to get
the first value I submit into the array but not the subsequent values. Hope I am
being clear enough, Any help would be great.
Here is my JavaScript

function getListOfNames() {
 "use strict";

  //Declare variables
  var form;
  var getNameValue;
  var myArray = [];
  var output;

  //Assign values
  output = document.getElementById("myTable");
  form = document.getElementById("myForm");
  getNameValue = form.getNameValue.value;

  //Each time form is submited put the new value into array

  myArray.push(getNameValue);

  //output the results

  output.innerHTML = myArray;
}

function project5Part2() {
  "use strict";

  // Your code goes in here.

   getListOfNames();

  return false;

}

Here is my HTML

<form  id="myForm" action="#"  onsubmit=" return project5Part2();" >
  Enter Name
  <input type="text" id="enteredName" name="getNameValue"/>
  <input type="submit" value="Enter Name" />
  <input type="reset"  value="Clear form - DO NOT SEND" />
</form>

A: Remove the onsubmit from the form.
change the input type="submit" into a regular button and use the onclick to execute JavaScript.
<form id="myForm" action="#" >
      Enter Name
      <input type="text" id="enteredName" name="getNameValue"/>
      <button type="button" onclick="project5Part2();">Enter Name</button>
      <input type="reset"  value="Clear form - DO NOT SEND" />
    </form>

Create or use a global array (cannot be enclosed in the method if you want to persist)
When the button is clicked, checked the value of the textbox and if not empty, add the value to the array.
var myArray = new Array();
    function project5Part2() {
        var name = document.getElementById('enteredName').value;
        if (!(typeof name === 'undefined') && name!=null && name.trim()!='') {
            myArray.push(name);
        }
        console.log(myArray);
        document.getElementById('enteredName').value = '';
    }

Will log the contents of the array each time the button is clicked.
For example: ["albert", "manny", "susan"]
The textbox value is being cleared each time the name is added.


text:
Q: std::optional & compilers - shouldn't this crash? I'm trying to create a hiearchy of classes in which parts are optional. I would like things to automatically be created as soon as variables are set.
For that I use C++17 std::optional feature.
Now in the example below I forgot to set the "parent" (test2_inst) first, yet g++, clang and msvc all compile and run fine altough with the "not set" output.
My questions now are: am I indeed doing the wrong thing in this example? and what would the proper way of resolving this?
Or are the compilers doing the wrong thing?
#include <optional>

class test1 {
public:
        class test2 {
        public:
                int a, b;

                class test3 {
                public:
                        int c, d;
                };

                test3 test3_inst;
        };

        std::optional<test2> test2_inst;
};

int main(int argc, char *argv[])
{
        test1 *test1_inst = new test1();

        // can set value
        test1_inst->test2_inst->test3_inst.c = 3;

        // yet optional says it is note set?
        if (test1_inst->test2_inst.has_value())
                printf("set\n");
        else
                printf("not set\n");

        return 0;
}

A: The behaviour of optional::operator* and optional::operator-> is undefined if the optional does not contain a value.

Accesses the contained value.

*

*Returns a pointer to the contained value.

*Returns a reference to the contained value.

The behavior is undefined if *this does not contain a value.

Source: https://en.cppreference.com/w/cpp/utility/optional/operator*

A:
shouldn't this crash?

Could.  Undefined behavior can do anything.  Crashing is one possibility.  Not crashing and appearing to work is also a possibility.

am I indeed doing the wrong thing in this example?

Yes.

what would the proper way of resolving this?

Depends what you are trying to do.  Check the optional...
if (test1_inst->test2_inst)
    test1_inst->test2_inst->test3_inst.c = 3;

Or, assign its value...
test1_inst->test2_inst = test1::test2{1, 2, {3, 4}};

Or are the compilers doing the wrong thing?

No, the C++ standard gives the compilers a lot of latitude.
C++ is not a nanny language, and gives programmers enough rope to shoot themselves in the foot.


text:
Q: iOS Storyboard Conditionally showing Views I am currently working on a project for the iPad using Storyboards for the 1st time and I am wondering if my approach is the correct way to do this.
The first ViewController in this example is actually a split view controller.
Currently within the iPad app when a user clicks on the Export Features Button I am conditionally requesting the segue based on some code / checks I am running
    [self performSegueWithIdentifier:@"subscribe" sender:self];
    [self performSegueWithIdentifier:@"filterOptions" sender:self];
    [self performSegueWithIdentifier:@"showExportedDoc" sender:self];

However I am not sure if I should have 3 navigation controllers and also when a user clicks on the Buy button in the subscribe View Controller it pushes to the Filter Options View which is actually nested in another Navigation Controller.
Any help / advice on this would be great as I mention I am just not sure if I am following the best approach with this.
Thanks

A:
... and
  also when a user clicks on the Buy button in the subscribe View
  Controller it pushes to the Filter Options View which is actually
  nested in another Navigation Controller.

Well, I think you have some misunderstanding here. The fact that the filter options view controller is embedded within a navigation controller in your storyboard doesn't mean that it will be instantiated with the UINavigationController when you're pushing it within the current navigation controller (It will be so though if you connect the segue to the UINavigationController that it's embedded into).
To answer your original question, I don't see right and wrong approach here. It all depends on the structure you would like to have. For me, I guess I would prefer to have only one UINavigationController that manages everything (set it as an initial view controller and embed your home view controller within it). This would provide a more consistent navigation experience to the user, plus more consistent look (navigation bar would be shown from the beginning).


text:
Q: Why my IF can't get some of my ArrayList's indexes? My idea here is to check whether the elements of my ArrayList start with A, B, C, or with another letter, but for some reason, my IF can't get some words, such as "Almofada".
package ArrayLists;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class ArrayList2 {
    public static void main(String[] args) {
        //arraylist pra verificar quais strings começam com a,b,c
        ArrayList<String> words = new ArrayList<>(
        Arrays.asList(
        "Canivete",
        "Almofada",
        "Corda",
        "Parede",
        "Caixa",
        "Zilhão",
        "Dedo"
        ));

        ArrayList abc = new ArrayList<>();
        ArrayList rest = new ArrayList<>();

        for(int i = 0; i < words.size();i++){
            char firstChar = words.get(i).charAt(0);
            if(firstChar == 'A'||firstChar == 'B'||firstChar == 'C'){
                abc.add(words.get(i));
                words.remove(words.get(i));
            }else{
                rest.add(words.get(i));
                words.remove(words.get(i));
            }
        }
        System.out.println("Start with A,B or C: " + abc);
        System.out.println("Start with other letters: " + rest);
        System.out.println("Original array: " + words);
    }
}

Output
Start with A,B or C: [Canivete, Corda, Caixa]
Start with other letters: [Dedo]
Original array: [Almofada, Parede, Zilhão]

A: The problem is because of removing the words from the ArrayList, words. Remove the line, words.remove(words.get(i)) to get the desired output.
Do it as follows:
import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<>(
                Arrays.asList("Canivete", "Almofada", "Corda", "Parede", "Caixa", "Zilhão", "Dedo"));
        ArrayList abc = new ArrayList<>();
        ArrayList rest = new ArrayList<>();

        for (int i = 0; i < words.size(); i++) {
            char firstChar = words.get(i).charAt(0);
            if (firstChar == 'A' || firstChar == 'B' || firstChar == 'C') {
                abc.add(words.get(i));
            } else {
                rest.add(words.get(i));
            }
        }
        System.out.println("Start with A,B or C: " + abc);
        System.out.println("Start with other letters: " + rest);
        System.out.println("Original array: " + words);
    }
}

Using Stream API:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<>(
                Arrays.asList("Canivete", "Almofada", "Corda", "Parede", "Caixa", "Zilhão", "Dedo"));
        List<String> abc = words.stream().filter(s -> s.startsWith("A") || s.startsWith("B") || s.startsWith("C"))
                .collect(Collectors.toList());
        List<String> rest = words.stream().filter(s -> !(s.startsWith("A") || s.startsWith("B") || s.startsWith("C")))
                .collect(Collectors.toList());
        System.out.println("Start with A,B or C: " + abc);
        System.out.println("Start with other letters: " + rest);
        System.out.println("Original array: " + words);
    }
}

Output:
Start with A,B or C: [Canivete, Almofada, Corda, Caixa]
Start with other letters: [Parede, Zilhão, Dedo]
Original array: [Canivete, Almofada, Corda, Parede, Caixa, Zilhão, Dedo]

A: Once an element is removed from the ArrayList, all the elements to the right of the removed element shift to the left of one.
E.g. if you have an ArrayList A = [1, 2, 3, 4] and do A.remove(0) then the result ArrayList will NOT be A = [null, 2, 3, 4] but it will be A = [1, 2, 4].
The problem with your program lies in the failure to handle this behavior of the remove() function.
How can you handle it?
Just change the exit condition of the for-loop. Always check the first element, in your case, and exit when the ArrayList has been emptied then words.size() == 0. You don't need to increment i.

Solution
public static void main(String[] args) {
    //arraylist pra verificar quais strings começam com a,b,c
    ArrayList<String> words = new ArrayList<>(
            Arrays.asList(
                    "Canivete",
                    "Almofada",
                    "Corda",
                    "Parede",
                    "Caixa",
                    "Zilhão",
                    "Dedo"
            ));

    System.out.println("Original array: " + words + "\n");

    ArrayList<String> abc = new ArrayList<>();
    ArrayList<String> rest = new ArrayList<>();

    for (int i = 0; words.size() > 0;) {
        char firstChar = words.get(i).charAt(0);
        if (firstChar == 'A' || firstChar == 'B' || firstChar == 'C') {
            abc.add(words.get(i));
        } else {
            rest.add(words.get(i));
        }
        words.remove(words.get(i));
    }
    System.out.println("Start with A,B or C: " + abc);
    System.out.println("Start with other letters: " + rest);
}

Another problem is when you try to print the original ArrayList at the end of the program.
Careful!
The ArrayList words has been emptied so you will print an empty ArrayList. For this you can print it at the beginning or do something else.

Sample Output
Original array: [Canivete, Almofada, Corda, Parede, Caixa, Zilhão, Dedo]

Start with A,B or C: [Canivete, Almofada, Corda, Caixa]
Start with other letters: [Parede, Zilhão, Dedo]

A: Your issue is with your for loop. You are incrementing the index 'i' on each iteration of the loop, then removing the word at words(i). Because i gets incremented, but the size of the words list is reduced each iteration, 'i' quickly increases to the new size of the words list without actually evaluating the Strings at the end.
To correct, you simply need to avoid incrementing i on each iteration:
for(int i = 0; i < words.size();){ //Notice i is not being incremented (i++)
    char firstChar = words.get(i).charAt(0);
    if(firstChar == 'A'||firstChar == 'B'||firstChar == 'C'){
        abc.add(words.get(i));
    }else{
        rest.add(words.get(i));
    }
    words.remove(words.get(i));
}


text:
Q: behavior while loop in c programming output in this case is 1
int main() {
    int i = 500;
    while( (i++) != 0 );
    printf("%d\n", i);
    return;
}

output in this case is 0
int main() {
    int i = 500;
    while( (i=i+1) != 0 );

    printf("%d\n", i);
    return;
}

I'm Not sure why  get this different output in every case I mean why 1 in first case and 0 at second case

A: For starters the both programs have undefined behavior. Instead of declaring the variable i as having the signed integer type int you should declare it as having the unsigned integer type unsigned int to make the programs correct.
This while loop
while( (i++) != 0 );

stops its iterations when the expression i++ is equal to 0. So when the variable i is equal to 0 the loop stops. But due to the postfix increment operator its value is incremented and becomes equal to 1.
According to the C Standard (6.5.2.4 Postfix increment and decrement operators)

2 The result of the postfix ++ operator is the value of the operand.
As a side effect, the value of the operand object is incremented (that
is, the value 1 of the appropriate type is added to it).

This while loop
while( (i=i+1) != 0 );

also stops its iterations when i is equal to 0 after the assignment i = i + 1.


text:
Q: Table cell constraints breaking on row insert I have a UICollectionView in a table view cell. I've put a few constraints on the cell to make the UICollectionView a square. A button in the cell above will insert another view, effectively pushing the UICollectionView cell to move down to make room for the new cell. When I do this, the constraints on the UICollectionView seem to be ignored.
The code can be found here.
Why would the constraints decide to be ignored when I insert a row? What should I call to keep the constraints? I've tried re-adding the constraints and calling layoutIfNeeded(), but that didn't add them back.
Edit: Some images to show what is going on
Before:

After:

A: Turns out the problem came from mixing frames with constraints. In the GameboardCell class, I overrode layoutSubviews to include setting the gameboard's frame. Later, I set the constraints programatically. By removing the frame, the constraints hold up.
    override func layoutSubviews() {
        super.layoutSubviews()
        //gameboard?.frame = self.contentView.bounds
    }

Lesson of the day: Don't mix frames with constraints.


text:
Q: Is Rust trait the same as Java interface It looks to me that Rust's trait is the same thing as Java's interface - a set of functions that needs to be implemented on object.
Is there a technical reason for naming it trait not interface or is it just some preference?

A: Interface is a concept of Object Oriented Programming. When you say that an object type implements an interface, you are talking about a property of that type. It says that the type follows certain contract.
Rust is not an object oriented language. And traits are not exactly interfaces. When you say, that a struct has some trait, it does not necessarily mean, that it is a property of the struct, but rather that struct maps with the functionality of the trait.
For example, you can have a built-in rust type [f32; 2] - an array with two values. And you can have a trait Point:
trait Point {
  fn x(&self) -> f32;
  fn y(&self) -> f32;
}

As the author of the trait, you can decide that the type [f32; 2] maps well to the functionality of this trait. And you can implement this trait for the type:
impl Point for [f32; 2] {
  fn x(&self) -> f32 { self[0] }
  fn y(&self) -> f32 { self[1] }
}

By doing so you didn't change the type itself, but rather said that it has your trait.
This is one thing you cannot do with interfaces but can do with traits. I believe that the name trait was chosen rather then interface for rust to emphase this distinction and prevent confusion of concepts.

A: Rust traits and Java interfaces both address the problem of having multiple possible implementations that adhere to some convention/protocol/interface for interacting with a value/object, without constraining the implementation details as a Java superclass does. They can be used in many of the same situations. However, they are different in many details, mostly meaning that Rust traits are more powerful:

*

*Java interfaces require that the implementing object have methods with specific names. Each Rust trait has a completely separate namespace. In Java, two interfaces might be impossible to implement together:
interface Foo {
  void someMethod();
}
interface Bar {
  int someMethod();
}
class TwoInterfaces implements Foo, Bar {
  public int someMethod();  // The return type must be void and also must be int
}

In Rust, when you implement a trait for a type, you do so with a separate impl block specifying that trait, so it is explicit which trait each method/function belongs to. This means that implementing a trait for a type cannot conflict with a different trait (except at call sites that have both traits in scope, which must disambiguate by using function syntax instead of method syntax).

*Java traits can have generics (type parameters), SomeInterface<T>, but an object can implement an interface only once.
class TwoGenerics implements Foo<Integer>, Foo<String> {
  public void someMethod(??? value) {}  // Can't implement, must be one method
}
interface Foo<T> {
  void someMethod(T value);
}

In Rust, a trait may be implemented for many types, and these are basically considered just like different traits:
struct TwoGenerics;

trait Foo<T> {
    fn some_method(&self, input: T);
}

impl Foo<i32> for TwoGenerics {
    fn some_method(&self, input: i32) {}
}
impl Foo<String> for TwoGenerics {
    fn some_method(&self, input: String) {}
}

To get Java-like behavior of requiring there to be one particular type for any implementing type, you can define an associated type instead of a generic:
struct Thing;

trait Foo {
    type Input;
    fn some_method(&self, input: Self::Input);
}

impl Foo for Thing {
    type Input = i32;
    fn some_method(&self, input: i32) {}
}

*In Rust, a trait may be implemented for a type you didn't define, if you defined the trait. Thus, you can define a trait in your crate and then implement it for relevant types in the standard library (or other libraries you depend on), such as for serialization, random generation, traversal, etc. In Java, workarounds such as run-time type checks are required to achieve similar results.

*In Rust, a trait may have a generic implementation that applies to all types meeting some criteria (bounds), or an implementation that applies to a particular generic type only when its parameters are suitable. For example, in the standard library, there is (approximately)
impl<T> Clone for Vec<T> where T: Clone {...}

so a Vec is clonable if and only if its contents are. In Java, a class cannot conditionally implement an interface, which is problematic for any recursive property: for example, list instanceof Serializable might be true while the list will fail to serialize because one or more of its elements is not serializable.

*Rust traits may have associated constants, types, and non-method functions (analogous to Java static methods), all of which may be different for each implementing type. When Java interfaces have static members, they have only one implementation for the entire interface.
For example, the Default trait in Rust allows constructing a new instance of any implementing type by calling Default::default() or T::default(). In Java, you need to create an interface implemented by separate "factory" classes to do this (but then the factories can have their own state/data, so you might still choose to use a factory trait and types in Rust).

*Rust traits can have functions which accept multiple inputs (or produce outputs) that are also of the implementing type. Java interfaces cannot refer to the implementing type; they can only add a type parameter that isn't required to be the same. (On the other hand, Java has subclassing (subtyping) where Rust doesn't, and so the situation is necessarily more complicated when you have a collection of instances of different concrete type but the same supertype.)
There's probably many more details that could be mentioned, but I think these cover a lot of the ways in which you can or must use them differently even though they are meant for the same tasks.

As to the name "trait" versus "interface", this is due to an existing concept of traits in computer science which are considered to have several specific properties, mostly that there is no inheritance and no overriding involved in implementing and using traits. This is closely related to the "separate namespace" I mentioned above.


text:
Q: ggplot2 plotly faceted chart colors in legends I have a ggplot2 graph that is then driving a plotly chart.  I am using the stock diamonds data set and am getting some wonkyness in the legends.  I want the legend to ONLY show colorizing for the colors.  It appears to be trying to take each clarity from each facet and merge into the legend.
How can I get the legend to only show the colors of the the clarities once?  Note: I tried removing size already :)
Below is the code and image of what is produced.
d = diamonds %>% sample_frac(.01)
p = d %>%
  ggplot(aes(x = carat, y = price)) +
  geom_point(aes(size = depth, color = clarity)) +
  facet_wrap(~cut)
ggplotly(p)

A: This ended up being a bug in the plotly rendering of the graphic, which has been resolved in the latest version of plotly.  The solution is to terminate your R session, reinstall your plotly packages and then pull in the updated library.


text:
Q: Elegant way to force two array elements when splitting a string Assume the following string:
$string = 'entry1_entry2';

What I want to do is something like this:
list($entry1, $entry2) = explode('_', $string);

My question now is are there any elegant ways to force the explode (or any other function) to get 2 array items minimum? You could specify a third parameter to get a maximum of 2 elements but I want a minimum. If there would be a string like this:
$string = 'entry1';

The second line would give a NOTICE because there is only one array element. The best would be a way without checking the resulting array or the string for the presence of the seperator.

A: You could probably use array_pad:
list($entry1, $entry2) = array_pad(explode('_', $string), 2, NULL);

See array_pad

A: I'd suggest that storing the explode inside multiple variables is just bad practice, when you can't enforce the integrity of your data.
Should you not simply be using
$entries = explode($string);

and avoid all the unnecessary complications?


text:
Q: Remove one or more dots at beginning of string How can I remove the dot that starts a string?
$string = ". Hello world .";

I only want to remove the first dot, not the dot at the end.

A: Simple pattern would match any period (or sequence, since you suggested this) at the start of a string, or (following a request from the OP in the comments below) at the end of the string:
preg_replace( "/^\.+|\.+$/", "", "....Hello...." );

Demo: http://codepad.org/Nst5EX1k

A: Using $stripped = trim($string, ' .'); is probably better and strips any space or dot.

A: ltrim('. Hello World! .','.');

A: It seems to me that you're using PHP. Try:
$string = ". Hello World! .";
$pos = strrpos($string, ".");
$stripped = substr($string, $pos + 1);


text:
Q: How to sort colors in two dimensions? I am currently working on a hobby project to automatically solve a puzzle from the popular mobile game I Love Hue. The game is available here.
Basically, the whole premise of the game is that you're given a bunch of colored rectangular blocks organized in a grid. You can swap most of the blocks except for a few fixed blocks, which are marked by black dots. The object of the game is to swap the blocks around so you get a two-dimensional spectrum of color. The colors are sorted such that the color of each block is approximately the average of the colors around it. (Sorry, I don't know any color theory but there's probably a word for what I'm looking for.) Here's what a typical puzzle looks like:

I have already been able to take screenshots through adb, extract the RGB matrix from the blocks and mark which blocks are "fixed". I'm having trouble with the actual algorithmic part of this problem.
Here's what I've done so far:

*

*Converting the RGB to HSV and sorting the colors by hue in a one-dimensional list. This gives me a spectrum, but I do not know how to convert this result into two dimensions.

*Leaving the colors in RGB and attempting to work with a singular color. There's probably some multivariable calculus I could do here, but the difficulty lies in the fact that some colors share one or more of their RGB values. It would be necessary to consider all three colors.

*Using Euclidean distance to find the distance between each pair of colors. I understand that the final goal is to have this distance to be the smallest among adjacent colors, but the two-dimensional grid is making this more difficult.

*Using Euclidean distance, I have developed a metric for how ideal a certain grid is by looking at the Euclidean distance of the colors of adjacent blocks. However, I cannot find an efficient algorithm that can figure out the swaps necessary to get to an ideal state.

A: If you have more solved images you could create RGB graphs plot
so plot the 3D graph where x,y is pixel position and z is inspected color channel (R,G or B). From it you can determine some properties of the gradients. If the plot is a plane than all you need is just the normal (taken from 3 known cells). If it is curved surface depending on how many inflex points it got you can determine how big polynomial was used for it. From all this you can start solving this.
I would start with something simple (assuming not too big gaps or fancy polynomials):
Handle each color channel separately. I would use just the static tiles and interpolate the grid colors only from them. Something similar to:

*

*Interpolating 3D Coordinates between known missing time intervals
Without seeing the R,G,B graphs I can not estimate which kind of interpolation you need. If the graphs are linear use bi-linear or linear interpolation. If not use higher degree polynomials.
So fill in any grid cells that you can (has neighbors with known color). After this find the closest movable tile to computed color (if cell has all 3 channels interpolated) and place them (and set as static).
Now just repeat the process until all the cells are computed.
[Edit1 Dec 14 2017] some additional notes and stuff
Was curious and got some time today so I gave it a shot. First I create the game in C++/VCL which took your image as input (cropped and resized). Then I sorted the tiles manually and plot the graphs:

The White dots means tile is placed correctly (match the interpolated color). The colored circles around the dots are the interpolated colors (for visual comparison you need to zoom to see them).
As you can see the R,G,B 3D plots looks linear so (bi)linear interpolation should be enough.
If I tried just linear interpolation for rows only the solver solves the puzzle immediately. However When I coded the same for columns (more unknown cells between known ones) the solver started to make few incorrect placings (invalidating the whole stuff hence the wrong white dots).

I Also tried HSL but after a while I throw it away due to hitting a wall because Hue can cross the 0 and 360 degree at any point which is not distinguishable from cases that did not cross. For that it would need some heuristics or cross correlation from neighboring solved areas and that would be too much coding for my taste. Without it the results where even worse then using RGB.
So now I am thinking about either using bilinear interpolation or solve the short distance interpolations first and only then solve the rest ...
[Edit2 Dec 14 2017] bilinear interpolation
Looks like bilinear RGB interpolation solves all the issues. So if your board is enclosed with fixed cells it should work. If not you need to solve the board iteratively and then use the newly solved cells as new bound for the unsolved areas. Also I realized I got RGB reversed so I also repaired that :).
Here the C++/VCL source for the game (It is not optimized at all):
//$$---- Form CPP ----
//---------------------------------------------------------------------------
#include <vcl.h>
#include <math.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
TForm1 *Form1;
bool _update=false;
//---------------------------------------------------------------------------
const _ILoveHue_state_fixed   =255<<24;
const _ILoveHue_state_unsolved=  0<<24;
const _ILoveHue_state_solved  =  1<<24;
const _ILoveHue_render_board=0;
const _ILoveHue_render_graph=1;
//---------------------------------------------------------------------------
int rgbdist(DWORD c0,DWORD c1)  // AABBGGRR
    {
    int r0,g0,b0,r1,g1,b1;
    r0=( c0     &255); r1=( c1     &255);
    g0=((c0>> 8)&255); g1=((c1>> 8)&255);
    b0=((c0>>16)&255); b1=((c1>>16)&255);
    r0-=r1; g0-=g1; b0-=b1;
    return (r0*r0)+(g0*g0)+(b0*b0);
    }
//---------------------------------------------------------------------------
class ILoveHue
    {
public:
    // variables
    bool _redraw;               // redraw needed?
    Graphics::TBitmap *bmp;     // screen buffer
    int sxs,sys,mxs,mys,gxs,gys;// screen,map,grid cell resolution
    DWORD **map,**imap;         // map[y][x] actual and interpolated
    int mx,my,mx0,my0;          // mouse position state actual and last
    TShiftState sh,sh0;         // mouse buttons and spec keys state actual and last
    int render_mode;
    // class constructors and destructors
    ILoveHue()  { bmp=new Graphics::TBitmap; bmp_resize(1,1); map=NULL; imap=NULL; mxs=0; mys=0; mx=-1; my=-1; mx0=-1; my0=-1; gxs=1; gys=1; render_mode=_ILoveHue_render_board; }
    ~ILoveHue() { map_free(); if (bmp) delete bmp; }
    ILoveHue(ILoveHue& a)   { *this=a; }
    ILoveHue* operator = (const ILoveHue *a) { *this=*a; return this; }
    //ILoveHue* operator = (const ILoveHue &a) { ...copy... return this; }

    // game/Window API and stuff
    void map_free()                             // relese map
        {
        if ( map) { if ( map[0]) delete[]  map[0]; delete[]  map; }  map=NULL; mxs=0; mys=0;
        if (imap) { if (imap[0]) delete[] imap[0]; delete[] imap; } imap=NULL;
        }
    void map_resize(int x,int y)                // resize/allocate map
        {
        _redraw=true;
        if ((x==mxs)&&(y==mys)) return; map_free();
         map=new DWORD*[y]; if ( map==NULL) return;  map[0]=new DWORD[x*y]; if ( map[0]==NULL) return;
        imap=new DWORD*[y]; if (imap==NULL) return; imap[0]=new DWORD[x*y]; if (imap[0]==NULL) return;
        mxs=x; mys=y; for (x=mxs,y=1;y<mys;y++,x+=mxs) { map[y]=map[0]+x; imap[y]=imap[0]+x; }
        if (mxs) gxs=sxs/mxs; else gxs=1;
        if (mys) gys=sys/mys; else gys=1;
        }
    void bmp_resize(int x=-1,int y=-1)          // resize bmp
        {
        _redraw=true;
        if ((x>=0)&&(y>=0)) bmp->SetSize(x,y);
        bmp->HandleType=bmDIB;
        bmp->PixelFormat=pf32bit;
        sxs=bmp->Width;
        sys=bmp->Height;
        if (mxs) gxs=sxs/mxs; else gxs=1;
        if (mys) gys=sys/mys; else gys=1;
        }
    void bmp_load(AnsiString file)              // init game from image (map must be resized already)
        {
        _redraw=true;
        // load file
        bmp->LoadFromFile(file);
        bmp_resize();
        // convert to map
        int x,y;
        DWORD *p,c;
        for (y=0;y<mys;y++)
         for (p=(DWORD*)bmp->ScanLine[(y*gys)+(gys>>1)],x=0;x<mxs;x++)
            {
            c=p[(x*gxs)+(gxs>>1)+4]&0x00FFFFFF;         // near mid point (0<<24 is unsolved state)
            c=((c>>16)&0x000000FF)                      // RGB -> BGR (file has reverse RGB order than bmp)
             |((c<<16)&0x00FF0000)
             |( c     &0x0000FF00);
            map[y][x]=c;
            c=p[(x*gxs)+(gxs>>1)]&0x00FFFFFF;           // mid point
            if ((((c)|(c>>8)|(c>>16))&255)<64)          // ~max(R,G,B)<32
             map[y][x]|=_ILoveHue_state_fixed;
            }
        }
    void mouse(int x,int y,TShiftState s)       // handle mouse
        {
        _redraw=true;
        mx=x/gxs;
        my=y/gys;
        sh0=sh; sh=s;
        bool q0=sh0.Contains(ssLeft);
        bool q1=sh .Contains(ssLeft);
        if ((!q0)&&( q1)){ mx0=mx; my0=my; }    // mouse left button down
        if (( q0)&&(!q1))                       // mouse left button up (swap)
            {
            // swap if valid coordinates
            if ((mx0>=0)&&(mx0<mxs)&&(my0>=0)&&(my0<mys)) if (DWORD(map[my0][mx0]&0xFF000000)!=_ILoveHue_state_fixed)
             if ((mx >=0)&&(mx <mxs)&&(my >=0)&&(my <mys)) if (DWORD(map[my ][mx ]&0xFF000000)!=_ILoveHue_state_fixed)
                {
                DWORD c=map[my0][mx0]; map[my0][mx0]=map[my][mx]; map[my][mx]=c;    // swap cells
                map[my0][mx0]&=0x00FFFFFF; map[my0][mx0]|=_ILoveHue_state_unsolved; // set them as unsolved
                map[my ][mx ]&=0x00FFFFFF; map[my ][mx ]|=_ILoveHue_state_unsolved;
                map_solve(false);                                                   // check for solved state
                }
            // clear selection
            mx0=-1; my0=-1;
            }
        }
    void draw()                                 // render game
        {
        _redraw=false;
        int x,y,z,x0,x1,x2,y0,y1,y2,r;
        DWORD c;
        if (render_mode==_ILoveHue_render_board)
            {
            for (y0=0,y1=gys,y2=gys>>1,y=0;y<mys;y++,y0+=gys,y1+=gys,y2+=gys)
             for (x0=0,x1=gxs,x2=gxs>>1,x=0;x<mxs;x++,x0+=gxs,x1+=gxs,x2+=gxs)
                {
                c=map[y][x];
                bmp->Canvas->Pen->Color=TColor(c&0x00FFFFFF);
                if ((x==mx )&&(y==my )) bmp->Canvas->Pen->Color=clYellow;
                if ((x==mx0)&&(y==my0)) bmp->Canvas->Pen->Color=clGreen;
                bmp->Canvas->Brush->Color=TColor(c&0x00FFFFFF);
                bmp->Canvas->Rectangle(x0,y0,x1,y1);

                if (DWORD(c&0xFF000000)!=_ILoveHue_state_fixed)
                    {
                    r=10;
                    bmp->Canvas->Pen->Color=imap[y][x]&0x00FFFFFF;
                    bmp->Canvas->Brush->Style=bsClear;
                    bmp->Canvas->Ellipse(x2-r,y2-r,x2+r,y2+r);
                    bmp->Canvas->Brush->Style=bsSolid;
                    }

                if (DWORD(c&0xFF000000)!=_ILoveHue_state_unsolved)
                    {
                    if (DWORD(c&0xFF000000)==_ILoveHue_state_fixed ) c=clBlack;
                    if (DWORD(c&0xFF000000)==_ILoveHue_state_solved) c=clWhite;
                    r=4;
                    bmp->Canvas->Pen->Color=c;
                    bmp->Canvas->Brush->Color=c;
                    bmp->Canvas->Ellipse(x2-r,y2-r,x2+r,y2+r);
                    }
                }
            }
        if (render_mode==_ILoveHue_render_graph)
            {
            bmp->Canvas->Pen->Color=clBlack;
            bmp->Canvas->Brush->Color=clBlack;
            bmp->Canvas->Rectangle(0,0,sxs,sys);
            r=13; x0=15; y0=sys-15;
            int c=r*double(256.0*cos(55.0*M_PI/180.0));
            int s=r*double(256.0*sin(55.0*M_PI/180.0));
            bmp->Canvas->Pen->Color=clRed;
            for (y=0;y<mys;y++)
             for (x=0;x<mxs;x++)
                {
                z=(map[y][x])&255;
                x1=x0+(x*r)+((y*c)>>8);
                y1=y0      -((y*s)>>8);
                bmp->Canvas->MoveTo(x1,y1);
                bmp->Canvas->LineTo(x1,y1-z);
                } x0=x1+5;
            bmp->Canvas->Pen->Color=clGreen;
            for (y=0;y<mys;y++)
             for (x=0;x<mxs;x++)
                {
                z=(map[y][x]>>8)&255;
                x1=x0+(x*r)+((y*c)>>8);
                y1=y0      -((y*s)>>8);
                bmp->Canvas->MoveTo(x1,y1);
                bmp->Canvas->LineTo(x1,y1-z);
                } x0=x1+5;
            bmp->Canvas->Pen->Color=clBlue;
            for (y=0;y<mys;y++)
             for (x=0;x<mxs;x++)
                {
                z=(map[y][x]>>16)&255;
                x1=x0+(x*r)+((y*c)>>8);
                y1=y0      -((y*s)>>8);
                bmp->Canvas->MoveTo(x1,y1);
                bmp->Canvas->LineTo(x1,y1-z);
                }

            }
        }
    // Solver
    void map_solve(bool _solve) // check for solved state and try to solve if _solve is true
        {
        _redraw=true;
        const int _thr=10;  // color comparison threshold
        int x,y,x0,x1,y0,y1,xx,yy;
        int r0,g0,b0,r,g,b;
        int r1,g1,b1;
        int r2,g2,b2;
        int r3,g3,b3;
        DWORD c;

        // compute interpolated colors to imap (wanted solution)
        for (x=0;x<mxs;x++)
         for (y=0;y<mys;y++)
          if (DWORD(map[y][x]&0xFF000000)!=_ILoveHue_state_fixed)
            {
            for (x0=-1,xx=x;xx>= 0;xx--) if (DWORD(map[y][xx]&0xFF000000)==_ILoveHue_state_fixed){ x0=xx; break; }
            for (x1=-1,xx=x;xx<mxs;xx++) if (DWORD(map[y][xx]&0xFF000000)==_ILoveHue_state_fixed){ x1=xx; break; }
            for (y0=-1,yy=y;yy>= 0;yy--) if (DWORD(map[yy][x]&0xFF000000)==_ILoveHue_state_fixed){ y0=yy; break; }
            for (y1=-1,yy=y;yy<mys;yy++) if (DWORD(map[yy][x]&0xFF000000)==_ILoveHue_state_fixed){ y1=yy; break; }
            c=0;
            if (int(x0|x1|y0|y1)>=0)
                {
                // bilinear interpolation
                c=map[y0][x0]; r0=c&255; g0=(c>>8)&255; b0=(c>>16)&255;
                c=map[y0][x1]; r1=c&255; g1=(c>>8)&255; b1=(c>>16)&255;
                c=map[y1][x0]; r2=c&255; g2=(c>>8)&255; b2=(c>>16)&255;
                c=map[y1][x1]; r3=c&255; g3=(c>>8)&255; b3=(c>>16)&255;
                r0=r0+(r1-r0)*(x-x0)/(x1-x0);
                g0=g0+(g1-g0)*(x-x0)/(x1-x0);
                b0=b0+(b1-b0)*(x-x0)/(x1-x0);
                r1=r2+(r3-r2)*(x-x0)/(x1-x0);
                g1=g2+(g3-g2)*(x-x0)/(x1-x0);
                b1=b2+(b3-b2)*(x-x0)/(x1-x0);
                r =r0+(r1-r0)*(y-y0)/(y1-y0);
                g =g0+(g1-g0)*(y-y0)/(y1-y0);
                b =b0+(b1-b0)*(y-y0)/(y1-y0);
                c=(r)+(g<<8)+(b<<16);
                }
            imap[y][x]=c;
            }

        // compute solved state
        for (x=0;x<mxs;x++)
         for (y=0;y<mys;y++)
          if (DWORD(map[y][x]&0xFF000000)!=_ILoveHue_state_fixed)
            {
            map[y][x]&=0x00FFFFFF;
            if (rgbdist(map[y][x],imap[y][x])<_thr) map[y][x]|=_ILoveHue_state_solved;
             else                                   map[y][x]|=_ILoveHue_state_unsolved;
            }

        // solver/checker
        if (_solve)
            {
            // process all unsolved cells
            for (x=0;x<mxs;x++)
             for (y=0;y<mys;y++)
              if (DWORD(map[y][x]&0xFF000000)==_ILoveHue_state_unsolved)
               // find match in unsolved cells
               for (xx=0;xx<mxs;xx++)
                for (yy=0;yy<mys;yy++)
                 if (DWORD(map[yy][xx]&0xFF000000)==_ILoveHue_state_unsolved)
                  if (rgbdist(map[yy][xx],imap[y][x])<_thr)
                    {
                    // swap if found
                    c=map[yy][xx];
                    map[yy][xx]=map[y][x];
                    map[y][x]=(c&0x00FFFFFF)|_ILoveHue_state_solved;
                    }
            }
        }
    } gam;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner):TForm(Owner)
    {
    gam.map_resize(7,9);
    gam.bmp_load("map.bmp");
    gam.map_solve(false);
    _update=true;
    ClientWidth=gam.sxs;
    ClientHeight=gam.sys;
    _update=false;
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormDestroy(TObject *Sender)
    {
    gam.render_mode=_ILoveHue_render_board;
    gam.draw();
    gam.bmp->SaveToFile("map.bmp");
    }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint(TObject *Sender){ gam.draw(); Canvas->Draw(0,0,gam.bmp); }
void __fastcall TForm1::FormResize(TObject *Sender){ if (_update) return; gam.bmp_resize(ClientWidth,ClientHeight); }
void __fastcall TForm1::Timer1Timer(TObject *Sender){ if (gam._redraw) FormPaint(Sender); }
void __fastcall TForm1::FormMouseMove(TObject *Sender, TShiftState Shift, int X, int Y){ gam.mouse(X,Y,Shift); }
void __fastcall TForm1::FormMouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y){ gam.mouse(X,Y,Shift); }
void __fastcall TForm1::FormMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y){ gam.mouse(X,Y,Shift); }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
    {
    if (Key=='S') gam.map_solve(true);                      // try to solve
    if (Key=='M') { gam.render_mode^=1; gam._redraw=true; } // swap render modes
    if (Key==115) gam.bmp->SaveToFile("screenshot.bmp");    // [F4] screenshot
    }
//---------------------------------------------------------------------------

It is a single Form App in BDS2006 with single 40ms Timer on it. So just add the events ... You can ignore the VCL rendering and window stuff. The important thing is the class and the solve() function in it. It is used for both correct placing check and for solving (depending on the _solve bool). This is the input image map.bmp

I did not code appropriate save/load state functions instead I chose to use the bitmap itself directly (waste of space but almost no code effort).
The map itself is 2D 32bit DWORD array with form of SSBBGGRR hex where SS is the flag of the cell (fixed/solved/unsolved).
Here compiled demo with the source code

*

*Win32 demo
Read the readme.txt for more info. Here result after solving (pressing [S]):

As you can (not) see the circles vanish as the bilinearly interpolated color matches more closely your input.
Program is expecting grid of size 7x9 the resolution of image is not important. The color is sampled from mid point of cell (black dot) and slightly to the right (the tile color)
To make this efficient you can make 2 things:

*

*add/use list containing unsolved cells
instead of itearting over whole map iterate only through list of unsolved cells.

*convert T(N^2) searches to T((N^2)/2) by triangle search
This is still O(N^2) however but the constant time is smaller.

*use 3D RGB LUT table
for large grids you can create 32K entries 3D LUT table to find the searched matching cell in O(1). Simply convert RGB to 15 bit color and use
DWORD LUT[32][32][32];

where LUT[r][g][b]=row+(column<<16); Tis way you will know where each color is placed. All the unused colors set to 0xFFFFFFFF. Here an example of using this technique for similar purpose:

*

*Effective gif/image color quantization?
Look for recolor[32][32][32] in the code... Of coarse 15bit color may be not enough for this purpose so may be you would need more bits like 18bit resulting in 256K entries which is still manageable.
Creating this LUT will take O(N) time but using and maintaining it is only O(1) time.

A: I don't have an idea if this would work or not. I've just wrote it for fun and could not apply a real test on it. It would be appreciated if you kindly give it a try and comment about it.
        struct pixel
        {
            public int R;
            public int G;
            public int B;
            public bool Fixed;
            public pixel(int r, int g, int b, bool _fixed)
            {
                this.R = r; this.G = g; this.B = b; this.Fixed = _fixed;
            }
            public int DistanceSQ(pixel px)
            {
                int r = this.R - px.R;
                int g = this.G - px.G;
                int b = this.B - px.B;
                return r * r + g * g + b * b;
            }
            public override string ToString()
            {
                return string.Format("{0} {1} {2} {3}", this.R, this.G, this.B, this.Fixed);
            }
            public override int GetHashCode()
            {
                return this.R.GetHashCode() ^ this.G.GetHashCode() ^ this.B.GetHashCode();
            }
            public override bool Equals(object obj)
            {
                pixel px = (pixel)obj;
                return this.R == px.R && this.G == px.G && this.B == px.B;
            }
        }
        static void sort(pixel[,] img)
        {
            List<pixel> lst = new List<pixel>();
            foreach (pixel px in img)
                if (!px.Fixed)
                    lst.Add(px);

            int rows = img.GetLength(0);
            int cols = img.GetLength(1);
            while (lst.Count > 0)
                for (int row = 0; row < rows; row++)
                    for (int col = 0; col < cols; col++)
                        if (!img[row, col].Fixed)
                        {
                            pixel[] neighbors = getFixedNeighbors(img, row, col, rows, cols).ToArray();
                            int min = int.MaxValue;
                            pixel nearest = new pixel();
                            foreach (pixel n in lst)
                            {
                                int dist = neighbors.Select((a) => a.DistanceSQ(n)).Sum();
                                if (dist < min)
                                {
                                    min = dist;
                                    nearest = n;
                                }
                            }
                            nearest.Fixed = true;
                            img[row, col] = nearest;
                            lst.Remove(nearest);
                            if (lst.Count == 0)
                                return;
                        }
        }
        private static IEnumerable<pixel> getFixedNeighbors(pixel[,] img, int row, int col, int rows, int cols)
        {
            for (int r = Math.Max(0, row - 1); r < Math.Min(row + 2, rows); r++)
                for (int c = Math.Max(0, col - 1); c < Math.Min(col + 2, cols); c++)
                    if (img[r, c].Fixed)
                        yield return img[r, c];

        }

        //test
        {
            bool b0 = false; bool b1 = true;//for easy editing
            {
                pixel[,] img = new pixel[3, 4];
                img[0, 0] = new pixel(0, 0, 0, b1); img[1, 0] = new pixel(0, 1, 0, b0); img[2, 0] = new pixel(0, 2, 0, b1);
                img[0, 1] = new pixel(1, 0, 0, b0); img[1, 1] = new pixel(1, 1, 0, b0); img[2, 1] = new pixel(1, 2, 0, b0);
                img[0, 2] = new pixel(2, 0, 0, b0); img[1, 2] = new pixel(2, 1, 0, b0); img[2, 2] = new pixel(2, 2, 0, b0);
                img[0, 3] = new pixel(3, 0, 0, b1); img[1, 3] = new pixel(3, 1, 0, b0); img[2, 3] = new pixel(3, 2, 0, b1);
                sort(img);
            }
            {
                pixel[,] img = new pixel[3, 4];
                img[0, 0] = new pixel(0, 0, 0, b1); img[1, 0] = new pixel(0, 1, 0, b0); img[2, 0] = new pixel(0, 2, 0, b1);
                img[0, 1] = new pixel(2, 0, 0, b0); img[1, 2] = new pixel(2, 1, 0, b0); img[2, 2] = new pixel(2, 2, 0, b0);
                img[0, 2] = new pixel(1, 0, 0, b0); img[1, 1] = new pixel(1, 1, 0, b0); img[2, 1] = new pixel(1, 2, 0, b0);
                img[0, 3] = new pixel(3, 0, 0, b1); img[1, 3] = new pixel(3, 1, 0, b0); img[2, 3] = new pixel(3, 2, 0, b1);
                sort(img);
            }
        }

Code is simple. It keeps the not-rated ones in a list and remove each when the location is found for it. For deciding which color should be choosen for a location, color that has the minimum sum of square distance is choosen. Sqrt is not required since we only need it for comparison.
"sort" is the main function that changes the locations of the not fixed pixels. The input for this function is a row-col array of pixels. "sort" function make changes on this array.


text:
Q: Generate random human understandable ID for users in rails I want to generate a unique (human recognisable) id for each user that changes when they comment on different posts in my app. (so doesn't need to be stored in db as is constantly changing). The ID only needs to be used within the scope of a thread.
What I mean by this is identical to what YikYak does. In YikYak, anonymity is essential, so in each thread, users are assigned a randomly generated avatar which is the only way they and other people recognise which posts are posted from the same user.
I'm building an app where I too need anonymity, but I need users to be able to recognise when other people are commenting more than once.
What is the best thing to generate? A string of 2 random words like "Brocolli umbrella"? Or is there a way to randomly generate a simple avatar?
Any advice much appreciated

A: You might try ffaker gem and use
FFaker::Name.name
#=> "Christophe Bartell"


text:
Q: How can I use gcm data payload to launch my app when my app stopped I can receive message google-cloud-messaging data payload when my app is active, but when the app is not active I do not receive messages.
My device is android, when app is alive,send notification or data message. It worked.
but when app is not alive, sent data message, it doesn't work.
Is there any way to use the data payload message to activate the intent and receive the message when my app is not alive?
there is my code, according to the demo:
public class AgooGcmListenerService extends GcmListenerService{

    public final static String TAG = "AgooGcmListenerService";

    private AgooFactory agooFactory;

    @Override
    public void onMessageSent(String msgId) {
        super.onMessageSent(msgId);
    }

    @Override
    public void onSendError(String msgId, String error) {
        ALog.e(TAG, "onSendError,msgId=" + msgId + ",error=" + error);
        super.onSendError(msgId, error);
    }

    @Override
    public void onDeletedMessages() {
        super.onDeletedMessages();
    }

    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        ALog.d(TAG, "From: " + from);
        ALog.d(TAG, "Message: " + data.toString());
        if(TextUtils.isEmpty(message)){
            return;
        }
        byte[] msg = message.getBytes();
        Context mContext = getApplicationContext();
        agooFactory = new AgooFactory();
        agooFactory.init(mContext, null, null);
        agooFactory.msgRecevie(msg,
                AgooConstants.MESSAGE_SYSTEM_SOURCE_GCM);
        Intent intent = new Intent();
        intent.setAction("org.agoo.android.intent.action.PING_V4");
        intent.setClassName(mContext.getPackageName(),ProxyFactroy.getChannelService(mContext));
        intent.putExtra("source", "accs-bundle");
        mContext.startService(intent);
    }
}

there is my config:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_ADDED" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_CHANGED" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_INSTALL" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_REPLACED" />
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />

<service
        android:name="org.android.agoo.thirdPush.AgooGcmListenerService"
        android:process=":channel"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

    <!-- [START gcm_receiver] -->
    <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"

        android:exported="true"
        android:process=":channel"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.taobao.taobao" />
        </intent-filter>
    </receiver>

    <service
        android:name="org.android.agoo.thirdPush.AgooInstanceIDListenerService"

        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID"/>
        </intent-filter>
    </service>


text:
Q: How does a shell execute a program? If I compile a program using gcc, and try to execute it from the bash shell, what is the exact sequence of steps followed by bash to execute it ?
I know fork(), execve(), loader, dynamic linker (and other things) are involved, but can someone give an exact sequence of steps and some suitable reading reference ?
Edit:
From the answers, it seems the question could imply many possibilities. I want to narrow down to a simple case:
(test.c just prints hello world)
$ gcc test.c -o test
$ ./test

What will be the steps in the above case (./test), specifically relating bash starting program in some child process, doing loading, linking etc. ?

A: Well, the exact sequence may vary, as there might be a shell alias or function that first gets expanded/interpreted before the actual program gets executed, and then differences for a qualified filename (/usr/libexec/foo) versus something that will be looked for through all the directories of the PATH environment variable (just foo). Also, the details of the execution may complicate matters, as foo | bar | zot requires more work for the shell (some number of fork(2), dup(2), and, of course, pipe(2), among other system calls), while something like exec foo is much less work as the shell merely replaces itself with the new program (i.e., it doesn't fork). Also important are process groups (especially the foreground process group, all PIDs of which eat SIGINT when someone starts mashing on Ctrl+C, sessions, and whether the job is going to be run in the background, monitored (foo &) or background, ignored (foo & disown). I/O redirection details will also change things, e.g., if standard input is closed by the shell (foo <&-), or whether a file is opened as stdin (foo < blah).
strace or similar will be informative about the specific system calls made along this process, and there should be man pages for each of those calls. Suitable system level reading would be any number of chapters from Stevens's "Advanced Programming in the UNIX Environment" while a shell book (e.g., "From Bash to Z Shell") will cover the shell side of things in more detail.

A: Assuming a textbook example shell (for code clarity) that is already running (so the dynamic  linker is done), the commands you mention will require the shell to make the following system calls:

*

*read: gets the next command in this case gcc

*fork: two process are needed, we assume the parent has pid 500 and the child for illustration.

*the parent will call wait(501), meanwhile the child will call exec. At this point the shell is no longer running on pid 501. gcc makes lots of system calls including at a minimum open, close, read, write, chmod, fork, exec,  wait and exit.

*when gcc calls exit, wait will return, write is called to display the prompt and the process will repeat.

More complicated commands of course add more complication to this basic sequence. Two  simpler examples of basic complications are basic io redirection where a open, close, dup sequence is inserted between the fork and the exec and background processes where the wait  is skipped (and another wait is added to a sigchld handler).

A: I suggest reading Section 8.4.6 Using fork and execve to Run Programs
on
http://www.groupes.polymtl.ca/inf2610/documentation/ComputerSystemBook.pdf


text:
Q: PHP prevent header overwriting by Proxy I want to access a PHP script hosted on dnsserver.icu via this proxy 207.154.231.211:8080 with curl.
The problem is that the Proxy server seems to do overwrite the HTTP 200 code with a 302 code making it impossible to reach the script.
curl -v dnsserver.icu gives the following output:
* Rebuilt URL to: dnsserver.icu/
*   Trying 134.122.73.150...
* TCP_NODELAY set
* Connected to dnsserver.icu (134.122.73.150) port 80 (#0)
> GET / HTTP/1.1
> Host: dnsserver.icu
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Wed, 15 Apr 2020 20:05:18 GMT
< Server: Apache/2.4.29 (Ubuntu)
< Content-Length: 31
< Content-Type: text/html; charset=UTF-8
<
* Connection #0 to host dnsserver.icu left intact

whereas curl -v -x 207.154.231.211:8080 dnsserver.icu gives the unexpected result of:
* Rebuilt URL to: dnsserver.icu/
*   Trying 207.154.231.211...
* TCP_NODELAY set
* Connected to 207.154.231.211 (207.154.231.211) port 8080 (#0)
> GET http://dnsserver.icu/ HTTP/1.1
> Host: dnsserver.icu
> User-Agent: curl/7.58.0
> Accept: */*
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 302 Found
< Location: http://206.189.153.135
< Date: Wed, 15 Apr 2020 20:08:37 GMT
< Connection: keep-alive
< Transfer-Encoding: chunked
<
* Connection #0 to host 207.154.231.211 left intact

The address in the Location header is also changing sometimes.
I already experimented with different header configurations but I couldn't get it to work. When I log every call to the PHP script it doesn't look like the server is even reached by the proxy (no call logged). Futhermore the apache access log is empty.
Strangely this is not the case for all domains. I'm able to access e.g. ip-api.com, google.com or also less popular domains like proxyjudge.us (but not the ip equivalent of 45.33.35.141) through the proxy.
I have no idea what the reason for this behaviour is. Is there any 'trick' in terms of header setting or apache configuration that makes it possible to also access dnsserver.icu through this proxy? Something I havent tought of?
I appreciate any help.


text:
Q: results from different functions to make a receipt I need help with printing a receipt for my program, so basically, the user will enter their personal details into the program and I tried to make the validation perfect by using the functions below but the problem is that when I use those functions for validtion, I don't know how to get the correct info from function to my receipt. I don't know how to put all that results from different functions into one receipt like how I formated at the bottom. when the receipt is printed it says that (date: None)(email: None) (phone: None) but the actual input in the receipt I have tried in many different ways is not working.
def date():
    inputDate = input("Enter the booking date in format 'dd/mm/yy' : ")

    day, month, year = inputDate.split('/')

    isValidDate = True
    try:
        datetime.datetime(int(year), int(month), int(day))
    except ValueError:
        isValidDate = False

    if(isValidDate):
        print("Input date is valid ..")
    else:
        print("Input date is not valid..")
        date()

def validateEmail(email):
    return re.match(r'[\w-]{1,20}@\w{2,20}\.\w{2,3}$', email)

def checkemail():
    email = console.input('[bright_white]Please enter your email address: [/]')
    valid = validateEmail(email)
    if valid:
        print(email, 'is valid')
    else:
        print("invalid email format", email)
        checkemail()

def phone():
    phoneno = console.input('[bright_white]Please enter your phone number :[/] ')
    patter = r"^(1|8|9)[0-9]{7}"

    if re.match(patter, phoneno) and len(phoneno) == 8:
        print("Valid")
    else:
        print("Invalid")
        phone()

def booking_form():

    bookings = []

    FirstName = input('Please enter your first name: ')
    LastName = input('Please enter your last name: ')
    Email = checkemail()
    ContactNumber = phone()
    Date = date()
    Time = input('Enter time in 00:00 AM/PM format:')
    Gym = input("Please Enter the Name of the Gym Again to Ensure that to be the Correct one:  ")
    Commentsrequest = input('Comments/Additional Request: ')

    bookings.append(FirstName)
    bookings.append(LastName)
    bookings.append(Email)
    bookings.append(ContactNumber)
    bookings.append(Date)
    bookings.append(Time)
    bookings.append(Gym)
    bookings.append(Commentsrequest)

    with open("booking.csv", 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(bookings)

    print(" Date:", date())
    print(" Time:", Time)
    print(" First Name:", FirstName)
    print(" Last Name:", LastName)
    print(" Email:", validateEmail(email))
    print(" Phone Number:", ContactNumber)
    print(" Chosen Location [Area/Gym]:", Gym)
    print(" Additional Notes/Requests:", Commentsrequest)
    print("**********************************************************************", )
    print("|         Thank You for Using the Volleyball Booking System          |", )
    print("|            You have Successfully Booked a Court/Gym                |", )
    print("|             Please Screenshot this Receipt to Keep                 |", )
    print("|                      as Proof of Booking                           |", )
    print("|          Have a Good Day, We will see you on the Court!!           |", )
    print(
        "                          ★★★★★★★★★★★★                              ")
    print("**********************************************************************", )
    exit()

A: Your functions don't return anything, so you can't print the result because it will always be None. also, why did you called the functions again when you tried to print? you don't need to do that, you already saved them before.
This is the fixed code:
import re
import datetime
import csv

def date():

    inputDate = input("Enter the booking date in format 'dd/mm/yy' : ")
    day, month, year = inputDate.split('/')
    isValidDate = True
    try:
        datetime.datetime(int(year), int(month), int(day))
    except ValueError:
        isValidDate = False

    if(isValidDate):
        return datetime.datetime(int(year), int(month), int(day))
    else:
        print("Input date is not valid..")
        date()

def validateEmail(email):
    return re.match(r'[\w-]{1,20}@\w{2,20}\.\w{2,3}$', email)

def checkemail():
    email = input('[bright_white]Please enter your email address: [/]')
    valid = validateEmail(email)
    if valid:
        return email
    else:
        print("invalid email format", email)
        checkemail()

def phone():
    phoneno = input('[bright_white]Please enter your phone number :[/] ')
    patter = r"^(1|8|9)[0-9]{7}"

    if re.match(patter, phoneno) and len(phoneno) == 8:
        return phoneno
    else:
        print("Invalid")
        phone()

def booking_form():

    bookings = []

    FirstName = input('Please enter your first name: ')
    LastName = input('Please enter your last name: ')
    Email = checkemail()
    ContactNumber = phone()
    Date = date()
    Time = input('Enter time in 00:00 AM/PM format:')
    Gym = input("Please Enter the Name of the Gym Again to Ensure that to be the Correct one:  ")
    Commentsrequest = input('Comments/Additional Request: ')

    bookings.append(FirstName)
    bookings.append(LastName)
    bookings.append(Email)
    bookings.append(ContactNumber)
    bookings.append(Date)
    bookings.append(Time)
    bookings.append(Gym)
    bookings.append(Commentsrequest)

    with open("booking.csv", 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(bookings)

    print(" Date:", Date)
    print(" Time:", Time)
    print(" First Name:", FirstName)
    print(" Last Name:", LastName)
    print(" Email:", Email)
    print(" Phone Number:", ContactNumber)
    print(" Chosen Location [Area/Gym]:", Gym)
    print(" Additional Notes/Requests:", Commentsrequest)
    print("**********************************************************************", )
    print("|         Thank You for Using the Volleyball Booking System          |", )
    print("|            You have Successfully Booked a Court/Gym                |", )
    print("|             Please Screenshot this Receipt to Keep                 |", )
    print("|                      as Proof of Booking                           |", )
    print("|          Have a Good Day, We will see you on the Court!!           |", )
    print(
        "                          ★★★★★★★★★★★★                              ")
    print("**********************************************************************", )
    exit()

booking_form()

Summary of the changes I have done:
In the date() function, instead of printing that the date is valid, I have returned  the valid email, and keep looping on the function is the date isn't valid.
I did the same with checkemail(), I have returned the valid email, and if not valid, ask the user for a valid one.
Same with phone() function.
At the printing statements at the end of the file, I just used the variable Date that you created earlier instead of calling date() function and ask the user for another date again. Same with the email.
Now it works fine (Just know that you never check the time and input can be invalid).


text:
Q: Watch the the Tasks and fetch the Task again - Vuejs I have a problem when I create a task and send it to the database. then I want the data, in other words, to fetch the tasks from the database using "Watch" (no set timeout / is there a way?
In my example here I used set timeout to update and get the list of tasks again, but I want to do it with Watch
App
var Todo = new Vue({
  el: ".container",
  data() {
    return {
      tasks: [],
      selectTask: { tasktitle: "", taskcontent: "" },
      addTask:{ tasktitle: "", taskcontent: "" },
    }
  },
  computed: {
    validatelengthleeter(){
      if(this.addTask.tasktitle.length>65)
      return "Ist zu lang"
    }
  },
    validatelengthleeterbutton(){
      if(this.selectTask.tasktitle.length>65)
      this.$refs.taskan.style.color="red"
    },
  mounted () {
    this.showTask();
  },
  methods: {

    showTask() {
      axios
        .get("http://localhost/todolistefinalauflocal/db.php?action=read")
        .then((dieDaten) => {
          console.log(dieDaten.data);

          this.tasks = dieDaten.data.tasken;
        });
    },
    createTask() {
      let formData = this.convertToFormData(this.addTask);
      axios
        .post(
          "http://localhost/todolistefinalauflocal/db.php?action=create",
          formData
        )
        .then((dieDaten) => {});
        //V-modell entleeren
       this.selectTask.tasktitle=""
       this.selectTask.taskcontent="";
       setTimeout(this.showTask,3)
       this.addTask = { tasktitle: "", taskcontent: "" };

    },
    // deleteTask(taskid) {
    //   console.log(id)
    //   let formData = this.convertToFormData(taskid);
    //   axios
    //     .post(
    //       "http://localhost/WhattoDOliste_VUE/db.php?action=delete",
    //       formData
    //     )
    //     .then(function (respons) {
    //       this.selectTask = { tasktitle: "", taskcontent: "" };
    //     });

    // },
    deleteTasks(taskid) {
      // console.log(taskid)
      let formData = this.convertToFormData({ 'taskid': taskid });

      axios
          .post(
           "http://localhost/todolistefinalauflocal/db.php?action=delete",
           formData
          )
          .then(function (respons) {
             this.selectTask = { tasktitle: "", taskcontent: "" };
          });
          setTimeout(this.showTask,3)

  },

    convertToFormData(data) {
      let fd = new FormData();
      for (value in data) {
        fd.append(value, data[value]);
      }
      return fd;
    },

  },
});

HTML
    <!DOCTYPE html>

       <meta name="viewport" content="width=device-width, initial-scale=1">
       <link rel="stylesheet" href="style.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

To Do List

                      <form action="" method="post">
                      <input type="text" id="myInput" placeholder="add Task.." name="tasktitle" v-model="addTask.tasktitle">
                      <textarea name="" id="note" cols="30" rows="5" placeholder="Notiz"
                      name="taskcontent" v-model="addTask.taskcontent"></textarea>

                      <button @click.prevent="createTask()" ref="taskan" v-if="addTask.tasktitle"  > Add Task</button>

                </form>

Bitte einen Task eintragen

{{validatelengthleeter}}

 {{task.tasktitle}}

  {{task.taskcontent}}  {{showTask}}

DB.php

    <?php

//quelle: https://www.php.net/manual/de/mysqli.construct.php
$conn=new mysqli("localhost", "root", "", "todoliste");
//quelle https://www.php.net/manual/de/mysqli.connect-error.php
if($conn->connect_error){
    error_log('Connection error: ' . $conn->connect_error);

}

$result=array("erorr"=>false);
$action="";
if(isset($_GET["action"])) {
    $action=$_GET["action"];
}

//Daten Lesen قراءة او استدعائ المهام Read Date

if($action =="read"){
    $sql=$conn->query("SELECT * FROM tasks");
    $tasken=array();
    while($row=$sql->fetch_assoc()){
        array_push($tasken,$row);
    }
    $result["tasken"]=$tasken;
}

//Task anelegen   انشاء مهمة Create Task

if($action =="create"){
    $tasktitle=$_POST['tasktitle'];
    $taskcontent=$_POST['taskcontent'];

    //هون انشاء البيانات
        $sql=$conn->query("INSERT INTO tasks (tasktitle,taskcontent)VALUES('$tasktitle','$taskcontent')");

}

//Task löschen
//   حذف المهمة
// Remove  Task

if($action =="delete"){
    $taskid=$_POST['taskid'];

    $sql=$conn->query("DELETE FROM tasks WHERE `taskid` = $taskid");
    // echo $sql;

 }

// //Task bearbeiten   تعديل الواجب  Upadate Date

// if($action =="update"){
//     $id=$_POST["id"];
//     $tasktitle=$_POST["tasktitle"];
//     $taskcontent=$_POST["taskcontent"];

//     //هون تعديل  البيانات

//     $sql=$conn->query("UPADATE tasks SET tasktitle='$tasktitle',taskcontent='$taskcontent',statue='$statue' WHERE id='$id' ");

// }

$conn->close();
echo(json_encode($result));

?>

A: You need to wait for response:
async showTask() {
  await axios
    .get("http://localhost/todolistefinalauflocal/db.php?action=read")
    .then((dieDaten) => {
      console.log(dieDaten.data);

      this.tasks = dieDaten.data.tasken;
    });
},
async createTask() {
  let formData = this.convertToFormData(this.addTask);
  await axios
    .post(
      "http://localhost/todolistefinalauflocal/db.php?action=create",
      formData
    )
    .then((dieDaten) => {});
    //V-modell entleeren
   this.selectTask.tasktitle=""
   this.selectTask.taskcontent="";
   await this.showTask()
   this.addTask = { tasktitle: "", taskcontent: "" };

},


text:
Q: How to parse string with {{}} I have a string
var str = "{{a}} {{b}} aaa";

I want to split the string with {{}}. So, my expected result is
array = ["a", "b"]

Update:
As another case, given
var str1 = "{{a {{b}}}}",
    str2 = "{{{a}}}";

The result should be
var arr1 = ["b"],
    arr2 = ["a"];

A: One option would be to match them all, then extract the contents.

var units = [
    "{{a}} {{b}} aaa",
    "{{a {{b}}}}",
    "{{{a}}};"
];
units.forEach(function(str) {
    var matched = str.match(/{{([^}]*[^{]*)}}/g).map(function(s) {
        return s.substring(2, s.length - 2)
    });
    console.log(str, '=');
    console.log(matched);
});

A: As mentioned there might not be a best way to cover every scenario, but split could be used like:
var str1 = "{{a}} {{b}} aaa", str2 = "{{a {{b}}}}", str3 = "{{{a}}};"

var splits = str1.split(/[^{][^.][^}]|[{}]/).filter(Boolean);
console.log(splits);

Results:
Array [ "a", "b" ]
Array [ "b" ]
Array [ "a" ]

Examples:
https://jsfiddle.net/gsL46bg7


text:
Q: Communicating with program process using pipes I want to be able to fully communicate with some programs after spawning them from Golang program. What I already have is spawning process and talking through pipes based on last line read from stdout:
package main

import (
    "fmt"
    "io"
    "log"
    "os/exec"
    "strings"
)

var stdinPipe io.WriteCloser
var stdoutPipe io.ReadCloser
var err error

func main() {
    cmd := &exec.Cmd{
        Path: "/Users/seba/Projects/go/src/bootstrap/in",
        Args: []string{"program"},
    }

    stdinPipe, err = cmd.StdinPipe()

    if err != nil {
        log.Fatal(err)
    }

    stdoutPipe, err = cmd.StdoutPipe()

    if err != nil {
        log.Fatal(err)
    }

    err = cmd.Start()

    if err != nil {
        log.Fatal(err)
    }

    var stdoutLines []string
    go stdoutManage(stdoutLines, stdoutController)

    cmd.Wait()
}

// TODO: imporove as in io.Copy
func stdoutManage(lines []string, manager func(string)) {
    buf := make([]byte, 32*1024)

    for {
        nr, err := stdoutPipe.Read(buf)

        if nr > 0 {
            thelines := strings.Split(string(buf), "\n")
            for _, l := range thelines {
                manager(l)
                lines = append(lines, l)
            }
        }

        buf = make([]byte, 32*1024) // clear buf

        if err != nil {
            break
        }
    }
}

However this approach have problems with programs clearing terminal output and programs which somehow buffer it's stdin or don't use stdin at all (don't know if it's possible).
So the question: is there a portable way of talking with programs (it can be non-Golang solution)?

A: Problems like this are usually to do with the C library which changes its default buffering mode depending on exactly what stdin / stdout / stderr are.
If stdout is a terminal then buffering is automatically set to line buffered, else it is set to buffered.
This is relevant to you because when you run the programs through a pipe they aren't connected to a terminal and so will have buffering which messes up this sort of use.
To fix, you need to use a pseudo tty which pretends to be a terminal but acts just like a pipe.  Here is a library implementing the pty interface which I haven't actually tried but it looks like it does the right thing!


text:
Q: Passing a HOC component to all your other routes in redux I have a HOC component that uses IdleTimer.  I am creating a idle timeout feature to logout the user after a certain time in my react, redux application.  I am having a hard time passing this over to my other routes.  What would be the best way to approach this?
HOC (IdleTimer)
import IdleTimer from "react-idle-timer";
import React, { Component } from 'react'
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router-dom'

export default function HOC (AutoLogoutComponent) {
 return class extends Component{
      idleTimer;

      constructor(props) {
          super(props);

          this.state = {
              timeout:      1000*5,
              showModal:    false,
              userLoggedIn: false,
              isTimedOut:   false
          };

          this.idleTimer = null;
          this.onAction = this._onAction.bind(this);
          this.onActive = this._onActive.bind(this);
          this.onIdle = this._onIdle.bind(this);

      }

      _onAction(e){
          console.log('User did something', e);
          this.setState({isTimedOut: false})
      }

      _onActive(e){
          console.log('user is active', e);
          this.setState({isTimedOut: false})
      }

      _onIdle(e){
          console.log('user is idle', e);
          const isTimedOut = this.state.isTimedOut;
          if (isTimedOut){
              this.props.history.push('/')
          }else {
              this.setState({showModal: true});
              this.idleTimer.reset();
              this.setState({isTimedOut: true})
          }
      }

    render() {
        const { match } = this.props;
        return (

                <IdleTimer
                    ref={ref => {this.idleTimer = ref}}
                    element={document}
                    onActive={this.onActive}
                    onIdle={this.onIdle}
                    onAction={this.onAction}
                    debounce={250}
                    timeout={this.state.timeout} />

                        <Switch>
                            <Route
                               exact path={`${match.path}/sales-analysis/dashboard`}
                                render={(props) => <DefaultLayout {...props} /> }/>
                            />
                        </Switch>

        )
    }

 }
}
    HOC.propTypes = {
        match: PropTypes.any.isRequired,
        history: PropTypes.func.isRequired
    };

my Index.js file where my routes are.
 render() {
    return (
      <Provider store={this.props.store}>
        <PersistGate loading={
} persistor={this.props.persistor}>
          <BrowserRouter>

              <Route exact path="/" component={LoginContainer} key="login" />
              <Route
                path="/change-password"
                component={LoginContainer}
                key="change-password"
              />
              <Route path="/logout" component={Logout} key="logout" />
              <DefaultLayout
                path="/sales-analysis/dashboard"
                component={HOC(DashboardContainer)}
              />
              <DefaultLayout
                path="/sales-analysissbfhghgb"
                component={HOC(ActiveClientsContainer)}
              />
              <DefaultLayout
                path="/sales-analysis/sbs5dygkjgkh"
                component={HOC(ActivityReportsContainer)}
              />
              <DefaultLayout
                path="/sales-analysis/bbebshyfyfu"
                component={HOC(SegmentsContainer)}
              />
              <DefaultLayout path="/adfserv" component={ProspectsContainer} />
              <DefaultLayout
                path="/preferences/general"
                component={HOC(PreferenceGeneral)}
              />
              <DefaultLayout
                path="/preferences/sdfgsverv"
                component={HOC(PreferenceAccountManager)}
              />
              <DefaultLayout
                path="/preferences/sdvs3esdfvsd"
                component={HOC(PreferenceFlexFields)}
              />
              <DefaultLayout
                path="/preferences/osbrddfsf"
                component={HOC(PreferenceOEMManager)}
              />
              <DefaultLayout
                path="/preferences/users"
                component={HOC(PreferenceUsers)}
              />
              <DefaultLayout
                path="/preferences/group-users"
                component={HOC(PreferenceGroupUsers)}
              />

          </BrowserRouter>
        </PersistGate>
      </Provider>
    );
  }
}
AppEntry = HOC(AppEntry);

store
function configureStore() {
  let store = createStore(
    reducer,
    composeEnhancers(
      applyMiddleware(
        //onSuccessMiddleware, may not need this...
        axiosMiddleware(API, apiOptions),
        thunk,
        notificationMiddleware
      )
    )
  );
  let persistor = persistStore(store);

  return { persistor, store };
}

A: When you call HOC(SegmentsContainer), you're generally trying to wrap your SegmentsContainer with some new code, right?
And in the context of your HOC, function HOC (AutoLogoutComponent), your SegmentsContainer ends up being named AutoLogoutComponent.
Now, I'm not an expert on Higher Order Components, but generally speaking, inside your HOC you'd want to actually render your AutoLogoutComponent somewhere. Otherwise, it seems to me that you're accepting it as an argument and then throwing it away. And that's what it looks like you're doing here. You're not using that argument in your render function anywhere.
[edit] look at the example here. The official docs. They've got a higher order component, function withSubscription(WrappedComponent, selectData), and they render WrappedComponent in their render function