问:
Which method is better for multiple join and left join by Linq?
I have multiple table and I want multiple join and left join them together by Linq. I tried 2 different methods to achieve it and it seems both of them return correct results.

But each method generate different SQL query. For example method 1 generate an Order By for some keys at end of the query too.

My question is:
Which method do you recommend? Why (Performance &...)?

Method 1:

```<code>    from t1 in Table1
    // Inner Join on a foreign key in tb1
    join t2 in Table2 on t1.fkId1 equals t2.Id1
    // Left Join
    join t3 in Table3 on t1.fkId1 equals t3.Id1 into ServCons
    from t3 in ServCons.DefaultIfEmpty()
    // Left Join
    join t4 in Table4 on t3.Id2 equals t4.Id2 into t4
    select new{t1,t2,t3,t4}
</code>```

Method 2:

```<code>    from t1 in Table1
    // Inner Join on a foreign key in tb1
    from t2 in Table2 .Where(w=>t1.fkId1 == t2.Id1)
    // Left Join
    from t3 in Table3 .Where(w=>t1.fkId1 == w.Id1).DefaultIfEmpty()
    // Left Join
    from t4 in Table4 .Where(w=>t3.Id2 ==w.Id2).DefaultIfEmpty()
    select new{t1,t2,t3,t4}
</code>```

Update:

I think it is clear that the performance is an important issue for a program and programmer. Faster results with lower costs is my target here too. So when i mentioned about different SQL queries with a question about performance it is clear enough that a good compare between 2 methods by writing about pros and cons of them will be accepted answer.

答:
First, the SQL difference is because the two queries are not equivalent.

In the first query:

```<code>join t4 in Table4 on t3.Id2 equals t4.Id2 into t4
</code>```

is actually a group join which produces a different shape in the projection (t4 is collection).

If you convert it to the left outer join LINQ pattern:

```<code>join t4 in Table4 on t3.Id2 equals t4.Id2 into t4Group
from t4 in t4Group.DefaultIfEmpty()
</code>```

the generated SQL will be one and the same (depending on the query provider).

Now about performance. Since LINQ has no special left outer join operator, the first is the "officially" agreed LINQ pattern for implementing such operator. And LINQ to Objects it's definitely the way to go, because the Enumerable.Join implementation uses fast hash based lookup to perform the correlation woit O(n + m) time complexity, while from ... .Where(...).DefaultIfEmpty() is basically SelectMany with linear search operation with O(m * n) complexity.

For IQueryable<T> implementations, it really depends on the query provider. For EF6 provider both constructs are equivalent and gets translated to one and the same SQL. For EF Core - well, currently it's still in development and has many bugs and issues, especially with left joins, so it's hard to give you a general advice.

So for IQueryable<T> implementations, always check the query provider capabilities - what is supported or not, how it's translated / processed etc (LINQ is sort of broken in that regard).

In general I would say use the first pattern. Essential in LINQ to Objects and hopefully should be recognized by any good query provider.

But specifically for EF6, it's just a matter of a taste - since EF6 is smart enough to recognize and translate them to one and the same SQL, the performance is also one and the same.

Body:
I have multiple table and I want multiple join and left join them together by Linq. I tried 2 different methods to achieve it and it seems both of them return correct results.

But each method generate different SQL query. For example method 1 generate an Order By for some keys at end of the query too.

My question is:
Which method do you recommend? Why (Performance &...)?

Method 1:

    from t1 in Table1
    // Inner Join on a foreign key in tb1
    join t2 in Table2 on t1.fkId1 equals t2.Id1
    // Left Join
    join t3 in Table3 on t1.fkId1 equals t3.Id1 into ServCons
    from t3 in ServCons.DefaultIfEmpty()
    // Left Join
    join t4 in Table4 on t3.Id2 equals t4.Id2 into t4
    select new{t1,t2,t3,t4}

Method 2:

    from t1 in Table1
    // Inner Join on a foreign key in tb1
    from t2 in Table2 .Where(w=>t1.fkId1 == t2.Id1)
    // Left Join
    from t3 in Table3 .Where(w=>t1.fkId1 == w.Id1).DefaultIfEmpty()
    // Left Join
    from t4 in Table4 .Where(w=>t3.Id2 ==w.Id2).DefaultIfEmpty()
    select new{t1,t2,t3,t4}

Update:

I think it is clear that the performance is an important issue for a program and programmer. Faster results with lower costs is my target here too. So when i mentioned about different SQL queries with a question about performance it is clear enough that a good compare between 2 methods by writing about pros and cons of them will be accepted answer.

Body:
First, the SQL difference is because the two queries are not equivalent.

In the first query:

join t4 in Table4 on t3.Id2 equals t4.Id2 into t4

is actually a group join which produces a different shape in the projection (t4 is collection).

If you convert it to the left outer join LINQ pattern:

join t4 in Table4 on t3.Id2 equals t4.Id2 into t4Group
from t4 in t4Group.DefaultIfEmpty()

the generated SQL will be one and the same (depending on the query provider).

Now about performance. Since LINQ has no special left outer join operator, the first is the "officially" agreed LINQ pattern for implementing such operator. And LINQ to Objects it's definitely the way to go, because the Enumerable.Join implementation uses fast hash based lookup to perform the correlation woit O(n + m) time complexity, while from ... .Where(...).DefaultIfEmpty() is basically SelectMany with linear search operation with O(m * n) complexity.

For IQueryable<T> implementations, it really depends on the query provider. For EF6 provider both constructs are equivalent and gets translated to one and the same SQL. For EF Core - well, currently it's still in development and has many bugs and issues, especially with left joins, so it's hard to give you a general advice.

So for IQueryable<T> implementations, always check the query provider capabilities - what is supported or not, how it's translated / processed etc (LINQ is sort of broken in that regard).

In general I would say use the first pattern. Essential in LINQ to Objects and hopefully should be recognized by any good query provider.

But specifically for EF6, it's just a matter of a taste - since EF6 is smart enough to recognize and translate them to one and the same SQL, the performance is also one and the same.


来源: stackexchange

问:
A short javascript to keep scrolling to the top of page until the end?
I'm using web interface of telegram (a IM like whatsapp) so I want to view some message which is on top of page and I want to scroll but there are like 15000 lines and i dont want to keep pressing pageup so is there a java script which i could execute in console to reach to the top??</p>

答:
To scroll to the top of an element in JavaScript you can use vanilla JavaScript and the Web API:

```<code>yourElement.scrollTop = 0;
</code>```

You can read more about this function on the MDN docs: Element.scrollTop().

ContentLicense: CC BY-SA 3.0

Body:
To scroll to the top of an element in JavaScript you can use vanilla JavaScript and the Web API:

yourElement.scrollTop = 0;

You can read more about this function on the MDN docs: Element.scrollTop().


问:
Files get committed with the wrong file encoding
We are UTF8 with BOM in most of our code files.

However, some code files get into the git repository as plain ASCII. I haven't figured out how/why. It's mostly existing files. From what I can tell they do not have to been modified (i.e. code changes) to become converted to ASCII.

It causes problems since we are using latin1 characters in comments and text.

I'm trying to track down how/when the files are converted, but am a bit lost. We are using Visual Studio (2015 & 2017) and an application called "Git Extensions".

Is there a setting in Visual Studio, in git or in Git Extensions that can change the file encoding?

答: In GitExtensions there is a setting for Files content encoding. It is used when a file is open in GitExtensions internal editor.</p>


问:
Why does this code execute wrong?
There is an input file "input.txt". It looks like:

```<code>7
4
2
5
2
9
8
6
10
8
4
</code>```

And there's a code:

```<code>inn = open("/storage/emulated/0/input.txt", "r")
a = 0
b = 10
array = []

while not a == b:
     for i, line in enumerate(inn):
         if i == a:
              array += str(line)
     a+=1
print(array)
</code>```

I need to put all the numbers in "array" variable, but wher I run the code -- I get empty "array". Is there a mistake in a code?

(sorry for such noob question)

答:
I can't reproduce your error. Also, I don't get an empty array when running your code. See the following code and the results. I still suggest using np.genfromtxt when the input data is as clean as yours.

Code:

```<code>import numpy as np

# I have input.txt in same directory as this .py-file

# np.genfromtxt with int and with string
approach1a = np.genfromtxt('input.txt', dtype=int)
approach1b = np.genfromtxt('input.txt', dtype=np.str_)

# list comprehension
approach2 = []
with open('input.txt') as file:
    approach2 = [str(line) for line in file]

# like your approach, but without a, b and the if statement
approach3 = []
with open('input.txt') as file:
    for line in file:
        approach3.append(line)

# your code
inn = open("input.txt", "r")
a = 0
b = 10
array = []
while not a == b:
    for i, line in enumerate(inn):
        if i == a:
            array += str(line)
    a+=1
</code>```

Results:

```<code>>>> approach1a
array([ 7,  4,  2,  5,  2,  9,  8,  6, 10,  8,  4])
>>> approach1b
array(['7', '4', '2', '5', '2', '9', '8', '6', '10', '8', '4'],
      dtype='<U2')
>>> approach2
['7\n', '4\n', '2\n', '5\n', '2\n', '9\n', '8\n', '6\n', '10\n', '8\n', '4']
>>> approach3
['7\n', '4\n', '2\n', '5\n', '2\n', '9\n', '8\n', '6\n', '10\n', '8\n', '4']
>>> array
['7', '\n']
</code>```

The reason that only the first line of the inpur file is read with your code is because with open you can only iterate over the lines once. If you have done that, you can't go back. To understand that, see for example @Aaron Hall's anwer to this question: there is only a method next, but there is no way to go back (in this case to go back a line). You have reached that point where all lines of open were used once when you set the value of a to 1, i.e. after you have added the first line of the input file to array. This is why I understand that your code only reads the first line, why I can't reproduce you claiming you have array as an empty list and why I suggested approach3.

Title: Why does this code execute wrong?

Body:
There is an input file "input.txt". It looks like:

7
4
2
5
2
9
8
6
10
8
4

And there's a code:

inn = open("/storage/emulated/0/input.txt", "r")
a = 0
b = 10
array = []

while not a == b:
     for i, line in enumerate(inn):
         if i == a:
              array += str(line)
     a+=1
print(array)

I need to put all the numbers in "array" variable, but wher I run the code -- I get empty "array". Is there a mistake in a code?

(sorry for such noob question)

Body:
I can't reproduce your error. Also, I don't get an empty array when running your code. See the following code and the results. I still suggest using np.genfromtxt when the input data is as clean as yours.

Code:

import numpy as np

# I have input.txt in same directory as this .py-file

# np.genfromtxt with int and with string
approach1a = np.genfromtxt('input.txt', dtype=int)
approach1b = np.genfromtxt('input.txt', dtype=np.str_)

# list comprehension
approach2 = []
with open('input.txt') as file:
    approach2 = [str(line) for line in file]

# like your approach, but without a, b and the if statement
approach3 = []
with open('input.txt') as file:
    for line in file:
        approach3.append(line)

# your code
inn = open("input.txt", "r")
a = 0
b = 10
array = []
while not a == b:
    for i, line in enumerate(inn):
        if i == a:
            array += str(line)
    a+=1

Results:

>>> approach1a
array([ 7,  4,  2,  5,  2,  9,  8,  6, 10,  8,  4])
>>> approach1b
array(['7', '4', '2', '5', '2', '9', '8', '6', '10', '8', '4'],
      dtype='<U2')
>>> approach2
['7\n', '4\n', '2\n', '5\n', '2\n', '9\n', '8\n', '6\n', '10\n', '8\n', '4']
>>> approach3
['7\n', '4\n', '2\n', '5\n', '2\n', '9\n', '8\n', '6\n', '10\n', '8\n', '4']
>>> array
['7', '\n']

The reason that only the first line of the inpur file is read with your code is because with open you can only iterate over the lines once. If you have done that, you can't go back. To understand that, see for example @Aaron Hall's anwer to this question: there is only a method next, but there is no way to go back (in this case to go back a line). You have reached that point where all lines of open were used once when you set the value of a to 1, i.e. after you have added the first line of the input file to array. This is why I understand that your code only reads the first line, why I can't reproduce you claiming you have array as an empty list and why I suggested approach3.


问:
Validating CSV data validity as well as CSV file name before inserting and if there is an error/missing data in between do not insert to database
I need help on validating CSV data, as well as CSV filename before inserting and if there is an error/missing data in between do not insert to database and print error message.</p>

```<code>try {
    if(isset($_POST['importSubmit'])){
        //validate whether uploaded file is a csv file
        $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
        $surveydate = $_POST['surveydate'];
        $userID = $_SESSION['userID'];

        if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
            if(is_uploaded_file($_FILES['file']['tmp_name'])){
                //open uploaded csv file with read only mode
                $csvFile = fopen($_FILES['file']['tmp_name'], 'r');

                //skip first line
                fgetcsv($csvFile);

                //parse data from csv file line by line
                while(($line = fgetcsv($csvFile)) !== FALSE) {
                    //check whether member already exists in database with same email
                    //insert member data into database
                    $db->query("INSERT INTO communitysurvey (surveyNum,stationID,age,gender,educationalattainment,question,response,userID,surveydate) VALUES('".$line[0]."', '".$line[1]."','".$line[2]."', '".$line[3]."', '".$line[4]."','".$line[5]."','".$line[6]."','{$userID}','{$surveydate}')");
                }

                //problem on userID session won't get inserted
                //close opened csv file
                fclose($csvFile);
            }
        }
    }

    //redirect to the listing page
    header("Location: inputcommunity.php".$qstring);
} catch (Exception $e) {
    alert ($e->getMessage());
}
</code>```

答: To get the data from your CSV you could use explode and explode on your delimiters (likely "," or ", " for a CSV) for each line read in in your while loop. This will return an array of each value in that line. You can check the length of this array for missing values and compare types/values to expected ones to check for "correctness".

Body:
I need help on validating CSV data, as well as CSV filename before inserting and if there is an error/missing data in between do not insert to database and print error message.

try {
    if(isset($_POST['importSubmit'])){
        //validate whether uploaded file is a csv file
        $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
        $surveydate = $_POST['surveydate'];
        $userID = $_SESSION['userID'];

        if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
            if(is_uploaded_file($_FILES['file']['tmp_name'])){
                //open uploaded csv file with read only mode
                $csvFile = fopen($_FILES['file']['tmp_name'], 'r');

                //skip first line
                fgetcsv($csvFile);

                //parse data from csv file line by line
                while(($line = fgetcsv($csvFile)) !== FALSE) {
                    //check whether member already exists in database with same email
                    //insert member data into database
                    $db->query("INSERT INTO communitysurvey (surveyNum,stationID,age,gender,educationalattainment,question,response,userID,surveydate) VALUES('".$line[0]."', '".$line[1]."','".$line[2]."', '".$line[3]."', '".$line[4]."','".$line[5]."','".$line[6]."','{$userID}','{$surveydate}')");
                }

                //problem on userID session won't get inserted
                //close opened csv file
                fclose($csvFile);
            }
        }
    }

    //redirect to the listing page
    header("Location: inputcommunity.php".$qstring);
} catch (Exception $e) {
    alert ($e->getMessage());
}


问:
How to add class to all rows
In given example, I can select/deselect each row on clicking on checkbox from td, but how to select/deselect all rows on click  id="selectAll" from th

JS :

```<code>$(document).ready(function () {

    $("input[type='checkbox']").change(function (e) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("warning");
        } else {
            $(this).closest('tr').removeClass("warning");
        }
    });
});
</code>```

Demo Here (Fiddle)

答:
Should cover all cases including switching selectAll appropriately  when other inputs are selected/unselected

```<code>   var $dataInputs;

   var $selectAll = $('#selectAll').change(function() {
       $dataInputs.prop('checked', this.checked)
                .closest('tr')
                .toggleClass("warning", this.checked);
   });

   $dataInputs = $("input[type='checkbox']").not('#selectAll').change(function(e) {
     // toggle class on this row
     $(this).closest('tr').toggleClass("warning", this.checked);

     // adjust `selectAll` based on all rows selected or not
     $selectAll.prop('checked', function() {
       return $dataInputs.length === $dataInputs.filter(':checked').length;
     });

   });
</code>```

DEMO

Title: How to add class to all rows

Body:
In given example, I can select/deselect each row on clicking on checkbox from td, but how to select/deselect all rows on click  id="selectAll" from th

JS :

$(document).ready(function () {

    $("input[type='checkbox']").change(function (e) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("warning");
        } else {
            $(this).closest('tr').removeClass("warning");
        }
    });
});

Demo Here (Fiddle)

Body:
Should cover all cases including switching selectAll appropriately  when other inputs are selected/unselected

   var $dataInputs;

   var $selectAll = $('#selectAll').change(function() {
       $dataInputs.prop('checked', this.checked)
                .closest('tr')
                .toggleClass("warning", this.checked);
   });

   $dataInputs = $("input[type='checkbox']").not('#selectAll').change(function(e) {
     // toggle class on this row
     $(this).closest('tr').toggleClass("warning", this.checked);

     // adjust `selectAll` based on all rows selected or not
     $selectAll.prop('checked', function() {
       return $dataInputs.length === $dataInputs.filter(':checked').length;
     });

   });

DEMO


问:
express4 reusing mongodb handle
I am new to javascript and nodejs programming. I am trying to connect mongodb in express framework but like to keep code modular. I have below code written. I am using express version 4.14.0 and mongodb driver 2.2.27 version and nodejs v6.10.3

```<code>//app.js
var express = require('express');
var app = express();
var index = require('./routes/index');
app.use('/', index);
app.listen(3000);

//routes/index.js
var router = require('express').Router();
var anotherfile = require('../controllers/anotherfile');

router.get('/', function(req, res) {
        res.send('Connected');
});
module.exports = router;

//controllers/db.js
var MongoClient = require('mongodb').MongoClient;
var connectionString = 'mongodb://user:password@127.0.0.1:27017/testdb';
var _db;

MongoClient.connect(connectionString, function(err, db) {
  if (err) {
    console.log('Error: ', err);
  } else {
    console.log('Connected!');
    _db = db;
    console.log("_db",_db);
  }
});

module.exports.getDb = function() {
  return _db;
}

//controllers/anotherfile.js
var connect = require('./db.js');
var db1 = connect.getDb();
console.log("print db1",db1);
</code>```

What I want from above code is access to db handle in anotherfile.js. What am I doing wrong here?

答:
To keep the code modular you should keep the database functions in a separate file and then access those function from other your anotherfile.js. This way you can use that database function file for other projects as well.

mongoConfig.js

```<code>var express = require('express');
var router = express.Router();
module.exports = router;
var mongo = require('mongodb');
var uri = '<MongoDB server path>';

module.exports.insert = function(collectionName, json, callback) {
  mongo.MongoClient.connect(uri, function(err, db) {
    if (!err) {

    } else {

    }
  });
};

module.exports.retrieve = function(collectionName, json, callback) {
  mongo.MongoClient.connect(uri, function(err, db) {
    if (!err) {

    } else {

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

Your code in server.js.

server.js

```<code>var express = require('express');
var app = express();
var index = require('./routes/index');
app.use('/', index);
app.listen(3000);

//routes/index.js
var router = require('express').Router();
var anotherfile = require('../controllers/anotherfile');

router.get('/', function(req, res) {
    res.send('Connected');
});
</code>```

Then,

anotherfile.js

```<code>var Mongo = require('./mongoConfig');.
Mongo.insert();
Mongo.retrieve();
</code>```

Use require to import the mongoConfig.js into your anotherfile.js

Title: express4 reusing mongodb handle

Body:
I am new to javascript and nodejs programming. I am trying to connect mongodb in express framework but like to keep code modular. I have below code written. I am using express version 4.14.0 and mongodb driver 2.2.27 version and nodejs v6.10.3

//app.js
var express = require('express');
var app = express();
var index = require('./routes/index');
app.use('/', index);
app.listen(3000);

//routes/index.js
var router = require('express').Router();
var anotherfile = require('../controllers/anotherfile');

router.get('/', function(req, res) {
        res.send('Connected');
});
module.exports = router;

//controllers/db.js
var MongoClient = require('mongodb').MongoClient;
var connectionString = 'mongodb://user:password@127.0.0.1:27017/testdb';
var _db;

MongoClient.connect(connectionString, function(err, db) {
  if (err) {
    console.log('Error: ', err);
  } else {
    console.log('Connected!');
    _db = db;
    console.log("_db",_db);
  }
});

module.exports.getDb = function() {
  return _db;
}

//controllers/anotherfile.js
var connect = require('./db.js');
var db1 = connect.getDb();
console.log("print db1",db1);

What I want from above code is access to db handle in anotherfile.js. What am I doing wrong here?

Body:
To keep the code modular you should keep the database functions in a separate file and then access those function from other your anotherfile.js. This way you can use that database function file for other projects as well.

mongoConfig.js

var express = require('express');
var router = express.Router();
module.exports = router;
var mongo = require('mongodb');
var uri = '<MongoDB server path>';

module.exports.insert = function(collectionName, json, callback) {
  mongo.MongoClient.connect(uri, function(err, db) {
    if (!err) {

    } else {

    }
  });
};

module.exports.retrieve = function(collectionName, json, callback) {
  mongo.MongoClient.connect(uri, function(err, db) {
    if (!err) {

    } else {

    }
  });
};

Your code in server.js.

server.js

var express = require('express');
var app = express();
var index = require('./routes/index');
app.use('/', index);
app.listen(3000);

//routes/index.js
var router = require('express').Router();
var anotherfile = require('../controllers/anotherfile');

router.get('/', function(req, res) {
    res.send('Connected');
});

Then,

anotherfile.js

var Mongo = require('./mongoConfig');.
Mongo.insert();
Mongo.retrieve();

Use require to import the mongoConfig.js into your anotherfile.js


问:
What is the maximum value for mapreduce.task.io.sort.mb?
When I set mapreduce.task.io.sort.mb = 100000. I get following exception.

```<code>java.lang.Exception: java.io.IOException: Invalid "mapreduce.task.io.sort.mb": 100000
</code>```

What is the maximum value for mapreduce.task.io.sort.mb?

答: By default it is 100MB and it can go up to 2047 MB.</p>

Body:
When I set mapreduce.task.io.sort.mb = 100000. I get following exception.

java.lang.Exception: java.io.IOException: Invalid "mapreduce.task.io.sort.mb": 100000

What is the maximum value for mapreduce.task.io.sort.mb?


问:
Calling RESTful web service using a GET in JavaScript
I am struggling to send a GET request to my web service.

I have a web service set up that has values assigned to x and y values, where x represents a value A-E and y represents a value 1-5. Let's say that, the values are assigned to C1.

So if I point to the URL: x.x.x.x:xxxx/app/x/c/y/1 then I would get back a response of 'Success' and if x and y represent other values then I have messages for failure and so on for invalid data types.

I cannot seem to get it to work!

The web service contains the following logic:

```<code>log.info 'queryContext = ' + queryContext
def x = queryContext.get('x',"value")
def y = queryContext.get('y',"value")
def yN = y.toInteger()
log.info 'x = ' + x
log.info 'y = ' + y

if (x == 'C' ||  x == 'c' && y == '4') return("Hit")
if (yN == 0 || yN > 5) return("Error1")
def checkX = ['A','a','B','b','C','c','D','d','E','e'].containsAll(x)
if (checkX == false){return("Error2")}</con:dispatchPath><con:dispatchXPath/><con:parameterDispatcherRuleContainer/><con:routeScript/><con:response name="Hit" id="13e72027-3b34-4771-931a-578bd023d584" httpResponseStatus="200" mediaType="application/json"><con:settings/><con:responseContent>{
    "Result":"HIT"
</code>```

HTML/JavaScript code:

```<code><html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            $('#btn').click(function () {
                var obj = { x: $("#xcoord").val(), y: $("#ycoord").val()};
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: "http://x.x.x.x:xxxx/app/",
                    data: JSON.stringify(obj),
                    dataType: "json",
                    success: function (data) {
                        alert(data);
                    }
                });
            });
        });
    </script>
<title>Battleships</title>
</head>
<body>
<form>
X Coordinate:<br>
<input type="text" id="xcoord"><br>
Y Coordinate:<br>
<input type="text" id="ycoord"><br><br>
<input type="button" value="Submit" id="btn">
</form>
</body>
</html>
</code>```

答:
Your question states:

So if I point to the URL: x.x.x.x:xxxx/app/x/c/y/1 then I would get back a response of 'Success'

Therefore you need to send the values in the URL. However your current jQuery code is sending them in the querystring, as you specify the data property of $.ajax, ie.

```<code>x.x.x.x:xxxx/app/?x=c&y=1
</code>```

To fix this, set the URL of the AJAX request like this:

```<code>$('#btn').click(function () {
  $.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    url: "http://x.x.x.x:xxxx/app/x/" + $("#xcoord").val() + '/y/' + $("#ycoord").val(),
    dataType: "json",
    success: function (data) {
      alert(data);
    }
  });
});
</code>```

Body:
I am struggling to send a GET request to my web service.

I have a web service set up that has values assigned to x and y values, where x represents a value A-E and y represents a value 1-5. Let's say that, the values are assigned to C1.

So if I point to the URL: x.x.x.x:xxxx/app/x/c/y/1 then I would get back a response of 'Success' and if x and y represent other values then I have messages for failure and so on for invalid data types.

I cannot seem to get it to work!

The web service contains the following logic:

log.info 'queryContext = ' + queryContext
def x = queryContext.get('x',"value")
def y = queryContext.get('y',"value")
def yN = y.toInteger()
log.info 'x = ' + x
log.info 'y = ' + y

if (x == 'C' ||  x == 'c' && y == '4') return("Hit")
if (yN == 0 || yN > 5) return("Error1")
def checkX = ['A','a','B','b','C','c','D','d','E','e'].containsAll(x)
if (checkX == false){return("Error2")}</con:dispatchPath><con:dispatchXPath/><con:parameterDispatcherRuleContainer/><con:routeScript/><con:response name="Hit" id="13e72027-3b34-4771-931a-578bd023d584" httpResponseStatus="200" mediaType="application/json"><con:settings/><con:responseContent>{
    "Result":"HIT"

HTML/JavaScript code:

<title>Battleships</title>

<form>
X Coordinate:

<input type="text" id="xcoord">

Y Coordinate:

<input type="text" id="ycoord">

<input type="button" value="Submit" id="btn">
</form>

Body:
Your question states:

So if I point to the URL: x.x.x.x:xxxx/app/x/c/y/1 then I would get back a response of 'Success'

Therefore you need to send the values in the URL. However your current jQuery code is sending them in the querystring, as you specify the data property of $.ajax, ie.

x.x.x.x:xxxx/app/?x=c&y=1

To fix this, set the URL of the AJAX request like this:

$('#btn').click(function () {
  $.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    url: "http://x.x.x.x:xxxx/app/x/" + $("#xcoord").val() + '/y/' + $("#ycoord").val(),
    dataType: "json",
    success: function (data) {
      alert(data);
    }
  });
});


问:
Nginx gives an Internal Server Error 500 after I have configured basic auth
I am trying to do basic auth on Nginx. I have version 1.9.3 up and running on Ubuntu 14.04 and it works fine with a simple html file.

Here is the html file:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  "Some shoddy text"
</body>
</html>
</code>```

And here is my nginx.conf file:

```<code>user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    server {
        listen 80;
        server_name 192.168.1.30;
        location / {
            root /www;
            index index.html;
            auth_basic "Restricted";
            auth_basic_user_file /etc/users;
        }
    }
}
</code>```

I used htpasswd to create two users in the "users" file under /etc (username "calvin" password "Calvin", and username "hobbes" password "Hobbes"). It's encrypted by looks like this:

```<code>calvin:$apr1$Q8LGMfGw$RbO.cG4R1riIfERU/175q0
hobbes:$apr1$M9KoUUhh$ayGd8bqqlN989ghWdTP4r/
</code>```

All files belong to root:root. The server IP address is 192.168.1.30 and I am referencing that directly in the conf file.

It all works fine if I comment out the two auth lines and restart nginx, but if I uncomment them, then I do indeed get the username and password prompts when I try to load the site, but immediately thereafter get an Error 500 Internal Server error which seems to persist and I have to restart nginx.

Anybody can see what I'm doing wrong here? I had the same behaviour on the standard Ubuntu 14.04 apt-get version of Nginx (1.4.something) so I don't think it's the nginx version.

答: I just had the same problem - after checking log as suggested by @Drazen Urch I've discovered that the file had root:root permissions - after changing to forge:forge (I'm using Forge with Digital Ocean) - the problem went away.

Body:
I am trying to do basic auth on Nginx. I have version 1.9.3 up and running on Ubuntu 14.04 and it works fine with a simple html file.

Here is the html file:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title></title>

  "Some shoddy text"

And here is my nginx.conf file:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    server {
        listen 80;
        server_name 192.168.1.30;
        location / {
            root /www;
            index index.html;
            auth_basic "Restricted";
            auth_basic_user_file /etc/users;
        }
    }
}

I used htpasswd to create two users in the "users" file under /etc (username "calvin" password "Calvin", and username "hobbes" password "Hobbes"). It's encrypted by looks like this:

calvin:$apr1$Q8LGMfGw$RbO.cG4R1riIfERU/175q0
hobbes:$apr1$M9KoUUhh$ayGd8bqqlN989ghWdTP4r/

All files belong to root:root. The server IP address is 192.168.1.30 and I am referencing that directly in the conf file.

It all works fine if I comment out the two auth lines and restart nginx, but if I uncomment them, then I do indeed get the username and password prompts when I try to load the site, but immediately thereafter get an Error 500 Internal Server error which seems to persist and I have to restart nginx.

Anybody can see what I'm doing wrong here? I had the same behaviour on the standard Ubuntu 14.04 apt-get version of Nginx (1.4.something) so I don't think it's the nginx version.


问:
Can I install and run multiple versions of gcloud (google cloud sdk) on the same machine?
Features and options in gcloud are sometimes deprecated/removed. If CI depends on it and refactoring is not an option while at the same time we need to use new features which come out in later releases can we have multiple versions of gcloud installed on same machines and used concurrently?</p>

答:
There are multiple ways to install Cloud SDK on your machine. For this probably simplest would be to download versioned package from https://cloud.google.com/sdk/downloads#versioned.

For example you can do

```<code>gsutil cp gs://cloud-sdk-release/google-cloud-sdk-VERSION-linux-x86_64.tar.gz .
</code>```

where VERSION is you want to get (for example "161.0.0"). You could also use wget or curl or simply use browser to download the package for your platform.

Then unzip/untar into your desired location for example

```<code>mkdir -p ~/cloudsdk/161.0.0
tar xzf google-cloud-sdk-161.0.0-linux-x86_64.tar.gz -C ~/cloudsdk/161.0.0
</code>```

repeat for some different version:

```<code>mkdir -p ~/cloudsdk/130.0.0
tar xzf google-cloud-sdk-130.0.0-linux-x86_64.tar.gz -C ~/cloudsdk/130.0.0
</code>```

Now you can run gcloud via

```<code>~/cloudsdk/161.0.0/google-cloud-sdk/bin/gcloud components list
</code>```

or

```<code>~/cloudsdk/130.0.0/google-cloud-sdk/bin/gcloud components list
</code>```

Note both version will share same config directory. This is generally undesirable, because there could have been changes between versions in how they treat configuration. To force different Cloud SDK versions use different gcloud configurations set CLOUDSDK_CONFIG environment variable to point to different gcloud config directory. For example:

```<code>$ CLOUDSDK_CONFIG=~/.config/gcloud-legacy ~/cloudsdk/130.0.0/google-cloud-sdk/bin/gcloud
</code>```

Body:
There are multiple ways to install Cloud SDK on your machine. For this probably simplest would be to download versioned package from https://cloud.google.com/sdk/downloads#versioned.

For example you can do

gsutil cp gs://cloud-sdk-release/google-cloud-sdk-VERSION-linux-x86_64.tar.gz .

where VERSION is you want to get (for example "161.0.0"). You could also use wget or curl or simply use browser to download the package for your platform.

Then unzip/untar into your desired location for example

mkdir -p ~/cloudsdk/161.0.0
tar xzf google-cloud-sdk-161.0.0-linux-x86_64.tar.gz -C ~/cloudsdk/161.0.0

repeat for some different version:

mkdir -p ~/cloudsdk/130.0.0
tar xzf google-cloud-sdk-130.0.0-linux-x86_64.tar.gz -C ~/cloudsdk/130.0.0

Now you can run gcloud via

~/cloudsdk/161.0.0/google-cloud-sdk/bin/gcloud components list

or

~/cloudsdk/130.0.0/google-cloud-sdk/bin/gcloud components list

Note both version will share same config directory. This is generally undesirable, because there could have been changes between versions in how they treat configuration. To force different Cloud SDK versions use different gcloud configurations set CLOUDSDK_CONFIG environment variable to point to different gcloud config directory. For example:

$ CLOUDSDK_CONFIG=~/.config/gcloud-legacy ~/cloudsdk/130.0.0/google-cloud-sdk/bin/gcloud


问:
htaccess rewrite and recursive internal redirects
I want to do a simple internal htaccess rewrite which is

```<code>http://localhost/icore4/t9/module/ac/Main.php?do=subject_add
</code>```

to

```<code>http://localhost/icore4/module/ac/Main.php?do=subject_add
</code>```

I am using the following rewrite rule

```<code>RewriteEngine on
RewriteRule ^([A-Za-z0-9]*/)(.*)$ $2 [NC,L]
</code>```

I keep getting page not found error.

When I look at the rewrite log I see that the rewriting is happening recursively.
That is

```<code>http://localhost/icore4/t9/module/ac/Main.php?do=subject_add
</code>```

to

```<code>http://localhost/icore4/module/ac/Main.php?do=subject_add
</code>```

to

```<code>http://localhost/icore4/ac/Main.php?do=subject_add
</code>```

to

```<code>http://localhost/icore4/Main.php?do=subject_add
</code>```

LOG

```<code>127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (1) pass through /icore4/t9/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (3) [perdir F:/xampp/htdocs/icore4/] add path info postfix: F:/xampp/htdocs/icore4/t9 -> F:/xampp/htdocs/icore4/t9/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (3) [perdir F:/xampp/htdocs/icore4/] strip per-dir prefix: F:/xampp/htdocs/icore4/t9/module/ac/Main.php -> t9/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (3) [perdir F:/xampp/htdocs/icore4/] applying pattern '^([A-Za-z0-9]*/)(.*)$' to uri 't9/module/ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (2) [perdir F:/xampp/htdocs/icore4/] rewrite 't9/module/ac/Main.php' -> 'module/ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (3) [perdir F:/xampp/htdocs/icore4/] add per-dir prefix: module/ac/Main.php -> F:/xampp/htdocs/icore4/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (2) [perdir F:/xampp/htdocs/icore4/] strip document_root prefix: F:/xampp/htdocs/icore4/module/ac/Main.php -> /icore4/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (1) [perdir F:/xampp/htdocs/icore4/] internal redirect with /icore4/module/ac/Main.php [INTERNAL REDIRECT]
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (2) init rewrite engine with requested uri /icore4/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (1) pass through /icore4/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (3) [perdir F:/xampp/htdocs/icore4/] strip per-dir prefix: F:/xampp/htdocs/icore4/module/ac/Main.php -> module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (3) [perdir F:/xampp/htdocs/icore4/] applying pattern '^([A-Za-z0-9]*/)(.*)$' to uri 'module/ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (2) [perdir F:/xampp/htdocs/icore4/] rewrite 'module/ac/Main.php' -> 'ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (3) [perdir F:/xampp/htdocs/icore4/] add per-dir prefix: ac/Main.php -> F:/xampp/htdocs/icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (2) [perdir F:/xampp/htdocs/icore4/] strip document_root prefix: F:/xampp/htdocs/icore4/ac/Main.php -> /icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (1) [perdir F:/xampp/htdocs/icore4/] internal redirect with /icore4/ac/Main.php [INTERNAL REDIRECT]
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (2) init rewrite engine with requested uri /icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (1) pass through /icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (3) [perdir F:/xampp/htdocs/icore4/] add path info postfix: F:/xampp/htdocs/icore4/ac -> F:/xampp/htdocs/icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (3) [perdir F:/xampp/htdocs/icore4/] strip per-dir prefix: F:/xampp/htdocs/icore4/ac/Main.php -> ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (3) [perdir F:/xampp/htdocs/icore4/] applying pattern '^([A-Za-z0-9]*/)(.*)$' to uri 'ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (2) [perdir F:/xampp/htdocs/icore4/] rewrite 'ac/Main.php' -> 'Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (3) [perdir F:/xampp/htdocs/icore4/] add per-dir prefix: Main.php -> F:/xampp/htdocs/icore4/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (2) [perdir F:/xampp/htdocs/icore4/] strip document_root prefix: F:/xampp/htdocs/icore4/Main.php -> /icore4/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (1) [perdir F:/xampp/htdocs/icore4/] internal redirect with /icore4/Main.php [INTERNAL REDIRECT]
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (2) init rewrite engine with requested uri /icore4/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (1) pass through /icore4/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (3) [perdir F:/xampp/htdocs/icore4/] strip per-dir prefix: F:/xampp/htdocs/icore4/Main.php -> Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (3) [perdir F:/xampp/htdocs/icore4/] applying pattern '^([A-Za-z0-9]*/)(.*)$' to uri 'Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (1) [perdir F:/xampp/htdocs/icore4/] pass through F:/xampp/htdocs/icore4/Main.php
</code>```

答:
I think this recursion is supposed to happen.

After the url goes through the rewrite rule, it is again passed to the mod_rewrite engine with the same htaccess.  In you case it will always satisfy the Reg exp.

You may put a rewrite cond to avoid the same, something like

```<code>RewriteEngine on
RewriteCond %{QUERY_STRING} !t=(.*)
RewriteRule ^([A-Za-z0-9_-]*/)(.*)$ $2?%{QUERY_STRING}&t=$1 [NC,L]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to do a simple internal htaccess rewrite which is

http://localhost/icore4/t9/module/ac/Main.php?do=subject_add

to

http://localhost/icore4/module/ac/Main.php?do=subject_add

I am using the following rewrite rule

RewriteEngine on
RewriteRule ^([A-Za-z0-9]*/)(.*)$ $2 [NC,L]

I keep getting page not found error.

When I look at the rewrite log I see that the rewriting is happening recursively.
That is

http://localhost/icore4/t9/module/ac/Main.php?do=subject_add

to

http://localhost/icore4/module/ac/Main.php?do=subject_add

to

http://localhost/icore4/ac/Main.php?do=subject_add

to

http://localhost/icore4/Main.php?do=subject_add

LOG

127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (1) pass through /icore4/t9/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (3) [perdir F:/xampp/htdocs/icore4/] add path info postfix: F:/xampp/htdocs/icore4/t9 -> F:/xampp/htdocs/icore4/t9/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (3) [perdir F:/xampp/htdocs/icore4/] strip per-dir prefix: F:/xampp/htdocs/icore4/t9/module/ac/Main.php -> t9/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (3) [perdir F:/xampp/htdocs/icore4/] applying pattern '^([A-Za-z0-9]*/)(.*)$' to uri 't9/module/ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (2) [perdir F:/xampp/htdocs/icore4/] rewrite 't9/module/ac/Main.php' -> 'module/ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (3) [perdir F:/xampp/htdocs/icore4/] add per-dir prefix: module/ac/Main.php -> F:/xampp/htdocs/icore4/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (2) [perdir F:/xampp/htdocs/icore4/] strip document_root prefix: F:/xampp/htdocs/icore4/module/ac/Main.php -> /icore4/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34ad8e8/initial] (1) [perdir F:/xampp/htdocs/icore4/] internal redirect with /icore4/module/ac/Main.php [INTERNAL REDIRECT]
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (2) init rewrite engine with requested uri /icore4/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (1) pass through /icore4/module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (3) [perdir F:/xampp/htdocs/icore4/] strip per-dir prefix: F:/xampp/htdocs/icore4/module/ac/Main.php -> module/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (3) [perdir F:/xampp/htdocs/icore4/] applying pattern '^([A-Za-z0-9]*/)(.*)$' to uri 'module/ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (2) [perdir F:/xampp/htdocs/icore4/] rewrite 'module/ac/Main.php' -> 'ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (3) [perdir F:/xampp/htdocs/icore4/] add per-dir prefix: ac/Main.php -> F:/xampp/htdocs/icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (2) [perdir F:/xampp/htdocs/icore4/] strip document_root prefix: F:/xampp/htdocs/icore4/ac/Main.php -> /icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3481db8/initial/redir#1] (1) [perdir F:/xampp/htdocs/icore4/] internal redirect with /icore4/ac/Main.php [INTERNAL REDIRECT]
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (2) init rewrite engine with requested uri /icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (1) pass through /icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (3) [perdir F:/xampp/htdocs/icore4/] add path info postfix: F:/xampp/htdocs/icore4/ac -> F:/xampp/htdocs/icore4/ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (3) [perdir F:/xampp/htdocs/icore4/] strip per-dir prefix: F:/xampp/htdocs/icore4/ac/Main.php -> ac/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (3) [perdir F:/xampp/htdocs/icore4/] applying pattern '^([A-Za-z0-9]*/)(.*)$' to uri 'ac/Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (2) [perdir F:/xampp/htdocs/icore4/] rewrite 'ac/Main.php' -> 'Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (3) [perdir F:/xampp/htdocs/icore4/] add per-dir prefix: Main.php -> F:/xampp/htdocs/icore4/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (2) [perdir F:/xampp/htdocs/icore4/] strip document_root prefix: F:/xampp/htdocs/icore4/Main.php -> /icore4/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#3487118/initial/redir#2] (1) [perdir F:/xampp/htdocs/icore4/] internal redirect with /icore4/Main.php [INTERNAL REDIRECT]
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (2) init rewrite engine with requested uri /icore4/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (1) pass through /icore4/Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (3) [perdir F:/xampp/htdocs/icore4/] strip per-dir prefix: F:/xampp/htdocs/icore4/Main.php -> Main.php
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (3) [perdir F:/xampp/htdocs/icore4/] applying pattern '^([A-Za-z0-9]*/)(.*)$' to uri 'Main.php'
127.0.0.1 - - [15/Dec/2010:12:57:17 +051800] [localhost/sid#93d158][rid#34895f8/initial/redir#3] (1) [perdir F:/xampp/htdocs/icore4/] pass through F:/xampp/htdocs/icore4/Main.php

Body:
I think this recursion is supposed to happen.

After the url goes through the rewrite rule, it is again passed to the mod_rewrite engine with the same htaccess.  In you case it will always satisfy the Reg exp.

You may put a rewrite cond to avoid the same, something like

RewriteEngine on
RewriteCond %{QUERY_STRING} !t=(.*)
RewriteRule ^([A-Za-z0-9_-]*/)(.*)$ $2?%{QUERY_STRING}&t=$1 [NC,L]


问:
undefined method `permit' for :like:Symbol
This is probably really stupid but, I don't get why this happens.
I have this method.

```<code> def vote_params
    params.fetch(:vote, :like, :hate, :movie_id, {}).permit(:like, :hate, :movie_id)
 end
</code>```

And I call the method that calls it (a default scaffold create method) like this.

```<code><td><%= link_to Vote.where(movie_id: movie.id, like: true).count, upvote_path( :like => true, :hate => false, :movie_id => movie.id) %></td>
</code>```

My route is

```<code>  get 'vote/movies' => 'votes#create', as: :upvote
</code>```

What am I missing?

答:
```<code>params.fetch(:vote, :like, :hate, :movie_id, {})
</code>```

that part is not good, if you need to get parameters of separated scopes you need to do something like this.

```<code>def vote_params
  params.require('vote').permit(:parameter1, :parameter2)
end

def like_params
  params.require('like').permit(:parameter1, :parameter2)
end

def hate_params
  params.require('hate').permit(:parameter1, :parameter2)
end
</code>```

But I believe that the following is what you need

```<code>def vote_params
   params.permit(:like, :hate, :movie_id)
end
</code>```

Body:
This is probably really stupid but, I don't get why this happens.
I have this method.

 def vote_params
    params.fetch(:vote, :like, :hate, :movie_id, {}).permit(:like, :hate, :movie_id)
 end

And I call the method that calls it (a default scaffold create method) like this.

<%= link_to Vote.where(movie_id: movie.id, like: true).count, upvote_path( :like => true, :hate => false, :movie_id => movie.id) %>

My route is

  get 'vote/movies' => 'votes#create', as: :upvote

What am I missing?

Body:
params.fetch(:vote, :like, :hate, :movie_id, {})

that part is not good, if you need to get parameters of separated scopes you need to do something like this.

def vote_params
  params.require('vote').permit(:parameter1, :parameter2)
end

def like_params
  params.require('like').permit(:parameter1, :parameter2)
end

def hate_params
  params.require('hate').permit(:parameter1, :parameter2)
end

But I believe that the following is what you need

def vote_params
   params.permit(:like, :hate, :movie_id)
end


问:
Laravel 5.4 Redirect not working
There is no problem adding data to the database but after adding the data to the database, redirect is not working. It keeps me on the "saving" page

Here is my controller;

```<code>public function postSave(Request $gamedata)
{
    $postcheck = Validator:: make($gamedata -> all(), array(

        'game_name' => 'required|min:3',
        'game_year' => 'numeric',
        'game_type' => 'required',
    ));
   if ($postcheck-> fails()) {
       return redirect() -> to('/')->withErrors($postcheck)->withInput();
   } else {

       $game_name = $gamedata -> input('game_name');
       $game_year = $gamedata -> input('game_year');
       $game_type = $gamedata -> input('game_type');

       $saving= games::create(array('name' =>$game_name , 'year' =>$game_year , 'type' =>$game_type));
   }
if ($saving){
    redirect() -> route('index') ;
}
return null;
}
</code>```

my form;

```<code><div class="col-md-6">
    <form action="{{url('/saving')}}" method="post">
        {{csrf_field()}}
        <div class="form-group">
            <label for="game_name">Game Name</label>
            <input type="text" class="form-control" name="game_name" placeholder="Game Name">
        </div>
        <div class="form-group">
            <label for="exampleInputPassword1">Release Date</label>
            <input type="number" class="form-control" name="game_year" placeholder="Release Date">
        </div>
        <div class="form-group">
            <label for="Game_Type">Game Type</label>
            <input type="text" class="form-control" name="game_type" placeholder="Game type">
        </div>
        <button type="submit" class="btn btn-default" name="gameinfo_save">Add a new game</button>

    </form>
</div>
</code>```

and routes;

```<code>    Route::get('/', array ('as' => 'index', 'uses' =>'homecontroller@getIndex'));
    Route::post('/saving', array ('as' => 'saving', 'uses' =>'homecontroller@postSave'));
</code>```

This not a project, I'm just trying to learn.. So where do i mistake ?

答:
Have a look here, from your code:
redirect() -> route('index') ;

you need to get rid of the spaces as well!
return redirect()->route('index') ;

In this situation the spaces are important, they affect how the code is executed:
[  'foo' =>     'bar' ] (spaces don't matter)

$company->employeeOfTheMonth (valid, works)

$company -> employeeOfTheMonth (invalid, doesn't work)

I'm guessing you're asking that question because Laravel doesn't throw an error - but that doesn't mean it does what you expect (because of the space).

Title: Laravel 5.4 Redirect not working

Body:
There is no problem adding data to the database but after adding the data to the database, redirect is not working. It keeps me on the "saving" page

Here is my controller;

public function postSave(Request $gamedata)
{
    $postcheck = Validator:: make($gamedata -> all(), array(

        'game_name' => 'required|min:3',
        'game_year' => 'numeric',
        'game_type' => 'required',
    ));
   if ($postcheck-> fails()) {
       return redirect() -> to('/')->withErrors($postcheck)->withInput();
   } else {

       $game_name = $gamedata -> input('game_name');
       $game_year = $gamedata -> input('game_year');
       $game_type = $gamedata -> input('game_type');

       $saving= games::create(array('name' =>$game_name , 'year' =>$game_year , 'type' =>$game_type));
   }
if ($saving){
    redirect() -> route('index') ;
}
return null;
}

my form;

    <form action="{{url('/saving')}}" method="post">
        {{csrf_field()}}

            Game Name
            <input type="text" class="form-control" name="game_name" placeholder="Game Name">

            Release Date
            <input type="number" class="form-control" name="game_year" placeholder="Release Date">

            Game Type
            <input type="text" class="form-control" name="game_type" placeholder="Game type">

        <button type="submit" class="btn btn-default" name="gameinfo_save">Add a new game</button>

    </form>

and routes;

    Route::get('/', array ('as' => 'index', 'uses' =>'homecontroller@getIndex'));
    Route::post('/saving', array ('as' => 'saving', 'uses' =>'homecontroller@postSave'));

This not a project, I'm just trying to learn.. So where do i mistake ?


问:
Error creating AWS CloudFormation stack : Cannot restore this instance based in Windows OS
I am using the following Cloudformation Json to create a new Sql Server RDS instance of more storage from an existing snapshot. THe Json is valid and i am able to initiate the stack creation. Its failing with the error </p>

<p>"Cannot restore this instance based in Windows OS because the request has a different storage type than the backup". What does this mean ? Am i missing any thing ?</p>

```<code>{
    "AWSTemplateFormatVersion" : "2010-09-09",
    "Resources" : {
        "DBInstance" : {
            "Type": "AWS::RDS::DBInstance",
            "Properties": {
                "DBInstanceClass" : "db.m2.xlarge",
                "AllocatedStorage" : "400",
                "MasterUsername" : "myusername",
                "MasterUserPassword" : "mypassword",
                "DBSnapshotIdentifier":"xxxxxxxx-2016-07-13-17-00"
            }
        }
    }
}
</code>```

答:
(year later, in case future googlers)

Had the same issue, however I missed "StorageType" (I see OP also missed it and probably added it at the same time as Iops). "StorageType" defaults to "standard" (i.e. magnetic) when using CloudFormation, however defaults to "gp2" (SSD) when using the console.

Therefore a backup created from a console created DB is likely to be using SSD, but the instance generated in CF is using Magnetic, unless "StorageType" is declared as "gp2".

Body:
I am using the following Cloudformation Json to create a new Sql Server RDS instance of more storage from an existing snapshot. THe Json is valid and i am able to initiate the stack creation. Its failing with the error

"Cannot restore this instance based in Windows OS because the request has a different storage type than the backup". What does this mean ? Am i missing any thing ?

{
    "AWSTemplateFormatVersion" : "2010-09-09",
    "Resources" : {
        "DBInstance" : {
            "Type": "AWS::RDS::DBInstance",
            "Properties": {
                "DBInstanceClass" : "db.m2.xlarge",
                "AllocatedStorage" : "400",
                "MasterUsername" : "myusername",
                "MasterUserPassword" : "mypassword",
                "DBSnapshotIdentifier":"xxxxxxxx-2016-07-13-17-00"
            }
        }
    }
}


问:
Creating a new NodeId in OPC UA
Dear stackoverflowers,

If I want to make a NodeId in the Identifiers.java file of Eclipse Milo with Ns=3 and S='Counters' what kind of init(number) should I have?

The return method for the value is:

```<code> private static NodeId init(int value) {
         return new NodeId(Unsigned.ushort(0), Unsigned.uint(value));
     }
</code>```

This is the best way I could explain it because I'm not sure myself.

Thanks in advance!

答:
That file is for the built-in NodeIds belonging to namespace 0. You shouldn't be defining nodes in there.

You're free to define your own NodeIds ahead of time but the only answer to which namespace index they belong to is "it depends". The index should correspond to the index in the NamespaceUri array of the URI belonging to the Namespace you add them to...

Title: Creating a new NodeId in OPC UA

Body:
Dear stackoverflowers,

If I want to make a NodeId in the Identifiers.java file of Eclipse Milo with Ns=3 and S='Counters' what kind of init(number) should I have?

The return method for the value is:

 private static NodeId init(int value) {
         return new NodeId(Unsigned.ushort(0), Unsigned.uint(value));
     }

This is the best way I could explain it because I'm not sure myself.

Thanks in advance!


问:
spring-rabbit 1.7.2+ autorecovery broken?
Is it possible the connection auto recovery is broken as of spring-rabbit 1.7.2 ?

A test of listeners succeed until upgrading spring-rabbit to 1.7.2. The next version, 1.7.3, also fails. The test is simple enough: Start the listener, stop the RabbitMQ server, start the Rabbit MQ server and watch the listener getting messages.

However, strangely enough, the auto recovery does work for 1.7.2 and higher when not calling "setAutomaticRecoveryEnabled()". Or calling it with false. Which should disable the auto recovery.

The Spring config (in Scala)

```<code>@Configuration
@ComponentScan(Array("com.foo"))
@EnableRabbit
class AMQPConfig {

  @Bean
  def rabbitListenerContainerFactory: SimpleRabbitListenerContainerFactory = {
    val factory = new SimpleRabbitListenerContainerFactory
    factory.setConnectionFactory(connectionFactory())
    factory.setConcurrentConsumers(1)
    factory.setMaxConcurrentConsumers(1)
    factory
  }

  @Bean
  def rabbitTemplate(): RabbitTemplate = {
    val template = new RabbitTemplate(connectionFactory())
    template.setRoutingKey("key")
    template.setExchange("xchange")
    template
  }

  @Bean
  def connectionFactory(): ConnectionFactory = {
    val factory = new CachingConnectionFactory("localhost")
    factory.setUsername("foo")
    factory.setPassword("bar")
    factory.setVirtualHost("fooman")
    factory.setPort(5672)
    factory.getRabbitConnectionFactory.setAutomaticRecoveryEnabled(true)
    factory.getRabbitConnectionFactory.setRequestedHeartbeat(120)
    factory
  }
}
</code>```

The listener

```<code>@Component
class QueueListener {

  @RabbitListener(id = "listen", containerFactory = "rabbitListenerContainerFactory", queues = Array("q"))
  def onMessage(message: String): Unit = {
    QueueListener.count.incrementAndGet()
    println("GOT MESSAGE: " + message)
  }

}

object QueueListener {
  val count = new AtomicInteger(0)
}
</code>```

答:
Spring AMQP has had its own recovery mechanism since day 1; it predates auto recovery in the client library by several years.

If you create a CachingConnectionFactory with the constructor that takes a preconfigured RabbitMQ ConnectionFactory, we emit this message...

```<code>if (rabbitConnectionFactory.isAutomaticRecoveryEnabled()) {
    logger.warn("***\nAutomatic Recovery is Enabled in the provided connection factory;\n"
            + "while Spring AMQP is compatible with this feature, it\n"
            + "prefers to use its own recovery mechanisms; when this option is true, you may receive\n"
            + "'AutoRecoverConnectionNotCurrentlyOpenException's until the connection is recovered.");
}
</code>```

When you set the option the way you are doing it we, of course, can't detect that and won't emit the message.

In general, the connection will be recovered faster by Spring AMQP (on the sending side), recovery on the consumer side has similar characteristics to the client (with default configuration).

That said, as the log message indicates, using auto recovery shouldn't hurt anything, it will just cause a recovery delay on the producer side.

I have not seen the behavior you describe; perhaps it has something to do with you using Scala, or something else in your environment; a DEBUG log spanning the shutdown/restart and failure to recover would be useful if you really must use the client's auto recovery for some reason.

Body:
Is it possible the connection auto recovery is broken as of spring-rabbit 1.7.2 ?

A test of listeners succeed until upgrading spring-rabbit to 1.7.2. The next version, 1.7.3, also fails. The test is simple enough: Start the listener, stop the RabbitMQ server, start the Rabbit MQ server and watch the listener getting messages.

However, strangely enough, the auto recovery does work for 1.7.2 and higher when not calling "setAutomaticRecoveryEnabled()". Or calling it with false. Which should disable the auto recovery.

The Spring config (in Scala)

@Configuration
@ComponentScan(Array("com.foo"))
@EnableRabbit
class AMQPConfig {

  @Bean
  def rabbitListenerContainerFactory: SimpleRabbitListenerContainerFactory = {
    val factory = new SimpleRabbitListenerContainerFactory
    factory.setConnectionFactory(connectionFactory())
    factory.setConcurrentConsumers(1)
    factory.setMaxConcurrentConsumers(1)
    factory
  }

  @Bean
  def rabbitTemplate(): RabbitTemplate = {
    val template = new RabbitTemplate(connectionFactory())
    template.setRoutingKey("key")
    template.setExchange("xchange")
    template
  }

  @Bean
  def connectionFactory(): ConnectionFactory = {
    val factory = new CachingConnectionFactory("localhost")
    factory.setUsername("foo")
    factory.setPassword("bar")
    factory.setVirtualHost("fooman")
    factory.setPort(5672)
    factory.getRabbitConnectionFactory.setAutomaticRecoveryEnabled(true)
    factory.getRabbitConnectionFactory.setRequestedHeartbeat(120)
    factory
  }
}

The listener

@Component
class QueueListener {

  @RabbitListener(id = "listen", containerFactory = "rabbitListenerContainerFactory", queues = Array("q"))
  def onMessage(message: String): Unit = {
    QueueListener.count.incrementAndGet()
    println("GOT MESSAGE: " + message)
  }

}

object QueueListener {
  val count = new AtomicInteger(0)
}

Body:
Spring AMQP has had its own recovery mechanism since day 1; it predates auto recovery in the client library by several years.

If you create a CachingConnectionFactory with the constructor that takes a preconfigured RabbitMQ ConnectionFactory, we emit this message...

if (rabbitConnectionFactory.isAutomaticRecoveryEnabled()) {
    logger.warn("***\nAutomatic Recovery is Enabled in the provided connection factory;\n"
            + "while Spring AMQP is compatible with this feature, it\n"
            + "prefers to use its own recovery mechanisms; when this option is true, you may receive\n"
            + "'AutoRecoverConnectionNotCurrentlyOpenException's until the connection is recovered.");
}

When you set the option the way you are doing it we, of course, can't detect that and won't emit the message.

In general, the connection will be recovered faster by Spring AMQP (on the sending side), recovery on the consumer side has similar characteristics to the client (with default configuration).

That said, as the log message indicates, using auto recovery shouldn't hurt anything, it will just cause a recovery delay on the producer side.

I have not seen the behavior you describe; perhaps it has something to do with you using Scala, or something else in your environment; a DEBUG log spanning the shutdown/restart and failure to recover would be useful if you really must use the client's auto recovery for some reason.


问:
Android nestedScrollview And ViewPager not working together
I am developing an app which has a viewPager and it should scroll

```<code>   <android.support.v4.widget.NestedScrollView
        android:id="@+id/activity_main_nestedscrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v4.view.ViewPager
            android:id="@+id/activity_main_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FFA0"/>

    </android.support.v4.widget.NestedScrollView>
</code>```

but viewPager is not visible if i use above code

答:
You are doing it wrong. This is the correct way:

```<code>    <android.support.v4.view.ViewPager
        android:id="@+id/activity_main_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFA0"/>
</code>```

Fragment layout parent view should be

```<code><android.support.v4.widget.NestedScrollView
    android:id="@+id/activity_main_nestedscrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</android.support.v4.widget.NestedScrollView>
</code>```

Body:
I am developing an app which has a viewPager and it should scroll

   <android.support.v4.widget.NestedScrollView
        android:id="@+id/activity_main_nestedscrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v4.view.ViewPager
            android:id="@+id/activity_main_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FFA0"/>

    </android.support.v4.widget.NestedScrollView>

but viewPager is not visible if i use above code

Body:
You are doing it wrong. This is the correct way:

    <android.support.v4.view.ViewPager
        android:id="@+id/activity_main_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFA0"/>

Fragment layout parent view should be

<android.support.v4.widget.NestedScrollView
    android:id="@+id/activity_main_nestedscrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</android.support.v4.widget.NestedScrollView>

ContentLicense: CC BY-SA 4.0


问:
Sum Expression Access Query for Completed Fields
I am trying to write a code that will sum the prices of all the orders that come up when I fill out the query. For example, if I enter the ID range 1-60, I want there to be a sum column created that then sums up all the prices of ID's 1-60.

I thought it would be simple enough to just create a SUM(.....) AS Exp 1, but it tells me that there is a problem with the ID and aggregate function.

My current code looks like this:

```<code>SELECT table.ID, table.Price, SUM(table.Price) AS Exp 1
FROM table
WHERE table.ID BETWEEN StartID AND EndID
</code>```

Thank you for any help

EDIT: I should've specified this earlier, but I want to be able to see the individual prices, as well as a new column with the sum of all these prices. I plan on adding some more columns of data into the table later on.

答:
If you want the sum over all the rows, then only include that in the SELECT:

```<code>SELECT SUM(table.Price) AS Exp1
FROM table
WHERE table.ID BETWEEN StartID AND EndID
</code>```

Body:
I am trying to write a code that will sum the prices of all the orders that come up when I fill out the query. For example, if I enter the ID range 1-60, I want there to be a sum column created that then sums up all the prices of ID's 1-60.

I thought it would be simple enough to just create a SUM(.....) AS Exp 1, but it tells me that there is a problem with the ID and aggregate function.

My current code looks like this:

SELECT table.ID, table.Price, SUM(table.Price) AS Exp 1
FROM table
WHERE table.ID BETWEEN StartID AND EndID

Thank you for any help

EDIT: I should've specified this earlier, but I want to be able to see the individual prices, as well as a new column with the sum of all these prices. I plan on adding some more columns of data into the table later on.

Body:
If you want the sum over all the rows, then only include that in the SELECT:

SELECT SUM(table.Price) AS Exp1
FROM table
WHERE table.ID BETWEEN StartID AND EndID


问:
Getting an array from AJAX call
I'm working on a summernote editor and trying to implement the "mention" feature by pulling usernames from a database.

```<code>match: /\B@(\w*)$/,
            mentions:function(keyword, callback) {
            $.ajax({
                    url: document.location.origin+"/topic/groupusers/"+topic_cat,
                    type: 'GET',
                    success: function(callback) {
                        callback = $(callback).filter('.mentiondata').text();
                    }
                });
            },

            search: function (keyword, callback) {
                callback($.grep(this.mentions, function (item) {
                    return item.indexOf(keyword) == 0;
                  }));
            },
            content: function (item) {
                return '@' + item;
            }
</code>```

The mention attribute needs to have this format:
mentions: ['jayden', 'sam', 'alvin', 'david'],

when I console.log callback inside the success function that's what I get. However, it doesn't work on search event and gives me  item is undefined error

答:
Pass keyword or your parameters in mention function while search.

Return value of success in mentions function

```<code> match: /\B@(\w*)$/,
  mentions: function(keyword) {
    $.ajax({
      url: document.location.origin + "/topic/groupusers/" + topic_cat,
      type: 'GET',
      success: function(result) {
        return $(result).filter('.mentiondata').text();
      }
    });
  },
  search: function(keyword, callback) {
    callback($.grep(this.mentions(keyword), function(item) {
      return item.indexOf(keyword) == 0;
    }));
  },
  content: function(item) {
    return '@' + item;
  }
</code>```

Sample code

Title: Getting an array from AJAX call

Body:
I'm working on a summernote editor and trying to implement the "mention" feature by pulling usernames from a database.

match: /\B@(\w*)$/,
            mentions:function(keyword, callback) {
            $.ajax({
                    url: document.location.origin+"/topic/groupusers/"+topic_cat,
                    type: 'GET',
                    success: function(callback) {
                        callback = $(callback).filter('.mentiondata').text();
                    }
                });
            },

            search: function (keyword, callback) {
                callback($.grep(this.mentions, function (item) {
                    return item.indexOf(keyword) == 0;
                  }));
            },
            content: function (item) {
                return '@' + item;
            }

The mention attribute needs to have this format:
mentions: ['jayden', 'sam', 'alvin', 'david'],

when I console.log callback inside the success function that's what I get. However, it doesn't work on search event and gives me  item is undefined error

Body:
Pass keyword or your parameters in mention function while search.

Return value of success in mentions function

 match: /\B@(\w*)$/,
  mentions: function(keyword) {
    $.ajax({
      url: document.location.origin + "/topic/groupusers/" + topic_cat,
      type: 'GET',
      success: function(result) {
        return $(result).filter('.mentiondata').text();
      }
    });
  },
  search: function(keyword, callback) {
    callback($.grep(this.mentions(keyword), function(item) {
      return item.indexOf(keyword) == 0;
    }));
  },
  content: function(item) {
    return '@' + item;
  }

Sample code


问:
customizing the css for audio tag
i have this audio control and i am trying to change even the color of the player but i can't target it i found some posts talking about doing this using javascript is that the only way to write css for it.

```<code><audio controls class="radio-audio">
   <source src="" type="audio/mpeg"></audio>
</code>```

i tried to write some code like this found it somewhere on the internet but still i don't see any changes.

it is all hover and focus not doing much

```<code>.radio-audio:hover, .radio-audio:focus, .radio-audio:active {
    -webkit-box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    -moz-box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    -webkit-transform: scale(1.05);
    -moz-transform: scale(1.05);
    transform: scale(1.05);
}

.radio-audio {
    -webkit-transition: all 0.5s linear;
    -moz-transition: all 0.5s linear;
    -o-transition: all 0.5s linear;
    transition: all 0.5s linear;
    -moz-box-shadow: 2px 2px 4px 0px #006773;
    -webkit-box-shadow: 2px 2px 4px 0px #006773;
    box-shadow: 2px 2px 4px 0px #006773;
    -moz-border-radius: 7px 7px 7px 7px;
    -webkit-border-radius: 7px 7px 7px 7px;
    border-radius: 7px 7px 7px 7px;
}
</code>```

答: Currently there is no way to style HTML5  players using CSS. Instead, you can turn off the control attribute, and implement your own controls using JS. If you don't want to do it yourself, you can use something like jPlayer.

Title: customizing the css for audio tag

Body:
i have this audio control and i am trying to change even the color of the player but i can't target it i found some posts talking about doing this using javascript is that the only way to write css for it.

<audio controls class="radio-audio">
   <source src="" type="audio/mpeg"></audio>

i tried to write some code like this found it somewhere on the internet but still i don't see any changes.

it is all hover and focus not doing much

.radio-audio:hover, .radio-audio:focus, .radio-audio:active {
    -webkit-box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    -moz-box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    -webkit-transform: scale(1.05);
    -moz-transform: scale(1.05);
    transform: scale(1.05);
}

.radio-audio {
    -webkit-transition: all 0.5s linear;
    -moz-transition: all 0.5s linear;
    -o-transition: all 0.5s linear;
    transition: all 0.5s linear;
    -moz-box-shadow: 2px 2px 4px 0px #006773;
    -webkit-box-shadow: 2px 2px 4px 0px #006773;
    box-shadow: 2px 2px 4px 0px #006773;
    -moz-border-radius: 7px 7px 7px 7px;
    -webkit-border-radius: 7px 7px 7px 7px;
    border-radius: 7px 7px 7px 7px;
}


问:
What should the output layer of my CNN look like?
I am running a model to detect a few interesting features in an image. I have a set of images measuring 600x200 px. These images have features such as rock fragments that I would like to identify. Imagine a (4x12) grid overlayed on the image I can produce annotations manually using an annotator tool such as ((4,9), (3,10), (3,11), (3,12)) to identify the interesting cells in the image. I can build a CNN model with Keras with the input as a grayscale image. But how should I encode the output. One way that seems intuitive to me is to treat it as a sparse matrix of shape (12,4,1) and only the interesting cells have 1 while others have 0.

Is there a better way to encode the outputs?

What should be the activation function on the last layer be? I am using ReLU for the hidden layers.

What should the loss function be? Will mean_squared_error work?

答:
Your problem is really similiar to both detection and segmentation problems (you can read about it e.g. here. The approach you proposed is reasonable because in both detection and segmentation tasks computing the feature map you proposed is an usual part of training pipeline. However - there are several problem you might come across:

memory issues: you need to either deal with sparse tensors or use generators in order to deal with memory problems,

loss and activation: loss and activation for segmentation are currently not supported by Keras API so you need to implement it on your own. Here and here you can find an examples on how to tackle this problem.

In case of detection only (not classification of this points) I would advice you to use sigmoid and binary_crossentropy. In case of classification softmax and categorical_crossentropy.

Of course - there are other ways on how to tackle this problem. One could solve it as a regression where you need to predict the pixels where there is something interesting. But dealing with varying input in Keras is rather cumbersome.


问:
Replacing values in numpy array based on inequalities
Given a numpy array, I would like to replace its values based on inequalities. For example, given

```<code>x=np.array([0.3,7,8,-5.5,1,0.1])
</code>```

I want to replace the values that are smaller than 0 with 0, those that are between 0 and 5 would be replaced by 1, and the rest would be replaced with 2. So I want to get:

```<code>x=np.array([1,2,2,0,1,1])
</code>```

I could do that with pandas.cut as follows:

```<code>pandas.cut(pandas.DataFrame(x).iloc[:,0],[-np.inf,0,5,np.inf],labels=[0,1,2],right=False)
</code>```

but I was wondering if there is a more direct way to do that using numpy itself. Note that I could have more than 3 categories, which is why I was looking for something more systematic that behaves similarly to pandas.cut.

答:
Perfect setup to leverage np.searchsorted -

```<code>np.searchsorted([0,5],x)
</code>```

This is extensible to incorporate generic number of bin elements. Thus, generically put -

```<code>bins = [0,5]
out = np.searchsorted(bins,x)
</code>```

Sample runs -

```<code>In [46]: x
Out[46]: array([ 0.3,  7. ,  8. , -5.5,  1. ,  0.1])

In [47]: np.searchsorted([0,5],x)
Out[47]: array([1, 2, 2, 0, 1, 1])

In [55]: np.searchsorted([0,2,5],x)
Out[55]: array([1, 3, 3, 0, 1, 1])

In [60]: np.searchsorted([0,2,5,7],x)
Out[60]: array([1, 3, 4, 0, 1, 1])
</code>```

Body:
Given a numpy array, I would like to replace its values based on inequalities. For example, given

x=np.array([0.3,7,8,-5.5,1,0.1])

I want to replace the values that are smaller than 0 with 0, those that are between 0 and 5 would be replaced by 1, and the rest would be replaced with 2. So I want to get:

x=np.array([1,2,2,0,1,1])

I could do that with pandas.cut as follows:

pandas.cut(pandas.DataFrame(x).iloc[:,0],[-np.inf,0,5,np.inf],labels=[0,1,2],right=False)

but I was wondering if there is a more direct way to do that using numpy itself. Note that I could have more than 3 categories, which is why I was looking for something more systematic that behaves similarly to pandas.cut.

Body:
Perfect setup to leverage np.searchsorted -

np.searchsorted([0,5],x)

This is extensible to incorporate generic number of bin elements. Thus, generically put -

bins = [0,5]
out = np.searchsorted(bins,x)

Sample runs -

In [46]: x
Out[46]: array([ 0.3,  7. ,  8. , -5.5,  1. ,  0.1])

In [47]: np.searchsorted([0,5],x)
Out[47]: array([1, 2, 2, 0, 1, 1])

In [55]: np.searchsorted([0,2,5],x)
Out[55]: array([1, 3, 3, 0, 1, 1])

In [60]: np.searchsorted([0,2,5,7],x)
Out[60]: array([1, 3, 4, 0, 1, 1])


问:
Handle dynamic Xpath in Selenium Webdriver
In Selenium I need to handle the XPath which is being dynamic on every next page.

Here, I am trying to click on the same element at every page.

Below are the Xpath of the same Web-element with the only difference with div[] tag

Page 1:

```<code>.//*[@id='PageScrollArea']/div/div/div[4]/div/div/table/tbody/tr[3]/td/table/tbody/tr[1]/td/div/div[1]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
</code>```

Page 2:

```<code>.//*[@id='PageScrollArea']/div/div/div[4]/div/div/table/tbody/tr[3]/td/table/tbody/tr[1]/td/div/div[2]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
</code>```

Page 3:

```<code>.//*[@id='PageScrollArea']/div/div/div[4]/div/div/table/tbody/tr[3]/td/table/tbody/tr[1]/td/div/div[1]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
</code>```

I am not sure how to handle this dynamic behavior of div[] tag:

```<code>.... /div[1]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
.... /div[2]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
.... /div[1]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
.... /div[2]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
</code>```

答:
there's no way to handle dynamic path in this case, that's why you should use relative path like:

```<code>//parent//child-few-layers-below
</code>```

please provide html of searched element and we'll help to write path

Body:
In Selenium I need to handle the XPath which is being dynamic on every next page.

Here, I am trying to click on the same element at every page.

Below are the Xpath of the same Web-element with the only difference with div[] tag

Page 1:

.//*[@id='PageScrollArea']/div/div/div[4]/div/div/table/tbody/tr[3]/td/table/tbody/tr[1]/td/div/div[1]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img

Page 2:

.//*[@id='PageScrollArea']/div/div/div[4]/div/div/table/tbody/tr[3]/td/table/tbody/tr[1]/td/div/div[2]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img

Page 3:

.//*[@id='PageScrollArea']/div/div/div[4]/div/div/table/tbody/tr[3]/td/table/tbody/tr[1]/td/div/div[1]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img

I am not sure how to handle this dynamic behavior of div[] tag:

.... /div[1]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
.... /div[2]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
.... /div[1]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img
.... /div[2]/table/tbody/tr[3]/td[3]/table/tbody/tr/td/img

Body:
there's no way to handle dynamic path in this case, that's why you should use relative path like:

//parent//child-few-layers-below

please provide html of searched element and we'll help to write path


问:
How to change a text based onclick with JavaScript?
Good evening everybody!

Well, I am studying JavaScript at the moment, and I reachead the point in where I need, based on clicked text (button, ... it doesn't matter, I guess).

For example:

This message should be edited.

Two choices: ES - EN

If choice "ES" is clicked/selected, then:

This message has been edited to ES.

Otherwise, if choice "EN" is clicked/selected, then:

This message has been edited to EN.

I think this could have been achieved with an if in a script, but the problem is how to tell the script which option has been chosen, if "ES" or "EN".

I have this:

```<code><p id="demo">This message should be edited.<p>
<a href="#" id="ES" onclick="func();">ES</a> - <a href="#" id="EN" onclick="func();">EN</a> - <a href="#" id="JP" onclick="func();">JP</a>
</code>```

And as I said, the problem is that I don't know how to tell the script what has been clicked/selected.

Thank you for any help you may give me (if possible, an explanation with or over a solution would be amazing because I want to learn and understand, not to solve this problem without being able to solve the same thing or similar in a future).

答:
Pass this in your func(), this will allow you to access the current clicked element.

var text = "This message should be edited to ";
function func(ele){
  console.log(ele.innerHTML);
  document.getElementById('demo').innerText = text + ele.innerText + ".";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo">This message should be edited.<p>
ES - EN - JP</code>```

Body:
Good evening everybody!

Well, I am studying JavaScript at the moment, and I reachead the point in where I need, based on clicked text (button, ... it doesn't matter, I guess).

For example:

This message should be edited.

Two choices: ES - EN

If choice "ES" is clicked/selected, then:

This message has been edited to ES.

Otherwise, if choice "EN" is clicked/selected, then:

This message has been edited to EN.

I think this could have been achieved with an if in a script, but the problem is how to tell the script which option has been chosen, if "ES" or "EN".

I have this:

This message should be edited.

ES - EN - JP

And as I said, the problem is that I don't know how to tell the script what has been clicked/selected.

Thank you for any help you may give me (if possible, an explanation with or over a solution would be amazing because I want to learn and understand, not to solve this problem without being able to solve the same thing or similar in a future).

Body:
Pass this in your func(), this will allow you to access the current clicked element.

var text = "This message should be edited to ";
function func(ele){
  console.log(ele.innerHTML);
  document.getElementById('demo').innerText = text + ele.innerText + ".";
}

<p id="demo">This message should be edited.<p>
<a href="#" id="ES" onclick="func(this);">ES</a> - <a href="#" id="EN" onclick="func(this);">EN</a> - <a href="#" id="JP" onclick="func(this);">JP</a>