问:
How to set a context variable in a template
I want my page to be dependent on a model object which is emitted from an Observable. If the object were a list, I'd use

```<code><div ngFor="let currentListItem of myObservable | async" >
</code>```

however, ngFor is not applicable, since I don't have a list of models, but just one. Is there something like

```<code><div ngContext="let currentItem of myObservable |async" >
</code>```

which would allow me to access currentItem's properties like this

```<code><div ngContext="let currentItem of myObservable |async" >
     <label>{{currentItem.name}}
</div>
</code>```

答:
You can use the as keyword with *ngIf* in Angular 4:

```<code><div *ngIf="myObservable | async as currentItem">
     <label>The current item's name is {{currentItem.name}}</label>
</div>
</code>```

I guess it could work, but seems unweildly. I don't need IF, it should always display...

Well, that's the only way to do what you want. There is no harm in the *ngIf; it will prevent the text I've added (The current item's name is) from displaying until the observable emits, which is presumably what you want anyway.

Body:
I want my page to be dependent on a model object which is emitted from an Observable. If the object were a list, I'd use

however, ngFor is not applicable, since I don't have a list of models, but just one. Is there something like

which would allow me to access currentItem's properties like this

     {{currentItem.name}}

Body:
You can use the as keyword with *ngIf* in Angular 4:

<div *ngIf="myObservable | async as currentItem">
     <label>The current item's name is {{currentItem.name}}</label>
</div>

I guess it could work, but seems unweildly. I don't need IF, it should always display...

Well, that's the only way to do what you want. There is no harm in the *ngIf; it will prevent the text I've added (The current item's name is) from displaying until the observable emits, which is presumably what you want anyway.


来源: stackexchange

问:
Horizontally align div
I'm having trouble horizontally aligning the spinning circle animation (contained within the div with id of "spin-panel") within the outer div (id of "loading") as shown here: https://codepen.io/depaolif/pen/MoYwrP

Does anyone know why margin: auto wouldn't work in this case like it generally does?

HTML:

```<code><div id="loading">
    Loading account info
    <div id="spin-panel">
      <span id="loading8-1">
            <span id="CircleBottom"><span class="ball"></span></span>
      </span>
      <span id="loading8-2">
            <span id="CircleMiddle"><span class="ball"></span></span>
      </span>
      <span id="loading8-3">
            <span id="CircleTop"><span class="ball"></span></span>
      </span>
    </div>
</div>
</code>```

SCSS:

```<code>@keyframes cwSpin {
  0%{transform:rotate(0deg);}
  100%{transform:rotate(360deg);}
}

#loading {
  text-align: center;
  margin-top: 40vh;
  font-size: 40px;
  width: 100vw;

  #spin-panel {
    width: 50%; // this doesn't make a difference
    margin: 0 auto;

    #loading8-1, #loading8-2, #loading8-3 {
      display:block;
      position:absolute;
      margin:30px 0 0 100px;
      width:80px;
      height:80px;
      animation: cwSpin 1s linear 0s infinite;

        #CircleBottom, #CircleMiddle, #CircleTop {
          display:block;
          position:absolute;

          width:100px;
          height:100px;

          border-radius:100px;

          .ball {
            width:20px;
            height:20px;
            display:block;
            position:absolute;
            background-color:#06C;
            border-radius:20px;
            margin:0 0 0 45px;
          }
        }

        #CircleBottom {
          transform:rotate(0deg);
        }
        #CircleMiddle {
          transform:rotate(50deg);
        }
        #CircleTop {
          transform:rotate(100deg);
        }
      }
    }
  }
</code>```

答:
#spin-panel is centered, but the children are absolutely positioned and have margins offsetting their position.

Add position: relative to #spin-panel, and to the children that are spinning, add top: 0; left: 50%; transform: translateX(-50%); and remove the left margins to center them horizontally.

@keyframes cwSpin {
  0% {
    transform: translateX(-50%) rotate(0deg);
  }
  100% {
    transform: translateX(-50%) rotate(360deg);
  }
}
#loading {
  text-align: center;
  margin-top: 40vh;
  font-size: 40px;
  width: 100vw;
}
#loading #spin-panel {
  width: 50%;
  margin: 1em auto 0;
  position: relative;
}
#loading #spin-panel #loading8-1, #loading #spin-panel #loading8-2, #loading #spin-panel #loading8-3 {
  display: block;
  position: absolute;
  margin: 0 0 0 0;
  width: 80px;
  height: 80px;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
}
#loading #spin-panel #loading8-1 #CircleBottom, #loading #spin-panel #loading8-1 #CircleMiddle, #loading #spin-panel #loading8-1 #CircleTop, #loading #spin-panel #loading8-2 #CircleBottom, #loading #spin-panel #loading8-2 #CircleMiddle, #loading #spin-panel #loading8-2 #CircleTop, #loading #spin-panel #loading8-3 #CircleBottom, #loading #spin-panel #loading8-3 #CircleMiddle, #loading #spin-panel #loading8-3 #CircleTop {
  display: block;
  position: absolute;
  width: 100px;
  height: 100px;
  border-radius: 100px;
}
#loading #spin-panel #loading8-1 #CircleBottom .ball, #loading #spin-panel #loading8-1 #CircleMiddle .ball, #loading #spin-panel #loading8-1 #CircleTop .ball, #loading #spin-panel #loading8-2 #CircleBottom .ball, #loading #spin-panel #loading8-2 #CircleMiddle .ball, #loading #spin-panel #loading8-2 #CircleTop .ball, #loading #spin-panel #loading8-3 #CircleBottom .ball, #loading #spin-panel #loading8-3 #CircleMiddle .ball, #loading #spin-panel #loading8-3 #CircleTop .ball {
  width: 20px;
  height: 20px;
  display: block;
  position: absolute;
  background-color: #06C;
  border-radius: 20px;
  margin: 0 0 0 45px;
}
#loading #spin-panel #loading8-1 #CircleBottom, #loading #spin-panel #loading8-2 #CircleBottom, #loading #spin-panel #loading8-3 #CircleBottom {
  transform: rotate(0deg);
}
#loading #spin-panel #loading8-1 #CircleMiddle, #loading #spin-panel #loading8-2 #CircleMiddle, #loading #spin-panel #loading8-3 #CircleMiddle {
  transform: rotate(50deg);
}
#loading #spin-panel #loading8-1 #CircleTop, #loading #spin-panel #loading8-2 #CircleTop, #loading #spin-panel #loading8-3 #CircleTop {
  transform: rotate(100deg);
}
#loading #spin-panel #loading8-1, #loading #spin-panel #loading8-2, #loading #spin-panel #loading8-3 {
  animation: cwSpin 1s linear 0s infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="loading">
  Loading account info
  <div id="spin-panel">
    <span id="loading8-1">
                <span id="CircleBottom"><span class="ball"></span></span>
    </span>
    <span id="loading8-2">
                <span id="CircleMiddle"><span class="ball"></span></span>
    </span>
    <span id="loading8-3">
                <span id="CircleTop"><span class="ball"></span></span>
    </span>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Horizontally align div

Body:
I'm having trouble horizontally aligning the spinning circle animation (contained within the div with id of "spin-panel") within the outer div (id of "loading") as shown here: https://codepen.io/depaolif/pen/MoYwrP

Does anyone know why margin: auto wouldn't work in this case like it generally does?

HTML:

    Loading account info

SCSS:

@keyframes cwSpin {
  0%{transform:rotate(0deg);}
  100%{transform:rotate(360deg);}
}

#loading {
  text-align: center;
  margin-top: 40vh;
  font-size: 40px;
  width: 100vw;

  #spin-panel {
    width: 50%; // this doesn't make a difference
    margin: 0 auto;

    #loading8-1, #loading8-2, #loading8-3 {
      display:block;
      position:absolute;
      margin:30px 0 0 100px;
      width:80px;
      height:80px;
      animation: cwSpin 1s linear 0s infinite;

        #CircleBottom, #CircleMiddle, #CircleTop {
          display:block;
          position:absolute;

          width:100px;
          height:100px;

          border-radius:100px;

          .ball {
            width:20px;
            height:20px;
            display:block;
            position:absolute;
            background-color:#06C;
            border-radius:20px;
            margin:0 0 0 45px;
          }
        }

        #CircleBottom {
          transform:rotate(0deg);
        }
        #CircleMiddle {
          transform:rotate(50deg);
        }
        #CircleTop {
          transform:rotate(100deg);
        }
      }
    }
  }

Body:
#spin-panel is centered, but the children are absolutely positioned and have margins offsetting their position.

Add position: relative to #spin-panel, and to the children that are spinning, add top: 0; left: 50%; transform: translateX(-50%); and remove the left margins to center them horizontally.

@keyframes cwSpin {
  0% {
    transform: translateX(-50%) rotate(0deg);
  }
  100% {
    transform: translateX(-50%) rotate(360deg);
  }
}
#loading {
  text-align: center;
  margin-top: 40vh;
  font-size: 40px;
  width: 100vw;
}
#loading #spin-panel {
  width: 50%;
  margin: 1em auto 0;
  position: relative;
}
#loading #spin-panel #loading8-1, #loading #spin-panel #loading8-2, #loading #spin-panel #loading8-3 {
  display: block;
  position: absolute;
  margin: 0 0 0 0;
  width: 80px;
  height: 80px;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
}
#loading #spin-panel #loading8-1 #CircleBottom, #loading #spin-panel #loading8-1 #CircleMiddle, #loading #spin-panel #loading8-1 #CircleTop, #loading #spin-panel #loading8-2 #CircleBottom, #loading #spin-panel #loading8-2 #CircleMiddle, #loading #spin-panel #loading8-2 #CircleTop, #loading #spin-panel #loading8-3 #CircleBottom, #loading #spin-panel #loading8-3 #CircleMiddle, #loading #spin-panel #loading8-3 #CircleTop {
  display: block;
  position: absolute;
  width: 100px;
  height: 100px;
  border-radius: 100px;
}
#loading #spin-panel #loading8-1 #CircleBottom .ball, #loading #spin-panel #loading8-1 #CircleMiddle .ball, #loading #spin-panel #loading8-1 #CircleTop .ball, #loading #spin-panel #loading8-2 #CircleBottom .ball, #loading #spin-panel #loading8-2 #CircleMiddle .ball, #loading #spin-panel #loading8-2 #CircleTop .ball, #loading #spin-panel #loading8-3 #CircleBottom .ball, #loading #spin-panel #loading8-3 #CircleMiddle .ball, #loading #spin-panel #loading8-3 #CircleTop .ball {
  width: 20px;
  height: 20px;
  display: block;
  position: absolute;
  background-color: #06C;
  border-radius: 20px;
  margin: 0 0 0 45px;
}
#loading #spin-panel #loading8-1 #CircleBottom, #loading #spin-panel #loading8-2 #CircleBottom, #loading #spin-panel #loading8-3 #CircleBottom {
  transform: rotate(0deg);
}
#loading #spin-panel #loading8-1 #CircleMiddle, #loading #spin-panel #loading8-2 #CircleMiddle, #loading #spin-panel #loading8-3 #CircleMiddle {
  transform: rotate(50deg);
}
#loading #spin-panel #loading8-1 #CircleTop, #loading #spin-panel #loading8-2 #CircleTop, #loading #spin-panel #loading8-3 #CircleTop {
  transform: rotate(100deg);
}
#loading #spin-panel #loading8-1, #loading #spin-panel #loading8-2, #loading #spin-panel #loading8-3 {
  animation: cwSpin 1s linear 0s infinite;
}

<div id="loading">
  Loading account info
  <div id="spin-panel">
    <span id="loading8-1">
                <span id="CircleBottom"><span class="ball"></span></span>
    </span>
    <span id="loading8-2">
                <span id="CircleMiddle"><span class="ball"></span></span>
    </span>
    <span id="loading8-3">
                <span id="CircleTop"><span class="ball"></span></span>
    </span>
  </div>
</div>


问:
How to allow clicking a button "n" times and then disappear for a month
Implement a simple button, which changes information but I need that information only change 3 times, I need to disappear that button
When Exceed of the three clicks but I do not know how to do it and how to disappear it for 3 months</p>

答:
You could use a counter and a date variable to store the information. Save them in the shared preferences and get them whenever you want.

```<code>final SharedPreferences prefs = getSharedPreferences("MySharedPrefName", MODE_PRIVATE);

final Button button = findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
          int counter = prefs.getInt("counter", 0); //0 is the default value.
          counter++;
          editor.putInt("counter", counter);
          if(counter == 3){
              button.setVisibility(View.GONE);
              Date myDate = ;
              String format = "yyyy-MM-dd";
              String prefData = SimpleDateFormat(format).format(myDate);
              prefs.putString("date", prefDate);
          }
      }
 });
</code>```

After that, you can get the date from the shared preferences and check if 3 months have already passed in order to modify the visibility of the button.

To check if the 3 months have alredy passed use this method

```<code>private boolean havePassedThreeMonths(){

  //GET CURRENT DATE
  Calendar c = Calendar.getInstance();
  Date currentDate = c.getTime();

  //GET DATE FROM PREFERENCES
  prefDate = prefs.getString("Date", "");
  String format = "yyyy-MM-dd";
  Date date = new SimpleDateFormat(format).parse(prefDate);

  //Compare the two dates
  return monthsBetweenDates(date, currentDate) > 3;
}
</code>```

Here the monthsBetweenDates method:

```<code>public int monthsBetweenDates(Date startDate, Date endDate){

        Calendar start = Calendar.getInstance();
        start.setTime(startDate);

        Calendar end = Calendar.getInstance();
        end.setTime(endDate);

          int monthsBetween = 0;
            int dateDiff = end.get(Calendar.DAY_OF_MONTH)-start.get(Calendar.DAY_OF_MONTH);

if(dateDiff<0) {
                int borrrow = end.getActualMaximum(Calendar.DAY_OF_MONTH);
                 dateDiff = (end.get(Calendar.DAY_OF_MONTH)+borrrow)-start.get(Calendar.DAY_OF_MONTH);
                 monthsBetween--;

if(dateDiff>0) {
                     monthsBetween++;
                 }
            }
            else {
                monthsBetween++;
            }
            monthsBetween += end.get(Calendar.MONTH)-start.get(Calendar.MONTH);
            monthsBetween  += (end.get(Calendar.YEAR)-start.get(Calendar.YEAR))*12;
            return monthsBetween;
     }
</code>```

Hope it helps

Body:
You could use a counter and a date variable to store the information. Save them in the shared preferences and get them whenever you want.

final SharedPreferences prefs = getSharedPreferences("MySharedPrefName", MODE_PRIVATE);

final Button button = findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
          int counter = prefs.getInt("counter", 0); //0 is the default value.
          counter++;
          editor.putInt("counter", counter);
          if(counter == 3){
              button.setVisibility(View.GONE);
              Date myDate = ;
              String format = "yyyy-MM-dd";
              String prefData = SimpleDateFormat(format).format(myDate);
              prefs.putString("date", prefDate);
          }
      }
 });

After that, you can get the date from the shared preferences and check if 3 months have already passed in order to modify the visibility of the button.

To check if the 3 months have alredy passed use this method

private boolean havePassedThreeMonths(){

  //GET CURRENT DATE
  Calendar c = Calendar.getInstance();
  Date currentDate = c.getTime();

  //GET DATE FROM PREFERENCES
  prefDate = prefs.getString("Date", "");
  String format = "yyyy-MM-dd";
  Date date = new SimpleDateFormat(format).parse(prefDate);

  //Compare the two dates
  return monthsBetweenDates(date, currentDate) > 3;
}

Here the monthsBetweenDates method:

public int monthsBetweenDates(Date startDate, Date endDate){

        Calendar start = Calendar.getInstance();
        start.setTime(startDate);

        Calendar end = Calendar.getInstance();
        end.setTime(endDate);

          int monthsBetween = 0;
            int dateDiff = end.get(Calendar.DAY_OF_MONTH)-start.get(Calendar.DAY_OF_MONTH);

if(dateDiff<0) {
                int borrrow = end.getActualMaximum(Calendar.DAY_OF_MONTH);
                 dateDiff = (end.get(Calendar.DAY_OF_MONTH)+borrrow)-start.get(Calendar.DAY_OF_MONTH);
                 monthsBetween--;

if(dateDiff>0) {
                     monthsBetween++;
                 }
            }
            else {
                monthsBetween++;
            }
            monthsBetween += end.get(Calendar.MONTH)-start.get(Calendar.MONTH);
            monthsBetween  += (end.get(Calendar.YEAR)-start.get(Calendar.YEAR))*12;
            return monthsBetween;
     }

Hope it helps


问:
Dropdown menu in Bootstrap
```<code><!DOCTYPE html>
<html>
<head>
<title>Dropdown</title>
<link rel="stylesheet" href="css/bootstrap.css">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Article<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Technology</li>
<li>Technology 2</li>
<li>Technology 3</li>
</ul>
</div>
</body>
</html>
</code>```

this code is not working properly on my Browser(firefox),the dropdown-list is not apearing when I click the button.. Please help

答:
When using Bootstrap, always make sure that head section contains:

jquery script

bootstrap javascript

bootstrap css file

This has to be the order, otherwise it won't work.
D Sai Krishna's code (especially first three rows) is how it is supposed to be. I always find it better to use external link to .js and .css files than to use local files. To conclude, in head section paste external links (these one's are current as of this writing):

```<code>    1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   //This will initialize jQuery and enable it to work properly//

    2. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>   //This will implement Javascript whenever Bootstrap is being used (if applicable). //

    3. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">   //This will enable Bootstrap styles to be applied to your HTML//
</code>```

For reference, visit W3schools.com/bootstrap where you can find how to implement above mentioned lines and where. You will also find current external links of bootstrap .js and .css

Title: Dropdown menu in Bootstrap

Body:
<!DOCTYPE html>

<title>Dropdown</title>
<link rel="stylesheet" href="css/bootstrap.css">

<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Article</button>

Technology

Technology 2

Technology 3

this code is not working properly on my Browser(firefox),the dropdown-list is not apearing when I click the button.. Please help

Body:
When using Bootstrap, always make sure that head section contains:

jquery script

bootstrap javascript

bootstrap css file

This has to be the order, otherwise it won't work.
D Sai Krishna's code (especially first three rows) is how it is supposed to be. I always find it better to use external link to .js and .css files than to use local files. To conclude, in head section paste external links (these one's are current as of this writing):

    1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   //This will initialize jQuery and enable it to work properly//

    2. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>   //This will implement Javascript whenever Bootstrap is being used (if applicable). //

    3. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">   //This will enable Bootstrap styles to be applied to your HTML//

For reference, visit W3schools.com/bootstrap where you can find how to implement above mentioned lines and where. You will also find current external links of bootstrap .js and .css


问:
How to get parameters using "/:params" in Angular 2
I want to get parameters from a link similar to this "sample.com/product/45" using "product/:id",
Here is my route declaration :

```<code>export const routes: Routes = [
  { path: 'product/:id', component: Product }
];
</code>```

Here is the component class

```<code>export class Product implements OnInit, OnDestroy {
  id: number;
  private sub: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = +params['id'];

       console.log(this.id); //I get undefined here
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}
</code>```

when i tried to console.log() the id , i got undefined

答:
Try this ,</p>

```<code>ngOnInit() {
    this.id = this.activatedRoute.snapshot.params["id"];
}
</code>```

Body:
I want to get parameters from a link similar to this "sample.com/product/45" using "product/:id",
Here is my route declaration :

export const routes: Routes = [
  { path: 'product/:id', component: Product }
];

Here is the component class

export class Product implements OnInit, OnDestroy {
  id: number;
  private sub: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = +params['id'];

       console.log(this.id); //I get undefined here
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

when i tried to console.log() the id , i got undefined

Body:
Try this ,

ngOnInit() {
    this.id = this.activatedRoute.snapshot.params["id"];
}


问:
What is the best way of showing progress on an Ajax call?
I have an Ajax call that updates 5,000 records in a database so this takes a lot of time.  I have an Ajax "Loading image" showing that something is happening, but I am looking for a better way to show "Updating  50 of 5000 . . .", "Updating 200 of 5000", or something like that.

What is the best way to do something like this in Ajax / jQuery without doing 5000 different posts?

答: I would fire an Ajax callback once every n milliseconds that can query on how much is done (e.g. number of records updated) and use that to display a progress bar. Something like the way this works.

ContentLicense: CC BY-SA 2.5


问:
Integrate OnsenUI in Angular 4
I'm really struggling with integrating OnsenUI in my Angular 2 (version 4) App. The project was generated using the latest Angular CLI.
It seems the OnsenUI docs are not up to date.

So if add

```<code>import {OnsenModule} from 'angular2-onsenui';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
.
.
.
@NgModule({
imports: [
    OnsenModule,
    BrowserModule
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
</code>```

as it is described in the docs:
https://onsen.io/v2/docs/guide/angular2/

I'm getting the following error:

```<code>Uncaught ReferenceError: ons is not defined
at Object../node_modules/angular2-onsenui/dist/src/ons/notification.js (notification.js:5)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../node_modules/angular2-onsenui/dist/src/angular2-onsenui.js (angular2-onsenui.js:16)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../src/app/app.module.ts (app.component.ts:12)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../src/main.ts (environment.ts:8)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object.2 (main.ts:12)
at __webpack_require__ (bootstrap 43794b3…:54)
./node_modules/angular2-onsenui/dist/src/ons/notification.js @
notification.js:5
__webpack_require__ @ bootstrap 43794b3…:54
./node_modules/angular2-onsenui/dist/src/angular2-onsenui.js @     angular2-onsenui.js:16
__webpack_require__ @ bootstrap 43794b3…:54
./src/app/app.module.ts @ app.component.ts:12
__webpack_require__ @ bootstrap 43794b3…:54
./src/main.ts @ environment.ts:8
__webpack_require__ @ bootstrap 43794b3…:54
2 @ main.ts:12
__webpack_require__ @ bootstrap 43794b3…:54
webpackJsonpCallback @ bootstrap 43794b3…:25
(anonymous) @ main.bundle.js:1
</code>```

I don't want to use the monaca template, this will not solve the problem.

答:
Finally got the solution:
As long as OnsenUI does not support Angular 4, you need to add the following to .angular_cli.json:

```<code> "styles": [
    "../node_modules/onsenui/css/onsen-css-components.css",
    "../node_modules/onsenui/css/onsenui.css"
  ],
  "scripts": [
    "../node_modules/onsenui/js/onsenui.js"
  ],
</code>```

Title: Integrate OnsenUI in Angular 4

Body:
I'm really struggling with integrating OnsenUI in my Angular 2 (version 4) App. The project was generated using the latest Angular CLI.
It seems the OnsenUI docs are not up to date.

So if add

import {OnsenModule} from 'angular2-onsenui';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
.
.
.
@NgModule({
imports: [
    OnsenModule,
    BrowserModule
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]

as it is described in the docs:
https://onsen.io/v2/docs/guide/angular2/

I'm getting the following error:

Uncaught ReferenceError: ons is not defined
at Object../node_modules/angular2-onsenui/dist/src/ons/notification.js (notification.js:5)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../node_modules/angular2-onsenui/dist/src/angular2-onsenui.js (angular2-onsenui.js:16)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../src/app/app.module.ts (app.component.ts:12)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object../src/main.ts (environment.ts:8)
at __webpack_require__ (bootstrap 43794b3…:54)
at Object.2 (main.ts:12)
at __webpack_require__ (bootstrap 43794b3…:54)
./node_modules/angular2-onsenui/dist/src/ons/notification.js @
notification.js:5
__webpack_require__ @ bootstrap 43794b3…:54
./node_modules/angular2-onsenui/dist/src/angular2-onsenui.js @     angular2-onsenui.js:16
__webpack_require__ @ bootstrap 43794b3…:54
./src/app/app.module.ts @ app.component.ts:12
__webpack_require__ @ bootstrap 43794b3…:54
./src/main.ts @ environment.ts:8
__webpack_require__ @ bootstrap 43794b3…:54
2 @ main.ts:12
__webpack_require__ @ bootstrap 43794b3…:54
webpackJsonpCallback @ bootstrap 43794b3…:25
(anonymous) @ main.bundle.js:1

I don't want to use the monaca template, this will not solve the problem.

Body:
Finally got the solution:
As long as OnsenUI does not support Angular 4, you need to add the following to .angular_cli.json:

 "styles": [
    "../node_modules/onsenui/css/onsen-css-components.css",
    "../node_modules/onsenui/css/onsenui.css"
  ],
  "scripts": [
    "../node_modules/onsenui/js/onsenui.js"
  ],


问:
How do you order by a custom model method that has no attribute in SQL?
Previously I ordered my posts as this:

```<code>@posts = Post.find(:all, :order => "created_at DESC")
</code>```

But now I want to replace created_at with a custom method I wrote in the Post model that gives a number as its result.

My guess:

```<code>@posts = Post.find(:all, :order => "custom_method DESC")
</code>```

which fails..

答:
This is a bit more complicated than what I like but this I like to keep my sort to stay as a active record model so its bit more complicated than just

```<code>Post.all.sort_by {|post| post.custom_method }
</code>```

what I do is:

```<code>ids = Post.all.sort_by {|post| post.custom_method }.map(&:ids)
Post.for_ids_with_order(ids)
</code>```

this is a custom scope in the Post model

```<code>#app/models/post.rb
class Post < ApplicationRecord
  ...
    scope :for_ids_with_order, ->(ids) {
    order = sanitize_sql_array(
      ["position(id::text in ?)", ids.join(',')]
    )
    where(:id => ids).order(order)
  }

  ...
end
</code>```

I hope that this help

Body:
Previously I ordered my posts as this:

@posts = Post.find(:all, :order => "created_at DESC")

But now I want to replace created_at with a custom method I wrote in the Post model that gives a number as its result.

My guess:

@posts = Post.find(:all, :order => "custom_method DESC")

which fails..

Body:
This is a bit more complicated than what I like but this I like to keep my sort to stay as a active record model so its bit more complicated than just

Post.all.sort_by {|post| post.custom_method }

what I do is:

ids = Post.all.sort_by {|post| post.custom_method }.map(&:ids)
Post.for_ids_with_order(ids)

this is a custom scope in the Post model

#app/models/post.rb
class Post < ApplicationRecord
  ...
    scope :for_ids_with_order, ->(ids) {
    order = sanitize_sql_array(
      ["position(id::text in ?)", ids.join(',')]
    )
    where(:id => ids).order(order)
  }

  ...
end

I hope that this help


问:
Python pandas - DataFrame groupby and re-construct
I have a question for groupby() in pandas

If I have a DataFrame "df" like

```<code>    user  day  click
0   U1    Mon  15
1   U2    Mon  7
2   U1    Wed  15
3   U3    Tue  21
4   U2    Tue  15
5   U2    Tue  10
</code>```

When I use df.groupby(['user', 'day']).sum()

It would be

```<code>            click
user  day
U1    Mon   15
      Tue   NaN
      Wed   15
U2    Mon   7
      Tue   25
      Wed   NaN
U3    Mon   NaN
      Tue   21
      Wed   NaN
</code>```

How can I get a DataFrame like this

```<code>day    Mon   Tue   Wed
user
U1     15    NaN   15
U2     7     25    NaN
U3     NaN   21    NaN
</code>```

Which means transform one column to be the column name of DataFrame.

Is there any method to do this?

答:
Use pivot function with day as columns and fill with clicks.

```<code>df.groupby(['user', 'day']).sum().reset_index()\
  .pivot(index='user',columns='day',values='click')
Out[388]:
day    Mon   Tue   Wed
user
U1    15.0   NaN  15.0
U2     7.0  25.0   NaN
U3     NaN  21.0   NaN
</code>```

Or you can only reset the second level index so you don't need to specify index column in the pivot function.

```<code>df.groupby(['user', 'day']).sum().reset_index(level=1)\
.pivot(columns='day',values='click')
</code>```

Body:
I have a question for groupby() in pandas

If I have a DataFrame "df" like

    user  day  click
0   U1    Mon  15
1   U2    Mon  7
2   U1    Wed  15
3   U3    Tue  21
4   U2    Tue  15
5   U2    Tue  10

When I use df.groupby(['user', 'day']).sum()

It would be

            click
user  day
U1    Mon   15
      Tue   NaN
      Wed   15
U2    Mon   7
      Tue   25
      Wed   NaN
U3    Mon   NaN
      Tue   21
      Wed   NaN

How can I get a DataFrame like this

day    Mon   Tue   Wed
user
U1     15    NaN   15
U2     7     25    NaN
U3     NaN   21    NaN

Which means transform one column to be the column name of DataFrame.

Is there any method to do this?

Body:
Use pivot function with day as columns and fill with clicks.

df.groupby(['user', 'day']).sum().reset_index()\
  .pivot(index='user',columns='day',values='click')
Out[388]:
day    Mon   Tue   Wed
user
U1    15.0   NaN  15.0
U2     7.0  25.0   NaN
U3     NaN  21.0   NaN

Or you can only reset the second level index so you don't need to specify index column in the pivot function.

df.groupby(['user', 'day']).sum().reset_index(level=1)\
.pivot(columns='day',values='click')


问:
Is AlertIOS in React Native an outdated component?
I am learning React Native and what I am learning from only talks about Alert, even for iOS. In the API/Docs I see AlertIOS and I am curious if it does something special or is lighter weight for an iOS only app than the regular Alert?

(I found no post that had a definitive answer, but all the AlertIOS posts seem to date back to 2015-ish.)

Thank you.

答:
AlertIOS is special as it allows users to enter information into the alert using AlertIOS.prompt. According to the React Native documentation this is only a common pattern on iOS which is why they only made it available with an iOS specific API.

React Native still supports and recommends using Alert if you do not need iOS specific functionality.

From the alert docs

This is an API that works both on iOS and Android and can show static
  alerts. To show an alert that prompts the user to enter some
  information, see AlertIOS; entering text in an alert is common on iOS
  only.

From the alertIOS docs

We recommend using the Alert.alert method for cross-platform support
  if you don't need to create iOS-only prompts.


问:
Change datepicker display format (php)
how can i change the display format of date picker?

```<code><tr>
  <td width="30%"><label>Date Registered</label</td>
  <td >'.$row["dateRegistered_vehicle"].'</td>
</tr>
</code>```

using the date attributes, the data would be displayed as 2017/08/21.
how can i change this to 21/08/2017?

ive used datepicker in the insert form and does show the value as i want. but when i want to display the date in a table(html), the date come out as 2017/02/21 instead of 21/02/2017.

答:
Use the date built in method of php.
These websites are helpful:

1) http://php.net/manual/en/datetime.formats.date.php

2) https://www.w3schools.com/php/func_date_date.asp

Anyways here is the answer to your question.

```<code>date("d-m-Y", strtotime($row["dateRegistered_vehicle"]));
</code>```

Hope it helps.

Title: Change datepicker display format (php)

Body:
how can i change the display format of date picker?

  Date Registered</label
  '.$row["dateRegistered_vehicle"].'

using the date attributes, the data would be displayed as 2017/08/21.
how can i change this to 21/08/2017?

ive used datepicker in the insert form and does show the value as i want. but when i want to display the date in a table(html), the date come out as 2017/02/21 instead of 21/02/2017.

Body:
Use the date built in method of php.
These websites are helpful:

1) http://php.net/manual/en/datetime.formats.date.php

2) https://www.w3schools.com/php/func_date_date.asp

Anyways here is the answer to your question.

date("d-m-Y", strtotime($row["dateRegistered_vehicle"]));

Hope it helps.


问:
What is the difference of applying a CSS class/id directly to a tag vs wrapping the tag in DIV tags with the same class/id?
What is the difference of

```<code><ol class="specialClass">
  <li>Hello World!</li>
</ol>
</code>```

versus

```<code><div class="specialClass">
  <ol>
    <li>Hello World!</li>
  </ol>
</div>
</code>```

I couldn't find an answer that explicitly answered this. I plan on experimenting and researching it further, but it'd be nice to get an answer to directly explain it (if possible) or a link to an explanation.

答: If you put anything else under the div tag, the formatting will apply to everything before the end tag. Whereas, with the ordered list, the formatting only applies to the list text/blocks.</p>

ContentLicense: CC BY-SA 4.0

Body:
What is the difference of

Hello World!

versus

Hello World!

I couldn't find an answer that explicitly answered this. I plan on experimenting and researching it further, but it'd be nice to get an answer to directly explain it (if possible) or a link to an explanation.


问:
Python: For Loop return total price if in stock?
I'm quite new to python and this is one of the tasks from codeacademy that I am stuck on. The compute_bill function has to loop through each item in "food (list)" and only add the price of the item to "total (variable)" if the item's stock count is greater than zero. Next, if the item is in stock and after it has added the price to the total, subtract one from the item's stock count.

```<code>shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!

def compute_bill(food):
    total = 0
    for price in food:
        if stock[price] > 0:
            total += prices[price]
    return total
</code>```

It returns an error saying that *

calling compute_bill with a list containing 1 apples, 3 pears, 1
  oranges and 9 bananas resulted in 46.5 instead of the correct 34.5

*. But clearly, it says in the stock dictionary that there are 0 apples, 15 pears, 32 oranges and 6 bananas. Or am I supposed to make a list/dictionary to put in the "food" argument in the compute_bill function?

Any answer would be greatly appreciated.

答:
```<code>def compute_bill(food):
    total = 0

    for item in food:
        if stock[item] > 0:
            total += prices[item]
            stock[item]-=1
    return total
</code>```

Body:
I'm quite new to python and this is one of the tasks from codeacademy that I am stuck on. The compute_bill function has to loop through each item in "food (list)" and only add the price of the item to "total (variable)" if the item's stock count is greater than zero. Next, if the item is in stock and after it has added the price to the total, subtract one from the item's stock count.

shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!

def compute_bill(food):
    total = 0
    for price in food:
        if stock[price] > 0:
            total += prices[price]
    return total

It returns an error saying that *

calling compute_bill with a list containing 1 apples, 3 pears, 1
  oranges and 9 bananas resulted in 46.5 instead of the correct 34.5

*. But clearly, it says in the stock dictionary that there are 0 apples, 15 pears, 32 oranges and 6 bananas. Or am I supposed to make a list/dictionary to put in the "food" argument in the compute_bill function?

Any answer would be greatly appreciated.


问:
How to get html tags?
Say I have a text file like this:

```<code><html><head>Headline<html><head>more words
</script>even more words</script>
<html><head>Headline<html><head>more words
</script>even more words</script>
</code>```

How would I get just the tags into a list like this:

```<code><html>
<head>
<html>
<head>
</script>
</script>
<html>
<head>
<html>
<head>
</script>
</script>
</code>```

答:
Python has a HTMLParser module for this.

Here is some code which does what you want:

```<code>from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "<%s>"%tag

    def handle_endtag(self, tag):
        print "</%s>"%tag

parser = MyHTMLParser();
parser.feed("""<html><head>Headline<html><head>more words
        </script>even more words</script>
        <html><head>Headline<html><head>more words
        </script>even more words</script>
        """)
</code>```

Enter your string in parser.feed

Output:

```<code>$ python htmlparser.py
<html>
<head>
<html>
<head>
</script>
</script>
<html>
<head>
<html>
<head>
</script>
</script>
</code>```

This discussion on SO should help: Using HTMLParser in Python efficiently

Title: How to get html tags?

Body:
Say I have a text file like this:

Headlinemore words
</script>even more words</script>
Headlinemore words
</script>even more words</script>

How would I get just the tags into a list like this:

</script>
</script>

</script>
</script>

Body:
Python has a HTMLParser module for this.

Here is some code which does what you want:

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "<%s>"%tag

    def handle_endtag(self, tag):
        print "</%s>"%tag

parser = MyHTMLParser();
parser.feed("""<html><head>Headline<html><head>more words
        </script>even more words</script>
        <html><head>Headline<html><head>more words
        </script>even more words</script>
        """)

Enter your string in parser.feed

Output:

$ python htmlparser.py
<html>
<head>
<html>
<head>
</script>
</script>
<html>
<head>
<html>
<head>
</script>
</script>

This discussion on SO should help: Using HTMLParser in Python efficiently


问:
put file from local to hadoop environment
Note: I have read all earlier posts on stackoverflow related to this scenario but couldn't find any helpful

I'm learning hadoop and facing some stucks while playing around.

1) After connected to hadoop when I check pwd, it showes /home/hduser. So it means I'm in hduser dir which is my user as well for hadoop environment. When I create a dir using below command, dir gets created.

```<code>hadoop fs -mkdir /user/
</code>```

My question is, Why am not able to see that dir (user) under path /home/hduser from terminal but on http://localhost:50070/explorer.html#/user ?

2) Under my root two exists, One is Jon and second one is hduser.
   There is a file that I have created in user Jon at location /home/Jon and I want to put this file into hduser under /user directory.
   When I put his file using below command

```<code>hadoop fs -put /home/Jon/test.txt /user
</code>```

Get an error like this

```<code>17/06/04 21:33:26 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
put: `/home/Jon/test.txt': No such file or directory
</code>```

Note: I have given permissions as well from root in visudo file like this

```<code>Jon ALL(ALL:ALL) ALL
hduser ALL(ALL:ALL) ALL
</code>```

But I am still unable to do that put from local to hduser. When I create a file in hadoop environment under dir /home/hduser then I am easily able to copy file from there to /user dir

Could anyone help me to go through these stucks...?

答:
My question is, Why am not able to see that dir (user) under path /home/hduser from terminal but on http://localhost:50070/explorer.html#/user ?

HDFS and linux file system are two different ways of managing files and directories. HDFS needs namenode and datanode to be alive to view the files stored in HDFS. Namenode stores all the metadata of data stored in datanode. They are stored in local file system but in different format that HDFS can only read it.

/user is not exactly the local path but the path of HDFS (HDFS virtual file system).

Get an error like this
    17/06/04 21:33:26 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
    put: `/home/Jon/test.txt': No such file or directory

Generally above error is displayed when a file doesn't exists on local file system. I tried it myself and it works without any errors. Its really strange that its not working for you

What you can do is try to see if the file really exists. If it does then try

```<code>$HADOOP_HOME/bin/hadoop fs -put /home/Jon/test.txt /user
</code>```

If it still doesn't work then try changing the file permission of /user of HDFS

```<code>hadoop fs -chmod 777 /user
</code>```

Body:
Note: I have read all earlier posts on stackoverflow related to this scenario but couldn't find any helpful

I'm learning hadoop and facing some stucks while playing around.

1) After connected to hadoop when I check pwd, it showes /home/hduser. So it means I'm in hduser dir which is my user as well for hadoop environment. When I create a dir using below command, dir gets created.

hadoop fs -mkdir /user/

My question is, Why am not able to see that dir (user) under path /home/hduser from terminal but on http://localhost:50070/explorer.html#/user ?

2) Under my root two exists, One is Jon and second one is hduser.
   There is a file that I have created in user Jon at location /home/Jon and I want to put this file into hduser under /user directory.
   When I put his file using below command

hadoop fs -put /home/Jon/test.txt /user

Get an error like this

17/06/04 21:33:26 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
put: `/home/Jon/test.txt': No such file or directory

Note: I have given permissions as well from root in visudo file like this

Jon ALL(ALL:ALL) ALL
hduser ALL(ALL:ALL) ALL

But I am still unable to do that put from local to hduser. When I create a file in hadoop environment under dir /home/hduser then I am easily able to copy file from there to /user dir

Could anyone help me to go through these stucks...?

Body:
My question is, Why am not able to see that dir (user) under path /home/hduser from terminal but on http://localhost:50070/explorer.html#/user ?

HDFS and linux file system are two different ways of managing files and directories. HDFS needs namenode and datanode to be alive to view the files stored in HDFS. Namenode stores all the metadata of data stored in datanode. They are stored in local file system but in different format that HDFS can only read it.

/user is not exactly the local path but the path of HDFS (HDFS virtual file system).

Get an error like this
    17/06/04 21:33:26 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
    put: `/home/Jon/test.txt': No such file or directory

Generally above error is displayed when a file doesn't exists on local file system. I tried it myself and it works without any errors. Its really strange that its not working for you

What you can do is try to see if the file really exists. If it does then try

$HADOOP_HOME/bin/hadoop fs -put /home/Jon/test.txt /user

If it still doesn't work then try changing the file permission of /user of HDFS

hadoop fs -chmod 777 /user


问:
jQuery ajax post using FormData() append data element can't find the appended data element after post
I use the code from talkerscode.com to implement file upload using drag and drop. The code is working. Now I would like to add additional input value during in the same ajax post. I add an input tag called "user_id" in the following html code. And I append the element into the formdata object. After the change drag and drop upload still work, but the PHP code complain the $_POST["user_id"] is not defined. Here is my code. Please help!</p>

```<code><html>
<!-- code original from talkerscode.com -->
<head>
<link rel="stylesheet" type="text/css" href="upload_style.css">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="wrapper">
<input type="text" name="user_id", id="user_id" value="1228">
<input type="file">
<div id="drop-area">
 <h3 class="drop-text">Drag and Drop Images Here</h3>
 </div>
</div>
</body>
</html>

<script>
$(document).ready(function()
{
 $("#drop-area").on('dragenter', function (e){
  e.preventDefault();
  $(this).css('background', '#BBD5B8');
 });

 $("#drop-area").on('dragover', function (e){
  e.preventDefault();
 });

 $("#drop-area").on('drop', function (e){
  $(this).css('background', '#D8F9D3');
  e.preventDefault();
  var image = e.originalEvent.dataTransfer.files;
  createFormData(image);
 });
});

function createFormData(image)
{
 var formImage = new FormData();
 formImage.append('userImage', image[0]);
 formData.append('user_id', $('#user_id').val());
 uploadFormData(formImage);
}

function uploadFormData(formData)
{
 $.ajax({
 url: "upload_image.php",
 type: "POST",
 data: formData,
 contentType:false,
 cache: false,
 processData: false,
 success: function(data){
 $('#drop-area').html(data);
 }});
 }
 </script>

 ----------------PHP code -------------------

<?php
    if(is_array($_FILES))
    {
     if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
     $sourcePath = $_FILES['userImage']['tmp_name'];
     $targetPath = "images/".$_FILES['userImage']['name'];
     if(move_uploaded_file($sourcePath,$targetPath)) {
?>
   <img src="<?php echo $targetPath; ?>">
   <p> user_id = <?php echo $_POST["user_id"] ?> </p>
   <?php
   exit();
  }
 }
}
?>

-----------------------------------------------
</code>```

答:
```<code> function createFormData(image) {
  var formImage = new FormData();
  formImage.append('userImage', image[0]);
  formData.append('user_id', $('#user_id').val()); //change formData to formImage
  uploadFormData(formImage);
 }
</code>```

From:

```<code>  formData.append('user_id', $('#user_id').val());
</code>```

to:

```<code>  formImage.append('user_id', $('#user_id').val());
</code>```

Body:
I use the code from talkerscode.com to implement file upload using drag and drop. The code is working. Now I would like to add additional input value during in the same ajax post. I add an input tag called "user_id" in the following html code. And I append the element into the formdata object. After the change drag and drop upload still work, but the PHP code complain the $_POST["user_id"] is not defined. Here is my code. Please help!

<link rel="stylesheet" type="text/css" href="upload_style.css">

<input type="text" name="user_id", id="user_id" value="1228">
<input type="file">

Drag and Drop Images Here

 ----------------PHP code -------------------

<?php
    if(is_array($_FILES))
    {
     if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
     $sourcePath = $_FILES['userImage']['tmp_name'];
     $targetPath = "images/".$_FILES['userImage']['name'];
     if(move_uploaded_file($sourcePath,$targetPath)) {
?>
   <img src="<?php echo $targetPath; ?>">

 user_id = <?php echo $_POST["user_id"] ?>

   <?php
   exit();
  }
 }
}
?>

-----------------------------------------------

Body:
 function createFormData(image) {
  var formImage = new FormData();
  formImage.append('userImage', image[0]);
  formData.append('user_id', $('#user_id').val()); //change formData to formImage
  uploadFormData(formImage);
 }

From:

  formData.append('user_id', $('#user_id').val());

to:

  formImage.append('user_id', $('#user_id').val());


问:
how to place listview and toolstrip into a static variable
Hey everyone I am not sure if anyone can help me on this issue or not. Let me explain the setup
First I have a main form and a add form and a class file that has the save code in it,in the save code I have to enable the listview and enable a toolstrip button.

The add form is used to insert data into a listview that's on the main form

Now I was told that I could do something like

public statuc Listview LV1;  in the main form then
on the add form I could do LV1.whatever .

This is so I don't have to do a method with 2 arguments.

The goes is I need to be able to access the listview or what ever I need that's ont eh main form from the class file but through the add form since the save button on the add form would call the method in the class file.

I hope you understand.

答:
If I understand correctly you have:

Main form (MF) with ListView (LV) and ToolStrip with button.

Add form (AF) with UI elements such as labels and text boxes that you are using to present values of some class. There also should be OK and Cancel buttons for accepting or rejecting user input.

Class (CL) with several properties that user needs to fill-in. This class has Save method that captures values from AF. When users exits with OK you want to store instance of CL into LV of MF.

If this is what you have in mind I would suggest to do following:

Create Add method in MF with parameter ListView LV.

In this method you need to instantiate AF and save LV in some variable of AF.

Show AF form.

In btn_OK method instantiate CL and fill-in properties based on user entered values and add instance to LV variable or

In btn_OK instantiate CL and invoke Save method that will have AF as parameter. In Save method pick-up values of AF fields and put them in CL properties. Add this in LV using AF variable for LV.

Static variables are not used here since, in this scenario, you do not need static variables. However, you may create static variable for LV (MyListView for example) and set it's value to LV instance (MyListView = ListView1 for example). After that you can access it through MainForm.MyListView in AF and CL as needed.


问:
Mapbox GL / style - data separation
I have played with Mapbox and can quite easily create a Choropleth map in Mapbox studio and interact with it in Javascript.

I would like to create Choropleth map of the states with the ability to change the colours of the states for 100 years of different data points. I'm not allowed to upload the data into Mapbox as its sensitive healthcare data and I can't get sign of for the $499 a month cost.

My idea is I create a mapbox style layer in MapBox Studio then push the data client side for each of the states depending on the year x that the user selects. I have seen quite a few cloropeth tutorials such as this https://www.mapbox.com/help/choropleth-studio-gl-pt-1/ but the data is added in through a layer in Mapbox Studio. My thoughts are to embed the large GeoJson in the style and only push the data to the Polygon ID's, whilst creating transtions between the two.

Does anyone have any ideas if this is possible? and perhaps any useful API requests which may help me achieve this https://www.mapbox.com/api-documentation/.

答:
It's possible. There are two approaches:

Upload the geometry as a Dataset in Studio, or load it directly as a GeoJSON.

Set data attributes directly on the geometry.

Create a style with data-driven styles (eg, map "47" to "rgb(100,0,0)" and "153" to "rgb(250,250,0)" and let Mapbox interpolate.

Or:

Upload the geometry as a Tileset to Studio.

Calculate the color you want to represent each possible value of each state.

Generate a data-driven style property that maps each state's code to the color you want, like ...['FL','rgb(143,15,0)']....

Neither method will cope with large numbers of regions, but should be ok for 50 US states at low resolution.

More discussion here: https://github.com/mapbox/mapbox-gl-js/issues/4261

Title: Mapbox GL / style - data separation


问:
Adding CSS3 animation to elements created with HTML string method in pure JavaScript ( No Library)
I am struggling to create a fade in effect using vanilla JavaScript. Adding a className property works for the elements created using document.createElement method but doesn't not seem to work using var elem = "
 List Item
" method. I have ul with id list in html and I am creating a list item using html string method. I am using list.innerHTML = elem to append list item to the list and then trying to add a class "fade-in" on list item. I have used setTimeout function to delay the animation but it still doesn't work. Please refer to the code below.

var list = document.getElementById("list");

var li = "
 This is a list item
";
list.innerHTML = li;
li.className = "fade-in";
// setTimeout(function(){
//   li.className = "fade-in";
// },5);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#list {
  opacity: 0;
}

.fade-in {
  opacity: 1;
  transition: opacity 0.5s;
}

li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

```

答:
First up, you are attempting to do DOM manipulation on a string with li.className=. Thie list item is not a DOM element yet. It will be once you set the inner HTML

Also you have opacity 0 on the ul that will override child elements.

var list = document.getElementById("list");

var li = "
 This is a list item
";
//li.className = "fade-in"; -- Can't set className on a string
list.innerHTML = li;
console.log(list);
// setTimeout(function(){
//   li.className = "fade-in";
// },5);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#list>li { /*Set opacity on this list itmes, not the list*/
  opacity: 0;
}

#list .fade-in { /*Use a selector that is atleast as specific as the above.*/
  opacity: 1;
  transition: opacity 0.5s;
}
li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

```
</div>
</div>
</p>

<p><strong>Option 2</strong></p>

<p>If you want to work with DOM elements only, you can do the following.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var list = document.getElementById("list");

var li = document.createElement('li'); //Now we have a dom element
li.innerHTML = "This is a list item";
list.appendChild(li);
console.log(list);
 setTimeout(function(){
   li.className = "fade-in";
 },5);</code>```

#list>li { /*Set opacity on this list itmes, not the list*/
  opacity: 0;
}

#list .fade-in { /*Use a selector that is atleast as specific as the above.*/
  opacity: 1;
  transition: opacity 2s;
}
li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <ul id="list">
  </ul>
</body>
</html></code>```

Keep in mind, repeated DOM manipulations can use a lot of resources, so injecting strings is sometimes considered a better practice.

Body:
I am struggling to create a fade in effect using vanilla JavaScript. Adding a className property works for the elements created using document.createElement method but doesn't not seem to work using var elem = "
 List Item
" method. I have ul with id list in html and I am creating a list item using html string method. I am using list.innerHTML = elem to append list item to the list and then trying to add a class "fade-in" on list item. I have used setTimeout function to delay the animation but it still doesn't work. Please refer to the code below.

var list = document.getElementById("list");

var li = "
 This is a list item
";
list.innerHTML = li;
li.className = "fade-in";
// setTimeout(function(){
//   li.className = "fade-in";
// },5);

#list {
  opacity: 0;
}

.fade-in {
  opacity: 1;
  transition: opacity 0.5s;
}

li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Body:
First up, you are attempting to do DOM manipulation on a string with li.className=. Thie list item is not a DOM element yet. It will be once you set the inner HTML

Also you have opacity 0 on the ul that will override child elements.

var list = document.getElementById("list");

var li = "<li class='fade-in'> This is a list item</li>";
//li.className = "fade-in"; -- Can't set className on a string
list.innerHTML = li;
console.log(list);
// setTimeout(function(){
//   li.className = "fade-in";
// },5);

#list>li { /*Set opacity on this list itmes, not the list*/
  opacity: 0;
}

#list .fade-in { /*Use a selector that is atleast as specific as the above.*/
  opacity: 1;
  transition: opacity 0.5s;
}
li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <ul id="list">
  </ul>
</body>
</html>

Option 2

If you want to work with DOM elements only, you can do the following.

var list = document.getElementById("list");

var li = document.createElement('li'); //Now we have a dom element
li.innerHTML = "This is a list item";
list.appendChild(li);
console.log(list);
 setTimeout(function(){
   li.className = "fade-in";
 },5);

#list>li { /*Set opacity on this list itmes, not the list*/
  opacity: 0;
}

#list .fade-in { /*Use a selector that is atleast as specific as the above.*/
  opacity: 1;
  transition: opacity 2s;
}
li {
  list-style-type: none;
  font-size: 18px;
  background-color: #84ac47;
  color: #fff;
  padding: 10px 5px;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <ul id="list">
  </ul>
</body>
</html>

Keep in mind, repeated DOM manipulations can use a lot of resources, so injecting strings is sometimes considered a better practice.


问:
Count Stored Procedures in Database?
How can i count the number of stored procedures in my database and is it a bad practice to have too many stored procedures?</p>

答:
You need as many as your application requires.  Keeping procedures small and simple is a good thing.

If you're using sql 2005, a visual way to see your proc count is to navigate in SSMS to your stored procedure node under programmability.  Click View-Object Explorer Details and a count of objects will be displayed on the right.

OwnerDisplayName: Jack

Title: Count Stored Procedures in Database?

LastEditorDisplayName: Cade Roux

OwnerDisplayName: Sam


问:
PDO with $_POST
I have a little problem,

For exemple, the last time i used MySQL and now PDO, so that was my problem:

When a user want post a message on my website, with MySQL, if he try to post something like
 it doesn't work or it gonna show: From USER, Message =>

But now with PDO, when users post like HTML that gonna work on my website. (I don't know if that make a sence).

My piece of code:

```<code><?php $contenu = nl2br($_POST['contenu']);

$sql_add_pub = $pdo->prepare("INSERT INTO publications (steamid,profile,contenu,ajout,ip) VALUES ('".$user['steamid']."','".$user['steamid']."', :contenu , '".time()."', '".$_SERVER['REMOTE_ADDR']."') ");
        $sql_add_pub->execute(Array("contenu" => $contenu)); ?>
</code>```

So my question is, how can i fix that with PDO ?

Thanks in advance.

答:
For a start never use user input in your query string. Use Prepared Statements. That will help prevent SQL injection.

Secondly use the PHP strip_tags function on user input. http://php.net/manual/en/function.strip-tags.php

This will stop people from injecting HTML.

Title: PDO with $_POST

Body:
I have a little problem,

For exemple, the last time i used MySQL and now PDO, so that was my problem:

When a user want post a message on my website, with MySQL, if he try to post something like
 it doesn't work or it gonna show: From USER, Message =>

But now with PDO, when users post like HTML that gonna work on my website. (I don't know if that make a sence).

My piece of code:

<?php $contenu = nl2br($_POST['contenu']);

$sql_add_pub = $pdo->prepare("INSERT INTO publications (steamid,profile,contenu,ajout,ip) VALUES ('".$user['steamid']."','".$user['steamid']."', :contenu , '".time()."', '".$_SERVER['REMOTE_ADDR']."') ");
        $sql_add_pub->execute(Array("contenu" => $contenu)); ?>

So my question is, how can i fix that with PDO ?

Thanks in advance.


答:
Just another way to use unstack():

```<code>df=df.groupby(['user', 'day']).sum().unstack('day') #unstack
df.columns = df.columns.droplevel() # drop first level column name
df
</code>```

Output:

```<code>day  Mon  Tue  Wed
user
U1   15.0 NaN  15.0
U2   7.0  25.0 NaN
U3   NaN  21.0 NaN
</code>```

Title: Python pandas - DataFrame groupby and re-construct

Body:
Just another way to use unstack():

df=df.groupby(['user', 'day']).sum().unstack('day') #unstack
df.columns = df.columns.droplevel() # drop first level column name
df

Output:

day  Mon  Tue  Wed
user
U1   15.0 NaN  15.0
U2   7.0  25.0 NaN
U3   NaN  21.0 NaN


问:
Deleting String Pointers Memory in Struct
With the struct declaration:

```<code>struct Dat {
   int count; // number of files
   string *files;
   Dat(): count(0), files(nullptr) {}
   ~Dat() {
      delete[] files;
   }
}
</code>```

And then I built files like so:

```<code>buildFiles(int argc, char *argv, Dat my) {
   my.files = new string[my.count]; // my.files = new string[3]
   int filedex = 0;
   for (int i=0; i<argc; ++i) {
      if (some condition for argv[i]) { // only looking for filenames from argv
         my.files[filedex] = argv[i]; // store filename in my structure
         filedex++;
      }
   }
   if (filedex != my.count) cerr << "BAD";
}

int main (int argc, char *argv[])
{
   Dat my;
   // functions that define my.count to be non-zero, e.g. my.count = 3
   buildsFiles(argc, argv, my);
   // blahblah
   return 0;
}
</code>```

How do I now delete the dynamically allocated variables, files?
I've tried delete[] my.files and delete[] my->files but neither seem to work. I'm very new to c++ so any help would be much appreciated.

答:
When Dat my; leaves scope the destructor is called, which deletes the array of char pointers. You don't need to do anything about the stored strings because they're just pointers to the contents of the argv array, which is handled by c++

Bit right now you've got errors. my.count starts as zero, so it's allocating zero space. Then you're writing to memory, even though no space has been allocated. That's dangerous - it's on the stack so you can overwrite the stack's important values.

You need to pre-allocate some space and check that you don't try to store too many things in the array. Right now you're playing russian roulette with memory writes.

If you want to be able to resize a structure on the fly you need to use std::vector or some sort of linked list.

If you insist on manual allocation, then you need to pre-allocate enough space (either a set amount or by counting the number of things to store), and put checks in to detect if you've tried to access something outside of the allocated memory.

Body:
With the struct declaration:

struct Dat {
   int count; // number of files
   string *files;
   Dat(): count(0), files(nullptr) {}
   ~Dat() {
      delete[] files;
   }
}

And then I built files like so:

buildFiles(int argc, char *argv, Dat my) {
   my.files = new string[my.count]; // my.files = new string[3]
   int filedex = 0;
   for (int i=0; i<argc; ++i) {
      if (some condition for argv[i]) { // only looking for filenames from argv
         my.files[filedex] = argv[i]; // store filename in my structure
         filedex++;
      }
   }
   if (filedex != my.count) cerr << "BAD";
}

int main (int argc, char *argv[])
{
   Dat my;
   // functions that define my.count to be non-zero, e.g. my.count = 3
   buildsFiles(argc, argv, my);
   // blahblah
   return 0;
}

How do I now delete the dynamically allocated variables, files?
I've tried delete[] my.files and delete[] my->files but neither seem to work. I'm very new to c++ so any help would be much appreciated.


问:
Wordpress posts having odd issue all of a sudden
I'm running into an odd problem on my Wordpress site ( www.ez007.net). My most recent posts don't finish loading properly. The last two pieces that usually load on my page is the green vote buttons and the text in the right sidebar. But for some reason the page stops loading and these elements stay unloaded. Images below to explain

An older good post, you can see the red and green vote buttons are working and the text in the right hand sidebars looks clean:

One of the newer posts with issues, see the red and green vote button are not showing and the text in the right hand sidebar is all ski-whiff:

This only occurs on the last 10 or so posts on my website, and I made no changes to code or anything else when this started occurring.

It's really hard to explain and I can't even begin to understand how I can start troubleshooting this issue.

Any help would be amazing, I'll add the HTML output from both pages. Please let me know what else is needed? Thanks.

I realize there are errors in the code but I'm in the process of working those out, and the theme was working fine for a number of weeks before this issue started occurring.

答:
The problem lies in a missing CSS file on the templates with the issue - on the home page the following CSS file is referenced :

http://www.ez007.net/FreeSamplesAustraliaByMailOnly/wp-content/plugins/wordpress-popular-posts/style/wpp.css?ver=3.3.4

The link tag for this CSS file is missing on this page:

You've probably got to fix that wherever your wp_enqueue_style() calls for that particular template are made.

The reason the issue is occuring:

The wpp.css file contains the rules for the class wpp-thumbnail this class applies display: inline and float: left to the thumbnail image which is what lets the description text sit to the right of the image.


问:
Enable two factor login when logging in to the Azure Portal
The link below shows how to enable Multi Factor Authentication (MFA) when logging in to the Azure Portal. Unfortunately the walk through talks about using the classic portal to achieve this. Does anyone know if it possible to enable MFA in the proper portal (portal.azure.com).

https://blogs.technet.microsoft.com/enterprisemobility/2013/10/09/getting-started-with-windows-azure-multi-factor-authentication/

答: We can enable MFA via new portal, here is the screenshot, we can follow this steps to enable it.


问:
Is this common practice to avoid key not found in a dictionary
I was wondering, whether the following style is a common practice to avoid key not found in a dictionary?</p>

```<code># default is 0
value = my_dic[100] if 100 in my_dic else 0
</code>```

答:
If you try to access a key that is not in the dictionary, python will raise an exception that will crash your program. Instead of this, you should "catch" the exception and do something more graceful.

it's better practice to catch the exception:

```<code>try:
  value = my_dic[100]
except KeyError:
   print("key not found in dictionary") #or handle the error more elegantly
</code>```

I haven't read the article, but you can learn more here:
http://en.wikipedia.org/wiki/Exception_handling

Body:
I was wondering, whether the following style is a common practice to avoid key not found in a dictionary?

# default is 0
value = my_dic[100] if 100 in my_dic else 0

Body:
If you try to access a key that is not in the dictionary, python will raise an exception that will crash your program. Instead of this, you should "catch" the exception and do something more graceful.

it's better practice to catch the exception:

try:
  value = my_dic[100]
except KeyError:
   print("key not found in dictionary") #or handle the error more elegantly

I haven't read the article, but you can learn more here:
http://en.wikipedia.org/wiki/Exception_handling


问:
In Go's http package, how do I get the query string on a POST request?
I'm using the httppackage from Go to deal with POST request. How can I access and parse the content of the query string from the Requestobject ? I can't find the answer from the official documentation.

答:
Below words come from the official document.

Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.

So, sample codes as below would work.

```<code>func parseRequest(req *http.Request) error {
    var err error

    if err = req.ParseForm(); err != nil {
        log.Error("Error parsing form: %s", err)
        return err
    }

    _ = req.Form.Get("xxx")

    return nil
}
</code>```

Body:
Below words come from the official document.

Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.

So, sample codes as below would work.

func parseRequest(req *http.Request) error {
    var err error

    if err = req.ParseForm(); err != nil {
        log.Error("Error parsing form: %s", err)
        return err
    }

    _ = req.Form.Get("xxx")

    return nil
}


问:
SQL How to return all rows of a table and limit the rows of another by id and have them joined
How do i return all rows from the timeslot table and also limit the rows from consultation table by employeeId

This query returns entries with the employeeId =1,

```<code>SELECT TimeSlot, conStart, firstName, lastName, phoneNumber
FROM TimeSlots
LEFT JOIN consultation
ON TimeSlots.TimeSlot = consultation.conStart
LEFT JOIN patient
ON consultation.patientId = patient.patientID
WHERE employeeId = 1
</code>```

Which gives me this

```<code>11:00:00.0000000    11:00:00.0000000    chris   wilson  6666666666
</code>```

I would like to know how to show all the Timeslots but only show entries from
one employeeID

This is how i want it to turn out.

```<code>09:00:00.0000000    NULL    NULL    NULL    NULL

09:20:00.0000000    NULL    NULL    NULL    NULL

09:40:00.0000000    NULL    NULL    NULL    NULL

10:00:00.0000000    NULL    NULL    NULL    NULL

10:20:00.0000000    10:20   tim     is      1111111111

10:40:00.0000000    NULL    NULL    NULL    NULL

11:00:00.0000000    11:00   chris   wilson  6666666666

11:20:00.0000000    NULL    NULL    NULL    NULL
</code>```

答:
```<code>SELECT TimeSlot, conStart, firstName, lastName, phoneNumber
FROM TimeSlots
LEFT JOIN consultation
ON TimeSlots.TimeSlot = consultation.conStart
LEFT JOIN patient
ON consultation.patientId = patient.patientId AND employeeId = 1
</code>```

<p>`</p>

Body:
How do i return all rows from the timeslot table and also limit the rows from consultation table by employeeId

This query returns entries with the employeeId =1,

SELECT TimeSlot, conStart, firstName, lastName, phoneNumber
FROM TimeSlots
LEFT JOIN consultation
ON TimeSlots.TimeSlot = consultation.conStart
LEFT JOIN patient
ON consultation.patientId = patient.patientID
WHERE employeeId = 1

Which gives me this

11:00:00.0000000    11:00:00.0000000    chris   wilson  6666666666

I would like to know how to show all the Timeslots but only show entries from
one employeeID

This is how i want it to turn out.

09:00:00.0000000    NULL    NULL    NULL    NULL

09:20:00.0000000    NULL    NULL    NULL    NULL

09:40:00.0000000    NULL    NULL    NULL    NULL

10:00:00.0000000    NULL    NULL    NULL    NULL

10:20:00.0000000    10:20   tim     is      1111111111

10:40:00.0000000    NULL    NULL    NULL    NULL

11:00:00.0000000    11:00   chris   wilson  6666666666

11:20:00.0000000    NULL    NULL    NULL    NULL

Body:
SELECT TimeSlot, conStart, firstName, lastName, phoneNumber
FROM TimeSlots
LEFT JOIN consultation
ON TimeSlots.TimeSlot = consultation.conStart
LEFT JOIN patient
ON consultation.patientId = patient.patientId AND employeeId = 1

`


答:
Use a css animation

```<code>@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

.fade-in{
    animation: fadeIn .25s forwards;
}
</code>```

And change your li string to be
...
. That way the class will be on the element when you use innerHTML and the animation will take care of the opacity change.

Updated Explanation:

So you are adding the li element to the DOM using innerHTML. When that element is added to the DOM it has the class fade-in.

We create a css animation using @keyframes rule and we arbitrarily  name our animation fadeIn. Within the @keyframes rule we specify what we want our animation to do when applied to an element. We say we want to start at opacity: 0 and go to opacity: 1.

We use the animation by specifying the animation property on the .fade-in class. We called our animation fadeIn so by setting the animation property on the .fade-in class we are saying we want all elements with .fade-in to complete the fadeIn animation in .25s and set the animation-fill-mode property to forwards which means it will keep the final animation styles when the animation is done.

Title: Adding CSS3 animation to elements created with HTML string method in pure JavaScript ( No Library)

Body:
Use a css animation

@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

.fade-in{
    animation: fadeIn .25s forwards;
}

And change your li string to be <li class="fade-in">...</li>. That way the class will be on the element when you use innerHTML and the animation will take care of the opacity change.

Updated Explanation:

So you are adding the li element to the DOM using innerHTML. When that element is added to the DOM it has the class fade-in.

We create a css animation using @keyframes rule and we arbitrarily  name our animation fadeIn. Within the @keyframes rule we specify what we want our animation to do when applied to an element. We say we want to start at opacity: 0 and go to opacity: 1.

We use the animation by specifying the animation property on the .fade-in class. We called our animation fadeIn so by setting the animation property on the .fade-in class we are saying we want all elements with .fade-in to complete the fadeIn animation in .25s and set the animation-fill-mode property to forwards which means it will keep the final animation styles when the animation is done.


问:
Local maven package is not in import list
I am trying to import a class in my java code. The class is from a local maven repository. Is this possible?

My POM file includes:

```<code><dependency
  <groupId>com.datuma.jbpm</groupId>
  <artifactId>HR</artifactId>
  <version>1.0</version>
</dependency>
</code>```

Here is the jar in the maven library for my project:

However, when try to import it in my class, it is not found:

```<code>import com.datuma.jbpm.*
</code>```

There are not any packages in this project, which was the problem, Thanks

答: Just to answer my own question, the class I was trying to import was not in the repository, and I was able to determine that it was not by expanding the contents of the jar.</p>

Body:
I am trying to import a class in my java code. The class is from a local maven repository. Is this possible?

My POM file includes:

<dependency
  <groupId>com.datuma.jbpm</groupId>
  <artifactId>HR</artifactId>
  <version>1.0</version>
</dependency>

Here is the jar in the maven library for my project:

However, when try to import it in my class, it is not found:

import com.datuma.jbpm.*

There are not any packages in this project, which was the problem, Thanks


问:
Executing a sqlalchemy exists query
I'm having trouble understanding how to execute a query to check and see if a matching record already exists in sqlalchemy.  Most of the examples I can find online seem to reference "session" and "query" objects that I don't have.

Here's a short complete program that illustrates my problem:

1. sets up in-memory sqlite db with "person" table.

2. inserts two records into the person table.

3. check if a particular record exists in the table.  This is where it barfs.

```<code>from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s)
print(s)

print("But it doesn't run...")
result = conn.execute(s)
</code>```

The output of this program is:

```<code>I can see the names in the table:
[(1, 'Alice'), (2, 'Bob')]
This query looks like it should check to see if a matching record exists:
EXISTS (SELECT person.id, person.name
FROM person
WHERE person.name = :name_1)
But it doesn't run...
Traceback (most recent call last):
  File "/project_path/db_test/db_test_env/exists_example.py", line 30, in <module>
    result = conn.execute(s)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 265, in _execute_on_connection
    raise exc.ObjectNotExecutableError(self)
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: <sqlalchemy.sql.selectable.Exists object at 0x105797438>
</code>```

答:
The s.exists() is only building the exists clause.  All you need to do to get your code to work is to generate a select for it.

```<code>s = exists(s).select()
</code>```

Here's your full example:

```<code>from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s).select()
print(s)

print("And it runs fine...")
result = conn.execute(s)
print(result.fetchall())
</code>```

Title: Executing a sqlalchemy exists query

Body:
I'm having trouble understanding how to execute a query to check and see if a matching record already exists in sqlalchemy.  Most of the examples I can find online seem to reference "session" and "query" objects that I don't have.

Here's a short complete program that illustrates my problem:

1. sets up in-memory sqlite db with "person" table.

2. inserts two records into the person table.

3. check if a particular record exists in the table.  This is where it barfs.

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s)
print(s)

print("But it doesn't run...")
result = conn.execute(s)

The output of this program is:

I can see the names in the table:
[(1, 'Alice'), (2, 'Bob')]
This query looks like it should check to see if a matching record exists:
EXISTS (SELECT person.id, person.name
FROM person
WHERE person.name = :name_1)
But it doesn't run...
Traceback (most recent call last):
  File "/project_path/db_test/db_test_env/exists_example.py", line 30, in <module>
    result = conn.execute(s)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 265, in _execute_on_connection
    raise exc.ObjectNotExecutableError(self)
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: <sqlalchemy.sql.selectable.Exists object at 0x105797438>

Body:
The s.exists() is only building the exists clause.  All you need to do to get your code to work is to generate a select for it.

s = exists(s).select()

Here's your full example:

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s).select()
print(s)

print("And it runs fine...")
result = conn.execute(s)
print(result.fetchall())


问:
custom node class with java's linkedlist class
Been a while since I used java. I want to use Java's built in linkedlist class but I want a custom node class that has children and siblings. How can I write a custom node class that Java's linked list will use? Just a matter of creating the node class and declaring a linkedlist class but just create a new constructor that will override javas? Thanks!</p>

答: LinkedList uses a private Node<E> class internally. If this is just an academic exercise, given that the source code is available you could just start with that and go from there.


答:
```<code>value = my_dic.get(100, 0)
</code>```

Title: Is this common practice to avoid key not found in a dictionary

Body: value = my_dic.get(100, 0)


问:
Have to use C++ dll to call C# .NET methods?
I use this way,but there is a problem.
C# dll'namespace is a.b.c.d, when i write [a.b.c.d::className::method] in C++ code,namespace a.b.c.d can't be identifed.
https://www.codeproject.com/Tips/695387/Calling-Csharp-NET-methods-from-unmanaged-C-Cplusp

C# dll： vs2017 .Net4.6.2

C++ dll： vs2013 .Net4.6.2

答:
In C++ CLI, you use :: instead of . when accessing managed namespaces. So if it is a static method, then you would call:

```<code>a::b::c::d::className::method
</code>```

Body:
In C++ CLI, you use :: instead of . when accessing managed namespaces. So if it is a static method, then you would call:

a::b::c::d::className::method


问:
Having two lists as a value to a single key: Dictionaries
Looking for a way to add two lists to a value in a dictionary for example if want to add two lists to a single value for example

For example this dictionary dict1 = {a: [], b:[], c:[]}

Would become dict1 = {a:([1,3,4,5,6],[1,2,3,4]),b:[],c:[]}

When you add the two lists [1,2,3,4,5,6] and [1,2,3,4] to the key a.
And if you were to print the key a you would get the two lists as output

Any help would be much appreciated

Body:
You can use list.append() because your dict1['a']'s value is a list. See this example:

dict1 = {'a': [], 'b':[], 'c':[]}

a = [1,2,3,4,5,6]
b = [1,2,3,4]

dict1['a'].append(a)
dict1['a'].append(b)

print(dict1)

Output:

{'a': [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4]], 'b': [], 'c': []}


答:
Try this instead:</p>

```<code>...
s = person.select().where(person.c.name == "Bob")
s = select(exists(s))
print(s)
...
</code>```

Title: Executing a sqlalchemy exists query

Body:
Try this instead:

...
s = person.select().where(person.c.name == "Bob")
s = select(exists(s))
print(s)
...


问:
How to deactivate the default stop words feature for sklearn TfidfVectorizer
I am trying to get the tf-idf values for Japanese words.
The problem I am having is that sklearn TfidfVectorizer removes some Japanese characters, which I want to keep, as stop words.

The following is the example:

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
tf = TfidfVectorizer(stop_words = None)

words_list = ["歯","が","痛い"]
tfidf_matrix =  tf.fit_transform(words_list)
feature_names = tf.get_feature_names()
print (feature_names)
</code>```

The output is:['痛い']

However, I want to keep all those three characters in the list.
I believe TfidfVectorizer removes characters with length of 1 as stop words.
How could I deactivate the default stop words feature and keep all characters?

答:
You can change the token_pattern parameter from (?u)\\b\\w\\w+\\b (default) to (?u)\\b\\w\\w*\\b; The default matches token that has two or more word characters (in case you are not familiar with regex, + means one or more, so \\w\\w+ matches word with two or more word characters; * on the other hand means zero or more, \\w\\w* will thus match word with one or more characters):

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
tf = TfidfVectorizer(stop_words = None, token_pattern='(?u)\\b\\w\\w*\\b')

words_list = ["歯","が","痛い"]
tfidf_matrix =  tf.fit_transform(words_list)
feature_names = tf.get_feature_names()
print(feature_names)
# ['が', '歯', '痛い']
</code>```

Body:
I am trying to get the tf-idf values for Japanese words.
The problem I am having is that sklearn TfidfVectorizer removes some Japanese characters, which I want to keep, as stop words.

The following is the example:

from sklearn.feature_extraction.text import TfidfVectorizer
tf = TfidfVectorizer(stop_words = None)

words_list = ["歯","が","痛い"]
tfidf_matrix =  tf.fit_transform(words_list)
feature_names = tf.get_feature_names()
print (feature_names)

The output is:['痛い']

However, I want to keep all those three characters in the list.
I believe TfidfVectorizer removes characters with length of 1 as stop words.
How could I deactivate the default stop words feature and keep all characters?

Body:
You can change the token_pattern parameter from (?u)\\b\\w\\w+\\b (default) to (?u)\\b\\w\\w*\\b; The default matches token that has two or more word characters (in case you are not familiar with regex, + means one or more, so \\w\\w+ matches word with two or more word characters; * on the other hand means zero or more, \\w\\w* will thus match word with one or more characters):

from sklearn.feature_extraction.text import TfidfVectorizer
tf = TfidfVectorizer(stop_words = None, token_pattern='(?u)\\b\\w\\w*\\b')

words_list = ["歯","が","痛い"]
tfidf_matrix =  tf.fit_transform(words_list)
feature_names = tf.get_feature_names()
print(feature_names)
# ['が', '歯', '痛い']


问:
PostgreSQL: Show tables in PostgreSQL
What's the equivalent to show tables (from MySQL) in PostgreSQL?

答:
If you are using pgAdmin4 in PostgreSQL, you can use this to show the tables in your database:</p>

```<code>select * from information_schema.tables where table_schema='public';
</code>```

Title: PostgreSQL: Show tables in PostgreSQL

Body:
If you are using pgAdmin4 in PostgreSQL, you can use this to show the tables in your database:

select * from information_schema.tables where table_schema='public';


问:
timstamp keep changing in recyclerview
I have a recyclerview which has 50+ data. And there I show the timestamp difference.

```<code>new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                try{
                    long mtime = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis())-TimeUnit.MILLISECONDS.toMinutes(Long.parseLong(time));
                    if (mtime<60){
                        holder.timestamp.setText(String.valueOf(mtime)+ " mins");
                        if (mtime==1)
                            holder.timestamp.setText(1+ " min");
                        else if (mtime<1){
                            holder.timestamp.setText("Just Now");

                        }
                        else
                            holder.timestamp.setText(mtime+ " mins");
                    }
                    else if (mtime>60 && mtime<1440){
                        if (mtime/60==1)
                            holder.timestamp.setText(String.valueOf(mtime/60)+ " hour");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/60)+ " hours");
                    }
                    else if (mtime>1440&&mtime<10080){
                        if (mtime/1440==1)
                            holder.timestamp.setText(String.valueOf(mtime/1440)+ " day");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/1440)+ " days");
                    }else if(mtime>10080&&mtime<3679200){
                        if (mtime/10080==1)
                            holder.timestamp.setText(String.valueOf(mtime/10080)+ " week");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/10080)+ " weeks");

                    }else if(mtime>3679200){
                        if (mtime/3679200==1)
                            holder.timestamp.setText(String.valueOf(mtime/3679200)+ " year");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/3679200)+ " years");
                    }
                }catch (Exception e){

                }

                h.postDelayed(this,1000);
            }
        },1000);
</code>```

It works fine. But when I scroll the recyclerview it keeps changing the timestamp with timestamp of other recyclerview items.

Timestamp flash gif

答:
yes, because you are using new Handler(Looper.getMainLooper()).postDelayed().  Why you use Handler here? the RecyclerView Adapter callbacks are called in the UI thread already.

As I see in your code, each time you scroll, the timestamp will be displayed after 1s. If you scroll fast (actually you always do), 1s later, your row view is already reused and displays another item.

Therefore, to solve your issue, you need to remove the handler in your code.

Title: timstamp keep changing in recyclerview

Body:
I have a recyclerview which has 50+ data. And there I show the timestamp difference.

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                try{
                    long mtime = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis())-TimeUnit.MILLISECONDS.toMinutes(Long.parseLong(time));
                    if (mtime<60){
                        holder.timestamp.setText(String.valueOf(mtime)+ " mins");
                        if (mtime==1)
                            holder.timestamp.setText(1+ " min");
                        else if (mtime<1){
                            holder.timestamp.setText("Just Now");

                        }
                        else
                            holder.timestamp.setText(mtime+ " mins");
                    }
                    else if (mtime>60 && mtime<1440){
                        if (mtime/60==1)
                            holder.timestamp.setText(String.valueOf(mtime/60)+ " hour");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/60)+ " hours");
                    }
                    else if (mtime>1440&&mtime<10080){
                        if (mtime/1440==1)
                            holder.timestamp.setText(String.valueOf(mtime/1440)+ " day");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/1440)+ " days");
                    }else if(mtime>10080&&mtime<3679200){
                        if (mtime/10080==1)
                            holder.timestamp.setText(String.valueOf(mtime/10080)+ " week");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/10080)+ " weeks");

                    }else if(mtime>3679200){
                        if (mtime/3679200==1)
                            holder.timestamp.setText(String.valueOf(mtime/3679200)+ " year");
                        else
                            holder.timestamp.setText(String.valueOf(mtime/3679200)+ " years");
                    }
                }catch (Exception e){

                }

                h.postDelayed(this,1000);
            }
        },1000);

It works fine. But when I scroll the recyclerview it keeps changing the timestamp with timestamp of other recyclerview items.

Timestamp flash gif


问:
Prevent >1 person from running VBA macro at a time (shared wkb)
What I'm aiming at is getting a list of all currently running scripts in order to check if other users aren't running the same VBA macro at the same time (and if yes, then stop the code etc., similar to what the OP of the below question wanted). This would be for a shared workbook (I learned it's not designed for this type of work, but I need to try it).

https://stackoverflow.com/a/36116091/5947935

I've been trying to make the code in the above answer work in VBA, but it seems it's a vbs thing and I would like to avoid that.

I'm not an expert to say the least, so I'm having trouble understanding how to get this to work in Excel VBA. I don't even know if it's possible at all.

I've found this as well: VBA Getting program names and task ID of running processes and it works fine but it only lists the running processes.

I've no idea however how to merge the two... or even if the WMI is the correct way to go.

I'd appreciate any sort of help.

答:
No codes here and theory not tested yet, but the idea of preventing a different user executing a Macro on a shared workbook requires some thinking.

I would create a hidden worksheet, and use one of the cells to store the Environ("USERNAME") when the macro is first started - to indicate who has it running, then clear it when complete, first-in-first-out.

Lets say named range MUser (macro user) is range A1 in that hidden worksheet

When the macro runs, it will first check if MUser is empty, if so then change it's value to Environ("USERNAME") and Save the file before next step (here I am not certain the value is updated on others session).

If MUser is not empty, either abort or retry in a few second.

When macro completes, MUser will be ClearContents, and save the File to free up the workbook for macro.

Idea is here but please test. Post your own code for us to troubleshoot. You may also use Workbook events to "lock" the macro execution this way. Or even use this hidden sheet to make a log record for debug. Also some fail-safe needs to be implemented (such as a time stamp at macro start and override the lock after some minutes).