问:
JAVA Match a Username with a Password for Login Program
I am coding a login program that allows you to set and store a password and username in two separate files (named accordingly). My problem is I can't figure out how to set a username to a password. Ex: Username is Bob, Password is cat, and the user needs to input Bob as the username and cat as the password or else it gives an error(if the user inputs the username as bill and the password as cat, it should detect that the username doesn't go with its respective password). Any help would be nice. *I have not added the username part yet as it is structured the same as the password part, I just need the username to correspond with the password so that the user cannot use a different username with the same password

Here is my code I have so far for a reference:

```<code>import java.io.File;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileReader;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class PassCode
{
    static String adminPassword = "Change Password";
    public static void fileMaker() throws IOException
    {
        PrintStream standard = System.out;
        File f = new File("Password.txt");
        FileOutputStream fs= new FileOutputStream(f);
        PrintStream ps = new PrintStream(fs);
        System.setOut(ps);
        String theMessage = "Set New Password";
        String userInput = JOptionPane.showInputDialog(theMessage);
        System.out.println(userInput);
        ps.close();
        System.setOut(standard);
    }
public static void Checker() throws IOException
    {
        Scanner inputStream = new Scanner(new FileReader("Password.txt")); //Scans declared file for text on the first line
        String fileChecker = inputStream.nextLine(); //Sets scanned line into a string variable
        if(fileChecker.isEmpty())
        {
            fileMaker();
        }
        else
        {
        int reply = JOptionPane.showConfirmDialog(null, "Would you like to change the current password", "Warning!", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION)
          {
              String inquire = "Type Administrator Password to Proceed";
              boolean flag = true;
              while(flag == true)
          {
              String confirm = JOptionPane.showInputDialog(inquire);
          if(confirm.equals(adminPassword))
          {
              fileMaker();
              flag = false;
          }
          else
          {
              inquire = "Incorrect!" + "\n" + "Retry";
          }
          }
        }
        }
    }
    public static void main(String[] args) throws IOException
    {
        Checker();
        Scanner inputStreamThree = new Scanner(new FileReader("Password.txt"));
        String line = inputStreamThree.nextLine();
        String question = "Password Please";
        Boolean right = true;
         while(right == true)
        {
            String ask = JOptionPane.showInputDialog(question); //Asks for user to input password
        if(ask.equals(adminPassword)) //Checks if user input the admin password
        {
            fileMaker();
            Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
            String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
            line = adminChecker;
        }
        else if(line.equals(ask)) //Checks if user password is correct
        {
            System.out.println("Welcome Fellow Programmer to the Now Functioning Password Checker!" +
                "\n" + "Date Today: 10/31/2017" +
                "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
            right = false;
        }
        else if(ask != line) //Checks if user password is incorrect
            {
               question = "Incorrect Password!";
            }
        }
    }
}
</code>```

答:
I found a way to implement LineNumberReader(LNR) and have the program check if the line numbers for both the username and password are the same. I used a separate method and called it in the main method. I tested the code and it worked with multiple username info and password info in both files. I know this is messy as well, but I was going for functionality first. Then I will optimize it accordingly. I cannot upload the whole code as it is way to big for space given.

Here is the code I added(just the method with the LNR):

```<code>public static void reader() throws IOException
    {
        JTextField username = new JTextField();
        JTextField password = new JPasswordField();
        Object[] message = {
            "Username:", username,
            "Password:", password
             };

        int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);

        boolean right = true;

        while(right == true)
        {
        int u = 0;
        String userCheck;
        FileReader ur = null;
        LineNumberReader lnru = null;

        try {

        ur = new FileReader("username.txt");
        lnru = new LineNumberReader(ur);

        while ((userCheck = lnru.readLine()) != null)
        {
            if (userCheck.equals(username.getText()))
            {
                break;
            }
            else
            {
                u = lnru.getLineNumber();
            }
        }
      } catch(Exception e)
        {
          e.printStackTrace();
        } finally {
                if(ur!=null)
                    ur.close();
                if(lnru!=null)
                    lnru.close();
            }

        int p = 0;
        String passCheck;
        FileReader pr = null;
        LineNumberReader lnrp = null;

        try {

        pr = new FileReader("Password.txt");
        lnrp = new LineNumberReader(pr);

        while ((passCheck = lnrp.readLine()) != null)
        {
            if (passCheck.equals(password.getText()))
            {
                break;
            }
            else
            {
                p = lnrp.getLineNumber();
            }
        }
    } catch(Exception e)
        {
            e.printStackTrace();
        } finally {

            if(pr!=null)
                pr.close();
            if(lnrp!=null)
                lnrp.close();
        }

        if (option == JOptionPane.OK_OPTION)
        {
         if(password.getText().equals(adminPassword)) //Checks if user input the admin password
        {
            passMaker();
            Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
            String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
            //lineFromFile = adminChecker;
        }
        else if(p == u) //Checks if username and password are correct
        {
            System.out.println("Welcome Fellow Programmer to the Now Functioning login program!" + "\n" + "Date Today: 10/31/2017" + "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
            right = false;
        }
        else  //Checks if user password is incorrect
            {
               option = JOptionPane.showConfirmDialog(null, message, "Login Failed Try Again", JOptionPane.OK_CANCEL_OPTION);
            }
        }
     }
    }
</code>```

Body:
I am coding a login program that allows you to set and store a password and username in two separate files (named accordingly). My problem is I can't figure out how to set a username to a password. Ex: Username is Bob, Password is cat, and the user needs to input Bob as the username and cat as the password or else it gives an error(if the user inputs the username as bill and the password as cat, it should detect that the username doesn't go with its respective password). Any help would be nice. *I have not added the username part yet as it is structured the same as the password part, I just need the username to correspond with the password so that the user cannot use a different username with the same password

Here is my code I have so far for a reference:

import java.io.File;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileReader;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class PassCode
{
    static String adminPassword = "Change Password";
    public static void fileMaker() throws IOException
    {
        PrintStream standard = System.out;
        File f = new File("Password.txt");
        FileOutputStream fs= new FileOutputStream(f);
        PrintStream ps = new PrintStream(fs);
        System.setOut(ps);
        String theMessage = "Set New Password";
        String userInput = JOptionPane.showInputDialog(theMessage);
        System.out.println(userInput);
        ps.close();
        System.setOut(standard);
    }
public static void Checker() throws IOException
    {
        Scanner inputStream = new Scanner(new FileReader("Password.txt")); //Scans declared file for text on the first line
        String fileChecker = inputStream.nextLine(); //Sets scanned line into a string variable
        if(fileChecker.isEmpty())
        {
            fileMaker();
        }
        else
        {
        int reply = JOptionPane.showConfirmDialog(null, "Would you like to change the current password", "Warning!", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION)
          {
              String inquire = "Type Administrator Password to Proceed";
              boolean flag = true;
              while(flag == true)
          {
              String confirm = JOptionPane.showInputDialog(inquire);
          if(confirm.equals(adminPassword))
          {
              fileMaker();
              flag = false;
          }
          else
          {
              inquire = "Incorrect!" + "\n" + "Retry";
          }
          }
        }
        }
    }
    public static void main(String[] args) throws IOException
    {
        Checker();
        Scanner inputStreamThree = new Scanner(new FileReader("Password.txt"));
        String line = inputStreamThree.nextLine();
        String question = "Password Please";
        Boolean right = true;
         while(right == true)
        {
            String ask = JOptionPane.showInputDialog(question); //Asks for user to input password
        if(ask.equals(adminPassword)) //Checks if user input the admin password
        {
            fileMaker();
            Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
            String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
            line = adminChecker;
        }
        else if(line.equals(ask)) //Checks if user password is correct
        {
            System.out.println("Welcome Fellow Programmer to the Now Functioning Password Checker!" +
                "\n" + "Date Today: 10/31/2017" +
                "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
            right = false;
        }
        else if(ask != line) //Checks if user password is incorrect
            {
               question = "Incorrect Password!";
            }
        }
    }
}

Body:
I found a way to implement LineNumberReader(LNR) and have the program check if the line numbers for both the username and password are the same. I used a separate method and called it in the main method. I tested the code and it worked with multiple username info and password info in both files. I know this is messy as well, but I was going for functionality first. Then I will optimize it accordingly. I cannot upload the whole code as it is way to big for space given.

Here is the code I added(just the method with the LNR):

public static void reader() throws IOException
    {
        JTextField username = new JTextField();
        JTextField password = new JPasswordField();
        Object[] message = {
            "Username:", username,
            "Password:", password
             };

        int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);

        boolean right = true;

        while(right == true)
        {
        int u = 0;
        String userCheck;
        FileReader ur = null;
        LineNumberReader lnru = null;

        try {

        ur = new FileReader("username.txt");
        lnru = new LineNumberReader(ur);

        while ((userCheck = lnru.readLine()) != null)
        {
            if (userCheck.equals(username.getText()))
            {
                break;
            }
            else
            {
                u = lnru.getLineNumber();
            }
        }
      } catch(Exception e)
        {
          e.printStackTrace();
        } finally {
                if(ur!=null)
                    ur.close();
                if(lnru!=null)
                    lnru.close();
            }

        int p = 0;
        String passCheck;
        FileReader pr = null;
        LineNumberReader lnrp = null;

        try {

        pr = new FileReader("Password.txt");
        lnrp = new LineNumberReader(pr);

        while ((passCheck = lnrp.readLine()) != null)
        {
            if (passCheck.equals(password.getText()))
            {
                break;
            }
            else
            {
                p = lnrp.getLineNumber();
            }
        }
    } catch(Exception e)
        {
            e.printStackTrace();
        } finally {

            if(pr!=null)
                pr.close();
            if(lnrp!=null)
                lnrp.close();
        }

        if (option == JOptionPane.OK_OPTION)
        {
         if(password.getText().equals(adminPassword)) //Checks if user input the admin password
        {
            passMaker();
            Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
            String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
            //lineFromFile = adminChecker;
        }
        else if(p == u) //Checks if username and password are correct
        {
            System.out.println("Welcome Fellow Programmer to the Now Functioning login program!" + "\n" + "Date Today: 10/31/2017" + "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
            right = false;
        }
        else  //Checks if user password is incorrect
            {
               option = JOptionPane.showConfirmDialog(null, message, "Login Failed Try Again", JOptionPane.OK_CANCEL_OPTION);
            }
        }
     }
    }


来源: stackexchange

问:
Sending other data along with a file using Kombu (carrot)
How can I send a file along with other data using Kombu? I'm using rabbitmq as the broker.

e.g. file.pdf along a dictionary {'author': 'user'}

I'd like to do this in a single message if possible. But if you reckon using standard serializers of Kombu, how would you bind the separate messages?

答:
There are several ways, but how about:

```<code>producer.send({"author": "user", "file": file})
</code>```

or:

```<code>producer.send(file, serializer=None, headers={"author": "user"})
</code>```

Headers can only be of types supported by AMQP though.

ContentLicense: CC BY-SA 2.5

Body:
There are several ways, but how about:

producer.send({"author": "user", "file": file})

or:

producer.send(file, serializer=None, headers={"author": "user"})

Headers can only be of types supported by AMQP though.


问:
How do I use #keyPath() in Swift 4?
I think part of my problem is because Swift 4 has changed the way things like @objc work.

There are a lot of tutorials floating around, with a lot of different values, and I can't pick my way between what used to work in what version enough to figure out how to make it work in this version.

```<code>let delegate = UIApplication.shared.delegate as! AppDelegate
delegate.addObserver(self, forKeyPath: #keyPath(AppDelegate.session), options: [], context: nil)
// Warning: Argument of #keyPath refers to non-'@objc' property 'session'
</code>```

Adding @objc to the var declaration just informs me that APISession can't be referenced in Objective-C.  That seems to lead down the path towards requiring me to expose every class / variable I want to use this tool with to Obj-C, and that just seems backwards -- this is a newer feature, as I understand it, and it's just odd that Apple wouldn't make it work natively in Swift.  Which, to me, suggests I'm misunderstanding or misapplying something, somewhere, somehow.

答:
According to the docs:

In Objective-C, a key is a string that identifies a specific property of an object. A key path is a string of dot-separated keys that specifies a sequence of object properties to traverse.

Significantly, the discussion of #keyPath is found in a section titled "Interacting with Objective-C APIs". KVO and KVC are Objective-C features.

All the examples in the docs show Swift classes which inherit from NSObject.

Finally, when you type #keyPath in Xcode, the autocomplete tells you it is expecting an @objc property sequence.

Expressions entered using #keyPath will be checked by the compiler (good!), but this doesn't remove the dependency on Objective-C.

ContentLicense: CC BY-SA 4.0

Title: How do I use #keyPath() in Swift 4?

Body:
I think part of my problem is because Swift 4 has changed the way things like @objc work.

There are a lot of tutorials floating around, with a lot of different values, and I can't pick my way between what used to work in what version enough to figure out how to make it work in this version.

let delegate = UIApplication.shared.delegate as! AppDelegate
delegate.addObserver(self, forKeyPath: #keyPath(AppDelegate.session), options: [], context: nil)
// Warning: Argument of #keyPath refers to non-'@objc' property 'session'

Adding @objc to the var declaration just informs me that APISession can't be referenced in Objective-C.  That seems to lead down the path towards requiring me to expose every class / variable I want to use this tool with to Obj-C, and that just seems backwards -- this is a newer feature, as I understand it, and it's just odd that Apple wouldn't make it work natively in Swift.  Which, to me, suggests I'm misunderstanding or misapplying something, somewhere, somehow.

ContentLicense: CC BY-SA 3.0


问:
Using $this when not in object context in header.php using Codeigniter
I just got one code from online to fetch data from db. Its working for me. But in debugging with phpstorm. I got this error. I am using $this in header.php for display data with session.

```<code><li  class="dropdown" id="profile-messages" ><a title="" href="#" data-toggle="dropdown" data-target="#profile-messages" class="dropdown-toggle">
    <i class="icon icon-user"></i>
    <span class="text">Welcome
    <?php echo $this->session->userdata('user_name'); ?></span><b class="caret"></b></a>
</code>```

my controller:

```<code>function login_user(){
  $user_login=array(

  'USER_NAME'=>$this->input->post('user_email'),
  'PASSWORD'=>($this->input->post('user_password')),
  'PIN'=>($this->input->post('user_pin'))
    );

    $data=$this->user_model->login_user($user_login['USER_NAME'],$user_login['PASSWORD'],$user_login['PIN']);

      if($data)
      {
        $this->session->set_userdata('user_id',$data['USER_ID']);
        $this->session->set_userdata('user_name',$data['USER_NAME']);
        $this->session->set_userdata('employee_id',$data['EMPLOYEE_ID']);
        $this->session->set_userdata('nationality',$data['NATIONALITY']);
        $this->session->set_userdata('EMPLOYEE_NAME',$data['EMPLOYEE_NAME']);
        $this->session->set_userdata('EMPLOYEE_NUMBER',$data['EMPLOYEE_NUMBER']);
        $this->session->set_userdata('DATE_OF_BIRTH',$data['DATE_OF_BIRTH']);
        $this->session->set_userdata('JOINING_DATE',$data['JOINING_DATE']);
        $this->session->set_userdata('CURRENT_LOCATION',$data['CURRENT_LOCATION']);
        $this->session->set_userdata('SEX',$data['SEX']);
        $this->session->set_userdata('ADDRESS',$data['ADDRESS']);
        $this->session->set_userdata('COMPANY_EMPLOYEE_NUMBER',$data['COMPANY_EMPLOYEE_NUMBER']);
        $this->session->set_userdata('PHONE',$data['PHONE']);
        $this->session->set_userdata('MOBILE',$data['MOBILE']);
        $this->session->set_userdata('EMAIL_ADDRESS',$data['EMAIL_ADDRESS']);
        $this->session->set_userdata('ALTERNATE_EMAIL',$data['ALTERNATE_EMAIL']);
        $this->session->set_userdata('WORKING_HOURS',$data['WORKING_HOURS']);
        $this->session->set_userdata('NOK',$data['NOK']);
        $this->session->set_userdata('NOK_CONTACT_NUMBER',$data['NOK_CONTACT_NUMBER']);
        $this->session->set_userdata('EMPLOYMENT_STATUS_ID',$data['EMPLOYMENT_STATUS_ID']);
        $this->session->set_userdata('DESIGNATION_NAME',$data['DESIGNATION_NAME']);
        $this->session->set_userdata('CURRENT_ORG_ID',$data['CURRENT_ORG_ID']);
        $this->session->set_userdata('COS_NUMBER',$data['COS_NUMBER']);
        $this->session->set_userdata('VISA_START_DATE',$data['VISA_START_DATE']);
        $this->session->set_userdata('VISA_END_DATE',$data['VISA_END_DATE']);
        $this->session->set_userdata('DESCRIPTION',$data['DESCRIPTION']);
        $this->session->set_userdata('SKILLS',$data['SKILLS']);
        $this->session->set_userdata('YR_OF_EXPERIENCE',$data['YR_OF_EXPERIENCE']);

        $this->load->view('layouts/index.php');

      }
      else{
        $this->session->set_flashdata('error_msg', 'Error occured,Try again.');
        $this->load->view('layouts/login.php');

      }

}
</code>```

答:
Actually, you are trying to access CodeIgniter class object in view which is always inaccessible. Please refer the code below.

```<code>$CI =& get_instance();
echo $CI->session->userdata('username');
</code>```

$CI is instantiated with the CodeIgniter class object and you will see the result.

Body:
I just got one code from online to fetch data from db. Its working for me. But in debugging with phpstorm. I got this error. I am using $this in header.php for display data with session.

    Welcome
    <?php echo $this->session->userdata('user_name'); ?>

my controller:

function login_user(){
  $user_login=array(

  'USER_NAME'=>$this->input->post('user_email'),
  'PASSWORD'=>($this->input->post('user_password')),
  'PIN'=>($this->input->post('user_pin'))
    );

    $data=$this->user_model->login_user($user_login['USER_NAME'],$user_login['PASSWORD'],$user_login['PIN']);

      if($data)
      {
        $this->session->set_userdata('user_id',$data['USER_ID']);
        $this->session->set_userdata('user_name',$data['USER_NAME']);
        $this->session->set_userdata('employee_id',$data['EMPLOYEE_ID']);
        $this->session->set_userdata('nationality',$data['NATIONALITY']);
        $this->session->set_userdata('EMPLOYEE_NAME',$data['EMPLOYEE_NAME']);
        $this->session->set_userdata('EMPLOYEE_NUMBER',$data['EMPLOYEE_NUMBER']);
        $this->session->set_userdata('DATE_OF_BIRTH',$data['DATE_OF_BIRTH']);
        $this->session->set_userdata('JOINING_DATE',$data['JOINING_DATE']);
        $this->session->set_userdata('CURRENT_LOCATION',$data['CURRENT_LOCATION']);
        $this->session->set_userdata('SEX',$data['SEX']);
        $this->session->set_userdata('ADDRESS',$data['ADDRESS']);
        $this->session->set_userdata('COMPANY_EMPLOYEE_NUMBER',$data['COMPANY_EMPLOYEE_NUMBER']);
        $this->session->set_userdata('PHONE',$data['PHONE']);
        $this->session->set_userdata('MOBILE',$data['MOBILE']);
        $this->session->set_userdata('EMAIL_ADDRESS',$data['EMAIL_ADDRESS']);
        $this->session->set_userdata('ALTERNATE_EMAIL',$data['ALTERNATE_EMAIL']);
        $this->session->set_userdata('WORKING_HOURS',$data['WORKING_HOURS']);
        $this->session->set_userdata('NOK',$data['NOK']);
        $this->session->set_userdata('NOK_CONTACT_NUMBER',$data['NOK_CONTACT_NUMBER']);
        $this->session->set_userdata('EMPLOYMENT_STATUS_ID',$data['EMPLOYMENT_STATUS_ID']);
        $this->session->set_userdata('DESIGNATION_NAME',$data['DESIGNATION_NAME']);
        $this->session->set_userdata('CURRENT_ORG_ID',$data['CURRENT_ORG_ID']);
        $this->session->set_userdata('COS_NUMBER',$data['COS_NUMBER']);
        $this->session->set_userdata('VISA_START_DATE',$data['VISA_START_DATE']);
        $this->session->set_userdata('VISA_END_DATE',$data['VISA_END_DATE']);
        $this->session->set_userdata('DESCRIPTION',$data['DESCRIPTION']);
        $this->session->set_userdata('SKILLS',$data['SKILLS']);
        $this->session->set_userdata('YR_OF_EXPERIENCE',$data['YR_OF_EXPERIENCE']);

        $this->load->view('layouts/index.php');

      }
      else{
        $this->session->set_flashdata('error_msg', 'Error occured,Try again.');
        $this->load->view('layouts/login.php');

      }

}

Body:
Actually, you are trying to access CodeIgniter class object in view which is always inaccessible. Please refer the code below.

$CI =& get_instance();
echo $CI->session->userdata('username');

$CI is instantiated with the CodeIgniter class object and you will see the result.


问:
Applying CSS classes to plugin-generated elements of the same tag?
Basically, I have a plugin that generates a HTML menu made up of one
 tag and several
 tags. I want to apply different background colors to each menu item, but I am unable to add these CSS classes to each list item due to them being programmatically generated, therefore directly inaccessible. Is there a way to apply different classes to multiple child elements of the same tag? Without accessing the plugin files, in my case.

答:
Yes, it is possible.

You can use the nth-of-type(n) selector to target different
 elements without adding classes to the generated code.

body {font-size: 22px}

ul li:nth-of-type(1){background:red}
ul li:nth-of-type(2){background:blue}
ul li:nth-of-type(3){background:green}
ul li:nth-of-type(4){background:yellow}
ul li:nth-of-type(5){background:orange}
ul li:nth-of-type(6){background:purple}
ul li:nth-of-type(7){background:cyan}
ul li:nth-of-type(8){background:brown}
ul li:nth-of-type(9){background:pink}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Apple</li>
  <li>Orange</li>
  <li>Watermelon</li>
  <li>Pear</li>
  <li>Milk</li>
  <li>Cheese</li>
  <li>Bread</li>
  <li>Jam</li>
  <li>Sugar</li>
</ul></code>```

You can also use other elements on the page to make sure the changes are only applied to the element you want to affect.

example:

body {
  font-size: 22px
}

.foo ul li:nth-of-type(1) {
  background: red
}

.foo ul li:nth-of-type(2) {
  background: blue
}

.foo ul li:nth-of-type(3) {
  background: green
}

.foo ul li:nth-of-type(4) {
  background: yellow
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bar">

  <h1> First List (not modified)</h1>
  <ul>
    <li>Apple</li>
    <li>Orange</li>
    <li>Watermelon</li>
    <li>Pear</li>
  </ul>

</div>

<div class="foo">

  <h1> Second List (modified)</h1>
  <ul>
    <li>Apple</li>
    <li>Orange</li>
    <li>Watermelon</li>
    <li>Pear</li>
  </ul>

</div>

<div class="bar">

  <h1> Third List (not modified)</h1>
  <ul>
    <li>Apple</li>
    <li>Orange</li>
    <li>Watermelon</li>
    <li>Pear</li>
  </ul>

</div></code>```

Body:
Yes, it is possible.

You can use the nth-of-type(n) selector to target different <li> elements without adding classes to the generated code.

body {font-size: 22px}

ul li:nth-of-type(1){background:red}
ul li:nth-of-type(2){background:blue}
ul li:nth-of-type(3){background:green}
ul li:nth-of-type(4){background:yellow}
ul li:nth-of-type(5){background:orange}
ul li:nth-of-type(6){background:purple}
ul li:nth-of-type(7){background:cyan}
ul li:nth-of-type(8){background:brown}
ul li:nth-of-type(9){background:pink}

<ul>
  <li>Apple</li>
  <li>Orange</li>
  <li>Watermelon</li>
  <li>Pear</li>
  <li>Milk</li>
  <li>Cheese</li>
  <li>Bread</li>
  <li>Jam</li>
  <li>Sugar</li>
</ul>

You can also use other elements on the page to make sure the changes are only applied to the element you want to affect.

example:

body {
  font-size: 22px
}

.foo ul li:nth-of-type(1) {
  background: red
}

.foo ul li:nth-of-type(2) {
  background: blue
}

.foo ul li:nth-of-type(3) {
  background: green
}

.foo ul li:nth-of-type(4) {
  background: yellow
}

<div class="bar">

  <h1> First List (not modified)</h1>
  <ul>
    <li>Apple</li>
    <li>Orange</li>
    <li>Watermelon</li>
    <li>Pear</li>
  </ul>

</div>

<div class="foo">

  <h1> Second List (modified)</h1>
  <ul>
    <li>Apple</li>
    <li>Orange</li>
    <li>Watermelon</li>
    <li>Pear</li>
  </ul>

</div>

<div class="bar">

  <h1> Third List (not modified)</h1>
  <ul>
    <li>Apple</li>
    <li>Orange</li>
    <li>Watermelon</li>
    <li>Pear</li>
  </ul>

</div>


问:
Google Cloud Function connection to Google Compute Engine via internal IP
According to several sources I found on the internet it is not possible to connect google cloud functions to a restricted Compute Engine Instance via internal IP only (e.g. https://groups.google.com/forum/#!topic/gce-discussion/HEn5P9PJzYQ ). Is this really still the case?
My setup looks as follows:

google cloud functions as API (public)

google app engine flexible for some python application (should be private)

google compute engine instance with redis (should be private)

I now restricted via firewall rules the compute engine instance to only internal traffic (10.128.0.0/9). My app engine still could connect to the compute engine instance, my cloud functions though, now were not able to connect anymore. I tried to find further information on how to use this with VPC but couldn't find anything which led me to the solution. I switched back to public IP usage and using redis auth to protect the data, but I am still not happy with this solution (in AWS it is far more easy - I can select a VPC which is able to communicate via lambda). Not only I see security issues, but also unnecessary network traffic [not sure if I get charged - in AWS this would be case]. Did I miss something or does this "feature" is really missing?

Thanks a lot in advance!

答: You must be running your App Engine app as a flexible environment app, which is built on top of Compute Engine instances. App Engine standard environment and Cloud Functions are on different networks than Compute Engine currently and cannot use VPN or VPC functionality to connect between them. </p>


问:
PHP Generate Math equation from answer
I need some a function written in PHP to generate a simple math equation using the answer. For example:

Input:

```<code>6688650
</code>```

Output: (Or something simmilar)

```<code>75 * 34 * (1 * (43 * 61))
</code>```

Input:

```<code>249366
</code>```

Output: (Or something simmilar)

```<code>(((99 + 87) + 95 * 99) * 26)
</code>```

I came up with this prime factor generator but I need a way to turn the factors into a equation like the (((99 + 87) + 95 * 99) * 26)

```<code>function primefactor($num) {
    $sqrt = sqrt($num);
    for ($i = 2; $i <= $sqrt; $i++) {
        if ($num % $i == 0) {
            return array_merge(primefactor($num/$i), array($i));
        }
    }
    return array($num);
}
</code>```

And with a number generator:

```<code>do {
    $num = mt_rand(6542,89523498);

} while (is_prime($num) & count(primefactor($num)) > 5);
</code>```

This leaves me with somthing like:

```<code>Original: 78973465
Array ( [0] => 349 [1] => 271 [2] => 167 [3] => 5 )
</code>```

答:
Concept

Convert your integer into an array of prime factors.

You can combine your prime factors however you choose to generate an equation.  However, this isn't a 1:1 function (unless the number is prime). So, you can be creative as to how you wish to combine the numbers back together.

In this implementation, I decided to generate random addition and combining of primes to form co-primes.

Note

Creating an efficient way of prime factorization becomes a bit more complicated of a problem.  I wrote a very simple one here and, odds are, it will suit your needs.  However, if you need a method that is faster (or if you're dealing with much larger numbers or many more numbers) you may want to do some independent research.  I googled it and this suggestion showed up.

Code

```<code><?php

$n = 6688650;

//generates a list of all factors
function primefactor($num) {
    $sqrt = sqrt($num);
    for ($i = 2; $i <= $sqrt; $i++) {
        if ($num % $i == 0) {
            return array_merge(primefactor($num/$i), array($i));
        }
    }
    return array($num);
}

//generates multiplication equation
//  Let's scramble those numbers

$factors = primefactor($n);

//let's randomly combine some of our prime factors
for ($i = 0, $len = count($factors); $i < $len; $i++) {
  if (mt_rand(0,1)) {
    $keys = array_rand($factors,2);
    $to = $factors[$keys[0]]*$factors[$keys[1]];
    array_push($factors, $to);
    unset($factors[$keys[0]]);
    unset($factors[$keys[1]]);
  }
}

//now, let's insert some random addition
foreach ($factors as $key => $value) {
  if (mt_rand(0,1)) {
    $delta = mt_rand(1,$factors[$key]-1);
    $factors[$key] = '(' . ($value-$delta) . '+' . $delta . ')';
  }
}

//output the information
$myValues = array_values($factors);
shuffle($myValues);
echo join('*',$myValues);

?>
</code>```

Some outputs

```<code>5185*(145+1145)
3*(59+27)*(23+62)*(269+36)
1462*(26+35)*5*5*(2+1)
</code>```

Title: PHP Generate Math equation from answer

Body:
I need some a function written in PHP to generate a simple math equation using the answer. For example:

Input:

6688650

Output: (Or something simmilar)

75 * 34 * (1 * (43 * 61))

Input:

249366

Output: (Or something simmilar)

(((99 + 87) + 95 * 99) * 26)

I came up with this prime factor generator but I need a way to turn the factors into a equation like the (((99 + 87) + 95 * 99) * 26)

function primefactor($num) {
    $sqrt = sqrt($num);
    for ($i = 2; $i <= $sqrt; $i++) {
        if ($num % $i == 0) {
            return array_merge(primefactor($num/$i), array($i));
        }
    }
    return array($num);
}

And with a number generator:

do {
    $num = mt_rand(6542,89523498);

} while (is_prime($num) & count(primefactor($num)) > 5);

This leaves me with somthing like:

Original: 78973465
Array ( [0] => 349 [1] => 271 [2] => 167 [3] => 5 )

Body:
Concept

Convert your integer into an array of prime factors.

You can combine your prime factors however you choose to generate an equation.  However, this isn't a 1:1 function (unless the number is prime). So, you can be creative as to how you wish to combine the numbers back together.

In this implementation, I decided to generate random addition and combining of primes to form co-primes.

Note

Creating an efficient way of prime factorization becomes a bit more complicated of a problem.  I wrote a very simple one here and, odds are, it will suit your needs.  However, if you need a method that is faster (or if you're dealing with much larger numbers or many more numbers) you may want to do some independent research.  I googled it and this suggestion showed up.

Code

<?php

$n = 6688650;

//generates a list of all factors
function primefactor($num) {
    $sqrt = sqrt($num);
    for ($i = 2; $i <= $sqrt; $i++) {
        if ($num % $i == 0) {
            return array_merge(primefactor($num/$i), array($i));
        }
    }
    return array($num);
}

//generates multiplication equation
//  Let's scramble those numbers

$factors = primefactor($n);

//let's randomly combine some of our prime factors
for ($i = 0, $len = count($factors); $i < $len; $i++) {
  if (mt_rand(0,1)) {
    $keys = array_rand($factors,2);
    $to = $factors[$keys[0]]*$factors[$keys[1]];
    array_push($factors, $to);
    unset($factors[$keys[0]]);
    unset($factors[$keys[1]]);
  }
}

//now, let's insert some random addition
foreach ($factors as $key => $value) {
  if (mt_rand(0,1)) {
    $delta = mt_rand(1,$factors[$key]-1);
    $factors[$key] = '(' . ($value-$delta) . '+' . $delta . ')';
  }
}

//output the information
$myValues = array_values($factors);
shuffle($myValues);
echo join('*',$myValues);

?>

Some outputs

5185*(145+1145)
3*(59+27)*(23+62)*(269+36)
1462*(26+35)*5*5*(2+1)


问:
checking invariants in C++
Are there any established patterns for checking class invariants in C++?

Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.

Of course, manually inserting check_invariants() calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:

```<code>template <typename T>
class invariants_checker
{
    const T* p;

public:

    invariants_checker(const T* p) : p(p)
    {
        p->check_invariants();
    }

    ~invariants_checker()
    {
        p->check_invariants();
    }
};

void Foo::bar()
{
    // class invariants checked by construction of _
    invariants_checker<Foo> _(this);

    // ... mutate the object

    // class invariants checked by destruction of _
}
</code>```

Question #0: I suppose there is no way to declare an unnamed local variable? :)

We would still have to call check_invariants() manually at the end of the Foo constructor and at the beginning of the Foo destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an invariants_checker as the last member?

```<code>#include <string>
#include <stdexcept>

class Foo
{
    std::string str;
    std::string::size_type cached_length;
    invariants_checker<Foo> _;

public:

    Foo(const std::string& str)
    : str(str), cached_length(str.length()), _(this) {}

    void check_invariants() const
    {
        if (str.length() != cached_length)
            throw std::logic_error("wrong cached length");
    }

    // ...
};
</code>```

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

Question #2: Do you see any other problems with this approach? Can you improve it?

Question #3: Is this approach new or well-known? Are there better solutions available?

答:
Answer #0: You can have unnamed local variables, but you give up control over the life time of the object - and the whole point of the object is because you have a good idea when it goes out of scope. You can use

```<code>void Foo::bar()
{
    invariants_checker<Foo>(this); // goes out of scope at the semicolon
    new invariants_checker<Foo>(this); // the constructed object is never destructed
    // ...
}
</code>```

but neither is what you want.

Answer #1: No, I believe it's not valid. The object referenced by this is only fully constructed (and thus starts to exist) when the constructor finished. You're playing a dangerous game here.

Answer #2 & #3: This approach is not new, a simple google query for e.g. "check invariants C++ template" will yield a lot of hits on this topic. In particular, this solution can be improved further if you don't mind overloading the -> operator, like this:

```<code>template <typename T>
class invariants_checker {
public:
  class ProxyObject {
  public:
    ProxyObject(T* x) : m(x) { m->check_invariants(); }
    ~ProxyObject() { m->check_invariants(); }
    T* operator->() { return m; }
    const T* operator->() const { return m; }
  private:
    T* m;
  };

invariants_checker(T* x) : m(x) { }

ProxyObject operator->() { return m; }
const ProxyObject operator->() const { return m; }

private:
   T* m;
};
</code>```

The idea is that for the duration of a member function call, you create an anonymous proxy object which performs the check in its constructor and destructor. You can use the above template like this:

```<code>void f() {
  Foo f;
  invariants_checker<Foo> g( &f );
  g->bar(); // this constructs and destructs the ProxyObject, which does the checking
}
</code>```

Title: checking invariants in C++

Body:
Are there any established patterns for checking class invariants in C++?

Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special before and after member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.

Of course, manually inserting check_invariants() calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:

template <typename T>
class invariants_checker
{
    const T* p;

public:

    invariants_checker(const T* p) : p(p)
    {
        p->check_invariants();
    }

    ~invariants_checker()
    {
        p->check_invariants();
    }
};

void Foo::bar()
{
    // class invariants checked by construction of _
    invariants_checker<Foo> _(this);

    // ... mutate the object

    // class invariants checked by destruction of _
}

Question #0: I suppose there is no way to declare an unnamed local variable? :)

We would still have to call check_invariants() manually at the end of the Foo constructor and at the beginning of the Foo destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an invariants_checker as the last member?

#include <string>
#include <stdexcept>

class Foo
{
    std::string str;
    std::string::size_type cached_length;
    invariants_checker<Foo> _;

public:

    Foo(const std::string& str)
    : str(str), cached_length(str.length()), _(this) {}

    void check_invariants() const
    {
        if (str.length() != cached_length)
            throw std::logic_error("wrong cached length");
    }

    // ...
};

Question #1: Is it valid to pass this to the invariants_checker constructor which immediately calls check_invariants via that pointer, even though the Foo object is still under construction?

Question #2: Do you see any other problems with this approach? Can you improve it?

Question #3: Is this approach new or well-known? Are there better solutions available?

Body:
Answer #0: You can have unnamed local variables, but you give up control over the life time of the object - and the whole point of the object is because you have a good idea when it goes out of scope. You can use

void Foo::bar()
{
    invariants_checker<Foo>(this); // goes out of scope at the semicolon
    new invariants_checker<Foo>(this); // the constructed object is never destructed
    // ...
}

but neither is what you want.

Answer #1: No, I believe it's not valid. The object referenced by this is only fully constructed (and thus starts to exist) when the constructor finished. You're playing a dangerous game here.

Answer #2 & #3: This approach is not new, a simple google query for e.g. "check invariants C++ template" will yield a lot of hits on this topic. In particular, this solution can be improved further if you don't mind overloading the -> operator, like this:

template <typename T>
class invariants_checker {
public:
  class ProxyObject {
  public:
    ProxyObject(T* x) : m(x) { m->check_invariants(); }
    ~ProxyObject() { m->check_invariants(); }
    T* operator->() { return m; }
    const T* operator->() const { return m; }
  private:
    T* m;
  };

invariants_checker(T* x) : m(x) { }

ProxyObject operator->() { return m; }
const ProxyObject operator->() const { return m; }

private:
   T* m;
};

The idea is that for the duration of a member function call, you create an anonymous proxy object which performs the check in its constructor and destructor. You can use the above template like this:

void f() {
  Foo f;
  invariants_checker<Foo> g( &f );
  g->bar(); // this constructs and destructs the ProxyObject, which does the checking
}


问:
Why does my Boost Library fail to link?
I'm using a MacBook Pro, running MacOS 10.13.1; installed boost via homebrew using the following:

```<code>brew install boost --build-from-source
</code>```

My code is the following:

```<code>#include <iostream>
#include <boost/filesystem.hpp>

namespace boostfs = boost::filesystem;

int main(int argc, char* argv[])
{
    if (argc <= 1)
{
    std::cerr << "Usage: " << argv[0] << " <filename>" << std::endl;
    return 1;
}

boostfs::path p(argv[1]);

if (boostfs::exists(p))
{
    std::cout << "File " << p << " exists." << std::endl;
}
else
{
    std::cout << "File " << p << " does not exist." << std::endl;
}

    return 0;
}
</code>```

The error I am receiving is the following:

```<code>Undefined symbols for architecture x86_64:
"boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)", referenced from:
  boost::filesystem::exists(boost::filesystem::path const&) in chkfile-c30777.o
  "boost::system::system_category()", referenced from:
  ___cxx_global_var_init.2 in chkfile-c30777.o
  "boost::system::generic_category()", referenced from:
  ___cxx_global_var_init in chkfile-c30777.o
  ___cxx_global_var_init.1 in chkfile-c30777.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [chkfile] Error 1
</code>```

I ran the code in the terminal using make and gcc 7.2.0.

I attempted the following:

```<code>g++ -std=c++17 -I /usr/local/include/ chkfile.cpp -o chkfile
</code>```

and got a new error:

```<code>Undefined symbols for architecture x86_64:
"boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)", referenced from:
boost::filesystem::exists(boost::filesystem::path const&) in cce7HDO8.o
"boost::system::system_category()", referenced from:
  __static_initialization_and_destruction_0(int, int) in cce7HDO8.o
"boost::system::generic_category()", referenced from:
  boost::system::error_category::std_category::equivalent(int, std::error_condition const&) const in cce7HDO8.o

boost::system::error_category::std_category::equivalent(std::error_code const&, int) const in cce7HDO8.o
  __static_initialization_and_destruction_0(int, int) in cce7HDO8.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
</code>```

What am I doing wrong?

答:
Include filesystem this way

```<code>#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>
#undef BOOST_NO_CXX11_SCOPED_ENUMS
</code>```

Make sure you linked proper libraries

```<code>-lboost_system -lboost_filesystem
</code>```

Title: Why does my Boost Library fail to link?

Body:
I'm using a MacBook Pro, running MacOS 10.13.1; installed boost via homebrew using the following:

brew install boost --build-from-source

My code is the following:

#include <iostream>
#include <boost/filesystem.hpp>

namespace boostfs = boost::filesystem;

int main(int argc, char* argv[])
{
    if (argc <= 1)
{
    std::cerr << "Usage: " << argv[0] << " <filename>" << std::endl;
    return 1;
}

boostfs::path p(argv[1]);

if (boostfs::exists(p))
{
    std::cout << "File " << p << " exists." << std::endl;
}
else
{
    std::cout << "File " << p << " does not exist." << std::endl;
}

    return 0;
}

The error I am receiving is the following:

Undefined symbols for architecture x86_64:
"boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)", referenced from:
  boost::filesystem::exists(boost::filesystem::path const&) in chkfile-c30777.o
  "boost::system::system_category()", referenced from:
  ___cxx_global_var_init.2 in chkfile-c30777.o
  "boost::system::generic_category()", referenced from:
  ___cxx_global_var_init in chkfile-c30777.o
  ___cxx_global_var_init.1 in chkfile-c30777.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [chkfile] Error 1

I ran the code in the terminal using make and gcc 7.2.0.

I attempted the following:

g++ -std=c++17 -I /usr/local/include/ chkfile.cpp -o chkfile

and got a new error:

Undefined symbols for architecture x86_64:
"boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)", referenced from:
boost::filesystem::exists(boost::filesystem::path const&) in cce7HDO8.o
"boost::system::system_category()", referenced from:
  __static_initialization_and_destruction_0(int, int) in cce7HDO8.o
"boost::system::generic_category()", referenced from:
  boost::system::error_category::std_category::equivalent(int, std::error_condition const&) const in cce7HDO8.o

boost::system::error_category::std_category::equivalent(std::error_code const&, int) const in cce7HDO8.o
  __static_initialization_and_destruction_0(int, int) in cce7HDO8.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

What am I doing wrong?

Body:
Include filesystem this way

#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>
#undef BOOST_NO_CXX11_SCOPED_ENUMS

Make sure you linked proper libraries

-lboost_system -lboost_filesystem


问:
TypeScript error on implicit type conversion
Is there a way to make TypeScript throw an error on an implicit type conversion? Seems to me like all the implicit type conversions in JavaScript are one of the larger sources of bugs in the language, so I'd like a way for something like the following code:

```<code>let h = (n: number): number => {
    let f = () => 0
    return -f
}
</code>```

to let me know it will be implicitly converting the function type to a number via the - operator, and thus always returning NaN.

答:
TypeScript allows this because it is valid JavaScript.
You can always override the toString() method.

Consider the following:

```<code>let x = {}
x.toString = () => "1"
ley y = -x  // -1

let f = () => { }
f.toString = () => "1"
let z = -f // -1
</code>```

Body:
Is there a way to make TypeScript throw an error on an implicit type conversion? Seems to me like all the implicit type conversions in JavaScript are one of the larger sources of bugs in the language, so I'd like a way for something like the following code:

let h = (n: number): number => {
    let f = () => 0
    return -f
}

to let me know it will be implicitly converting the function type to a number via the - operator, and thus always returning NaN.

Body:
TypeScript allows this because it is valid JavaScript.
You can always override the toString() method.

Consider the following:

let x = {}
x.toString = () => "1"
ley y = -x  // -1

let f = () => { }
f.toString = () => "1"
let z = -f // -1


问:
Minimum and maximum date in UIDatePicker
I want to get the minimum and maximum date from a date picker, but minimum date should be "- 18" of the current date and the maximum date should be "- 100" of current date.

Suppose current year is 2018 then I want minimum date 2000 and maximum date 1918.

What I have done so far is :

```<code>NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];

NSInteger year = [components year];

int mindt = year - 18;

int maxdt = year -100;

   // NSDate * MinDate = [components year] - 18;

   // NSDate * MaxDate =  [components year] - 100;

   // self.datePicker.minimumDate = MinDate;

   // self.datePicker.maximumDate = MaxDate;
</code>```

but I cant get this integer to my date format..

答:
Swift 4.0

UIDatePicker Extension

```<code>extension UIDatePicker {
    func set18YearValidation() {
        let currentDate: NSDate = NSDate()
        let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
        calendar.timeZone = NSTimeZone(name: "UTC")! as TimeZone
        let components: NSDateComponents = NSDateComponents()
        components.calendar = calendar as Calendar
        components.year = -18
        let maxDate: NSDate = calendar.date(byAdding: components as DateComponents, to: currentDate as Date, options: NSCalendar.Options(rawValue: 0))! as NSDate
        components.year = -150
        let minDate: NSDate = calendar.date(byAdding: components as DateComponents, to: currentDate as Date, options: NSCalendar.Options(rawValue: 0))! as NSDate
        self.minimumDate = minDate as Date
        self.maximumDate = maxDate as Date
    } }
</code>```

Body:
I want to get the minimum and maximum date from a date picker, but minimum date should be "- 18" of the current date and the maximum date should be "- 100" of current date.

Suppose current year is 2018 then I want minimum date 2000 and maximum date 1918.

What I have done so far is :

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];

NSInteger year = [components year];

int mindt = year - 18;

int maxdt = year -100;

   // NSDate * MinDate = [components year] - 18;

   // NSDate * MaxDate =  [components year] - 100;

   // self.datePicker.minimumDate = MinDate;

   // self.datePicker.maximumDate = MaxDate;

but I cant get this integer to my date format..

Body:
Swift 4.0

UIDatePicker Extension

extension UIDatePicker {
    func set18YearValidation() {
        let currentDate: NSDate = NSDate()
        let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
        calendar.timeZone = NSTimeZone(name: "UTC")! as TimeZone
        let components: NSDateComponents = NSDateComponents()
        components.calendar = calendar as Calendar
        components.year = -18
        let maxDate: NSDate = calendar.date(byAdding: components as DateComponents, to: currentDate as Date, options: NSCalendar.Options(rawValue: 0))! as NSDate
        components.year = -150
        let minDate: NSDate = calendar.date(byAdding: components as DateComponents, to: currentDate as Date, options: NSCalendar.Options(rawValue: 0))! as NSDate
        self.minimumDate = minDate as Date
        self.maximumDate = maxDate as Date
    } }


问:
Refresh remote Git branches in Android studio
There is a new branch in the remote repository, but it does not appear in the git branches in android studio. How can I refresh that list to show the new branch?

I have tried git branch -r
but new branch is not showing in the list.

答:
In your Android Studio menu bar, click on VCS > Git > Fetch

Check the image:


问:
Wordpress multisite port forwarding fails when adding new sites (behind firewall)
How do I get a WordPress Multisite working behind a firewall port forwarding external port 1731 to the machine running WordPress listening on port 443?

That configuration works well for the initial installation of WordPress, but breaks in Multisite mode for the added sites (original site still works).

Here's the behavior when adding a new site using the WordPress GUI:

Dashboard/Sites/Add New:
Site Address (URL) 1.2.3.4:1731/wordpress/

(here I add 'woof' in the form)

(NOTE THAT IT KNOWS THE RIGHT PORT AT THIS POINT)
I click 'Add Site' button.

When I click Dashboard/Sites/All Sites, the URL of the newly added site shows erroneously as:
https://1.2.3.41731/wordpress/woof (NOTE THE MISSING COLON)
So I click edit and add the colon and click 'Save Changes'

The Edit page reloads with the message "Site info updated". This time the address showing is:
https://1.2.3.4/wordpress/woof (NOTE THE ENTIRE PORT IS NOW MISSING)

wp-admin/includes/network.php has:
if ( ( false !== $has_ports && ! in_array( $has_ports, array( ':80', ':443', ':1731' ) ) ) ) {

wp-config.php has:
define('DOMAIN_CURRENT_SITE', '1.2.3.4:1731');

答:
WordPress has the following comment about this:

Restrictions

You cannot create a network in the following cases:

  "WordPress address (URL)" uses a port number other than ':80', ':443'.

Found at: https://codex.wordpress.org/Before_You_Create_A_Network

...hope this helps someone.


答: Try using git fetch or use git fetch --all

Title: Refresh remote Git branches in Android studio

Body:
There is a new branch in the remote repository, but it does not appear in the git branches in android studio. How can I refresh that list to show the new branch?

I have tried git branch -r
but new branch is not showing in the list.


问:
When using custom cursors, how can you set the I-bar cursor when hovering over text?
I am using a custom cursor set for my website (to override the ugly AA cursors that most modern Operating Systems employ). I have successfully set the custom pointer/cursor, but I am having some difficulty setting the I-bar cursor for when the user hovers over/selects text. Is there not an easy/general #text element to style all text on a web-page? I don't want to just change the cursor to an I-bar when I enter a div (as discussed in a similar stackoverflow post); I only want to change it when hovering over text. Thanks.</p>

```<code>body {
    margin: 0 !important;
    cursor: url(../images/cursors/cursor.png), default;
}
a:link:active {
    cursor: url(../images/cursors/pointer_active.png), pointer ;
}
a:link {
    cursor: url(../images/cursors/pointer.png), pointer ;
}
input[type=text], #text {
    cursor: url(../images/cursors/text.png), text !important;
}
</code>```

答:
I figured this out while simplifying some of the extant stylesheets on my website:

html {
    cursor: url(cursors/crosshair.gif) 17 17, pointer;
}
body {
    cursor: initial;
}
```

Simple and concise.

Body:
I am using a custom cursor set for my website (to override the ugly AA cursors that most modern Operating Systems employ). I have successfully set the custom pointer/cursor, but I am having some difficulty setting the I-bar cursor for when the user hovers over/selects text. Is there not an easy/general #text element to style all text on a web-page? I don't want to just change the cursor to an I-bar when I enter a div (as discussed in a similar stackoverflow post); I only want to change it when hovering over text. Thanks.

body {
    margin: 0 !important;
    cursor: url(../images/cursors/cursor.png), default;
}
a:link:active {
    cursor: url(../images/cursors/pointer_active.png), pointer ;
}
a:link {
    cursor: url(../images/cursors/pointer.png), pointer ;
}
input[type=text], #text {
    cursor: url(../images/cursors/text.png), text !important;
}

Body:
I figured this out while simplifying some of the extant stylesheets on my website:

html {
    cursor: url(cursors/crosshair.gif) 17 17, pointer;
}
body {
    cursor: initial;
}

Simple and concise.


问:
threejs - morphTargets shrink other meshes in scene
Description of the problem

I have a simple box mesh with a morphTarget and a slider which adjusts the morphTargetInfluence. The morph affects the mesh as it should but it also shrinks any other mesh in the scene.

I've put together a jsfiddle (modified from the threejs morph target) example below to demo the issue. In this demo moving the slider correctly morphs the corner of the red cube but incorrectly shrinks the size of the blue cube. The cube meshes are entirely unrelated so I don't see how the morph could affect the blue cube.

https://jsfiddle.net/djmm7vv2/

```<code>  // JS code from jsfiddle
  var container, stats;
  var camera, scene, renderer;
  var geometry, objects;
  var mesh, mesh2;
  init();
  animate();

  function init() {
    // Create cameras, lights, scene, ect.
    container = document.getElementById( 'container' );
    camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 15000 );
    camera.position.z = 500;
    scene = new THREE.Scene();
    scene.background = new THREE.Color( 0x222222 );
    scene.fog = new THREE.Fog( 0x000000, 1, 15000 );
    var light1 = new THREE.PointLight( 'white', 1);
    light1.position.set( 100, 100, 100 );
    var light2 = new THREE.PointLight( 'white', 1);
    light2.position.set( -100, 100, 100 );
    scene.add( light1 );
    scene.add( light2 );

    // Create first mesh (red cube)
    var geometry = new THREE.BoxGeometry( 100, 100, 100 );
    var material = new THREE.MeshLambertMaterial( { color: 'red', morphTargets: true } );

    // Create 1 blend shape
    for ( var i = 0; i < 1; i ++ ) {
      var vertices = [];
      for ( var v = 0; v < geometry.vertices.length; v ++ ) {
        vertices.push( geometry.vertices[ v ].clone() );
        if ( v === i ) {
          vertices[ vertices.length - 1 ].x *= 2;
          vertices[ vertices.length - 1 ].y *= 2;
          vertices[ vertices.length - 1 ].z *= 2;
        }
      }
      geometry.morphTargets.push( { name: "target" + i, vertices: vertices } );
    }
    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    // Add second mesh (blue cube)
    var blue = new THREE.MeshLambertMaterial( { color: 'blue', morphTargets: true } );
    var box2 = new THREE.BoxGeometry( 100, 100, 100 );
    mesh2 = new THREE.Mesh( box2, blue );
    scene.add( mesh2 );
    mesh2.position.x = 150

    // Create simple GUI slider to change morph influence on mesh (red cube)
    var params = {
      influence1: 0,
    };
    var gui = new dat.GUI();
    var folder = gui.addFolder( 'Morph Targets' );
    folder.add( params, 'influence1', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 0 ] = value; } );
    folder.open();

    // Render it all
    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );
  }

  function animate() {
    requestAnimationFrame( animate );
    render();
  }

  function render() {
    mesh.rotation.y += 0.01;
    renderer.render( scene, camera );
  }
</code>```

答:
...And here's the answer https://github.com/mrdoob/three.js/issues/12691#issuecomment-345416590. My blue mesh material had morphTargets set to true. Changing it to false corrected the issue.

```<code>var blue = new THREE.MeshLambertMaterial( { color: 'blue', morphTargets: false } );
</code>```

If anyone knows why this is the case I would love to know more. The documentation on MeshLambertMaterials is sparse. Maybe this has to do with keeping material textures from freaking out when the morph is applied?

Body:
Description of the problem

I have a simple box mesh with a morphTarget and a slider which adjusts the morphTargetInfluence. The morph affects the mesh as it should but it also shrinks any other mesh in the scene.

I've put together a jsfiddle (modified from the threejs morph target) example below to demo the issue. In this demo moving the slider correctly morphs the corner of the red cube but incorrectly shrinks the size of the blue cube. The cube meshes are entirely unrelated so I don't see how the morph could affect the blue cube.

https://jsfiddle.net/djmm7vv2/

  // JS code from jsfiddle
  var container, stats;
  var camera, scene, renderer;
  var geometry, objects;
  var mesh, mesh2;
  init();
  animate();

  function init() {
    // Create cameras, lights, scene, ect.
    container = document.getElementById( 'container' );
    camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 15000 );
    camera.position.z = 500;
    scene = new THREE.Scene();
    scene.background = new THREE.Color( 0x222222 );
    scene.fog = new THREE.Fog( 0x000000, 1, 15000 );
    var light1 = new THREE.PointLight( 'white', 1);
    light1.position.set( 100, 100, 100 );
    var light2 = new THREE.PointLight( 'white', 1);
    light2.position.set( -100, 100, 100 );
    scene.add( light1 );
    scene.add( light2 );

    // Create first mesh (red cube)
    var geometry = new THREE.BoxGeometry( 100, 100, 100 );
    var material = new THREE.MeshLambertMaterial( { color: 'red', morphTargets: true } );

    // Create 1 blend shape
    for ( var i = 0; i < 1; i ++ ) {
      var vertices = [];
      for ( var v = 0; v < geometry.vertices.length; v ++ ) {
        vertices.push( geometry.vertices[ v ].clone() );
        if ( v === i ) {
          vertices[ vertices.length - 1 ].x *= 2;
          vertices[ vertices.length - 1 ].y *= 2;
          vertices[ vertices.length - 1 ].z *= 2;
        }
      }
      geometry.morphTargets.push( { name: "target" + i, vertices: vertices } );
    }
    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    // Add second mesh (blue cube)
    var blue = new THREE.MeshLambertMaterial( { color: 'blue', morphTargets: true } );
    var box2 = new THREE.BoxGeometry( 100, 100, 100 );
    mesh2 = new THREE.Mesh( box2, blue );
    scene.add( mesh2 );
    mesh2.position.x = 150

    // Create simple GUI slider to change morph influence on mesh (red cube)
    var params = {
      influence1: 0,
    };
    var gui = new dat.GUI();
    var folder = gui.addFolder( 'Morph Targets' );
    folder.add( params, 'influence1', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 0 ] = value; } );
    folder.open();

    // Render it all
    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );
  }

  function animate() {
    requestAnimationFrame( animate );
    render();
  }

  function render() {
    mesh.rotation.y += 0.01;
    renderer.render( scene, camera );
  }

Body:
...And here's the answer https://github.com/mrdoob/three.js/issues/12691#issuecomment-345416590. My blue mesh material had morphTargets set to true. Changing it to false corrected the issue.

var blue = new THREE.MeshLambertMaterial( { color: 'blue', morphTargets: false } );

If anyone knows why this is the case I would love to know more. The documentation on MeshLambertMaterials is sparse. Maybe this has to do with keeping material textures from freaking out when the morph is applied?


问:
Triple quotes required on command line in QB64
Have a program which parses the command line in QB64. The COMMAND$ function
returns the command line. I need to parse a long filename which might contain
a space by parsing it from within quotes to differ from a filename with no
space. For example, "long filename.ext"

The problem is that, when the command line has no quotes, the command$ returns
the filename, when in quotes, the same, for example "filename", and ""filename"" both return filename. However, """filename""" returns the
filename with quotes... Is there another way to send a quote to command$??

答:
QB64 provides the COMMAND$ and _COMMANDCOUNT functions—mostly analogous to argv and argc in C++. COMMAND$ without arguments will return a single string containing all command line args, but QB64 also allows COMMAND$(i) to retrieve the argument at index i as a string. Example from the _COMMANDCOUNT entry on the QB64 Wiki:

```<code>limit = _COMMANDCOUNT
FOR i = 1 TO limit
    PRINT COMMAND$(i)
NEXT
</code>```

You'd use them to deal with the command-line arguments in QB64. If you want to pass command-line args that include quotes to a program, you'd likely need to escape the quotes you want kept using a backslash.

Unfortunately, the backslash escape isn't foolproof and can lead to trouble in cmd.exe specifically, mainly because backslashes are used in file paths. Combine this with spaces in a file path, and you have a nightmarish command interpreter. From this answer, you double the quotes inside a quoted string to pass a proper quote to a program:

```<code>> program.exe hello world
hello
world

> program.exe hello"" world
hello (+ empty quoted string)
world

> program.exe "hello"" world
hello"
world

> program.exe "hello""" world
hello" world
</code>```

In Wine's cmd.exe, the "" escaped quote also closes the quoted string as shown above, so an immediately successive quote is needed to continue grouping the next spaced item with the current argument. I'm not sure about the Windows implementation since I'm not running a Windows machine, but it seems likely to me that the same behavior occurs.

In other words, you pass """filename""" because:

```<code>"        Open quoted string
""       Escaped double quote, closes quoted string
filename Concatenated at the end of the first quoted string
"        Open quoted string, concatenated to filename
""       Escaped double quote, closes quoted string
</code>```

Edit

You can use ^" outside of a quoted string, but that has its own issues as ""^" results in " for example, just like """. Passing ""^" to a batch file requires an extra escape as ""^^". Using ^ is therefore not recommended, especially when "" and """ work just as well. See the answer I linked above for info on the ^ escape character.

You should also be careful with backslashes and quoted strings. Consider how you might pass the proper Windows representation of the Unix-like argument 'C:/Program Files/"file" name' as a single argument to your program:

```<code>> program.exe "C:\Program Files\\""file\"" name"
C:\Program Files\"file" name
</code>```

cmd.exe explanation:

```<code>"                   Open quoted string
C:\Program Files\\  Quoted string contents, including escaped \
""                  Escaped double quote, closes quoted string
file\               Unquoted string contents, including C escape char
""                  Open quoted string with escaped double quote
[ ]name             Quoted string contents
"                   Close quoted string
</code>```

This results in a command-line of "C:\Program Files\\"file\" name" being passed to the program, which then results in a path of C:\Program Files\"file" name. Of course, such a path isn't possible in Windows (and maybe not at all on NTFS filesystems?), but it illustrates the point: you need to account for both cmd.exe's quoting rules and the C runtime's quoting rules and backslash escapes.

Body:
QB64 provides the COMMAND$ and _COMMANDCOUNT functions—mostly analogous to argv and argc in C++. COMMAND$ without arguments will return a single string containing all command line args, but QB64 also allows COMMAND$(i) to retrieve the argument at index i as a string. Example from the _COMMANDCOUNT entry on the QB64 Wiki:

limit = _COMMANDCOUNT
FOR i = 1 TO limit
    PRINT COMMAND$(i)
NEXT

You'd use them to deal with the command-line arguments in QB64. If you want to pass command-line args that include quotes to a program, you'd likely need to escape the quotes you want kept using a backslash.

Unfortunately, the backslash escape isn't foolproof and can lead to trouble in cmd.exe specifically, mainly because backslashes are used in file paths. Combine this with spaces in a file path, and you have a nightmarish command interpreter. From this answer, you double the quotes inside a quoted string to pass a proper quote to a program:

> program.exe hello world
hello
world

> program.exe hello"" world
hello (+ empty quoted string)
world

> program.exe "hello"" world
hello"
world

> program.exe "hello""" world
hello" world

In Wine's cmd.exe, the "" escaped quote also closes the quoted string as shown above, so an immediately successive quote is needed to continue grouping the next spaced item with the current argument. I'm not sure about the Windows implementation since I'm not running a Windows machine, but it seems likely to me that the same behavior occurs.

In other words, you pass """filename""" because:

"        Open quoted string
""       Escaped double quote, closes quoted string
filename Concatenated at the end of the first quoted string
"        Open quoted string, concatenated to filename
""       Escaped double quote, closes quoted string

Edit

You can use ^" outside of a quoted string, but that has its own issues as ""^" results in " for example, just like """. Passing ""^" to a batch file requires an extra escape as ""^^". Using ^ is therefore not recommended, especially when "" and """ work just as well. See the answer I linked above for info on the ^ escape character.

You should also be careful with backslashes and quoted strings. Consider how you might pass the proper Windows representation of the Unix-like argument 'C:/Program Files/"file" name' as a single argument to your program:

> program.exe "C:\Program Files\\""file\"" name"
C:\Program Files\"file" name

cmd.exe explanation:

"                   Open quoted string
C:\Program Files\\  Quoted string contents, including escaped \
""                  Escaped double quote, closes quoted string
file\               Unquoted string contents, including C escape char
""                  Open quoted string with escaped double quote
[ ]name             Quoted string contents
"                   Close quoted string

This results in a command-line of "C:\Program Files\\"file\" name" being passed to the program, which then results in a path of C:\Program Files\"file" name. Of course, such a path isn't possible in Windows (and maybe not at all on NTFS filesystems?), but it illustrates the point: you need to account for both cmd.exe's quoting rules and the C runtime's quoting rules and backslash escapes.


问:
The Meaning of @override in Android Studio
I am completely new to Android Studio and I want to know the purpose of the @Override statement in Android Studio.

答:
@Override is an java annotation.

Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

Also See

when-do-you-use-javas-override-annotation-and-why

Example:

```<code>class Parent{
    public void foo(){

    }
}

class Child extends Parent{
    //compile perfect !
    @Override
    public void foo(){

    }
    //will show compile time error message here as it is not being overridden
    @Override
    public void foo(int i){

    }

}
</code>```

Body:
@Override is an java annotation.

Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

Also See

when-do-you-use-javas-override-annotation-and-why

Example:

class Parent{
    public void foo(){

    }
}

class Child extends Parent{
    //compile perfect !
    @Override
    public void foo(){

    }
    //will show compile time error message here as it is not being overridden
    @Override
    public void foo(int i){

    }

}


问:
How to set the timing right for a delay loop in Assembly?
I want to write a one-second delay loop in assembly language and I'm not sure what would be the count for the loop so that it'll delay for 1 second.

Here is what I have so far:

```<code>MOV   R1, #count

DELAY_LOOP:
             SUBS   R1, R1, #1

             BNE  DELAY_LOOP
</code>```

I'm using a Beaglebone Black. Thanks in advance!

答:
Difficult to get this right for ARM, particularly if you are running this on an operating system. Not possible to be accurate. Pure baremetal, no interrupts, you can hand tune it experimentally, but if you change the alignment the performance can change by quite a bit, not only due to caching as most folks will assume but also do to where the fetch lines lie and sweet spots for branch prediction if there is branch prediction and how it is implemented.  I use this exact loop to demonstrate this problem it is somewhat trivial.

The problem is not specific to ARM anything pipelined is often going to fetch more than one instruction per fetch transaction, the fetches are often on aligned boundaries for performance reasons, and there is a watermark in the prefetch buffer that receives this data that determines when to do the next fetch, the alignment of even these two instructions in a loop depending on where they lie can play havoc on execution performance, basically is it doing two fetch lines or one per loop, cache isnt relevant beyond the first pass, one or two fetch lines can still hit the cache.

But this all varies by architecture.  Mips fetching and buffering into the pipe, arm, x86, powerpc, etc all vary and probably vary by rev or generation of that architecture every couple three years the rules may change for the next version of that core

ARM and MIPS and other IP based cores (where the chip vendor implements the memory system) you can have the same exact version of the core but
the chip vendor or family to chip vendor or family differences can/will
affect performance, so even if you got kinda close on one chip, keep the
same alignment and other core settings performance can be different based
on the chip vendor/memory side.  Add dram to this equation, where the
performance of memory is not not-deterministic and you just make it that much worse.

If you go back to pre-pipelined days, where the execution was one instruction at a time, very predictable, a commonly used timed loop is done with the older PIC instruction set(s), extremely predictable and not uncommon to see timed loops used instead of a timer.  Has lead to a lot of folks trying to do this, after they learned/saw it on that architecture with other mcus and architectures (only to fail).

this is a very educational exercise and I recommend you try it.  use a timer as reference and sample it ideally with a single load instruction before and after the code under test.  If you are doing all of this on an operating system there might be enough noise that you dont actually see as much detail in the differences.  You will have created other cycle stealers that are added to the overall timing, in particular the calls to get the time before and after the code under test.

Body:
I want to write a one-second delay loop in assembly language and I'm not sure what would be the count for the loop so that it'll delay for 1 second.

Here is what I have so far:

MOV   R1, #count

DELAY_LOOP:
             SUBS   R1, R1, #1

             BNE  DELAY_LOOP

I'm using a Beaglebone Black. Thanks in advance!


问:
How to get height of entire document with JavaScript?
Some documents I can't get the height of the document (to position something absolutely at the very bottom). Additionally, a padding-bottom on  seems to do nothing on these pages, but do on the pages where height will return. Case(s) in point:

http://fandango.com

http://paperbackswap.com

On Fandango

jQuery's $(document).height(); returns correct value

document.height returns 0

document.body.scrollHeight returns 0

On Paperback Swap:

jQuery's $(document).height(); TypeError: $(document) is null

document.height returns an incorrect value

document.body.scrollHeight returns an incorrect value

Note: I have browser level permissions, if there is some trick there.

答:
The proper answer for 2017 is:

document.documentElement.getBoundingClientRect().height

Unlike document.body.scrollHeight this method accounts for body margins.
It also gives fractional height value, which can be useful in some cases


问:
Failed to load resource: the server responded with a status of 503 (Service Unavailable) favicon.ico
I am trying to deploy my Node.JS site through Heroku and I keep getting this error "Failed to load resource: the server responded with a status of 503 (Service Unavailable) favicon.ico" I searched around and thought I would add the following to my header

```<code><link rel="shortcut icon" href="">
</code>```

However I am still getting this error. Any ideas?

答:
This specific problem is why packages like express-favicion and serve-favicon exist. They add a handler for the favicon.ico file.

What you've done there has only made things worse as it tells the client that the icon for the page is actually the page itself.

Body:
I am trying to deploy my Node.JS site through Heroku and I keep getting this error "Failed to load resource: the server responded with a status of 503 (Service Unavailable) favicon.ico" I searched around and thought I would add the following to my header

<link rel="shortcut icon" href="">

However I am still getting this error. Any ideas?


问:
R: How to combine an arbitrary number of functions and parameters into one computation
I am trying to combine vectors of parameters of arbitrary length into one logical computation.  Basically, I am trying to compute:

```<code>    get("&")(get("&")(sigBuy(">",
               30.30815,
               30.39961),
            sigBuy(">",
               30.39961,
               30.47286)),
            sigBuy(">",
               30.47286,
               30.519))
</code>```

from the following sets of parameters:

```<code>IndicatorA <- c(30.30815, 30.39961, 30.47286)
IndicatorB <- c(30.39961, 30.47286, 30.519)
BuyConditions <- c(">", ">", ">")
BuySigConditions <- c("&", "&")
</code>```

and function sigBuy():

```<code>sigBuy <- function(BuyCondition, IndicatorA, IndicatorB) {
    out <- get(get("BuyCondition"))(IndicatorA, IndicatorB)
    return(out)
}
</code>```

The actual logic I am trying to apply in this case is

```<code>IndicatorA[1] > IndicatorB[1] &
    IndicatorA[2] > IndicatorB[2] &
     IndicatorA[3] > IndicatorB[3]
</code>```

In actual practice, I do not know the length of the parameters IndicatorA, IndicatorB, BuyConditions, or BuySigConditions, other than to constrain that the lengths of IndicatorA, IndicatorB, & BuyConditions are equal, and that length of BuySigConditions is one less than the rest.  Additionally, BuyConditions can be any of <, >, <=, >=, ==, !=, and BuySigConditions can be & or |.  I will be functionalizing the logic such that the user will pass in an arbitrary length of vector parameters (following length constraints above), and my function will construct the computation I am trying to obtain, resulting in this example as:

```<code>[1] FALSE
</code>```

答:
do.call and mapply can help here.

```<code>sigBuy <- function(cond, ...) do.call(cond, list(...))
reln <- mapply(sigBuy, BuyConditions, IndicatorA, IndicatorB)

result <- reln[1]
for(i in seq_along(BuySigConditions))
  result <- do.call(BuySigConditions[i], list(result, reln[i+1]))
result
</code>```

Body:
I am trying to combine vectors of parameters of arbitrary length into one logical computation.  Basically, I am trying to compute:

    get("&")(get("&")(sigBuy(">",
               30.30815,
               30.39961),
            sigBuy(">",
               30.39961,
               30.47286)),
            sigBuy(">",
               30.47286,
               30.519))

from the following sets of parameters:

IndicatorA <- c(30.30815, 30.39961, 30.47286)
IndicatorB <- c(30.39961, 30.47286, 30.519)
BuyConditions <- c(">", ">", ">")
BuySigConditions <- c("&", "&")

and function sigBuy():

sigBuy <- function(BuyCondition, IndicatorA, IndicatorB) {
    out <- get(get("BuyCondition"))(IndicatorA, IndicatorB)
    return(out)
}

The actual logic I am trying to apply in this case is

IndicatorA[1] > IndicatorB[1] &
    IndicatorA[2] > IndicatorB[2] &
     IndicatorA[3] > IndicatorB[3]

In actual practice, I do not know the length of the parameters IndicatorA, IndicatorB, BuyConditions, or BuySigConditions, other than to constrain that the lengths of IndicatorA, IndicatorB, & BuyConditions are equal, and that length of BuySigConditions is one less than the rest.  Additionally, BuyConditions can be any of <, >, <=, >=, ==, !=, and BuySigConditions can be & or |.  I will be functionalizing the logic such that the user will pass in an arbitrary length of vector parameters (following length constraints above), and my function will construct the computation I am trying to obtain, resulting in this example as:

[1] FALSE

Body:
do.call and mapply can help here.

sigBuy <- function(cond, ...) do.call(cond, list(...))
reln <- mapply(sigBuy, BuyConditions, IndicatorA, IndicatorB)

result <- reln[1]
for(i in seq_along(BuySigConditions))
  result <- do.call(BuySigConditions[i], list(result, reln[i+1]))
result


问:
Replace string with output of command, different each time
I have many files and I want to replace the class names with a UUID. I figured out this

```<code>sed -i -r "s/ Class \w(\w|\d)+/ Class C$(python -c 'import uuid;print(uuid.uuid4().hex)')/"
</code>```

It works fine when the pattern only occurs once in each file. However if the pattern occurs more than once, each occurence is replaced by the same number.

Class1.vb

```<code>Public Class Class1
    Public ReadOnly Property P As String = "hello"
End Class

Public Class Class2
    Public ReadOnly Property P As String = "hello"
End Class
</code>```

$ sed -r "s/ Class \w(\w|\d)+/ Class C$(echo $RANDOM)/" Class1.vb
Public Class C27244
        Public ReadOnly Property P As String = "hello"
End Class

Public Class C27244
        Public ReadOnly Property P As String = "hello"
End Class
```

I expect the two classes to have different names. How do I fix my script?

答:
More as a proof of concept than a serious alternative: a GNU sed solution.

sed -E -e '/Class \w+/{h;s/.*/bash -c "echo C\\$RANDOM"/;e' \
    -e 'G;s/(.*)\n(.*Class )\w+(.*)/\2\1\3/}' infile
```

<p>resulting in</p>

<pre class="lang-none prettyprint-override"><code>Public Class C24276
    Public ReadOnly Property P As String = "hello"
End Class

Public Class C28554
    Public ReadOnly Property P As String = "hello"
End Class
</code>```

Here is how it works:

/Class \w+/ {                           # If the line matches "Class <name>"
    h                                   # Copy pattern space to hold space
    s/.*/bash -c "echo C\\$RANDOM"/     # Write Bash command into pattern space
    e                                   # Replace pattern space with command output
    G                                   # Append hold space to pattern space
    s/(.*)\n(.*Class )\w+(.*)/\2\1\3/   # Swap class name with random number
}
```

<p>Remarks:</p>

<ul>
<li>This uses GNU extensions: notably the <code>\w</code> character class and the <code>e</code> command.

<ul>
<li><code>\w</code> includes digits, so there is no need for <code>(\w|\d)</code>.</li>
</ul></li>
<li>The one-liner version is split into two commands using <code>-e</code> because the <code>e</code> command cannot be followed by anything, or that anything is interpreted as the command.</li>
<li>The command to be run can't just be <code>echo C$RANDOM</code> because the <code>e</code> command uses <code>sh</code> instead of Bash, and <code>sh</code> might not have <code>$RANDOM</code> (like on Ubuntu, where <code>sh</code> is dash).</li>
<li><p>Because the command is in double quotes, the <code>$</code> in <code>$RANDOM</code> has to be escaped, and because sed does a first pass before the shell sees the command, is has to be escaped twice. Alternatively, I could have used</p>

<pre class="lang-sh prettyprint-override"><code>s/.*/bash -c '\''echo C$RANDOM'\''/
</code>```

to single quote the command, but that's not very readable either.

Body:
I have many files and I want to replace the class names with a UUID. I figured out this

sed -i -r "s/ Class \w(\w|\d)+/ Class C$(python -c 'import uuid;print(uuid.uuid4().hex)')/"

It works fine when the pattern only occurs once in each file. However if the pattern occurs more than once, each occurence is replaced by the same number.

Class1.vb

Public Class Class1
    Public ReadOnly Property P As String = "hello"
End Class

Public Class Class2
    Public ReadOnly Property P As String = "hello"
End Class

$ sed -r "s/ Class \w(\w|\d)+/ Class C$(echo $RANDOM)/" Class1.vb
Public Class C27244
        Public ReadOnly Property P As String = "hello"
End Class

Public Class C27244
        Public ReadOnly Property P As String = "hello"
End Class

I expect the two classes to have different names. How do I fix my script?

Body:
More as a proof of concept than a serious alternative: a GNU sed solution.

sed -E -e '/Class \w+/{h;s/.*/bash -c "echo C\\$RANDOM"/;e' \
    -e 'G;s/(.*)\n(.*Class )\w+(.*)/\2\1\3/}' infile

resulting in

Public Class C24276
    Public ReadOnly Property P As String = "hello"
End Class

Public Class C28554
    Public ReadOnly Property P As String = "hello"
End Class

Here is how it works:

/Class \w+/ {                           # If the line matches "Class <name>"
    h                                   # Copy pattern space to hold space
    s/.*/bash -c "echo C\\$RANDOM"/     # Write Bash command into pattern space
    e                                   # Replace pattern space with command output
    G                                   # Append hold space to pattern space
    s/(.*)\n(.*Class )\w+(.*)/\2\1\3/   # Swap class name with random number
}

Remarks:

This uses GNU extensions: notably the \w character class and the e command.

\w includes digits, so there is no need for (\w|\d).

The one-liner version is split into two commands using -e because the e command cannot be followed by anything, or that anything is interpreted as the command.

The command to be run can't just be echo C$RANDOM because the e command uses sh instead of Bash, and sh might not have $RANDOM (like on Ubuntu, where sh is dash).

Because the command is in double quotes, the $ in $RANDOM has to be escaped, and because sed does a first pass before the shell sees the command, is has to be escaped twice. Alternatively, I could have used

s/.*/bash -c '\''echo C$RANDOM'\''/

to single quote the command, but that's not very readable either.


问:
User input upperCase and lowerCase - Java
I am attempting to take an input of A or B in either Uppercase or LowerCase to follow on through the if statement. I can't figure out how to do this. At the moment, it's only taking in UpperCase A or B. Looked around the forum and the class notes, came up with nothing. Any help would be appriciated!
I tried using toUpperCase() but don't think i am putting it in the right place. It keeps giving me an error</p>

```<code>import java.util.Scanner;

public class printNumber{
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please select an option between A or B: ");
        char user = input.next().charAt(0);

        System.out.println("You have selected " +user+ " : ");
        if (user == 'A'){
            for(int n=1; n<=100; n++){
                if((n%2)==0)
                    System.out.println(n);
            }
        }
        else if (user =='B'){
            for (int x =1; x<=100; x=x+2){
                System.out.println(x);
            }
        }
        else
            System.out.println("Error, please try again!");
    }
}
</code>```

答:
Try this

```<code>if (user == 'A' || user == 'a')
</code>```

The same for 'B'

Body:
I am attempting to take an input of A or B in either Uppercase or LowerCase to follow on through the if statement. I can't figure out how to do this. At the moment, it's only taking in UpperCase A or B. Looked around the forum and the class notes, came up with nothing. Any help would be appriciated!
I tried using toUpperCase() but don't think i am putting it in the right place. It keeps giving me an error

import java.util.Scanner;

public class printNumber{
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please select an option between A or B: ");
        char user = input.next().charAt(0);

        System.out.println("You have selected " +user+ " : ");
        if (user == 'A'){
            for(int n=1; n<=100; n++){
                if((n%2)==0)
                    System.out.println(n);
            }
        }
        else if (user =='B'){
            for (int x =1; x<=100; x=x+2){
                System.out.println(x);
            }
        }
        else
            System.out.println("Error, please try again!");
    }
}

Body:
Try this

if (user == 'A' || user == 'a')

The same for 'B'


问:
Summation query using groupBy() function in laravel
A table where X, Y and Z have some individual amounts.

Sample data:

```<code>Name | Amount |  Date
—————|————————|—————————
  X  |    100 | 15-11-17
  Y  |     50 | 15-11-17
  X  |     50 | 15-11-17
  Z  |     70 | 15-11-17
  Z  |     30 | 15-11-17
</code>```

Now I want to show a table where X will return one row with the summation of it's two values in the same date.

Expected result:

```<code>Name | Amount |  Date
—————|————————|—————————
  X  |    150 | 15-11-17
  Y  |     50 | 15-11-17
  Z  |    100 | 15-11-17
</code>```

So what is the laravel query for that? I use groupBy(). But can't get the targeted result.

Here is my laravel query code

```<code>$data = DB::table('transactions')
            ->select('transactions.*')
            ->groupBy('transactions.title_id')
            ->whereDate('transactions.created_at', '=', $date)
            ->get();
</code>```

And got this error continuously

```<code>"SQLSTATE[42000]: Syntax error or access violation: 1055 'finance_report.transactions.id' isn't in GROUP BY
</code>```

Anybody please help

答: You can use SUM(Amount) with groupBy(date)</p>

Body:
A table where X, Y and Z have some individual amounts.

Sample data:

Name | Amount |  Date
—————|————————|—————————
  X  |    100 | 15-11-17
  Y  |     50 | 15-11-17
  X  |     50 | 15-11-17
  Z  |     70 | 15-11-17
  Z  |     30 | 15-11-17

Now I want to show a table where X will return one row with the summation of it's two values in the same date.

Expected result:

Name | Amount |  Date
—————|————————|—————————
  X  |    150 | 15-11-17
  Y  |     50 | 15-11-17
  Z  |    100 | 15-11-17

So what is the laravel query for that? I use groupBy(). But can't get the targeted result.

Here is my laravel query code

$data = DB::table('transactions')
            ->select('transactions.*')
            ->groupBy('transactions.title_id')
            ->whereDate('transactions.created_at', '=', $date)
            ->get();

And got this error continuously

"SQLSTATE[42000]: Syntax error or access violation: 1055 'finance_report.transactions.id' isn't in GROUP BY

Anybody please help