问:
Cannot start Jenkins
After downloading a plugin, the Jenkins server cannot be accessed. I am using windows 7.
I tried to start windows Jenkins service manually, but I get the following message:

"Windows could not start the Jenkins service on Local COmputer. Error
  1067: The process terminated unexpectedly"

I also tried to run the jenkins.exe from the installation directory, but with no success.
In the error logs I see the following:

```<code>INFO: Obtained the updated data file for hudson.tasks.Maven.MavenInstaller
Ιουν 06, 2014 11:31:46 ΠΜ hudson.model.DownloadService$Downloadable doPostBack
INFO: Obtained the updated data file for hudson.tools.JDKInstaller
Ιουν 06, 2014 11:32:18 ΠΜ hudson.model.UpdateCenter doSafeRestart
INFO: Scheduling Jenkins reboot
Ιουν 06, 2014 11:33:00 ΠΜ hudson.model.UpdateCenter$DownloadJob run
INFO: Starting the installation of FTP-Publisher Plugin on behalf of anonymous
Ιουν 06, 2014 11:33:15 ΠΜ hudson.model.UpdateCenter doRestart
INFO: Scheduling the core downgrade
Ιουν 06, 2014 11:33:25 ΠΜ hudson.model.UpdateCenter$UpdateCenterConfiguration download
INFO: Downloading FTP-Publisher Plugin
Ιουν 06, 2014 11:33:26 ΠΜ hudson.model.UpdateCenter$HudsonDowngradeJob run
INFO: Starting the downgrade of jenkins.war on behalf of anonymous
Ιουν 06, 2014 11:33:26 ΠΜ jenkins.model.Jenkins$24 run
INFO: Restart in 10 seconds
Ιουν 06, 2014 11:33:26 ΠΜ hudson.model.UpdateCenter$HudsonDowngradeJob run
INFO: Downgrading successful: jenkins.war
Ιουν 06, 2014 11:33:36 ΠΜ jenkins.model.Jenkins$24 run
SEVERE: Restarting VM as requested by anonymous
Error: Unable to access jarfile D:\Program Files (x86)\Jenkins\jenkins.war
Error: Unable to access jarfile D:\Program Files (x86)\Jenkins\jenkins.war
Error: Unable to access jarfile D:\Program Files (x86)\Jenkins\jenkins.war
</code>```

Can anyone help? We are at release point, and I have nowhere to run my tests..

答:
If you have installed jenkins with msi (jenkins.msi), run the repair. That is run the file jenkins.msi again and choose to repair.

After the repair completes successfully it will start the service automatically.

Worked in my case! Had the same problem.

Title: Cannot start Jenkins

Body:
After downloading a plugin, the Jenkins server cannot be accessed. I am using windows 7.
I tried to start windows Jenkins service manually, but I get the following message:

"Windows could not start the Jenkins service on Local COmputer. Error
  1067: The process terminated unexpectedly"

I also tried to run the jenkins.exe from the installation directory, but with no success.
In the error logs I see the following:

INFO: Obtained the updated data file for hudson.tasks.Maven.MavenInstaller
Ιουν 06, 2014 11:31:46 ΠΜ hudson.model.DownloadService$Downloadable doPostBack
INFO: Obtained the updated data file for hudson.tools.JDKInstaller
Ιουν 06, 2014 11:32:18 ΠΜ hudson.model.UpdateCenter doSafeRestart
INFO: Scheduling Jenkins reboot
Ιουν 06, 2014 11:33:00 ΠΜ hudson.model.UpdateCenter$DownloadJob run
INFO: Starting the installation of FTP-Publisher Plugin on behalf of anonymous
Ιουν 06, 2014 11:33:15 ΠΜ hudson.model.UpdateCenter doRestart
INFO: Scheduling the core downgrade
Ιουν 06, 2014 11:33:25 ΠΜ hudson.model.UpdateCenter$UpdateCenterConfiguration download
INFO: Downloading FTP-Publisher Plugin
Ιουν 06, 2014 11:33:26 ΠΜ hudson.model.UpdateCenter$HudsonDowngradeJob run
INFO: Starting the downgrade of jenkins.war on behalf of anonymous
Ιουν 06, 2014 11:33:26 ΠΜ jenkins.model.Jenkins$24 run
INFO: Restart in 10 seconds
Ιουν 06, 2014 11:33:26 ΠΜ hudson.model.UpdateCenter$HudsonDowngradeJob run
INFO: Downgrading successful: jenkins.war
Ιουν 06, 2014 11:33:36 ΠΜ jenkins.model.Jenkins$24 run
SEVERE: Restarting VM as requested by anonymous
Error: Unable to access jarfile D:\Program Files (x86)\Jenkins\jenkins.war
Error: Unable to access jarfile D:\Program Files (x86)\Jenkins\jenkins.war
Error: Unable to access jarfile D:\Program Files (x86)\Jenkins\jenkins.war

Can anyone help? We are at release point, and I have nowhere to run my tests..


来源: stackexchange

问:
Trim string fetched from a Google Spreadsheet range and return the largest value
I am building a small script and, on it, I need to "read" the largest value in a range of cells. The cells look like this: "a-10", "a-3", "a-4" and so on, but their real values are 10, 3 and 4 respectively. I cannot remove the "a-" from the cells.

What I have so far is this:

Code:

function getLargestValue() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheets=['Sheet1','Sheet2','Sheet3'];
  var values=[];
  for(var i=0;i<sheets.length;i++)
  {
    var sht=ss.getSheetByName(sheets[i]);
    var rng=sht.getDataRange();
    var rngA=rng.getValues();
    for(var j=1;j<rngA.length;j++)
    {
      rngA[j][0] = substring(2, rngA[j][0]);
      values.push(rngA[j][0]);
    }
  }
  values.sort(function(a, b) {return a - b;});
  var max = values[values.length-1];
  SpreadsheetApp.getUi().alert('The max is ' + max); //Just checking to be sure it works
  return max;
  // must show the largest value on "Max" sheet
}```

Link to spreadsheet:

https://docs.google.com/spreadsheets/d/16WrsztYlOV7qDOMBqGYU8az26Bw9NoqdQ4Imk_hZM90/edit?usp=sharing

I still need to trim the strings and insert the largest value in a different sheet. How could I do that?

Thank you.

答:
```<code>function getLargestValue()
{
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheets=['Sheet1','Sheet2','Sheet3'];
  var values=[];
  for(var i=0;i<sheets.length;i++)
  {
    var sht=ss.getSheetByName(sheets[i]);
    var rng=sht.getDataRange();
    var rngA=rng.getValues();//this will give you a 2D array
    for (var items in rngA) //foreach loop, easier than for loop
    {
      var result = rngA[items][0].substring(2);//split string at 2nd character
      if(!isNaN(parseFloat(result)) && isFinite(result))// check whether it is a number (since cell has strings like "Values")
      {
        values.push(result);//adds all numbers to the array
      }
    }
  }

  values.sort(function(a, b) {return a - b;});
  var max = values[values.length-1];
  //SpreadsheetApp.getUi().alert('The max is ' + max); //Just checking to be sure it works
  //return max;
  // must show the largest value on "Max" sheet
  ss.getSheetByName('MAX').getRange("A2").setValue(max)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am building a small script and, on it, I need to "read" the largest value in a range of cells. The cells look like this: "a-10", "a-3", "a-4" and so on, but their real values are 10, 3 and 4 respectively. I cannot remove the "a-" from the cells.

What I have so far is this:

Code:

function getLargestValue() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheets=['Sheet1','Sheet2','Sheet3'];
  var values=[];
  for(var i=0;i<sheets.length;i++)
  {
    var sht=ss.getSheetByName(sheets[i]);
    var rng=sht.getDataRange();
    var rngA=rng.getValues();
    for(var j=1;j<rngA.length;j++)
    {
      rngA[j][0] = substring(2, rngA[j][0]);
      values.push(rngA[j][0]);
    }
  }
  values.sort(function(a, b) {return a - b;});
  var max = values[values.length-1];
  SpreadsheetApp.getUi().alert('The max is ' + max); //Just checking to be sure it works
  return max;
  // must show the largest value on "Max" sheet
}

Link to spreadsheet:

https://docs.google.com/spreadsheets/d/16WrsztYlOV7qDOMBqGYU8az26Bw9NoqdQ4Imk_hZM90/edit?usp=sharing

I still need to trim the strings and insert the largest value in a different sheet. How could I do that?

Thank you.


问:
how to receive multiple same name checkbox value and insert into db in laravel 5.2
I need to receive multiple same name checkbox value and insert into db in laravel 5.2.

My Table row : tagname, postid

Advance Thanks .

答:
Follow this example :

```<code><form action="{{url('submitdata')}}" method="post">
{!!csrf_field()!!}
<lavel  for="subject1">Bangla</label>
 <input id="subject1" name="subject[]"  type="checkbox" value="Bangla"/>
<lavel  for="subject1">English</label>
<input id="subject1" name="subject[]"  type="checkbox" value="English"/>
</form>
</code>```

In Controller:

```<code><public function insert(Request $r){

foreach($r->get('subject') AS $k=>$v){

 DB::table('subject')->insert([

'subject'=>$r->get('subject')[$k]

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

Body:
Follow this example :

<form action="{{url('submitdata')}}" method="post">
{!!csrf_field()!!}
<lavel  for="subject1">Bangla</label>
 <input id="subject1" name="subject[]"  type="checkbox" value="Bangla"/>
<lavel  for="subject1">English</label>
<input id="subject1" name="subject[]"  type="checkbox" value="English"/>
</form>

In Controller:

<public function insert(Request $r){

foreach($r->get('subject') AS $k=>$v){

 DB::table('subject')->insert([

'subject'=>$r->get('subject')[$k]

 ]);
}
}


问:
Passing an additional parameter with an onChange event
What I'm trying to do:

I am trying to pass a string from a child component to the handleChange function of a parent component.

What currently works:

I have a parent React JS class with the following method:

```<code>handleChange(event) {

    console.log(event.target.value);
}
</code>```

In the render function I have the following:

```<code><Child handleChange={this.handleChange.bind(this)} />
</code>```

In the Child class I have:

```<code><fieldset onChange={this.props.handleChange}>
    <div>Tag 1: <input id="tag1" value={tags[0]} /></div>
    <div>Tag 2: <input id="tag2" value={tags[1]} /></div>
    <div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>
</code>```

This works fine.

What I am trying to do instead:

I am attempting to add a section parameter to the handleChange function as follows:

```<code>handleChange(section, event) {
    console.log(section);
    console.log(event.target.value);
}
</code>```

And in the Child class I have:

```<code><fieldset onChange={this.props.handleChange("tags")}>
    <div>Tag 1: <input id="tag1" value={tags[0]} /></div>
    <div>Tag 2: <input id="tag2" value={tags[1]} /></div>
    <div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>
</code>```

I now get the error:

```<code>Uncaught TypeError: Cannot read property 'target' of undefined
</code>```

This error is being thrown in my second console.log statement.

What am I doing wrong?

Also, I am considering making the section parameter optional. If so, is there an easy way to do this? It seems like it might not be possible if the event parameter needs to be last.

答:
When you are writing this:

```<code><fieldset onChange={this.props.handleChange("tags")}>
</code>```

handleChange will be called immediately as soon as render is triggered.

Instead, do it like this:

```<code><fieldset onChange={(e) => this.props.handleChange("tags", e)}>
</code>```

Now the handleChange will be called when onChange handler is called.

Body:
What I'm trying to do:

I am trying to pass a string from a child component to the handleChange function of a parent component.

What currently works:

I have a parent React JS class with the following method:

handleChange(event) {

    console.log(event.target.value);
}

In the render function I have the following:

<Child handleChange={this.handleChange.bind(this)} />

In the Child class I have:

<fieldset onChange={this.props.handleChange}>

Tag 1: <input id="tag1" value={tags[0]} />

Tag 2: <input id="tag2" value={tags[1]} />

Tag 3: <input id="tag3" value={tags[2]} />

</fieldset>

This works fine.

What I am trying to do instead:

I am attempting to add a section parameter to the handleChange function as follows:

handleChange(section, event) {
    console.log(section);
    console.log(event.target.value);
}

And in the Child class I have:

<fieldset onChange={this.props.handleChange("tags")}>

Tag 1: <input id="tag1" value={tags[0]} />

Tag 2: <input id="tag2" value={tags[1]} />

Tag 3: <input id="tag3" value={tags[2]} />

</fieldset>

I now get the error:

Uncaught TypeError: Cannot read property 'target' of undefined

This error is being thrown in my second console.log statement.

What am I doing wrong?

Also, I am considering making the section parameter optional. If so, is there an easy way to do this? It seems like it might not be possible if the event parameter needs to be last.

Body:
When you are writing this:

<fieldset onChange={this.props.handleChange("tags")}>

handleChange will be called immediately as soon as render is triggered.

Instead, do it like this:

<fieldset onChange={(e) => this.props.handleChange("tags", e)}>

Now the handleChange will be called when onChange handler is called.


问:
Slice an array based on matching conditions with $lookup
I'm discovering Mongodb and its queries with pipelines and I'm struggling on a case.

I'm looking for each pathsList document where I can find a path from a position B to a position C

Inputs: 10 and 12

Output: [pathsList] (I expect only 1 result in this example, but more likely an array later on)

Let's say I have the 2 following pathsList documents from pathsListsCollection, they have an array of path documents

```<code>-------------
pathsList = {
    _id: ObjectId(...),
    pathIds: [path1Id, path2Id, path3Id]
}
-------------
path1 = {
    _id: ObjectId(...),
    positionStart: 8,
    positionFinal: 10,
    index:0
}
-------------
path2 = {
    _id: ObjectId(...),
    positionStart: 10,
    positionFinal: 12,
    index:1
}
-------------
path3 = {
    _id: ObjectId(...),
    positionStart: 12,
    positionFinal: 14,
    index:2
}
-------------

-------------
pathsList = {
    _id: ObjectId(...),
    pathIds: [path4Id, path5Id, path6Id]
}
-------------
path4 = {
    _id: ObjectId(...),
    positionStart: 14,
    positionFinal: 12,
    index:0
}
-------------
path5 = {
    _id: ObjectId(...),
    positionStart: 12,
    positionFinal: 10,
    index:1
}
-------------
path6 = {
    _id: ObjectId(...),
    positionStart: 10,
    positionFinal: 8,
    index:2
}
-------------
</code>```

So far I've done something like this:

```<code>pathsListCollection.aggregate([
    {
    $lookup:{
        from: "pathsCollection",
        localField: "pathIds",
        foreignField: "_id",
        as: paths
        }
    },
    {
        $match:{
            paths.positionStart : 10 // first input value
        }
    },
    {
        $match:{
            paths.positionFinal : 12  // second input value
        }
    },
])
</code>```

Doing this I get the 2 pathsList docs.

Now, how can I change this aggregate to find only the one having a positionStart = 10 and positionFinal = 12 in that specific order
How can try to validate the second expression only if the first one already has been validate?

I've looked into $slice trying to slice the paths array after the first $match, and continue the query with the rest of it, but couldn't find any revelent syntax to do it.

ie: working with the first pathsList, I reach the first $match with a paths array like that :

```<code>[{
    _id: ObjectId(...),
    positionStart: 8,
    positionFinal: 10,
    index:0
},
{
    _id: ObjectId(...),
    positionStart: 10,     // first $match here
    positionFinal: 12,
    index:1
},
{
    _id: ObjectId(...),
    positionStart: 12,
    positionFinal: 14,
    index:2
}]
</code>```

and I want to do the next $match on an array like that :

```<code>[{
    _id: ObjectId(...),
    positionStart: 10,
    positionFinal: 12,    // second $match has to start from this elem of the array
    index:1
},
{
    _id: ObjectId(...),
    positionStart: 12,
    positionFinal: 14,
    index:2
}]
</code>```

Is it possible to do that?
would it be easier to query pathsCollection rather than pathsListsCollection in first place?

However, I'm open to any different approach or thoughs which could help me to solve that problem
Thanks in advance

答:
If I'm getting this then you want to "slice" based on a given matching positionStart and and positionFinish here.

Optimal Case

It would in fact be better for performance if you indeed start the query on the "pathsCollection" instead, because that is where you are actually going to match the items. So the $match there should be done "first" and using an $or expression to "slice" across the range:

Then with the $lookup you would then only return the "pathsListCollection" items, formatted with the "sliced" array:

On a minimal sample of your data, going from "start" 10 to "finish" 12 would be:

```<code>db.getCollection('pathsCollection').aggregate([
  { "$match": {
    "positionStart": { "$gte": 10, "$lte": 12 },
    "positionFinal": { "$gte": 10, "$lte": 12 }
  }},
  { "$lookup": {
    "from": "pathsListCollection",
    "localField": "_id",
    "foreignField": "pathIds",
    "as": "pathsList"
  }},
  { "$unwind": "$pathsList" },
  { "$addFields": {
    "pathsList.pathIds": {
      "$filter": {
        "input": "$pathsList.pathIds",
        "as": "p",
        "cond": { "$eq": [ "$_id", "$$p" ] }
      }
    }
  }},
  { "$unwind": "$pathsList.pathIds" },
  { "$group": {
    "_id": "$pathsList._id",
    "pathIds": {
      "$push": {
        "_id": "$_id",
        "positionStart": "$positionStart",
        "positionFinal": "$positionFinal",
        "index": "$index"
      }
    }
  }},
  { "$redact": {
    "$cond": {
      "if": {
        "$and": [
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionStart",
              0
            ]},
            10
          ]},
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionFinal",
              -1
            ]},
            12
          ]}
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])
</code>```

Would produce:

```<code>/* 1 */
{
    "_id" : ObjectId("595db5d8f5f11516540d1185"),
    "pathIds" : [
        {
            "_id" : ObjectId("595db4c7f5f11516540d1183"),
            "positionStart" : 10.0,
            "positionFinal" : 12.0,
            "index" : 1.0
        }
    ]
}
</code>```

And with reducing the "range" to "start" 10 and "finish" 14, that would be :

```<code>db.getCollection('pathsCollection').aggregate([
  { "$match": {
    "positionStart": { "$gte": 10, "$lte": 14 },
    "positionFinal": { "$gte": 10, "$lte": 14 }
  }},
  { "$lookup": {
    "from": "pathsListCollection",
    "localField": "_id",
    "foreignField": "pathIds",
    "as": "pathsList"
  }},
  { "$unwind": "$pathsList" },
  { "$addFields": {
    "pathsList.pathIds": {
      "$filter": {
        "input": "$pathsList.pathIds",
        "as": "p",
        "cond": { "$eq": [ "$_id", "$$p" ] }
      }
    }
  }},
  { "$unwind": "$pathsList.pathIds" },
  { "$group": {
    "_id": "$pathsList._id",
    "pathIds": {
      "$push": {
        "_id": "$_id",
        "positionStart": "$positionStart",
        "positionFinal": "$positionFinal",
        "index": "$index"
      }
    }
  }},
  { "$redact": {
    "$cond": {
      "if": {
        "$and": [
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionStart",
              0
            ]},
            10
          ]},
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionFinal",
              -1
            ]},
            14
          ]}
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])
</code>```

Producing:

```<code>/* 1 */
{
    "_id" : ObjectId("595db5d8f5f11516540d1185"),
    "pathIds" : [
        {
            "_id" : ObjectId("595db4c7f5f11516540d1183"),
            "positionStart" : 10.0,
            "positionFinal" : 12.0,
            "index" : 1.0
        },
        {
            "_id" : ObjectId("595db4c7f5f11516540d1184"),
            "positionStart" : 12.0,
            "positionFinal" : 14.0,
            "index" : 2.0
        }
    ]
}
</code>```

Reverse Case

It might look a bit shorter in syntax, but it's probably not the best performing option given that you cannot "query" the "pathsCollection" in the reverse case until the $lookup is actually performed:

```<code>db.pathsListCollection.aggregate([
  { "$lookup": {
    "from": "pathsCollection",
    "localField": "pathIds",
    "foreignField": "_id",
    "as": "pathIds"
  }},
  { "$unwind": "$pathIds" },
  { "$match": {
    "pathIds.positionStart": { "$gte": 10, "$lte": 14 },
    "pathIds.positionFinal": { "$gte": 10, "$lte": 14 }
  }},
  { "$group": {
    "_id": "$_id",
    "pathIds": { "$push": "$pathIds" }
  }},
  { "$redact": {
    "$cond": {
      "if": {
        "$and": [
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionStart",
              0
            ]},
            10
          ]},
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionFinal",
              -1
            ]},
            14
          ]}
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])
</code>```

That is the most optimal form of the "reverse case" given on how MongoDB actually issues the $lookup when applied to the server, which can be seen in the "explain" output:

```<code>    {
        "$lookup" : {
            "from" : "pathsCollection",
            "as" : "pathIds",
            "localField" : "pathIds",
            "foreignField" : "_id",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "$and" : [
                    {
                        "positionStart" : {
                            "$gte" : 10.0
                        }
                    },
                    {
                        "positionStart" : {
                            "$lte" : 14.0
                        }
                    },
                    {
                        "positionFinal" : {
                            "$gte" : 10.0
                        }
                    },
                    {
                        "positionFinal" : {
                            "$lte" : 14.0
                        }
                    }
                ]
            }
        }
    },
    {
        "$group" : {
</code>```

Showing there that the $unwind and $match have "magically" disappeared. They now of course have been "rolled-up" into the $lookup so that when the related data is queried, you actually get only those results that matched the given condition.

The "non-optimal" approach would be to $filter instead. But in fact ALL results from the related collection are returned, and then only removed once the "full" array was already present:

```<code>db.pathsListCollection.aggregate([
  { "$lookup": {
    "from": "pathsCollection",
    "localField": "pathIds",
    "foreignField": "_id",
    "as": "pathIds"
  }},
  { "$addFields": {
    "pathIds": {
      "$filter": {
        "input": "$pathIds",
        "as": "p",
        "cond": {
          "$and": [
            { "$gte": [ "$$p.positionStart", 10 ] },
            { "$lte": [ "$$p.positionStart", 14 ] },
            { "$gte": [ "$$p.positionFinal", 10 ] },
            { "$lte": [ "$$p.positionFinal", 14 ] },
          ]
        }
      }
    }
  }},
  { "$match": {
    "pathIds": {
      "$elemMatch": {
        "positionStart": { "$gte": 10, "$lte": 14 },
        "positionFinal": { "$gte": 10, "$lte": 14 }
      }
    }
  }},
  { "$redact": {
    "$cond": {
      "if": {
        "$and": [
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionStart",
              0
            ]},
            10
          ]},
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionFinal",
              -1
            ]},
            14
          ]}
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])
</code>```

Also noting that you still need to $match or $redact given that the resulting array entries still meet the conditions in this case, and that the array was not in fact "empty" as a result of the $filter.

Samples used

pathsCollection

```<code>/* 1 */
{
    "_id" : ObjectId("595db4c7f5f11516540d1182"),
    "positionStart" : 8.0,
    "positionFinal" : 10.0,
    "index" : 0.0
}

/* 2 */
{
    "_id" : ObjectId("595db4c7f5f11516540d1183"),
    "positionStart" : 10.0,
    "positionFinal" : 12.0,
    "index" : 1.0
}

/* 3 */
{
    "_id" : ObjectId("595db4c7f5f11516540d1184"),
    "positionStart" : 12.0,
    "positionFinal" : 14.0,
    "index" : 2.0
}

/* 4 */
{
    "_id" : ObjectId("595db616f5f11516540d1186"),
    "positionStart" : 14.0,
    "positionFinal" : 12.0,
    "index" : 0.0
}

/* 5 */
{
    "_id" : ObjectId("595db616f5f11516540d1187"),
    "positionStart" : 12.0,
    "positionFinal" : 10.0,
    "index" : 1.0
}

/* 6 */
{
    "_id" : ObjectId("595db616f5f11516540d1188"),
    "positionStart" : 10.0,
    "positionFinal" : 8.0,
    "index" : 2.0
}
</code>```

pathsListCollection

```<code>/* 1 */
{
    "_id" : ObjectId("595db5d8f5f11516540d1185"),
    "pathIds" : [
        ObjectId("595db4c7f5f11516540d1182"),
        ObjectId("595db4c7f5f11516540d1183"),
        ObjectId("595db4c7f5f11516540d1184")
    ]
}

/* 2 */
{
    "_id" : ObjectId("595db62df5f11516540d1189"),
    "pathIds" : [
        ObjectId("595db616f5f11516540d1186"),
        ObjectId("595db616f5f11516540d1187"),
        ObjectId("595db616f5f11516540d1188")
    ]
}
</code>```

Body:
I'm discovering Mongodb and its queries with pipelines and I'm struggling on a case.

I'm looking for each pathsList document where I can find a path from a position B to a position C

Inputs: 10 and 12

Output: [pathsList] (I expect only 1 result in this example, but more likely an array later on)

Let's say I have the 2 following pathsList documents from pathsListsCollection, they have an array of path documents

-------------
pathsList = {
    _id: ObjectId(...),
    pathIds: [path1Id, path2Id, path3Id]
}
-------------
path1 = {
    _id: ObjectId(...),
    positionStart: 8,
    positionFinal: 10,
    index:0
}
-------------
path2 = {
    _id: ObjectId(...),
    positionStart: 10,
    positionFinal: 12,
    index:1
}
-------------
path3 = {
    _id: ObjectId(...),
    positionStart: 12,
    positionFinal: 14,
    index:2
}
-------------

-------------
pathsList = {
    _id: ObjectId(...),
    pathIds: [path4Id, path5Id, path6Id]
}
-------------
path4 = {
    _id: ObjectId(...),
    positionStart: 14,
    positionFinal: 12,
    index:0
}
-------------
path5 = {
    _id: ObjectId(...),
    positionStart: 12,
    positionFinal: 10,
    index:1
}
-------------
path6 = {
    _id: ObjectId(...),
    positionStart: 10,
    positionFinal: 8,
    index:2
}
-------------

So far I've done something like this:

pathsListCollection.aggregate([
    {
    $lookup:{
        from: "pathsCollection",
        localField: "pathIds",
        foreignField: "_id",
        as: paths
        }
    },
    {
        $match:{
            paths.positionStart : 10 // first input value
        }
    },
    {
        $match:{
            paths.positionFinal : 12  // second input value
        }
    },
])

Doing this I get the 2 pathsList docs.

Now, how can I change this aggregate to find only the one having a positionStart = 10 and positionFinal = 12 in that specific order
How can try to validate the second expression only if the first one already has been validate?

I've looked into $slice trying to slice the paths array after the first $match, and continue the query with the rest of it, but couldn't find any revelent syntax to do it.

ie: working with the first pathsList, I reach the first $match with a paths array like that :

[{
    _id: ObjectId(...),
    positionStart: 8,
    positionFinal: 10,
    index:0
},
{
    _id: ObjectId(...),
    positionStart: 10,     // first $match here
    positionFinal: 12,
    index:1
},
{
    _id: ObjectId(...),
    positionStart: 12,
    positionFinal: 14,
    index:2
}]

and I want to do the next $match on an array like that :

[{
    _id: ObjectId(...),
    positionStart: 10,
    positionFinal: 12,    // second $match has to start from this elem of the array
    index:1
},
{
    _id: ObjectId(...),
    positionStart: 12,
    positionFinal: 14,
    index:2
}]

Is it possible to do that?
would it be easier to query pathsCollection rather than pathsListsCollection in first place?

However, I'm open to any different approach or thoughs which could help me to solve that problem
Thanks in advance

Body:
If I'm getting this then you want to "slice" based on a given matching positionStart and and positionFinish here.

Optimal Case

It would in fact be better for performance if you indeed start the query on the "pathsCollection" instead, because that is where you are actually going to match the items. So the $match there should be done "first" and using an $or expression to "slice" across the range:

Then with the $lookup you would then only return the "pathsListCollection" items, formatted with the "sliced" array:

On a minimal sample of your data, going from "start" 10 to "finish" 12 would be:

db.getCollection('pathsCollection').aggregate([
  { "$match": {
    "positionStart": { "$gte": 10, "$lte": 12 },
    "positionFinal": { "$gte": 10, "$lte": 12 }
  }},
  { "$lookup": {
    "from": "pathsListCollection",
    "localField": "_id",
    "foreignField": "pathIds",
    "as": "pathsList"
  }},
  { "$unwind": "$pathsList" },
  { "$addFields": {
    "pathsList.pathIds": {
      "$filter": {
        "input": "$pathsList.pathIds",
        "as": "p",
        "cond": { "$eq": [ "$_id", "$$p" ] }
      }
    }
  }},
  { "$unwind": "$pathsList.pathIds" },
  { "$group": {
    "_id": "$pathsList._id",
    "pathIds": {
      "$push": {
        "_id": "$_id",
        "positionStart": "$positionStart",
        "positionFinal": "$positionFinal",
        "index": "$index"
      }
    }
  }},
  { "$redact": {
    "$cond": {
      "if": {
        "$and": [
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionStart",
              0
            ]},
            10
          ]},
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionFinal",
              -1
            ]},
            12
          ]}
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

Would produce:

/* 1 */
{
    "_id" : ObjectId("595db5d8f5f11516540d1185"),
    "pathIds" : [
        {
            "_id" : ObjectId("595db4c7f5f11516540d1183"),
            "positionStart" : 10.0,
            "positionFinal" : 12.0,
            "index" : 1.0
        }
    ]
}

And with reducing the "range" to "start" 10 and "finish" 14, that would be :

db.getCollection('pathsCollection').aggregate([
  { "$match": {
    "positionStart": { "$gte": 10, "$lte": 14 },
    "positionFinal": { "$gte": 10, "$lte": 14 }
  }},
  { "$lookup": {
    "from": "pathsListCollection",
    "localField": "_id",
    "foreignField": "pathIds",
    "as": "pathsList"
  }},
  { "$unwind": "$pathsList" },
  { "$addFields": {
    "pathsList.pathIds": {
      "$filter": {
        "input": "$pathsList.pathIds",
        "as": "p",
        "cond": { "$eq": [ "$_id", "$$p" ] }
      }
    }
  }},
  { "$unwind": "$pathsList.pathIds" },
  { "$group": {
    "_id": "$pathsList._id",
    "pathIds": {
      "$push": {
        "_id": "$_id",
        "positionStart": "$positionStart",
        "positionFinal": "$positionFinal",
        "index": "$index"
      }
    }
  }},
  { "$redact": {
    "$cond": {
      "if": {
        "$and": [
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionStart",
              0
            ]},
            10
          ]},
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionFinal",
              -1
            ]},
            14
          ]}
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

Producing:

/* 1 */
{
    "_id" : ObjectId("595db5d8f5f11516540d1185"),
    "pathIds" : [
        {
            "_id" : ObjectId("595db4c7f5f11516540d1183"),
            "positionStart" : 10.0,
            "positionFinal" : 12.0,
            "index" : 1.0
        },
        {
            "_id" : ObjectId("595db4c7f5f11516540d1184"),
            "positionStart" : 12.0,
            "positionFinal" : 14.0,
            "index" : 2.0
        }
    ]
}

Reverse Case

It might look a bit shorter in syntax, but it's probably not the best performing option given that you cannot "query" the "pathsCollection" in the reverse case until the $lookup is actually performed:

db.pathsListCollection.aggregate([
  { "$lookup": {
    "from": "pathsCollection",
    "localField": "pathIds",
    "foreignField": "_id",
    "as": "pathIds"
  }},
  { "$unwind": "$pathIds" },
  { "$match": {
    "pathIds.positionStart": { "$gte": 10, "$lte": 14 },
    "pathIds.positionFinal": { "$gte": 10, "$lte": 14 }
  }},
  { "$group": {
    "_id": "$_id",
    "pathIds": { "$push": "$pathIds" }
  }},
  { "$redact": {
    "$cond": {
      "if": {
        "$and": [
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionStart",
              0
            ]},
            10
          ]},
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionFinal",
              -1
            ]},
            14
          ]}
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

That is the most optimal form of the "reverse case" given on how MongoDB actually issues the $lookup when applied to the server, which can be seen in the "explain" output:

    {
        "$lookup" : {
            "from" : "pathsCollection",
            "as" : "pathIds",
            "localField" : "pathIds",
            "foreignField" : "_id",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "$and" : [
                    {
                        "positionStart" : {
                            "$gte" : 10.0
                        }
                    },
                    {
                        "positionStart" : {
                            "$lte" : 14.0
                        }
                    },
                    {
                        "positionFinal" : {
                            "$gte" : 10.0
                        }
                    },
                    {
                        "positionFinal" : {
                            "$lte" : 14.0
                        }
                    }
                ]
            }
        }
    },
    {
        "$group" : {

Showing there that the $unwind and $match have "magically" disappeared. They now of course have been "rolled-up" into the $lookup so that when the related data is queried, you actually get only those results that matched the given condition.

The "non-optimal" approach would be to $filter instead. But in fact ALL results from the related collection are returned, and then only removed once the "full" array was already present:

db.pathsListCollection.aggregate([
  { "$lookup": {
    "from": "pathsCollection",
    "localField": "pathIds",
    "foreignField": "_id",
    "as": "pathIds"
  }},
  { "$addFields": {
    "pathIds": {
      "$filter": {
        "input": "$pathIds",
        "as": "p",
        "cond": {
          "$and": [
            { "$gte": [ "$$p.positionStart", 10 ] },
            { "$lte": [ "$$p.positionStart", 14 ] },
            { "$gte": [ "$$p.positionFinal", 10 ] },
            { "$lte": [ "$$p.positionFinal", 14 ] },
          ]
        }
      }
    }
  }},
  { "$match": {
    "pathIds": {
      "$elemMatch": {
        "positionStart": { "$gte": 10, "$lte": 14 },
        "positionFinal": { "$gte": 10, "$lte": 14 }
      }
    }
  }},
  { "$redact": {
    "$cond": {
      "if": {
        "$and": [
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionStart",
              0
            ]},
            10
          ]},
          { "$eq": [
            { "$arrayElemAt": [
              "$pathIds.positionFinal",
              -1
            ]},
            14
          ]}
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

Also noting that you still need to $match or $redact given that the resulting array entries still meet the conditions in this case, and that the array was not in fact "empty" as a result of the $filter.

Samples used

pathsCollection

/* 1 */
{
    "_id" : ObjectId("595db4c7f5f11516540d1182"),
    "positionStart" : 8.0,
    "positionFinal" : 10.0,
    "index" : 0.0
}

/* 2 */
{
    "_id" : ObjectId("595db4c7f5f11516540d1183"),
    "positionStart" : 10.0,
    "positionFinal" : 12.0,
    "index" : 1.0
}

/* 3 */
{
    "_id" : ObjectId("595db4c7f5f11516540d1184"),
    "positionStart" : 12.0,
    "positionFinal" : 14.0,
    "index" : 2.0
}

/* 4 */
{
    "_id" : ObjectId("595db616f5f11516540d1186"),
    "positionStart" : 14.0,
    "positionFinal" : 12.0,
    "index" : 0.0
}

/* 5 */
{
    "_id" : ObjectId("595db616f5f11516540d1187"),
    "positionStart" : 12.0,
    "positionFinal" : 10.0,
    "index" : 1.0
}

/* 6 */
{
    "_id" : ObjectId("595db616f5f11516540d1188"),
    "positionStart" : 10.0,
    "positionFinal" : 8.0,
    "index" : 2.0
}

pathsListCollection

/* 1 */
{
    "_id" : ObjectId("595db5d8f5f11516540d1185"),
    "pathIds" : [
        ObjectId("595db4c7f5f11516540d1182"),
        ObjectId("595db4c7f5f11516540d1183"),
        ObjectId("595db4c7f5f11516540d1184")
    ]
}

/* 2 */
{
    "_id" : ObjectId("595db62df5f11516540d1189"),
    "pathIds" : [
        ObjectId("595db616f5f11516540d1186"),
        ObjectId("595db616f5f11516540d1187"),
        ObjectId("595db616f5f11516540d1188")
    ]
}


答:
You can do this:</p>

```<code><fieldset onChange={(e) => this.props.handleChange("tags", e)}>
    <div>Tag 1: <input id="tag1" value={tags[0]} /></div>
    <div>Tag 2: <input id="tag2" value={tags[1]} /></div>
    <div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>
</code>```

Title: Passing an additional parameter with an onChange event

Body:
You can do this:

<fieldset onChange={(e) => this.props.handleChange("tags", e)}>
    <div>Tag 1: <input id="tag1" value={tags[0]} /></div>
    <div>Tag 2: <input id="tag2" value={tags[1]} /></div>
    <div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>


问:
Difference between now and birthdate in years, months, days, mintues
```<code>import datetime
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
#This returns a timedelta object -> datetime.timedelta(7629, 36148, 156646)
</code>```

Now i want to convert precisely the timedelta object in years, months, days and seconds..
I know i can do like difference.days // 365 to get years and so on..
Is there any other way or methods to convert this timedelta objects in
Year, months, days and minutes precisely and easily?

答:
I think you probably want to use dateutil.relativedelta. Here is a SO post explaining how to use it:

Python timedelta in years

If this isn't what you're looking for then providing some example output in your question might help.

Body:
import datetime
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
#This returns a timedelta object -> datetime.timedelta(7629, 36148, 156646)

Now i want to convert precisely the timedelta object in years, months, days and seconds..
I know i can do like difference.days // 365 to get years and so on..
Is there any other way or methods to convert this timedelta objects in
Year, months, days and minutes precisely and easily?


问:
How to merge two stream using stream?
I have two stream, one contains object of A, one contains object of B, they are in same length. Now I have a class called C, it contains A and B as its fields.

```<code>class C {
    A a;
    B b;
}
</code>```

How can I merge the two stream into one stream using stream operation?

答:
Try this:

```<code>public class ZipTest{

    static A[] arrayA;
    static B[] arrayB;
    public static void main(String[] args) {

        //more convenient to zip arrays. if you start with streams
        //collect to arrays : arrayA = streamA.toArray();

        arrayA = new A[] {new A("a1"), new A("a2"), new A("a3")};
        arrayB = new B[] {new B("b1"), new B("b2"), new B("b3")};

        Stream<Object> zippedA_B = IntStream.range(0, 2* Math.min(arrayA.length, arrayB.length))
        .mapToObj( i ->  getElement(i) );

        System.out.println(Arrays.toString(zippedA_B.toArray()));
    }

    private static Object getElement(int i) {

        return ((i%2) == 0) ? arrayA[i/2] : arrayB[i/2];
    }
}

class A{
    String name;
    A(String name){ this.name = name;}
    @Override
    public String toString() {return name;}
}

class B{
    String name;
    B(String name){ this.name = name;}
    @Override
    public String toString() {return name;}
}
</code>```

Output:

[a1, b1, a2, b2, a3, b3]

Title: How to merge two stream using stream?

Body:
I have two stream, one contains object of A, one contains object of B, they are in same length. Now I have a class called C, it contains A and B as its fields.

class C {
    A a;
    B b;
}

How can I merge the two stream into one stream using stream operation?

Body:
Try this:

public class ZipTest{

    static A[] arrayA;
    static B[] arrayB;
    public static void main(String[] args) {

        //more convenient to zip arrays. if you start with streams
        //collect to arrays : arrayA = streamA.toArray();

        arrayA = new A[] {new A("a1"), new A("a2"), new A("a3")};
        arrayB = new B[] {new B("b1"), new B("b2"), new B("b3")};

        Stream<Object> zippedA_B = IntStream.range(0, 2* Math.min(arrayA.length, arrayB.length))
        .mapToObj( i ->  getElement(i) );

        System.out.println(Arrays.toString(zippedA_B.toArray()));
    }

    private static Object getElement(int i) {

        return ((i%2) == 0) ? arrayA[i/2] : arrayB[i/2];
    }
}

class A{
    String name;
    A(String name){ this.name = name;}
    @Override
    public String toString() {return name;}
}

class B{
    String name;
    B(String name){ this.name = name;}
    @Override
    public String toString() {return name;}
}

Output:

[a1, b1, a2, b2, a3, b3]


问:
Solr - Reverse deep paging
I want pagination feature in my app where the user can go to next and previous pages.
Paging in Solr using cursorMark gives only the nextCursorMark. How to get the previous cursors? What is the best way to implement it?</p>

答:
In this case you need to remember previous cursor mark, similar question is answered here,

Solr: Use Cursor in pagination to get previous page

Title: Solr - Reverse deep paging


问:
Database design - defining a basic many-to-one relationship
This is a basic database design question. I want a table (or multiple tables) defining relationships between customers. I want it so PrimaryCustomer can be linked to multiple SecondaryCustomers, and can have many SecondaryCustomers with the same relationship.

```<code>PrimaryCustomerID  RelationshipID  SecondaryCustomerID
</code>```

1) If the primary key is {PrimaryCustomerID} then I can only have one linked customer of any kind.

2) If the primary key is {PrimaryCustomerID, RelationshipID}, then I can only have one linked customer for each relationship type.

3) If the primary key is {PrimaryCustomerID, RelationshipID, SecondaryCustomerID}, then I can have whatever I like, but having all columns as the primary key seems completely wrong.

What's the right way to set things up?

答:
If a customer can only be linked to one primary customer then you can use a simple recursive relationship in the customer table itself.

CustomerID as PK

PrimaryCustomerID as FK to CustomerID

ContentLicense: CC BY-SA 2.5

Body:
This is a basic database design question. I want a table (or multiple tables) defining relationships between customers. I want it so PrimaryCustomer can be linked to multiple SecondaryCustomers, and can have many SecondaryCustomers with the same relationship.

PrimaryCustomerID  RelationshipID  SecondaryCustomerID

1) If the primary key is {PrimaryCustomerID} then I can only have one linked customer of any kind.

2) If the primary key is {PrimaryCustomerID, RelationshipID}, then I can only have one linked customer for each relationship type.

3) If the primary key is {PrimaryCustomerID, RelationshipID, SecondaryCustomerID}, then I can have whatever I like, but having all columns as the primary key seems completely wrong.

What's the right way to set things up?


问:
End to end testing of two or more mule applications
I have multiple mule applications forming one big application. Individual components have been tested but when it comes to automate end to end testing we are finding a way for it.

Application 1 takes an input, processes it and send the processed object to application 2 which processes the input and sends to application 3, output of third application is the final result.

I want to validate the integration among the application 1-2 and 2-3 and then 1-3 also, so that we can easily test whenever there are more applications added to the main application.

Can anyone help me out on this, are there any tools which can be used to test this inside or outside anypoint studio?

Thanks in advance.

答: You can use Soap UI for your integration and functional testing. You can test for both SOAP,REST and JMS endpoints.</p>


问:
Implement hashid in django
I've been trying to implement hashids in django models. I want to acquire hashid based on model's id like when model's id=3 then hash encoding should be like this: hashid.encode(id). The thing is i can not get id or pk until i save them. What i have in my mind is get the latest objects id and add 1 on them. But it's not a solution for me. Can anyone help me to figure it out???

django model is:

```<code>from hashids import Hashids
hashids = Hashids(salt='thismysalt', min_length=4)

class Article(models.Model):
    title = models.CharField(...)
    text = models.TextField(...)
    hashid = models.CharField(...)

    # i know that this is not a good solution. This is meant to be more clear understanding.
    def save(self, *args, **kwargs):
        super(Article, self).save(*args, **kwargs)
        self.hashid = hashids.encode(self.id)
        super(Article, self).save(*args, **kwargs)
</code>```

答:
I think hashids always return the same value for a specific id. So you can just calculate it before displaying it (using template tags).

But if you still want to save it, one way is to save the hashid field in the views like this:

```<code>instance = Article()
instance.title = 'whatever...'
instance.text = 'whatever...'
instance.save()

hashids = Hashids()
instance.hashid = hashids.encode(instance.id)
instance.save()
</code>```

(I don't know if it's the best approach, but it worked for me!)

Title: Implement hashid in django

Body:
I've been trying to implement hashids in django models. I want to acquire hashid based on model's id like when model's id=3 then hash encoding should be like this: hashid.encode(id). The thing is i can not get id or pk until i save them. What i have in my mind is get the latest objects id and add 1 on them. But it's not a solution for me. Can anyone help me to figure it out???

django model is:

from hashids import Hashids
hashids = Hashids(salt='thismysalt', min_length=4)

class Article(models.Model):
    title = models.CharField(...)
    text = models.TextField(...)
    hashid = models.CharField(...)

    # i know that this is not a good solution. This is meant to be more clear understanding.
    def save(self, *args, **kwargs):
        super(Article, self).save(*args, **kwargs)
        self.hashid = hashids.encode(self.id)
        super(Article, self).save(*args, **kwargs)

Body:
I think hashids always return the same value for a specific id. So you can just calculate it before displaying it (using template tags).

But if you still want to save it, one way is to save the hashid field in the views like this:

instance = Article()
instance.title = 'whatever...'
instance.text = 'whatever...'
instance.save()

hashids = Hashids()
instance.hashid = hashids.encode(instance.id)
instance.save()

(I don't know if it's the best approach, but it worked for me!)


问:
How to configure Nginx with Passenger to process 500 requests/sec
I am hosting ruby application but it gives errors (some kind of error 500) while processing more than 400 requests per second. Test (loader.io) with lower amount of requests (below 400 request) finishes with good results.
I think I could have better results while processing 500 requests/second and more.

The app is using t2.2xlarge ec2 instance (with 32Gb of memory, 8 virtual cores). I guess it might give better performance. The machine is running on Ubuntu 14.04, Rails 4.0.12, Nginx with Passenger.

I tried to make some changes in Nginx configuration but without any big progress.
My current configuration:

```<code>passenger_max_pool_size 60;
#passenger_pool_idle_time 20;
server {
  listen 80;
  return 301 https://mydomain.eu$request_uri;
}

server {
  listen 443;
  server_name ~^(\w+)\.mydomain.eu$;
  return 301 https://mydomain.eu$request_uri;
}
server {
  listen 443 ssl spdy default;
  server_name mydomain.eu;
  passenger_enabled on;
  #passenger_max_pool_size 12;
  passenger_max_request_queue_size 2000;
  gzip on;

  root /home/ubuntu/application/cversion/public;

  ssl                  on;
  ssl_certificate      /home/ubuntu/fvhsdvhfd35/ssl-bundle1.crt;
  ssl_certificate_key  /home/ubuntu/fvhsdvhfd35/prvt.key;
  ssl_session_timeout  5m;
  ssl_protocols        TLSv1 TLSv1.1 TLSv1.2 SSLv3;
  ssl_ciphers          "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";
  ssl_prefer_server_ciphers  on;

  location = /favicon.png {
    expires    max;
    add_header Cache-Control public;
  }

  location = /ZeroClipboard.swf {
    expires    max;
    add_header Cache-Control public;
  }

  location ~ ^/(assets)/  {
    gzip_static on;
    expires     max;
    add_header  Cache-Control public;
  }

  # disable gzip on all omniauth paths to prevent BREACH
  location ~ ^/auth/ {
    gzip off;
    passenger_enabled on;
  }
</code>```

Do you have any idea how to get more than 400 request per second?

here is a log of Nginx with Passenger while processing 500 requests(with passenger_max_pool_size 30; and passenger_max_request_queue_size 1200;)

```<code>2017/07/06 01:58:32 [error] 11749#11749: *56391 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.89.44.6, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11740#11740: *64104 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.87.219.148, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11749#11749: *64251 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.87.219.148, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11749#11749: *63289 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.89.44.6, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *67786 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *35057 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *35166 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11744#11744: *43208 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11744#11744: *69130 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.162.105.71, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
[ 2017-07-06 01:58:34.3865 11703/7fc703fff700 Ser/AcceptLoadBalancer.h:150 ]: Resuming accepting new clients
</code>```

UPDATE

I got a solution.
These changes of Nginx Configuration gave me 1000 request/second performance.

At first I put:

```<code>"65536" in /proc/sys/net/core/somaxconn
"65536" in /proc/sys/net/ipv4/tcp_max_syn_backlog
</code>```

/etc/nginx/conf.d/m.conf:

```<code>    passenger_max_pool_size 90;
    passenger_socket_backlog 16384;

    #in server block
    #was listen 443 ssl spdy default;
    listen 443 ssl spdy default backlog=16384;
    passenger_max_request_queue_size 2300;
    ssl_session_cache shared:SSL:10m;
</code>```

/etc/nginx/nginx.conf:

```<code>worker_rlimit_nofile 131072;

#in events block:
use epoll;
worker_connections 8192;
</code>```

Another question

Average response time is about 6seconds for 1000 requests per second during 1 minute of tests. Any ideas how to improve average response time for this amount of requests?

UPDATE2

I change my Nginx config to enable Nginx Microcashing according to this blog, but I've got no better performance. 500 req/second gave me 5.1sec as average response time. About 900 req/sec - 5.5sec. However without caching I have 2.5sec for 500 requests and 5.6 sec for 900 requests.

/etc/nginx/nginx.conf:

```<code>    ...
    http {
      ...
      proxy_cache_path /tmp/cache keys_zone=one:10m levels=1:2 inactive=600s max_size=100m;
      ...
    }
</code>```

/etc/nginx/conf.d/m.conf:

}

```<code>passenger_max_pool_size 90;
#passenger_pool_idle_time 20;
passenger_socket_backlog 16384;
server {
  listen 80;
  return 301 https://mydomain.eu$request_uri;
}

server {
  listen 443;
  server_name ~^(\w+)\.mydomain.eu$;
  return 301 https://mydomain.eu$request_uri;
}
server {
  listen 443 ssl spdy default backlog=16384;
  server_name mydomain.eu;

  ssl                  on;
  ssl_certificate      /home/ubuntu/fvhsdvhfd35/ssl-bundle1.crt;
  ssl_certificate_key  /home/ubuntu/fvhsdvhfd35/prvt.key;
  ssl_session_timeout  5m;
  ssl_protocols        TLSv1 TLSv1.1 TLSv1.2 SSLv3;
  ssl_ciphers          "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";
  ssl_prefer_server_ciphers  on;

  ssl_session_cache shared:SSL:10m;

  location / {

    proxy_http_version 1.1; # Always upgrade to HTTP/1.1
    proxy_set_header Connection ""; # Enable keepalives
    proxy_set_header Accept-Encoding ""; # Optimize encoding
    proxy_pass http://127.0.0.1:81/;

    proxy_cache one;
    proxy_cache_lock on;
    proxy_cache_valid 200 1s;
    proxy_cache_use_stale updating;
  }
}
server {

  listen 81;
  server_name mydomain.eu;
  passenger_enabled on;

  passenger_max_request_queue_size 2300;
  gzip on;

  root /home/ubuntu/application/cversion/public;

  location = /favicon.png {
    expires    max;
    add_header Cache-Control public;
  }

  location = /ZeroClipboard.swf {
    expires    max;
    add_header Cache-Control public;
  }

  location ~ ^/(assets)/  {
    gzip_static on;
    expires     max;
    add_header  Cache-Control public;
  }

  # disable gzip on all omniauth paths to prevent BREACH
  location ~ ^/auth/ {
    gzip off;
    passenger_enabled on;
  }

}
</code>```

答: Nginx configuration can be reviewed according to official performance tuning recommendation: https://www.nginx.com/blog/tuning-nginx/</p>

Body:
I am hosting ruby application but it gives errors (some kind of error 500) while processing more than 400 requests per second. Test (loader.io) with lower amount of requests (below 400 request) finishes with good results.
I think I could have better results while processing 500 requests/second and more.

The app is using t2.2xlarge ec2 instance (with 32Gb of memory, 8 virtual cores). I guess it might give better performance. The machine is running on Ubuntu 14.04, Rails 4.0.12, Nginx with Passenger.

I tried to make some changes in Nginx configuration but without any big progress.
My current configuration:

passenger_max_pool_size 60;
#passenger_pool_idle_time 20;
server {
  listen 80;
  return 301 https://mydomain.eu$request_uri;
}

server {
  listen 443;
  server_name ~^(\w+)\.mydomain.eu$;
  return 301 https://mydomain.eu$request_uri;
}
server {
  listen 443 ssl spdy default;
  server_name mydomain.eu;
  passenger_enabled on;
  #passenger_max_pool_size 12;
  passenger_max_request_queue_size 2000;
  gzip on;

  root /home/ubuntu/application/cversion/public;

  ssl                  on;
  ssl_certificate      /home/ubuntu/fvhsdvhfd35/ssl-bundle1.crt;
  ssl_certificate_key  /home/ubuntu/fvhsdvhfd35/prvt.key;
  ssl_session_timeout  5m;
  ssl_protocols        TLSv1 TLSv1.1 TLSv1.2 SSLv3;
  ssl_ciphers          "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";
  ssl_prefer_server_ciphers  on;

  location = /favicon.png {
    expires    max;
    add_header Cache-Control public;
  }

  location = /ZeroClipboard.swf {
    expires    max;
    add_header Cache-Control public;
  }

  location ~ ^/(assets)/  {
    gzip_static on;
    expires     max;
    add_header  Cache-Control public;
  }

  # disable gzip on all omniauth paths to prevent BREACH
  location ~ ^/auth/ {
    gzip off;
    passenger_enabled on;
  }

Do you have any idea how to get more than 400 request per second?

here is a log of Nginx with Passenger while processing 500 requests(with passenger_max_pool_size 30; and passenger_max_request_queue_size 1200;)

2017/07/06 01:58:32 [error] 11749#11749: *56391 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.89.44.6, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11740#11740: *64104 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.87.219.148, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11749#11749: *64251 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.87.219.148, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11749#11749: *63289 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.89.44.6, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *67786 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *35057 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11748#11748: *35166 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11744#11744: *43208 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 52.86.198.91, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
2017/07/06 01:58:32 [error] 11744#11744: *69130 connect() to unix:/tmp/passenger.e1PiPXp/agents.s/core failed (11: Resource temporarily unavailable) while connecting to upstream, client: 54.162.105.71, server: mydomain.us, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.e1PiPXp/agents.s/core:", host: "mydomain.us"
[ 2017-07-06 01:58:34.3865 11703/7fc703fff700 Ser/AcceptLoadBalancer.h:150 ]: Resuming accepting new clients

UPDATE

I got a solution.
These changes of Nginx Configuration gave me 1000 request/second performance.

At first I put:

"65536" in /proc/sys/net/core/somaxconn
"65536" in /proc/sys/net/ipv4/tcp_max_syn_backlog

/etc/nginx/conf.d/m.conf:

    passenger_max_pool_size 90;
    passenger_socket_backlog 16384;

    #in server block
    #was listen 443 ssl spdy default;
    listen 443 ssl spdy default backlog=16384;
    passenger_max_request_queue_size 2300;
    ssl_session_cache shared:SSL:10m;

/etc/nginx/nginx.conf:

worker_rlimit_nofile 131072;

#in events block:
use epoll;
worker_connections 8192;

Another question

Average response time is about 6seconds for 1000 requests per second during 1 minute of tests. Any ideas how to improve average response time for this amount of requests?

UPDATE2

I change my Nginx config to enable Nginx Microcashing according to this blog, but I've got no better performance. 500 req/second gave me 5.1sec as average response time. About 900 req/sec - 5.5sec. However without caching I have 2.5sec for 500 requests and 5.6 sec for 900 requests.

/etc/nginx/nginx.conf:

    ...
    http {
      ...
      proxy_cache_path /tmp/cache keys_zone=one:10m levels=1:2 inactive=600s max_size=100m;
      ...
    }

/etc/nginx/conf.d/m.conf:

}

passenger_max_pool_size 90;
#passenger_pool_idle_time 20;
passenger_socket_backlog 16384;
server {
  listen 80;
  return 301 https://mydomain.eu$request_uri;
}

server {
  listen 443;
  server_name ~^(\w+)\.mydomain.eu$;
  return 301 https://mydomain.eu$request_uri;
}
server {
  listen 443 ssl spdy default backlog=16384;
  server_name mydomain.eu;

  ssl                  on;
  ssl_certificate      /home/ubuntu/fvhsdvhfd35/ssl-bundle1.crt;
  ssl_certificate_key  /home/ubuntu/fvhsdvhfd35/prvt.key;
  ssl_session_timeout  5m;
  ssl_protocols        TLSv1 TLSv1.1 TLSv1.2 SSLv3;
  ssl_ciphers          "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";
  ssl_prefer_server_ciphers  on;

  ssl_session_cache shared:SSL:10m;

  location / {

    proxy_http_version 1.1; # Always upgrade to HTTP/1.1
    proxy_set_header Connection ""; # Enable keepalives
    proxy_set_header Accept-Encoding ""; # Optimize encoding
    proxy_pass http://127.0.0.1:81/;

    proxy_cache one;
    proxy_cache_lock on;
    proxy_cache_valid 200 1s;
    proxy_cache_use_stale updating;
  }
}
server {

  listen 81;
  server_name mydomain.eu;
  passenger_enabled on;

  passenger_max_request_queue_size 2300;
  gzip on;

  root /home/ubuntu/application/cversion/public;

  location = /favicon.png {
    expires    max;
    add_header Cache-Control public;
  }

  location = /ZeroClipboard.swf {
    expires    max;
    add_header Cache-Control public;
  }

  location ~ ^/(assets)/  {
    gzip_static on;
    expires     max;
    add_header  Cache-Control public;
  }

  # disable gzip on all omniauth paths to prevent BREACH
  location ~ ^/auth/ {
    gzip off;
    passenger_enabled on;
  }

}


问:
Zero margin between labels in bootstrap modal
I've using bootstrap labels in web page but in normal page its looking good but in modal there is no margin b/w two labels:

$('.task').dblclick(function (e) {
$('#Modal_Task_View').modal({keyboard: true, show: true});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Common styles for all types */
.task {
  padding: 10px 15px;
  margin: 10px 0;
  border: 1px solid #eee;
  border-left-width: 10px;
  border-radius: 3px;
}
.task h4 {
  margin-top: 0;
  margin-bottom: 5px;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Title 2
                                (First Category)

                        Assigned to :

                Gobind Samrow(admindddd)

                Chris Walker(CW)

                Due Date: 26-Jun-2017

                Days Left: 0

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Task 2 Wishlist

                DueNormal
                Due Date : 08-Jul-2017

                         Category : Second Category

                        Description :
                        Description Description Description

                        Assigned To :
                        StandardAsh Wilde(ACW)admin admin(admin)

Linked TasksTitle 4Title 3

Documents

```

答:
You can try this

```<code>#myModal .modal-body span.spn-actionee label {
    margin-right: 10px;
}
</code>```

Hope it will helps you.

Body:
I've using bootstrap labels in web page but in normal page its looking good but in modal there is no margin b/w two labels:

$('.task').dblclick(function (e) {
$('#Modal_Task_View').modal({keyboard: true, show: true});
});

/* Common styles for all types */
.task {
  padding: 10px 15px;
  margin: 10px 0;
  border: 1px solid #eee;
  border-left-width: 10px;
  border-radius: 3px;
}
.task h4 {
  margin-top: 0;
  margin-bottom: 5px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Title 2
                                (First Category)

                        Assigned to :

                Gobind Samrow(admindddd)

                Chris Walker(CW)

                Due Date: 26-Jun-2017

                Days Left: 0

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Task 2 Wishlist

                DueNormal
                Due Date : 08-Jul-2017

                         Category : Second Category

                        Description :
                        Description Description Description

                        Assigned To :
                        StandardAsh Wilde(ACW)admin admin(admin)

Linked TasksTitle 4Title 3

Documents

Body:
You can try this

#myModal .modal-body span.spn-actionee label {
    margin-right: 10px;
}

Hope it will helps you.


问:
Can't get haproxy to load balanace Galera Cluster nodes
I recently installed Galera Cluster on two Red Hat 7 servers and have it configured correctly. However I can't get HAProxy to work. I'm just getting errors.

Node 1 has an IP of 1.1.1.1 and all traffic is open. SELinux has mysql set to permissive.

Node 2 has an IP of 2.2.2.2 and all traffic is open. SELinux has mysql set to permissive.

HAProxy has an IP of 3.3.3.3 and all traffic is open. SELinux has been disabled.

All nodes are on separate servers. The only thing Node 3 has installed on it is HAProxy and mysql client.

So per the Galera documentation, I install HAProxy and add this portion to the bottom of the config file:

```<code># Load Balancing for Galera Cluster
listen galera 3.3.3.3:3306
     balance roundrobin
     mode tcp
     option tcpka
     option mysql-check user haproxy
     server node1 1.1.1.1:3306 check weight 1
     server node2 2.2.2.2:3306 check weight 1
</code>```

But then when I check status of HAProxy I get these errors:

```<code>[root@nodemgr haproxy]# service haproxy restart
Redirecting to /bin/systemctl restart  haproxy.service
[root@nodemgr haproxy]# service haproxy status
Redirecting to /bin/systemctl status  haproxy.service
● haproxy.service - HAProxy Load Balancer
   Loaded: loaded (/usr/lib/systemd/system/haproxy.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Tue 2017-07-04 20:18:50 EDT; 3s ago
  Process: 11773 ExecStart=/usr/sbin/haproxy-systemd-wrapper -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid $OPTIONS (code=exited, status=1/FAILURE)
 Main PID: 11773 (code=exited, status=1/FAILURE)

Jul 04 20:18:50 nodemgr systemd[1]: Started HAProxy Load Balancer.
Jul 04 20:18:50 nodemgr systemd[1]: Starting HAProxy Load Balancer...
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: haproxy-systemd-wrapper: executing /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /ru...pid -Ds
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: [WARNING] 184/201850 (11774) : parsing [/etc/haproxy/haproxy.cfg:45] : 'option httplog'...cplog'.
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: [WARNING] 184/201850 (11774) : config : 'option forwardfor' ignored for proxy 'galera' ...P mode.
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: [ALERT] 184/201850 (11774) : Starting proxy galera: cannot bind socket [3.3.3.3:3306]
Jul 04 20:18:50 nodemgr systemd[1]: haproxy.service: main process exited, code=exited, status=1/FAILURE
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: haproxy-systemd-wrapper: exit, haproxy RC=1
Jul 04 20:18:50 nodemgr systemd[1]: Unit haproxy.service entered failed state.
Jul 04 20:18:50 nodemgr systemd[1]: haproxy.service failed.
Hint: Some lines were ellipsized, use -l to show in full.
</code>```

I'm assuming my problem is here:

```<code> Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: [ALERT] 184/201850 (11774) : Starting proxy galera: cannot bind socket [3.3.3.3:3306]
</code>```

but after disabling SELinux I don't know what else I need to do. Any help is greatly appreciated!

Full haproxy config file is here:

```<code>#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    log         127.0.0.1 local2

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend  main *:5000
    acl url_static       path_beg       -i /static /images /javascript /stylesheets
    acl url_static       path_end       -i .jpg .gif .png .css .js

    use_backend static          if url_static
    default_backend             app

#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
backend static
    balance     roundrobin
    server      static 127.0.0.1:4331 check
#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend app
    balance     roundrobin
    server  app1 127.0.0.1:5001 check
    server  app2 127.0.0.1:5002 check
    server  app3 127.0.0.1:5003 check
    server  app4 127.0.0.1:5004 check

# Load Balancing for Galera Cluster
listen galera 3.3.3.3:3306
     balance roundrobin
     mode tcp
     option tcpka
     option mysql-check user haproxy
     server node1 1.1.1.1:3306 check weight 1
     server node2 2.2.2.2:3306 check weight 1
</code>```

答: vi /etc/sysctl.conf and add ‘net.ipv4.ip_nonlocal_bind=1’ to bottom of file ended up doing what I needed.</p>

Body:
I recently installed Galera Cluster on two Red Hat 7 servers and have it configured correctly. However I can't get HAProxy to work. I'm just getting errors.

Node 1 has an IP of 1.1.1.1 and all traffic is open. SELinux has mysql set to permissive.

Node 2 has an IP of 2.2.2.2 and all traffic is open. SELinux has mysql set to permissive.

HAProxy has an IP of 3.3.3.3 and all traffic is open. SELinux has been disabled.

All nodes are on separate servers. The only thing Node 3 has installed on it is HAProxy and mysql client.

So per the Galera documentation, I install HAProxy and add this portion to the bottom of the config file:

# Load Balancing for Galera Cluster
listen galera 3.3.3.3:3306
     balance roundrobin
     mode tcp
     option tcpka
     option mysql-check user haproxy
     server node1 1.1.1.1:3306 check weight 1
     server node2 2.2.2.2:3306 check weight 1

But then when I check status of HAProxy I get these errors:

[root@nodemgr haproxy]# service haproxy restart
Redirecting to /bin/systemctl restart  haproxy.service
[root@nodemgr haproxy]# service haproxy status
Redirecting to /bin/systemctl status  haproxy.service
● haproxy.service - HAProxy Load Balancer
   Loaded: loaded (/usr/lib/systemd/system/haproxy.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Tue 2017-07-04 20:18:50 EDT; 3s ago
  Process: 11773 ExecStart=/usr/sbin/haproxy-systemd-wrapper -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid $OPTIONS (code=exited, status=1/FAILURE)
 Main PID: 11773 (code=exited, status=1/FAILURE)

Jul 04 20:18:50 nodemgr systemd[1]: Started HAProxy Load Balancer.
Jul 04 20:18:50 nodemgr systemd[1]: Starting HAProxy Load Balancer...
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: haproxy-systemd-wrapper: executing /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /ru...pid -Ds
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: [WARNING] 184/201850 (11774) : parsing [/etc/haproxy/haproxy.cfg:45] : 'option httplog'...cplog'.
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: [WARNING] 184/201850 (11774) : config : 'option forwardfor' ignored for proxy 'galera' ...P mode.
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: [ALERT] 184/201850 (11774) : Starting proxy galera: cannot bind socket [3.3.3.3:3306]
Jul 04 20:18:50 nodemgr systemd[1]: haproxy.service: main process exited, code=exited, status=1/FAILURE
Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: haproxy-systemd-wrapper: exit, haproxy RC=1
Jul 04 20:18:50 nodemgr systemd[1]: Unit haproxy.service entered failed state.
Jul 04 20:18:50 nodemgr systemd[1]: haproxy.service failed.
Hint: Some lines were ellipsized, use -l to show in full.

I'm assuming my problem is here:

 Jul 04 20:18:50 nodemgr haproxy-systemd-wrapper[11773]: [ALERT] 184/201850 (11774) : Starting proxy galera: cannot bind socket [3.3.3.3:3306]

but after disabling SELinux I don't know what else I need to do. Any help is greatly appreciated!

Full haproxy config file is here:

#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    log         127.0.0.1 local2

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend  main *:5000
    acl url_static       path_beg       -i /static /images /javascript /stylesheets
    acl url_static       path_end       -i .jpg .gif .png .css .js

    use_backend static          if url_static
    default_backend             app

#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
backend static
    balance     roundrobin
    server      static 127.0.0.1:4331 check
#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend app
    balance     roundrobin
    server  app1 127.0.0.1:5001 check
    server  app2 127.0.0.1:5002 check
    server  app3 127.0.0.1:5003 check
    server  app4 127.0.0.1:5004 check

# Load Balancing for Galera Cluster
listen galera 3.3.3.3:3306
     balance roundrobin
     mode tcp
     option tcpka
     option mysql-check user haproxy
     server node1 1.1.1.1:3306 check weight 1
     server node2 2.2.2.2:3306 check weight 1


问:
Create a table in mysql
Here is the mysql code. I can't find the error here. when I execute this bunch of code it shows syntax error.</p>

```<code> CREATE TABLE Movie(
-> title            varchar(100),
-> year             int,
-> length           int,
-> inColor          BIT(1),
-> studioName       varchar(50),
-> producerC#       int,
-> PRIMARY KEY      ('title'));
</code>```

答:
You can use below query to create table:</p>

```<code>CREATE TABLE Movie(
title VARCHAR(100) PRIMARY KEY,
year INT,
length INT,
inColor BIT(1),
studioName VARCHAR(50),
producerC# int
)
</code>```

Title: Create a table in mysql

Body:
Here is the mysql code. I can't find the error here. when I execute this bunch of code it shows syntax error.

 CREATE TABLE Movie(
-> title            varchar(100),
-> year             int,
-> length           int,
-> inColor          BIT(1),
-> studioName       varchar(50),
-> producerC#       int,
-> PRIMARY KEY      ('title'));

Body:
You can use below query to create table:

CREATE TABLE Movie(
title VARCHAR(100) PRIMARY KEY,
year INT,
length INT,
inColor BIT(1),
studioName VARCHAR(50),
producerC# int
)


问:
Cron Terminates Python Script?
I have a 'long' python script that takes roughly 45[min] to run. I use another (a 'scheduler' script) python script to run this long script. When I run the 'scheduler' script using the terminal, everything works perfectly (meaning, the 'long' script runs without any issues).

I had some struggles, but eventually succeeded adding the 'scheduler' script to run through cron every minute. so it now 'runs' other script and works OK.

Here is the problem: whenever a script (that is being 'run' by the 'scheduler') has a line that says:

```<code>print "hello"
</code>```

or any 'print' statement, the cron job runs, but terminates after 20-30 seconds. When I remove any 'print' statements, cron runs the jobs normally and does not terminate.

I'd like to fix this situation, and have the scripts continue to run even if they have some 'print' statements in them. any hints how to do it?

P.S. from within the 'scheduler', I use

```<code>subprocess.Popen([sys.executable, command])
</code>```

to 'run' all other python scripts.

答:
I have a hunch that it's due to the way cron handles stdout. How are you redirecting output?

From http://aplawrence.com/BDD/bbcronbasics.html:

OUTPUT

Normally the output of any program is
  sent to STDOUT (standard out) and
  usually winds up on someone's display
  screen.  For jobs started by cron,
  STDOUT will be directed to the local
  mail subsystem, which means any output
  generated by a cron job will be mailed
  to the user owning the job.  If this
  is not desirable you should take steps
  to redirect your cron job's output to
  a file.  It is also suggested you
  redirect STDERR (standard error) to a
  file so as to be able to analyze any
  anomalies in your cron job's
  execution.

Title: Cron Terminates Python Script?

Body:
I have a 'long' python script that takes roughly 45[min] to run. I use another (a 'scheduler' script) python script to run this long script. When I run the 'scheduler' script using the terminal, everything works perfectly (meaning, the 'long' script runs without any issues).

I had some struggles, but eventually succeeded adding the 'scheduler' script to run through cron every minute. so it now 'runs' other script and works OK.

Here is the problem: whenever a script (that is being 'run' by the 'scheduler') has a line that says:

print "hello"

or any 'print' statement, the cron job runs, but terminates after 20-30 seconds. When I remove any 'print' statements, cron runs the jobs normally and does not terminate.

I'd like to fix this situation, and have the scripts continue to run even if they have some 'print' statements in them. any hints how to do it?

P.S. from within the 'scheduler', I use

subprocess.Popen([sys.executable, command])

to 'run' all other python scripts.


问:
How to subscript +, -, _, and other arithmetic symbols in R
Previous questions on subscripts in R (specifically relating to text in ggplot/annotate/geo arguments) don't quite touch on this issue.

Say I want to have a subscript "+", like

$\Sigma_+$

If I do something like

```<code>scale_colour_manual(values = c('red' = 'red','blue' = 'blue'),name = '',
                  labels = expression(P[+] - P[-] == P[w])
</code>```

We get an error similar to:

```<code>Error: unexpected ']' in:
"scale_colour_manual(values = c('red' = 'red','blue' = 'blue'),name = '',
labels = expression(P[+]"
</code>```

答:
I think that R thinks that the + is acting as a arithematic operator, and adding two non-numbers "[" and "]".

The solution is to put make the subscript a character string. I think that some people may forget that this is a possibility.

```<code>scale_colour_manual(values = c('red' = 'red','blue' = 'blue'),name = '',
                  labels = expression(P["+"] - P["-"] == P[w])
</code>```

Body:
Previous questions on subscripts in R (specifically relating to text in ggplot/annotate/geo arguments) don't quite touch on this issue.

Say I want to have a subscript "+", like

$\Sigma_+$

If I do something like

scale_colour_manual(values = c('red' = 'red','blue' = 'blue'),name = '',
                  labels = expression(P[+] - P[-] == P[w])

We get an error similar to:

Error: unexpected ']' in:
"scale_colour_manual(values = c('red' = 'red','blue' = 'blue'),name = '',
labels = expression(P[+]"

Body:
I think that R thinks that the + is acting as a arithematic operator, and adding two non-numbers "[" and "]".

The solution is to put make the subscript a character string. I think that some people may forget that this is a possibility.

scale_colour_manual(values = c('red' = 'red','blue' = 'blue'),name = '',
                  labels = expression(P["+"] - P["-"] == P[w])


问:
Check only last 3 digits of sensor output
I have a library from WiringPi for DHT11 sensor and I need to modify condition which checks if the value read from sensor is good.

Sometimes the library reads bad values which are 255.255,255.255 or 55,255.255 etc.

sample output

There is the condition in the library:

```<code>if(counter==255)
        break;
</code>```

But it doesn't work if the value is e.g. 55,255.255

How can I modify this condition the check last 3 digits of output?
If the output is wrong, there are always "255" at the end of value.
I tried to add conditions like

```<code>if(counter==255)
        break;
        else if(counter==255.255)
        break;
</code>```

But it doesn't solve all possible situations and I realy don't know anything about C/C++

Here is the whole library:

```<code>#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAX_TIME 85
#define DHT11PIN 7
#define ATTEMPTS 5
int dht11_val[5]={0,0,0,0,0};

int dht11_read_val()
{
  uint8_t lststate=HIGH;
  uint8_t counter=0;
  uint8_t j=0,i;
  for(i=0;i<5;i++)
     dht11_val[i]=0;
  pinMode(DHT11PIN,OUTPUT);
  digitalWrite(DHT11PIN,LOW);
  delay(18);
  digitalWrite(DHT11PIN,HIGH);
  delayMicroseconds(40);
  pinMode(DHT11PIN,INPUT);
  for(i=0;i<MAX_TIME;i++)
  {
    counter=0;
    while(digitalRead(DHT11PIN)==lststate){
      counter++;
      delayMicroseconds(1);
      if(counter==255)
        break;
    }
    lststate=digitalRead(DHT11PIN);
    if(counter==255)
       break;
    // top 3 transistions are ignored
    if((i>=4)&&(i%2==0)){
      dht11_val[j/8]<<=1;
      if(counter>16)
        dht11_val[j/8]|=1;
      j++;
    }
  }
  // verify checksum and print the verified data
  if((j>=40)&&(dht11_val[4]==((dht11_val[0]+dht11_val[1]+dht11_val[2]+dht11_val[3])& 0xFF)))
  {
    printf("%d.%d,%d.%d\n",dht11_val[0],dht11_val[1],dht11_val[2],dht11_val[3]);
    return 1;
  }
  else
    return 0;
}

int main(void)
{
  int attempts=ATTEMPTS;
  if(wiringPiSetup()==-1)
    exit(1);
  while(attempts)
  {
    int success = dht11_read_val();
    if (success) {
      break;
    }
    attempts--;
    delay(500);
  }
  return 0;
}
</code>```

答:
No single variable in your code can hold "255.255", that would require a string or a float. You are obviously referring to the output of

printf("%d.%d,%d.%d\n",dht11_val[0],dht11_val[1],dht11_val[2],dht11_val[3]);.

This printf can never produce a three-value output like 55,255.255.
I assume that your output would be 55.255,255.255.

This in turn means that in case of error you will find the "last three digits" in dht11_val[3].

If my assumption is not correct please provide much more detail on the error circumstances.

On the other hand, I suspect that looking for that value is not the solution for your problem either. The function is more complicated. The value of 255 seems the result of an endless loop which is detected by breaking early at counter = 255. So I am pretty sure that checking "the last three digits" is a LESS precise check than what is already implemented.

Body:
I have a library from WiringPi for DHT11 sensor and I need to modify condition which checks if the value read from sensor is good.

Sometimes the library reads bad values which are 255.255,255.255 or 55,255.255 etc.

sample output

There is the condition in the library:

if(counter==255)
        break;

But it doesn't work if the value is e.g. 55,255.255

How can I modify this condition the check last 3 digits of output?
If the output is wrong, there are always "255" at the end of value.
I tried to add conditions like

if(counter==255)
        break;
        else if(counter==255.255)
        break;

But it doesn't solve all possible situations and I realy don't know anything about C/C++

Here is the whole library:

#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAX_TIME 85
#define DHT11PIN 7
#define ATTEMPTS 5
int dht11_val[5]={0,0,0,0,0};

int dht11_read_val()
{
  uint8_t lststate=HIGH;
  uint8_t counter=0;
  uint8_t j=0,i;
  for(i=0;i<5;i++)
     dht11_val[i]=0;
  pinMode(DHT11PIN,OUTPUT);
  digitalWrite(DHT11PIN,LOW);
  delay(18);
  digitalWrite(DHT11PIN,HIGH);
  delayMicroseconds(40);
  pinMode(DHT11PIN,INPUT);
  for(i=0;i<MAX_TIME;i++)
  {
    counter=0;
    while(digitalRead(DHT11PIN)==lststate){
      counter++;
      delayMicroseconds(1);
      if(counter==255)
        break;
    }
    lststate=digitalRead(DHT11PIN);
    if(counter==255)
       break;
    // top 3 transistions are ignored
    if((i>=4)&&(i%2==0)){
      dht11_val[j/8]<<=1;
      if(counter>16)
        dht11_val[j/8]|=1;
      j++;
    }
  }
  // verify checksum and print the verified data
  if((j>=40)&&(dht11_val[4]==((dht11_val[0]+dht11_val[1]+dht11_val[2]+dht11_val[3])& 0xFF)))
  {
    printf("%d.%d,%d.%d\n",dht11_val[0],dht11_val[1],dht11_val[2],dht11_val[3]);
    return 1;
  }
  else
    return 0;
}

int main(void)
{
  int attempts=ATTEMPTS;
  if(wiringPiSetup()==-1)
    exit(1);
  while(attempts)
  {
    int success = dht11_read_val();
    if (success) {
      break;
    }
    attempts--;
    delay(500);
  }
  return 0;
}


问:
How to pass a deleter to a method in the same class that is held by a shared_ptr
I have several classes from 3rd party library similar to the class, StagingConfigDatabase, which requires to be destroyed after it is created. I am using a shared_ptr for RAII but would prefer to create the shared_ptr using a single line of code rather than using a seperate template functor as my example shows. Perhaps using lambdas?  or bind?

```<code>struct StagingConfigDatabase
{
  static StagingConfigDatabase* create();
  void destroy();
};

template<class T>
    struct RfaDestroyer
    {
        void operator()(T* t)
        {
            if(t) t->destroy();
        }
    };

    int main()
    {
      shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), RfaDestroyer<StagingConfigDatabase>());
    return 1;
    }
</code>```

I was considering something like:

```<code>shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), [](StagingConfigDatabase* sdb) { sdb->destroy(); } );
</code>```

but that doesn't compile :(

Help!

答:
What compiler are you using? Does it support C++0x features like lambdas? The following (which is basically the same as your example) compiles and works fine for me under MSVC 2010:

```<code>#include <iostream>
#include <memory>

struct X
{
    static X *create()
    {
        std::cout << "X::create\n";
        return new X;
    }

    void destroy()
    {
        std::cout << "X::destroy\n";
        delete this;
    }
};

int main()
{
    auto p = std::shared_ptr<X>(X::create(), [](X *p) { p->destroy(); });
    return 0;
}
</code>```

By "works fine", I mean "outputs X::create followed by X::destroy".

Body:
I have several classes from 3rd party library similar to the class, StagingConfigDatabase, which requires to be destroyed after it is created. I am using a shared_ptr for RAII but would prefer to create the shared_ptr using a single line of code rather than using a seperate template functor as my example shows. Perhaps using lambdas?  or bind?

struct StagingConfigDatabase
{
  static StagingConfigDatabase* create();
  void destroy();
};

template<class T>
    struct RfaDestroyer
    {
        void operator()(T* t)
        {
            if(t) t->destroy();
        }
    };

    int main()
    {
      shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), RfaDestroyer<StagingConfigDatabase>());
    return 1;
    }

I was considering something like:

shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), [](StagingConfigDatabase* sdb) { sdb->destroy(); } );

but that doesn't compile :(

Help!

Body:
What compiler are you using? Does it support C++0x features like lambdas? The following (which is basically the same as your example) compiles and works fine for me under MSVC 2010:

#include <iostream>
#include <memory>

struct X
{
    static X *create()
    {
        std::cout << "X::create\n";
        return new X;
    }

    void destroy()
    {
        std::cout << "X::destroy\n";
        delete this;
    }
};

int main()
{
    auto p = std::shared_ptr<X>(X::create(), [](X *p) { p->destroy(); });
    return 0;
}

By "works fine", I mean "outputs X::create followed by X::destroy".