问:
Ajax Loader on button click - error with code
I've followed other advice regarding showing an Ajax Loading Gif on button click to submit a form, however I can't seem to get the code working.

Any help greatly appreciated.

```<code>    <p>
        <input type="hidden" name="job_manager_form" value="<?php echo $form; ?>" />
        <input type="hidden" name="job_id" value="<?php echo esc_attr( $job_id ); ?>" />
        <input type="hidden" name="step" value="<?php echo esc_attr( $step ); ?>" />

                    <?php if($job_id){ ?>
                    <img src="https://www.salusa.co.uk/wp-content/uploads/2017/12/ajax-loader.gif" id="img" style="display:none"/ >
                    <input type="submit" id="submitjob" name="submit_job" class="button" value="Update my service profile" />

                    <?php } else { ?>
                     <img src="https://www.salusa.co.uk/wp-content/uploads/2017/12/ajax-loader.gif" id="img" style="display:none"/ >
                    <input type="submit" id="submitjob" name="submit_job" class="button" value="Submit profile for admin approval" />
                    <?php } ?>

    </p>

<script>
                    $('#submitjob').click(function(){
                    $('#img').show();
                    $.ajax({
                    ....
                    success:function(result){
                    $('#img').hide();  //<--- hide again
}
}
</script>
</code>```

答:
The Code won't work if your Ajax request is having the errors or if you don't include necessary scripts for jquery. Based on what you did above, I'm having the working example, have it for your reference:

  <title>Ajax Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <input type="hidden" name="job_manager_form" value="<?php echo $form; ?>" />
  <input type="hidden" name="job_id" value="<?php echo esc_attr( $job_id ); ?>" />
  <input type="hidden" name="step" value="<?php echo esc_attr( $step ); ?>" />

  <input type="submit" id="submitjob" name="submit_job" class="button" value="Update my service profile" />

```

Body:
I've followed other advice regarding showing an Ajax Loading Gif on button click to submit a form, however I can't seem to get the code working.

Any help greatly appreciated.

        <input type="hidden" name="job_manager_form" value="<?php echo $form; ?>" />
        <input type="hidden" name="job_id" value="<?php echo esc_attr( $job_id ); ?>" />
        <input type="hidden" name="step" value="<?php echo esc_attr( $step ); ?>" />

                    <?php if($job_id){ ?>

                    <input type="submit" id="submitjob" name="submit_job" class="button" value="Update my service profile" />

                    <?php } else { ?>

                    <input type="submit" id="submitjob" name="submit_job" class="button" value="Submit profile for admin approval" />
                    <?php } ?>

Body:
The Code won't work if your Ajax request is having the errors or if you don't include necessary scripts for jquery. Based on what you did above, I'm having the working example, have it for your reference:

<html>

<head>
  <title>Ajax Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>

<body>
  <input type="hidden" name="job_manager_form" value="<?php echo $form; ?>" />
  <input type="hidden" name="job_id" value="<?php echo esc_attr( $job_id ); ?>" />
  <input type="hidden" name="step" value="<?php echo esc_attr( $step ); ?>" />

  <!-- Here comes your if condition -->
  <img src="https://www.salusa.co.uk/wp-content/uploads/2017/12/ajax-loader.gif" id="img" style="display:none" />
  <input type="submit" id="submitjob" name="submit_job" class="button" value="Update my service profile" />

  <div id="content"></div>
</body>

<script>
  $('#submitjob').click(function() {
    $('#img').show();
    $.ajax({
      url: 'https://jsonplaceholder.typicode.com/posts/1',
      type: 'GET',

      error: function() {
        $('#content').html('<p>An error has occurred</p>');
      },
      dataType: 'json',
      success: function(result) {
        $('#content').html("data Received" + result);
        $('#img').hide(); //<--- hide again
      },
    });
  });
</script>
</body>

</html>


来源: stackexchange

问:
C string arrays

Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

```<code>char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";
</code>```

It won't compile saying Incompatible types in assignment. What am I doing wrong?

答:
You have to increase the size of the words and use strcpy():

```<code>char result[3][8];    // at least 8!

strcpy(result[0], "horse");
strcpy(result[1], "pig");
strcpy(result[2], "chicken");
</code>```

ContentLicense: CC BY-SA 2.5

Title: C string arrays

Body:
Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

It won't compile saying Incompatible types in assignment. What am I doing wrong?

Body:
You have to increase the size of the words and use strcpy():

char result[3][8];    // at least 8!

strcpy(result[0], "horse");
strcpy(result[1], "pig");
strcpy(result[2], "chicken");


问:
Finding users who has signed between given dates using Mongoose
I have user model like this

```<code>const guestSchema = mongoose.Schema({
  facebook: {
    id: String,
    token: String,
    email: String,
    name: String,
    phone: String,
    dates: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "loginDate"
      }
    ]
  }
});
</code>```

and loginDate model

```<code>const loginDateSchema = mongoose.Schema({
  loginDate: Date
});
</code>```

Every time user signs in current Date is added.
How can I find users who have signed in between given date?
I did below but I am getting empty result

```<code>Guest.find({ "facebook.id": { $exists: true } })
      .populate("facebook.dates")
      .find({ "facebook.dates": { $gte: startDate,$lte: endDate } })
      .exec((err, foundUsers) => {
        res.render("./admin/send", {
          facebookUsers: foundUsers
        });
      });
</code>```

Sample JSON

```<code>{
    "_id" : ObjectId("5a1a838f58eb1a50c408de84"),
    "facebook" : {
        "email" : "sample@yahoo.com",
        "name" : "Sample user",
        "id" : "12345",
        "dates" : [
            ObjectId("5a1a838f58eb1a50c408de85"),
            ObjectId("5a1a839258eb1a50c408de86"),
            ObjectId("5a1a839358eb1a50c408de87"),
            ObjectId("5a1a839758eb1a50c408de88"),
            ObjectId("5a1aa17058eb1a50c408de8b")
        ]
    },
    "__v" : NumberInt(5)
}
</code>```

LoginDate

```<code>{
    "_id" : ObjectId("5a1a839358eb1a50c408de87"),
    "loginDate" : ISODate("2017-11-26T09:04:19.107+0000"),
    "__v" : NumberInt(0)
}
</code>```

答:
I think the issue is with your date which you are passing into find function on line

```<code> .find({ "facebook.dates": { $gte: startDate,$lte: endDate } })
</code>```

You need to pass a date object and not a date string.

Here is my solution which is working fine for me

Facebook model

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.Promise = global.Promise;

var facebookSchema = new Schema({
    id: String,
    token: String,
    email: String,
    name: String,
    phone: String,
    logindate: Date
},
    {
        versionKey: false
    }
);

module.exports = mongoose.model('Facebook', facebookSchema);
</code>```

Here is data

```<code>[
   {
      "_id":"5a2949d40591a2192c8fad6b",
      "logindate":"2016-10-10T06:28:37.146Z",
      "phone":"03006351611",
      "name":"mainuhassan",
      "email":"mainuhassan@gmail.com",
      "token":"MxuXmblL56aqt17aHh1rqcyeHc0E4CwQ",
      "id":"100"
   },
   {
      "_id":"5a294cd26c3e661514f3699e",
      "logindate":"2015-10-10T06:28:37.146Z",
      "phone":"03006351611",
      "name":"mainuhassan1",
      "email":"mainuhassan1@gmail.com",
      "token":"MxuXmblL56aqt17aHh1rqcyeHc0E4CwQ",
      "id":"100"
   },
   {
      "_id":"5a294cfe75e2ba2778e9f249",
      "logindate":"2017-10-10T06:28:37.146Z",
      "phone":"03006351612",
      "name":"mainuhassan2",
      "email":"mainuhassan2@gmail.com",
      "token":"MxuXmblL56aqt17aHh1rqcyeHc0E4CwQ",
      "id":"100"
   }
]
</code>```

And here is my code for getting data between dates

```<code>Facebook.find({ logindate: { "$gte": new Date("2016-10-10T06:28:37.146Z"), "$lte": new Date("2017-10-10T06:28:37.146Z") } })
    .exec(function(error, facebook){
        if (!error) {
            res.send(facebook);
        }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have user model like this

const guestSchema = mongoose.Schema({
  facebook: {
    id: String,
    token: String,
    email: String,
    name: String,
    phone: String,
    dates: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "loginDate"
      }
    ]
  }
});

and loginDate model

const loginDateSchema = mongoose.Schema({
  loginDate: Date
});

Every time user signs in current Date is added.
How can I find users who have signed in between given date?
I did below but I am getting empty result

Guest.find({ "facebook.id": { $exists: true } })
      .populate("facebook.dates")
      .find({ "facebook.dates": { $gte: startDate,$lte: endDate } })
      .exec((err, foundUsers) => {
        res.render("./admin/send", {
          facebookUsers: foundUsers
        });
      });

Sample JSON

{
    "_id" : ObjectId("5a1a838f58eb1a50c408de84"),
    "facebook" : {
        "email" : "sample@yahoo.com",
        "name" : "Sample user",
        "id" : "12345",
        "dates" : [
            ObjectId("5a1a838f58eb1a50c408de85"),
            ObjectId("5a1a839258eb1a50c408de86"),
            ObjectId("5a1a839358eb1a50c408de87"),
            ObjectId("5a1a839758eb1a50c408de88"),
            ObjectId("5a1aa17058eb1a50c408de8b")
        ]
    },
    "__v" : NumberInt(5)
}

LoginDate

{
    "_id" : ObjectId("5a1a839358eb1a50c408de87"),
    "loginDate" : ISODate("2017-11-26T09:04:19.107+0000"),
    "__v" : NumberInt(0)
}

Body:
I think the issue is with your date which you are passing into find function on line

 .find({ "facebook.dates": { $gte: startDate,$lte: endDate } })

You need to pass a date object and not a date string.

Here is my solution which is working fine for me

Facebook model

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.Promise = global.Promise;

var facebookSchema = new Schema({
    id: String,
    token: String,
    email: String,
    name: String,
    phone: String,
    logindate: Date
},
    {
        versionKey: false
    }
);

module.exports = mongoose.model('Facebook', facebookSchema);

Here is data

[
   {
      "_id":"5a2949d40591a2192c8fad6b",
      "logindate":"2016-10-10T06:28:37.146Z",
      "phone":"03006351611",
      "name":"mainuhassan",
      "email":"mainuhassan@gmail.com",
      "token":"MxuXmblL56aqt17aHh1rqcyeHc0E4CwQ",
      "id":"100"
   },
   {
      "_id":"5a294cd26c3e661514f3699e",
      "logindate":"2015-10-10T06:28:37.146Z",
      "phone":"03006351611",
      "name":"mainuhassan1",
      "email":"mainuhassan1@gmail.com",
      "token":"MxuXmblL56aqt17aHh1rqcyeHc0E4CwQ",
      "id":"100"
   },
   {
      "_id":"5a294cfe75e2ba2778e9f249",
      "logindate":"2017-10-10T06:28:37.146Z",
      "phone":"03006351612",
      "name":"mainuhassan2",
      "email":"mainuhassan2@gmail.com",
      "token":"MxuXmblL56aqt17aHh1rqcyeHc0E4CwQ",
      "id":"100"
   }
]

And here is my code for getting data between dates

Facebook.find({ logindate: { "$gte": new Date("2016-10-10T06:28:37.146Z"), "$lte": new Date("2017-10-10T06:28:37.146Z") } })
    .exec(function(error, facebook){
        if (!error) {
            res.send(facebook);
        }
});


问:
SQL Select titles of all books that have at least one rating of 4 or higher Titles must be ordered alphabetically
You are given three tables:

```<code>create table books(id int, title varchar(250), year int, author varchar(250));

create table reviewers(id int, name varchar(250));

create table ratings(reviewer_id int, book_id int, rating int, rating_date date);
</code>```

Select titles of all books that have at least one rating of 4 or higher
Titles must be ordered alphabetically.

What is wrong with my statement:

```<code>SELECT title FROM books WHERE id = (SELECT book_id FROM ratings WHERE rating >= 4) ORDER BY title;
</code>```

Desired Results:

```<code>A Tale Of Two Cities
And Then There Were None
Dream of the Red Chamber
She: A History of Adventure
</code>```

Books: sample data

```<code>id  title   year    author
101 A Tale Of Two Cities    1859    Charles Dickens
102 The Lord of the Rings   1955    J. R. R. Tolkien
103 The Hobbit  1937    NULL
104 The Little Prince   1943    Antoine de Saint-Exupéry
</code>```

Reviewers: sample data

```<code>id  name
15201   Joe Martinez
53202   Alice Lewis
44203   John Smith
Ratings: sample data
reviewer_id book_id rating  rating_date
15201   101 2   2015-02-11
15201   101 4   2015-06-16
53202   103 4   NULL
</code>```

答:
You need to change that = to an IN statement:

```<code>SELECT title FROM books WHERE id IN (SELECT book_id FROM ratings WHERE rating >= 4) ORDER BY title;
</code>```

...because your inner SELECT could return more than one result.

Body:
You are given three tables:

create table books(id int, title varchar(250), year int, author varchar(250));

create table reviewers(id int, name varchar(250));

create table ratings(reviewer_id int, book_id int, rating int, rating_date date);

Select titles of all books that have at least one rating of 4 or higher
Titles must be ordered alphabetically.

What is wrong with my statement:

SELECT title FROM books WHERE id = (SELECT book_id FROM ratings WHERE rating >= 4) ORDER BY title;

Desired Results:

A Tale Of Two Cities
And Then There Were None
Dream of the Red Chamber
She: A History of Adventure

Books: sample data

id  title   year    author
101 A Tale Of Two Cities    1859    Charles Dickens
102 The Lord of the Rings   1955    J. R. R. Tolkien
103 The Hobbit  1937    NULL
104 The Little Prince   1943    Antoine de Saint-Exupéry

Reviewers: sample data

id  name
15201   Joe Martinez
53202   Alice Lewis
44203   John Smith
Ratings: sample data
reviewer_id book_id rating  rating_date
15201   101 2   2015-02-11
15201   101 4   2015-06-16
53202   103 4   NULL

Body:
You need to change that = to an IN statement:

SELECT title FROM books WHERE id IN (SELECT book_id FROM ratings WHERE rating >= 4) ORDER BY title;

...because your inner SELECT could return more than one result.


问:
changing position of a bootstrap navbar
Hello I want to ask if anyone knows how to center a bootstrap navbar.

HTML

```<code><nav class="navbar navbar-default">
            <div class="container-fluid">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">Home</a></li>
                    <li><a href="#">History</a></li>
                    <li><a href="#">Information</a></li>
                    <li><a href="#">Geographical location</a></li>
                </ul>
            </div>
        </div>
    </nav>
</code>```

and I changed the width of the navbar so it fits better a doesn't have have lot of unused space there but its glued to the left side and i would love to center it.

CSS

```<code>.navbar-default {

width:38.5%;}
</code>```

答:
Try This. This should do it  </p>

```<code>.navbar-default {
 margin-left:auto;
 margin-right:auto;
 width:38.5%;}
</code>```

Title: changing position of a bootstrap navbar

Body:
Hello I want to ask if anyone knows how to center a bootstrap navbar.

HTML

Home

History

Information

Geographical location

and I changed the width of the navbar so it fits better a doesn't have have lot of unused space there but its glued to the left side and i would love to center it.

CSS

.navbar-default {

width:38.5%;}

Body:
Try This. This should do it

.navbar-default {
 margin-left:auto;
 margin-right:auto;
 width:38.5%;}


问:
Calculating price from quantity
I making the shops for my site, and but I can't understand why this conde don't wont to work...Here's the code:

```<code><script>
function Price() {
    var Quantity = document.getElementsByClassName('BUY')[0].value;
    var Total = Quantity * 20;
    if (!IsNan(Total)) {

        document.getElementsByClassName('Total').innerHTML = Total;
        document.getElementsByClassName('Quantity').innerHTML = Quantity;
    } else {
        document.getElementsByClassName('Total').innerHTML = "Invalid number";
        document.getElementsByClassName('Quantity').innerHTML = 0
    }
}
</code>```

Here is the html:

```<code><input style="margin-top:1%;" type="text" name="BUY" class="input" maxlength="1000" autocomplete="on" placeholder="Buy " onchange="Price()" required>Price for <span class="Quantity">0</span>Views:<span class="Total">0</span> Satoshis<br>
</code>```

From this code I expect a print of the calculation based on the quantity but  the code don't work and I get no errors...

答:
you have worng class name in the script that's why it is not working.

corrected code:(Just copy & paste it .works changed class into ID)
Because using classname it is not fetching the correct value instead it assigns Quantity as undefined  refer this answer

                function price(){
                    var Quantity=document.getElementById('buy').value;

                    var Total=Quantity*20;
                    if(Total != 'NaN'){

                        document.getElementById('Total').innerHTML=Total;
                        document.getElementById('Quantity').innerHTML=Quantity;
                    }else{
                        document.getElementById('Total').innerHTML="Invalid number";
                        document.getElementById('Quantity').innerHTML=0;
                    }
                }
           ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input style="margin-top:1%;" type="text" name="BY" id="buy" maxlength="1000" autocomplete="on" placeholder="Buy " onkeyup="price()" required/>Price for
    <span id="Quantity">0</span>
    Views:<span id="Total">0</span>
    Satoshis<br>

  </code>```

Title: Calculating price from quantity

Body:
you have worng class name in the script that's why it is not working.

corrected code:(Just copy & paste it .works changed class into ID)
Because using classname it is not fetching the correct value instead it assigns Quantity as undefined  refer this answer

                function price(){
                    var Quantity=document.getElementById('buy').value;

                    var Total=Quantity*20;
                    if(Total != 'NaN'){

                        document.getElementById('Total').innerHTML=Total;
                        document.getElementById('Quantity').innerHTML=Quantity;
                    }else{
                        document.getElementById('Total').innerHTML="Invalid number";
                        document.getElementById('Quantity').innerHTML=0;
                    }
                }

<input style="margin-top:1%;" type="text" name="BY" id="buy" maxlength="1000" autocomplete="on" placeholder="Buy " onkeyup="price()" required/>Price for
    <span id="Quantity">0</span>
    Views:<span id="Total">0</span>
    Satoshis<br>


问:
Toggle class on click body
I know lot of questions something like this are also in Stackoverflow. Here is a bit of Jquery problem. I have added toggle class Jquery function, and the same class should be remove when click anywhere on the body. Its working now, but I no need toggle that class when we click inside of the input text field.

Code:

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}</code>```

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

```

JS Fiddle: https://jsfiddle.net/vishnuprasadps/3a84p6h0/

答:
sweet and simple

$(".btn-search").click(function(event) {
 event.stopPropagation();
  $(".input-search").toggleClass('expanded');
});
$("html").click(function() {
    $(".input-search").removeClass('expanded');
});
$(".input-search").click(function(event) {
 event.stopPropagation();
  $(".input-search").addClass('expanded');

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
  z-index: 10;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}</code>```

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

```

Title: Toggle class on click body

Body:
I know lot of questions something like this are also in Stackoverflow. Here is a bit of Jquery problem. I have added toggle class Jquery function, and the same class should be remove when click anywhere on the body. Its working now, but I no need toggle that class when we click inside of the input text field.

Code:

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});

body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}

  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">

JS Fiddle: https://jsfiddle.net/vishnuprasadps/3a84p6h0/

Body:
sweet and simple

$(".btn-search").click(function(event) {
 event.stopPropagation();
  $(".input-search").toggleClass('expanded');
});
$("html").click(function() {
    $(".input-search").removeClass('expanded');
});
$(".input-search").click(function(event) {
 event.stopPropagation();
  $(".input-search").addClass('expanded');

});

body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
  z-index: 10;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="col-search">
  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">
</div>


答:
Here you go.

@media (min-width: 768px){
    .navbar-nav{
        float:none;
        margin: 0 auto;
        display: table;
        table-layout: fixed;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <nav class="navbar navbar-default">
            <div class="container-fluid">
                <ul class="nav navbar-nav">
                    <li class="active">Home</li>
                    <li>History</li>
                    <li>Information</li>
                    <li>Geographical location</li>
                </ul>
            </div>
        </div>
    </nav></code>```

Also codepen example: https://codepen.io/Karadjordje/pen/eewpWO

Title: changing position of a bootstrap navbar

Body:
Here you go.

@media (min-width: 768px){
    .navbar-nav{
        float:none;
        margin: 0 auto;
        display: table;
        table-layout: fixed;
    }
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <nav class="navbar navbar-default">
            <div class="container-fluid">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">Home</a></li>
                    <li><a href="#">History</a></li>
                    <li><a href="#">Information</a></li>
                    <li><a href="#">Geographical location</a></li>
                </ul>
            </div>
        </div>
    </nav>

Also codepen example: https://codepen.io/Karadjordje/pen/eewpWO


答:
Hard to say without your data, but try this:

```<code>SELECT
    title
FROM
    books
WHERE id IN
     (SELECT DISTINCT book_id FROM ratings WHERE rating >= 4)
ORDER BY title;
</code>```

Your WHERE clause with = is expecting a single value, not a possible group of values, and your subselect could include the same book ID many times, if there is more than one record for a book with a rating.

Give that a go.

Title: SQL Select titles of all books that have at least one rating of 4 or higher Titles must be ordered alphabetically

Body:
Hard to say without your data, but try this:

SELECT
    title
FROM
    books
WHERE id IN
     (SELECT DISTINCT book_id FROM ratings WHERE rating >= 4)
ORDER BY title;

Your WHERE clause with = is expecting a single value, not a possible group of values, and your subselect could include the same book ID many times, if there is more than one record for a book with a rating.

Give that a go.


答:
Instead of:

```<code>...WHERE id = (SELECT...
</code>```

You want:

```<code>...WHERE id IN (SELECT...
</code>```

Body:
Instead of:

...WHERE id = (SELECT...

You want:

...WHERE id IN (SELECT...


问:
Console app running in Google Cloud
I am trying to add my project to Google cloud under "App Engine". I have added it through the "Cloud Shell" using Git run the "dotnet restore" command which all works correctly.

However my application is a console app and not a web application. I can't find any documentation related to a console app running on Google cloud. Is this possible?

答: AppEngine is a web and mobile applications platform, even tho you could make it work for your app if you configure it to respond to the IP address provided, there is no guide for it since is not a predetermined function. I believe that Compute Engine would be a better fit for your application, although you have to do all the configurations by yourself. Maybe you can find a pre-made solution on Cloud Launcher.</p>

Title: Console app running in Google Cloud


问:
Generating random numbers from a gaussian distribution in CUDA
I've searched a lot over the internet to find a way to generate random numbers on my CUDA device, within a kernel. The numbers must come from a gaussian distribution.

The best thing I found was from NVIDIA itself. It is the Wallace algorithm, that uses a uniform distribution to build a gaussian one. But the code samples they give lack explanation and I really need to understand how the algorithm goes, especially on the device. For example, they give:

```<code> __device__ void generateRandomNumbers_wallace(
unsigned seed,  // Initialization seed
 float *chi2Corrections,  // Set of correction values
 float *globalPool,  // Input random number pool
 float *output  // Output random numbers

    unsigned tid=threadIdx.x;
    // Load global pool into shared memory.
     unsigned offset = __mul24(POOL_SIZE, blockIdx.x);
    for( int i = 0; i < 4; i++ )
      pool[tid+THREADS*i] = globalPool[offset+TOTAL_THREADS*i+tid];
    __syncthreads();
      const unsigned lcg_a=241;
      const unsigned lcg_c=59;
      const unsigned lcg_m=256;
      const unsigned mod_mask = lcg_m-1;
      seed=(seed+tid)&mod_mask ;
      // Loop generating outputs repeatedly
     for( int loop = 0; loop < OUTPUTS_PER_RUN; loop++ )
      {
        Transform();
        unsigned intermediate_address;
        i_a = __mul24(loop,8*TOTAL_THREADS)+8*THREADS *
          blockIdx.x + threadIdx.x;
        float chi2CorrAndScale=chi2Corrections[
          blockIdx.x * OUTPUTS_PER_RUN + loop];
        for( i = 0; i < 4; i++ )
          output[i_a + i*THREADS]=chi2CorrAndScale*pool[tid+THREADS*i];
    }
</code>```

First of all, many of the variables declared aren't even used in the function! And I really don't get what the "8" is for in the second loop. I understand the "4" in the other loops have something to do with the 4x4 orthogonal matrix block, am I right? Could anyone give me a better idea of what is going on here?

Anyway, does anyone have any good code samples I could use? Or does anyone have another way of generating random gaussian numbers in a CUDA kernel? Code samples will be much appreciated.

Thanks!

答:
You could use CURAND, which is included with the CUDA Toolkit (version 3.2 and later). It'd be far simpler!

A few notes on the code you posted:

The Wallace generator transforms Gaussian to Gaussian (i.e. not Uniform to Gaussian)

CUDA code has two implicit variables: blockIdx and threadIdx - these define the block index and thread index with a block, see the CUDA Programming Guide for more information

The code uses __mul24, on sm_20 and later this is actually slower than "ordinary" 32-bit multiplication so I would avoid it (even on older architectures for simplicity)

Body:
I've searched a lot over the internet to find a way to generate random numbers on my CUDA device, within a kernel. The numbers must come from a gaussian distribution.

The best thing I found was from NVIDIA itself. It is the Wallace algorithm, that uses a uniform distribution to build a gaussian one. But the code samples they give lack explanation and I really need to understand how the algorithm goes, especially on the device. For example, they give:

 __device__ void generateRandomNumbers_wallace(
unsigned seed,  // Initialization seed
 float *chi2Corrections,  // Set of correction values
 float *globalPool,  // Input random number pool
 float *output  // Output random numbers

    unsigned tid=threadIdx.x;
    // Load global pool into shared memory.
     unsigned offset = __mul24(POOL_SIZE, blockIdx.x);
    for( int i = 0; i < 4; i++ )
      pool[tid+THREADS*i] = globalPool[offset+TOTAL_THREADS*i+tid];
    __syncthreads();
      const unsigned lcg_a=241;
      const unsigned lcg_c=59;
      const unsigned lcg_m=256;
      const unsigned mod_mask = lcg_m-1;
      seed=(seed+tid)&mod_mask ;
      // Loop generating outputs repeatedly
     for( int loop = 0; loop < OUTPUTS_PER_RUN; loop++ )
      {
        Transform();
        unsigned intermediate_address;
        i_a = __mul24(loop,8*TOTAL_THREADS)+8*THREADS *
          blockIdx.x + threadIdx.x;
        float chi2CorrAndScale=chi2Corrections[
          blockIdx.x * OUTPUTS_PER_RUN + loop];
        for( i = 0; i < 4; i++ )
          output[i_a + i*THREADS]=chi2CorrAndScale*pool[tid+THREADS*i];
    }

First of all, many of the variables declared aren't even used in the function! And I really don't get what the "8" is for in the second loop. I understand the "4" in the other loops have something to do with the 4x4 orthogonal matrix block, am I right? Could anyone give me a better idea of what is going on here?

Anyway, does anyone have any good code samples I could use? Or does anyone have another way of generating random gaussian numbers in a CUDA kernel? Code samples will be much appreciated.

Thanks!


问:
Using endorsements in Hyperledger Composer to design a process
NB: I am seeking to understand how endorsements works in general. This will help me determine how to design applications when using Hyperledger Composer.

When I read the links here and here, I came across this statement: "Transactions have to be “endorsed” and only endorsed transactions may be committed and have an effect on the state". The statement is clear. However, let's consider the composer developer tutorial here. We have a commodity that is currently owned by an owner(Trader1) who could sell it to somebody else(Trader 2). Currently, how many endorsements are needed for the transaction to be put on the blockchain? Because, when running the application, I only submit a transaction Trade and I get results. I only deal with one function, and I get results. The following things are transparent to me as a programmer:

Creation of a transaction proposal,
When the transaction proposal is endorsed and by whom,
Whether an endorsement is performed explicitly by a human on the other end or it's programmatically done by code
That there is a proposal response from the endorser and how many they are,
When the application verifies the endorsing peer signatures
When the application creates a transaction message from the transaction proposal and response
etc.

All I do is submit one transaction and get a result.

So it becomes hard for me to assess the value of endorsement policies besides the theory in the text. And thus, the difficulty in designing a program to utilize the same. For example, consider two scenarios which we could use to handle a Trade:

We need 2 endorsements from the seller and the buyer before a transaction is commited. This would effectively be one transaction (This is what is transparent to me)

We need 2 authorizations from seller and the buyer before a transaction is commited. These authorizations could update states in the commodity such that we capture the approval from both the seller and the buyer. This could be 2 transactions i.e. sellerTradeRequest, buyerTradeApproval. The sellerTradeRequest could update commodity.sellerApproval=true while the buyerTradeApproval could update commodity.buyerApproval=true. Then, a final trade transaction that checks that the states on the commodity are OK i.e. commodity.sellerApproval=true and commodity.buyerApproval=true before commiting the transaction.

If I get a clear distinction between 1 and 2, especially how composer enables 1 above. Then maybe I will start understanding how to use endorsements.

Could anyone help?

答:
The endorsement policy enables you the chance to add an extra verification layer to your Blockchain. You define it when you create the channel.

When a (Initial) Peer sends a proposal, firts of all the proposal is send to all of the Peers that you have defined in your Endorsement policy.

Then, each Endorser Peer executes the proposal against its ledger. The Endorser Peer will send the result signed to the Initial Peer.

The Initial Peer will receive more than one respone. Then, the Initial Peer will verify all the signatures and will compare the result of each response. The result sent by each Endorse Peer have to be the same.

In that case, the Initial Peer will send the transaction to the Orderers. That transaction will wraper all the responses all of the Endorses Peers.

So, you should define your Endorsement policy according to your requirements


问:
Solr parent-child query
I am trying to query solr documents based on criteria both in parent and a child.

Documentation: BlockJoinQueryParsers instructs to use a query like:

```<code>q= +title:join +{!parent which="content_type:parentDocument"}comments:SolrCloud
</code>```

where title is a parent's field and comments is child's.
A query like this works fine. However, I can not add any other condition on the child. No matter what statement I try to put after the '}', it fails with SyntaxError. For example

```<code>q= +title:join +{!parent which="content_type:parentDocument"}(comments:SolrCloud AND id:4)
</code>```

fails with SyntaxError.

I think I can use a workaround by utilizing fq parameter, but I wonder if it is possible to achieve in one query.

P.S. I am using Solr 6.6, and upgrading to version 7 can be considered.

答:
You need to use local parameters, basically your query is equal to

```<code>q= +title:join +{!parent which="content_type:parentDocument" v='comments:SolrCloud'}
</code>```

which could be rewritten even further:

```<code>q= +title:join +{!parent which="content_type:parentDocument" v=$qq}&qq=+comments:SolrCloud +whatever:ClauseYouWant
</code>```

Title: Solr parent-child query

Body:
I am trying to query solr documents based on criteria both in parent and a child.

Documentation: BlockJoinQueryParsers instructs to use a query like:

q= +title:join +{!parent which="content_type:parentDocument"}comments:SolrCloud

where title is a parent's field and comments is child's.
A query like this works fine. However, I can not add any other condition on the child. No matter what statement I try to put after the '}', it fails with SyntaxError. For example

q= +title:join +{!parent which="content_type:parentDocument"}(comments:SolrCloud AND id:4)

fails with SyntaxError.

I think I can use a workaround by utilizing fq parameter, but I wonder if it is possible to achieve in one query.

P.S. I am using Solr 6.6, and upgrading to version 7 can be considered.

Body:
You need to use local parameters, basically your query is equal to

q= +title:join +{!parent which="content_type:parentDocument" v='comments:SolrCloud'}

which could be rewritten even further:

q= +title:join +{!parent which="content_type:parentDocument" v=$qq}&qq=+comments:SolrCloud +whatever:ClauseYouWant


问:
How do I change an event's background color with different colors, in fullcalendar?
I'm using the last version of fullcalendar, I looked on documentation how change background color event, but I don't know how make to different events.

I need for code sample with events red, blue, green, like the following picture:

I see this code, on document site, but I can't to apply 2 colors:

```<code>$('#calendar').fullCalendar({
  editable: true,
  events: [{
    title: 'Teste1',
    start: new Date(y, m, d, 10, 30),
    allDay: false,
    editable: false
  }, {
    title: 'Teste2',
    start: new Date(y, m, d, 11, 40),
    allDay: false
  }],
  eventColor: '#378006'
});
</code>```

答:
I have applied the color code like this for each event, It works for me.     </p>

```<code> $.each(data, function(i, v){
    var event =[];
    var col = "";
                            if(v.Status == 1)
                            {
                                col = "#00c0ef";
                            }
                            else if(v.Status == 2){
                                col = "#dd4b39";
                            }
                            else if (v.Status === 3)
                            {
                                col = "#f39c12";
                            }
                            else {
                                col = "#00a65a";
                            }
                         event.push({
                             title: v.AssignedName + "\n  Installation Date: \n" + da,
                             start: da,
                             backgroundColor: col,
                                textColor:'black'
                         })
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using the last version of fullcalendar, I looked on documentation how change background color event, but I don't know how make to different events.

I need for code sample with events red, blue, green, like the following picture:

I see this code, on document site, but I can't to apply 2 colors:

$('#calendar').fullCalendar({
  editable: true,
  events: [{
    title: 'Teste1',
    start: new Date(y, m, d, 10, 30),
    allDay: false,
    editable: false
  }, {
    title: 'Teste2',
    start: new Date(y, m, d, 11, 40),
    allDay: false
  }],
  eventColor: '#378006'
});

Body:
I have applied the color code like this for each event, It works for me.

 $.each(data, function(i, v){
    var event =[];
    var col = "";
                            if(v.Status == 1)
                            {
                                col = "#00c0ef";
                            }
                            else if(v.Status == 2){
                                col = "#dd4b39";
                            }
                            else if (v.Status === 3)
                            {
                                col = "#f39c12";
                            }
                            else {
                                col = "#00a65a";
                            }
                         event.push({
                             title: v.AssignedName + "\n  Installation Date: \n" + da,
                             start: da,
                             backgroundColor: col,
                                textColor:'black'
                         })
});


问:
How to get value of checkbox in tix

i can get status of checkbox but How to Get value of checkbox in Tix.

```<code>from tkinter import tix

class View(object):
    def __init__(self, root):
        self.root = root
        self.makeCheckList()

    def makeCheckList(self):
        self.cl = tix.CheckList(self.root, browsecmd=self.selectItem)
        self.cl.pack()
        self.cl.hlist.add("CL1", text="C:/")
        self.cl.hlist.add("CL1.Item1", text="subitem1")
        self.cl.hlist.add("CL2", text="some folder")
        self.cl.hlist.add("CL2.Item1", text="test")
        self.cl.setstatus("CL2", "on")
        self.cl.setstatus("CL2.Item1", "on")
        self.cl.setstatus("CL1", "off")
        self.cl.setstatus("CL1.Item1", "off")
        self.cl.autosetmode()

    def selectItem(self, item):
        print (item, self.cl.getstatus(item))

def main():
    root = tix.Tk()
    view = View(root)
    root.update()
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

Expected output

if i click on checkbox c:/ then it should print c:/.I want the value of checkbox.

Output

答:
It keeps all in hlist

Official documentation for more informations about hlist sends to tcl/tk documentation and then you can find

```<code>pathName item_cget entryPath col option
</code>```

But it doesn't work as I expected

```<code>value = self.cl.hlist.item_cget('CL1.Item1', 0, 'text')

# _tkinter.TclError: unknown option "text"
</code>```

You have to use "-text" instead of "text"

```<code>value = self.cl.hlist.item_cget('CL1.Item1', 0, '-text')
</code>```

Title: How to get value of checkbox in tix

Body:
i can get status of checkbox but How to Get value of checkbox in Tix.

from tkinter import tix

class View(object):
    def __init__(self, root):
        self.root = root
        self.makeCheckList()

    def makeCheckList(self):
        self.cl = tix.CheckList(self.root, browsecmd=self.selectItem)
        self.cl.pack()
        self.cl.hlist.add("CL1", text="C:/")
        self.cl.hlist.add("CL1.Item1", text="subitem1")
        self.cl.hlist.add("CL2", text="some folder")
        self.cl.hlist.add("CL2.Item1", text="test")
        self.cl.setstatus("CL2", "on")
        self.cl.setstatus("CL2.Item1", "on")
        self.cl.setstatus("CL1", "off")
        self.cl.setstatus("CL1.Item1", "off")
        self.cl.autosetmode()

    def selectItem(self, item):
        print (item, self.cl.getstatus(item))

def main():
    root = tix.Tk()
    view = View(root)
    root.update()
    root.mainloop()

if __name__ == '__main__':
    main()

Expected output

if i click on checkbox c:/ then it should print c:/.I want the value of checkbox.

Output

Body:
It keeps all in hlist

Official documentation for more informations about hlist sends to tcl/tk documentation and then you can find

pathName item_cget entryPath col option

But it doesn't work as I expected

value = self.cl.hlist.item_cget('CL1.Item1', 0, 'text')

# _tkinter.TclError: unknown option "text"

You have to use "-text" instead of "text"

value = self.cl.hlist.item_cget('CL1.Item1', 0, '-text')


问:
Error : Property [uploads] does not exist on this collection instance - one to many relationship
I am trying to make a one to many relationship between my Users table and my Uploads table.

To do so I did the following :

Added this function to my User table :

```<code>public function uploads(){
        return $this->belongsTo('App\Upload');
    }
</code>```

And this to my Upload table :

```<code>public function user(){
        return $this->belongsTo('App\User');
    }
</code>```

Then I added this simple function to my UploadController :

```<code>   public function uploads()
{
    $user_id = auth()->user('id');
    $user = User::find($user_id);
    return view('uploads')->with('uploads',$user->uploads);
}
</code>```

My Uploads view is looking like this :

```<code> @extends('layouts.app')
@section('content')
    <h1>Uploads</h1>
    @if(count($uploads)>0)
@foreach($uploads as $upload)
    <div class="well">
        <h3><a href="/uploads/{{$upload->id}}">{{$upload->name}}</a> </h3>
        <small>Written on {{$upload->created_at}}</small>

    </div>
        @endforeach
             {{$uploads->links()}}
    @else
    <p>No uploads found</p>
    @endif

@endsection
</code>```

When I try to go to myproject.dev/uploads I'm getting the following error :

Property [uploads] does not exist on this collection instance.

Since I am new to laravel, as far as I am aware I don't have to run a migration after I make something like this. But still it doesn't work and I just don't see what am I doing wrong? I just followed the documentation....

答:
There is a problem in the relationship of the User model, it should be like this :

```<code>public function uploads(){
    return $this->hasMany('App\Upload');
}
</code>```

Then you have to eager load the uploads :

```<code>$user = User::with('uploads')->find($user_id);
</code>```

But the better solution in your case is to load the uploads instead of the user, because you ar using pagination so:

```<code>public function uploads()
{
    $user_id = auth()->user('id');
    $uploads = Upload::whereHas('user', function ($query) use($user_id) {
                        $query->where('id', $user_id);
                    })
                    ->paginate(10);
    return view('uploads')->with('uploads',$uploads);
}
</code>```

Ps : you can change 10 in paginate function to metion the needed elements per page.

Body:
I am trying to make a one to many relationship between my Users table and my Uploads table.

To do so I did the following :

Added this function to my User table :

public function uploads(){
        return $this->belongsTo('App\Upload');
    }

And this to my Upload table :

public function user(){
        return $this->belongsTo('App\User');
    }

Then I added this simple function to my UploadController :

   public function uploads()
{
    $user_id = auth()->user('id');
    $user = User::find($user_id);
    return view('uploads')->with('uploads',$user->uploads);
}

My Uploads view is looking like this :

 @extends('layouts.app')
@section('content')

Uploads

    @if(count($uploads)>0)
@foreach($uploads as $upload)

id}}">{{$upload->name}}

        Written on {{$upload->created_at}}

        @endforeach
             {{$uploads->links()}}
    @else

No uploads found

    @endif

@endsection

When I try to go to myproject.dev/uploads I'm getting the following error :

Property [uploads] does not exist on this collection instance.

Since I am new to laravel, as far as I am aware I don't have to run a migration after I make something like this. But still it doesn't work and I just don't see what am I doing wrong? I just followed the documentation....

Body:
There is a problem in the relationship of the User model, it should be like this :

public function uploads(){
    return $this->hasMany('App\Upload');
}

Then you have to eager load the uploads :

$user = User::with('uploads')->find($user_id);

But the better solution in your case is to load the uploads instead of the user, because you ar using pagination so:

public function uploads()
{
    $user_id = auth()->user('id');
    $uploads = Upload::whereHas('user', function ($query) use($user_id) {
                        $query->where('id', $user_id);
                    })
                    ->paginate(10);
    return view('uploads')->with('uploads',$uploads);
}

Ps : you can change 10 in paginate function to metion the needed elements per page.


问:
Insert document into mongodb from existing table
I am trying to write a query in mongo that will create a new table, loop through my data set, and insert the TopExecutiveTitle into the new table. I also would like it to keep count of each position and only insert a position into the table when it is new.

This is what I have so far. This code loops through my table and inserts the TopExectuiveTitle into a new table. However, it does not group them together and keep count. How do I write my query so that it will?

```<code>db.car.find().forEach( function (x) {
db.TopExecutiveTable.insert({Topexecutivetitle: x.Topexecutivetitle})
});
</code>```

Here is a sample of a document in my database.

```<code>{
    "_id" : ObjectId("5a22c8e562c2e489c5df70fa"),
    "2016rank" : 1,
    "Dealershipgroupname" : "AutoNation Inc.?",
    "Address" : "200 S.W. 1st Ave.",
    "City/State/Zip" : "Fort Lauderdale, FL 33301",
    "Phone" : "(954) 769-7000",
    "Companywebsite" : "www.autonation.com",
    "Topexecutive" : "Mike Jackson",
    "Topexecutivetitle" : "chairman & CEO",
    "Totalnewretailunits" : "337,622",
    "Totalusedunits" : "225,713",
    "Totalfleetunits" : 3,
    "Totalwholesaleunits" : "82,342",
    "Total_units" : "649,415",
    "Total_number_of _dealerships" : 260,
    "Grouprevenuealldepartments*" : "$21,609,000,000",
    "2015rank" : 1
}
</code>```

The result I would like is something like this

```<code>"Topexecutivetitle" : "chairman & CEO"
           "Count"  : 3
"Topexecutivetitle" : "president"
           "Count"  : 7
}
</code>```

答:
To do this you need to use the aggregate function of mongo, something like this:

```<code>db.car.aggregate([
{
    $group:{
            _id:"$Topexecutivetitle",
            count:{$sum:1}
        }
},
{
    $project:{
            Topexecutivetitle:"$_id",
            count:1,
            _id:0
        }
 },
 {
     $out:"result"
 }])
</code>```

This will give you your desired output and store it into a new collection "result":

```<code>{
    "_id" : "president",
    "count" : 1.0
},
{
    "_id" : "chairman & CEO",
    "count" : 3.0
}
</code>```

Body:
I am trying to write a query in mongo that will create a new table, loop through my data set, and insert the TopExecutiveTitle into the new table. I also would like it to keep count of each position and only insert a position into the table when it is new.

This is what I have so far. This code loops through my table and inserts the TopExectuiveTitle into a new table. However, it does not group them together and keep count. How do I write my query so that it will?

db.car.find().forEach( function (x) {
db.TopExecutiveTable.insert({Topexecutivetitle: x.Topexecutivetitle})
});

Here is a sample of a document in my database.

{
    "_id" : ObjectId("5a22c8e562c2e489c5df70fa"),
    "2016rank" : 1,
    "Dealershipgroupname" : "AutoNation Inc.?",
    "Address" : "200 S.W. 1st Ave.",
    "City/State/Zip" : "Fort Lauderdale, FL 33301",
    "Phone" : "(954) 769-7000",
    "Companywebsite" : "www.autonation.com",
    "Topexecutive" : "Mike Jackson",
    "Topexecutivetitle" : "chairman & CEO",
    "Totalnewretailunits" : "337,622",
    "Totalusedunits" : "225,713",
    "Totalfleetunits" : 3,
    "Totalwholesaleunits" : "82,342",
    "Total_units" : "649,415",
    "Total_number_of _dealerships" : 260,
    "Grouprevenuealldepartments*" : "$21,609,000,000",
    "2015rank" : 1
}

The result I would like is something like this

"Topexecutivetitle" : "chairman & CEO"
           "Count"  : 3
"Topexecutivetitle" : "president"
           "Count"  : 7
}

Body:
To do this you need to use the aggregate function of mongo, something like this:

db.car.aggregate([
{
    $group:{
            _id:"$Topexecutivetitle",
            count:{$sum:1}
        }
},
{
    $project:{
            Topexecutivetitle:"$_id",
            count:1,
            _id:0
        }
 },
 {
     $out:"result"
 }])

This will give you your desired output and store it into a new collection "result":

{
    "_id" : "president",
    "count" : 1.0
},
{
    "_id" : "chairman & CEO",
    "count" : 3.0
}


问:
Django dynamic table with AJAX
This is the second question in the row about my Django project. The code I use here has parts copied from this question:Stack Overflow

What I aim to achieve is a dynamic table, that loops through objects in a list(currently the interval between records is 3 seconds). Let's say I have 21 records. The table first displays records of 1 to 10, on the displaykala.html table. Then it replaces only the table content with records of 11 to 20(with AJAX, without page refresh. The new contents come from get_more_tables_kala.html, and those table rows coming from there, are appended to the displaykala.html table).
At no point should the table be empty (UNLESS there is simply no objects to display).

Finally, the contents of 11-20 are replaced with contents of 21-30. In this case, only one row is displayed.

Basicly it always displays first ten records(even if there is only one). Then the code increments the startindex and endindex of the rows, and checks if there is records between those. If there is more than 10 records, it will empty the table and instantly load up the next records (as long as there is even 1 record). Else, the program should wait X amount of seconds, until checking  again.

The code has been going through various experimentations, I'm sorry for any dumb coding. I'm still learning Django and AJAX.

There is a few problems though, but let's focus on the main one
When the displaykala.html is loaded, the table is displayed empty first, for 3 seconds. I know this is because the code loads the empty displaykala.html table.
If I were to set in views that displaykala.html table should display rows 1 to 10 by default, I run into a rendering problem if there is more than 10 rows.

Those rows are loaded from the get_more_tables_kala.html, but when the code is supposed to switch back to displaykala.html, I'm either forced to reload the page (which is not an option due to network traffic increase), or return a new render with displaykala.html as a parameter, which causes the page to create a "copy" of itself, in the place where the table rows are supposed to be.

What I want is the program to switch between the records, without diplaying empty page in between.

I am open to any kind of optimizations or different ideas, as long as they're somewhat simple to understand. I know that this code is rubbish. I'm just trying to get it to work.

I must have missed something vital to tell you, please comment below if you need more info.

EDIT: Also, when I look at the django server console, the three tables (1-10, 11-20(only two records) and the empty one) produce these rows:

[14/Dec/2017 12:33:22] "GET /user/get_more_tables_k HTTP/1.1" 200 2222

[14/Dec/2017 12:33:24] "GET /user/get_more_tables_k HTTP/1.1" 200 439

[14/Dec/2017 12:33:27] "GET /user/get_more_tables_k HTTP/1.1" 200 1

My code runs between views.py, js_kala.html,  displaykala.html and get_more_tables_kala.html.

views.py

```<code>from django.shortcuts import render, redirect
from userside.models import Kala
from django.contrib.auth.decorators import login_required
from django.db import connection

@login_required
def displaykala(request):
    return render(request, 'displaykala.html')

@login_required
def get_more_tables_kala(request):

    startind = request.session.get('startind')
    if not startind:
        startind = 0
    request.session['startind'] = startind

    endind = request.session.get('endind')
    if not endind:
        endind = 10
    request.session['endind'] = endind

    kalat = Kala.objects.filter(rivinro__gt=startind, rivinro__lte=endind)
    count = kalat.count()
    if count == 0:
        request.session['startind'] = 0
        request.session['endind'] = 10
        kalat = Kala.objects.filter(rivinro__gt=startind, rivinro__lte=endind)
        return render(request, 'get_more_tables_kala.html', {'kalat': kalat})
    else:
        request.session['startind'] += 10
        request.session['endind'] += 10
        kalat = Kala.objects.filter(rivinro__gt=startind, rivinro__lte=endind)
        return render(request, 'get_more_tables_kala.html', {'kalat': kalat})
</code>```

js_kala.html

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
    var append_increment = 0;
    setInterval(function() {
        $.ajax({
            type: "GET",
            url: "{% url 'get_more_tables_kala' %}",  // URL to your view that serves new info
            data: {'append_increment': append_increment}
        })
        .done(function(response) {
            $('#_appendHere_kala').html('');
            $('#_appendHere_kala').append(response);
            append_increment += 10;
        });
     }, 3000)
</script>
</code>```

displaykala.html

```<code><html>
    <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
  {% load static %}
    {% include 'loginbar.html' %}
    <head>
      <link rel="stylesheet" type="text/css" href="{% get_static_prefix %}css/style.css">
        <title>Display</title>
    </head>
    <body>
            <h1>Display</h1>
            <table>
                <tr>
                    <th>Rivinumero</th>
                    <th>Tuote</th>
                    <th>Latinankielinen nimi</th>
                    <th>Pyyntialue</th>
                    <th>Pyyntipäivä</th>
                    <th>Tuotantotapa</th>
                    <th>Pyydystyyppi</th>
                </tr>
            </table>
            <table id="_appendHere_kala" class="table table-striped table-condensed">
                        <thead>
                      </thead>
                      {% include 'js_kala.html' %}
                        {% for kala in kalat %}
                        <tr>
                        <tbody id="tbody">
                          <td>{{kala.rivinro}}</td>
                          <td>{{kala.tuote}}</td>
                          <td>{{kala.latinalainen_nimi}}</td>
                          <td>{{kala.pyyntialue}}</td>
                          <td>{{kala.pyyntipaiva|date:"d.m.Y" }}</td>
                          <td>{{kala.tuotantotapa}}</td>
                          <td>{{kala.pyydystyyppi}}</td>
                        </tbody>
                        </tr>
                        {% endfor %}
                      </table>
    </body>
</html>
</code>```

get_more_tables_kala.html

```<code>{% load static %}
{% for kala in kalat %}
<tbody id='tbody'>
    <tr>
        <td>{{kala.rivinro}}</td>
        <td>{{kala.tuote}}</td>
        <td>{{kala.latinalainen_nimi}}</td>
        <td>{{kala.pyyntialue}}</td>
        <td>{{kala.pyyntipaiva|date:"d.m.Y" }}</td>
        <td>{{kala.tuotantotapa}}</td>
        <td>{{kala.pyydystyyppi}}</td>
     </tr>
</tbody>

{% endfor %}
</code>```

答:
You should fetch data from database in "displaykala" view and throw the data into the template file. The startind should be 0 and endind should be 9 because you are fetching 10 records only.

For the empty table problem, it seems that the setInterval() function would cause the table to be empty for 3 seconds. After calling the setInterval(), it will wait for a period of time (3 seconds in this case) before executing the process. Which means this function makes your program cannot be executed immediately.
Here is the process workflow:

Wait for 3 seconds

Run AJAX

Wait for 3 seconds

Run AJAX

Again and again

Which means you should execute the AJAX process once before calling the setInterval().

--Edit--
After asking so many questions, I've found something that might also cause the empty table problem.

In this part,

```<code>if count == 0:
    request.session['startind'] = 0
    request.session['endind'] = 10
    kalat = Kala.objects.filter(rivinro__gt=startind, rivinro__lte=endind)
    return render(request, 'get_more_tables_kala.html', {'kalat': kalat})
</code>```

You still use startind and endind (which are the same arguments used in previous filtering statement) to do filter when the system cannot find any data in the filtering. This makes your system prints nothing.

However, from your code, I cannot see why your system finds nothing from the database in every time you started opening the page. You will have to open debug mode of IDE and DevTools of web browser to see what happens with the session and Python variables.

Title: Django dynamic table with AJAX

Body:
This is the second question in the row about my Django project. The code I use here has parts copied from this question:Stack Overflow

What I aim to achieve is a dynamic table, that loops through objects in a list(currently the interval between records is 3 seconds). Let's say I have 21 records. The table first displays records of 1 to 10, on the displaykala.html table. Then it replaces only the table content with records of 11 to 20(with AJAX, without page refresh. The new contents come from get_more_tables_kala.html, and those table rows coming from there, are appended to the displaykala.html table).
At no point should the table be empty (UNLESS there is simply no objects to display).

Finally, the contents of 11-20 are replaced with contents of 21-30. In this case, only one row is displayed.

Basicly it always displays first ten records(even if there is only one). Then the code increments the startindex and endindex of the rows, and checks if there is records between those. If there is more than 10 records, it will empty the table and instantly load up the next records (as long as there is even 1 record). Else, the program should wait X amount of seconds, until checking  again.

The code has been going through various experimentations, I'm sorry for any dumb coding. I'm still learning Django and AJAX.

There is a few problems though, but let's focus on the main one
When the displaykala.html is loaded, the table is displayed empty first, for 3 seconds. I know this is because the code loads the empty displaykala.html table.
If I were to set in views that displaykala.html table should display rows 1 to 10 by default, I run into a rendering problem if there is more than 10 rows.

Those rows are loaded from the get_more_tables_kala.html, but when the code is supposed to switch back to displaykala.html, I'm either forced to reload the page (which is not an option due to network traffic increase), or return a new render with displaykala.html as a parameter, which causes the page to create a "copy" of itself, in the place where the table rows are supposed to be.

What I want is the program to switch between the records, without diplaying empty page in between.

I am open to any kind of optimizations or different ideas, as long as they're somewhat simple to understand. I know that this code is rubbish. I'm just trying to get it to work.

I must have missed something vital to tell you, please comment below if you need more info.

EDIT: Also, when I look at the django server console, the three tables (1-10, 11-20(only two records) and the empty one) produce these rows:

[14/Dec/2017 12:33:22] "GET /user/get_more_tables_k HTTP/1.1" 200 2222

[14/Dec/2017 12:33:24] "GET /user/get_more_tables_k HTTP/1.1" 200 439

[14/Dec/2017 12:33:27] "GET /user/get_more_tables_k HTTP/1.1" 200 1

My code runs between views.py, js_kala.html,  displaykala.html and get_more_tables_kala.html.

views.py

from django.shortcuts import render, redirect
from userside.models import Kala
from django.contrib.auth.decorators import login_required
from django.db import connection

@login_required
def displaykala(request):
    return render(request, 'displaykala.html')

@login_required
def get_more_tables_kala(request):

    startind = request.session.get('startind')
    if not startind:
        startind = 0
    request.session['startind'] = startind

    endind = request.session.get('endind')
    if not endind:
        endind = 10
    request.session['endind'] = endind

    kalat = Kala.objects.filter(rivinro__gt=startind, rivinro__lte=endind)
    count = kalat.count()
    if count == 0:
        request.session['startind'] = 0
        request.session['endind'] = 10
        kalat = Kala.objects.filter(rivinro__gt=startind, rivinro__lte=endind)
        return render(request, 'get_more_tables_kala.html', {'kalat': kalat})
    else:
        request.session['startind'] += 10
        request.session['endind'] += 10
        kalat = Kala.objects.filter(rivinro__gt=startind, rivinro__lte=endind)
        return render(request, 'get_more_tables_kala.html', {'kalat': kalat})

js_kala.html

displaykala.html

    <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
  {% load static %}
    {% include 'loginbar.html' %}

      <link rel="stylesheet" type="text/css" href="{% get_static_prefix %}css/style.css">
        <title>Display</title>

Display

                    Rivinumero
                    Tuote
                    Latinankielinen nimi
                    Pyyntialue
                    Pyyntipäivä
                    Tuotantotapa
                    Pyydystyyppi

                      {% include 'js_kala.html' %}
                        {% for kala in kalat %}

                          {{kala.rivinro}}
                          {{kala.tuote}}
                          {{kala.latinalainen_nimi}}
                          {{kala.pyyntialue}}
                          {{kala.pyyntipaiva|date:"d.m.Y" }}
                          {{kala.tuotantotapa}}
                          {{kala.pyydystyyppi}}

                        {% endfor %}

get_more_tables_kala.html

{% load static %}
{% for kala in kalat %}

        {{kala.rivinro}}
        {{kala.tuote}}
        {{kala.latinalainen_nimi}}
        {{kala.pyyntialue}}
        {{kala.pyyntipaiva|date:"d.m.Y" }}
        {{kala.tuotantotapa}}
        {{kala.pyydystyyppi}}

{% endfor %}

Body:
You should fetch data from database in "displaykala" view and throw the data into the template file. The startind should be 0 and endind should be 9 because you are fetching 10 records only.

For the empty table problem, it seems that the setInterval() function would cause the table to be empty for 3 seconds. After calling the setInterval(), it will wait for a period of time (3 seconds in this case) before executing the process. Which means this function makes your program cannot be executed immediately.
Here is the process workflow:

Wait for 3 seconds

Run AJAX

Wait for 3 seconds

Run AJAX

Again and again

Which means you should execute the AJAX process once before calling the setInterval().

--Edit--
After asking so many questions, I've found something that might also cause the empty table problem.

In this part,

if count == 0:
    request.session['startind'] = 0
    request.session['endind'] = 10
    kalat = Kala.objects.filter(rivinro__gt=startind, rivinro__lte=endind)
    return render(request, 'get_more_tables_kala.html', {'kalat': kalat})

You still use startind and endind (which are the same arguments used in previous filtering statement) to do filter when the system cannot find any data in the filtering. This makes your system prints nothing.

However, from your code, I cannot see why your system finds nothing from the database in every time you started opening the page. You will have to open debug mode of IDE and DevTools of web browser to see what happens with the session and Python variables.


问:
Convert Array of Dictionary to custom object swift
I have:

```<code>    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]
</code>```

I want to add all this array of dictionary to my custom object like

```<code>let country:[Country] = countries
</code>```

My custom object looks like this:

```<code>class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }
</code>```

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

答:
There are a lot of answers already, but I find that there are short comings with most of them. This is what I would suggest:

```<code>extension Country {
    init?(fromDict dict: [String: Any]) {
        guard let name = dict["name"] as? String,
              let dialCode = dict["dial_code"] as? String,
              let code = dict["code"] as? String else {
            return nil
        }
        self.init(name: name, dialCode: dialCode, code: code)
    }
}

let countries = countryDictionaries.map { dict -> Country in
    if let country = Country(fromDict: dict) { return Country }
    else {
        preconditionFailure("Tried to convert an invalid dict into a country")
        // TODO: handle error appropriately
    }
}
</code>```

If you just want to ignore invalid country dictionaries, that's even easier:

```<code>let countries = countryDictionaries.flatMap(Country.init(fromDict:))
</code>```

Body:
I have:

    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]

I want to add all this array of dictionary to my custom object like

let country:[Country] = countries

My custom object looks like this:

class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

Body:
There are a lot of answers already, but I find that there are short comings with most of them. This is what I would suggest:

extension Country {
    init?(fromDict dict: [String: Any]) {
        guard let name = dict["name"] as? String,
              let dialCode = dict["dial_code"] as? String,
              let code = dict["code"] as? String else {
            return nil
        }
        self.init(name: name, dialCode: dialCode, code: code)
    }
}

let countries = countryDictionaries.map { dict -> Country in
    if let country = Country(fromDict: dict) { return Country }
    else {
        preconditionFailure("Tried to convert an invalid dict into a country")
        // TODO: handle error appropriately
    }
}

If you just want to ignore invalid country dictionaries, that's even easier:

let countries = countryDictionaries.flatMap(Country.init(fromDict:))


问:
How to create Performance testing framework in jmeter?
For functional automation we use to create a framework which is reusable for automating application. Is there any way to create Performance testing framework in jmeter. So that we can use same framework for Performance testing of different applications.

Please help if any one knows and provide more information regarding it.

答:
You must first ask yourself, how dynamic is my conversation that I am attempting to replicate.  If you have a very stable services API where the exposed external interface is static, but the code to handle it on the back end is changing, then you have a good shot at building something which has a long life.

But, if you are like the majority of web sites in the universe then you are dealing with developers who are always changing something, adding a resource, adding of deleting form values (hidden or not), headers, etc....  In this case you should consider that your scripts are perishable, with a limited life, and you will need to rebuild them at some point.

Having noted the limited lifetime of a piece of code to test a piece of code with a limited lifetime, are there some techniques you can use to insulate yourself?  Yes.  Rule of thumb is the higher up the stack you go to build your test scripts the more insulated you are from changes under the covers ( assuming the layer you build to is stable ).  The trade off is with more of the intelligence under the covers of your test interface, the higher the resource cost for any individual virtual user which then dictates more hosts for test execution and more skew from client side code which can distort the view of what is coming from the server.   An example, run a selenium script instead of a base jmeter script.  A browser is invoked, you have the benefit of all of the local javascript processing to handle the dynamic changes and your script has a longer life.


问:
Lua: Piece of code to a specific circumstance
I'm making a (poor) cryptography script in Lua and for this, I need to make a loop that will return a value for each number in a string, for example:

```<code>Input: 15, 18, 1, 20, 15, 18, 15, 5, 21, 1, 18, 15, 21, 16, 1, 4, 15, 18, 5, 9, 4, 5, 18, 15, 13, 1
</code>```

And I want it to return each of these digits to a function which will do a certain math with them, then return the correspondent letter for each of the resulting numbers (15 will become 'o', 18 will become 'r' and so on)

Explaining in detail, I need the a piece of code to insert into a function that will:

Return each of the numbers in a string to a function.

After this, the function needs to convert the numbers into letters (as previously said).

Then a new function needs to insert the resulting letters in a new string.

Here's a brief example of how it needs to behave.

```<code>Input: 8, 5, 12, 12, 15
Result: 26, 7, 15, 15, 12 (These numbers aren't constant because of a hidden math made inside the function.)

Input: 26, 7, 15, 15, 12
Result: z, g, o, o, l

Input: z, g, o, o, l
Result: "zgool"
</code>```

I think the source code of this project isn't necessary for this occasion, I'll just implement this code into the functions on the script. Please, someone (who understands what I meant) can help me?

答:
```<code>local function my_poor_cryptography(s)
   local codes = {}
   -- string to numbers
   for c in s:gmatch"%a" do
      table.insert(codes, c:byte() - (c:find"%l" and 96 or 64))
   end
   -- math here (https://en.wikipedia.org/wiki/ROT13)
   for j = 1, #codes do
      codes[j] = (codes[j] + 12) % 26 + 1
   end
   -- numbers to string
   s = s:gsub("%a",
      function(c)
         return c.char(table.remove(codes, 1) + (c:find"%l" and 96 or 64))
      end)
   return s
end
</code>```

Usage:

```<code>local str = "Hello, World!"
str = my_poor_cryptography(str)
print(str)     --> Uryyb, Jbeyq!
str = my_poor_cryptography(str)
print(str)     --> Hello, World!
</code>```

Body:
I'm making a (poor) cryptography script in Lua and for this, I need to make a loop that will return a value for each number in a string, for example:

Input: 15, 18, 1, 20, 15, 18, 15, 5, 21, 1, 18, 15, 21, 16, 1, 4, 15, 18, 5, 9, 4, 5, 18, 15, 13, 1

And I want it to return each of these digits to a function which will do a certain math with them, then return the correspondent letter for each of the resulting numbers (15 will become 'o', 18 will become 'r' and so on)

Explaining in detail, I need the a piece of code to insert into a function that will:

Return each of the numbers in a string to a function.

After this, the function needs to convert the numbers into letters (as previously said).

Then a new function needs to insert the resulting letters in a new string.

Here's a brief example of how it needs to behave.

Input: 8, 5, 12, 12, 15
Result: 26, 7, 15, 15, 12 (These numbers aren't constant because of a hidden math made inside the function.)

Input: 26, 7, 15, 15, 12
Result: z, g, o, o, l

Input: z, g, o, o, l
Result: "zgool"

I think the source code of this project isn't necessary for this occasion, I'll just implement this code into the functions on the script. Please, someone (who understands what I meant) can help me?

Body:
local function my_poor_cryptography(s)
   local codes = {}
   -- string to numbers
   for c in s:gmatch"%a" do
      table.insert(codes, c:byte() - (c:find"%l" and 96 or 64))
   end
   -- math here (https://en.wikipedia.org/wiki/ROT13)
   for j = 1, #codes do
      codes[j] = (codes[j] + 12) % 26 + 1
   end
   -- numbers to string
   s = s:gsub("%a",
      function(c)
         return c.char(table.remove(codes, 1) + (c:find"%l" and 96 or 64))
      end)
   return s
end

Usage:

local str = "Hello, World!"
str = my_poor_cryptography(str)
print(str)     --> Uryyb, Jbeyq!
str = my_poor_cryptography(str)
print(str)     --> Hello, World!


问:
ES query over different types and join over a common field
I'm trying to investigate if this is a possiblity in elasticsearch, since I want to decouple at its best the data, I would like to have inside an index different types one for each field.

Question1: how bad is this decision?

Now, if I've type name:

```<code>/myindex/name

{
    "name" : "mat",
    "id":1
}
</code>```

and surname

```<code>/myindex/surname
{
    "surname" : "txt",
    "id":1
}
</code>```

question 2: how can i create a search that is name='mat AND surname='txt' and returns id?

If I run the query as this (on the index, without specifying the type):

```<code>/myindex/_search
{

    "query" : {
       "bool" : {
        "should" : [{
            "term" : { "name" : "mat" }
        },
        {
            "term" : { "surname" : "txt" }
        }]
       }
    }
}
</code>```

it returns (obviusly) two documents, can I say something like join by id ?

答:
If you're going to use ElasticSearch (or any other noSQL database), you really need to change your mindset around "joins".  We don't do joins in noSQL...at all...ever.  Instead, what you should do is put duplicate data in each record.

Take the following example: Let's say I have a product, and each product has a product type.

In SQL, the 2 records would look like this:

```<code>| Product ID | Product Name | Product Type ID |
| ---------- | ------------ | --------------- |
| 1 | product name 1 | 99 |
| 2 | product name 2 | 99 |
</code>```

In elasticsearch, we would store the data like this:

```<code>products/product/1
{
    "name": "product name 1",
    "type: {
        "type name": "product type 99"
    }
}

products/product/2
{
    "name": "product name 2",
    "type: {
        "type name": "product type 99"
    }
}
</code>```

Notice how the product type information is duplicated in both rows.  As a general rule, noSQL has the advantage of being much faster, at the cost of data duplication.  This means that it's much harder to change the name "product type 99" because I'd need to change it in N records.

Hopefully that helps.

Body:
I'm trying to investigate if this is a possiblity in elasticsearch, since I want to decouple at its best the data, I would like to have inside an index different types one for each field.

Question1: how bad is this decision?

Now, if I've type name:

/myindex/name

{
    "name" : "mat",
    "id":1
}

and surname

/myindex/surname
{
    "surname" : "txt",
    "id":1
}

question 2: how can i create a search that is name='mat AND surname='txt' and returns id?

If I run the query as this (on the index, without specifying the type):

/myindex/_search
{

    "query" : {
       "bool" : {
        "should" : [{
            "term" : { "name" : "mat" }
        },
        {
            "term" : { "surname" : "txt" }
        }]
       }
    }
}

it returns (obviusly) two documents, can I say something like join by id ?

Body:
If you're going to use ElasticSearch (or any other noSQL database), you really need to change your mindset around "joins".  We don't do joins in noSQL...at all...ever.  Instead, what you should do is put duplicate data in each record.

Take the following example: Let's say I have a product, and each product has a product type.

In SQL, the 2 records would look like this:

| Product ID | Product Name | Product Type ID |
| ---------- | ------------ | --------------- |
| 1 | product name 1 | 99 |
| 2 | product name 2 | 99 |

In elasticsearch, we would store the data like this:

products/product/1
{
    "name": "product name 1",
    "type: {
        "type name": "product type 99"
    }
}

products/product/2
{
    "name": "product name 2",
    "type: {
        "type name": "product type 99"
    }
}

Notice how the product type information is duplicated in both rows.  As a general rule, noSQL has the advantage of being much faster, at the cost of data duplication.  This means that it's much harder to change the name "product type 99" because I'd need to change it in N records.

Hopefully that helps.


问:
How to separate fields in a text file with a delimiter
I have a scenario where I have a text file and I want to separate the row values in the text file with a particular delimiter (say, :).

I have generated the text file by storing the output of an SQL query into a text file.

The contents of the text file are

```<code>field 1.2     xxxx
field 2.7.1   xxxx
field 1.9     xxxx
field 1.4     xxxx
field 2.7.1   xxxx
</code>```

I tried this:

```<code>cat /tmp/file.txt | sed 's/ /:/g'
</code>```

but as the space is not consistent over the rows, this does not work for me.

How can I do this?
the output that i am expecting here is something like this

```<code>field :1.2    :xxxx
field :2.7.1  :xxxx
field :1.9    :xxxx
field :1.4    :xxxx
field :2.7.1  :xxxx
</code>```

答:
You can use tr with its "squeeze" option:

```<code>$ tr -s ' ' : < input
field:1.2:xxxx
field:2.7.1:xxxx
field:1.9:xxxx
field:1.4:xxxx
field:2.7.1:xxxx
</code>```

This squeezes any sequence of repeated spaces into a single one, which is then replaced by a colon.

Body:
I have a scenario where I have a text file and I want to separate the row values in the text file with a particular delimiter (say, :).

I have generated the text file by storing the output of an SQL query into a text file.

The contents of the text file are

field 1.2     xxxx
field 2.7.1   xxxx
field 1.9     xxxx
field 1.4     xxxx
field 2.7.1   xxxx

I tried this:

cat /tmp/file.txt | sed 's/ /:/g'

but as the space is not consistent over the rows, this does not work for me.

How can I do this?
the output that i am expecting here is something like this

field :1.2    :xxxx
field :2.7.1  :xxxx
field :1.9    :xxxx
field :1.4    :xxxx
field :2.7.1  :xxxx

Body:
You can use tr with its "squeeze" option:

$ tr -s ' ' : < input
field:1.2:xxxx
field:2.7.1:xxxx
field:1.9:xxxx
field:1.4:xxxx
field:2.7.1:xxxx

This squeezes any sequence of repeated spaces into a single one, which is then replaced by a colon.


问:
What is default css display value for react web application?
I was passing upwork test for react.js and I have got this question, I realy don't know, and google/react documentation don't help me. Can anyone know? it is very interesting to me)

答: I think the right answer is browser dependent. It can't be inherit. See my jsbin example. I set display: inline-block on #root. And after rendering h1 only has browser default value display: block.


问:
Multiple key names, same pair value
I'm trying to setup an object literal in a JavaScript script that has a key with multiple names. referring to the same object value i.e. something like these that I have already tried:

```<code>var holidays: {
    "thanksgiving day", "thanksgiving", "t-day": {
        someValue : "foo"
    }
}

var holidays: {
    ["thanksgiving day", "thanksgiving", "t-day"]: {
        someValue : "foo"
    }
}
</code>```

Is there a way I can accomplish this?

答:
Another solution, if you can afford RegExp execution, and ES6 Proxy:

```<code>let align = new Proxy({

    'start|top|left': -1,
    'middle|center': 0,
    'end|bottom|right': 1,

}, {

    get: function(target, property, receiver) {

        for (let k in target)
            if (new RegExp(k).test(property))
                return target[k]

        return null

    }

})

align.start     // -1
align.top       // -1
align.left      // -1

align.middle    // 0
align.center    // 0

align.end       // 1
align.bottom    // 1
align.right     // 1
</code>```

See MDN Proxy

2021 EDIT:

Another (cleaner?) solution using reduce & defineProperty :

```<code>const myDict = [
    // list of pairs [value, keys],
    // note that a key should appear only once
    [-1, ['start', 'left', 'top']],
    [0, ['center', 'middle']],
    [1, ['end', 'right', 'bottom']],
].reduce((obj, [value, keys]) => {
    for (const key of keys) {
        Object.defineProperty(obj, key, { value })
    }
    return obj
}, {})
</code>```

Title: Multiple key names, same pair value

Body:
I'm trying to setup an object literal in a JavaScript script that has a key with multiple names. referring to the same object value i.e. something like these that I have already tried:

var holidays: {
    "thanksgiving day", "thanksgiving", "t-day": {
        someValue : "foo"
    }
}

var holidays: {
    ["thanksgiving day", "thanksgiving", "t-day"]: {
        someValue : "foo"
    }
}

Is there a way I can accomplish this?

Body:
Another solution, if you can afford RegExp execution, and ES6 Proxy:

let align = new Proxy({

    'start|top|left': -1,
    'middle|center': 0,
    'end|bottom|right': 1,

}, {

    get: function(target, property, receiver) {

        for (let k in target)
            if (new RegExp(k).test(property))
                return target[k]

        return null

    }

})

align.start     // -1
align.top       // -1
align.left      // -1

align.middle    // 0
align.center    // 0

align.end       // 1
align.bottom    // 1
align.right     // 1

See MDN Proxy

2021 EDIT:

Another (cleaner?) solution using reduce & defineProperty :

const myDict = [
    // list of pairs [value, keys],
    // note that a key should appear only once
    [-1, ['start', 'left', 'top']],
    [0, ['center', 'middle']],
    [1, ['end', 'right', 'bottom']],
].reduce((obj, [value, keys]) => {
    for (const key of keys) {
        Object.defineProperty(obj, key, { value })
    }
    return obj
}, {})