问:
Why do I get InputMismatchException in my Java programme?
I have made a dog kennel/pound in Java that is working (in eclipse). But when I test it I get this InputMismatchException.
Is it something wrong with the way I did the switch-statement and the cases? Or something with my Scanner? The program is compiling so I don't understand.
One of the requirements in the assignment is for the program to accept these commands:

register new dog

increase age

list dogs

remove dog

exit

Another requirement is that the test program must identify the word "Error".
Please help me!!!

Here is the Dog class:

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

public class Dog {

    private String dogName;
    private String dogRace;
    private int dogAge;
    private double dogWeight;

    public Dog(String name, String race, int age, double weight){
    this.dogName = name;
    this.dogRace = race;
    this.dogAge = age;
    this.dogWeight = weight;
    }

    public String getDogName (){
        return this.dogName;
    }
    public String getDogRace (){
        return this.dogRace;
    }
    public void birthday(){
        dogAge = dogAge+1;
    }
    public int getDogAge(){
        return this.dogAge;
    }
    public double getDogWeight(){
        return this.dogWeight;
    }
    public double getDogTailLength(){
        if (!getDogRace().equalsIgnoreCase("Tax"))
        if(!getDogRace().equalsIgnoreCase("Dachshund")){
            return ((dogAge * dogWeight)/ 10);

        }
        return 3.7;
    }

    public String toString(){
        return "Name: " + getDogName() + ", Race: " + getDogRace() + ", Age: " + getDogAge() + ", Weight: " +
                getDogWeight() + ", Tail: " + getDogTailLength();

    }
}
</code>```

And here is the Main class:

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

public class Main {

    public static Scanner scan = new Scanner(System.in);

    private ArrayList <Dog> dogList = new ArrayList<Dog>();

    public ArrayList<Dog> getDogList(){
        return this.dogList;
    }

    public String dogMenu(){
        return "Choose a commande below: \n1) Register new dog \n2) Increase age \n3) List dogs \n4)"
                    + " Remove dog \n5) Exit ";
    }
    public String error(){
        return "ERROR: please choose a number between 1-5";
    }
    public void addDog(){
        System.out.println("1- Enter the dogs name: ");
        String name = scan.next();
        System.out.println("2- Enter the dogs race: ");
        String race = scan.next();
        System.out.println("3- Enter the dogs age: ");
        int age = scan.nextInt();
        System.out.println("4- Enter the dogs weight: ");
        double weight = scan.nextDouble();
        Dog newDog = new Dog(name, race, age, weight);
        getDogList().add(newDog);
        System.out.println(newDog);

    }

    public void ageDog(){
        System.out.println("Which dog would you like to age? (State the name): ");
        String write = scan.next();
        for(Dog d: getDogList()){
            if(d.getDogName().equalsIgnoreCase(write)){
                d.birthday();
            }else{
                System.out.println("ERROR: The dog doesn't exist in the kennel");

            }
        }
    }

    public void dogTail(){
        System.out.println("State the tail length: ");
        double dogTailLengthIn = scan.nextDouble();
        for(Dog d1: getDogList()){
            if(d1.getDogTailLength()>= dogTailLengthIn){
                System.out.println(d1);
            }
        }
        if(getDogList().isEmpty()){
            System.out.println("ERROR: There are no dogs!!!");

    }

    }
    public void deleteDog(){
        System.out.println("Which dog do you want to delete? (State the name): ");
        String nameIn = scan.next();
        boolean delete = false;
        for(int a = 0; a <getDogList().size();a++){
            if(getDogList().get(a).getDogName().equalsIgnoreCase(nameIn)){
                getDogList().remove(a);
                delete = true;
            }
        }
        if(delete){
            System.out.println("The dog " + nameIn + " is deleted from the register.");
        }else{
            System.out.println("The dog " + nameIn + " doesn't exist in the register.");
        }
    }
    public void exit(){
        System.out.println("Thank you. Hope to see you soon!");
        scan.close();
        System.exit(0);
    }
    public static void main(String[] args){

        /*      Dog betty = new Dog("pudel", "Betty", 4, 22, 1.5);

        Dog jonte = new Dog("rotweiler", "Jontis", 8, 60, 2);

        Dog jonas = new Dog("chihuahua", "Jonis", 2, 5, 0.3);*/

        Main kennel = new Main();

        while (true){
            System.out.print(kennel.dogMenu());
            int write = scan.nextInt();

            switch(write){

            case 1:
                kennel.addDog();
                break;

            case 2:
                kennel.ageDog();
                break;

            case 3:
                kennel.dogTail();
                break;

            case 4:
                kennel.deleteDog();
                break;

            case 5:
                kennel.exit();
            default:
                System.out.println(kennel.error());
            }
        }
    }
}
</code>```

Here is the problem:

```<code>Choose a commande below:
1) Register new dog
2) Increase age
3) List dogs
4) Remove dog
5) Exit

[IN:wrong command]
    java.util.concurrent.TimeoutException [LOOKING FOR: Any of [[fel case insensitive], [error case insensitive]]]
    [ERR: Exception in thread "main" java.util.InputMismatchException
      at java.util.Scanner.throwFor(Scanner.java:864)
      at java.util.Scanner.next(Scanner.java:1485)
      at java.util.Scanner.nextInt(Scanner.java:2117)
      at java.util.Scanner.nextInt(Scanner.java:2076)
      at Main.main(Main.java:96)]
</code>```

I get exactly this in every case!!

答: You are getting InputMismatchException because you are typing a String as an input but int write = scan.nextInt(); is expecting an int value from the user, so there is a mismatch of datatype. You code will work fine if you type the number of the option and not the string but still you need to change it for the input Error

Body:
I have made a dog kennel/pound in Java that is working (in eclipse). But when I test it I get this InputMismatchException.
Is it something wrong with the way I did the switch-statement and the cases? Or something with my Scanner? The program is compiling so I don't understand.
One of the requirements in the assignment is for the program to accept these commands:

register new dog

increase age

list dogs

remove dog

exit

Another requirement is that the test program must identify the word "Error".
Please help me!!!

Here is the Dog class:

import java.util.*;

public class Dog {

    private String dogName;
    private String dogRace;
    private int dogAge;
    private double dogWeight;

    public Dog(String name, String race, int age, double weight){
    this.dogName = name;
    this.dogRace = race;
    this.dogAge = age;
    this.dogWeight = weight;
    }

    public String getDogName (){
        return this.dogName;
    }
    public String getDogRace (){
        return this.dogRace;
    }
    public void birthday(){
        dogAge = dogAge+1;
    }
    public int getDogAge(){
        return this.dogAge;
    }
    public double getDogWeight(){
        return this.dogWeight;
    }
    public double getDogTailLength(){
        if (!getDogRace().equalsIgnoreCase("Tax"))
        if(!getDogRace().equalsIgnoreCase("Dachshund")){
            return ((dogAge * dogWeight)/ 10);

        }
        return 3.7;
    }

    public String toString(){
        return "Name: " + getDogName() + ", Race: " + getDogRace() + ", Age: " + getDogAge() + ", Weight: " +
                getDogWeight() + ", Tail: " + getDogTailLength();

    }
}

And here is the Main class:

import java.util.*;

public class Main {

    public static Scanner scan = new Scanner(System.in);

    private ArrayList <Dog> dogList = new ArrayList<Dog>();

    public ArrayList<Dog> getDogList(){
        return this.dogList;
    }

    public String dogMenu(){
        return "Choose a commande below: \n1) Register new dog \n2) Increase age \n3) List dogs \n4)"
                    + " Remove dog \n5) Exit ";
    }
    public String error(){
        return "ERROR: please choose a number between 1-5";
    }
    public void addDog(){
        System.out.println("1- Enter the dogs name: ");
        String name = scan.next();
        System.out.println("2- Enter the dogs race: ");
        String race = scan.next();
        System.out.println("3- Enter the dogs age: ");
        int age = scan.nextInt();
        System.out.println("4- Enter the dogs weight: ");
        double weight = scan.nextDouble();
        Dog newDog = new Dog(name, race, age, weight);
        getDogList().add(newDog);
        System.out.println(newDog);

    }

    public void ageDog(){
        System.out.println("Which dog would you like to age? (State the name): ");
        String write = scan.next();
        for(Dog d: getDogList()){
            if(d.getDogName().equalsIgnoreCase(write)){
                d.birthday();
            }else{
                System.out.println("ERROR: The dog doesn't exist in the kennel");

            }
        }
    }

    public void dogTail(){
        System.out.println("State the tail length: ");
        double dogTailLengthIn = scan.nextDouble();
        for(Dog d1: getDogList()){
            if(d1.getDogTailLength()>= dogTailLengthIn){
                System.out.println(d1);
            }
        }
        if(getDogList().isEmpty()){
            System.out.println("ERROR: There are no dogs!!!");

    }

    }
    public void deleteDog(){
        System.out.println("Which dog do you want to delete? (State the name): ");
        String nameIn = scan.next();
        boolean delete = false;
        for(int a = 0; a <getDogList().size();a++){
            if(getDogList().get(a).getDogName().equalsIgnoreCase(nameIn)){
                getDogList().remove(a);
                delete = true;
            }
        }
        if(delete){
            System.out.println("The dog " + nameIn + " is deleted from the register.");
        }else{
            System.out.println("The dog " + nameIn + " doesn't exist in the register.");
        }
    }
    public void exit(){
        System.out.println("Thank you. Hope to see you soon!");
        scan.close();
        System.exit(0);
    }
    public static void main(String[] args){

        /*      Dog betty = new Dog("pudel", "Betty", 4, 22, 1.5);

        Dog jonte = new Dog("rotweiler", "Jontis", 8, 60, 2);

        Dog jonas = new Dog("chihuahua", "Jonis", 2, 5, 0.3);*/

        Main kennel = new Main();

        while (true){
            System.out.print(kennel.dogMenu());
            int write = scan.nextInt();

            switch(write){

            case 1:
                kennel.addDog();
                break;

            case 2:
                kennel.ageDog();
                break;

            case 3:
                kennel.dogTail();
                break;

            case 4:
                kennel.deleteDog();
                break;

            case 5:
                kennel.exit();
            default:
                System.out.println(kennel.error());
            }
        }
    }
}

Here is the problem:

Choose a commande below:
1) Register new dog
2) Increase age
3) List dogs
4) Remove dog
5) Exit

[IN:wrong command]
    java.util.concurrent.TimeoutException [LOOKING FOR: Any of [[fel case insensitive], [error case insensitive]]]
    [ERR: Exception in thread "main" java.util.InputMismatchException
      at java.util.Scanner.throwFor(Scanner.java:864)
      at java.util.Scanner.next(Scanner.java:1485)
      at java.util.Scanner.nextInt(Scanner.java:2117)
      at java.util.Scanner.nextInt(Scanner.java:2076)
      at Main.main(Main.java:96)]

I get exactly this in every case!!


来源: stackexchange

问:
Comparison method violates its general contract when I try to order contacts
I would like to compare my contacts to get an alphabetical order but I have this error :

```<code> java.lang.IllegalArgumentException: Comparison method violates its general contract!
</code>```

This happen when I call :

```<code>Collections.sort(aVoid, new CustomComparator());
</code>```

This is my CustomComparator :

```<code>public class CustomComparator implements Comparator<ContactItems> {
        @Override
        public int compare(ContactItems o1, ContactItems o2) {
            if (o1.getName() == null || o2.getName() == null)
                return 0;
            else
                return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
        }
    }
</code>```

My aVoid array is the result of the method @onPostExecute(List<ContactItems> aVoid) of the class AsyncTaskGetContacts extends AsyncTask<Void, Void, List<ContactItems>>

答:
Consider three values, A, B, and C. Let's say A's name is null, while B and C's names are non-null and are different.

In your comparator, compare(A, B) will return 0. And compare(A, C) will return 0. According to the general contract of comparators, if A==B and A==C, then B==C. But that is not true for your data set. This means there is an error in your compare method.

You need a better method for handling nulls. Probably something like

```<code>public int compare(...) {
    if (o1.getName() == null && o2.getName() == null) {
        return 0;
    } else if (o1.getName() == null) {
        return 1;
    } else if (o2.getName() == null) {
        return -1;
    } else {
        return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to compare my contacts to get an alphabetical order but I have this error :

 java.lang.IllegalArgumentException: Comparison method violates its general contract!

This happen when I call :

Collections.sort(aVoid, new CustomComparator());

This is my CustomComparator :

public class CustomComparator implements Comparator<ContactItems> {
        @Override
        public int compare(ContactItems o1, ContactItems o2) {
            if (o1.getName() == null || o2.getName() == null)
                return 0;
            else
                return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
        }
    }

My aVoid array is the result of the method @onPostExecute(List<ContactItems> aVoid) of the class AsyncTaskGetContacts extends AsyncTask<Void, Void, List<ContactItems>>

Body:
Consider three values, A, B, and C. Let's say A's name is null, while B and C's names are non-null and are different.

In your comparator, compare(A, B) will return 0. And compare(A, C) will return 0. According to the general contract of comparators, if A==B and A==C, then B==C. But that is not true for your data set. This means there is an error in your compare method.

You need a better method for handling nulls. Probably something like

public int compare(...) {
    if (o1.getName() == null && o2.getName() == null) {
        return 0;
    } else if (o1.getName() == null) {
        return 1;
    } else if (o2.getName() == null) {
        return -1;
    } else {
        return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
    }
}


问:
python splinter webdriver can't start
I've wrote a simple file splinter_test.py

```<code>    from splinter import Browser

    print("here")
    br = Browser()
</code>```

When I run the code, it prints

Ran 0 tests in 0.000s

OK

I run with IDLE, but it prints the same in the command line.
It doesn't even gets to my print("here") statement.
Also, the Browser import doesn't work, i.e I can't use b = Browser()

答:
it seems you don't have "splinter" module installed in you pc.
Just try this , go to run and start command prompt, in that put the following line

```<code>python -m pip install splinter
</code>```

it will install it, I tried what you have written, it needs gecodriver in the path so go to this link "https://github.com/mozilla/geckodriver/releases/download/v0.19.1/geckodriver-v0.19.1-win64.zip"
unzip it and put this file in the path.Done

Title: python splinter webdriver can't start

Body:
I've wrote a simple file splinter_test.py

    from splinter import Browser

    print("here")
    br = Browser()

When I run the code, it prints

Ran 0 tests in 0.000s

OK

I run with IDLE, but it prints the same in the command line.
It doesn't even gets to my print("here") statement.
Also, the Browser import doesn't work, i.e I can't use b = Browser()

Body:
it seems you don't have "splinter" module installed in you pc.
Just try this , go to run and start command prompt, in that put the following line

python -m pip install splinter

it will install it, I tried what you have written, it needs gecodriver in the path so go to this link "https://github.com/mozilla/geckodriver/releases/download/v0.19.1/geckodriver-v0.19.1-win64.zip"
unzip it and put this file in the path.Done


问:
Replace text within variable in Bash
I am saving a Curl response into a variable here:

```<code>results=$(curl -username:password "URL/api/search/dates?dateFields=created&from=${Three_Months_Ago}&today&repos=generic-sgca" | jq -r '.results[].uri')
echo "$results"
</code>```

which returns the following:

```<code>URL/api/storage/generic-sgca/Lastest_Deploy.tar
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-windows-installer.exe
</code>```

In each of these lines, I need to remove the "/api/storage" part of the URL. How can I accomplish this?

答:
With parameter expansion:</p>

```<code>echo "${results//\/api\/storage}"
</code>```

Title: Replace text within variable in Bash

Body:
I am saving a Curl response into a variable here:

results=$(curl -username:password "URL/api/search/dates?dateFields=created&from=${Three_Months_Ago}&today&repos=generic-sgca" | jq -r '.results[].uri')
echo "$results"

which returns the following:

URL/api/storage/generic-sgca/Lastest_Deploy.tar
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-windows-installer.exe

In each of these lines, I need to remove the "/api/storage" part of the URL. How can I accomplish this?

Body:
With parameter expansion:

echo "${results//\/api\/storage}"


问:
sorting two corresponding arrays with user information
A jTable has been created to store information the user inputs. ClothesName and price is linked therefore two arrays need to be corresponding in order to implement binary search, (the clothesName & price). This is all done in a button called 'Search' however I'm not quite sure on how to do this so any help would be appreciated.

```<code>  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

  private String[] ClothesName;
  private Double[] price;

  int iPrice = Integer.parseInt(price);

public findingPrice(String ClothesName, int iPrice) {
    this.ClothesName = ClothesName;
    this.iPrice = iPrice;
}

public String getClothesName() {
    return this.ClothesName;
}

public double iPrice() {
    return this.iPrice;
}

@Override
public int compareTo(findingPrice price)
{
    return iPrice.compareTo(findingPrice.getiPrice()));
}
</code>```

If there is an easier way for me to retrieve data from the two columns that are linked (clothesname is linked to price so if someone searches for an item that is £50 the clothesname comes up) then also that would be appreciated also.

The expected result is to have the clothesName and Price sorted (price lowest to highest with the clothesname also in order) using collection.sort();  --> as long as binary search can be implemented to the method.

Here is my method to add information to my jTable1.

```<code>     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
        String ClothesID = jTextField1.getText();
        String ClothesName = jTextField2.getText();
        Catergory = jComboBox1.getSelectedItem().toString();
        String Price = jTextField3.getText();
        String[] name = {ClothesID, Catergory, ClothesName, Colour, Price};
        int rowCount = jTable1.getRowCount();
        int columnCount = jTable1.getColumnCount();
        int nextRow = 0;
        boolean emptyRowFlag = false;
        String s;
        do {
            s = (String)jTable1.getValueAt(nextRow,0);
            if (s != null && s.length() != 0) nextRow++;
            else emptyRowFlag = true;
        } while (nextRow < rowCount && !emptyRowFlag);
        for (int i=0; i<columnCount; i++)
        jTable1.setValueAt(name[i],nextRow,i);
   } catch (Exception e){ JOptionPane.showMessageDialog(null, "Error"); }
jTextField1.setText("");
jTextField2.setText("");
jTextField2.setText("");
jTextField3.setText("");
// TODO add your handling code here:
    }
</code>```

And this is the method to sort thanks to the @Dax Loy:

```<code>public class NamePrice {

   private String[] clothingNames;
   private double[] price; //You used Double which is the object wrapper, either way works
   //This map maps the clothing name to price
   private Map<String, double> nameToPrice;
   //This map maps the price to the clothing name
   private Map<double, String> priceToName;

   public NamePrice(String[] cN, double[] p){

      //Takes the input and set it to the private variables
      clothingNames = cN;
      price = p;

      //Then we construct or map
      nameToPrice = new HashMap<String, double>();
      priceToName = new HashMap<double, String>();
      //Put everthing we have into the maps
      for(int i = 0; i < clothingNames.length && i < price.length; i++){
         nameToPrice.put(clothingNames[i], price[i]);
         priceToName.put(price[i], clothingNames[i]);
      }

      //Then we sort the arrays
      Arrays.sort(clothingNames);
      Arrays.sort(price);

   }
</code>```

But i already have a public class: public class CSInfo extends javax.swing.JFrame

I have no idea how to implement binary search into this now.

答:
From what I understand you are wanting two arrays, price and name, that are ordered numerically and alphabetically respectively. You also seem to hint at the idea of them being linked in some sense. This would be most easily done using two arrays and two maps.

The actual code would go something like this:

```<code>public class NamePrice {

   private String[] clothingNames;
   private double[] price; //You used Double which is the object wrapper, either way works
   //This map maps the clothing name to price
   private Map<String, double> nameToPrice;
   //This map maps the price to the clothing name
   private Map<double, String> priceToName;

   public NamePrice(String[] cN, double[] p){

      //Takes the input and set it to the private variables
      clothingNames = cN;
      price = p;

      //Then we construct or map
      nameToPrice = new HashMap<String, double>();
      priceToName = new HashMap<double, String>();
      //Put everthing we have into the maps
      for(int i = 0; i < clothingNames.length && i < price.length; i++){
         nameToPrice.put(clothingNames[i], price[i]);
         priceToName.put(price[i], clothingNames[i]);
      }

      //Then we sort the arrays
      Arrays.sort(clothingNames);
      Arrays.sort(price);

   }

}
</code>```

This ends up with us having two sorted arrays, clothingNames and price, and we have two maps to switch between the two values, nameToPrice and priceToName. This means you can search through either name or price and use the maps to find the corresponding value.

You would use the Arrays to search using your binary search to find the value you are looking for and the maps to convert them.

Also, you could use a bidirectional map but there is not one in the standard Java API so you would have to use some external library like the BidiMap from Apache Collections.

Finally, I am not sure what exactly you would use this for as you can just use the map to find the price from clothing or vice versa unless you specifically need the position of the name of clothing with respect to price or vice versa.

Body:
A jTable has been created to store information the user inputs. ClothesName and price is linked therefore two arrays need to be corresponding in order to implement binary search, (the clothesName & price). This is all done in a button called 'Search' however I'm not quite sure on how to do this so any help would be appreciated.

  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

  private String[] ClothesName;
  private Double[] price;

  int iPrice = Integer.parseInt(price);

public findingPrice(String ClothesName, int iPrice) {
    this.ClothesName = ClothesName;
    this.iPrice = iPrice;
}

public String getClothesName() {
    return this.ClothesName;
}

public double iPrice() {
    return this.iPrice;
}

@Override
public int compareTo(findingPrice price)
{
    return iPrice.compareTo(findingPrice.getiPrice()));
}

If there is an easier way for me to retrieve data from the two columns that are linked (clothesname is linked to price so if someone searches for an item that is £50 the clothesname comes up) then also that would be appreciated also.

The expected result is to have the clothesName and Price sorted (price lowest to highest with the clothesname also in order) using collection.sort();  --> as long as binary search can be implemented to the method.

Here is my method to add information to my jTable1.

     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
        String ClothesID = jTextField1.getText();
        String ClothesName = jTextField2.getText();
        Catergory = jComboBox1.getSelectedItem().toString();
        String Price = jTextField3.getText();
        String[] name = {ClothesID, Catergory, ClothesName, Colour, Price};
        int rowCount = jTable1.getRowCount();
        int columnCount = jTable1.getColumnCount();
        int nextRow = 0;
        boolean emptyRowFlag = false;
        String s;
        do {
            s = (String)jTable1.getValueAt(nextRow,0);
            if (s != null && s.length() != 0) nextRow++;
            else emptyRowFlag = true;
        } while (nextRow < rowCount && !emptyRowFlag);
        for (int i=0; i<columnCount; i++)
        jTable1.setValueAt(name[i],nextRow,i);
   } catch (Exception e){ JOptionPane.showMessageDialog(null, "Error"); }
jTextField1.setText("");
jTextField2.setText("");
jTextField2.setText("");
jTextField3.setText("");
// TODO add your handling code here:
    }

And this is the method to sort thanks to the @Dax Loy:

public class NamePrice {

   private String[] clothingNames;
   private double[] price; //You used Double which is the object wrapper, either way works
   //This map maps the clothing name to price
   private Map<String, double> nameToPrice;
   //This map maps the price to the clothing name
   private Map<double, String> priceToName;

   public NamePrice(String[] cN, double[] p){

      //Takes the input and set it to the private variables
      clothingNames = cN;
      price = p;

      //Then we construct or map
      nameToPrice = new HashMap<String, double>();
      priceToName = new HashMap<double, String>();
      //Put everthing we have into the maps
      for(int i = 0; i < clothingNames.length && i < price.length; i++){
         nameToPrice.put(clothingNames[i], price[i]);
         priceToName.put(price[i], clothingNames[i]);
      }

      //Then we sort the arrays
      Arrays.sort(clothingNames);
      Arrays.sort(price);

   }

But i already have a public class: public class CSInfo extends javax.swing.JFrame

I have no idea how to implement binary search into this now.

Body:
From what I understand you are wanting two arrays, price and name, that are ordered numerically and alphabetically respectively. You also seem to hint at the idea of them being linked in some sense. This would be most easily done using two arrays and two maps.

The actual code would go something like this:

public class NamePrice {

   private String[] clothingNames;
   private double[] price; //You used Double which is the object wrapper, either way works
   //This map maps the clothing name to price
   private Map<String, double> nameToPrice;
   //This map maps the price to the clothing name
   private Map<double, String> priceToName;

   public NamePrice(String[] cN, double[] p){

      //Takes the input and set it to the private variables
      clothingNames = cN;
      price = p;

      //Then we construct or map
      nameToPrice = new HashMap<String, double>();
      priceToName = new HashMap<double, String>();
      //Put everthing we have into the maps
      for(int i = 0; i < clothingNames.length && i < price.length; i++){
         nameToPrice.put(clothingNames[i], price[i]);
         priceToName.put(price[i], clothingNames[i]);
      }

      //Then we sort the arrays
      Arrays.sort(clothingNames);
      Arrays.sort(price);

   }

}

This ends up with us having two sorted arrays, clothingNames and price, and we have two maps to switch between the two values, nameToPrice and priceToName. This means you can search through either name or price and use the maps to find the corresponding value.

You would use the Arrays to search using your binary search to find the value you are looking for and the maps to convert them.

Also, you could use a bidirectional map but there is not one in the standard Java API so you would have to use some external library like the BidiMap from Apache Collections.

Finally, I am not sure what exactly you would use this for as you can just use the map to find the price from clothing or vice versa unless you specifically need the position of the name of clothing with respect to price or vice versa.


问:
Is accessing CPU cache (read and write) through C# possible?
I want to know if there are implemented stuff in C# which allows to access CPU cache. It is just interesting for me but I do not have something to do with the cpu cache at the moment. So I was wondering if it is a system limited access or it is avilable to users also. I am talking about L1/L2 or whatever they are called!

Would be nice to hear your comments, external linkes and maybe some code snippets! Thanks.

答:
```<code>public static string GetComponent(string hwclass, string syntax)
    {
        var mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + hwclass);
        foreach (var o in mos.Get())
        {
            var mj = (ManagementObject)o;
            CpuModel = Convert.ToString(mj[syntax]);
        }
        return CpuModel;
    }

private string L2CacheSize = HardwareManagement.GetComponent("Win32_Processor", "L2CacheSize");
private string L3CacheSize = HardwareManagement.GetComponent("Win32_Processor", "L3CacheSize");
</code>```


问:
In StackDriver logging viewer is there a way to query for entries that DO NOT contain a specific string
My question is wrt to the log viewer at https://console.cloud.google.com/logs/viewer All the examples here show how to search for existence of text but not for absence.

I want to use this functionality to search for errors that do not contain "Request was aborted after waiting too long to attempt to service your request."

答:
You can use Advanced Logs Filters which support the NOT boolean operator:

Boolean expressions

```<code>expression =
    ["NOT" | "-"] comparison {["AND" | "OR"] ["NOT" | "-"] comparison}
</code>```

From Introduction:

To use advanced filters in the Logs Viewer, select the drop-down menu
  at the end of the search bar, and choose Convert to advanced
  filter. You see the advanced filter interface pictured below:

In your case add the following line to the ones filled in by default when switching to the advanced filter:

```<code>NOT "Request was aborted after waiting too long to attempt to service your request."
</code>```

Body:
You can use Advanced Logs Filters which support the NOT boolean operator:

Boolean expressions

expression =
    ["NOT" | "-"] comparison {["AND" | "OR"] ["NOT" | "-"] comparison}

From Introduction:

To use advanced filters in the Logs Viewer, select the drop-down menu
  at the end of the search bar, and choose Convert to advanced
  filter. You see the advanced filter interface pictured below:

In your case add the following line to the ones filled in by default when switching to the advanced filter:

NOT "Request was aborted after waiting too long to attempt to service your request."


问:
dynamic multidimensional array c#
I am not sure whether or not this has been answered before, but this question is really specific. I am attempting to code a dungeon generator in c#, and I want the size of the array to be dynamic, and it to display in the console as a grid, per the size inputted. I got the array to be dynamic, and it can display every index in a grid form, but I can't figure out how to make the amount of indexes in a row dynamic. Here's what I have so far:

```<code>        Random rand = new Random();
        int num;
        num = Convert.ToInt32(Console.ReadLine());
        int x = num;
        int y = num;
        int i = x - 1;
        int j = y - 1;
        int[,] dungeon = new int[x,y];

        for(int z = 0; z <= i; z++)
        {
            int a = 0;
            for( a = 0; a <= j; a++)
              {
                  dungeon[a,z] = rand.Next(0,2);
              }

            }
            for (int h = 0; h <= i; h++)
            {
                if (h == 0)
                {
                    Console.WriteLine("#-#-#-#-#");
                }
            Console.WriteLine("|" + dungeon[h,0] + "|" + dungeon[h,1] + "|" + dungeon[h,2] + "|" + dungeon[h,3] + "|");
            Console.WriteLine("#-#-#-#-#");
</code>```

Excuse the messiness. It isn't quite finished yet.

答:
I want the size of the array to be dynamic

So if you have no restriction on Generic Collections, I would highly recommend using a List<>.  Ignoring better ways of scrubbing user input, your code using lists could look like the following.  Since we're using a Object oriented language, it's best to create objects that represent our needs (a cell, a grid, etc).  Then create properties or methods that represent things we need form those objects, (rows, columns, values).

So I'm going to throw you right into the deep end, but here are references for what i'm using.

Delegates, Anonymous Methods, and Lambda Expressions. - A very good article about all the different statements/abstractions of the same thing.

Lambda expressions () =>  - Microsoft Docs.

Lambda expressions in a Query - How to Query lists using Linq Methods with Lambda Expressions.

Func(TResult) - Basically another Delegate.. does C# have enough of these now?

Generic Classes; MyClass - The power of Generics!

DotNetFiddle Example.

```<code>using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        Random rand = new Random();
        int num;
        num = Convert.ToInt32(Console.ReadLine());
        Func<int> valueGenerator = () => { return rand.Next(0,2); };
        var dungeon = new Grid<int>(num, num, valueGenerator);

        foreach(var row in dungeon.Rows)
        {
            // First() - https://msdn.microsoft.com/en-us/library/bb291976(v=vs.110).aspx
            if (row.First().Row == 0)
            {
                Console.WriteLine("#-#-#-#-#");
            }
            // ToArray() - https://msdn.microsoft.com/en-us/library/bb298736(v=vs.110).aspx
            var rowValues = row.Select(r => r.Value.ToString()).ToArray();

            // string.Join() - https://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx
            var rowDisplay = string.Join("|", rowValues);

            // $ ie Interpolated Strings - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interpolated-strings
            Console.WriteLine($"|{rowDisplay}|");
            Console.WriteLine("#-#-#-#-#");
        }
    }

    public class Grid<T>
    {
        private int _numberOfRows;
        private int _numberOfColumns;

        // List<> - https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
        private List<Cell<T>> _cells;

        public Grid(int numberOfRows, int numberOfColumns)
        {
            if (numberOfRows == 0)
                throw new ArgumentOutOfRangeException("numberOfRows must be greater than zero.");
            if (numberOfColumns == 0)
                throw new ArgumentOutOfRangeException("numberOfColumns must be greater than zero.");

            _numberOfRows = numberOfRows;
            _numberOfColumns = numberOfColumns;

            // Enumerable.Range - https://msdn.microsoft.com/en-us/library/system.linq.enumerable.range(v=vs.110).aspx
            _cells = Enumerable.Range(0, _numberOfRows)
                // Select - https://msdn.microsoft.com/en-us/library/bb548891(v=vs.110).aspx
                .Select(r => Enumerable.Range(0, _numberOfColumns)
                        .Select(c => new Cell<T>
                                {
                                    Row = r,
                                    Col = c
                                })
                        // ToList() - https://msdn.microsoft.com/en-us/library/bb342261(v=vs.110).aspx
                        .ToList())
                // - https://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany(v=vs.110).aspx
                .SelectMany(c => c)
                .ToList();
        }

        public Grid(int numberOfRows, int numberOfColumns, Func<T> valueGenerator)
        {
            if (numberOfRows == 0)
                throw new ArgumentOutOfRangeException("numberOfRows must be greater than zero.");
            if (numberOfColumns == 0)
                throw new ArgumentOutOfRangeException("numberOfColumns must be greater than zero.");

            _numberOfRows = numberOfRows;
            _numberOfColumns = numberOfColumns;

            _cells = Enumerable.Range(0, _numberOfRows)
                .Select(r => Enumerable.Range(0, _numberOfColumns)
                        .Select(c => new Cell<T>
                                {
                                    Row = r,
                                    Col = c,
                                    Value = valueGenerator()
                                })
                        .ToList())
                .SelectMany(c => c)
                .ToList();
        }

        public IEnumerable<ICell<T>> Cells
        {
            get
            {
                return _cells;
            }
        }

        public IEnumerable<IEnumerable<ICell<T>>> Rows
        {
            get
            {
                return _cells.GroupBy(c => c.Row)
                    .Select(gs => gs.OrderBy(g => g.Col).ToList())
                    .ToList();
            }
        }

        public IEnumerable<IEnumerable<ICell<T>>> Columns
        {
            get
            {
                return _cells.GroupBy(c => c.Col)
                    .Select(gs => gs.OrderBy(g => g.Row).ToList())
                    .ToList();
            }
        }

        // We expose the Interface because we don't want anyone outside grid modifying
        // Row or Col
        public interface ICell<T>
        {
            int Row { get; }
            int Col { get; }
            T Value { get; set; }
        }

        private class Cell<T> : ICell<T>
        {
            public T Value { get; set; }
            public int Row { get; set; }
            public int Col { get; set; }
        }

    }

}
</code>```

Output (well the 0s and 1s are random so...)

4

```<code>#-#-#-#-#
|0|0|0|1|
#-#-#-#-#
|1|0|0|1|
#-#-#-#-#
|0|0|1|0|
#-#-#-#-#
|0|1|1|0|
#-#-#-#-#
</code>```

After all of this you might be asking yourself, why use a generic class Grid?  Well I doubt that the only thing you want to store in a Cell is an int.  Maybe you want to store a full object that represents all sorts of things...

int Replaced with DungeonCell<>

ContentLicense: CC BY-SA 4.0

Title: dynamic multidimensional array c#

Body:
I am not sure whether or not this has been answered before, but this question is really specific. I am attempting to code a dungeon generator in c#, and I want the size of the array to be dynamic, and it to display in the console as a grid, per the size inputted. I got the array to be dynamic, and it can display every index in a grid form, but I can't figure out how to make the amount of indexes in a row dynamic. Here's what I have so far:

        Random rand = new Random();
        int num;
        num = Convert.ToInt32(Console.ReadLine());
        int x = num;
        int y = num;
        int i = x - 1;
        int j = y - 1;
        int[,] dungeon = new int[x,y];

        for(int z = 0; z <= i; z++)
        {
            int a = 0;
            for( a = 0; a <= j; a++)
              {
                  dungeon[a,z] = rand.Next(0,2);
              }

            }
            for (int h = 0; h <= i; h++)
            {
                if (h == 0)
                {
                    Console.WriteLine("#-#-#-#-#");
                }
            Console.WriteLine("|" + dungeon[h,0] + "|" + dungeon[h,1] + "|" + dungeon[h,2] + "|" + dungeon[h,3] + "|");
            Console.WriteLine("#-#-#-#-#");

Excuse the messiness. It isn't quite finished yet.

Body:
I want the size of the array to be dynamic

So if you have no restriction on Generic Collections, I would highly recommend using a List<>.  Ignoring better ways of scrubbing user input, your code using lists could look like the following.  Since we're using a Object oriented language, it's best to create objects that represent our needs (a cell, a grid, etc).  Then create properties or methods that represent things we need form those objects, (rows, columns, values).

So I'm going to throw you right into the deep end, but here are references for what i'm using.

Delegates, Anonymous Methods, and Lambda Expressions. - A very good article about all the different statements/abstractions of the same thing.

Lambda expressions () =>  - Microsoft Docs.

Lambda expressions in a Query - How to Query lists using Linq Methods with Lambda Expressions.

Func(TResult) - Basically another Delegate.. does C# have enough of these now?

Generic Classes; MyClass - The power of Generics!

DotNetFiddle Example.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        Random rand = new Random();
        int num;
        num = Convert.ToInt32(Console.ReadLine());
        Func<int> valueGenerator = () => { return rand.Next(0,2); };
        var dungeon = new Grid<int>(num, num, valueGenerator);

        foreach(var row in dungeon.Rows)
        {
            // First() - https://msdn.microsoft.com/en-us/library/bb291976(v=vs.110).aspx
            if (row.First().Row == 0)
            {
                Console.WriteLine("#-#-#-#-#");
            }
            // ToArray() - https://msdn.microsoft.com/en-us/library/bb298736(v=vs.110).aspx
            var rowValues = row.Select(r => r.Value.ToString()).ToArray();

            // string.Join() - https://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx
            var rowDisplay = string.Join("|", rowValues);

            // $ ie Interpolated Strings - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interpolated-strings
            Console.WriteLine($"|{rowDisplay}|");
            Console.WriteLine("#-#-#-#-#");
        }
    }

    public class Grid<T>
    {
        private int _numberOfRows;
        private int _numberOfColumns;

        // List<> - https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
        private List<Cell<T>> _cells;

        public Grid(int numberOfRows, int numberOfColumns)
        {
            if (numberOfRows == 0)
                throw new ArgumentOutOfRangeException("numberOfRows must be greater than zero.");
            if (numberOfColumns == 0)
                throw new ArgumentOutOfRangeException("numberOfColumns must be greater than zero.");

            _numberOfRows = numberOfRows;
            _numberOfColumns = numberOfColumns;

            // Enumerable.Range - https://msdn.microsoft.com/en-us/library/system.linq.enumerable.range(v=vs.110).aspx
            _cells = Enumerable.Range(0, _numberOfRows)
                // Select - https://msdn.microsoft.com/en-us/library/bb548891(v=vs.110).aspx
                .Select(r => Enumerable.Range(0, _numberOfColumns)
                        .Select(c => new Cell<T>
                                {
                                    Row = r,
                                    Col = c
                                })
                        // ToList() - https://msdn.microsoft.com/en-us/library/bb342261(v=vs.110).aspx
                        .ToList())
                // - https://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany(v=vs.110).aspx
                .SelectMany(c => c)
                .ToList();
        }

        public Grid(int numberOfRows, int numberOfColumns, Func<T> valueGenerator)
        {
            if (numberOfRows == 0)
                throw new ArgumentOutOfRangeException("numberOfRows must be greater than zero.");
            if (numberOfColumns == 0)
                throw new ArgumentOutOfRangeException("numberOfColumns must be greater than zero.");

            _numberOfRows = numberOfRows;
            _numberOfColumns = numberOfColumns;

            _cells = Enumerable.Range(0, _numberOfRows)
                .Select(r => Enumerable.Range(0, _numberOfColumns)
                        .Select(c => new Cell<T>
                                {
                                    Row = r,
                                    Col = c,
                                    Value = valueGenerator()
                                })
                        .ToList())
                .SelectMany(c => c)
                .ToList();
        }

        public IEnumerable<ICell<T>> Cells
        {
            get
            {
                return _cells;
            }
        }

        public IEnumerable<IEnumerable<ICell<T>>> Rows
        {
            get
            {
                return _cells.GroupBy(c => c.Row)
                    .Select(gs => gs.OrderBy(g => g.Col).ToList())
                    .ToList();
            }
        }

        public IEnumerable<IEnumerable<ICell<T>>> Columns
        {
            get
            {
                return _cells.GroupBy(c => c.Col)
                    .Select(gs => gs.OrderBy(g => g.Row).ToList())
                    .ToList();
            }
        }

        // We expose the Interface because we don't want anyone outside grid modifying
        // Row or Col
        public interface ICell<T>
        {
            int Row { get; }
            int Col { get; }
            T Value { get; set; }
        }

        private class Cell<T> : ICell<T>
        {
            public T Value { get; set; }
            public int Row { get; set; }
            public int Col { get; set; }
        }

    }

}

Output (well the 0s and 1s are random so...)

4

#-#-#-#-#
|0|0|0|1|
#-#-#-#-#
|1|0|0|1|
#-#-#-#-#
|0|0|1|0|
#-#-#-#-#
|0|1|1|0|
#-#-#-#-#

After all of this you might be asking yourself, why use a generic class Grid?  Well I doubt that the only thing you want to store in a Cell is an int.  Maybe you want to store a full object that represents all sorts of things...

int Replaced with DungeonCell<>


问:
redefinition error C2086 when trying to declare and define a variable in a namespace
I get the error C2086 from Visual Studio when trying to declare a variable in a name space, define it in one code file and access it in another code file.

When building with gcc (from codeblocks), the error is
(... == path on my harddisk):

...file_one.cpp|2|error: redefinition of 'RecvVarProxyFn Skins::fnSequenceProxyFn'

...file_one.h|4|note: 'RecvVarProxyFn Skins::fnSequenceProxyFn' previously declared here

Even when deactivating (using //) the access line in main(), the error is the same.

file_one.h:

```<code>typedef int RecvVarProxyFn;

namespace Skins {
    RecvVarProxyFn fnSequenceProxyFn; // "previously declared here"
}
</code>```

file_one.cpp

```<code>#include "file_one.h"
RecvVarProxyFn Skins::fnSequenceProxyFn = 0; // redefinition error 2086
</code>```

main.cpp

```<code>#include "file_one.h"
int main()
{   Skins::fnSequenceProxyFn = 1; // making this a comment does not help
    return 0;
}
</code>```

Why do I get a redefinition error for my attempt to define the variable in a separate code file?

NOTE:

I am using visual studio 2015 Target Platform set to version 8.1

and Platform toolset set to v140.

答:
Use the keyword extern to change one of the definitions into a declaration.

Obviously the line in the header is the first choice.

```<code>namespace Skins {
    extern RecvVarProxyFn fnSequenceProxyFn;
}
</code>```

Body:
I get the error C2086 from Visual Studio when trying to declare a variable in a name space, define it in one code file and access it in another code file.

When building with gcc (from codeblocks), the error is
(... == path on my harddisk):

...file_one.cpp|2|error: redefinition of 'RecvVarProxyFn Skins::fnSequenceProxyFn'

...file_one.h|4|note: 'RecvVarProxyFn Skins::fnSequenceProxyFn' previously declared here

Even when deactivating (using //) the access line in main(), the error is the same.

file_one.h:

typedef int RecvVarProxyFn;

namespace Skins {
    RecvVarProxyFn fnSequenceProxyFn; // "previously declared here"
}

file_one.cpp

#include "file_one.h"
RecvVarProxyFn Skins::fnSequenceProxyFn = 0; // redefinition error 2086

main.cpp

#include "file_one.h"
int main()
{   Skins::fnSequenceProxyFn = 1; // making this a comment does not help
    return 0;
}

Why do I get a redefinition error for my attempt to define the variable in a separate code file?

NOTE:

I am using visual studio 2015 Target Platform set to version 8.1

and Platform toolset set to v140.

Body:
Use the keyword extern to change one of the definitions into a declaration.

Obviously the line in the header is the first choice.

namespace Skins {
    extern RecvVarProxyFn fnSequenceProxyFn;
}


问:
Multiple conditions using replace plyr or dplyr in R
Here is a dataset:

```<code>> mydat
species section obs doy ranking
   A      A1  b1 123     2.1
   A      A2  b2 135     2.2
   A      A3  b3 147     2.3
   B      A1  b2 124     2.2
   B      A2  b3 132     2.3
   B      A3  b2 145     2.2
   C      A1  b1 120     2.1
   C      A2  b3 133     2.3
   C      A3  b2 137     2.2
</code>```

I am trying to code; for each species where obs==b2, if doy of b2 > doy of b3, then ranking=="2.4". If doy of b2 < doy of b3, then ranking=="2.2" (remains the same), so I get this result:

```<code>> mydat2
species section obs doy ranking
   A      A1  b1 123     2.1
   A      A2  b2 135     2.2
   A      A3  b3 147     2.3
   B      A1  b2 124     2.2
   B      A2  b3 132     2.3
   B      A3  b2 145     2.4
   C      A1  b1 120     2.1
   C      A2  b3 133     2.3
   C      A3  b2 137     2.4
</code>```

I used the package plyr to avoid loops because I find loops difficult to understand. I know a lot of people use dplyr instead of plyr nowadays, so I'd by glad for an answer using either plyr or dplyr.
Here is my clumsy try:

```<code>require (plyr)
mydat2 <- ddply(.data=mydat,
            .variables=c("species"),
            function(x){
              return(data.frame(replace(x$ranking, x$doy[x$obs=='b2']>x$doy[x$obs=="b3"],2.4)))})
</code>```

This works, but there is only species and ranking left in the dataset. How can I  code this properly to keep the whole dataset with changes in ranking?
Thank you for your help.

答:
ASSUMING each species only ever has one doy value for b3, you could get those values as a single table, then join it to the other table to make your comparisons simple, all using dplyr:

```<code>library(dplyr)

# get a single doy value for each species
b3values  <- mydat %>%
  filter(obs == 'b3') %>%
  group_by(species) %>%
  summarize(
    # using min(doy) but if there's only one value, you could use any grouping function like sum, max, etc
    b3doy = min(doy)
  )

# join b3values to your original data
mydat2  <- mydat %>%
  left_join(b3values, by = 'species') %>%
  mutate(
    # use case_when() to lay out your conditions and the values you want
    ranking = case_when(
        obs == 'b2' & (doy > b3doy) ~ 2.4
      , obs == 'b2' & (doy < b3doy) ~ 2.2
        # default value is to keep the ranking as-is
      , T ~ ranking
    )
  ) %>%
 # optionally, drop the extra b3doy column
 select(-b3doy)
</code>```

Body:
Here is a dataset:

> mydat
species section obs doy ranking
   A      A1  b1 123     2.1
   A      A2  b2 135     2.2
   A      A3  b3 147     2.3
   B      A1  b2 124     2.2
   B      A2  b3 132     2.3
   B      A3  b2 145     2.2
   C      A1  b1 120     2.1
   C      A2  b3 133     2.3
   C      A3  b2 137     2.2

I am trying to code; for each species where obs==b2, if doy of b2 > doy of b3, then ranking=="2.4". If doy of b2 < doy of b3, then ranking=="2.2" (remains the same), so I get this result:

> mydat2
species section obs doy ranking
   A      A1  b1 123     2.1
   A      A2  b2 135     2.2
   A      A3  b3 147     2.3
   B      A1  b2 124     2.2
   B      A2  b3 132     2.3
   B      A3  b2 145     2.4
   C      A1  b1 120     2.1
   C      A2  b3 133     2.3
   C      A3  b2 137     2.4

I used the package plyr to avoid loops because I find loops difficult to understand. I know a lot of people use dplyr instead of plyr nowadays, so I'd by glad for an answer using either plyr or dplyr.
Here is my clumsy try:

require (plyr)
mydat2 <- ddply(.data=mydat,
            .variables=c("species"),
            function(x){
              return(data.frame(replace(x$ranking, x$doy[x$obs=='b2']>x$doy[x$obs=="b3"],2.4)))})

This works, but there is only species and ranking left in the dataset. How can I  code this properly to keep the whole dataset with changes in ranking?
Thank you for your help.

Body:
ASSUMING each species only ever has one doy value for b3, you could get those values as a single table, then join it to the other table to make your comparisons simple, all using dplyr:

library(dplyr)

# get a single doy value for each species
b3values  <- mydat %>%
  filter(obs == 'b3') %>%
  group_by(species) %>%
  summarize(
    # using min(doy) but if there's only one value, you could use any grouping function like sum, max, etc
    b3doy = min(doy)
  )

# join b3values to your original data
mydat2  <- mydat %>%
  left_join(b3values, by = 'species') %>%
  mutate(
    # use case_when() to lay out your conditions and the values you want
    ranking = case_when(
        obs == 'b2' & (doy > b3doy) ~ 2.4
      , obs == 'b2' & (doy < b3doy) ~ 2.2
        # default value is to keep the ranking as-is
      , T ~ ranking
    )
  ) %>%
 # optionally, drop the extra b3doy column
 select(-b3doy)


问:
How to selenium test web sites depending on each other? (OAuth2 IdS, protected sites)
I have an IdS (Thinktecture Identity Server3) and various web sites trusting the IdS.

I have selenium tests for IdS and for each of the sites.

I use TeamCity and Octopus Deploy.

Changes in IdS should trigger test of dependent web sites. Changes in individual sites should trigger only test of the site (as it is).

What is the best way of ensuring this? I should think this is a common problem? ;)

BR, Anders

答: One way to do so, is to use App settings configuration options of the .Net itself. You can use config transformations to create different configuration per site and change. You will have to however map each, though. This will allow you to keep everything in the project. Example of such script creating transformed config files using the command line transform execution tool. Or if you prefer to use TeamCity with XML pokes. I've used the later with great success on Selenium and multi site platform test framework. Before each test build that was chained, we modified the XMLs, so the execution was dedicated to the related Git branch or repo that TeamCity was set to monitor.</p>


问:
JavaScript toggle divs
I want to toggle between 3 divs. Unfortunately it only works for 2 divs.

My code (for two divs):

```<code>$(function() {
  $('#playerbargreen').hide();
  $('#playerbaroff,#playerbargreen').click(function() {
    $('#playerbargreen,#playerbaroff').toggle();
  });
});
</code>```

The end result must be:

show first div --> click --> hide first div and show second div --> Click --> hide second div and show third div

Has someone any idea? Thanks in advance!

答:
Start with Div 2 & Div 3 hidden.

Create an on click event for Div 1 which hides Div 1 and shows Div 2.

Repeat for Div 2 to Div 3.

Something simple like the following should suffice:

```<code>$('#Div1').click(function() {
    $('#Div1').hide();
    $('#Div2').show();
});

$('#Div2').click(function() {
    $('#Div2').hide();
    $('#Div3').show();
});
</code>```

Title: JavaScript toggle divs

Body:
I want to toggle between 3 divs. Unfortunately it only works for 2 divs.

My code (for two divs):

$(function() {
  $('#playerbargreen').hide();
  $('#playerbaroff,#playerbargreen').click(function() {
    $('#playerbargreen,#playerbaroff').toggle();
  });
});

The end result must be:

show first div --> click --> hide first div and show second div --> Click --> hide second div and show third div

Has someone any idea? Thanks in advance!

Body:
Start with Div 2 & Div 3 hidden.

Create an on click event for Div 1 which hides Div 1 and shows Div 2.

Repeat for Div 2 to Div 3.

Something simple like the following should suffice:

$('#Div1').click(function() {
    $('#Div1').hide();
    $('#Div2').show();
});

$('#Div2').click(function() {
    $('#Div2').hide();
    $('#Div3').show();
});


问:
Error when rendering a partial view in ASP.NET MVC 5
I am trying to return a page within another when an id is passed on to a controller.
But I get this error:

```<code> Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
</code>```

Views\Error_Summaries\Details.cshtml

```<code>  @{Html.RenderAction("FindAllDetails", new { bolnumber = Model.BOL });}
</code>```

Error_SummariesController.cs

```<code>public ActionResult FindRelatedBols(string bolnumber)
{
    if (bolnumber == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Error_Summaries error_Summaries = db.Error_Summaries.SingleOrDefault(r => r.BOL == bolnumber);
    if (error_Summaries == null)
    {
        return HttpNotFound();
    }
    return View("Views/Error_Details/Details");
}
</code>```

答:
When checking the inner exception it showed that it was looking at the wrong action name. I had specified FindAllDetails instead FindRelatedBols. Also, the return path was wrong. And finally, I wasn't using the right Method name.</p>

```<code>public ActionResult FindRelatedBols(string bolnumber)
{
    if (bolnumber == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    //var test =
    //var qrytest = db.Error_Details.Where(r => r.BOL == bolnumber);
    //var details = qrytest.ToList();
    var details = db.Error_Details.Where(r => r.BOL == bolnumber).ToList();
    if (details == null)
    {
        return HttpNotFound();
    }
    return PartialView("~/Views/Error_Details/Index.cshtml", details);
}
</code>```

Body:
I am trying to return a page within another when an id is passed on to a controller.
But I get this error:

 Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.

Views\Error_Summaries\Details.cshtml

  @{Html.RenderAction("FindAllDetails", new { bolnumber = Model.BOL });}

Error_SummariesController.cs

public ActionResult FindRelatedBols(string bolnumber)
{
    if (bolnumber == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Error_Summaries error_Summaries = db.Error_Summaries.SingleOrDefault(r => r.BOL == bolnumber);
    if (error_Summaries == null)
    {
        return HttpNotFound();
    }
    return View("Views/Error_Details/Details");
}

Body:
When checking the inner exception it showed that it was looking at the wrong action name. I had specified FindAllDetails instead FindRelatedBols. Also, the return path was wrong. And finally, I wasn't using the right Method name.

public ActionResult FindRelatedBols(string bolnumber)
{
    if (bolnumber == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    //var test =
    //var qrytest = db.Error_Details.Where(r => r.BOL == bolnumber);
    //var details = qrytest.ToList();
    var details = db.Error_Details.Where(r => r.BOL == bolnumber).ToList();
    if (details == null)
    {
        return HttpNotFound();
    }
    return PartialView("~/Views/Error_Details/Index.cshtml", details);
}


问:
Escape comma in "$@" expansion
"$@" seems to make , disappear. e.g.

```<code>param="123 1,2"
set echo $param
"$@"
</code>```

This will echo "123 1 2" instead of "123 1,2", but in some cases , is needed as a value to a command.

And this seems to be related to bash version, with bash 4.1.2, the result is correct, but with 4.2.46, the comma is missing.

Edit:

In short, maybe it's nice to blame:

I did unset IFS and in terminal the test case I gave worked correctly, but not with my script.

I'm actually working on an init script, I checked the action() function in /etc/init.d/functions, and added some debugging code:

```<code>echo "$@" # added by me
unset IFS # added by me
"$@" && success $"$STRING" || failure $"$STRING"
</code>```

the command echoed is correct(nice -n -10 ovs-vswitchd ... --socket-mem 1024,1024), but in the ps result the actual command executed by nice becomes ovs-vswitchd ... --socket-mem 1024 1024.

I started to think maybe it's nice to blame.

答:
Please set the IFS directly in your script just before splitting param (before command set). For example do something like this:

```<code>oldIFS=$IFS
param="123 1,2"
IFS=" "  # put tabs and or newline if also wanted.
set echo $param
IFS=$oldIFS
"$@"
</code>```

This will work no matter what was your IFS before.

Title: Escape comma in "$@" expansion

Body:
"$@" seems to make , disappear. e.g.

param="123 1,2"
set echo $param
"$@"

This will echo "123 1 2" instead of "123 1,2", but in some cases , is needed as a value to a command.

And this seems to be related to bash version, with bash 4.1.2, the result is correct, but with 4.2.46, the comma is missing.

Edit:

In short, maybe it's nice to blame:

I did unset IFS and in terminal the test case I gave worked correctly, but not with my script.

I'm actually working on an init script, I checked the action() function in /etc/init.d/functions, and added some debugging code:

echo "$@" # added by me
unset IFS # added by me
"$@" && success $"$STRING" || failure $"$STRING"

the command echoed is correct(nice -n -10 ovs-vswitchd ... --socket-mem 1024,1024), but in the ps result the actual command executed by nice becomes ovs-vswitchd ... --socket-mem 1024 1024.

I started to think maybe it's nice to blame.

Body:
Please set the IFS directly in your script just before splitting param (before command set). For example do something like this:

oldIFS=$IFS
param="123 1,2"
IFS=" "  # put tabs and or newline if also wanted.
set echo $param
IFS=$oldIFS
"$@"

This will work no matter what was your IFS before.


问:
Custom Control Overridden Text Property Default Value
I have created a user control that has a textbox inside of it. I have overridden the Text property of the base control like the following:

```<code>    [Browsable(true)]
    [DefaultValue("")]
    [Description("Test1"), Category("Test")]
    public new string Text
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text= value;
        }
    }
</code>```

Now, I am having this issue where any instances i create of the control in a form, the Text always have a value of the controlname + number (of instance). I want to know why is this happening, and how to remove this default value? Thanks.

答:
The attribute DefaultValue does not set the default value.  The attribute is for describing what the default value is.  You have to set the default value yourself, and then use the attribute to describe it.

So in your example, textbox1.Text must be populated with the control id.  On your UserControl, in OnInit or wherever appropriate, you should call

```<code>this.Text = "";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have created a user control that has a textbox inside of it. I have overridden the Text property of the base control like the following:

    [Browsable(true)]
    [DefaultValue("")]
    [Description("Test1"), Category("Test")]
    public new string Text
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text= value;
        }
    }

Now, I am having this issue where any instances i create of the control in a form, the Text always have a value of the controlname + number (of instance). I want to know why is this happening, and how to remove this default value? Thanks.

Body:
The attribute DefaultValue does not set the default value.  The attribute is for describing what the default value is.  You have to set the default value yourself, and then use the attribute to describe it.

So in your example, textbox1.Text must be populated with the control id.  On your UserControl, in OnInit or wherever appropriate, you should call

this.Text = "";


问:
Env variables not persisting in parent shell
I have the following bash script that attempts to automate the assuming of an AWS role (I've obviously removed the various private settings):

```<code>#! /bin/bash
#
# Dependencies:
#   brew install jq
#
# Execute:
#   source aws-cli-assumerole.sh

unset AWS_SESSION_TOKEN
export AWS_ACCESS_KEY_ID=<user_access_key>
export AWS_SECRET_ACCESS_KEY=<user_secret_key>

temp_role=$(aws sts assume-role \
                    --role-arn "arn:aws:iam::<aws_account_number>:role/<role_name>" \
                    --role-session-name "<some_session_name>")

export AWS_ACCESS_KEY_ID=$(echo $temp_role | jq .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $temp_role | jq .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $temp_role | jq .Credentials.SessionToken)

env | grep -i AWS_
</code>```

I have to execute this script using source because otherwise if I use standard bash or sh the exported environment variables are not available within the parent shell executing this script.

The problem is, even when using source it doesn't work; and by that I mean: the environment variables AND their correct/updated values are showing in the parent shell (if I execute env | grep AWS_ I can see the correct values).

If I then try to use the AWS CLI tools (e.g. aws s3 ls - to list all s3 buckets within the specific account I've assumed the role for) it'll report back that the access key is invalid.

BUT, if I manually copy and paste the environment variable values and re-export them in the parent shell (effectively overwriting them with the exact same values that are already set), then the AWS CLI command will work - but I do not know why. What's different?

答:
jq .Blah will return the output quoted.

So for example
export AWS_ACCESS_KEY_ID=$(echo $temp_role | jq .Credentials.AccessKeyId)
Will result "KEY" instead what you need is just KEY which is why your xargs works in your comment.

If you use the -r flag for raw with jq you will get the result you want
export AWS_ACCESS_KEY_ID=$(echo $temp_role | jq -r .Credentials.AccessKeyId)

Body:
I have the following bash script that attempts to automate the assuming of an AWS role (I've obviously removed the various private settings):

#! /bin/bash
#
# Dependencies:
#   brew install jq
#
# Execute:
#   source aws-cli-assumerole.sh

unset AWS_SESSION_TOKEN
export AWS_ACCESS_KEY_ID=<user_access_key>
export AWS_SECRET_ACCESS_KEY=<user_secret_key>

temp_role=$(aws sts assume-role \
                    --role-arn "arn:aws:iam::<aws_account_number>:role/<role_name>" \
                    --role-session-name "<some_session_name>")

export AWS_ACCESS_KEY_ID=$(echo $temp_role | jq .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $temp_role | jq .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $temp_role | jq .Credentials.SessionToken)

env | grep -i AWS_

I have to execute this script using source because otherwise if I use standard bash or sh the exported environment variables are not available within the parent shell executing this script.

The problem is, even when using source it doesn't work; and by that I mean: the environment variables AND their correct/updated values are showing in the parent shell (if I execute env | grep AWS_ I can see the correct values).

If I then try to use the AWS CLI tools (e.g. aws s3 ls - to list all s3 buckets within the specific account I've assumed the role for) it'll report back that the access key is invalid.

BUT, if I manually copy and paste the environment variable values and re-export them in the parent shell (effectively overwriting them with the exact same values that are already set), then the AWS CLI command will work - but I do not know why. What's different?


问:
Laravel route/{variable?} not working when not entered
So in my web.php I have route like this:

```<code>Route::get('city/{city_id?}', function($city_id) {
    return view('search');
});
</code>```

But when I try to enter just 'localhost/public/city/' it displays me an error:

```<code>"Type error: Too few arguments to function Illuminate\Routing\Router::{closure}(), 0 passed in /opt/lampp/htdocs/laravelcourse/vendor/laravel/framework/src/Illuminate/Routing/Route.php on line 198 and exactly 1 expected "
</code>```

When I enter the variable it works just fine. Shouldn't ? symbol mean that I may enter it or may leave it blank and it still should work?

答:
This should work, you need to provide a default value in case if no parameter is passed.</p>

```<code>Route::get('city/{city_id?}', function($city_id = null) {
    return view('search');
});
</code>```

Body:
So in my web.php I have route like this:

Route::get('city/{city_id?}', function($city_id) {
    return view('search');
});

But when I try to enter just 'localhost/public/city/' it displays me an error:

"Type error: Too few arguments to function Illuminate\Routing\Router::{closure}(), 0 passed in /opt/lampp/htdocs/laravelcourse/vendor/laravel/framework/src/Illuminate/Routing/Route.php on line 198 and exactly 1 expected "

When I enter the variable it works just fine. Shouldn't ? symbol mean that I may enter it or may leave it blank and it still should work?

Body:
This should work, you need to provide a default value in case if no parameter is passed.

Route::get('city/{city_id?}', function($city_id = null) {
    return view('search');
});


问:
iOS - UICollectionView - When inserting multiple items at once, how can you fade them in one after the other instead of simultaneously?
when you have a collection view and you're changing the items by inserting a few, the default layout fades them in simultaneously. Is there a possibility to fade them in one after the other?

I was thinking about subclassing UICollectionViewLayout, but I'm not sure if that's going to work like that.

Do I really have to add logic so that multiple inserts at once don't occur? (so that I insert an item, wait a second, insert the second item, ... Doing it manually) There has to be a better way. I hope

Thanks for any help

答:
If you want to fade them in one at a time, you are going to have to add one to your model and reload that one item and then delay (e.g. asyncAfter) and do the next one. Note, you cannot add all of them to your model at once and simply defer the reloading of the individual items of the collection view. You have to defer both the update of the model and the reloading of the appropriate item of the collection view. E.g.:

```<code>private func append(_ objectsToAdd: [Foo]) {
    for i in 0 ..< objectsToAdd.count {
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * 0.25) {
            self.objects.append(objectsToAdd[i])
            self.collectionView?.insertItems(at: [IndexPath(item: self.objects.count - 1, section: 0)])
        }
    }
}
</code>```

That yields:

No subclassing of UICollectionViewLayout is needed.

Body:
If you want to fade them in one at a time, you are going to have to add one to your model and reload that one item and then delay (e.g. asyncAfter) and do the next one. Note, you cannot add all of them to your model at once and simply defer the reloading of the individual items of the collection view. You have to defer both the update of the model and the reloading of the appropriate item of the collection view. E.g.:

private func append(_ objectsToAdd: [Foo]) {
    for i in 0 ..< objectsToAdd.count {
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * 0.25) {
            self.objects.append(objectsToAdd[i])
            self.collectionView?.insertItems(at: [IndexPath(item: self.objects.count - 1, section: 0)])
        }
    }
}

That yields:

No subclassing of UICollectionViewLayout is needed.


问:
How to create a vector with components bigger than a number in numpy?
For example, I have a vector like this:

```<code>v = np.array([2, 4, 1, 7, 9, 3, 5])
</code>```

I want to compare each component to a number to obtain a new vector which components are bigger of equal to the number (in case if the original component is less). For the above example and limit=3 the result should be:

```<code>np.array([3, 4, 3, 7, 9, 3, 5])
</code>```

How can I do it with numpy?

答:
You can also use numpy.clip:

```<code>>>> np.clip(v, 3, None)
array([3, 4, 3, 7, 9, 3, 5])
</code>```

The second argument is a maximum, but I've given it only a minimum.

This can also be provided with an out argument, in this case, if you supply itself as the target, it will work in-place:

```<code>>>> x = np.clip(v, 3, None, v)
>>> id(x), id(v)
(4357557104, 4357557104)
>>> v
array([3, 4, 3, 7, 9, 3, 5])
>>>
</code>```

The docs:

```<code>out : ndarray, optional
    The results will be placed in this array. It may be the input
    array for in-place clipping.  `out` must be of the right shape
    to hold the output.  Its type is preserved.
</code>```

This could potentially be useful if you are memory constrained (I believe no intermediate boolean array gets created).

Body:
For example, I have a vector like this:

v = np.array([2, 4, 1, 7, 9, 3, 5])

I want to compare each component to a number to obtain a new vector which components are bigger of equal to the number (in case if the original component is less). For the above example and limit=3 the result should be:

np.array([3, 4, 3, 7, 9, 3, 5])

How can I do it with numpy?

Body:
You can also use numpy.clip:

>>> np.clip(v, 3, None)
array([3, 4, 3, 7, 9, 3, 5])

The second argument is a maximum, but I've given it only a minimum.

This can also be provided with an out argument, in this case, if you supply itself as the target, it will work in-place:

>>> x = np.clip(v, 3, None, v)
>>> id(x), id(v)
(4357557104, 4357557104)
>>> v
array([3, 4, 3, 7, 9, 3, 5])
>>>

The docs:

out : ndarray, optional
    The results will be placed in this array. It may be the input
    array for in-place clipping.  `out` must be of the right shape
    to hold the output.  Its type is preserved.

This could potentially be useful if you are memory constrained (I believe no intermediate boolean array gets created).


问:
d3-celestial library export to SVG
I am using the D3-Celestial Library (https://github.com/ofrohn/d3-celestial) and trying to convert the canvas image, to an SVG (I need to use this as a Vector image so it can be converted to GCode for a laser cutter).
I have tried using the Fabric JS library and Canvas-GetSVG with no success.

Does anyone have a good place to start or easy way to do this?

```<code><div style="overflow:hidden;"><div id="celestial-map"></div></div>
<div id="celestial-form"></div>

<script type="text/javascript">
var canvas;
Celestial.display({
  form: true,
  location: true,
  datapath: "../data/",
  stars: {proper: true}
});
document.getElementById("celestial-map").firstChild.setAttribute("id", "findthisstring");

function myFunction(){
   var canvas = new fabric.Canvas('findthisstring', { isDrawingMode: true });
   canvas.isDrawingMode = false;
   canvas.toSVG();
 }
 function do_save() {
    var canvas = new fabric.Canvas('findthisstring', { isDrawingMode: true });
    canvas.isDrawingMode = false;
    var filedata=canvas.toSVG(); // the SVG file is now in filedata

    var locfile = new Blob([filedata], {type: "image/svg+xml;charset=utf-8"});
    var locfilesrc = URL.createObjectURL(locfile);//mylocfile);

    var dwn = document.getElementById('dwn');
    dwn.innerHTML = "<a href=" + locfilesrc + "
    download='mysvg.svg'>Download</a>";
  }
  </script>

 <button onclick="myFunction()">Click me</button>
 <input type="button" id="saveBtn" value="save" onclick="do_save()"></input>
 <div id='dwn'></div>
 <div id="imgOut"></div>
</code>```

I tried to use a few different libraries to export the data from the Canvas object to a SVG, but only was able to get Empty SVGs.

答:
I don't have specifics at hand at the moment, but I was trying to do the same thing (from the frustratingly incomplete Make magazine article) and was able to coerce an SVG by:

Hosting a local instance of d3-celestial

Modifying HTML pages to use the older 0.4 version which actually used SVGs (in dist folder)

Installing "SVG crowbar" bookmarklet to export the output to a file.

Title: d3-celestial library export to SVG

Body:
I am using the D3-Celestial Library (https://github.com/ofrohn/d3-celestial) and trying to convert the canvas image, to an SVG (I need to use this as a Vector image so it can be converted to GCode for a laser cutter).
I have tried using the Fabric JS library and Canvas-GetSVG with no success.

Does anyone have a good place to start or easy way to do this?

 <button onclick="myFunction()">Click me</button>
 <input type="button" id="saveBtn" value="save" onclick="do_save()"></input>

I tried to use a few different libraries to export the data from the Canvas object to a SVG, but only was able to get Empty SVGs.


问:
Ionic/Cordova: How to install plugin into existing project?
How do I install an additional Cordova plugin into an existing Ionic/Cordova project? I need the Cordova Camera Plugin. If I try:

```<code>cordova plugin add https://github.com/apache/cordova-plugin-camera.git
</code>```

I get error:

```<code>Error: Command failed: fatal: could not create work tree dir .... No such file or directory.
</code>```

答:
The best way to install cordova plugin in ionic by tapping these commands line :

```<code>$ionic cordova plugin add cordova-plugin-camera
$npm install --save @ionic-native/camera
</code>```

Add the plugin in your module app here

And follow the instruction on the official documentation https://ionicframework.com/docs/native/camera/

Good luck :)

Body:
How do I install an additional Cordova plugin into an existing Ionic/Cordova project? I need the Cordova Camera Plugin. If I try:

cordova plugin add https://github.com/apache/cordova-plugin-camera.git

I get error:

Error: Command failed: fatal: could not create work tree dir .... No such file or directory.

Body:
The best way to install cordova plugin in ionic by tapping these commands line :

$ionic cordova plugin add cordova-plugin-camera
$npm install --save @ionic-native/camera

Add the plugin in your module app here

And follow the instruction on the official documentation https://ionicframework.com/docs/native/camera/

Good luck :)


问:
ERD... Is this a many-to-many relationship?
I have 2 tables below. USERS can have 1 or more PROJECTS. The PROJECTS table references the USERS table in a number of fields where the referenced user_id's can be either all the same or different. Is this a many to many relationship?

```<code>table: USERS
------------
user_id pk,
user_firstname,
user_lastname

table: PROJECTS
---------------
project_id pk,
created_by fk references USERS,
project_manager fk references USERS,
dev_lead fk references USERS
</code>```

答:
No.  You have three foreign keys in PROJECTS that all happen to refer to the same table USERS, but none of them is a many-to-many relationship.

Each project can have ONE created_by, ONE project manager, and ONE dev lead.

A many-to-many relationship would be a situation where each project could have many dev leads and each dev lead could manage many projects.  In such a situation, you'd have a third table (e.g., PROJECT_DEV_LEAD_USERS) to hold the relationship.

Body:
I have 2 tables below. USERS can have 1 or more PROJECTS. The PROJECTS table references the USERS table in a number of fields where the referenced user_id's can be either all the same or different. Is this a many to many relationship?

table: USERS
------------
user_id pk,
user_firstname,
user_lastname

table: PROJECTS
---------------
project_id pk,
created_by fk references USERS,
project_manager fk references USERS,
dev_lead fk references USERS


问:
MATLAB index within groups
Given a vector A of group numbers (such as the one returned by findgroups), how to return a vector B of the same length containing indices of elements within groups of A?

For example, if A = [1 1 1 2 2 2 1 1 2 2] then B = [1 2 3 1 2 3 4 5 4 5].

Add 1

My own solution to this is

```<code>s = splitapply(@(x) {x, [1:numel(x)]'}, [1:numel(A)]', A(:))
B(vertcat(s{:,1})) = vertcat(s{:,2})
</code>```

but it seems somewhat convoluted.

答:
Here's a solution that may not look as compact, but it's quite fast since it uses cumsum and indexing:

```<code>mA = max(A);
nA = numel(A);
ind = false(mA, nA);
ind(mA.*(0:(nA-1))+A) = true;
B = cumsum(ind, 2);
B = B(ind).';
</code>```

And here are some timing results for the solutions thus far:

```<code>A = [1 1 1 2 2 2 1 1 2 2];

rahnema1: 6.51343e-05
    Luis: 3.00891e-05
     OmG: 2.36826e-05
 gnovice: 4.93539e-06  % <---

A = randi(20, 1, 1000);

rahnema1: 0.000274138
    Luis: 0.000257126
     OmG: 0.000233348
 gnovice: 9.95673e-05  % <---

A = randi(20, 1, 10000);

rahnema1: 0.00162955
    Luis: 0.00163943
     OmG: 0.00126571
 gnovice: 0.00107134  % <---
</code>```

My solution is the fastest for the above test cases (moderate size, moderate number of unique values). For larger cases, other solutions gain the edge. The solution from rahnema1 seems to do better as the number of unique values in A increases, whereas the basic for loop from OmG does better when the number of elements in A increases (with relatively fewer unique values):

```<code>>> A = randi(200, 1, 100000);

rahnema1: 0.0108024  % <---
    Luis: 0.0931876
     OmG: 0.0427542
 gnovice: 0.0815516

>> A = randi(20, 1, 1000000);

rahnema1: 0.131256
    Luis: 0.171415
     OmG: 0.106548  % <---
 gnovice: 0.124446
</code>```

Title: MATLAB index within groups

Body:
Given a vector A of group numbers (such as the one returned by findgroups), how to return a vector B of the same length containing indices of elements within groups of A?

For example, if A = [1 1 1 2 2 2 1 1 2 2] then B = [1 2 3 1 2 3 4 5 4 5].

Add 1

My own solution to this is

s = splitapply(@(x) {x, [1:numel(x)]'}, [1:numel(A)]', A(:))
B(vertcat(s{:,1})) = vertcat(s{:,2})

but it seems somewhat convoluted.

Body:
Here's a solution that may not look as compact, but it's quite fast since it uses cumsum and indexing:

mA = max(A);
nA = numel(A);
ind = false(mA, nA);
ind(mA.*(0:(nA-1))+A) = true;
B = cumsum(ind, 2);
B = B(ind).';

And here are some timing results for the solutions thus far:

A = [1 1 1 2 2 2 1 1 2 2];

rahnema1: 6.51343e-05
    Luis: 3.00891e-05
     OmG: 2.36826e-05
 gnovice: 4.93539e-06  % <---

A = randi(20, 1, 1000);

rahnema1: 0.000274138
    Luis: 0.000257126
     OmG: 0.000233348
 gnovice: 9.95673e-05  % <---

A = randi(20, 1, 10000);

rahnema1: 0.00162955
    Luis: 0.00163943
     OmG: 0.00126571
 gnovice: 0.00107134  % <---

My solution is the fastest for the above test cases (moderate size, moderate number of unique values). For larger cases, other solutions gain the edge. The solution from rahnema1 seems to do better as the number of unique values in A increases, whereas the basic for loop from OmG does better when the number of elements in A increases (with relatively fewer unique values):

>> A = randi(200, 1, 100000);

rahnema1: 0.0108024  % <---
    Luis: 0.0931876
     OmG: 0.0427542
 gnovice: 0.0815516

>> A = randi(20, 1, 1000000);

rahnema1: 0.131256
    Luis: 0.171415
     OmG: 0.106548  % <---
 gnovice: 0.124446


答:
Should be like this:

```<code>Route::get('city/{city_id?}', function($city_id = null) {
    return view('search');
});
</code>```

Please read documentation here: Laravel optional routing

Title: Laravel route/{variable?} not working when not entered

Body:
Should be like this:

Route::get('city/{city_id?}', function($city_id = null) {
    return view('search');
});

Please read documentation here: Laravel optional routing


问:
Replace text within variable in Bash
I am saving a Curl response into a variable here:

```<code>results=$(curl -username:password "URL/api/search/dates?dateFields=created&from=${Three_Months_Ago}&today&repos=generic-sgca" | jq -r '.results[].uri')
echo "$results"
</code>```

which returns the following:

```<code>URL/api/storage/generic-sgca/Lastest_Deploy.tar
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-windows-installer.exe
</code>```

In each of these lines, I need to remove the "/api/storage" part of the URL. How can I accomplish this?

答:
```<code>echo "${results//\/api\/storage/}"
</code>```

would do what you're asking, but there is probably no good reason to capture the result in a variable just to print it. Maybe you're better off with

```<code>curl ... | jq ... | sed 's=/api/storage=='
</code>```

or figuring out how to do the subsititution as part of your jq script.

Title: Replace text within variable in Bash

Body:
I am saving a Curl response into a variable here:

results=$(curl -username:password "URL/api/search/dates?dateFields=created&from=${Three_Months_Ago}&today&repos=generic-sgca" | jq -r '.results[].uri')
echo "$results"

which returns the following:

URL/api/storage/generic-sgca/Lastest_Deploy.tar
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-windows-installer.exe

In each of these lines, I need to remove the "/api/storage" part of the URL. How can I accomplish this?

Body:
echo "${results//\/api\/storage/}"

would do what you're asking, but there is probably no good reason to capture the result in a variable just to print it. Maybe you're better off with

curl ... | jq ... | sed 's=/api/storage=='

or figuring out how to do the subsititution as part of your jq script.