问:
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 asking for a int from user in your Main class. Check for the below line in your public static void main(String[] args)

int write = scan.nextInt();

If you enter anything else then integer, it will throw exception.
You can add a try catch block to handle the unwanted inputs. It should look something like the below. This will handle the inputs which are not integer and will give the user option to select a proper input.

```<code>public static void main(String[] args) {
    Main kennel = new Main();
    while (true) {
        try {
            System.out.print(kennel.dogMenu() + "\n");
            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());
            }

        } catch (InputMismatchException e) {
            System.out.println(kennel.error());
            scan.nextLine();
        }
    }
}
</code>```

I am not sure, what you mean by this "Another requirement is that the test program must identify the word "Error". Please help me!!!". If you can provide more input, I can try to help.

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!!

Body:
You are getting  InputMismatchException because you are asking for a int from user in your Main class. Check for the below line in your public static void main(String[] args)

int write = scan.nextInt();

If you enter anything else then integer, it will throw exception.
You can add a try catch block to handle the unwanted inputs. It should look something like the below. This will handle the inputs which are not integer and will give the user option to select a proper input.

public static void main(String[] args) {
    Main kennel = new Main();
    while (true) {
        try {
            System.out.print(kennel.dogMenu() + "\n");
            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());
            }

        } catch (InputMismatchException e) {
            System.out.println(kennel.error());
            scan.nextLine();
        }
    }
}

I am not sure, what you mean by this "Another requirement is that the test program must identify the word "Error". Please help me!!!". If you can provide more input, I can try to help.


来源: stackexchange

问:
Add params to path rest.js
I'm using rest.js from npm install rest and cannot get my params to append to the path in the request.  Here is my client.js

```<code>'use strict';

var rest = require('rest');
var defaultRequest = require('rest/interceptor/defaultRequest');
var mime = require('rest/interceptor/mime');
var uriTemplateInterceptor = require('rest/interceptor/template');
var errorCode = require('rest/interceptor/errorCode');
var baseRegistry = require('rest/mime/registry');

var registry = baseRegistry.child();

registry.register('text/uri-list', require('./api/uriListConverter'));
registry.register('application/hal+json', require('rest/mime/type/application/hal'));

module.exports = rest
        .wrap(mime, { registry: registry })
        .wrap(uriTemplateInterceptor)
        .wrap(errorCode)
        .wrap(defaultRequest, { headers: { 'Accept': 'application/hal+json' }});
</code>```

I used the template interceptor suggested here https://github.com/cujojs/rest/blob/master/docs/interceptors.md#module-rest/interceptor/template.  Here is my code making the request:

```<code>client({method: 'GET', path: 'api/questions/page', params: {offset: 0, limit:10}})
        .then(response => console.log(response.request.path));
</code>```

The output of the console.log(response.request.path) is api/questions/page and it also doesn't show the request params in the network log.  How do I get the params to append to the path?

答:
I just created my own interceptor</p>

```<code>define(function(require) {
    'use strict';

    var interceptor = require('rest/interceptor');

    return interceptor({
        request: function (request /*, config, meta */) {
            /* If the URI is a URI Template per RFC 6570 (http://tools.ietf.org/html/rfc6570), trim out the template part */
            if (request.path.indexOf('{') === -1) {
                if(request.params != null){
                    request.path = request.path + '?'
                    Object.keys(request.params).forEach(function eachKey(key){
                        request.path = request.path + key + '=' + request.params[key] + '&';
                    });
                    request.path = request.path.slice(0, -1);
                }
                return request;
            } else {
                request.path = request.path.split('{')[0];
                return request;
            }
        }
    });

});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add params to path rest.js

Body:
I'm using rest.js from npm install rest and cannot get my params to append to the path in the request.  Here is my client.js

'use strict';

var rest = require('rest');
var defaultRequest = require('rest/interceptor/defaultRequest');
var mime = require('rest/interceptor/mime');
var uriTemplateInterceptor = require('rest/interceptor/template');
var errorCode = require('rest/interceptor/errorCode');
var baseRegistry = require('rest/mime/registry');

var registry = baseRegistry.child();

registry.register('text/uri-list', require('./api/uriListConverter'));
registry.register('application/hal+json', require('rest/mime/type/application/hal'));

module.exports = rest
        .wrap(mime, { registry: registry })
        .wrap(uriTemplateInterceptor)
        .wrap(errorCode)
        .wrap(defaultRequest, { headers: { 'Accept': 'application/hal+json' }});

I used the template interceptor suggested here https://github.com/cujojs/rest/blob/master/docs/interceptors.md#module-rest/interceptor/template.  Here is my code making the request:

client({method: 'GET', path: 'api/questions/page', params: {offset: 0, limit:10}})
        .then(response => console.log(response.request.path));

The output of the console.log(response.request.path) is api/questions/page and it also doesn't show the request params in the network log.  How do I get the params to append to the path?

Body:
I just created my own interceptor

define(function(require) {
    'use strict';

    var interceptor = require('rest/interceptor');

    return interceptor({
        request: function (request /*, config, meta */) {
            /* If the URI is a URI Template per RFC 6570 (http://tools.ietf.org/html/rfc6570), trim out the template part */
            if (request.path.indexOf('{') === -1) {
                if(request.params != null){
                    request.path = request.path + '?'
                    Object.keys(request.params).forEach(function eachKey(key){
                        request.path = request.path + key + '=' + request.params[key] + '&';
                    });
                    request.path = request.path.slice(0, -1);
                }
                return request;
            } else {
                request.path = request.path.split('{')[0];
                return request;
            }
        }
    });

});


问:
I implemented card views in XML on Android Studios. How can I have this act as buttons?
I'm new to Android and recently created a dashboard for my app. I followed a tutorial but it only covered the front end. I created a layout called content_main.xml with three Cardviews. Each of these Cardviews contains the code

```<code>android:clickable="true"
</code>```

Beginning the back end of things, I created a java receiver class called DashboardActivity (as seen below). I want to make my Cardviews clickable so that when one is clicked, I am taken to another screen within my app. The other screens in my app I am trying to get to are fragments. Each of these screens has its own java class in my "Fragments" folder. One of them, of which I try calling on in the code that follows is called SettingsViewFragment().

So far, I have tried the following. It does nothing.

```<code>public class DashboardActivity  extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        cd1 = (CardView) findViewById(R.id.dash_settings);
        cd2 = (CardView) findViewById(R.id.dash_profile);
        cd3 = (CardView) findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment1 = new SettingsViewFragment();
            }

        });
    }
}
</code>```

UPDATE: FULL CODE

```<code>public class DashboardActivity extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);

        cd1 = findViewById(R.id.dash_settings);
        cd2 = findViewById(R.id.dash_profile);
        cd3 = findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i("Testing 123 123 123");
            }

        });

    }
}
</code>```

And my XML: (it continues for 3 cards this way)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.newproject.DashboardActivity"
    tools:showIn="@layout/toolbar">

    <FrameLayout
        android:id="@+id/dashframe"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.CardView
            android:id="@+id/dash_settings"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:focusable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/bg_circle1"
                    android:src="@drawable/ic_settingspicture"
                    android:padding="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:text="View your settings"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightgray"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Follow along with guided tutorials"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>
</code>```

答:
Replace

```<code>Fragment fragment1 = new SettingsViewFragment();
</code>```

With this

```<code>Fragment fragment1 = new SettingsViewFragment();
FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.Main_Layout,fragment1);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();
</code>```

Body:
I'm new to Android and recently created a dashboard for my app. I followed a tutorial but it only covered the front end. I created a layout called content_main.xml with three Cardviews. Each of these Cardviews contains the code

android:clickable="true"

Beginning the back end of things, I created a java receiver class called DashboardActivity (as seen below). I want to make my Cardviews clickable so that when one is clicked, I am taken to another screen within my app. The other screens in my app I am trying to get to are fragments. Each of these screens has its own java class in my "Fragments" folder. One of them, of which I try calling on in the code that follows is called SettingsViewFragment().

So far, I have tried the following. It does nothing.

public class DashboardActivity  extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        cd1 = (CardView) findViewById(R.id.dash_settings);
        cd2 = (CardView) findViewById(R.id.dash_profile);
        cd3 = (CardView) findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment1 = new SettingsViewFragment();
            }

        });
    }
}

UPDATE: FULL CODE

public class DashboardActivity extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);

        cd1 = findViewById(R.id.dash_settings);
        cd2 = findViewById(R.id.dash_profile);
        cd3 = findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i("Testing 123 123 123");
            }

        });

    }
}

And my XML: (it continues for 3 cards this way)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.newproject.DashboardActivity"
    tools:showIn="@layout/toolbar">

    <FrameLayout
        android:id="@+id/dashframe"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.CardView
            android:id="@+id/dash_settings"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:focusable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/bg_circle1"
                    android:src="@drawable/ic_settingspicture"
                    android:padding="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:text="View your settings"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightgray"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Follow along with guided tutorials"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>

Body:
Replace

Fragment fragment1 = new SettingsViewFragment();

With this

Fragment fragment1 = new SettingsViewFragment();
FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.Main_Layout,fragment1);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();


问:
Is there a way to only accept a file with a certain name for an input button?
The accept object property filters files with a certain extension -- but is there a way to filter based on object name as well?

```<code><input type="file" id="HelloWorld" accept=".txt"></input>
</code>```

Let's say I wanted to filter for a file called "HelloWorld" with the extension of ".txt". How could this be done?

答:
No you only can provide mime types according this page: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-accept

accept

If the value of the type attribute is file, then this attribute will
  indicate the types of files that the server accepts, otherwise it will
  be ignored. The value must be a comma-separated list of unique content
  type specifiers: A file extension starting with the STOP character
  (U+002E). (e.g. .jpg, .png, .doc).

A valid MIME type with no extensions.

audio/* representing sound files.

video/* representing video

files. HTML5 image/* representing image files.

To explicit check the filename you need to do something with javascript or in your backend where you POST.

Body:
The accept object property filters files with a certain extension -- but is there a way to filter based on object name as well?

<input type="file" id="HelloWorld" accept=".txt"></input>

Let's say I wanted to filter for a file called "HelloWorld" with the extension of ".txt". How could this be done?


问:
What are the type parameters for FileBasedSink?
I'm migrating a custom sink extending FileBasedSink from version 2.0.0 to 2.2.0. The class has changed and added two extra type parameters: UserT and DestinationT:

```<code>@Experimental(value=FILESYSTEM)
public abstract class FileBasedSink<UserT,DestinationT,OutputT>
extends java.lang.Object
implements java.io.Serializable, HasDisplayData
</code>```

I've checked the doc of FileBasedSink but cannot find the purpose of it.

Of all type parameters only OutputT has a documentation:

```<code>* @param <OutputT> the type of values written to the sink.`
</code>```

答:
Note that this API is being redesigned and will be deprecated in the next version of Beam. However, meanwhile:

UserT is the type of PCollection elements to be written - the WriteFiles transform will be applicable to PCollection<UserT>.

OutputT is the low-level type of records that will be directly passed to your sink's Writer. It differs from UserT because some sinks have a "format function", e.g. Avro can convert any record to a GenericRecord. UserT is mapped to OutputT via DynamicDestinations.formatRecord.

DestinationT is a logical type for supporting writes to multiple destinations at the same time, e.g. writing events of different type to Avro files with different schemas in different directories. DestinationT functions as sort of a grouping key for records to be written, and records with the same DestinationT are written using the same configuration. See FileBasedSink.DynamicDestinations: getDestination extracts the destinations from a UserT record, and a bunch of other methods produce the configuration for a given destination, e.g. DynamicAvroDestinations.getSchema.

This API is not optimal - e.g. it introduces these high-level concepts (user type and destination) into code specific to file formats (e.g. writing to Avro files). That's why it is being redesigned. Stay tuned for the PR https://github.com/apache/beam/pull/3817 implementing the new API.

Body:
I'm migrating a custom sink extending FileBasedSink from version 2.0.0 to 2.2.0. The class has changed and added two extra type parameters: UserT and DestinationT:

@Experimental(value=FILESYSTEM)
public abstract class FileBasedSink<UserT,DestinationT,OutputT>
extends java.lang.Object
implements java.io.Serializable, HasDisplayData

I've checked the doc of FileBasedSink but cannot find the purpose of it.

Of all type parameters only OutputT has a documentation:

* @param <OutputT> the type of values written to the sink.`


问:
Sending a parameter (or get the key) with inAppSettingsKit when initialising custom controller
I'm trying to initialise a custom viewcontroller and send a parameter with it but can't figure it out.

To sketch an idea:

I want to have different settings per sport (walking, running, ...) and save those in core data on the custom viewcontroller.

To know to which sport the settings belong to I need to know what sport the user tapped to get to that screen. I was thinking about doing this by sending a parameter, using a custom init for each sport or by getting the key. All of which I can't figure out.

I've looked into this issue and tried to do it like this: (item 4)

But that doesn't work, according to the IASK docs I think I also need to specify a file, but what file?

The selector must have two arguments: an NSString argument for the file name in the Settings bundle and the IASKSpecifier.

I've tried setting a File field and tried different values but without success.

I'm seriously lost here, if it's possible to get the key of the item that initialised the controller ("running" for item 4 for example) that would also be good.

I've tried so many different things I'm losing my mind, I'm obviously doing something very wrong but I have no idea what it is.

答:
You don't need to specify an IASKSpecifier key in your Settings.plist. The way this works is you implement

SettingsPerSportViewController.m:

```<code>- (id) myinit:(NSString*)file specifier:(IASKSpecifier*)specifier {
    if ((self = [super init])) {
        // setup your VC
        if ([specifier.key isEqualToString:@"tennis"]) {
            // custom stuff for tennis
        }
    }
    return self;
}
</code>```

However, this means you build the settings view controllers for your sports on your own and don't use IASK for that.

If all sports share the same settings and you want to use IASK to generate the settings view controller, you could implement a custom settings storage and use the same Sport.plist for all sports. Your custom settings storage could then load from and save directly to Core Data. A sport property would then route the load and save operations to the right Core Data context or table.

At the root level you could have a simple static view controller that sets up and pushes an IASKAppSettingsViewController for each sport with the settingsStore property set to your custom storage subclass and the sport property set according to the selected sport.

Body:
You don't need to specify an IASKSpecifier key in your Settings.plist. The way this works is you implement

SettingsPerSportViewController.m:

- (id) myinit:(NSString*)file specifier:(IASKSpecifier*)specifier {
    if ((self = [super init])) {
        // setup your VC
        if ([specifier.key isEqualToString:@"tennis"]) {
            // custom stuff for tennis
        }
    }
    return self;
}

However, this means you build the settings view controllers for your sports on your own and don't use IASK for that.

If all sports share the same settings and you want to use IASK to generate the settings view controller, you could implement a custom settings storage and use the same Sport.plist for all sports. Your custom settings storage could then load from and save directly to Core Data. A sport property would then route the load and save operations to the right Core Data context or table.

At the root level you could have a simple static view controller that sets up and pushes an IASKAppSettingsViewController for each sport with the settingsStore property set to your custom storage subclass and the sport property set according to the selected sport.


问:
How To Add List-style-type: "disc" to
 tag
This seems like it ought to be ridiculously easy, but I'm having trouble figuring it out.

I want to replicate the
 function so the disc image appears to the left, but applied to a
 tag

I have this, but it does not show the disc image.

```<code>.list {
     margin-top: 15px;
     margin-bottom: 15px;
     list-style:disc outside none;
     display:inline;
     }

<p class="list"><em>And Much, Much More!</em></p>
</code>```

I want to avoid using any graphics to simulate the bullet if at all possible.

Thanks for the help

答:
Answer:
display: list-item;

Display must be set to list-item - not inline, and not list!

```<code>.list {
     list-style:disc outside none;
     display:list-item;
     }

<p class="list"><em>And Much, Much More!</em></p>
</code>```

ContentLicense: CC BY-SA 2.5

Title: How To Add List-style-type: "disc" to <p> tag

Body:
This seems like it ought to be ridiculously easy, but I'm having trouble figuring it out.

I want to replicate the
 function so the disc image appears to the left, but applied to a
 tag

I have this, but it does not show the disc image.

.list {
     margin-top: 15px;
     margin-bottom: 15px;
     list-style:disc outside none;
     display:inline;
     }

And Much, Much More!

I want to avoid using any graphics to simulate the bullet if at all possible.

Thanks for the help

Body:
Answer:
display: list-item;

Display must be set to list-item - not inline, and not list!

.list {
     list-style:disc outside none;
     display:list-item;
     }

<p class="list"><em>And Much, Much More!</em></p>


问:
PHP - How Can I Create Variable Names Within a Loop?
My goal is to have a loop where variable names are created.  Such as:

$variable1

$variable2

$variable3

and assigned values within the loop.  For instance, a for loop from 1 to 7 produces the variables $variable1, $variable2, $variable3, .etc, each with the value of the iterator.

答:
If you had an associative array i'ld prefer using the extract() method. Check it out here

for example

```<code><?php

/* Suppose that $var_array is an array*/

$var_array = array("color" => "blue",
               "size"  => "medium",
               "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape";

?>
</code>```

the above code would output,
blue, large, sphere, medium

Body:
If you had an associative array i'ld prefer using the extract() method. Check it out here

for example

<?php

/* Suppose that $var_array is an array*/

$var_array = array("color" => "blue",
               "size"  => "medium",
               "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape";

?>

the above code would output,
blue, large, sphere, medium


问:
web scraping of tables generated using JavaScript
I am trying to scrape the table from the codes tab on this website (the big table containing the x and .)

I thought one of the following would do the trick...

```<code>library(rvest)
library(tidyverse)
"https://international.ipums.org/international-action/variables/MIGYRSBR#codes_section" %>%
  read_html() %>%
  html_table()

"https://international.ipums.org/international-action/variables/MIGYRSBR#codes_section" %>%
  read_html() %>%
  html_nodes(".variablesList , #ui-id-1")
</code>```

... but nothing of use comes back. I had a look at the source of the html file. I think the the website is using some JavaScript to generate the table? Does this mean it is not possible to get the table?

Note: I cannot install RSelenium on my office PC

答:
See comment above about scraping, but in case it's helpful, we've just released the ipumsr package, which makes using IPUMS metadata in R a bit easier.

If you make an extract with MIGYRSBR in it, and then download the DDI (which is available even before the full microdata is), you can get the codes table using the command:

```<code># install.packages("ipumsr")
library(ipumsr)
ddi <- read_ipums_ddi("ipumsi_00020.xml")

ipums_val_labels(ddi, "MIGYRSBR")
#> # A tibble: 7 x 2
#>     val                              lbl
#>   <dbl>                            <chr>
#> 1     0                 Less than 1 year
#> 2     6 6 (6 to 10 1960-70, 6 to 9 1980)
#> 3    10                    10 (10+ 1980)
#> 4    11                 11 (11+ 1960-70)
#> 5    97                              97+
#> 6    98                          Unknown
#> 7    99            NIU (not in universe)
</code>```

Or, you can load the full dataset and the value labels will be attached as labelled class vectors (from haven). See the value-labels vignette for more details.

```<code>data <- read_ipums_micro(ddi, verbose = FALSE)
data$MIGYRSBR <- as_factor(data$MIGYRSBR)

table(data$MIGYRSBR)
#>
#>                 Less than 1 year                                1
#>                           123862                            65529
#>                                2                                3
#>                            77190                            59908
#>                                4                                5
#>                            44748                            49590
#> 6 (6 to 10 1960-70, 6 to 9 1980)                    10 (10+ 1980)
#>                           185220                                0
#>                 11 (11+ 1960-70)                              97+
#>                           318097                                0
#>                          Unknown            NIU (not in universe)
#>                             6459                          2070836
</code>```

Note the DDI alone won't have the availability / frequencies that are on the web, you'll need to calculate
those from the data.

Body:
I am trying to scrape the table from the codes tab on this website (the big table containing the x and .)

I thought one of the following would do the trick...

library(rvest)
library(tidyverse)
"https://international.ipums.org/international-action/variables/MIGYRSBR#codes_section" %>%
  read_html() %>%
  html_table()

"https://international.ipums.org/international-action/variables/MIGYRSBR#codes_section" %>%
  read_html() %>%
  html_nodes(".variablesList , #ui-id-1")

... but nothing of use comes back. I had a look at the source of the html file. I think the the website is using some JavaScript to generate the table? Does this mean it is not possible to get the table?

Note: I cannot install RSelenium on my office PC

Body:
See comment above about scraping, but in case it's helpful, we've just released the ipumsr package, which makes using IPUMS metadata in R a bit easier.

If you make an extract with MIGYRSBR in it, and then download the DDI (which is available even before the full microdata is), you can get the codes table using the command:

# install.packages("ipumsr")
library(ipumsr)
ddi <- read_ipums_ddi("ipumsi_00020.xml")

ipums_val_labels(ddi, "MIGYRSBR")
#> # A tibble: 7 x 2
#>     val                              lbl
#>   <dbl>                            <chr>
#> 1     0                 Less than 1 year
#> 2     6 6 (6 to 10 1960-70, 6 to 9 1980)
#> 3    10                    10 (10+ 1980)
#> 4    11                 11 (11+ 1960-70)
#> 5    97                              97+
#> 6    98                          Unknown
#> 7    99            NIU (not in universe)

Or, you can load the full dataset and the value labels will be attached as labelled class vectors (from haven). See the value-labels vignette for more details.

data <- read_ipums_micro(ddi, verbose = FALSE)
data$MIGYRSBR <- as_factor(data$MIGYRSBR)

table(data$MIGYRSBR)
#>
#>                 Less than 1 year                                1
#>                           123862                            65529
#>                                2                                3
#>                            77190                            59908
#>                                4                                5
#>                            44748                            49590
#> 6 (6 to 10 1960-70, 6 to 9 1980)                    10 (10+ 1980)
#>                           185220                                0
#>                 11 (11+ 1960-70)                              97+
#>                           318097                                0
#>                          Unknown            NIU (not in universe)
#>                             6459                          2070836

Note the DDI alone won't have the availability / frequencies that are on the web, you'll need to calculate
those from the data.


问:
Why run a program in a modified environment in a shell script
How is useful env in this install.sh script:

```<code>env git clone --depth=1 https://github.com/robbyrussell/oh-my-zsh.git $ZSH || {
  printf "Error: git clone of oh-my-zsh repo failed\n"
  exit 1
}
</code>```

Is it because of the variable $ZSH?

答:
The $ZSH variable is defined a couple of lines above so it is not the purpose here.

The env command can be used to run a command/program in a modified environment, but as there are no additional variables specified here, the command will be run in an unmodified environment.

The main purpose in this case is to get rid of aliases and functions that could shadow the command to be run.

Body:
How is useful env in this install.sh script:

env git clone --depth=1 https://github.com/robbyrussell/oh-my-zsh.git $ZSH || {
  printf "Error: git clone of oh-my-zsh repo failed\n"
  exit 1
}

Is it because of the variable $ZSH?


问:
How to add a dropdown menu using HTML and CSS
I want to use a href for the nav-menu instead of using a div class, so when 'menu' is clicked, link1, link2, and link3 appear as a drop-down list. My code is listed below ("ex7.css and ex7mobile.css" code is the same). I know there is a way of doing it using div class however I have been told to do it using href.

.clicker {
width:30px;
height:20px;
outline:none;
cursor:pointer;
}

.hiddendiv{
display:none;
height:70px;
}

.clicker:focus + .hiddendiv{
display:block;
}

header {
  display: block;
  background-color: blue;
  color: white;
  padding: 20px;
}

.box {
 background-color: red;
 width: 50px;
 height: 50px;
 margin-left: 0px;
 transition: margin-left 1s;
}

#menu:target .box {
 margin-left: 100px;
 background-color: green;

.content {
  display: table;
  width: 100%;
}

.shownav {
  background-color: white;
  height: 5px;
  width: 20px;
  display: block;
  border-radius: 5px;
  box-shadow: 0px 10px 0px white,
  0px -10px 0px white;
}

nav {
  width: 20%;
  display: table-cell;
  background-color: yellow;
}

main {
  width: 60%;
  display: table-cell;
  background-color: darkblue;
  color: white;
}

div {
  background-color: lightgreen;
  display: table-cell;
  width: 20%;
}

footer {
  clear: both;
  background-color: darkgreen;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>My Web Page!</title>
    <link rel="stylesheet" href="ex7.css"
    <link rel="stylesheet" href="ex7mobile.css"/>
media="screen and (max-width: 700px)" />
  </head>
  <body id="menu">
    <header>
      <h1>Heading</h1>
    </header>

<div class="content">

Menu
Close
<div class="box"></div>

<nav>
  <ul>
    <li>
      Link 1
    </li>
    <li>
      Link 2
    </li>
    <li>
      Link 3
    </li>
  </ul>
</nav>

    <main>
      <p>My website</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.</p>

<p>Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.</p>

<p>Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc.</p>
    </main>

    <div>
      Right hand side
    </div>
</div>

    <footer>
      © Your Name 2017
    </footer>
  </body>
</html></code>```

答:
You can try this in HTML5:

   Menu

      Link 1

      Link 2

      Link 3

```
</div>
</div>
</p>

<p>Or using Javascript:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>
function toggle() {
 var ele = document.getElementById("toggleText");
 var text = document.getElementById("displayText");
 if(ele.style.display == "block") {
      ele.style.display = "none";
   }
 else {
  ele.style.display = "block";
 }
} </code>```

Menu

      Link 1

      Link 2

      Link 3

```

Body:
I want to use a href for the nav-menu instead of using a div class, so when 'menu' is clicked, link1, link2, and link3 appear as a drop-down list. My code is listed below ("ex7.css and ex7mobile.css" code is the same). I know there is a way of doing it using div class however I have been told to do it using href.

.clicker {
width:30px;
height:20px;
outline:none;
cursor:pointer;
}

.hiddendiv{
display:none;
height:70px;
}

.clicker:focus + .hiddendiv{
display:block;
}

header {
  display: block;
  background-color: blue;
  color: white;
  padding: 20px;
}

.box {
 background-color: red;
 width: 50px;
 height: 50px;
 margin-left: 0px;
 transition: margin-left 1s;
}

#menu:target .box {
 margin-left: 100px;
 background-color: green;

.content {
  display: table;
  width: 100%;
}

.shownav {
  background-color: white;
  height: 5px;
  width: 20px;
  display: block;
  border-radius: 5px;
  box-shadow: 0px 10px 0px white,
  0px -10px 0px white;
}

nav {
  width: 20%;
  display: table-cell;
  background-color: yellow;
}

main {
  width: 60%;
  display: table-cell;
  background-color: darkblue;
  color: white;
}

div {
  background-color: lightgreen;
  display: table-cell;
  width: 20%;
}

footer {
  clear: both;
  background-color: darkgreen;
  color: white;
}

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>My Web Page!</title>
    <link rel="stylesheet" href="ex7.css"
    <link rel="stylesheet" href="ex7mobile.css"/>
media="screen and (max-width: 700px)" />

Heading

Menu
Close

      Link 1

      Link 2

      Link 3

My website

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.

Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.

Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc.

      Right hand side

      © Your Name 2017

Body:
You can try this in HTML5:

<details>
  <summary><a href="#"> Menu</a></summary>
  <ul>
    <li>
      <a href="#">Link 1</a>
    </li>
    <li>
      <a href="#">Link 2</a>
    </li>
    <li>
      <a href="#">Link 3</a>
    </li>
  </ul>
</details>

Or using Javascript:

function toggle() {
 var ele = document.getElementById("toggleText");
 var text = document.getElementById("displayText");
 if(ele.style.display == "block") {
      ele.style.display = "none";
   }
 else {
  ele.style.display = "block";
 }
}

<a id="displayText" href="javascript:toggle();">Menu</a>
<span id="toggleText" style="display: none">
  <ul>
    <li>
      <a href="#">Link 1</a>
    </li>
    <li>
      <a href="#">Link 2</a>
    </li>
    <li>
      <a href="#">Link 3</a>
    </li>
  </ul>
</span>


问:
C2386: 'void_t': a symbol with this name already exists in the current scope
I'm working on a Qt project which is intended to be built on Windows and on Linux. As a build system I use CMake with GCC 5.4 on Ubuntu 16.04 and with Visual Studio 2017 on Windows 10. Because the currently used standard is c++14 but I wanted to use the convenience type std::void_t I defined it as follows:

#if __cplusplus >= 201703L
#include <type_traits>
#else
namespace std {
template<typename... Ts> struct make_void { typedef void type; };
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
}
#endif
```

<p>The definition above is working fine if I build the project under Linux with the mentioned compiler, but when I try to build it under Windows I receive the following error messages:</p>

<pre class="lang-none prettyprint-override"><code>C2386: 'void_t': a symbol with this name already exists in the current scope
U1077: 'C:\PROGRA~2\MICROS~4\2017\ENTERP~1\VC\Tools\MSVC\1411~1.255\bin\HostX64\x64\cl.exe' : return code '0x2'
U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\nmake.exe"' : return code '0x2'
U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\nmake.exe"' : return code '0x2'
</code>```

The top-level CMake file sets the C++ standard as follows:

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
```

I don't understand why does Visual Studio 2017 complain for the std::void_t when the standard is set to c++14. Is this a normal behaviour and I expect it incorrectly that polluting the std namespace in the shown way won't cause errors? How can I overcome these errors produced by the Visual Studio 2017?

Edit: I just noticed that relying on the value of predefined macro __cplusplus may cause unexpected results. This question also aims to the __cplusplus macro.

答:
Is this a normal behaviour and I expect it incorrectly that polluting the std namespace in the shown way won't cause errors?

The standard library owns namespace std - you are only allowed to add things to it in certain, specific situations. Declaring brand new types is not one of those situations, and you should just not do it. Polluting namespace std is asking for trouble at some point.

In this particular case, there's really nothing to lose by using your own void_t over the standard library version. It'll work. So just do that. Or if you really want to use the standard ones, bring one or the other into a different namespace:

```<code>namespace xstd {
#if __cplusplus >= 201703L
    using std::void_t;
#else
    template<typename... Ts> struct make_void { typedef void type; };
    template<typename... Ts> using void_t = typename make_void<Ts...>::type;
#endif
}

// use xstd::void_t throughout
</code>```

Body:
I'm working on a Qt project which is intended to be built on Windows and on Linux. As a build system I use CMake with GCC 5.4 on Ubuntu 16.04 and with Visual Studio 2017 on Windows 10. Because the currently used standard is c++14 but I wanted to use the convenience type std::void_t I defined it as follows:

#if __cplusplus >= 201703L
#include <type_traits>
#else
namespace std {
template<typename... Ts> struct make_void { typedef void type; };
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
}
#endif

The definition above is working fine if I build the project under Linux with the mentioned compiler, but when I try to build it under Windows I receive the following error messages:

C2386: 'void_t': a symbol with this name already exists in the current scope
U1077: 'C:\PROGRA~2\MICROS~4\2017\ENTERP~1\VC\Tools\MSVC\1411~1.255\bin\HostX64\x64\cl.exe' : return code '0x2'
U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\nmake.exe"' : return code '0x2'
U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\nmake.exe"' : return code '0x2'

The top-level CMake file sets the C++ standard as follows:

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

I don't understand why does Visual Studio 2017 complain for the std::void_t when the standard is set to c++14. Is this a normal behaviour and I expect it incorrectly that polluting the std namespace in the shown way won't cause errors? How can I overcome these errors produced by the Visual Studio 2017?

Edit: I just noticed that relying on the value of predefined macro __cplusplus may cause unexpected results. This question also aims to the __cplusplus macro.

Body:
Is this a normal behaviour and I expect it incorrectly that polluting the std namespace in the shown way won't cause errors?

The standard library owns namespace std - you are only allowed to add things to it in certain, specific situations. Declaring brand new types is not one of those situations, and you should just not do it. Polluting namespace std is asking for trouble at some point.

In this particular case, there's really nothing to lose by using your own void_t over the standard library version. It'll work. So just do that. Or if you really want to use the standard ones, bring one or the other into a different namespace:

namespace xstd {
#if __cplusplus >= 201703L
    using std::void_t;
#else
    template<typename... Ts> struct make_void { typedef void type; };
    template<typename... Ts> using void_t = typename make_void<Ts...>::type;
#endif
}

// use xstd::void_t throughout


问:
Access 2013 Add multiple records

I am creating a Training Records database.
Tables: EmployeeList, RolesPerformed, SkillsNeeded, Courses, EmployeeRoles (Junction of EmployeeList and RolesPerformed), RoleSkills (Junction of Roles and Skills), SkillCourses (Junction of Skills and Courses). I can query to find out what courses an employee needs based on their roles. But I need to make another table to track the courses per employee and their date completed. When creating an Employee the user sets their Roles. I would like to auto populate the EmployeeCourses table with the needed courses.

I tried to use an After Insert event on EmployeeRoles, but it claims a createRecord cannot be used in a foreachrecord.

答:
Do you have a table that defines what courses go with what roles?

The real trick is figuring out what event to put code into. Perhaps AfterUpdate for a combobox to select Role. Will probably also need code that first commits the new employee/role record to table.

VBA could be like:

If Me.Dirty Then Me.Dirty = False
CurrentDb.Execute "INSERT INTO EmployeeCourses(EmpID, CourseID) SELECT " & Me.tbxEmpID & " AS EID, CourseID FROM RolesCourses WHERE RoleID = " & Me.cbxRoleID

To prevent duplicate employee/course entries, set compound index on the EmpID and CourseID fields in EmployeeCourses.

Title: Access 2013 Add multiple records


问:
ember-data: modeling a user-maintained list of products
Trying to wrap my head around how to efficiently model and code a "saved items" list for logged-in users.

I want the user to be able to click "save item" from a product page, and it will add the item to a list kept in their user profile that has its own route that displays their items and allows them to manage the list.  On that route, anytime there are changes to the list (like, item is removed), it should refresh to reflect the changes.

I'd think the user model would look something like this:

```<code>import DS from 'ember-data';
const { attr, belongsTo, hasMany } = DS;

export default DS.Model.extend({
    savedItems: hasMany('product'),
    ...
});
</code>```

And then I can add items to it with this action:

```<code>actions: {
    addSavedItem(product) {
        this.get('store').findRecord('user', 'me').then(user => {
            user.get('savedItems').pushObject(product);
            user.save();
        });
    },
}
</code>```

And load those saved items in my saved-items route like:

```<code>model() {
    return this.get("store").findRecord('user', 'me').then(user => {
        return user.get('savedItems');
    });
}
</code>```

That works!  BUT...product passes in the entire product object.  Name, prices, description, etc.  Then save sends it all in the payload to the back end.  Then the back-end has to send it all back (I think) for this to stay working.

Is there a way to have savedItems store just product IDs, and have ember-data load the rest of the product data as-needed?  Product ID is all I need to persist to the back end.

I've tried removing the relationship and having savedItems be an array:

```<code>savedItems: attr('')
</code>```

that stores just product IDs.  And I had partial success there.  But I can't figure out how to set up the model hook in the saved-items route so the it refreshes whenever there are changes to that list.

Any help appreciated!

UPDATE: Passing back just the product ids from the back end works - but only if the product is already in the store.

答:
I myself have setup such relationships that way:

```<code>// model user.js
export default DS.Model.extend({
    savedItems: hasMany('savedItem'),
    ...
});

// model savedItem.js
export default DS.Model.extend({
    //id- I have my ids in such a model as a string 'userID_productID'
    // just for convinience in the backend.
    user: belongsTo('user'),
    product: belongsTo('product'),
    someOtherPropertyUniqueToThatRelation: attr('string'), // like a status
    ...
});
</code>```

then I simply add another record to the relationShip Model.

```<code>addSavedItem(product) {
    this.get('store').findRecord('user', 'me').then(user => {
        let safedItem = this.get('store').createRecord('safedItem', {
              user: user,
              product: product,
              otherProp: 'whatever'
        });
        safedItem.save();
    });
},
</code>```

Now it's only sending the ids of user and product to the backend.

Maybe I'm doing it wrong, or this a strange approach, but that works fine for me in all situations.

Body:
Trying to wrap my head around how to efficiently model and code a "saved items" list for logged-in users.

I want the user to be able to click "save item" from a product page, and it will add the item to a list kept in their user profile that has its own route that displays their items and allows them to manage the list.  On that route, anytime there are changes to the list (like, item is removed), it should refresh to reflect the changes.

I'd think the user model would look something like this:

import DS from 'ember-data';
const { attr, belongsTo, hasMany } = DS;

export default DS.Model.extend({
    savedItems: hasMany('product'),
    ...
});

And then I can add items to it with this action:

actions: {
    addSavedItem(product) {
        this.get('store').findRecord('user', 'me').then(user => {
            user.get('savedItems').pushObject(product);
            user.save();
        });
    },
}

And load those saved items in my saved-items route like:

model() {
    return this.get("store").findRecord('user', 'me').then(user => {
        return user.get('savedItems');
    });
}

That works!  BUT...product passes in the entire product object.  Name, prices, description, etc.  Then save sends it all in the payload to the back end.  Then the back-end has to send it all back (I think) for this to stay working.

Is there a way to have savedItems store just product IDs, and have ember-data load the rest of the product data as-needed?  Product ID is all I need to persist to the back end.

I've tried removing the relationship and having savedItems be an array:

savedItems: attr('')

that stores just product IDs.  And I had partial success there.  But I can't figure out how to set up the model hook in the saved-items route so the it refreshes whenever there are changes to that list.

Any help appreciated!

UPDATE: Passing back just the product ids from the back end works - but only if the product is already in the store.

Body:
I myself have setup such relationships that way:

// model user.js
export default DS.Model.extend({
    savedItems: hasMany('savedItem'),
    ...
});

// model savedItem.js
export default DS.Model.extend({
    //id- I have my ids in such a model as a string 'userID_productID'
    // just for convinience in the backend.
    user: belongsTo('user'),
    product: belongsTo('product'),
    someOtherPropertyUniqueToThatRelation: attr('string'), // like a status
    ...
});

then I simply add another record to the relationShip Model.

addSavedItem(product) {
    this.get('store').findRecord('user', 'me').then(user => {
        let safedItem = this.get('store').createRecord('safedItem', {
              user: user,
              product: product,
              otherProp: 'whatever'
        });
        safedItem.save();
    });
},

Now it's only sending the ids of user and product to the backend.

Maybe I'm doing it wrong, or this a strange approach, but that works fine for me in all situations.


答:
The "accept" argument only filters on file types and extensions (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file)

You could write a JavaScript handler on before form post, or server-side handler, to capture and validate that the correct file name was chosen -- in fact, if you truly needed the file type to be correct, you would want to do this anyway -- as noted in the above reference documentation:

The accept attribute doesn't validate the types of the selected files; it simply provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.

Because of this, you should make sure that the accept attribute is backed up by appropriate server-side validation.

Title: Is there a way to only accept a file with a certain name for an input button?


问:
How to force a linebreak?
I've noticed that if I start a new paragraph right after an image, most renderers leave inadequate space between the image and the text below. The paragraph ends up looking like a legend. While this is useful when I do want to have a legend, sometimes I'd just like to insert an image in between two paragraphs, and have it adequately spaced below as above.

I correct this issue currently with:

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit:

[IMAGE]

<br/><br/>

Pellentesque pharetra turpis vitae velit consequat placerat. Duis sed volutpat neque, et scelerisque orci.
</code>```

But this strikes me as inelegant: I would like to avoid the HTML if possible.

Is there another way to force a linebreak?

I'm using Markdown Preview Plus for Atom to render.

答:
Short answer: two spaces at the end of the line

Details:

I am providing an updated answer, since @xof's answer, which while was incomplete was correct (per the docs):

When you do want to insert a
 break tag using Markdown, you end a line with two or more spaces, then type return.

Yes, this takes a tad more effort to create a
, but a simplistic “every line break is a
” rule wouldn’t work for Markdown. Markdown’s email-style blockquoting and multi-paragraph list items work best — and look better — when you format them with hard breaks.

Also, this has the extra benefit of avoiding the document unnecessarily becoming a mix of markdown and HTML. This retains readability, for when a Markdown viewer is not available, such as in a terminal window.

Just one thing: don't do a global trim on trailing spaces, as is often habit for source code, otherwise you'll lose important formatting.

Title: How to force a linebreak?

Body:
I've noticed that if I start a new paragraph right after an image, most renderers leave inadequate space between the image and the text below. The paragraph ends up looking like a legend. While this is useful when I do want to have a legend, sometimes I'd just like to insert an image in between two paragraphs, and have it adequately spaced below as above.

I correct this issue currently with:

Lorem ipsum dolor sit amet, consectetur adipiscing elit:

[IMAGE]

Pellentesque pharetra turpis vitae velit consequat placerat. Duis sed volutpat neque, et scelerisque orci.

But this strikes me as inelegant: I would like to avoid the HTML if possible.

Is there another way to force a linebreak?

I'm using Markdown Preview Plus for Atom to render.

Body:
Short answer: two spaces at the end of the line

Details:

I am providing an updated answer, since @xof's answer, which while was incomplete was correct (per the docs):

When you do want to insert a <br /> break tag using Markdown, you end a line with two or more spaces, then type return.

Yes, this takes a tad more effort to create a <br />, but a simplistic “every line break is a <br />” rule wouldn’t work for Markdown. Markdown’s email-style blockquoting and multi-paragraph list items work best — and look better — when you format them with hard breaks.

Also, this has the extra benefit of avoiding the document unnecessarily becoming a mix of markdown and HTML. This retains readability, for when a Markdown viewer is not available, such as in a terminal window.

Just one thing: don't do a global trim on trailing spaces, as is often habit for source code, otherwise you'll lose important formatting.

ContentLicense: CC BY-SA 4.0


问:
How can I keep queries like this out of mysql_slow.log?
I have the following query I need help with.

```<code>SELECT a.artist, a.facepic
FROM artists_vs AS v, artists AS a
WHERE v.genreid =0
AND (v.artistid1 = a.artistid OR v.artistid2 = a.artistid)
ORDER BY v.bid DESC
LIMIT 20
</code>```

All the fields in the query are indexed, but when I run an explain I get the following:

```<code>1   SIMPLE  v   ref genreid,artistid1,artistid2 genreid 4   const   15  Using temporary; Using filesort
1   SIMPLE  a   ALL PRIMARY NULL    NULL    NULL    18165   Range checked for each record (index map: 0x1)
</code>```

I need to have log-queries-not-using-indexes enabled in my.cnf

Can anyone suggest how I could rewrite this query to keep it out of the slow log?

答:
you can try something like this:</p>

```<code>SELECT
    a.artist,
    a.facepic,
    V.bid
FROM artists_vs AS v
inner join artists as a on v.artistid1 = a.artistid
WHERE v.genreid = 0
union
SELECT
    a.artist,
    a.facepic,
    v.bid
FROM artists_vs AS v
inner join artists as a on v.artistid2 = a.artistid
WHERE v.genreid = 0
ORDER BY bid DESC
LIMIT 20
</code>```

Body:
I have the following query I need help with.

SELECT a.artist, a.facepic
FROM artists_vs AS v, artists AS a
WHERE v.genreid =0
AND (v.artistid1 = a.artistid OR v.artistid2 = a.artistid)
ORDER BY v.bid DESC
LIMIT 20

All the fields in the query are indexed, but when I run an explain I get the following:

1   SIMPLE  v   ref genreid,artistid1,artistid2 genreid 4   const   15  Using temporary; Using filesort
1   SIMPLE  a   ALL PRIMARY NULL    NULL    NULL    18165   Range checked for each record (index map: 0x1)

I need to have log-queries-not-using-indexes enabled in my.cnf

Can anyone suggest how I could rewrite this query to keep it out of the slow log?

Body:
you can try something like this:

SELECT
    a.artist,
    a.facepic,
    V.bid
FROM artists_vs AS v
inner join artists as a on v.artistid1 = a.artistid
WHERE v.genreid = 0
union
SELECT
    a.artist,
    a.facepic,
    v.bid
FROM artists_vs AS v
inner join artists as a on v.artistid2 = a.artistid
WHERE v.genreid = 0
ORDER BY bid DESC
LIMIT 20


问:
Check if array is an ordered subset
I want to find out if an array is an ordered subset of another array:

[1,2] is an ordered subset of [1,2,3]

[1,3] is an ordered subset of [1,2,3]

[2,1] is not an ordered subset of [1,2,3]

I've found some solutions to this, but every solution ignores the order. Every method I've seen so far ignores the order of the arrays:

```<code>[1,2,3] - [2,1] #=> [3]
[1,2,3] & [2,1] #=> [1,2]
[1,2,3].to_set.superset?([2,1].to_set) #=> true
</code>```

Update:
Based on the discussion below, I've updated my question.

答:
Given two arrays, arr and sub, this is a way to determine if there exists an array of strictly increasing indices, indices, such that arr.values_at(*indices) == sub.

```<code>def ordered?(arr, sub)
  sub.each do |c|
    i = arr.index(c)
    return false if i.nil?
    arr = arr[i+1..-1]
  end
  true
end

ordered?([1,2,3], [1,2])           #=> true
ordered?([1,2,3], [2,3])           #=> true
ordered?([1,2,3], [1,3])           #=> true
ordered?([1,2,3], [3,1])           #=> false
ordered?([1,2,5,2,4,3,4], [2,2,3]) #=> true
</code>```

Note that @StefanPochmann suggested a more compact way of writing this in a comment below.

Title: Check if array is an ordered subset

Body:
I want to find out if an array is an ordered subset of another array:

[1,2] is an ordered subset of [1,2,3]

[1,3] is an ordered subset of [1,2,3]

[2,1] is not an ordered subset of [1,2,3]

I've found some solutions to this, but every solution ignores the order. Every method I've seen so far ignores the order of the arrays:

[1,2,3] - [2,1] #=> [3]
[1,2,3] & [2,1] #=> [1,2]
[1,2,3].to_set.superset?([2,1].to_set) #=> true

Update:
Based on the discussion below, I've updated my question.

Body:
Given two arrays, arr and sub, this is a way to determine if there exists an array of strictly increasing indices, indices, such that arr.values_at(*indices) == sub.

def ordered?(arr, sub)
  sub.each do |c|
    i = arr.index(c)
    return false if i.nil?
    arr = arr[i+1..-1]
  end
  true
end

ordered?([1,2,3], [1,2])           #=> true
ordered?([1,2,3], [2,3])           #=> true
ordered?([1,2,3], [1,3])           #=> true
ordered?([1,2,3], [3,1])           #=> false
ordered?([1,2,5,2,4,3,4], [2,2,3]) #=> true

Note that @StefanPochmann suggested a more compact way of writing this in a comment below.


问:
Reverse a string in javascript
I borrowed a piece of code for reversing a string in JavaScript. However it can't be done.

```<code>                <!DOCTYPE HTML>
            <html>
            <head>
            <meta charset="utf-8">
            <title>P4--Largest palindrome product</title>
            </head>
            <body>
            <!--A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

            Find the largest palindrome made from the product of two 3-digit numbers.
             -->
            <script type="text/javascript">
            var newdiv = document.createElement('div');
            newdiv.innerHTML=Palindromic();
                alert(Palindromic());
            function Palindromic(){
                var x;
                var a;
                var b;
                for(i=999*999;i>=100*100;i--)
                {
                    x=i.toString();
                    if(x != x.reverse())
                       continue;
                    else
                    {
                        for(j=100;j<999;j++)
                        {
                            if(i%j == 0)
                            {
                                var y =i/j;
                                if(y>=100 && y<=999)
                                {
                                    a=i;b=y;
                                    break;
                                }
                            }
                        }
                    }
                }
                return x;
            }
            String.prototype.reverse = function() {
              return this.split('').reverse().join('');
            }
            </script>
            </body>
            </html>
</code>```

The error is "has no method 'reverse'".

答:
ES6:
try this function

```<code>function reverse(str) {
           // 1 //    // 2 //   // 3 //
    return [...str].reverse().reduce((rev,el) => rev + el,'');
}
</code>```

spreads the string into an array of chars

reverses the array

reduce method on array to get the previous value and accumulate.

Title: Reverse a string in javascript

Body:
I borrowed a piece of code for reversing a string in JavaScript. However it can't be done.

                <!DOCTYPE HTML>

            <meta charset="utf-8">
            <title>P4--Largest palindrome product</title>

The error is "has no method 'reverse'".

Body:
ES6:
try this function

function reverse(str) {
           // 1 //    // 2 //   // 3 //
    return [...str].reverse().reduce((rev,el) => rev + el,'');
}

spreads the string into an array of chars

reverses the array

reduce method on array to get the previous value and accumulate.


问:
Unable to read from MongoDB slave using Node.js
I have seen many questions on the same regard but somehow I still can't successfully connect to MongoDB Slave.

I am running my cluster on Kubernetes using mongo-k8s-sidecar, connecting my application directly to the master works fine, however whenever I try to connect to the slave, I can't seem to read, here's error code:

MongoError: not master and slaveOk=false

I am using Node.js for my application, and this is how I am connecting:

```<code>var mongodb = require('mongodb').Db;
var Server = require('mongodb').Server
var db = new mongodb('dbname', new Server("localhost",27017,{slaveOk: true}));

        db.open(function(err, conn){
             if (err){
                callback(err);
             }else {
             client=conn;
             client.createIndex("tablename", {field:1}
             , {background:true}, function(err, i) {
                 logger.info(err);
             });
//The rest of the code is trimmed
</code>```

What am I missing here?

答:
You can't run createIndex() on a Secondary member, even if you're using slaveOk/ReadPreference.SECONDARY.

If you test the code without the createIndex() call, you'll probably see that it's working as you expect.

See Build Indexes on Replica Sets for more details. Basically, if you wanted to build an index on a secondary you need to stop the mongod instance, start it as a standalone (without the replSet option), then build the index.

Or you can only create the index on the Primary, and the index creation will replicate to the secondaries.

Body:
I have seen many questions on the same regard but somehow I still can't successfully connect to MongoDB Slave.

I am running my cluster on Kubernetes using mongo-k8s-sidecar, connecting my application directly to the master works fine, however whenever I try to connect to the slave, I can't seem to read, here's error code:

MongoError: not master and slaveOk=false

I am using Node.js for my application, and this is how I am connecting:

var mongodb = require('mongodb').Db;
var Server = require('mongodb').Server
var db = new mongodb('dbname', new Server("localhost",27017,{slaveOk: true}));

        db.open(function(err, conn){
             if (err){
                callback(err);
             }else {
             client=conn;
             client.createIndex("tablename", {field:1}
             , {background:true}, function(err, i) {
                 logger.info(err);
             });
//The rest of the code is trimmed

What am I missing here?


问:
How I can get info countries with allowed sms-sending from twilio.com in PHP?
How I can get countries via API with allowed sms-sending from twilio.com in PHP?

On image below highlighted what I need. Is this possible via API?

答:
Twilio developer evangelist here.

I'm afraid we don't have an API for that information. You can find out which countries' numbers support features like SMS from this page though: https://support.twilio.com/hc/en-us/articles/223183068-Twilio-international-phone-number-availability-and-their-capabilities


问:
Set response headers
I need to set some response headers within server.onPreHandler ext method.
There are 2 scenarios, where I need this happen when user sends an API request to my route end point.
1) In success scenario, I need to set headers and let process continue further down life cycle
2) In error scenario (where user has not provided a required field), I need to set headers and return immediately to user with appropriate error info.

In both of these scenarios, I would like to set response headers.
In the 2nd scenario above, I am able to invoke reply.response('error') and then set response header to it using response.header('x', 'value').  However, in the 1st scenario, where before calling reply.continue() I am trying to set header using request.response.header('x', 'value), I get response null error.

Please help

Thanks
Ramesh

答:
I'm able to change response headers like this. Have you tried this way?</p>

```<code>// at your onPreResponse ext body
const response = request.response;
if (request.response.isBoom) {
    response.output.headers['x'] = 'value';
} else {
    response.header('x', 'value');
}
</code>```

Title: Set response headers

Body:
I'm able to change response headers like this. Have you tried this way?

// at your onPreResponse ext body
const response = request.response;
if (request.response.isBoom) {
    response.output.headers['x'] = 'value';
} else {
    response.header('x', 'value');
}


问:
Regular expression to extract specific part of a URL
I have a vector of URLs and need to extract a certain part of it. I've tried using a regex tester to see if my attempts worked, but they were no good.

The URLs I have are in this format: https://www.baseball-reference.com/teams/MIL/1976.shtml

I ned to extract the three letters after "teams/" (so for the example above, I need "MIL")

Does anyone have any idea how to get the correct regular expression to get this working? Thanks.

答:
1) basename/dirname Try this:

```<code>u <- "https://www.baseball-reference.com/teams/MIL/1976.shtml" # input data

basename(dirname(u))
## [1] "MIL"
</code>```

2) sub or with a regular expression:

```<code>sub(".*teams/(.*?)/.*", "\\1", u)
## [1] "MIL"
</code>```

3) strsplit  Split the string on / and take the second last component.

```<code>s <- strsplit(u, "/")[[1]]
s[length(s) - 1]
## [1] "MIL"
</code>```

4) gsub Since the required substring is all upper case and no other characters in the input are this gsub which removes all characters that are not upper case letters would work:

```<code>gsub("[^A-Z]", "", u)
## [1] "MIL"
</code>```

Body:
1) basename/dirname Try this:

u <- "https://www.baseball-reference.com/teams/MIL/1976.shtml" # input data

basename(dirname(u))
## [1] "MIL"

2) sub or with a regular expression:

sub(".*teams/(.*?)/.*", "\\1", u)
## [1] "MIL"

3) strsplit  Split the string on / and take the second last component.

s <- strsplit(u, "/")[[1]]
s[length(s) - 1]
## [1] "MIL"

4) gsub Since the required substring is all upper case and no other characters in the input are this gsub which removes all characters that are not upper case letters would work:

gsub("[^A-Z]", "", u)
## [1] "MIL"


问:
How to switch frames using Protractor
I know this has been asked multiple times, and the suggested solution has been to use something like browser.driver.switchTo('your-frame-name') but I can't seem to access the same switchTo() method in my code.

This is my test :

```<code>import { AppPage } from './app.po';
import {browser, by, element} from 'protractor';

describe('angular-test App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    browser.driver.switchToParentFrame()

    //expect(page.getParagraphText()).toEqual('Welcome to app!');
    expect(element(by.id('myHeader')).getText()).toEqual('Welcome to Angular Test App!  ');
  });
});
</code>```

switchToParentFrame() is the only available method I get after the browser.driver.

This is how my HTML looks like

Any help is appreaciated, sorry for the vague description of the question but I'm pretty new to coding/protractor e2e testing.

答:
```<code> browser.switchTo().activeElement();
</code>```

or try to experiment with other available methods

Title: How to switch frames using Protractor

Body:
I know this has been asked multiple times, and the suggested solution has been to use something like browser.driver.switchTo('your-frame-name') but I can't seem to access the same switchTo() method in my code.

This is my test :

import { AppPage } from './app.po';
import {browser, by, element} from 'protractor';

describe('angular-test App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    browser.driver.switchToParentFrame()

    //expect(page.getParagraphText()).toEqual('Welcome to app!');
    expect(element(by.id('myHeader')).getText()).toEqual('Welcome to Angular Test App!  ');
  });
});

switchToParentFrame() is the only available method I get after the browser.driver.

This is how my HTML looks like

Any help is appreaciated, sorry for the vague description of the question but I'm pretty new to coding/protractor e2e testing.

Body:
 browser.switchTo().activeElement();

or try to experiment with other available methods


问:
Working with multiple related django modelforms
I'm trying to get two forms derived from related models to display on the same page and save together.

This is my models.py:

```<code>class userinfo(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key= True,
on_delete=models.CASCADE)
    name = models.CharField(max_length = 200, blank = True)
    email = models.EmailField(max_length= 300, default = 'Null')
    phone = models.CharField(max_length= 10, default = 'Null')

    def __unicode__(self):
        return self.user

class seller_event(models.Model):
    event_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
    title = models.CharField(max_length = 300, default = 'Null')
    description = models.CharField(max_length = 300, default = 'Null')
    location = models.CharField(max_length= 300, default = 'Null')
    cash_payment = models.BooleanField(default=False)
    paytm_payment = models.BooleanField(default=False)

    def __unicode__(self):
        return str(self.event_id) + str(self.title)
</code>```

As you can see, the user (saved as user_id in my sqlite3 db) is the foreign key from the userinfo table. I'm trying to get multiple events listed for each seller.

forms.py:

```<code>class Userinfo(forms.ModelForm):

    class Meta:
        model = userinfo
        exclude = {'user'}

class Seller_event(forms.ModelForm):

    class Meta:
        model = seller_event
        exclude = {'user'}
</code>```

views.py:

```<code>def newlist(request):
    if request.user.is_authenticated():
        user = request.user
        print user
        if request.method == 'POST':
            userinfo_form = Userinfo(request.POST, instance = user.userinfo)
            seller_event_form = Seller_event(request.POST, instance =
user.seller_event)
            if userinfo_form.is_valid() and seller_event_form.is_valid():
                userinfo_form.save()
                seller_event_form.save()
                return redirect('/home')
        else:
            userinfo_form = Userinfo()
            seller_event_form = Seller_event()

        return render(request, 'home/newlist.html', {'userinfo_form':
userinfo_form, 'seller_event_form': seller_event_form })
</code>```

html:

```<code>{% load static %}

<form action="/home/newlist/" method="post">

{% csrf_token %}
{{ userinfo_form.as_p }}
{{ seller_event_form.as_p }}

<input type="submit">

</form>
</code>```

I suspect the problem is that while for userinfo, the user pk is a onetoone, there is no issue with identifying the model. However, this is not the case for seller_event. Here it is a fk. So, how do I get it to accept the user as an fk?

Thanks in advance!

答:
After form validation, save your form without committing, then set your foreign key and save.</p>

```<code>if userinfo_form.is_valid() and seller_event_form.is_valid():
    userinfo_form.save()

    new_seller_event = seller_event_form.save(commit=False)
    new_seller_event.user = user
    new_seller_event.save()

    return redirect('/home')
</code>```

Body:
I'm trying to get two forms derived from related models to display on the same page and save together.

This is my models.py:

class userinfo(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key= True,
on_delete=models.CASCADE)
    name = models.CharField(max_length = 200, blank = True)
    email = models.EmailField(max_length= 300, default = 'Null')
    phone = models.CharField(max_length= 10, default = 'Null')

    def __unicode__(self):
        return self.user

class seller_event(models.Model):
    event_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
    title = models.CharField(max_length = 300, default = 'Null')
    description = models.CharField(max_length = 300, default = 'Null')
    location = models.CharField(max_length= 300, default = 'Null')
    cash_payment = models.BooleanField(default=False)
    paytm_payment = models.BooleanField(default=False)

    def __unicode__(self):
        return str(self.event_id) + str(self.title)

As you can see, the user (saved as user_id in my sqlite3 db) is the foreign key from the userinfo table. I'm trying to get multiple events listed for each seller.

forms.py:

class Userinfo(forms.ModelForm):

    class Meta:
        model = userinfo
        exclude = {'user'}

class Seller_event(forms.ModelForm):

    class Meta:
        model = seller_event
        exclude = {'user'}

views.py:

def newlist(request):
    if request.user.is_authenticated():
        user = request.user
        print user
        if request.method == 'POST':
            userinfo_form = Userinfo(request.POST, instance = user.userinfo)
            seller_event_form = Seller_event(request.POST, instance =
user.seller_event)
            if userinfo_form.is_valid() and seller_event_form.is_valid():
                userinfo_form.save()
                seller_event_form.save()
                return redirect('/home')
        else:
            userinfo_form = Userinfo()
            seller_event_form = Seller_event()

        return render(request, 'home/newlist.html', {'userinfo_form':
userinfo_form, 'seller_event_form': seller_event_form })

html:

{% load static %}

<form action="/home/newlist/" method="post">

{% csrf_token %}
{{ userinfo_form.as_p }}
{{ seller_event_form.as_p }}

<input type="submit">

</form>

I suspect the problem is that while for userinfo, the user pk is a onetoone, there is no issue with identifying the model. However, this is not the case for seller_event. Here it is a fk. So, how do I get it to accept the user as an fk?

Thanks in advance!

Body:
After form validation, save your form without committing, then set your foreign key and save.

if userinfo_form.is_valid() and seller_event_form.is_valid():
    userinfo_form.save()

    new_seller_event = seller_event_form.save(commit=False)
    new_seller_event.user = user
    new_seller_event.save()

    return redirect('/home')


问:
How to escape space in gradle script while running it on Linux OS?
I am running my gradle script on both windows and Linux OS.This is running fine while I run it on Windows OS.I am trying to execute the hg command to create the tag and push it to repository.Script is working fine.The issue is tag name.I apply the tag with below command which is running fine on windows OS.Gradle script is running this command.

```<code>commandLine "hg tag -r $hash \"Build $cbversion\"".split()
</code>```

But the same command is throwing an error while running on Linux OS and not applying the tag with Build 1.2.3.4 name.I tried below command but no luck

```<code>commandLine "hg tag -r $hash Build $cbversion".split()
</code>```

then it creates the tag with name Build only

Could someone tell me how could I overcome from this problem?

答:
This is executing a process and not the shell.  You can not quote here to make it work.  commandLine either takes an array or iteratable as arguments.  E.g.:

```<code>commandLine 'hg', 'tag', '-r', hash, "Build $cbversion"
</code>```

Body:
I am running my gradle script on both windows and Linux OS.This is running fine while I run it on Windows OS.I am trying to execute the hg command to create the tag and push it to repository.Script is working fine.The issue is tag name.I apply the tag with below command which is running fine on windows OS.Gradle script is running this command.

commandLine "hg tag -r $hash \"Build $cbversion\"".split()

But the same command is throwing an error while running on Linux OS and not applying the tag with Build 1.2.3.4 name.I tried below command but no luck

commandLine "hg tag -r $hash Build $cbversion".split()

then it creates the tag with name Build only

Could someone tell me how could I overcome from this problem?

Body:
This is executing a process and not the shell.  You can not quote here to make it work.  commandLine either takes an array or iteratable as arguments.  E.g.:

commandLine 'hg', 'tag', '-r', hash, "Build $cbversion"


问:
Why does css button lose its style when clicked?
Im completely lost with this one. Ok so I create a button with CSS, take a look at the CSS code:

```<code>.UploadPhotos a:link{
    display:block;
    width:100px;
    height:22px;
    padding-top:2px;
    margin-left:auto;
    margin-right:auto;
    text-align:center;
    background:url(../images/btn_image.png) 0 0 no-repeat;
    text-decoration:none;
    color:#FFF;
}
.UploadPhotos a:hover{
    background-position: 0 -24px;
    text-decoration:none;
    color:#060;
}
.UploadPhotos a:active{
    background-position: 0 0px;
    text-decoration:none;
    color:#FFF;
}
.UploadPhotos a:visited{
    background-position: 0 0px;
    text-decoration:none;
    color:#FFF;
}
</code>```

Now here is the HTML code:

```<code><div class="UploadPhotos">
    <a id="UpLd" href="uploader/upload.php">Upload Photos</a>
</div>
</code>```

The problem begins when I click on it. The link is opening up another page within an iframe which is done with js. Once I click this button, all the styles for this button is gone. I get the same problem even if I set the href="#" on the link. So I don't believe its the js opening the page. I can't figure out why the style suddenly disappears once clicked on.

I added images to give you guys an idea:

Regular

Hover

After click

Highlighting text with cursor after click

答:
Because :link means "An unvisited link" not "Any link".

Any styles you want to apply to the links all the time (i.e. everything except the colour, background-position and text-decoration) should be applied with either:

```<code>.UploadPhotos a {}
</code>```

or

```<code>.UploadPhotos a:link,
.UploadPhotos a:visited {}
</code>```

Body:
Im completely lost with this one. Ok so I create a button with CSS, take a look at the CSS code:

.UploadPhotos a:link{
    display:block;
    width:100px;
    height:22px;
    padding-top:2px;
    margin-left:auto;
    margin-right:auto;
    text-align:center;
    background:url(../images/btn_image.png) 0 0 no-repeat;
    text-decoration:none;
    color:#FFF;
}
.UploadPhotos a:hover{
    background-position: 0 -24px;
    text-decoration:none;
    color:#060;
}
.UploadPhotos a:active{
    background-position: 0 0px;
    text-decoration:none;
    color:#FFF;
}
.UploadPhotos a:visited{
    background-position: 0 0px;
    text-decoration:none;
    color:#FFF;
}

Now here is the HTML code:

    Upload Photos

The problem begins when I click on it. The link is opening up another page within an iframe which is done with js. Once I click this button, all the styles for this button is gone. I get the same problem even if I set the href="#" on the link. So I don't believe its the js opening the page. I can't figure out why the style suddenly disappears once clicked on.

I added images to give you guys an idea:

Regular

Hover

After click

Highlighting text with cursor after click

Body:
Because :link means "An unvisited link" not "Any link".

Any styles you want to apply to the links all the time (i.e. everything except the colour, background-position and text-decoration) should be applied with either:

.UploadPhotos a {}

or

.UploadPhotos a:link,
.UploadPhotos a:visited {}