答:
You can add a ID to checkbox one and write a style for that separately,
JSFiddle Code Here</p>

```<code>   #chk1 {
      margin :0px !important;
    }

    <div class="checkboxes">
  <span>
    <input type="checkbox" id="chk1" name="Mow" value="Mow"> One
    <input type="checkbox" name="Weedeat" value="Weedeat"> Two
    <input type="checkbox" name="Edge" value="Edge"> Three
    <input type="checkbox" name="Other" value="Other"> Four
  </span>
  </div>
</code>```

Title: Spacing between checkboxes and values

Body:
You can add a ID to checkbox one and write a style for that separately,
JSFiddle Code Here

   #chk1 {
      margin :0px !important;
    }

    <div class="checkboxes">
  <span>
    <input type="checkbox" id="chk1" name="Mow" value="Mow"> One
    <input type="checkbox" name="Weedeat" value="Weedeat"> Two
    <input type="checkbox" name="Edge" value="Edge"> Three
    <input type="checkbox" name="Other" value="Other"> Four
  </span>
  </div>


来源: stackexchange

问:
How do I redirect the user back to the page he comes from using vue-router middleware?
I have the following created the following codes that works as middlewares to my vue components.

```<code>  Router.beforeEach(
  (to, from, next) => {
    if (to.matched.some(record => record.meta.forVisitors)) {
      if (Vue.auth.isAuthenticated()) {
        next({
          path: '/home'
        })
      } else next()
    } else if (to.matched.some(record => record.meta.forAuth)) {
      if (!Vue.auth.isAuthenticated()) {
        next({
          path: '/login'
        })
      } else next()
    } else if (to.matched.some(record => record.meta.forLog)) {
      if (Vue.auth.isAuthenticated()) {
        next({
          path: from()
        })
      }else if (!localStorage.getItem('validUser')) {
                next({
          path: '/login'
        })
            } else next()
    } else next()
  }
)
</code>```

Most of the middlewares are working fine. but the from() is not working.
I also tried to do this as from but it is not still redirecting the user back to the page he came from.

答:
If you console.log from you get the following

```<code>Object {name: null, meta: Object, path: "/", hash: "", query: Object…}
fullPath
:
"/"
hash
:
""
matched
:
Array(0)
meta
:
Object
name
:
null
params
:
Object
path
:
"/"
query
:
Object
__proto__
:
Object
</code>```

You can see that from is not a string but an object. Instead, use the path attribute of the object like in the sample below

```<code>else if (to.matched.some(record => record.meta.forLog)) {
   if (Vue.auth.isAuthenticated()) {
    console.log(from);
    next({
       path: from.path
    })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following created the following codes that works as middlewares to my vue components.

  Router.beforeEach(
  (to, from, next) => {
    if (to.matched.some(record => record.meta.forVisitors)) {
      if (Vue.auth.isAuthenticated()) {
        next({
          path: '/home'
        })
      } else next()
    } else if (to.matched.some(record => record.meta.forAuth)) {
      if (!Vue.auth.isAuthenticated()) {
        next({
          path: '/login'
        })
      } else next()
    } else if (to.matched.some(record => record.meta.forLog)) {
      if (Vue.auth.isAuthenticated()) {
        next({
          path: from()
        })
      }else if (!localStorage.getItem('validUser')) {
                next({
          path: '/login'
        })
            } else next()
    } else next()
  }
)

Most of the middlewares are working fine. but the from() is not working.
I also tried to do this as from but it is not still redirecting the user back to the page he came from.

Body:
If you console.log from you get the following

Object {name: null, meta: Object, path: "/", hash: "", query: Object…}
fullPath
:
"/"
hash
:
""
matched
:
Array(0)
meta
:
Object
name
:
null
params
:
Object
path
:
"/"
query
:
Object
__proto__
:
Object

You can see that from is not a string but an object. Instead, use the path attribute of the object like in the sample below

else if (to.matched.some(record => record.meta.forLog)) {
   if (Vue.auth.isAuthenticated()) {
    console.log(from);
    next({
       path: from.path
    })


问:
What is the proper way to use services in Angular4?
I ask this because I’m new in Angular4, and the thing for me is: Should I use a service inside a model. e.g. a simple class for a type stucture or inside a component? My doubt comes from a stackoverflow answer, that said that a component is similar to the C in MVC.</p>

答:
The View (Template) depends on the Model (Json Objects) for data; the View also depends on the Controller (Component Class) for methods (Click Handlers). The Controller (Component Class) knows about the Models (Json Objects); the Controller depends on Services (Dependency Injected) to get the Data (Json Objects).

So, a service should be dependency injected into a Component class. Setup the dependency injection within your module.


问:
Spacing between checkboxes and values
JSFiddle

How would I go about editing the HTML/CSS  to create spacing between each checkbox/value pairing? Right now each checkbox and each value are spaced evenly. I'd like value1 to be close to checkbox1, but checkbox2 to have some distance from the value1.

Code here:

```<code>.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 20px 0;
}

<div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four
  </span>
</div>
</code>```

答:
you need to reduce right margin a bit and may need to increase left margin

```<code>.checkboxes input{
  margin: 0 5px 0 30px;
}
</code>```

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 5px 0 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="checkboxes">
      <span>
        <input type="checkbox" name="Mow" value="Mow"> One
        <input type="checkbox" name="Weedeat" value="Weedeat"> Two
        <input type="checkbox" name="Edge" value="Edge"> Three
        <input type="checkbox" name="Other" value="Other"> Four
      </span>
      </div></code>```

Title: Spacing between checkboxes and values

Body:
JSFiddle

How would I go about editing the HTML/CSS  to create spacing between each checkbox/value pairing? Right now each checkbox and each value are spaced evenly. I'd like value1 to be close to checkbox1, but checkbox2 to have some distance from the value1.

Code here:

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 20px 0;
}

    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four

Body:
you need to reduce right margin a bit and may need to increase left margin

.checkboxes input{
  margin: 0 5px 0 30px;
}

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 5px 0 30px;
}

    <div class="checkboxes">
      <span>
        <input type="checkbox" name="Mow" value="Mow"> One
        <input type="checkbox" name="Weedeat" value="Weedeat"> Two
        <input type="checkbox" name="Edge" value="Edge"> Three
        <input type="checkbox" name="Other" value="Other"> Four
      </span>
      </div>


答:
You are currently declaring three values for the input's margin.

Declare four so you can target top, left, bottom, and right, respectively.

.checkboxes {
  text-align: center;
}

.checkboxes input{
  margin: 0 0 0 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four
  </span>
</div></code>```

Title: Spacing between checkboxes and values

Body:
You are currently declaring three values for the input's margin.

Declare four so you can target top, left, bottom, and right, respectively.

.checkboxes {
  text-align: center;
}

.checkboxes input{
  margin: 0 0 0 20px;
}

<div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four
  </span>
</div>


问:
Use data from *ngFor outside of *ngFor scope
Here is a sample problem that i want to actually solve. Your help will really appreciate. Thanks a lot!</p>

```<code><div>
  <div>
    <!-- is it possible to put the item.preview here?
        It is outside of *ngFor
    -->
  </div>
  <div *ngFor="let item of items">
      <img [src]="item.cover" alt="item.name">
  </div>
</div>
</code>```

答:
There is not a way to directly show one item outside of an *ngFor unless you set one of the items into a variable.  Usually this would be based on some event (e.x. click(), mouseover(), etc..)

Here is an example showing a common pattern where a user clicks your image, this sets another variable which is then displayed anywhere else on the component as needed.

Here is a working plunker:
https://plnkr.co/edit/TzBjhisaPCD2pznb10B0?p=preview

```<code>import {Component, NgModule, VERSION, OnInit, Input} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

interface Item {
  id: number;
  name: string;
  covor: string
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  <div>
    <div>
      {{selectedItem | json}}
    </div>
    <div *ngFor="let item of items">
        <img [src]="item.cover" alt="item.name" (click)="selectItem(item)">
    </div>
  </div>
  `,
})
export class App implements OnInit {
  name:string;

  // This is an input just to show that this might be where the data comes from
  // otherwise call a service to set the data initially
  @Input() items: Item[] = [
    {id: 1, name: 'test', cover: 'https://i.vimeocdn.com/portrait/58832_300x300'},
    {id: 2, name: 'test2', cover: 'https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300'},
  ];
  selectedItem: Item;

  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  ngOnInit() {
    // you can init your item here
    if(this.items.length > 0) {
      this.selectedItem = this.items[0];
    }
  }

  selectItem(item: Item) {
    this.selectedItem = item;
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
</code>```

Body:
There is not a way to directly show one item outside of an *ngFor unless you set one of the items into a variable.  Usually this would be based on some event (e.x. click(), mouseover(), etc..)

Here is an example showing a common pattern where a user clicks your image, this sets another variable which is then displayed anywhere else on the component as needed.

Here is a working plunker:
https://plnkr.co/edit/TzBjhisaPCD2pznb10B0?p=preview

import {Component, NgModule, VERSION, OnInit, Input} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

interface Item {
  id: number;
  name: string;
  covor: string
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  <div>
    <div>
      {{selectedItem | json}}
    </div>
    <div *ngFor="let item of items">
        <img [src]="item.cover" alt="item.name" (click)="selectItem(item)">
    </div>
  </div>
  `,
})
export class App implements OnInit {
  name:string;

  // This is an input just to show that this might be where the data comes from
  // otherwise call a service to set the data initially
  @Input() items: Item[] = [
    {id: 1, name: 'test', cover: 'https://i.vimeocdn.com/portrait/58832_300x300'},
    {id: 2, name: 'test2', cover: 'https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300'},
  ];
  selectedItem: Item;

  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  ngOnInit() {
    // you can init your item here
    if(this.items.length > 0) {
      this.selectedItem = this.items[0];
    }
  }

  selectItem(item: Item) {
    this.selectedItem = item;
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}


问:
Lucene .net + equivalent of SpanMultiTermQueryWrapper<MultiTermQuery> in C#
I need to convert the following Java code to C# but I couldn't find the equivalent of "SpanMultiTermQueryWrapper". Could you please help?</p>

```<code>FuzzyQuery firstNameQuery = new FuzzyQuery(new Term("text", firstName), 2);
FuzzyQuery lastNameQuery = new FuzzyQuery(new Term("text", lastName), 2);

SpanQuery[] clauses = new SpanQuery[] {
  new SpanMultiTermQueryWrapper<MultiTermQuery>(firstNameQuery),
  new SpanMultiTermQueryWrapper<MultiTermQuery>(lastNameQuery)
};
SpanNearQuery spanNearQuery = new SpanNearQuery(clauses, 3, false);
</code>```

答:
SpanMultiTermQueryWrapper and MultiTermQuery are both available on Lucene.Net 4.8.0-beta00004.

If you need support in earlier versions of Lucene.Net, you can probably just grab the source code from the above links and any dependencies and drop them into a library for your applications.

Body:
I need to convert the following Java code to C# but I couldn't find the equivalent of "SpanMultiTermQueryWrapper". Could you please help?

FuzzyQuery firstNameQuery = new FuzzyQuery(new Term("text", firstName), 2);
FuzzyQuery lastNameQuery = new FuzzyQuery(new Term("text", lastName), 2);

SpanQuery[] clauses = new SpanQuery[] {
  new SpanMultiTermQueryWrapper<MultiTermQuery>(firstNameQuery),
  new SpanMultiTermQueryWrapper<MultiTermQuery>(lastNameQuery)
};
SpanNearQuery spanNearQuery = new SpanNearQuery(clauses, 3, false);


问:
JSON or object when pass the data to scope
I use the 'Postman' to fetch the data from API, it returns JSON format. Why I can either JSON or object to scope? Both JSON and object format is working. The difference between JSON and object (from my understanding) is that, JSON has double quote for key (for this example, "answers" has double quote), but object does not have double quote for key.

Here is the data returned from API:

```<code> [
        {
            "answers": [
                {
                    "answer": "Yes",
                    "count": 0,
                    "id": 1,
                    "question_id": 1
                },
                {
                    "answer": "No",
                    "count": 0,
                    "id": 2,
                    "question_id": 1
                }
            ],
            "id": 1,
            "question": "Is this hard?"
        },
   ...
]
</code>```

Here is the data passed to scope. You can see, both JSON ("answers") and object (answers) format are working.

Updates: I want to know why API returns JSON data format, but we can pass JSON or object to scope? Which we should choose, JSON or object?

答:
JSON is a standard of string representation of JavaScript objects (JavaScript Object Notation). So they may logically represent the same information but are fundamentally different. You don't need to choose, you must send JSON (assume we are talking on HTTP level).

Objects conceptually can only live in the memory space and can have some piece of information that can't be easily serialized to textual content and don't have the corresponding JSON representation (references, bytes, ...)

Body:
I use the 'Postman' to fetch the data from API, it returns JSON format. Why I can either JSON or object to scope? Both JSON and object format is working. The difference between JSON and object (from my understanding) is that, JSON has double quote for key (for this example, "answers" has double quote), but object does not have double quote for key.

Here is the data returned from API:

 [
        {
            "answers": [
                {
                    "answer": "Yes",
                    "count": 0,
                    "id": 1,
                    "question_id": 1
                },
                {
                    "answer": "No",
                    "count": 0,
                    "id": 2,
                    "question_id": 1
                }
            ],
            "id": 1,
            "question": "Is this hard?"
        },
   ...
]

Here is the data passed to scope. You can see, both JSON ("answers") and object (answers) format are working.

Updates: I want to know why API returns JSON data format, but we can pass JSON or object to scope? Which we should choose, JSON or object?


问:
Why doesn't the for loop in the code below run as an infinite loop (i continuing after -1 as 1 2 3...-3 -2 -1)?
```<code>    #include<stdio.h>
    int main()
    {
    char i = 0;
    for( i<=5 && i>=-1 ; ++i ; i>0)
        printf("%d ",i);
    return 0;
    }
</code>```

<p>output is 1 2 3 ...127 -128 -127 ... -3 -2 -1.Can anyone explain how it stops after printing -1? </p>

答:
```<code> for( i<=5 && i>=-1 ; ++i ; i>0)
    printf("%d ",i);
</code>```

Here ++i is the condition part.When i=-1 and then ++i becomes 0 which evaluates to false and the loop breaks.

Body:
    #include<stdio.h>
    int main()
    {
    char i = 0;
    for( i<=5 && i>=-1 ; ++i ; i>0)
        printf("%d ",i);
    return 0;
    }

output is 1 2 3 ...127 -128 -127 ... -3 -2 -1.Can anyone explain how it stops after printing -1?

Body:
 for( i<=5 && i>=-1 ; ++i ; i>0)
    printf("%d ",i);

Here ++i is the condition part.When i=-1 and then ++i becomes 0 which evaluates to false and the loop breaks.


问:
Video source with onclick selector
Hi StackOverflow friends. Sorry for being so noob, but I cannot manage to get this snippet working. All I wanted to do was selecting a number from a , and change the video src of the following player replacing that number inside the url itself. For example if I would choose the number 13 my plan was obtaining a refresh of the player with the new source, in this case "https://hostingsite.com/folder/Episode_13_Cartoon.mp4", but as you can see I'm not used to work in js so any help would be highly appreciated. Thanks in advance, here's the snippet

function changeVideo() {
        document.getElementById("player").src = "https://hostingsite.com/folder/Episode_" + episode + "_Cartoon.mp4";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="players">
<div class="container">
   <div class="media-container">
      <span class="title">Episode Selector</span>
      onclick="{ document.getElementById('episode').value='13'; changeVideo();}">
      onclick="{ document.getElementById('episode').value='14'; changeVideo();}">
      onclick="{ document.getElementById('episode').value='15'; changeVideo();}">
      <select name="player1-sources" id="player1-sources">
         <option value="">Select source</option>
         <option value="12">12</option>
         <option value="13">13</option>
         <option value="14">14</option>
      </select>
      <video id="player" width="100%" height="100%" controls preload="auto" src="https://hostingsite.com/folder/Episode_default_Cartoon.mp4" type="video/mp4"></video>
   </div>
</div></code>```

答:
// get the select box element
let select = document.getElementById('player1-sources');

// add event listener for 'change'
select.addEventListener('change', changeVideo);

// do this when the select box value changes
function changeVideo() {

  // the event listener handler sets 'this' to the element that triggered the handler. So 'this' is our select element.

// using the ternary operator here
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

// set the protocol based on number
let protocol = this.value > 10 ? 'https' : 'http';

// set the source
let src = this.value.toLowerCase() === 'film' ? 'https://hostingsite.com/folder/Film_Cartoon.mp4' : protocol + "://hostingsite.com/folder/Episode_" + this.value + "_Cartoon.mp4";

// set player source
document.getElementById("player").src = src;

// log it out for fun
console.log(src);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="players">
  <div class="container">
    <div class="media-container">
      <span class="title">Episode Selector</span>

      <select name="player1-sources" id="player1-sources">
                 <option value="Film">Select source</option>
                 <option value="9">9</option>
                 <option value="10">10</option>
                 <option value="11">11</option>
                 <option value="12">12</option>
                 <option value="13">13</option>
                 <option value="14">14</option>
              </select>
      <video id="player" width="100%" height="100%" controls preload="auto" src="https://hostingsite.com/folder/Episode_default_Cartoon.mp4" type="video/mp4"></video>
    </div>
  </div></code>```

Title: Video source with onclick selector

Body:
Hi StackOverflow friends. Sorry for being so noob, but I cannot manage to get this snippet working. All I wanted to do was selecting a number from a , and change the video src of the following player replacing that number inside the url itself. For example if I would choose the number 13 my plan was obtaining a refresh of the player with the new source, in this case "https://hostingsite.com/folder/Episode_13_Cartoon.mp4", but as you can see I'm not used to work in js so any help would be highly appreciated. Thanks in advance, here's the snippet

function changeVideo() {
        document.getElementById("player").src = "https://hostingsite.com/folder/Episode_" + episode + "_Cartoon.mp4";
}

      Episode Selector

      <select name="player1-sources" id="player1-sources">
         <option value="">Select source</option>
         <option value="12">12</option>
         <option value="13">13</option>
         <option value="14">14</option>
      </select>
      <video id="player" width="100%" height="100%" controls preload="auto" src="https://hostingsite.com/folder/Episode_default_Cartoon.mp4" type="video/mp4"></video>

Body:
// get the select box element
let select = document.getElementById('player1-sources');

// add event listener for 'change'
select.addEventListener('change', changeVideo);

// do this when the select box value changes
function changeVideo() {

  // the event listener handler sets 'this' to the element that triggered the handler. So 'this' is our select element.

// using the ternary operator here
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

// set the protocol based on number
let protocol = this.value > 10 ? 'https' : 'http';

// set the source
let src = this.value.toLowerCase() === 'film' ? 'https://hostingsite.com/folder/Film_Cartoon.mp4' : protocol + "://hostingsite.com/folder/Episode_" + this.value + "_Cartoon.mp4";

// set player source
document.getElementById("player").src = src;

// log it out for fun
console.log(src);
}

<section class="players">
  <div class="container">
    <div class="media-container">
      <span class="title">Episode Selector</span>

      <select name="player1-sources" id="player1-sources">
                 <option value="Film">Select source</option>
                 <option value="9">9</option>
                 <option value="10">10</option>
                 <option value="11">11</option>
                 <option value="12">12</option>
                 <option value="13">13</option>
                 <option value="14">14</option>
              </select>
      <video id="player" width="100%" height="100%" controls preload="auto" src="https://hostingsite.com/folder/Episode_default_Cartoon.mp4" type="video/mp4"></video>
    </div>
  </div>


问:
Angular 1.5 filter with ng-repeat not working by track by id
so I tried so many different ways to get this done. Followed so many StackOverflow and could not get this to work. All I am trying to do is to filter some list items based on the value of a boolean property. Below is the picture of my object data. The closest example I am following is this question Filtering an Angular 1.2 ng-repeat with "track by" by a boolean property. Still not working. does it have anything to do with an object literal and this type of filtering with property only works with array? I am new to javascript so not sure. Also using angular material, virtual repeat container and other material based things are not affecting the result, I can display the whole data, just the filtered by this specific property not working

      loadAssets = () => {

        var self = this;
        self.infiniteAssets = {
            numLoaded_: 0,
            toLoad_: 0,
            items: [],
            pageNum:1,
            virtualIndex:0,

            getItemAtIndex: function (index) {
                this.virtualIndex=index;

                if (index > this.numLoaded_) {
                    this.fetchMoreItems_(index);
                    return null;
                }
                return this.items[index];
            },

            // Required.
            getLength: function () {
                if (this.virtualIndex > this.numLoaded_) {
                    return this.numLoaded_ ;
                }else{
                    return this.numLoaded_ + 5 ;
                }
            },

            fetchMoreItems_ : function (index) {
                if (this.toLoad_ < index) {
                    self.loading = true;
                    this.toLoad_ += 20;
                    self.siAsset.getAssets(this.pageNum++,20)
                        .then(angular.bind(this, function (assets) {
                            //this.objLength = assets.length;
                            if(! assets.statusCode){
                                this.items = this.items.concat(assets);
                                this.toLoad_ = this.items.length;
                                this.numLoaded_ = this.toLoad_;
                            }
                            self.loading = false;
                        }))
                }
            }
        };
        console.log('++++++++++',self.infiniteAssets)```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <md-virtual-repeat-container id="vertical-container" ng-show="$ctrl.infiniteAssets.getLength() > 0 && $ctrl.switch">

          <md-list>
            <md-list-item  class="list-page" md-on-demand md-virtual-repeat="asset in $ctrl.infiniteAssets | filter: {disabled: true } track by asset.id" ng-click="$ctrl.loadDetail(asset)">
              <span class="search-status" style="border-left-color:{{asset.statusColor}};"></span>
              <p >{{asset.name}} </p>
              <label hide-xs ng-if="asset.disabled" class="ng-animate-disabled">
                <md-chips >
                  <md-chip >{{'LABELS.DISABLED' | translate}}</md-chip>
                </md-chips>
              </label>
              <label ><i>{{asset.status || 'UNKNOWN'}}</i></label>
                 <md-button  aria-label="Delete Asset" class="md-icon-button md-warn" layout-padding ng-click="$ctrl.deleteAsset(asset)">
                       <md-icon md-svg-icon="delete" class="modelTrashIcon"></md-icon>
                  </md-button>
              <md-divider></md-divider>
            </md-list-item>
          </md-list>
        </md-virtual-repeat-container></code>```

答:
As per you said, "Angular 1.5 filter with ng-repeat not working by track by id"

I have created sample example using AngularJs 1.5, and used filter with track by on ng-repeat.

angular.module('controllerAsExample', [])
  .controller('SettingsController1', SettingsController1);

function SettingsController1() {

   this.infiniteAssets = [
     {disabled :false, name:'test0',id:234 },
     {disabled :true, name:'test1',id:123 },
     {disabled :false, name:'test2',id:345 }
     ];
        //console.log(this.infiniteAssets);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html >
  <head>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>

  </head>
  <body ng-app="controllerAsExample">

<div  ng-controller="SettingsController1 as settings">
  <p>ng-repeat with track by field example using angularjs 1.5.0:</p>
  <ul>
 <li ng-repeat="asset in settings.infiniteAssets | filter: {disabled: false } track by asset.id">
 {{asset.name}}
 </li>
 </ul>
</div>

  </body>
</html></code>```

Body:
so I tried so many different ways to get this done. Followed so many StackOverflow and could not get this to work. All I am trying to do is to filter some list items based on the value of a boolean property. Below is the picture of my object data. The closest example I am following is this question Filtering an Angular 1.2 ng-repeat with "track by" by a boolean property. Still not working. does it have anything to do with an object literal and this type of filtering with property only works with array? I am new to javascript so not sure. Also using angular material, virtual repeat container and other material based things are not affecting the result, I can display the whole data, just the filtered by this specific property not working

      loadAssets = () => {

        var self = this;
        self.infiniteAssets = {
            numLoaded_: 0,
            toLoad_: 0,
            items: [],
            pageNum:1,
            virtualIndex:0,

            getItemAtIndex: function (index) {
                this.virtualIndex=index;

                if (index > this.numLoaded_) {
                    this.fetchMoreItems_(index);
                    return null;
                }
                return this.items[index];
            },

            // Required.
            getLength: function () {
                if (this.virtualIndex > this.numLoaded_) {
                    return this.numLoaded_ ;
                }else{
                    return this.numLoaded_ + 5 ;
                }
            },

            fetchMoreItems_ : function (index) {
                if (this.toLoad_ < index) {
                    self.loading = true;
                    this.toLoad_ += 20;
                    self.siAsset.getAssets(this.pageNum++,20)
                        .then(angular.bind(this, function (assets) {
                            //this.objLength = assets.length;
                            if(! assets.statusCode){
                                this.items = this.items.concat(assets);
                                this.toLoad_ = this.items.length;
                                this.numLoaded_ = this.toLoad_;
                            }
                            self.loading = false;
                        }))
                }
            }
        };
        console.log('++++++++++',self.infiniteAssets)

    <md-virtual-repeat-container id="vertical-container" ng-show="$ctrl.infiniteAssets.getLength() > 0 && $ctrl.switch">

          <md-list>
            <md-list-item  class="list-page" md-on-demand md-virtual-repeat="asset in $ctrl.infiniteAssets | filter: {disabled: true } track by asset.id" ng-click="$ctrl.loadDetail(asset)">

{{asset.name}}

                <md-chips >
                  <md-chip >{{'LABELS.DISABLED' | translate}}</md-chip>
                </md-chips>

              {{asset.status || 'UNKNOWN'}}
                 <md-button  aria-label="Delete Asset" class="md-icon-button md-warn" layout-padding ng-click="$ctrl.deleteAsset(asset)">
                       <md-icon md-svg-icon="delete" class="modelTrashIcon"></md-icon>
                  </md-button>
              <md-divider></md-divider>
            </md-list-item>
          </md-list>
        </md-virtual-repeat-container>

Body:
As per you said, "Angular 1.5 filter with ng-repeat not working by track by id"

I have created sample example using AngularJs 1.5, and used filter with track by on ng-repeat.

angular.module('controllerAsExample', [])
  .controller('SettingsController1', SettingsController1);

function SettingsController1() {

   this.infiniteAssets = [
     {disabled :false, name:'test0',id:234 },
     {disabled :true, name:'test1',id:123 },
     {disabled :false, name:'test2',id:345 }
     ];
        //console.log(this.infiniteAssets);
}

<!doctype html>
<html >
  <head>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>

  </head>
  <body ng-app="controllerAsExample">

<div  ng-controller="SettingsController1 as settings">
  <p>ng-repeat with track by field example using angularjs 1.5.0:</p>
  <ul>
 <li ng-repeat="asset in settings.infiniteAssets | filter: {disabled: false } track by asset.id">
 {{asset.name}}
 </li>
 </ul>
</div>

  </body>
</html>


问:
Substitute FROM ISNULL in where clause in ms sql server
We used Stored Procedure on our Queries. Some of our field got NULL value, so for us to get this value we Put the conversion of ISNULL inside the WHERE condition but per checking it affects the Process of our strodproc based on the SQL performance tool.

Ex.

```<code>SELECT * FROM tblInfo
WHERE ISNULL(fldInfo,'') <> ''
</code>```

tblInfo

```<code>fldinfo
NULL
30
NULL
20
</code>```

Query

```<code>SELECT * FROM tblinfo WHERE fldinfo NOT IN (30,20) - different result
SELECT * FROM tblinfo WHERE ISNULL(fldinfo,'') NOT IN (30,20) - Correct
</code>```

Result

Any other Substitute process of script we can use so that we can get the value but not affecting the performance of the query.

答:
Your approach will be non sargable. Even though you have an index it will not be used.

Right way to do this would be using IS NOT NULL condition

```<code>SELECT * FROM tblInfo
WHERE fldInfo <> ''
  AND fldInfo IS NOT NULL
</code>```

If you don't have a index, then create a index on fldinfo to improve the performance

Update :

Not In fails to compare the NULL values. Comparison with NULL values are unknown so it is fails to return the NULL values. Here is the correct way to do this

```<code>SELECT *
FROM   tblInfo
WHERE  (fldinfo NOT IN ( 30, 20 ) OR fldinfo IS NULL)
</code>```

Body:
We used Stored Procedure on our Queries. Some of our field got NULL value, so for us to get this value we Put the conversion of ISNULL inside the WHERE condition but per checking it affects the Process of our strodproc based on the SQL performance tool.

Ex.

SELECT * FROM tblInfo
WHERE ISNULL(fldInfo,'') <> ''

tblInfo

fldinfo
NULL
30
NULL
20

Query

SELECT * FROM tblinfo WHERE fldinfo NOT IN (30,20) - different result
SELECT * FROM tblinfo WHERE ISNULL(fldinfo,'') NOT IN (30,20) - Correct

Result

Any other Substitute process of script we can use so that we can get the value but not affecting the performance of the query.

Body:
Your approach will be non sargable. Even though you have an index it will not be used.

Right way to do this would be using IS NOT NULL condition

SELECT * FROM tblInfo
WHERE fldInfo <> ''
  AND fldInfo IS NOT NULL

If you don't have a index, then create a index on fldinfo to improve the performance

Update :

Not In fails to compare the NULL values. Comparison with NULL values are unknown so it is fails to return the NULL values. Here is the correct way to do this

SELECT *
FROM   tblInfo
WHERE  (fldinfo NOT IN ( 30, 20 ) OR fldinfo IS NULL)

ContentLicense: CC BY-SA 4.0


问:
How to change the rate of an AVPlayer video
Hey I'm trying to get a video to play at a different rate (Slower). I can't seem to get it to work.

Code:

This line of code doesn't work

```<code>playerLayerView.player?.rate = 0.50
</code>```

Full Code:

```<code>var player = AVPlayer()
var playerLayer = AVPlayerLayer()
var playerLayerView = AVPlayerViewController()

let path = Bundle.main.path(forResource: "Video", ofType: "mov")
let prl = URL(fileURLWithPath: path!)
player = AVPlayer(url: prl)
playerLayerView.player = player
playerLayerView.view.frame = CGRect(.frame.width * 0.0, .frame.height * 0.0, .frame.width, .frame.height)
playerLayerView.videoGravity = AVLayerVideoGravity.resizeAspectFill.rawValue
playerLayerView.player?.rate = 0.50
player.seek(to: kCMTimeZero)
player.isMuted = false
page.insertSubview(playerLayerView.view, at: 0)
playerLayerView.player?.play()
</code>```

The only why can get it to play is. If I use playImmediately and delete the .Play()

```<code>player.playImmediately(atRate: 0.50) //.rate = 1.50 //0.50, 0.67, 0.80, 1.0, 1.25, 1.50, and 2.0
</code>```

答: Set the rate property after playerLayerView.player?.play() calling this method.</p>

Body:
Hey I'm trying to get a video to play at a different rate (Slower). I can't seem to get it to work.

Code:

This line of code doesn't work

playerLayerView.player?.rate = 0.50

Full Code:

var player = AVPlayer()
var playerLayer = AVPlayerLayer()
var playerLayerView = AVPlayerViewController()

let path = Bundle.main.path(forResource: "Video", ofType: "mov")
let prl = URL(fileURLWithPath: path!)
player = AVPlayer(url: prl)
playerLayerView.player = player
playerLayerView.view.frame = CGRect(.frame.width * 0.0, .frame.height * 0.0, .frame.width, .frame.height)
playerLayerView.videoGravity = AVLayerVideoGravity.resizeAspectFill.rawValue
playerLayerView.player?.rate = 0.50
player.seek(to: kCMTimeZero)
player.isMuted = false
page.insertSubview(playerLayerView.view, at: 0)
playerLayerView.player?.play()

The only why can get it to play is. If I use playImmediately and delete the .Play()

player.playImmediately(atRate: 0.50) //.rate = 1.50 //0.50, 0.67, 0.80, 1.0, 1.25, 1.50, and 2.0


答:
you added padding on both side of checkbox

```<code> /*margin: 0 20px;*/
  margin-left: 40px;
</code>```

.checkboxes {
  text-align:center;
}

.checkboxes input{
  /*margin: 0 20px;*/
  margin-left: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four
  </span>
</div></code>```

Title: Spacing between checkboxes and values

Body:
you added padding on both side of checkbox

 /*margin: 0 20px;*/
  margin-left: 40px;

.checkboxes {
  text-align:center;
}

.checkboxes input{
  /*margin: 0 20px;*/
  margin-left: 40px;
}

<div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four
  </span>
</div>


问:
Sharing Redux state to other clients doesn't work when stringified
I am directly sending a redux state from one client to another by simple converting objects to string and sending over websocket and received and parsing and dispatching to store.

The issue is if object is like this :

```<code>"{"type":"some_action","uid":"1","updates":{"attributes":{"content":["hello"]}}}"
</code>```

then it works fine but if let's say object is like this :

then i get the error on other client : https://facebook.github.io/react/docs/error-decoder.html?invariant=31&args%5B%5D=object%20with%20keys%20%7Btype%2C%20key%2C%20ref%2C%20props%2C%20_owner%7D&args%5B%5D=

which states object are not valid as react client. Here is stringified version of object in image.

```<code>{
  "type": "some_action",
  "uid": "1",
  "updates": {
    "attributes": {
      "content": [
        {
          "type": "em",
          "key": "_domReact2",
          "ref": null,
          "props": {
            "children": {
              "type": "strong",
              "key": "_domReact1",
              "ref": null,
              "props": {
                "children": "a"
              },
              "_owner": null
            }
          },
          "_owner": null
        }
      ]
    }
  }
}
</code>```

Please see that props can be nested here. I tried a hack which is created a null React.creatElement and merged two object so that i have missing '$$typeof' key and it worked, but i am looking for better way or answers from the community. Thanks!

答:
If you convert a react component or an object with a function to a JSON string using JSON.stringify(), you will loose all functions and only properties will be kept. So when converting back to an object using JSON.parse() the object could not work properly. Example below.

A better way could be to pass the react state as JSON (or part of it) to another client, and use the reducer to update client state. When the state will be update your React component should be too.

Example:

Send a message using websocket which contains object redux action serialized in JSON. In redux an Action (Object) is a plain object describing the change that makes sense for your application and can be serialized.
From the client which receive the message, parse the JSON so you can recreate the action object. Now re-dispatch your action so the reducer can modify the state in that client. For this use dispatch(action) which will trigger a state change.

let test = {
   a(){
    alert('hi')
   },
   b: 'prop'
};

let str = JSON.stringify(test);
console.log(str);

let obj = JSON.parse(str);
console.log(obj); // a has been lost```

Body:
I am directly sending a redux state from one client to another by simple converting objects to string and sending over websocket and received and parsing and dispatching to store.

The issue is if object is like this :

"{"type":"some_action","uid":"1","updates":{"attributes":{"content":["hello"]}}}"

then it works fine but if let's say object is like this :

then i get the error on other client : https://facebook.github.io/react/docs/error-decoder.html?invariant=31&args%5B%5D=object%20with%20keys%20%7Btype%2C%20key%2C%20ref%2C%20props%2C%20_owner%7D&args%5B%5D=

which states object are not valid as react client. Here is stringified version of object in image.

{
  "type": "some_action",
  "uid": "1",
  "updates": {
    "attributes": {
      "content": [
        {
          "type": "em",
          "key": "_domReact2",
          "ref": null,
          "props": {
            "children": {
              "type": "strong",
              "key": "_domReact1",
              "ref": null,
              "props": {
                "children": "a"
              },
              "_owner": null
            }
          },
          "_owner": null
        }
      ]
    }
  }
}

Please see that props can be nested here. I tried a hack which is created a null React.creatElement and merged two object so that i have missing '$$typeof' key and it worked, but i am looking for better way or answers from the community. Thanks!


问:
If you don’t want Eloquent to automatically manage created_at and updated_at columns, which of the following will be correct?

Set the model $timestamps property to false.

Eloquent will always automatically manage created_at and updated_at
columns.

Set the model $created_at and updated_at properties to false.

I searched the net and found a lot of solution and what must be the real answer to this question,

I found that we can disable it add a line into the eloquent to make timestamp false

```<code>class User extends Eloquent {

    protected $table = 'users';

    public $timestamps = false;

}
</code>```

But we can also remove the created_at and updated_at and do not use it in the model so 3rd point is also true here?

So what is the proper solution for this question?

答: you should set the $timestamps property to false in your model. and not add the timestamp columns ($table->timestamps();) in your table migration.

Body:
Set the model $timestamps property to false.

Eloquent will always automatically manage created_at and updated_at
columns.

Set the model $created_at and updated_at properties to false.

I searched the net and found a lot of solution and what must be the real answer to this question,

I found that we can disable it add a line into the eloquent to make timestamp false

class User extends Eloquent {

    protected $table = 'users';

    public $timestamps = false;

}

But we can also remove the created_at and updated_at and do not use it in the model so 3rd point is also true here?

So what is the proper solution for this question?


答:
Maybe you are a little confused about what are JSON and Objects in Javascript

JSON

JSON format is only for send data in a structured way, and it only can contain String, Bool, Number, Array, and another JSON inside (nested JSON)

Object

In javascript objects have the same as JSON but with big different, that you can execute code Javascript inside them, so you can do it like so:

```<code>var object = {
 "hola": function(){
   console.log("This will work because this object can exec JS code")
 },
 age: 26,
 admin: false
}
</code>```

Title: JSON or object when pass the data to scope

Body:
Maybe you are a little confused about what are JSON and Objects in Javascript

JSON

JSON format is only for send data in a structured way, and it only can contain String, Bool, Number, Array, and another JSON inside (nested JSON)

Object

In javascript objects have the same as JSON but with big different, that you can execute code Javascript inside them, so you can do it like so:

var object = {
 "hola": function(){
   console.log("This will work because this object can exec JS code")
 },
 age: 26,
 admin: false
}


答:
Use This Code

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0px 0px 0px 0px;
}

.checkboxes label{
  margin: 0px 20px 0px 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head></head>

  <body>
    <div class="checkboxes">
    <span>
      <input type="checkbox" name="Mow" value="Mow"> <label>One</label>
      <input type="checkbox" name="Weedeat" value="Weedeat"> <label>Two</label>
      <input type="checkbox" name="Edge" value="Edge"> <label>Three</label>
      <input type="checkbox" name="Other" value="Other"> <label>Four</label>
    </span>
    </div>
  </body>

</html></code>```

Title: Spacing between checkboxes and values

Body:
JSFiddle

How would I go about editing the HTML/CSS  to create spacing between each checkbox/value pairing? Right now each checkbox and each value are spaced evenly. I'd like value1 to be close to checkbox1, but checkbox2 to have some distance from the value1.

Code here:

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 20px 0;
}

    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four

Body:
Use This Code

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0px 0px 0px 0px;
}

.checkboxes label{
  margin: 0px 20px 0px 3px;
}

<html>
  <head></head>

  <body>
    <div class="checkboxes">
    <span>
      <input type="checkbox" name="Mow" value="Mow"> <label>One</label>
      <input type="checkbox" name="Weedeat" value="Weedeat"> <label>Two</label>
      <input type="checkbox" name="Edge" value="Edge"> <label>Three</label>
      <input type="checkbox" name="Other" value="Other"> <label>Four</label>
    </span>
    </div>
  </body>

</html>


问:
What better way to use CSS / JS in Laravel and where to put it?
What do I call style files? Are there good practices? Laravel v.5.4</p>

答:
I use ```<code>{!! Html::script(asset('js/app.js?v=12')) !!}</code>```
and  ```<code>{!! Html::style(asset('css/app.css')) !!}</code>```
I think this is short code.</p>

Body:
I use
{!! Html::script(asset('js/app.js?v=12')) !!}

and
{!! Html::style(asset('css/app.css')) !!}

I think this is short code.


问:
Publish to Facebook Stream via PHP using Graph API
I'm trying to post a message to a user's wall using the new graph API and PHP. Connection seems to work fine, but no post appears. I'm not sure how to set up the posting code correctly. Please help me out. Sorry for the broken-looking code, for some reason StackOverflow didn't want to close it all in the code block.

Below is my full code. Am I missing an extender permission requests, or is that taken care in this code:

PHP Code

```<code><?php

include_once 'facebook.php';

$facebook = new Facebook(array(
    'appId'  => 'xxxxxxxxxxxxxxxxxx',
    'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
    'cookie' => true
));

$session = $facebook->getSession();

if (!$session) {
    $url = $facebook->getLoginUrl(array(
        'canvas' => 1,
        'fbconnect' => 0
    ));
    echo "<script type='text/javascript'>top.location.href = '$url';</script>";

} else {
    try {
        $uid = $facebook->getUser();
        $me = $facebook->api('/me');
        $updated = date("l, F j, Y", strtotime($me['updated_time']));
        echo "Hello " . $me['name'] . "<br />";
        echo "You last updated your profile on " . $updated;

        $connectUrl = $facebook->getUrl(
          'www',
          'login.php',
          array_merge(array(
            'api_key'         => $facebook->getAppId(),
            'cancel_url'      => 'http://www.test.com',
            'req_perms'       => 'publish_stream',
            'display'         => 'page',
            'fbconnect'       => 1,
            'next'            => 'http://www.test.com',
            'return_session'  => 1,
            'session_version' => 3,
            'v'               => '1.0',
          ), $params)
        );

        $result = $facebook->api(
            '/me/feed/',
            'post',
            array('access_token' => $facebook->access_token, 'message' => 'Playing around with FB Graph..')
        );

    } catch (FacebookApiException $e) {
        echo "Error:" . print_r($e, true);
    }
}
?>
</code>```

答:
it's because you didn't sepcify the "req_perms" and allow the app to publish stream to your wall. Make sure you add "publish_stream" in your "req_perms.

PHP code:

```<code>$url = $facebook->getLoginUrl(array(
                   'canvas' => 1,   //set to 1 bcoz my application is Iframe app
                   'fbconnect' => 0,
                   'req_perms' => 'publish_stream'
               ));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to post a message to a user's wall using the new graph API and PHP. Connection seems to work fine, but no post appears. I'm not sure how to set up the posting code correctly. Please help me out. Sorry for the broken-looking code, for some reason StackOverflow didn't want to close it all in the code block.

Below is my full code. Am I missing an extender permission requests, or is that taken care in this code:

PHP Code

<?php

include_once 'facebook.php';

$facebook = new Facebook(array(
    'appId'  => 'xxxxxxxxxxxxxxxxxx',
    'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
    'cookie' => true
));

$session = $facebook->getSession();

if (!$session) {
    $url = $facebook->getLoginUrl(array(
        'canvas' => 1,
        'fbconnect' => 0
    ));
    echo "";

} else {
    try {
        $uid = $facebook->getUser();
        $me = $facebook->api('/me');
        $updated = date("l, F j, Y", strtotime($me['updated_time']));
        echo "Hello " . $me['name'] . "
";
        echo "You last updated your profile on " . $updated;

        $connectUrl = $facebook->getUrl(
          'www',
          'login.php',
          array_merge(array(
            'api_key'         => $facebook->getAppId(),
            'cancel_url'      => 'http://www.test.com',
            'req_perms'       => 'publish_stream',
            'display'         => 'page',
            'fbconnect'       => 1,
            'next'            => 'http://www.test.com',
            'return_session'  => 1,
            'session_version' => 3,
            'v'               => '1.0',
          ), $params)
        );

        $result = $facebook->api(
            '/me/feed/',
            'post',
            array('access_token' => $facebook->access_token, 'message' => 'Playing around with FB Graph..')
        );

    } catch (FacebookApiException $e) {
        echo "Error:" . print_r($e, true);
    }
}
?>

Body:
it's because you didn't sepcify the "req_perms" and allow the app to publish stream to your wall. Make sure you add "publish_stream" in your "req_perms.

PHP code:

$url = $facebook->getLoginUrl(array(
                   'canvas' => 1,   //set to 1 bcoz my application is Iframe app
                   'fbconnect' => 0,
                   'req_perms' => 'publish_stream'
               ));


问:
aligning text to top of webpage in html code using css
I have this css code:

```<code>.post {
    margin-top: 0.5em;
    margin-left: 2em;
    margin-right: 2em;
    text-align: center;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}
</code>```

and have this in html:

```<code><div class="post">
 <h1>Title of Sample Work 2</h1>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.</p>
</div>
</code>```

And this is what I see:

Why there is so much margin at the top and the text title is so down?
You can see an example of the actual page on the web here:
http://www.nanogomo.com/sample1.html

It is interesting that if I add more content to it, it pushes the text up.

答:
Try setting a value to margin and padding:</p>

```<code>.post h1{
    text-align: center;
    margin: 0px;
    padding: 0px;
}
</code>```

Body:
I have this css code:

.post {
    margin-top: 0.5em;
    margin-left: 2em;
    margin-right: 2em;
    text-align: center;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}

and have this in html:

Title of Sample Work 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.

And this is what I see:

Why there is so much margin at the top and the text title is so down?
You can see an example of the actual page on the web here:
http://www.nanogomo.com/sample1.html

It is interesting that if I add more content to it, it pushes the text up.

Body:
Try setting a value to margin and padding:

.post h1{
    text-align: center;
    margin: 0px;
    padding: 0px;
}


问:
Trying to use Crystal's Bycrypt library - "invalid salt size"
I'm trying to hash + salt user passwords with the Bcrypt library that ships with Crystal.

The following code produces an "Invalid salt size" error, when run in a playground.

```<code>require "crypto/bcrypt"

user = "Jones"
pass = "password"

temp = Crypto::Bcrypt.new(pass, user)
</code>```

Relevant source code

答:
Use the Crypto::Bcrypt::Password API,  don't directly use Crypto::Bcrypt.

You don't use the username in the BCrypt hash generation, the API will use a random value as the salt.

```<code>bcryptHash = Crypto::Bcrypt::Password.create("password123")
</code>```

See https://crystal-lang.org/api/master/Crypto/Bcrypt/Password.html

Body:
I'm trying to hash + salt user passwords with the Bcrypt library that ships with Crystal.

The following code produces an "Invalid salt size" error, when run in a playground.

require "crypto/bcrypt"

user = "Jones"
pass = "password"

temp = Crypto::Bcrypt.new(pass, user)

Relevant source code

Body:
Use the Crypto::Bcrypt::Password API,  don't directly use Crypto::Bcrypt.

You don't use the username in the BCrypt hash generation, the API will use a random value as the salt.

bcryptHash = Crypto::Bcrypt::Password.create("password123")

See https://crystal-lang.org/api/master/Crypto/Bcrypt/Password.html


问:
Programmatically set the Background color of a Drawable in Android?
I have an image in a resource file.

```<code>Drawable draw = getResources().getDrawable(R.drawable.my_icon);
</code>```

The image has a transparent background.

Is there a way to programmatically set the background color to the Drawable before using the end product further in my code?

答:
setColorFilter() with Porterduff SRC will break the transparent of drawable.

I used this in my code, and it work

```<code>disabledIcon = ContextCompat.getDrawable(getContext(), resId);
disabledIcon = DrawableCompat.wrap(disabledIcon);
disabledIcon.mutate(); // to not share its state with any other drawable
DrawableCompat.setTint(disabledIcon, ContextCompat.getColor(getContext(), R.color.button_text_disabled));
</code>```

Body:
I have an image in a resource file.

Drawable draw = getResources().getDrawable(R.drawable.my_icon);

The image has a transparent background.

Is there a way to programmatically set the background color to the Drawable before using the end product further in my code?

Body:
setColorFilter() with Porterduff SRC will break the transparent of drawable.

I used this in my code, and it work

disabledIcon = ContextCompat.getDrawable(getContext(), resId);
disabledIcon = DrawableCompat.wrap(disabledIcon);
disabledIcon.mutate(); // to not share its state with any other drawable
DrawableCompat.setTint(disabledIcon, ContextCompat.getColor(getContext(), R.color.button_text_disabled));


问:
Check sheet exist or not in spreatsheet Google spreadsheet API PHP
How to check if sheet exits in a spreadsheet (check sheet by name) or not using Google Sheet API. I have used Google Sheet API v4.

If a sheet is not existed then create a new sheet.

Thanks

答:
Finally I found Solution.There is no method available to check sheet exist or not in spreadsheet.

I have used spreadsheet object to get all information of spreadsheet. and make custom function to check specific sheet name exist or not and it's working fine.

```<code>    function myArrayContainsWord(array $myArray, $word) {
    foreach ($myArray as $element) {
        if ($element->title == $word) {
            return true;
        }
    }
    return false;
  }

   $service = new Google_Service_Sheets($client);
   $spreadsheetId = 'your spredsheetid';
   $sheetInfo = $service->spreadsheets->get($spreadsheetId);
   $allsheet_info = $sheetInfo['sheets'];
   $idCats = array_column($allsheet_info, 'properties');

   if (myArrayContainsWord($idCats, "sheetname")) {
      //echo found
   }
</code>```

Body:
Finally I found Solution.There is no method available to check sheet exist or not in spreadsheet.

I have used spreadsheet object to get all information of spreadsheet. and make custom function to check specific sheet name exist or not and it's working fine.

    function myArrayContainsWord(array $myArray, $word) {
    foreach ($myArray as $element) {
        if ($element->title == $word) {
            return true;
        }
    }
    return false;
  }

   $service = new Google_Service_Sheets($client);
   $spreadsheetId = 'your spredsheetid';
   $sheetInfo = $service->spreadsheets->get($spreadsheetId);
   $allsheet_info = $sheetInfo['sheets'];
   $idCats = array_column($allsheet_info, 'properties');

   if (myArrayContainsWord($idCats, "sheetname")) {
      //echo found
   }


问:
how to apply background color to the found text
hello i have following code and it works fine for finding and replacing string... but it is not working globally..how to make it to work as globally and after replacing i want to highlight that string into green color.. how..?</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
 <script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
 <script>
$(document).ready(function(){
$('#replace').click(function(){
var oldstr=$('#inputstring').val();
var newstr=$('#newstring').val();
var para=$('#para').html();
var result=$('p:contains('+oldstr+')');

if(result)
{
var x=para.replace(new RegExp(oldstr, 'i','g'), newstr);
$('#para').empty().html(x);

}
})
})
 </script>
 </head>

 <body>
  Enter the string to find:<input type="text" id="inputstring"><br>
  Enter string to replace:<input type="text" id="newstring"><br>
  <input type="button" value="Replace" id="replace"><br>
  <p id="para">This is the new paragraph written to test how to replace the a string  with desired string</p>
 </body>
</html>
</code>```

答:
```<code>$('body').html($('body').html().replace(oldstr, '<span style="color: green">' + newstr + '</span>'));
</code>```

Body:
hello i have following code and it works fine for finding and replacing string... but it is not working globally..how to make it to work as globally and after replacing i want to highlight that string into green color.. how..?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> New Document </title>

  Enter the string to find:<input type="text" id="inputstring">

  Enter string to replace:<input type="text" id="newstring">

  <input type="button" value="Replace" id="replace">

This is the new paragraph written to test how to replace the a string  with desired string


问:
how to convert typedef basic_string<char> string to byte array in cpp
I am trying to pass cpp string to java android using JNI.

```<code>void Endpoint::utilLogWrite(int prmLevel,
                const string &prmSender,
                const string &prmMsg)
</code>```

so when i read the prmMsg from java using JNI i get exception.
The  below exception occurs while converting that cpp string to java String.

JNI DETECTED ERROR IN APPLICATION

I have no control over JNIMethods.so searching stackoverflow tells instead of sending cpp string prefer sending byte array.

The variable prmMsg is of type typedef basic_string
so how to convert this typedef basic_string    string to byte array.In java we have simple method

String.toBytes()

.But IN CPP how can i achieve it.

答:
"input is not valid Modified UTF-8: illegal start byte": Yep, UTF-8 is not the same as Modified UTF-8, which is a crutch JNI offers [and, in some places (class paths and member names, etc), demands]. So, I like your approach of using Java to do any character encoding conversions.

To create a byte array, call NewByteArray. To fill it, call SetByteArrayRegion. To get jbytes out of a std::string, call data and cast.

```<code>std::string s = "\xF0\x9F\x9A\xB2";

// jbyte and char are the same size
const auto output = env->NewByteArray(s.length());
env->SetByteArrayRegion(output, 0, s.length(), reinterpret_cast<const jbyte *>(s.data()));
return output; // return or release output
</code>```

Body:
I am trying to pass cpp string to java android using JNI.

void Endpoint::utilLogWrite(int prmLevel,
                const string &prmSender,
                const string &prmMsg)

so when i read the prmMsg from java using JNI i get exception.
The  below exception occurs while converting that cpp string to java String.

JNI DETECTED ERROR IN APPLICATION

I have no control over JNIMethods.so searching stackoverflow tells instead of sending cpp string prefer sending byte array.

The variable prmMsg is of type typedef basic_string
so how to convert this typedef basic_string    string to byte array.In java we have simple method

String.toBytes()

.But IN CPP how can i achieve it.

Body:
"input is not valid Modified UTF-8: illegal start byte": Yep, UTF-8 is not the same as Modified UTF-8, which is a crutch JNI offers [and, in some places (class paths and member names, etc), demands]. So, I like your approach of using Java to do any character encoding conversions.

To create a byte array, call NewByteArray. To fill it, call SetByteArrayRegion. To get jbytes out of a std::string, call data and cast.

std::string s = "\xF0\x9F\x9A\xB2";

// jbyte and char are the same size
const auto output = env->NewByteArray(s.length());
env->SetByteArrayRegion(output, 0, s.length(), reinterpret_cast<const jbyte *>(s.data()));
return output; // return or release output


问:
lodash check object properties has values
I have object with several properties, says it's something like this

```<code>{ a: "", b: undefined }
</code>```

in jsx is there any one line solution I can check whether that object's property is not empty or has value or not? If array there's a isEmpty method.

I tried this

```<code>const somethingKeyIsnotEmpty = Object.keys((props.something, key, val) => {
        return val[key] !== '' || val[key] !== undefined
})
</code>```

答:
In lodash, you can use _.some</p>

```<code>_.some(props.something, _.isEmpty)
</code>```

Body:
I have object with several properties, says it's something like this

{ a: "", b: undefined }

in jsx is there any one line solution I can check whether that object's property is not empty or has value or not? If array there's a isEmpty method.

I tried this

const somethingKeyIsnotEmpty = Object.keys((props.something, key, val) => {
        return val[key] !== '' || val[key] !== undefined
})

Body:
In lodash, you can use _.some

_.some(props.something, _.isEmpty)


问:
Extracting most frequent words out of a corpus with python
Maybe this is a stupid question, but I have a problem with extracting the ten most frequent words out of a corpus with Python. This is what I've got so far. (btw, I work with NLTK for reading a corpus with two subcategories with each 10 .txt files)

```<code>import re
import string
from nltk.corpus import stopwords
stoplist = stopwords.words('dutch')

from collections import defaultdict
from operator import itemgetter

def toptenwords(mycorpus):
    words = mycorpus.words()
    no_capitals = set([word.lower() for word in words])
    filtered = [word for word in no_capitals if word not in stoplist]
    no_punct = [s.translate(None, string.punctuation) for s in filtered]
    wordcounter = {}
    for word in no_punct:
        if word in wordcounter:
            wordcounter[word] += 1
        else:
            wordcounter[word] = 1
    sorting = sorted(wordcounter.iteritems(), key = itemgetter, reverse = True)
    return sorting
</code>```

If I print this function with my corpus, it gives me a list of all words with '1' behind it. It gives me a dictionary but all my values are one. And I know that for example the word 'baby' is five or six times in my corpus... And still it gives 'baby: 1'... So it doesn't function the way I want...

Can someone help me?

答:
The pythonic way:</p>

```<code>In [1]: from collections import Counter

In [2]: words = ['hello', 'hell', 'owl', 'hello', 'world', 'war', 'hello', 'war']

In [3]: counter_obj = Counter(words)

In [4]: counter_obj.most_common() #counter_obj.most_common(n=10)
Out[4]: [('hello', 3), ('war', 2), ('hell', 1), ('world', 1), ('owl', 1)]
</code>```

Body:
Maybe this is a stupid question, but I have a problem with extracting the ten most frequent words out of a corpus with Python. This is what I've got so far. (btw, I work with NLTK for reading a corpus with two subcategories with each 10 .txt files)

import re
import string
from nltk.corpus import stopwords
stoplist = stopwords.words('dutch')

from collections import defaultdict
from operator import itemgetter

def toptenwords(mycorpus):
    words = mycorpus.words()
    no_capitals = set([word.lower() for word in words])
    filtered = [word for word in no_capitals if word not in stoplist]
    no_punct = [s.translate(None, string.punctuation) for s in filtered]
    wordcounter = {}
    for word in no_punct:
        if word in wordcounter:
            wordcounter[word] += 1
        else:
            wordcounter[word] = 1
    sorting = sorted(wordcounter.iteritems(), key = itemgetter, reverse = True)
    return sorting

If I print this function with my corpus, it gives me a list of all words with '1' behind it. It gives me a dictionary but all my values are one. And I know that for example the word 'baby' is five or six times in my corpus... And still it gives 'baby: 1'... So it doesn't function the way I want...

Can someone help me?

Body:
The pythonic way:

In [1]: from collections import Counter

In [2]: words = ['hello', 'hell', 'owl', 'hello', 'world', 'war', 'hello', 'war']

In [3]: counter_obj = Counter(words)

In [4]: counter_obj.most_common() #counter_obj.most_common(n=10)
Out[4]: [('hello', 3), ('war', 2), ('hell', 1), ('world', 1), ('owl', 1)]


问:
How to uninstall global package with npm?
I have installed webpack in this way:

```<code>npm install -g webpack
</code>```

Now want to uninstall it:

```<code>npm uninstall -g webpack
</code>```

Check it again, it didn't been uninstalled:

```<code>webpack -v
3.1.0
</code>```

Why?

And, I use this way can't find webpack:

```<code>npm list -g | grep webpack
</code>```

This also didn't work:

```<code>npm uninstall -g webpack --save
</code>```

After run this under a directory which included package.json:

```<code>npm uninstall webpack
npm WARN babel-loader@6.4.1 requires a peer of webpack@1 || 2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.
npm WARN uglifyjs-webpack-plugin@0.3.1 requires a peer of uglify-js@^2.8.0 but none was installed.
npm WARN uglifyjs-webpack-plugin@0.3.1 requires a peer of webpack@^1.9 || ^2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.
</code>```

答:
Try running both of the below commands:

```<code>npm uninstall -g webpack
npm uninstall webpack
</code>```

I think you might be checking/looking at the local version after deleting only the global one.

Body:
I have installed webpack in this way:

npm install -g webpack

Now want to uninstall it:

npm uninstall -g webpack

Check it again, it didn't been uninstalled:

webpack -v
3.1.0

Why?

And, I use this way can't find webpack:

npm list -g | grep webpack

This also didn't work:

npm uninstall -g webpack --save

After run this under a directory which included package.json:

npm uninstall webpack
npm WARN babel-loader@6.4.1 requires a peer of webpack@1 || 2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.
npm WARN uglifyjs-webpack-plugin@0.3.1 requires a peer of uglify-js@^2.8.0 but none was installed.
npm WARN uglifyjs-webpack-plugin@0.3.1 requires a peer of webpack@^1.9 || ^2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.

Body:
Try running both of the below commands:

npm uninstall -g webpack
npm uninstall webpack

I think you might be checking/looking at the local version after deleting only the global one.


问:
Attempting to store values stored in variables into SQL Database
Hello quick question regarding storage of variables in a mySQL database in php.

```<code>if(count($_SESSION['cart'])>0) {

$ids = array();
foreach ($_SESSION['cart'] as $id => $value) {
    array_push($ids, $id);
}

$stmt = $food->readByIds($ids);

$total = 0;
$item_count = 0;

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    extract($row);

    $quantity = $_SESSION['cart'][$id]['quantity'];
    $sub_total = $price * $quantity;

    //echo "<div class='product-id' style='display:none;'>{$id}</div>";
    //echo "<div class='product-name'>{$name}</div>";

    // =================
    echo "<div class='cart-row'>";
    echo "<div class='col-md-8'>";

    echo "<div class='food-name m-b-10px'><h4>{$name}</h4></div>";
    echo $quantity > 1 ? "<div>{$quantity} items</div>" : "<div>{$quantity} item</div>";

    echo "</div>";

    echo "<div class='col-md-4'>";
    echo "<h4>$" . number_format($price, 2, '.', ',') . "</h4>";
    echo "</div>";
    echo "</div>";
    // =================

    $item_count += $quantity;
    $total += $sub_total;
}

$sql = "INSERT INTO food_orders (food_list, food_total, created_on) VALUES (:$name, :$total, :current_timestamp)";

$stmt = $db->prepare($sql);

$stmt->bindParam(':$name', $_POST['food_list'], PDO::PARAM_STR);
$stmt->bindParam(':$total', $_POST['food_total'], PDO::PARAM_STR);
$stmt->bindParam(':current_timestamp',$_POST['created_on'], PDO::PARAM_STR);

$stmt->execute();
</code>```

Currently, I am attempting to store the values calculated into the database under the $_POST tag, but I am constantly thrown the error:

```<code>Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number:
parameter was not defined in C:\wamp64\www\phpFoodSitewithCart\charge.php
</code>```

Is there a better way to store the variables or sync them properly?

Thanks for the look and the help.

答: Placeholders should look like :name not :$name. By using $name anywhere inside a double-quoted string you're asking for string interpolation to kick in and unless $name is defined as something that basically removes it from the string, leaving just : which is not valid. The placeholder goes invisible.

Body:
Hello quick question regarding storage of variables in a mySQL database in php.

if(count($_SESSION['cart'])>0) {

$ids = array();
foreach ($_SESSION['cart'] as $id => $value) {
    array_push($ids, $id);
}

$stmt = $food->readByIds($ids);

$total = 0;
$item_count = 0;

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    extract($row);

    $quantity = $_SESSION['cart'][$id]['quantity'];
    $sub_total = $price * $quantity;

    //echo "
{$id}
";
    //echo "
{$name}
";

    // =================
    echo "
";
    echo "
";

    echo "

{$name}

";
    echo $quantity > 1 ? "
{$quantity} items
" : "
{$quantity} item
";

    echo "
";

    echo "
";
    echo "
$" . number_format($price, 2, '.', ',') . "
";
    echo "
";
    echo "
";
    // =================

    $item_count += $quantity;
    $total += $sub_total;
}

$sql = "INSERT INTO food_orders (food_list, food_total, created_on) VALUES (:$name, :$total, :current_timestamp)";

$stmt = $db->prepare($sql);

$stmt->bindParam(':$name', $_POST['food_list'], PDO::PARAM_STR);
$stmt->bindParam(':$total', $_POST['food_total'], PDO::PARAM_STR);
$stmt->bindParam(':current_timestamp',$_POST['created_on'], PDO::PARAM_STR);

$stmt->execute();

Currently, I am attempting to store the values calculated into the database under the $_POST tag, but I am constantly thrown the error:

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number:
parameter was not defined in C:\wamp64\www\phpFoodSitewithCart\charge.php

Is there a better way to store the variables or sync them properly?

Thanks for the look and the help.


问:
IdP initiated saml recieved on SP always has RelayState as null
I have been tasked to implement a SAML2.0 SSO proof of concept and I have successfully integrated the spring saml extension which has been pretty straightforward, thanks to the author. Although, I still haven't been able to get the RelayState parameter to work, I always get its value as null on the receiving SP.

I am using SSOCircle's public IdP with an IdP initiated flow (although we have not blocked the SP initiated mode) and appending the RelayState in the URL.

I am trying to use the SAMLRelayStateSuccessHandler where I could get the RelayState parameter from the SAMLCredential instance but its always null. I traced it back to the HTTPPostDecoder.doDecode(MessageContext messageContext) method (HTTP post binding) and it was null there as well. I also traced the browser network url and noticed the SP consumer end point post url i.e. /saml/SSO contains SAMLResponse but there is no RelayState parameter (my understanding is it will be a separate parameter).

I feel the IdP is probably not sending the RelayState to my SP but also don't see any configuration on the IdP side to enable/disable it so not sure.

I would appreciate advice on debugging this or if someone could share their similar experiences.

答:
I donot have this issue any more but did not explicitly add any fix either. My best guess is ssocircle put in a fix on their end after which the RelayState url started flowing end to end for me.
Appreciate the help by @hos. Did not want to keep the question open so add this as an answer.</p>