问:
How to split the content of a String into a List
I am trying to iterate a txt file with java , I have the following code ,Firstly I read the txt file withouth any problem , then I add the lines that I am interested at the list called records and this arrays iterate correctly with the while.

The problem is that I received the content like this

```<code>  TCP    0.0.0.0:135            PCB:0             LISTENING
</code>```

I would like to split this content and avoid the white space  try before with split and trim but I am not doing this correctly.

Could anyone helps to me ?

```<code> String FILENAME = "src/example.txt";
        String line = null;
    Integer lines=0;
    Integer totalLines=countLines(FILENAME);
    List<String> records = new ArrayList<String>();

    try{
        InputStream fis=new FileInputStream(FILENAME);
        BufferedReader br=new BufferedReader(new InputStreamReader(fis));
            while ((line = br.readLine()) != null)
            {
                lines++;
                if (lines >= 5 && lines <= 180) {
                    records.add(line);
                }
            }
            br.close();

    }

    catch(Exception e){
        System.err.println("Error: Target File Cannot Be Read");
    }

    Iterator<String> it = records.iterator();

    while (it.hasNext()) {

        System.out.println(it.next());

    }
</code>```

Regards !

答:
Break your String into tokens, delimited by spaces

```<code>StringTokenizer st = new StringTokenizer(line);
</code>```

Then extract out the individual parts

```<code> String substringA = st.nextElement(); // "TCP"
 String substringB = st.nextElement(); // "0.0.0.0:135"
 String substringC = st.nextElement(); // "PCB:0"
 String substringD = st.nextElement(); // "LISTENING"
</code>```

As StringTokenizer is hated by many, you can alternatively split it into an array of Strings delimited by multiple spaces (using the regular expression "\\s+") using a method on the String object called split() like so:-

```<code>String[] tokens = line.split("\\s+");
</code>```

and access them via

```<code>String substringA = tokens[0]; // "TCP"
String substringB = tokens[1]; // "0.0.0.0:135"
String substringC = tokens[2]; // "PCB:0"
String substringD = tokens[3]; // "LISTENING"
</code>```

Body:
I am trying to iterate a txt file with java , I have the following code ,Firstly I read the txt file withouth any problem , then I add the lines that I am interested at the list called records and this arrays iterate correctly with the while.

The problem is that I received the content like this

  TCP    0.0.0.0:135            PCB:0             LISTENING

I would like to split this content and avoid the white space  try before with split and trim but I am not doing this correctly.

Could anyone helps to me ?

 String FILENAME = "src/example.txt";
        String line = null;
    Integer lines=0;
    Integer totalLines=countLines(FILENAME);
    List<String> records = new ArrayList<String>();

    try{
        InputStream fis=new FileInputStream(FILENAME);
        BufferedReader br=new BufferedReader(new InputStreamReader(fis));
            while ((line = br.readLine()) != null)
            {
                lines++;
                if (lines >= 5 && lines <= 180) {
                    records.add(line);
                }
            }
            br.close();

    }

    catch(Exception e){
        System.err.println("Error: Target File Cannot Be Read");
    }

    Iterator<String> it = records.iterator();

    while (it.hasNext()) {

        System.out.println(it.next());

    }

Regards !

Body:
Break your String into tokens, delimited by spaces

StringTokenizer st = new StringTokenizer(line);

Then extract out the individual parts

 String substringA = st.nextElement(); // "TCP"
 String substringB = st.nextElement(); // "0.0.0.0:135"
 String substringC = st.nextElement(); // "PCB:0"
 String substringD = st.nextElement(); // "LISTENING"

As StringTokenizer is hated by many, you can alternatively split it into an array of Strings delimited by multiple spaces (using the regular expression "\\s+") using a method on the String object called split() like so:-

String[] tokens = line.split("\\s+");

and access them via

String substringA = tokens[0]; // "TCP"
String substringB = tokens[1]; // "0.0.0.0:135"
String substringC = tokens[2]; // "PCB:0"
String substringD = tokens[3]; // "LISTENING"


来源: stackexchange

问:
how can i access the value of each data from this json?
```<code>{
    "sachin.company": {
        "classkey": "dotcompany",
        "status": "available"
    },
    "sachin.com": {
        "classkey": "domcno",
        "status": "regthroughothers"
    },
    "sachin.co.in": {
        "classkey": "thirdleveldotin",
        "status": "regthroughothers"
    },
   "sachin.org": {
        "classkey": "domorg",
        "status": "regthroughothers"
    },
    "sachin.guru": {
        "classkey": "dotguru",
        "status": "available"
    },
    "sachin.sexy": {
        "classkey": "dotsexy",
        "status": "available"
    },
    "sachin.nettlds=asia": {
        "status": "unknown"
    }
}
</code>```

I want to access the classKey and status from this object.
how can I access for each of keys value?
I tried this var keys = Object.keys(response); but this only create the array like ["sachin.company", "sachin.in", "sachin.community", "sachin.com", "sachin.computer", "sachin.co.in", "sachin.org", "sachin.compare", "sachin.net"]

答:
If you want to get all defined values

do as follows,

```<code>var allValues = [];
var keys = Object.keys(parsedJson);
Object.values(parsedJson).forEach(function(x) {
    Object.values(x).forEach(function(y){
       this.allValues.push(y);
    }, this);
}, this);
</code>```

allValues will give you what you want.

Thanks.

ContentLicense: CC BY-SA 3.0

Body:
{
    "sachin.company": {
        "classkey": "dotcompany",
        "status": "available"
    },
    "sachin.com": {
        "classkey": "domcno",
        "status": "regthroughothers"
    },
    "sachin.co.in": {
        "classkey": "thirdleveldotin",
        "status": "regthroughothers"
    },
   "sachin.org": {
        "classkey": "domorg",
        "status": "regthroughothers"
    },
    "sachin.guru": {
        "classkey": "dotguru",
        "status": "available"
    },
    "sachin.sexy": {
        "classkey": "dotsexy",
        "status": "available"
    },
    "sachin.nettlds=asia": {
        "status": "unknown"
    }
}

I want to access the classKey and status from this object.
how can I access for each of keys value?
I tried this var keys = Object.keys(response); but this only create the array like ["sachin.company", "sachin.in", "sachin.community", "sachin.com", "sachin.computer", "sachin.co.in", "sachin.org", "sachin.compare", "sachin.net"]

Body:
If you want to get all defined values

do as follows,

var allValues = [];
var keys = Object.keys(parsedJson);
Object.values(parsedJson).forEach(function(x) {
    Object.values(x).forEach(function(y){
       this.allValues.push(y);
    }, this);
}, this);

allValues will give you what you want.

Thanks.


问:
How to calculate the number of parameters of convolutional neural networks?
I can't give the correct number of parameters of AlexNet or VGG Net.

For example, to calculate the number of parameters of a conv3-256 layer of VGG Net, the answer is 0.59M = (3*3)*(256*256), that is (kernel size) * (product of both number of channels in the joint layers), however in that way, I can't get the 138M parameters.

So could you please show me where is wrong with my calculation, or show me the right calculation procedure?

答:
I know this is a old post nevertheless, I think the accepted answer by @deltheil contains a mistake. If not, I would be happy to be corrected. The convolution layer should not have bias.
i.e.
    128x3x3x256 (weights) + 256 (biases) = 295,168
should be
    128x3x3x256 (weights)  = 294,9112

Thanks


问:
Why is there a SIGSEGV here?
I'm trying to run this code here at http://ideone.com/YisrPH.

I am getting an SIGSEGV in this function -

```<code>int minDistance(string A, string B) {
    cout << "HEUI";
    int m = A.length();
    int n = B.length();
    cout << "H";
    int i, j;
    cout << "H";
    // int dist[m+1][n+1];
    // for(i=0;i<=m;i++)
    //     for(j=0;j<=n;j++)
    //         dist[i][j] = 0;
    cout << "H";
    vector<vector<int>> d(m+1, vector<int>(n+1,0));
    cout << "H";
    for(i=0;i<=m;i++) {
        for(j=0;j<=n;j++) {
            if(i==0) d[i][j] = j;
            if(j==0) d[i][j] = i;
            else if(A[i-1]==B[j-1]) d[i][j] = d[i-1][j-1];
            else d[i][j] = 1 + min(d[i-1][j], d[i][j-1], d[i-1][j-1]);
            // cout << dist[i][j] << i << j << endl;
        }
    }
    // cout << dist[m][n];
    return d[m][n];
}
</code>```

As you would notice, I am using vectors to construct a 2D array. If I replace that to use a normal 2D array, it runs, but the result is sometimes correct, and sometimes junk.

答:
You are accessing out of bounds of array.Consider i=0 and j=1

```<code> for(i=0;i<=m;i++)
 {
    for(j=0;j<=n;j++)
    {
        if(i==0)
            d[i][j] = j;
        if(j==0)
             d[i][j] = i;
        else if(A[i-1]==B[j-1])    //A[i-1]=A[0-1]=A[-1]
             d[i][j] = d[i-1][j-1];
</code>```

You can try this

```<code>   if(i==0 || j==0)
            d[i][j] = (i==0?j:i);
   else if(A[i-1]==B[j-1])
     ...
</code>```

Or better as pointed out by @mch in comments

```<code>    if(i==0 || j==0)
            d[i][j] = i+j;
   else if(A[i-1]==B[j-1])
      ...
</code>```

Title: Why is there a SIGSEGV here?

Body:
I'm trying to run this code here at http://ideone.com/YisrPH.

I am getting an SIGSEGV in this function -

int minDistance(string A, string B) {
    cout << "HEUI";
    int m = A.length();
    int n = B.length();
    cout << "H";
    int i, j;
    cout << "H";
    // int dist[m+1][n+1];
    // for(i=0;i<=m;i++)
    //     for(j=0;j<=n;j++)
    //         dist[i][j] = 0;
    cout << "H";
    vector<vector<int>> d(m+1, vector<int>(n+1,0));
    cout << "H";
    for(i=0;i<=m;i++) {
        for(j=0;j<=n;j++) {
            if(i==0) d[i][j] = j;
            if(j==0) d[i][j] = i;
            else if(A[i-1]==B[j-1]) d[i][j] = d[i-1][j-1];
            else d[i][j] = 1 + min(d[i-1][j], d[i][j-1], d[i-1][j-1]);
            // cout << dist[i][j] << i << j << endl;
        }
    }
    // cout << dist[m][n];
    return d[m][n];
}

As you would notice, I am using vectors to construct a 2D array. If I replace that to use a normal 2D array, it runs, but the result is sometimes correct, and sometimes junk.

Body:
You are accessing out of bounds of array.Consider i=0 and j=1

 for(i=0;i<=m;i++)
 {
    for(j=0;j<=n;j++)
    {
        if(i==0)
            d[i][j] = j;
        if(j==0)
             d[i][j] = i;
        else if(A[i-1]==B[j-1])    //A[i-1]=A[0-1]=A[-1]
             d[i][j] = d[i-1][j-1];

You can try this

   if(i==0 || j==0)
            d[i][j] = (i==0?j:i);
   else if(A[i-1]==B[j-1])
     ...

Or better as pointed out by @mch in comments

    if(i==0 || j==0)
            d[i][j] = i+j;
   else if(A[i-1]==B[j-1])
      ...


问:
saving values from radio buttons to database. rails app
I'm adding radio buttons to my page.
I want the user to be able to pick whether the order gets sent or they pick it up.

I'm having troubles to save the values to the database.

can someone advise me?

```<code>    <div class="col-md-5 pick-up-buttons" id="country_div">

    <li><%= f.radio_button :pick_up, true %></li>
    <li><%= f.label :pick_up, "Pick up order in store", :value => "false"  %></li>

    <li><%= f.radio_button :pick_up, false, :checked => true %></li>
    <li><%= f.label :pick_up, "have the order delivered", :value => "true" %></li>

  </div>
</code>```

here is the schema_file

```<code>  create_table "orders", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.text     "address"
    t.string   "city"
    t.string   "country"
    t.datetime "created_at",                 null: false
    t.datetime "updated_at",                 null: false
    t.boolean  "shipped",    default: false
    t.string   "pick_up"

  end
</code>```

答:
Just run:

```<code>rails generate migration changeStringToBooleanOfPickup
</code>```

then modified the generated migration file to:

```<code>change_column :orders, :pick_up, 'boolean USING CAST(pick_up AS boolean)'
</code>```

then execute
              rake db:migrate

Body:
I'm adding radio buttons to my page.
I want the user to be able to pick whether the order gets sent or they pick it up.

I'm having troubles to save the values to the database.

can someone advise me?

<%= f.radio_button :pick_up, true %>

<%= f.label :pick_up, "Pick up order in store", :value => "false"  %>

<%= f.radio_button :pick_up, false, :checked => true %>

<%= f.label :pick_up, "have the order delivered", :value => "true" %>

here is the schema_file

  create_table "orders", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.text     "address"
    t.string   "city"
    t.string   "country"
    t.datetime "created_at",                 null: false
    t.datetime "updated_at",                 null: false
    t.boolean  "shipped",    default: false
    t.string   "pick_up"

  end

Body:
Just run:

rails generate migration changeStringToBooleanOfPickup

then modified the generated migration file to:

change_column :orders, :pick_up, 'boolean USING CAST(pick_up AS boolean)'

then execute
              rake db:migrate


问:
How to specify sensitive environment variables at deploy time with Elastic Beanstalk
I am deploying a Python Flask application with Elastic Beanstalk. I have a config file /.ebextensions/01.config where among other things I set some environment variables - some of which should be secret.

The file looks something like this:

```<code>packages:
  yum:
    gcc: []
    git: []
    postgresql93-devel: []

option_settings:
  "aws:elasticbeanstalk:application:environment":
    SECRET_KEY: "sensitive"
    MAIL_USERNAME: "sensitive"
    MAIL_PASSWORD: "sensitive"
    SQLALCHEMY_DATABASE_URI: "sensitive"
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "app/static/"
</code>```

What are the best practices for keeping certain values secret? Currently the .ebextensions folder is under source control and I like this because it is shared with everyone, but at the same time I do not want to keep sensitive values under source control.

Is there a way to specify some environment variables through the EB CLI tool when deploying (e.g. eb deploy -config ...)? Or how is this use case covered by the AWS deployment tools?

答:
This question already has an answer, but I want to contribute an alternative solution to this problem. Instead of having to keep secrets in environment variables (which then have to be managed and stored somewhere out of version control, plus you need to remember to set them at deployment), I put all my secrets in an encrypted S3 bucket only accessible from the role the EB is running as. I then fetch the secrets at startup. This has the benefit of completely decoupling deployment from configuration, and you never ever have to fiddle with secrets in the command line again.

If needed (for example if secrets are needed during app setup, such as keys to repositories where code is fetched) you can also use an .ebextensions config file with an S3Auth directive to easily copy the contents of said S3 bucket to your local instance; otherwise just use the AWS SDK to fetch all secrets from the app at startup.

EDIT: As of April 2018 AWS offers a dedicated managed  service for secrets management; the AWS Secrets Manager. It offers convenient secure storage of secrets in string or json format, versioning, stages, rotation and more. It also eliminates some of the configuration when it comes to KMS, IAM etc for a quicker setup. I see no real reason using any other AWS service for storing static sensitive data such as private keys, passwords etc.

Body:
I am deploying a Python Flask application with Elastic Beanstalk. I have a config file /.ebextensions/01.config where among other things I set some environment variables - some of which should be secret.

The file looks something like this:

packages:
  yum:
    gcc: []
    git: []
    postgresql93-devel: []

option_settings:
  "aws:elasticbeanstalk:application:environment":
    SECRET_KEY: "sensitive"
    MAIL_USERNAME: "sensitive"
    MAIL_PASSWORD: "sensitive"
    SQLALCHEMY_DATABASE_URI: "sensitive"
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "app/static/"

What are the best practices for keeping certain values secret? Currently the .ebextensions folder is under source control and I like this because it is shared with everyone, but at the same time I do not want to keep sensitive values under source control.

Is there a way to specify some environment variables through the EB CLI tool when deploying (e.g. eb deploy -config ...)? Or how is this use case covered by the AWS deployment tools?

ContentLicense: CC BY-SA 4.0


问:
Strange matching nodes in Neo4j
I'm having a lot of problem trying to do something that should be very easy.
I have these 3 csv:
First one, Cast CSV ~ 150k records

```<code>idActor,idMovie,nameActor,character
"10990","321612","Belle","Emma Watson"
"221018","321612","Beast","Dan Stevens"
"114019","321612","Gaston","Luke Evans"
"8945","321612","Maurice","Kevin Kline"
</code>```

Second one, Actor CSV ~ 8k records.

```<code>idActor,deathday,gender,birthday,name,place_of_birth,popularity
"10990","null","1","1990-04-15","Emma Watson","Paris; France","54.327581"
"114019","null","2","1979-04-15","Luke Evans","Pontypool; Wales; UK","13.145154"
"54415","null","2","1981-02-23","Josh Gad","Hollywood; Florida; USA","11.418704"
"2283","null","2","1960-11-11","Stanley Tucci","Peekskill; New York; USA","11.013948"
"221018","null","2","1982-10-10","Dan Stevens","Croydon; Surrey; England; UK","27.461241"
"3061","null","2","1971-03-31","Ewan McGregor","Perth; Scotland; UK","18.398385"
</code>```

And the last one, Movie CSV ~ 10k records.

(Header - 1 line)

    idMovie,overview,popularity,companies,
    countries,release_date,revenue,runtime,tagline,vote_average,
    vote_count,budget,genre,title

```<code>"99861","When Tony Stark tries to jumpstart a dormant peacekeeping program, things go awry and Earth’s Mightiest Heroes are put to the ultimate test as the fate of the planet hangs in the balance. As the villainous Ultron emerges, it is up to The Avengers to stop him from enacting his terrible plans, and soon uneasy alliances and unexpected action pave the way for an epic and unique global adventure.","10.836173","Marvel Studios;Prime Focus;Revolution Sun Studios","US","2015-04-22","1405035767","141","A New Age Has Come.","7.3","5868","280000000","Action;Adventure;Science Fiction","Avengers: Age of Ultron"
</code>```

After doing import in Neo4j, converting the necessary field into Integer or Float, I want to do some relationship.

For example,

```<code>MATCH (m:Movie), (c:CastMember), (a:Actor)
WHERE m.idMovie = c.idMovie AND a.idActor = c.idActor
CREATE (a)-[:HAS_ACTED_IN{character:c.character}]->(m)
</code>```

But it create just ~50 relationships, instead of more than 100k.

So, I made other attemps, in particular:

```<code>MATCH (m:Movie), (c:CastMember)
WHERE m.idMovie = c.idMovie
RETURN DISTINCT m.title
</code>```

returns just ~20 matches.

Again,

```<code>MATCH (c:CastMember), (a:Actor)
WHERE c.idActor = a.idActor
RETURN a.name
</code>```

returns just ~5 matches.

The matches change every time I import the CSV. That's very strange.

答:
The docs about WHERE says:

WHERE adds constraints to the patterns in a MATCH or OPTIONAL MATCH
  clause or filters the results of a WITH clause.

So you can use more than one WHERE per Cypher query. I believe this is your case. I would try something like:

```<code>MATCH (c:CastMember)
MATCH (a:Actor)
WHERE a.idActor = c.idActor
MATCH (m:Movie)
WHERE m.idMovie = c.idMovie
CREATE (a)-[:HAS_ACTED_IN{character:c.character}]->(m)
</code>```

Title: Strange matching nodes in Neo4j

Body:
I'm having a lot of problem trying to do something that should be very easy.
I have these 3 csv:
First one, Cast CSV ~ 150k records

idActor,idMovie,nameActor,character
"10990","321612","Belle","Emma Watson"
"221018","321612","Beast","Dan Stevens"
"114019","321612","Gaston","Luke Evans"
"8945","321612","Maurice","Kevin Kline"

Second one, Actor CSV ~ 8k records.

idActor,deathday,gender,birthday,name,place_of_birth,popularity
"10990","null","1","1990-04-15","Emma Watson","Paris; France","54.327581"
"114019","null","2","1979-04-15","Luke Evans","Pontypool; Wales; UK","13.145154"
"54415","null","2","1981-02-23","Josh Gad","Hollywood; Florida; USA","11.418704"
"2283","null","2","1960-11-11","Stanley Tucci","Peekskill; New York; USA","11.013948"
"221018","null","2","1982-10-10","Dan Stevens","Croydon; Surrey; England; UK","27.461241"
"3061","null","2","1971-03-31","Ewan McGregor","Perth; Scotland; UK","18.398385"

And the last one, Movie CSV ~ 10k records.

(Header - 1 line)

    idMovie,overview,popularity,companies,
    countries,release_date,revenue,runtime,tagline,vote_average,
    vote_count,budget,genre,title

"99861","When Tony Stark tries to jumpstart a dormant peacekeeping program, things go awry and Earth’s Mightiest Heroes are put to the ultimate test as the fate of the planet hangs in the balance. As the villainous Ultron emerges, it is up to The Avengers to stop him from enacting his terrible plans, and soon uneasy alliances and unexpected action pave the way for an epic and unique global adventure.","10.836173","Marvel Studios;Prime Focus;Revolution Sun Studios","US","2015-04-22","1405035767","141","A New Age Has Come.","7.3","5868","280000000","Action;Adventure;Science Fiction","Avengers: Age of Ultron"

After doing import in Neo4j, converting the necessary field into Integer or Float, I want to do some relationship.

For example,

MATCH (m:Movie), (c:CastMember), (a:Actor)
WHERE m.idMovie = c.idMovie AND a.idActor = c.idActor
CREATE (a)-[:HAS_ACTED_IN{character:c.character}]->(m)

But it create just ~50 relationships, instead of more than 100k.

So, I made other attemps, in particular:

MATCH (m:Movie), (c:CastMember)
WHERE m.idMovie = c.idMovie
RETURN DISTINCT m.title

returns just ~20 matches.

Again,

MATCH (c:CastMember), (a:Actor)
WHERE c.idActor = a.idActor
RETURN a.name

returns just ~5 matches.

The matches change every time I import the CSV. That's very strange.

Body:
The docs about WHERE says:

WHERE adds constraints to the patterns in a MATCH or OPTIONAL MATCH
  clause or filters the results of a WITH clause.

So you can use more than one WHERE per Cypher query. I believe this is your case. I would try something like:

MATCH (c:CastMember)
MATCH (a:Actor)
WHERE a.idActor = c.idActor
MATCH (m:Movie)
WHERE m.idMovie = c.idMovie
CREATE (a)-[:HAS_ACTED_IN{character:c.character}]->(m)


问:
Foreign Key relationship using Primary Key of both tables
All users of our system are derived from a main "User" class. Likewise, we want to structure our database in the same way, having one main "user" table, which is joined with the necessary tables for the specific user type, to provide additional user information.

See as an example these three basic tables:

Table "user"

user_id | user_email | user_firstname | user_lastname | ...

Table "employee"

user_id | employee_staff_number | ...

Table "admin"

user_id | admin_permissions | ...

All three tables have the "user_id" column as their primary key, which will obviously always have the same value for same users.

However, I just tried to implement foreign keys, so that a user row cannot exist in the derived tables without the corresponding entry in the main user table. Trying to run the following SQL

```<code>ALTER TABLE `employee` ADD CONSTRAINT `fk_employee` FOREIGN KEY (`user_id`) REFERENCES `database_name`.`user`(`user_id`) ON DELETE RESTRICT ON UPDATE RESTRICT;
</code>```

results in the Error

```<code>#1215 - Cannot add foreign key constraint
</code>```

Is there even a way to implement this, without introducing a new primary key in the derived tables, to make "user_id" be a regular index in those?

答:
Two things to check for:

Is user(user_id) declared as the primary key in user?

Do user.user_id and employee.user_id have the same type?

You need an index on user(user_id) in order to use it as a foreign key reference.  The best way to create such an index is by declaring it to be a primary key.

Body:
All users of our system are derived from a main "User" class. Likewise, we want to structure our database in the same way, having one main "user" table, which is joined with the necessary tables for the specific user type, to provide additional user information.

See as an example these three basic tables:

Table "user"

user_id | user_email | user_firstname | user_lastname | ...

Table "employee"

user_id | employee_staff_number | ...

Table "admin"

user_id | admin_permissions | ...

All three tables have the "user_id" column as their primary key, which will obviously always have the same value for same users.

However, I just tried to implement foreign keys, so that a user row cannot exist in the derived tables without the corresponding entry in the main user table. Trying to run the following SQL

ALTER TABLE `employee` ADD CONSTRAINT `fk_employee` FOREIGN KEY (`user_id`) REFERENCES `database_name`.`user`(`user_id`) ON DELETE RESTRICT ON UPDATE RESTRICT;

results in the Error

#1215 - Cannot add foreign key constraint

Is there even a way to implement this, without introducing a new primary key in the derived tables, to make "user_id" be a regular index in those?


问:
Unexpected syntax error when copying Excel VBA code from a Web site
I was looking for a function to conditionally concatenate a range of cells in Excel. This function

```<code>Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, ConcatenateRange As Range, Optional Separator As String = ",") As Variant

Dim xResult As String
On Error Resume Next
If CriteriaRange.Count <> ConcatenateRange.Count Then
    ConcatenateIf = CVErr(xlErrRef)
    Exit Function
End If
For i = 1 To CriteriaRange.Count
    If CriteriaRange.Cells(i).Value = Condition Then
        xResult = xResult & Separator & ConcatenateRange.cells(i).Value
    End If
For i = 1 To CriteriaRange.Count
Next i
If xResult <> "" Then
    xResult = VBA.Mid(xResult, VBA.Len(Separator) + 1)
End If
ConcatenateIf = xResult
Exit Function
</code>```

from https://www.extendoffice.com/documents/excel/2723-excel-concatenate-based-on-criteria.html looked just the ticket. Comments suggested it had worked for other coders.

However, when I paste it into a VBA module in Excel2016, there are syntax errors which I can't figure out. "Exit Function" on line 7 can be resolved by deleting "Function". The call of "Exit Function" at the end doesn't register as an error but can removed as superfluous. But

```<code>If CriteriaRange.Cells(i).Value = Condition Then
</code>```

is highlighted as a syntax error (and the matching "End If"). If I simply use "If true Then", the error doesn't go away, which suggests looking at the previous line

```<code>For i = 1 To CriteriaRange.Count
</code>```

and I tried "For i = 1 To 8" but that doesn't fix it either. I just can't see what it wrong?

Further to the helpful responses, here is a screenshot of a direct paste into VBA

and here is a screenshot of the "dodgy" space characters as seen in Word

答:
Edit 2

As the OP discovered, copying and pasting from the Web site gives a bunch of non-breaking spaces:

On my test case (Excel 2013, Win7), those paste in fine, and Excel doesn't barf.  However, the OP's installation (Excel 2016) can't handle them.

To change those:

Paste the code into Word.

Do a Find/Replace to change ^s (nonbreaking spaces, ChrW(160)) to a single space ().

Copy from Word to Excel.

Original

All I had to do to get it to compile was:

Comment out the second For i=... line

Change Exit Function on the last line to End Function.

Haven't tested it, though.  Would you please edit your question to add the test case you are trying?

Edit @YowE3K beat me to it — there are some copy-and-paste errors in the code in your question.  Recopy from the site and you should be OK!

Body:
I was looking for a function to conditionally concatenate a range of cells in Excel. This function

Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, ConcatenateRange As Range, Optional Separator As String = ",") As Variant

Dim xResult As String
On Error Resume Next
If CriteriaRange.Count <> ConcatenateRange.Count Then
    ConcatenateIf = CVErr(xlErrRef)
    Exit Function
End If
For i = 1 To CriteriaRange.Count
    If CriteriaRange.Cells(i).Value = Condition Then
        xResult = xResult & Separator & ConcatenateRange.cells(i).Value
    End If
For i = 1 To CriteriaRange.Count
Next i
If xResult <> "" Then
    xResult = VBA.Mid(xResult, VBA.Len(Separator) + 1)
End If
ConcatenateIf = xResult
Exit Function

from https://www.extendoffice.com/documents/excel/2723-excel-concatenate-based-on-criteria.html looked just the ticket. Comments suggested it had worked for other coders.

However, when I paste it into a VBA module in Excel2016, there are syntax errors which I can't figure out. "Exit Function" on line 7 can be resolved by deleting "Function". The call of "Exit Function" at the end doesn't register as an error but can removed as superfluous. But

If CriteriaRange.Cells(i).Value = Condition Then

is highlighted as a syntax error (and the matching "End If"). If I simply use "If true Then", the error doesn't go away, which suggests looking at the previous line

For i = 1 To CriteriaRange.Count

and I tried "For i = 1 To 8" but that doesn't fix it either. I just can't see what it wrong?

Further to the helpful responses, here is a screenshot of a direct paste into VBA

and here is a screenshot of the "dodgy" space characters as seen in Word


答:
Testing on Excel 2010 there are 2 errors to solve:

You have For i = 1 To CriteriaRange.Count twice - you need to delete the second one. This seems it must be a typing error or something

The function should end with End Function

Working code with corrections:

```<code>Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, ConcatenateRange As Range, Optional Separator As String = ",") As Variant

    Dim xResult As String

    On Error Resume Next

    If CriteriaRange.Count <> ConcatenateRange.Count Then
        ConcatenateIf = CVErr(xlErrRef)
        Exit Function
    End If

    For i = 1 To CriteriaRange.Count
        If CriteriaRange.Cells(i).Value = Condition Then
            xResult = xResult & Separator & ConcatenateRange.Cells(i).Value
        End If
    Next i

    If xResult <> "" Then
        xResult = VBA.Mid(xResult, VBA.Len(Separator) + 1)
    End If

    ConcatenateIf = xResult

End Function
</code>```

Title: Unexpected syntax error when copying Excel VBA code from a Web site

Body:
Testing on Excel 2010 there are 2 errors to solve:

You have For i = 1 To CriteriaRange.Count twice - you need to delete the second one. This seems it must be a typing error or something

The function should end with End Function

Working code with corrections:

Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, ConcatenateRange As Range, Optional Separator As String = ",") As Variant

    Dim xResult As String

    On Error Resume Next

    If CriteriaRange.Count <> ConcatenateRange.Count Then
        ConcatenateIf = CVErr(xlErrRef)
        Exit Function
    End If

    For i = 1 To CriteriaRange.Count
        If CriteriaRange.Cells(i).Value = Condition Then
            xResult = xResult & Separator & ConcatenateRange.Cells(i).Value
        End If
    Next i

    If xResult <> "" Then
        xResult = VBA.Mid(xResult, VBA.Len(Separator) + 1)
    End If

    ConcatenateIf = xResult

End Function


问:
How to add space in a string in excel vba?
how can i add space in this example string?

Input value in cell A1 is ABCDEFGHIJK and will be paste in another cell B1 with a format of ABCDE FG HIJK.

答:
One formula to insert a space:
=LEFT(A1,5)&" "&RIGHT(A1,LEN(A1)-5) to insert a space after the 5th position. (ABCDE FGHIJK)

One to insert 2 spaces as per example:
=LEFT(A1,5)&" "&MID(A1,6,2)&" "&RIGHT(A1,LEN(A1)-7)
Input ABCDEFGHIJK, result ABCDE FG HIJK

In short: Use =LEFT(), =RIGHT() and =MID() to get parts of your string and concatenate the parts and your spaces.

Edit:
In VBA:

```<code>Public Function StringWithSpaces(inpStr As String) As String
    StringWithSpaces = Left(inpStr, 5) & " " & Mid(inpStr, 6, 2) & " " & Right(inpStr, Len(inpStr) - 7)
End Function
</code>```

Body:
One formula to insert a space:
=LEFT(A1,5)&" "&RIGHT(A1,LEN(A1)-5) to insert a space after the 5th position. (ABCDE FGHIJK)

One to insert 2 spaces as per example:
=LEFT(A1,5)&" "&MID(A1,6,2)&" "&RIGHT(A1,LEN(A1)-7)
Input ABCDEFGHIJK, result ABCDE FG HIJK

In short: Use =LEFT(), =RIGHT() and =MID() to get parts of your string and concatenate the parts and your spaces.

Edit:
In VBA:

Public Function StringWithSpaces(inpStr As String) As String
    StringWithSpaces = Left(inpStr, 5) & " " & Mid(inpStr, 6, 2) & " " & Right(inpStr, Len(inpStr) - 7)
End Function


问:
Python Socket gives "[Errno 24] Too many open files"
I have the following UDP class sending arrays of data at about 100Hz

```<code>from six import string_types
import socket
import struct

def convert_data(iterable):
    if isinstance(iterable, string_types):
        return str(iterable)
    data = tuple(iterable)
    format = "{0}H".format(len(data))
    print("Sending data:", format, data)
    if max(data) > 2**16 - 1:
        raise ValueError(max(data))
    if min(data) < 0:
        raise ValueError(min(data))
    return struct.pack(format, *data)

class UDP(object):
    def __init__(self, ip, port):
        self._ip = ip
        self._port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.connect((ip, port))

    def send_data(self, data):
        message = convert_data(data)
        return self.socket.sendall(message)
</code>```

It gives the following error after successfully sending for about a minute:

```<code>Traceback (most recent call last):
  File "take_analogue_data.py", line 13, in <module>
  File "take_analogue_data.py", line 8, in main
  File "/home/pi/nio-integration/hardware/raspi/UDP.py", line 22, in __init__
  File "/usr/lib/python2.7/socket.py", line 187, in __init__
socket.error: [Errno 24] Too many open files
</code>```

I have looked for a solution. This Stack Overflow answer suggests increasing the number of possible files. I really don't think this is the solution I am looking for though.

Is there something I can do? I was thinking that closing the connection each time might work, but I have already played around with a bunch of things. (I have tried send, sendall, and sendto -- none have worked)

Note: I am running Python2.6 on Raspbian Wheezy on a Raspberry Pi

Edit
Another module is sending the data. It could look something like

```<code>import UDP
udp = UDP.UDP(IP, PORT)
while(True):
    udp.send_data(range(8))
    sleep(0.01)
</code>```

答:
```<code>class UDP(object):

    def __init__(self, ip, port):
        self._ip = ip
        self._port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.connect((ip, port))
</code>```

What you have to know about UDP is that it is a session less and connectionless protocol which means that the: self.socket.connect((ip,int(port))) is not right and so you should remove it.

If you want to connect to a server use Tcp instead:

```<code>class TCP(object):

    def __init__(self, ip, port):
        self._ip = ip
        self._port = port
        self.socket = socket.socket() #Here is the change
        self.socket.connect((ip, port))

    def send_data(self, data):
        message = convert_data(data)
        return self.socket.sendall(message)
</code>```

Hope it helped !

Body:
I have the following UDP class sending arrays of data at about 100Hz

from six import string_types
import socket
import struct

def convert_data(iterable):
    if isinstance(iterable, string_types):
        return str(iterable)
    data = tuple(iterable)
    format = "{0}H".format(len(data))
    print("Sending data:", format, data)
    if max(data) > 2**16 - 1:
        raise ValueError(max(data))
    if min(data) < 0:
        raise ValueError(min(data))
    return struct.pack(format, *data)

class UDP(object):
    def __init__(self, ip, port):
        self._ip = ip
        self._port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.connect((ip, port))

    def send_data(self, data):
        message = convert_data(data)
        return self.socket.sendall(message)

It gives the following error after successfully sending for about a minute:

Traceback (most recent call last):
  File "take_analogue_data.py", line 13, in <module>
  File "take_analogue_data.py", line 8, in main
  File "/home/pi/nio-integration/hardware/raspi/UDP.py", line 22, in __init__
  File "/usr/lib/python2.7/socket.py", line 187, in __init__
socket.error: [Errno 24] Too many open files

I have looked for a solution. This Stack Overflow answer suggests increasing the number of possible files. I really don't think this is the solution I am looking for though.

Is there something I can do? I was thinking that closing the connection each time might work, but I have already played around with a bunch of things. (I have tried send, sendall, and sendto -- none have worked)

Note: I am running Python2.6 on Raspbian Wheezy on a Raspberry Pi

Edit
Another module is sending the data. It could look something like

import UDP
udp = UDP.UDP(IP, PORT)
while(True):
    udp.send_data(range(8))
    sleep(0.01)

Body:
class UDP(object):

    def __init__(self, ip, port):
        self._ip = ip
        self._port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.connect((ip, port))

What you have to know about UDP is that it is a session less and connectionless protocol which means that the: self.socket.connect((ip,int(port))) is not right and so you should remove it.

If you want to connect to a server use Tcp instead:

class TCP(object):

    def __init__(self, ip, port):
        self._ip = ip
        self._port = port
        self.socket = socket.socket() #Here is the change
        self.socket.connect((ip, port))

    def send_data(self, data):
        message = convert_data(data)
        return self.socket.sendall(message)

Hope it helped !


问:
JUnit test results show 0 when test fails, but 1 when test is ok
I am starting with JUnit tests.

I am trying to write simple test and got the issue.

When test is ok, it is shown in results:
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s

```<code>@SpringBootTest
public class SampleTest {

    @Test
    public void Test() {
        assertEquals( 1,1, "Fail");
        // assertEquals( 1,0, "Fail"); Should fail and display message
    }
}
</code>```

When I change one 1 to 0, so it should fail:
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s
It also doesn't throw the error message which should be thrown.

Am I doing something wrong or it should not be like that? Tried to google but can't find similar issue.

I am using JUnit5. Running tests from IntelliJ Idea - > Maven Projects -> Lifecycle -> Test

UPDATE:

I have tried to run it from IntelliJ - all messages shown etc.
Strange that it is not working properly from Maven tests.

UPDATE 2:
It may be something about pom.xml config?

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.project</groupId>
    <artifactId>project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>project</name>
    <description>project - server</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.BUILD-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <junit-jupiter-api-version>5.0.0-M5</junit-jupiter-api-version>
        <junit.jupiter.version>5.0.0-M5</junit.jupiter.version>
        <junit.platform.version>1.0.0-M5</junit.platform.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-social-facebook</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>LATEST</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>LATEST</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Use MySQL Connector-J -->

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-hibernate5 -->
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-hibernate5</artifactId>
            <version>2.9.0.pr1</version>
        </dependency>

        <!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
            <scope>compile</scope>
        </dependency>

        <!-- Guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit-jupiter-api-version}</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-runner</artifactId>
            <version>${junit.platform.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.platform</groupId>
                        <artifactId>junit-platform-surefire-provider</artifactId>
                        <version>1.0.0-M4</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>

    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>

    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>surefire-snapshots</id>
            <name>Surefire Snapshots</name>
            <url>https://repository.apache.org/snapshots/org/apache/maven/plugins/maven-surefire-plugin/</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

答:
Maven Surefire Plugin 2.20 is not supported. See https://github.com/junit-team/junit5/issues/809 for details. Roll back to 2.19.1

Align the JUnit (Jupiter and Platform) versions through-out the pom.xml. There's a mixure of M4 and M5.

When I change one 1 to 0, so it should fail: Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s It also doesn't throw the error message which should be thrown.

Tests run: 0 is reported because of the OutOfMemoryError produced by the Maven Surefire Plugin 2.20

Body:
I am starting with JUnit tests.

I am trying to write simple test and got the issue.

When test is ok, it is shown in results:
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s

@SpringBootTest
public class SampleTest {

    @Test
    public void Test() {
        assertEquals( 1,1, "Fail");
        // assertEquals( 1,0, "Fail"); Should fail and display message
    }
}

When I change one 1 to 0, so it should fail:
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s
It also doesn't throw the error message which should be thrown.

Am I doing something wrong or it should not be like that? Tried to google but can't find similar issue.

I am using JUnit5. Running tests from IntelliJ Idea - > Maven Projects -> Lifecycle -> Test

UPDATE:

I have tried to run it from IntelliJ - all messages shown etc.
Strange that it is not working properly from Maven tests.

UPDATE 2:
It may be something about pom.xml config?

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.project</groupId>
    <artifactId>project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>project</name>
    <description>project - server</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.BUILD-SNAPSHOT</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <junit-jupiter-api-version>5.0.0-M5</junit-jupiter-api-version>
        <junit.jupiter.version>5.0.0-M5</junit.jupiter.version>
        <junit.platform.version>1.0.0-M5</junit.platform.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-social-facebook</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>LATEST</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>LATEST</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-hibernate5</artifactId>
            <version>2.9.0.pr1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit-jupiter-api-version}</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-runner</artifactId>
            <version>${junit.platform.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.platform</groupId>
                        <artifactId>junit-platform-surefire-provider</artifactId>
                        <version>1.0.0-M4</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>

    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>

    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>surefire-snapshots</id>
            <name>Surefire Snapshots</name>
            <url>https://repository.apache.org/snapshots/org/apache/maven/plugins/maven-surefire-plugin/</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>


问:
Label original and duplicate copies of report
My report has 2 pages in one invoice. I need 3 copies for each invoice.
I want each to be labelled 1st copy - original copy; 2nd copy- duplicate copy; and 3rd copy - triplicate copy.

How can I set this up?

答:
Insert subreport

In the selection window, choose existing report. Browse to your invoice report

In Link Tab, link your main report parameter to sub report parameter.

Then in the subreport, change the header duplicate.

Repeat steps for triplicate


问:
How to achieve UILabel line breaks only on a specific separator character?
I have a string which has a separator character between words (Words with spaces) eg.

```<code>"Male • 89 • Senior Citizen • Side Lower Berth • Non Veg • Bedroll"
</code>```

So "•" is separator here. Now while assigning it to a multiline label I want line breaks only on this separator. Eg. I don't want line breaks in between "Side Lower Berth" so that some part of it rendered in the first line and remaining one in next line. It should draw it next line only by making the decision based on the defined separator "•" here.

答: Try replacing all of your ordinary spaces with nonbreaking spaces, except in the places where you want to allow that break the line. (So leave an ordinary space after each bullet)</p>

Body:
I have a string which has a separator character between words (Words with spaces) eg.

"Male • 89 • Senior Citizen • Side Lower Berth • Non Veg • Bedroll"

So "•" is separator here. Now while assigning it to a multiline label I want line breaks only on this separator. Eg. I don't want line breaks in between "Side Lower Berth" so that some part of it rendered in the first line and remaining one in next line. It should draw it next line only by making the decision based on the defined separator "•" here.


问:
Java Selenium webdriver : How to handle authentication window post login
I am trying to automate a login scenario for a web app , where after submitting username and password we see a native authentication pop-up(Not HTML) .

Scenario

```<code>sendKeys("Email","Test");
sendKeys("Password","user");
click('Login');
</code>```

Post clicking on Login , we see a authentication window in which we have to enter different credentials

Problem : After clicking on login button ,control never goes to next Line and it throws timeout exception(closing out the authentication pop up) . Any suggestions how to handle this .

What all i've tried so far - alert.authenticateUsing() and robot Script are not useful yet because control never goes to next line .

username:password@url is not an option because that url be generated after first credentials are validated.

ENV : MAC , Selenium 3.3 , Chrome Latest

答: Resolved it with username:password@url using some internal hacks </p>

Body:
I am trying to automate a login scenario for a web app , where after submitting username and password we see a native authentication pop-up(Not HTML) .

Scenario

sendKeys("Email","Test");
sendKeys("Password","user");
click('Login');

Post clicking on Login , we see a authentication window in which we have to enter different credentials

Problem : After clicking on login button ,control never goes to next Line and it throws timeout exception(closing out the authentication pop up) . Any suggestions how to handle this .

What all i've tried so far - alert.authenticateUsing() and robot Script are not useful yet because control never goes to next line .

username:password@url is not an option because that url be generated after first credentials are validated.

ENV : MAC , Selenium 3.3 , Chrome Latest


问:
String manipulation in C#. Inserting "+" between words
This is as far as I have got. My thinking was to stuff the string into an array, format it and recast it into a string.

```<code>    //input search term
    Console.WriteLine("What is your search query?:");
    string searchTerm = Console.ReadLine();

    //stuff the search term into an array to split it out
    string separator = " "; //assumes search terms are separated by spaces
    string[] searchTermArray = searchTerm.Split(separator.ToCharArray());

    //construct the search term
    string searchTermFormat = "";

    for (int i = 0; i < searchTermArray.Length; i++)
    {
        searchTermFormat += searchTermArray[i] + "+";
        //Console.WriteLine(searchTermFormat);
    }
</code>```

Desired output

```<code>word1+word2+word3
</code>```

where the number of words are not fixed.

答: Try string.Replace(" ", "+")

ContentLicense: CC BY-SA 2.5

Body:
This is as far as I have got. My thinking was to stuff the string into an array, format it and recast it into a string.

    //input search term
    Console.WriteLine("What is your search query?:");
    string searchTerm = Console.ReadLine();

    //stuff the search term into an array to split it out
    string separator = " "; //assumes search terms are separated by spaces
    string[] searchTermArray = searchTerm.Split(separator.ToCharArray());

    //construct the search term
    string searchTermFormat = "";

    for (int i = 0; i < searchTermArray.Length; i++)
    {
        searchTermFormat += searchTermArray[i] + "+";
        //Console.WriteLine(searchTermFormat);
    }

Desired output

word1+word2+word3

where the number of words are not fixed.

Body: Try string.Replace(" ", "+")