问:
Angular 2 class property value and binding
I am new to Angular 2 and I am making my first test app.

I tested class property and binding.

To check how classes work in Angular, I used many different ways, and every one works.

First, created a class on my app.component.css

```<code>.setGreenBackGroundClass
{
    background-color: green;
}
</code>```

I created one variable on my app.component.ts

```<code>assignedVar = 'setGreenBackGroundClass';
</code>```

I assigned the var´s name to the class and everything works right; class is assigned.

```<code><ul [class]="assignedVar">
</code>```

or

```<code><ul class="{{assignedVar}}">
</code>```

Both work fine.

Last way to test is passing directly the class name to the URL, and it works right too:

```<code><ul class="setGreenBackGroundClass">
</code>```

But my doubt comes when I tried to test binding and double binding. I wanted to create an input where I can write the value of the class property, and then, the color changes (i know, maybe it´s pretty nonsense and it would be better done with a select tag or something similar, but just wanted to check it).

On my app.component.html view I have:

```<code><input type="text" name="miBind" [(ngModel)]="binding" />

<!--on this div I check double binding works right-->
<div>{{binding}}</div>

<ul [class]="binding">

    ....
</code>```

The problem is at

```<code><ul [class]="binding">
</code>```

I have checked, and it works when you write on the textbox the css class name:

input--> setGreenBackGroundClass

This works. The  background color changes.

But when I do:

input-->assignedVar

It doesn´t work, and my question is: why, since assignedVar has the class name assigned, it doesn´t work?

The resulting HTML that I get from the inspector when I type "assignedVar" is:

```<code><ul _ngcontent-c0="" class="setGreenBackGroundClass">
    <li _ngcontent-c0="">
    <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://angular.io  /tutorial" rel="noopener" target="_blank">Tour of Heroes</a></h2>
    </li>
    <li _ngcontent-c0="">
        <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://github.com/angular/angular-cli/wiki" rel="noopener" target="_blank">CLI Documentation</a></h2>
    </li>
    <li _ngcontent-c0="">
        <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://blog.angular.io/" rel="noopener" target="_blank">Angular blog</a></h2>
    </li>
</ul>

<ul _ngcontent-c0="" class="setGreenBackGroundClass">
    <li _ngcontent-c0="">
    <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://angular.io/tutorial" rel="noopener" target="_blank">Tour of Heroes</a></h2>
    </li>
    <li _ngcontent-c0="">
        <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://github.com/angular/angular-cli/wiki" rel="noopener" target="_blank">CLI Documentation</a></h2>
    </li>
    <li _ngcontent-c0="">
        <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://blog.angular.io/" rel="noopener" target="_blank">Angular blog</a></h2>
    </li>
</ul>

<ul _ngcontent-c0="" class="setGreenBackGroundClass">
    <li _ngcontent-c0="">
    <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://angular.io/tutorial" rel="noopener" target="_blank">Tour of Heroes</a></h2>
    </li>
    <li _ngcontent-c0="">
        <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://github.com/angular/angular-cli/wiki" rel="noopener" target="_blank">CLI Documentation</a></h2>
    </li>
    <li _ngcontent-c0="">
        <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://blog.angular.io/" rel="noopener" target="_blank">Angular blog</a></h2>
  </li>
</ul>

<input _ngcontent-c0="" name="miBind" ng-reflect-name="miBind" ng-reflect-model="assignedVar" class="ng-valid ng-dirty ng-touched" type="text">

<div _ngcontent-c0="">assignedVar</div>

<ul _ngcontent-c0="" class="assignedVar">
    <li _ngcontent-c0="">
        <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://angular.io/tutorial" rel="noopener" target="_blank">Tour of Heroes</a></h2>
    </li>
    <li _ngcontent-c0="">
        <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://github.com/angular/angular-cli/wiki" rel="noopener" target="_blank">CLI Documentation</a></h2>
    </li>
    <li _ngcontent-c0="">
        <h2 _ngcontent-c0=""><a _ngcontent-c0="" href="https://blog.angular.io/" rel="noopener" target="_blank">Angular blog</a></h2>
    </li>
</ul>
</code>```

And I can't figure out why the text on my input value is here taken as simple plain text (but not as the variable name) for the class value , and when I write that variable name directly on the code (like I did on first examples) there is no problem and it knows it is a CSS class name.

答:
input--> setGreenBackGroundClass

This works. The background color changes.

But when I do:

input-->assignedVar

It doesn´t work.

When you input 'setGreenBackGroundClass', this is what happens

```<code><ul class='setGreenBackGroundClass'>
</code>```

which is what you expect to work.

When you input 'assignedVar', this is what happens

```<code><ul class='assignedVar'>
</code>```

and you don't have a css class with the name 'assignedVar' that's why it is not working. You confused the string assignedVar with the variable assignedVar

Update 1

With a stackblitz project provided, I modified your code to make your second
 to bind to a getter function.

Why I bind to a function?

Because I want to override the binding variable to return a assignedVar variable whenever you type a assignedVar string.

Checkout this updated stackblitz project

Hope this helps.

Body:
I am new to Angular 2 and I am making my first test app.

I tested class property and binding.

To check how classes work in Angular, I used many different ways, and every one works.

First, created a class on my app.component.css

.setGreenBackGroundClass
{
    background-color: green;
}

I created one variable on my app.component.ts

assignedVar = 'setGreenBackGroundClass';

I assigned the var´s name to the class and everything works right; class is assigned.

or

Both work fine.

Last way to test is passing directly the class name to the URL, and it works right too:

But my doubt comes when I tried to test binding and double binding. I wanted to create an input where I can write the value of the class property, and then, the color changes (i know, maybe it´s pretty nonsense and it would be better done with a select tag or something similar, but just wanted to check it).

On my app.component.html view I have:

<input type="text" name="miBind" [(ngModel)]="binding" />

{{binding}}

    ....

The problem is at

I have checked, and it works when you write on the textbox the css class name:

input--> setGreenBackGroundClass

This works. The  background color changes.

But when I do:

input-->assignedVar

It doesn´t work, and my question is: why, since assignedVar has the class name assigned, it doesn´t work?

The resulting HTML that I get from the inspector when I type "assignedVar" is:

Tour of Heroes

CLI Documentation

Angular blog

Tour of Heroes

CLI Documentation

Angular blog

Tour of Heroes

CLI Documentation

Angular blog

<input _ngcontent-c0="" name="miBind" ng-reflect-name="miBind" ng-reflect-model="assignedVar" class="ng-valid ng-dirty ng-touched" type="text">

assignedVar

Tour of Heroes

CLI Documentation

Angular blog

And I can't figure out why the text on my input value is here taken as simple plain text (but not as the variable name) for the class value , and when I write that variable name directly on the code (like I did on first examples) there is no problem and it knows it is a CSS class name.

Body:
input--> setGreenBackGroundClass

This works. The background color changes.

But when I do:

input-->assignedVar

It doesn´t work.

When you input 'setGreenBackGroundClass', this is what happens

<ul class='setGreenBackGroundClass'>

which is what you expect to work.

When you input 'assignedVar', this is what happens

<ul class='assignedVar'>

and you don't have a css class with the name 'assignedVar' that's why it is not working. You confused the string assignedVar with the variable assignedVar

Update 1

With a stackblitz project provided, I modified your code to make your second <ul> to bind to a getter function.

Why I bind to a function?

Because I want to override the binding variable to return a assignedVar variable whenever you type a assignedVar string.

Checkout this updated stackblitz project

Hope this helps.


来源: stackexchange

问:
Invoking a local notification with UNUserNotificationCenter right now
How can I invoke a local notification right now? Instead of setting a time interval in the future? This code will show a notification 5 seconds in the future. I want it to be invoked now.</p>

```<code>let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false)

let notificationRequest = UNNotificationRequest(identifier: "notification", content: notificationContent, trigger: trigger)

UNUserNotificationCenter.current().add(notificationRequest) { (error) in
    if let error = error {
        //error
    }
}
</code>```

答:
Because timeInterval must be greater than 0, you can try put 0.1 in timeInterval.

Or you can fire local notification at specific time.(now time)

```<code>let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.timeZone], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I invoke a local notification right now? Instead of setting a time interval in the future? This code will show a notification 5 seconds in the future. I want it to be invoked now.

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false)

let notificationRequest = UNNotificationRequest(identifier: "notification", content: notificationContent, trigger: trigger)

UNUserNotificationCenter.current().add(notificationRequest) { (error) in
    if let error = error {
        //error
    }
}

Body:
Because timeInterval must be greater than 0, you can try put 0.1 in timeInterval.

Or you can fire local notification at specific time.(now time)

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.timeZone], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)


问:
3D pointer seg error
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

```<code>int ***grid;
    grid=new int **[number];
</code>```

then I want to assign the 2D arrays to the 3D construct

```<code>for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);
</code>```

with

```<code>int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}
</code>```

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

```<code>printf("%d",grid[1][1][1]);
</code>```

What is my mistake?

Best,
  Hannes

答:
First, you discard the very first row of each matrix with that memset (the actual row is leaked). While technically grid[1][1][1] should still be readable, it probably becomes corrupt in some other place.

Can you provide a minimal verifiable example? This is likely to solve your problem.

Title: 3D pointer seg error

Body:
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

int ***grid;
    grid=new int **[number];

then I want to assign the 2D arrays to the 3D construct

for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);

with

int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

printf("%d",grid[1][1][1]);

What is my mistake?

Best,
  Hannes


问:
Changing the system.out font and color in BlueJ/Java
Here is a very simple code

```<code>public class test
{
    public static void main(String[] args)
    {

    System.out.println("  Hello ");

    }
}
</code>```

I am using a BlueJ IDE.
What I want to do is make the color of the printed output red.
And change the font to any custom made font - say Arial Unicode MS.

Feel free to make changes to the code above or give detailed instructions if other things are required.
Thanks in advance.

Edit:

BlueJ seems to use a wordpad as a console. That is it Channels the output into wordpad/notepad. Does this mean I have to something else?

Or is it the bluej.defs file where I should try changing?

答:
Or you can edit the stylesheets found in blueJ. For Windows, navigate to
C:\Program Files (x86)\BlueJ\lib\stylesheets, then copy the css file called terminal. Paste it into C:\Users\name\bluej. Edit the css file in your favorite ide (I prefer something that will preview a color on hover).

The css file here will override the previous file, so do not delete the old file. If you mess up with your color changes, you want a backup.

Aside: If you really want to have fun, edit the java-colors.css file. That will edit the colors of the BlueJ editor. My current one (with Options->Preferences->Scope Highlighting set a little under halfway, accessible from the main bluej page) is:

.token-keyword1 {
    -fx-fill: #7A0F55;
}
.token-keyword2 {
    -fx-fill: #AA4D00;
}
.token-keyword3 {
    -fx-fill: #006699;
}

.token-comment-normal {
    -fx-fill: #888;
}
.token-comment-javadoc {
    -fx-fill: #06598F;
}
.token-comment-standout {
    -fx-fill: #e527b3;
}

.token-primitive {
    -fx-fill: #AA4D00;
}
.token-string-literal {
    -fx-fill: #76B20E;
}
.token-label {
    -fx-fill: #999999;
}
.token-invalid {
    -fx-fill: #ff3300;
}
/* Default text colour */
.token-default {
    -fx-fill: #000000;
}

.scope-colors {
    -bj-background-color: #EEE;

    -bj-class-color: #9EE047;
    -bj-class-outer-color: #AAA;
    -bj-class-inner-color: #AAA;

    -bj-method-color: #E2D228;
    -bj-method-outer-color: #F2A228;

    -bj-selection-color: #378EA9;
    -bj-selection-outer-color:#378EA9;

    -bj-iteration-color: #D63938;
    -bj-iteration-outer-color: #D63938;

    -bj-breakpoint-overlay-color: rgba(200, 20, 20, 0.6);
    -bj-step-overlay-color: rgba(20, 140, 20, 0.6);
}

.moe-step-mark-icon {
    -fx-fill: rgb(20, 140, 20);
    -fx-stroke: white;
}

.moe-editor-pane {
    -fx-background-color: white;
    -fx-highlight-fill: hsb(211, 50%, 90%);
}

.moe-find-result {
    -rtfx-background-color: hsb(211, 20%, 99%);
}
.moe-editor-pane .caret {
   -fx-stroke: rgb(255, 0, 100);
}#```

Body:
Here is a very simple code

public class test
{
    public static void main(String[] args)
    {

    System.out.println("  Hello ");

    }
}

I am using a BlueJ IDE.
What I want to do is make the color of the printed output red.
And change the font to any custom made font - say Arial Unicode MS.

Feel free to make changes to the code above or give detailed instructions if other things are required.
Thanks in advance.

Edit:

BlueJ seems to use a wordpad as a console. That is it Channels the output into wordpad/notepad. Does this mean I have to something else?

Or is it the bluej.defs file where I should try changing?


问:
How to clear the shell while the program is running in Python?
```<code>word1=str(input("What is your first word (or topic state, event, any word with a corresponding 'definition')\n"))
def1=str(input("What is the corresponding definition or word to the first word entered?\n"))
print(word1, def1)
</code>```

I have this piece of code, as you can tell the finished result will be something of a flashcard study tool, I was just wondering, that since it is flashcards, being able to see the answer 4 lines up would not be the goal since it is flashcards.

Can I run like a clear function to erase all the prints and user input directly in the program?

答:
A way you can do a clear as stated in another question is:

```<code>import os
import subprocess

def clear():
    if os.name in ('nt','dos'):
        subprocess.call("cls")
    elif os.name in ('linux','osx','posix'):
        subprocess.call("clear")
    else:
        print("\n") * 120
</code>```

Another thing you might try is using tkinter and making your flashcard in a window so it is not just in a console.

Body:
word1=str(input("What is your first word (or topic state, event, any word with a corresponding 'definition')\n"))
def1=str(input("What is the corresponding definition or word to the first word entered?\n"))
print(word1, def1)

I have this piece of code, as you can tell the finished result will be something of a flashcard study tool, I was just wondering, that since it is flashcards, being able to see the answer 4 lines up would not be the goal since it is flashcards.

Can I run like a clear function to erase all the prints and user input directly in the program?

Body:
A way you can do a clear as stated in another question is:

import os
import subprocess

def clear():
    if os.name in ('nt','dos'):
        subprocess.call("cls")
    elif os.name in ('linux','osx','posix'):
        subprocess.call("clear")
    else:
        print("\n") * 120

Another thing you might try is using tkinter and making your flashcard in a window so it is not just in a console.


问:
NodeJS - Check if JSON contains sub JSON
I have two JSON objects and I want to check that one of them contains the other one (Object1 contains Object2)

Both JSON objects are dynamic - I don't know the structure or property names of either objects.

For example, Object1 can look like this:

```<code>{
    "propertyA": "value1",
    "propertyB": "value2",
    "propertyC": {
         "objProp1": "objVal1",
         "objProp2": "objVal2"
    }
    "propertyD": [
       {
         "arrProp1": "arrVal1",
         "arrProp2": "arrVal2"
       },
       {
         "arrProp1": "arrVal3",
         "arrProp2": "arrVal4",
       }
    ]
}
</code>```

While Object2 could be one of the following:

Option 1:

```<code>{
    "propertyA": "value1",
    "propertyD": [
       {
         "arrProp2": "arrVal4"
       }
    ]
}
</code>```

Option 2:

```<code>{
   "objProp1": "objVal1"
}
</code>```

答:
I hope this code come to some use. I didn't have much time to check all edge cases or reduce complexity.

I am not sure what logic exactly you have in mind, Therefore I wrote code for following conditions.

If you want to check in depth if object1 contains object2 (all keys and values in object2 can be found in object1) then this code may help you.

function _contains(obj1, obj2) {
    const obj2keys = Object.keys(obj2);

    for (let i = 0; i < obj2keys.length; i++) {
        const key = obj2keys[i];
        if (obj1.hasOwnProperty(key)) {
            if (typeof (obj1[key]) === typeof (obj2[key])) {
                if (typeof (obj1[key]) === 'object') {
                    if (Object.keys(obj1[key]).length !== Object.keys(obj2[key]).length)
                        return false;
                    const res = _contains(obj1[key], obj2[key])
                    if (!res)
                        return false;
                } else {
                    if (obj1[key] !== obj2[key])
                        return false;
                }
            } else {
                return false;
            }
        } else
            return false;
    }
    return true;
}

function contains(object1, object2) {
    let res = false;
    res = _contains(object1, object2);
    const keys = Object.keys(object1);
    for (let index = 0; index < keys.length; index++) {
        const key = keys[index];
        if (res)
            return res;
        else if (typeof (object1[key]) === 'object') {
            res = contains(object1[key], object2);
        }
    }
    return res;
}

const object1 = {
    "propertyA": "value1",
    "propertyB": "value2",
    "propertyC": {
        "objProp1": "objVal1",
        "objProp2": "objVal2"
    },
    "propertyD": [{
            "arrProp1": "arrVal1",
            "arrProp2": "arrVal2"
        },
        {
            "arrProp1": "arrVal3",
            "arrProp2": "arrVal4",
        }
    ]
}

const object2 = {
    "propertyA": "value1",
    "propertyD": [
       {
         "arrProp2": "arrVal4"
       }
    ]
}

console.log(contains(object1, object2));```
</div>
</div>
</p>

<ol start="2">
<li>If you only need to check for keys only, then below code should be enough. </li>
</ol>

<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>function containsKeys(object1,object2){
    let contains =true;
    const object1Keys = Object.keys(object1);
    const object2Keys = Object.keys(object2);

    for (let index = 0; index < object2Keys.length; index++) {
        const key = object2Keys[index];
        if(!object1.hasOwnProperty(key)){
            contains = false;
        }
    }
    return contains;
}

const object1 = {
    "propertyA": "value1",
    "propertyB": "value2",
    "propertyC": {
        "objProp1": "objVal1",
        "objProp2": "objVal2"
    },
    "propertyD": [{
            "arrProp1": "arrVal1",
            "arrProp2": "arrVal2"
        },
        {
            "arrProp1": "arrVal3",
            "arrProp2": "arrVal4",
        }
    ]
}

const object2 = {
    "propertyA": "value1",
    "propertyD": [
       {
         "arrProp2": "arrVal4"
       }
    ]
}

console.log(containsKeys(object1, object2));</code>```

Body:
I have two JSON objects and I want to check that one of them contains the other one (Object1 contains Object2)

Both JSON objects are dynamic - I don't know the structure or property names of either objects.

For example, Object1 can look like this:

{
    "propertyA": "value1",
    "propertyB": "value2",
    "propertyC": {
         "objProp1": "objVal1",
         "objProp2": "objVal2"
    }
    "propertyD": [
       {
         "arrProp1": "arrVal1",
         "arrProp2": "arrVal2"
       },
       {
         "arrProp1": "arrVal3",
         "arrProp2": "arrVal4",
       }
    ]
}

While Object2 could be one of the following:

Option 1:

{
    "propertyA": "value1",
    "propertyD": [
       {
         "arrProp2": "arrVal4"
       }
    ]
}

Option 2:

{
   "objProp1": "objVal1"
}

Body:
I hope this code come to some use. I didn't have much time to check all edge cases or reduce complexity.

I am not sure what logic exactly you have in mind, Therefore I wrote code for following conditions.

If you want to check in depth if object1 contains object2 (all keys and values in object2 can be found in object1) then this code may help you.

function _contains(obj1, obj2) {
    const obj2keys = Object.keys(obj2);

    for (let i = 0; i < obj2keys.length; i++) {
        const key = obj2keys[i];
        if (obj1.hasOwnProperty(key)) {
            if (typeof (obj1[key]) === typeof (obj2[key])) {
                if (typeof (obj1[key]) === 'object') {
                    if (Object.keys(obj1[key]).length !== Object.keys(obj2[key]).length)
                        return false;
                    const res = _contains(obj1[key], obj2[key])
                    if (!res)
                        return false;
                } else {
                    if (obj1[key] !== obj2[key])
                        return false;
                }
            } else {
                return false;
            }
        } else
            return false;
    }
    return true;
}

function contains(object1, object2) {
    let res = false;
    res = _contains(object1, object2);
    const keys = Object.keys(object1);
    for (let index = 0; index < keys.length; index++) {
        const key = keys[index];
        if (res)
            return res;
        else if (typeof (object1[key]) === 'object') {
            res = contains(object1[key], object2);
        }
    }
    return res;
}

const object1 = {
    "propertyA": "value1",
    "propertyB": "value2",
    "propertyC": {
        "objProp1": "objVal1",
        "objProp2": "objVal2"
    },
    "propertyD": [{
            "arrProp1": "arrVal1",
            "arrProp2": "arrVal2"
        },
        {
            "arrProp1": "arrVal3",
            "arrProp2": "arrVal4",
        }
    ]
}

const object2 = {
    "propertyA": "value1",
    "propertyD": [
       {
         "arrProp2": "arrVal4"
       }
    ]
}

console.log(contains(object1, object2));

If you only need to check for keys only, then below code should be enough.

function containsKeys(object1,object2){
    let contains =true;
    const object1Keys = Object.keys(object1);
    const object2Keys = Object.keys(object2);

    for (let index = 0; index < object2Keys.length; index++) {
        const key = object2Keys[index];
        if(!object1.hasOwnProperty(key)){
            contains = false;
        }
    }
    return contains;
}

const object1 = {
    "propertyA": "value1",
    "propertyB": "value2",
    "propertyC": {
        "objProp1": "objVal1",
        "objProp2": "objVal2"
    },
    "propertyD": [{
            "arrProp1": "arrVal1",
            "arrProp2": "arrVal2"
        },
        {
            "arrProp1": "arrVal3",
            "arrProp2": "arrVal4",
        }
    ]
}

const object2 = {
    "propertyA": "value1",
    "propertyD": [
       {
         "arrProp2": "arrVal4"
       }
    ]
}

console.log(containsKeys(object1, object2));


问:
How to avoid warning of Unreachable code
I have the below

```<code>string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (Match m = r.Match(expression); m.Success; m = m.NextMatch())
{
      currency = (m.Groups[1].Value);
      break;
}
return currency;
</code>```

The intension is that, after the first match in the loop it should break.

The warning messge(Unreachable code) is happening  m = m.NextMatch() of the loop.

How to overcome this?

Thanks

答:
I think you don't have to use m = m.NextMatch()
if the expression is matched you will get the same iterating the groups. so modify the code for scanning the groups for your desired values.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have the below

string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (Match m = r.Match(expression); m.Success; m = m.NextMatch())
{
      currency = (m.Groups[1].Value);
      break;
}
return currency;

The intension is that, after the first match in the loop it should break.

The warning messge(Unreachable code) is happening  m = m.NextMatch() of the loop.

How to overcome this?

Thanks


问:
list remove function on class instance in a list not working properly
here is the code, I'm confused:

```<code>class Button():
    def __init__(self, text):
        self.text = text

bt1 = Button('123')
bt2 = Button('3r5')
bt3 = Button('123')
bt4 = Button('1fe')
bt5 = Button('123')

bts = []

bts.extend((bt1,bt2,bt3,bt4,bt5))
bts.extend((bt1,bt2,bt3,bt4,bt5))

for bt in bts:
    if bt.text == '123':
        bts.remove(bt)

for bt in bts:
    print(bt.text)
</code>```

And here is the results:

```<code>3r5
1fe
123
3r5
1fe
</code>```

My question is, why there is one element with text '123' not been removed?

答:
You are attempting to remove data while iterating over the list. Try a comprehension:

```<code>final_data = [bt for bt in bts if bt.text != "123"]
for i in final_data:
   print(i.text)
</code>```

Output:

```<code>3r5
1fe
3r5
1fe
</code>```

Body:
here is the code, I'm confused:

class Button():
    def __init__(self, text):
        self.text = text

bt1 = Button('123')
bt2 = Button('3r5')
bt3 = Button('123')
bt4 = Button('1fe')
bt5 = Button('123')

bts = []

bts.extend((bt1,bt2,bt3,bt4,bt5))
bts.extend((bt1,bt2,bt3,bt4,bt5))

for bt in bts:
    if bt.text == '123':
        bts.remove(bt)

for bt in bts:
    print(bt.text)

And here is the results:

3r5
1fe
123
3r5
1fe

My question is, why there is one element with text '123' not been removed?

Body:
You are attempting to remove data while iterating over the list. Try a comprehension:

final_data = [bt for bt in bts if bt.text != "123"]
for i in final_data:
   print(i.text)

Output:

3r5
1fe
3r5
1fe


问:
Adding a point every time a div is a certain color, and has been clicked on
So I am trying to create a game with divs that change color, and give the user a point every time they click on a div that is flashing with color. The user will only get a point if the div is flashing that color, so that condition must be satisfied, I know that for sure. The points will display in another div below the colored divs. I have gotten the divs to change color on an interval, however, I cannot get the point system to work, despite creating an if statement that checks the conditions for background color and whether or not the div has been clicked on. Here is my code:</p>

```<code><!DOCTYPE html>
<HTML>

<HEAD>
<STYLE>
.container {
 border: 1px solid black;
 min-width: 100%;
 min-height: 50px;
margin: auto;
 }
   .bigbox {
   min-width: 100%;
   min-height: 100px;
   overflow: scroll;
   border: 1px solid black;
   }
   #bluebox {
   width: 100px;
    height: 100px;
    border: 4px solid black;
    background-color: grey;
    display: inline-block;
   }
 #redbox {
 width: 100px;
 height: 100px;
 border: 4px solid black;
 background-color: grey;
 display: inline-block;
 }
#yellowbox {
width: 100px;
height: 100px;
border: 4px solid black;
background-color: grey;
display: inline-block;
}
  #greenbox {
   width: 100px;
   height: 100px;
   border: 4px solid black;
   background-color: grey;
  display: inline-block;
  }
 </STYLE>
<SCRIPT>
var score = 0;

  function start_game() {
   setTimeout(function() {
 document.getElementById("redbox").style.backgroundColor = "red";
  }, 1000);

   setTimeout(function()
   {document.getElementById("redbox").style.backgroundColor = "grey";
    }, 2000);

   setTimeout(function() {
   document.getElementById("greenbox").style.backgroundColor = "green";
    }, 2000);
   setTimeout(function() {
  document.getElementById("greenbox").style.backgroundColor = "grey";
   }, 3000);

     setTimeout(function() {
   document.getElementById("bluebox").style.backgroundColor = "blue";
    }, 3000);
    setTimeout(function() {
   document.getElementById("bluebox").style.backgroundColor = "grey";
   }, 4000);

   setTimeout(function() {
    document.getElementById("yellowbox").style.backgroundColor = "yellow";
    }, 4000);
  setTimeout(function() {
   document.getElementById("yellowbox").style.backgroundColor = "grey";
   }, 5000);

   setInterval(function(){ start_game() }, 5500);

   if(document.getElementById("redbox").style.backgroundColor = "red" &&
   document.getElementById("redbox").clicked == true) {
   document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
    }

  }

 </SCRIPT>
 <TITLE> Game </TITLE>
 </HEAD>

 <BODY>
 <DIV class="container">
 <CENTER>
 <DIV id="redbox"> </DIV>
<DIV id="greenbox"> </DIV>
<DIV id="bluebox"> </DIV>
<DIV id="yellowbox"> </DIV>
</CENTER>
</DIV>

 <BR><BR>

  <DIV class="container" style= "background-color: grey;"> <CENTER> <BR>
  <button onclick="start_game()"> Start game </button> </CENTER> </DIV>
  <BR><BR>

  <DIV class="bigbox">
  Press "Start Game" to begin. <br>
  Score <p id="score"> 0 </p>

 </DIV>

</HTML>
</code>```

答:
This works!

So all I did was changed your code a little so every time you click on a box it does a check to see if the box that was click is in fact 'active' and then if it was it gives you a point.

This is very very buggy though and If I were you I would definitely looking into another library or atleast JQuery. JQuery would make you life tons easier :)

var score = 0;

function start_game() {
  setTimeout(function() {
    document.getElementById("redbox").style.backgroundColor = "red";
  }, 1000);

  setTimeout(function() {
    document.getElementById("redbox").style.backgroundColor = "grey";
  }, 2000);

  setTimeout(function() {
    document.getElementById("greenbox").style.backgroundColor = "green";
  }, 2000);
  setTimeout(function() {
    document.getElementById("greenbox").style.backgroundColor = "grey";
  }, 3000);

  setTimeout(function() {
    document.getElementById("bluebox").style.backgroundColor = "blue";
  }, 3000);
  setTimeout(function() {
    document.getElementById("bluebox").style.backgroundColor = "grey";
  }, 4000);

  setTimeout(function() {
    document.getElementById("yellowbox").style.backgroundColor = "yellow";
  }, 4000);
  setTimeout(function() {
    document.getElementById("yellowbox").style.backgroundColor = "grey";
  }, 5000);

  setInterval(function() {
    start_game()
  }, 5500);

}

document.getElementById("redbox").addEventListener("click", function(e) {
  if(e.target.style.backgroundColor == "red") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});
document.getElementById("greenbox").addEventListener("click", function(e) {
  if(e.target.style.backgroundColor == "green") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});
document.getElementById("bluebox").addEventListener("click", function(e) {
  if(e.target.style.backgroundColor == "blue") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});
document.getElementById("yellowbox").addEventListener("click", function(e) {
  if(e.target.style.backgroundColor == "yellow") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  border: 1px solid black;
  min-width: 100%;
  min-height: 50px;
  margin: auto;
}

.bigbox {
  min-width: 100%;
  min-height: 100px;
  overflow: scroll;
  border: 1px solid black;
}

#bluebox {
  width: 100px;
  height: 100px;
  border: 4px solid black;
  background-color: grey;
  display: inline-block;
}

#redbox {
  width: 100px;
  height: 100px;
  border: 4px solid black;
  background-color: grey;
  display: inline-block;
}

#yellowbox {
  width: 100px;
  height: 100px;
  border: 4px solid black;
  background-color: grey;
  display: inline-block;
}

#greenbox {
  width: 100px;
  height: 100px;
  border: 4px solid black;
  background-color: grey;
  display: inline-block;
}</code>```

    <button onclick="start_game()"> Start game </button>

  Press "Start Game" to begin.
 Score

 0

```

Body:
So I am trying to create a game with divs that change color, and give the user a point every time they click on a div that is flashing with color. The user will only get a point if the div is flashing that color, so that condition must be satisfied, I know that for sure. The points will display in another div below the colored divs. I have gotten the divs to change color on an interval, however, I cannot get the point system to work, despite creating an if statement that checks the conditions for background color and whether or not the div has been clicked on. Here is my code:

<!DOCTYPE html>

 <TITLE> Game </TITLE>

  <button onclick="start_game()"> Start game </button>

  Press "Start Game" to begin.

  Score
 0

Body:
This works!

So all I did was changed your code a little so every time you click on a box it does a check to see if the box that was click is in fact 'active' and then if it was it gives you a point.

This is very very buggy though and If I were you I would definitely looking into another library or atleast JQuery. JQuery would make you life tons easier :)

var score = 0;

function start_game() {
  setTimeout(function() {
    document.getElementById("redbox").style.backgroundColor = "red";
  }, 1000);

  setTimeout(function() {
    document.getElementById("redbox").style.backgroundColor = "grey";
  }, 2000);

  setTimeout(function() {
    document.getElementById("greenbox").style.backgroundColor = "green";
  }, 2000);
  setTimeout(function() {
    document.getElementById("greenbox").style.backgroundColor = "grey";
  }, 3000);

  setTimeout(function() {
    document.getElementById("bluebox").style.backgroundColor = "blue";
  }, 3000);
  setTimeout(function() {
    document.getElementById("bluebox").style.backgroundColor = "grey";
  }, 4000);

  setTimeout(function() {
    document.getElementById("yellowbox").style.backgroundColor = "yellow";
  }, 4000);
  setTimeout(function() {
    document.getElementById("yellowbox").style.backgroundColor = "grey";
  }, 5000);

  setInterval(function() {
    start_game()
  }, 5500);

}

document.getElementById("redbox").addEventListener("click", function(e) {
  if(e.target.style.backgroundColor == "red") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});
document.getElementById("greenbox").addEventListener("click", function(e) {
  if(e.target.style.backgroundColor == "green") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});
document.getElementById("bluebox").addEventListener("click", function(e) {
  if(e.target.style.backgroundColor == "blue") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});
document.getElementById("yellowbox").addEventListener("click", function(e) {
  if(e.target.style.backgroundColor == "yellow") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});

.container {
  border: 1px solid black;
  min-width: 100%;
  min-height: 50px;
  margin: auto;
}

.bigbox {
  min-width: 100%;
  min-height: 100px;
  overflow: scroll;
  border: 1px solid black;
}

#bluebox {
  width: 100px;
  height: 100px;
  border: 4px solid black;
  background-color: grey;
  display: inline-block;
}

#redbox {
  width: 100px;
  height: 100px;
  border: 4px solid black;
  background-color: grey;
  display: inline-block;
}

#yellowbox {
  width: 100px;
  height: 100px;
  border: 4px solid black;
  background-color: grey;
  display: inline-block;
}

#greenbox {
  width: 100px;
  height: 100px;
  border: 4px solid black;
  background-color: grey;
  display: inline-block;
}

<DIV class="container">
  <CENTER>
    <DIV onclick="" id="redbox"> </DIV>
    <DIV onclick="" id="greenbox"> </DIV>
    <DIV onclick="" id="bluebox"> </DIV>
    <DIV onclick="" id="yellowbox"> </DIV>
  </CENTER>
</DIV>

<BR>
<BR>

<DIV class="container" style="background-color: grey;">
  <CENTER>
    <BR>
    <button onclick="start_game()"> Start game </button> </CENTER>
</DIV>
<BR>
<BR>

<DIV class="bigbox">
  Press "Start Game" to begin. <br> Score
  <p id="score"> 0 </p>

</DIV>


问:
Mapping real-world coordinate to OpenGL coordinate system
I'm currently trying to implement an AR-browser based on indoor maps, but I'm facing several problems, let's take a look at the figure:

In this figure, I've already changed the coordinate to OpenGL's right-handed coordinate system.

In our real-world scenario,

given the angle FOV/2 and the camera height h then I can get nearest visible point P(0,0,-n).

Given the angle B and the camera height h then I can get a point  Q(0,0,-m) between nearest visible point and longest visible point.

Here comes a problem: when I finished setup my vertices(including P and Q) and use the method Matrix.setLookAtM like

```<code>Matrix.setLookAtM(modelMatrix, 0, 0f,h,0f,0f,-2000f,0f,0f,1f,0f);
</code>```

the aspect ratio is incorrect.
If the camera height h is set to 0.92 and FOV is set to 68 degrees, n should be 1.43, But in OpenGL the coordinate of the nearest point is not (0,0,-1.43f). So I'm wondering how to fix this problem, how to map real-world coordinate to OpenGL's coordinate system?

答:
Thank to @Rabbid76's support, I finally figure it out myself.

Figure 1: Real-life scenario

Figure 2: OpenGL scenario

In real-life, if we are facing north, we coordinate system would be like:

x point to the east

y point to the north

z point to the sky

so given a camera held by a user, assuming its height is 1.5 meter and its field of view is 68 degrees, we can reference the nearest visible point is located at P(0,2.223,0). We can set the angle B to 89 degrees, so segment QP will be the visible ground on the smartphone screen.

How can we map the coordinate of real-life to OpenGL coordinate system? I found that we must go through several steps:

Assign the camera position to be the origin (e.g. C in figure2).

Due to OpenGL always draw from (1,1) to (-1,-1), we must assign the distance from C to C' to be 1, so that C' is (0, -1, 0).

Finally, we calculate the aspect ratio with camera height in real-life and segment C, C' in OpenGL, and apply it to other coordinates.

By doing stuff above, we can map real-world coordinate to OpenGL coordinate system magically.

Body:
I'm currently trying to implement an AR-browser based on indoor maps, but I'm facing several problems, let's take a look at the figure:

In this figure, I've already changed the coordinate to OpenGL's right-handed coordinate system.

In our real-world scenario,

given the angle FOV/2 and the camera height h then I can get nearest visible point P(0,0,-n).

Given the angle B and the camera height h then I can get a point  Q(0,0,-m) between nearest visible point and longest visible point.

Here comes a problem: when I finished setup my vertices(including P and Q) and use the method Matrix.setLookAtM like

Matrix.setLookAtM(modelMatrix, 0, 0f,h,0f,0f,-2000f,0f,0f,1f,0f);

the aspect ratio is incorrect.
If the camera height h is set to 0.92 and FOV is set to 68 degrees, n should be 1.43, But in OpenGL the coordinate of the nearest point is not (0,0,-1.43f). So I'm wondering how to fix this problem, how to map real-world coordinate to OpenGL's coordinate system?


问:
script to dump single record from table in mysql
I want to dump single record from mysql table named as table1 for id = 5.

What is mysql query for same?

I think we can use mysqldump but i have used it with full records of table. But how to use it with single record?

答:
if you check at http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html you will find --where option which is the one you need.

Below follows what is stated in that reference:

```<code>--where='where_condition', -w 'where_condition'
</code>```

Dump only rows selected by the given WHERE condition. Quotes around the condition are mandatory if it contains spaces or other characters that are special to your command interpreter.

Examples:

```<code>--where="user='jimf'"
-w"userid>1"
-w"userid<1"
</code>```

Body:
if you check at http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html you will find --where option which is the one you need.

Below follows what is stated in that reference:

--where='where_condition', -w 'where_condition'

Dump only rows selected by the given WHERE condition. Quotes around the condition are mandatory if it contains spaces or other characters that are special to your command interpreter.

Examples:

--where="user='jimf'"
-w"userid>1"
-w"userid<1"


问:
Python pass by value with nested lists?
I'm having a simple issue that's frustrating me. I'm sure I'm making a very obvious mistake, but I can't seem to find it. I want l_old to be the copy of l before undergoing iteration.  I have the following Python script.

```<code>import random
def runtest(n,steps):
    l=[]
    for i in range(n):
        sublist=[]
        for j in range(n):
            sublist.append(0)
        l.append(sublist)

    for k in range(n-1):
        i = random.randint(0,n-1)
        j = random.randint(0,n-1)
        while(l[i][j]==1):
            i = random.randint(0,n-1)
            j = random.randint(0,n-1)
        l[i][j]=1
    l_old = list(l)
    print("L_OLD BEFORE ITERATION", l_old)
    for k in range(steps):
        for i in range(n):
            for j in range(n):
                num = 0
                if i is not 0:
                    num+=l[i-1][j]
                if i is not n-1:
                    num+=l[i+1][j]
                if j is not 0:
                    num+=l[i][j-1]
                if j is not n-1:
                    num+=l[i][j+1]
                if(num > 1):
                    l[i][j]=1
    print("L_OLD AFTER ITERATION",l_old)
    return sum([sum(item) for item in l]), l_old, l
</code>```

However, my output will look like this:

```<code>BEFORE ITERATION [[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [1, 0, 1, 0, 0], [0, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
AFTER ITERATION: [[0, 0, 0, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]
</code>```

So it's changing even though I made a copy of l's value rather than the reference to l. I tried l[:] with the same results. What am I missing? I think it has to do with the fact that it's a nested list, but how can I write it such that all nested lists are copied by value?

答:
I think it has to do with the fact that it's a nested list,

Yes.  You've done a shallow copy:

```<code>l_old = list(l)
</code>```

Slicing with l[:] is also a shallow copy.

but how can I write it such that all nested lists are copied by value?

Try a deep copy:

```<code>from copy import deepcopy
l_old = deepcopy(l)
</code>```

Title: Python pass by value with nested lists?

Body:
I'm having a simple issue that's frustrating me. I'm sure I'm making a very obvious mistake, but I can't seem to find it. I want l_old to be the copy of l before undergoing iteration.  I have the following Python script.

import random
def runtest(n,steps):
    l=[]
    for i in range(n):
        sublist=[]
        for j in range(n):
            sublist.append(0)
        l.append(sublist)

    for k in range(n-1):
        i = random.randint(0,n-1)
        j = random.randint(0,n-1)
        while(l[i][j]==1):
            i = random.randint(0,n-1)
            j = random.randint(0,n-1)
        l[i][j]=1
    l_old = list(l)
    print("L_OLD BEFORE ITERATION", l_old)
    for k in range(steps):
        for i in range(n):
            for j in range(n):
                num = 0
                if i is not 0:
                    num+=l[i-1][j]
                if i is not n-1:
                    num+=l[i+1][j]
                if j is not 0:
                    num+=l[i][j-1]
                if j is not n-1:
                    num+=l[i][j+1]
                if(num > 1):
                    l[i][j]=1
    print("L_OLD AFTER ITERATION",l_old)
    return sum([sum(item) for item in l]), l_old, l

However, my output will look like this:

BEFORE ITERATION [[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [1, 0, 1, 0, 0], [0, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
AFTER ITERATION: [[0, 0, 0, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]

So it's changing even though I made a copy of l's value rather than the reference to l. I tried l[:] with the same results. What am I missing? I think it has to do with the fact that it's a nested list, but how can I write it such that all nested lists are copied by value?

Body:
I think it has to do with the fact that it's a nested list,

Yes.  You've done a shallow copy:

l_old = list(l)

Slicing with l[:] is also a shallow copy.

but how can I write it such that all nested lists are copied by value?

Try a deep copy:

from copy import deepcopy
l_old = deepcopy(l)


问:
Pylint badge in gitlab
Gitlab has functionality to generade badges about build status and coverage percentage.

Is it possible to create custom badge to display Pylint results?
Or just display this results in README.md?

I already have CI job for Pylint

答:
I have written a python badge generation package that produces badges very visually similar to the main badge services.  It is highly flexible, you can import and use in your python code, or run from the command line.

I use this in GitLab CI to display pylint and coverage scores.

There are other ways to do this using shields.io (see other answer from kubouch), but this approach can be used in situations where you may not have external internet access, such as in a corporate / enterprise setting where firewalls or proxies are blocking internet access.

GitLab CI Setup

1. Generate the badge

My CI pipeline has a step that runs pylint, and I used sed to extract the score from the output text.  I then use anybadge (details below) to generate a pylint score badge, and save it as public/pylint.svg.

```<code>pylint:
  stage: test
  script:
    - pylint --rcfile=.pylintrc --output-format=text <LIST-OF-FILES-TO-RUN-PYLINT-AGAINST> | tee pylint.txt
    - score=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' pylint.txt)
    - echo "Pylint score was $score"
    - anybadge --value=$score --file=public/pylint.svg pylint
</code>```

If pylint generates a non-zero rc then GitLab will see that as a command error and the job will fail, meaning no badge is generated, and missing image will show where the badge is used.

NOTE: pylint WILL OFTEN generate non-zero return codes since it uses the exit code to communicate the status of the lint check.  I suggest using something like pylint-exit to handle pylint return codes in CI pipelines.

2. Register badge as pipeline artifact

I register the generated badge file as an artifact in the CI job by including this in the .gitlab-ci.yml:

```<code>pylint:
    ...
    - echo "Pylint score was $score"
    - anybadge --value=$score --file=public/pylint.svg pylint
  artifacts:
    paths:
      - public/pylint.svg
</code>```

3. Publish badge to GitLab Pages

I include a pages publish step, which deploys everything in the public directory to GitLab pages:

```<code>pages:
  stage: deploy
  artifacts:
    paths:
    - public
  only:
  - master
</code>```

4. Include badge in README.md

When the master pipeline runs for the project, the pylint.svg file is published to GitLab Pages, and I can then reference the image from my project README.md so that the latest pylint badge is displayed.

If you are using https://gitlab.com for your project then the URL for the svg artifact will usually be something like this (replace NAMESPACE with your username, or group name if your project is under a group - more details here):

https://NAMESPACE.gitlab.io/pyling.svg

In your README.md you can include an image with:

```<code>![pylint](https://NAMESPACE.gitlab.io/pyling.svg)
</code>```

If you want to make the image into a link you can use:

```<code>[![pylint](https://NAMESPACE.gitlab.io/pyling.svg)](LINKTARGET)
</code>```

Let me know if you need more information on any of the setup.

Anybadge Python Package

Here's some more info on the anybadge Python package:

You can set the badge label and value, and you can set the color based on thresholds.  There are pre-built settings for pylint, coverage, and pipeline success, but you can create any badge you like.

Here is a link to the github project with more detailed documentation: https://github.com/jongracecox/anybadge

Install with pip install anybadge

Example python code:

```<code>import anybadge

# Define thresholds: <2=red, <4=orange <8=yellow <10=green
thresholds = {2: 'red',
              4: 'orange',
              6: 'yellow',
              10: 'green'}

badge = anybadge.Badge('pylint', 2.22, thresholds=thresholds)

badge.write_badge('pylint.svg')
</code>```

Example command line use:

```<code>anybadge --label pylint --value 2.22 --file pylint.svg 2=red 4=orange 8=yellow 10=green
</code>```

Update 2019

Using GitLab Pages is no longer required

It is now possible to directly access to the latest articfact, which simplify the workaround.

Use a dedicated pylint artifact instead of public, and remove the unnecessary deploy step (or edit it if already used):

```<code>pylint:
  stage: test
  before_script:
    - pip install pylint pylint-exit anybadge
  script:
    - mkdir ./pylint
    - pylint --output-format=text . | tee ./pylint/pylint.log || pylint-exit $?
    - PYLINT_SCORE=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' ./pylint/pylint.log)
    - anybadge --label=Pylint --file=pylint/pylint.svg --value=$PYLINT_SCORE 2=red 4=orange 8=yellow 10=green
    - echo "Pylint score is $PYLINT_SCORE"
  artifacts:
    paths:
      - ./pylint/
</code>```

Note that here I copy the Pylint log file in the folder artifact, in this way it will be accessible without looking at the pipeline logs.

The badge image will then be available at https://gitlab.example.com/john-doe/foo/-/jobs/artifacts/master/raw/pylint/pylint.svg?job=pylint, and the Pylint log at https://gitlab.example.com/john-doe/foo/-/jobs/artifacts/master/raw/pylint/pylint.log?job=pylint.

2. You can use GitLab's builtin badges instead of images in README

GitLab can now include badges in a projet or group, that will be displayed in the project header.

Got to Settings / General / Badges, then create a new badge by setting its link and image link, as described above:

Title: Pylint badge in gitlab

Body:
I have written a python badge generation package that produces badges very visually similar to the main badge services.  It is highly flexible, you can import and use in your python code, or run from the command line.

I use this in GitLab CI to display pylint and coverage scores.

There are other ways to do this using shields.io (see other answer from kubouch), but this approach can be used in situations where you may not have external internet access, such as in a corporate / enterprise setting where firewalls or proxies are blocking internet access.

GitLab CI Setup

1. Generate the badge

My CI pipeline has a step that runs pylint, and I used sed to extract the score from the output text.  I then use anybadge (details below) to generate a pylint score badge, and save it as public/pylint.svg.

pylint:
  stage: test
  script:
    - pylint --rcfile=.pylintrc --output-format=text <LIST-OF-FILES-TO-RUN-PYLINT-AGAINST> | tee pylint.txt
    - score=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' pylint.txt)
    - echo "Pylint score was $score"
    - anybadge --value=$score --file=public/pylint.svg pylint

If pylint generates a non-zero rc then GitLab will see that as a command error and the job will fail, meaning no badge is generated, and missing image will show where the badge is used.

NOTE: pylint WILL OFTEN generate non-zero return codes since it uses the exit code to communicate the status of the lint check.  I suggest using something like pylint-exit to handle pylint return codes in CI pipelines.

2. Register badge as pipeline artifact

I register the generated badge file as an artifact in the CI job by including this in the .gitlab-ci.yml:

pylint:
    ...
    - echo "Pylint score was $score"
    - anybadge --value=$score --file=public/pylint.svg pylint
  artifacts:
    paths:
      - public/pylint.svg

3. Publish badge to GitLab Pages

I include a pages publish step, which deploys everything in the public directory to GitLab pages:

pages:
  stage: deploy
  artifacts:
    paths:
    - public
  only:
  - master

4. Include badge in README.md

When the master pipeline runs for the project, the pylint.svg file is published to GitLab Pages, and I can then reference the image from my project README.md so that the latest pylint badge is displayed.

If you are using https://gitlab.com for your project then the URL for the svg artifact will usually be something like this (replace NAMESPACE with your username, or group name if your project is under a group - more details here):

https://NAMESPACE.gitlab.io/pyling.svg

In your README.md you can include an image with:

![pylint](https://NAMESPACE.gitlab.io/pyling.svg)

If you want to make the image into a link you can use:

[![pylint](https://NAMESPACE.gitlab.io/pyling.svg)](LINKTARGET)

Let me know if you need more information on any of the setup.

Anybadge Python Package

Here's some more info on the anybadge Python package:

You can set the badge label and value, and you can set the color based on thresholds.  There are pre-built settings for pylint, coverage, and pipeline success, but you can create any badge you like.

Here is a link to the github project with more detailed documentation: https://github.com/jongracecox/anybadge

Install with pip install anybadge

Example python code:

import anybadge

# Define thresholds: <2=red, <4=orange <8=yellow <10=green
thresholds = {2: 'red',
              4: 'orange',
              6: 'yellow',
              10: 'green'}

badge = anybadge.Badge('pylint', 2.22, thresholds=thresholds)

badge.write_badge('pylint.svg')

Example command line use:

anybadge --label pylint --value 2.22 --file pylint.svg 2=red 4=orange 8=yellow 10=green

Update 2019

Using GitLab Pages is no longer required

It is now possible to directly access to the latest articfact, which simplify the workaround.

Use a dedicated pylint artifact instead of public, and remove the unnecessary deploy step (or edit it if already used):

pylint:
  stage: test
  before_script:
    - pip install pylint pylint-exit anybadge
  script:
    - mkdir ./pylint
    - pylint --output-format=text . | tee ./pylint/pylint.log || pylint-exit $?
    - PYLINT_SCORE=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' ./pylint/pylint.log)
    - anybadge --label=Pylint --file=pylint/pylint.svg --value=$PYLINT_SCORE 2=red 4=orange 8=yellow 10=green
    - echo "Pylint score is $PYLINT_SCORE"
  artifacts:
    paths:
      - ./pylint/

Note that here I copy the Pylint log file in the folder artifact, in this way it will be accessible without looking at the pipeline logs.

The badge image will then be available at https://gitlab.example.com/john-doe/foo/-/jobs/artifacts/master/raw/pylint/pylint.svg?job=pylint, and the Pylint log at https://gitlab.example.com/john-doe/foo/-/jobs/artifacts/master/raw/pylint/pylint.log?job=pylint.

2. You can use GitLab's builtin badges instead of images in README

GitLab can now include badges in a projet or group, that will be displayed in the project header.

Got to Settings / General / Badges, then create a new badge by setting its link and image link, as described above:

ContentLicense: CC BY-SA 4.0


问:
Unable to display the Array contents present inside of an Array in ES6
For some reason i am not able to display the Array contents present inside of an Array though i have them.

Here is the code attached

```<code>render() {
 {
 var data ={
   value : "dff",
   provider: [{
   0:[{name: 'Rishan'},{name: 'kishan'},{name: 'jishan'},{name: 'mishan'},{name: 'fishan'}]
   }]
 }
 data.provider.map((i) => {
     i.map((j) => {
       return (
         <div>
         <h1>{i.value}</h1>
         <h1>{j.name}</h1>
         </div>
       );
     })
    })
    }
   }
   }
</code>```

Now, I am trying to display the contents present inside the 0th index of the provider array

i.e

it has to print
   'Rishan', 'kishan', 'jishan' etc...

The present code is  displaying the

Any help would be appreciated.

答:
Its because your render function does not return valid jsx. wrap your entire content inside a div. else it wont work</p>

```<code> render() {
{
 var data ={
  value : "dff",
  provider: [{
  0:[{name: 'Rishan'},{name: 'kishan'},{name: 'jishan'},{name: 'mishan'},
 {name: 'fishan'}]
     }]
 }
return(<div>
 {data.provider.map((i) => {
    i[0].map((j) => {
      return (
        <div>
       <h1>{i.value}</h1>
       <h1>{j.name}</h1>
       </div>
     );
   })}</div>);
})
}
}
}
</code>```

Body:
For some reason i am not able to display the Array contents present inside of an Array though i have them.

Here is the code attached

render() {
 {
 var data ={
   value : "dff",
   provider: [{
   0:[{name: 'Rishan'},{name: 'kishan'},{name: 'jishan'},{name: 'mishan'},{name: 'fishan'}]
   }]
 }
 data.provider.map((i) => {
     i.map((j) => {
       return (

{i.value}

{j.name}

       );
     })
    })
    }
   }
   }

Now, I am trying to display the contents present inside the 0th index of the provider array

i.e

it has to print
   'Rishan', 'kishan', 'jishan' etc...

The present code is  displaying the

Any help would be appreciated.

Body:
Its because your render function does not return valid jsx. wrap your entire content inside a div. else it wont work

 render() {
{
 var data ={
  value : "dff",
  provider: [{
  0:[{name: 'Rishan'},{name: 'kishan'},{name: 'jishan'},{name: 'mishan'},
 {name: 'fishan'}]
     }]
 }
return(<div>
 {data.provider.map((i) => {
    i[0].map((j) => {
      return (
        <div>
       <h1>{i.value}</h1>
       <h1>{j.name}</h1>
       </div>
     );
   })}</div>);
})
}
}
}


答:
You need to return something, if you don't put a return statement, then JavaScript will return undefined</p>

```<code>render() {
 {
 var data ={
   value : "dff",
   provider: [{
   0:[{name: 'Rishan'},{name: 'kishan'},{name: 'jishan'},{name: 'mishan'},{name: 'fishan'}]
   }]
 }
 return data.provider.map((i) => {
     i[0].map((j) => {
       return (
         <div>
         <h1>{i.value}</h1>
         <h1>{j.name}</h1>
         </div>
       );
     })
    })
    }
   }
   }
</code>```

Title: Unable to display the Array contents present inside of an Array in ES6

Body:
You need to return something, if you don't put a return statement, then JavaScript will return undefined

render() {
 {
 var data ={
   value : "dff",
   provider: [{
   0:[{name: 'Rishan'},{name: 'kishan'},{name: 'jishan'},{name: 'mishan'},{name: 'fishan'}]
   }]
 }
 return data.provider.map((i) => {
     i[0].map((j) => {
       return (
         <div>
         <h1>{i.value}</h1>
         <h1>{j.name}</h1>
         </div>
       );
     })
    })
    }
   }
   }


问:
SQL Server pagination of a result set
I have a very meaty stored procedure in a SQL Server 2000 DB which returns a single resultset. I don't want to (not allowed to) touch the original SP but would like add pagination to the returned records.

Is it possible to wrap this SP with another that takes the returned resultset and only gives me rows X to Y ?

答:
```<code>create procedure ProcWrap
as

declare @T table (ID int, Name nvarchar(50))

insert into @T
exec ProcToWrap

select *
from @T
where ID < 10
</code>```

Edit 1
Don't have SQL Server 2000 to test on and I don't remember if table variables where available then. Here is a procedure using a temp table instead. Added a RowNum identity column that you can use for pagination.

```<code>create procedure ProcWrap2
as

create table #T (RowNum int identity, ID int, Name nvarchar(50))

insert into #T
exec ProcToWrap

select *
from #T
where RowNum between 10 and 19

drop table #T
</code>```

Edit 2
Output from ProcToWrap in this case is columns ID and Name. RowNum is generated automatically.

Title: SQL Server pagination of a result set

Body:
create procedure ProcWrap
as

declare @T table (ID int, Name nvarchar(50))

insert into @T
exec ProcToWrap

select *
from @T
where ID < 10

Edit 1
Don't have SQL Server 2000 to test on and I don't remember if table variables where available then. Here is a procedure using a temp table instead. Added a RowNum identity column that you can use for pagination.

create procedure ProcWrap2
as

create table #T (RowNum int identity, ID int, Name nvarchar(50))

insert into #T
exec ProcToWrap

select *
from #T
where RowNum between 10 and 19

drop table #T

Edit 2
Output from ProcToWrap in this case is columns ID and Name. RowNum is generated automatically.


问:
why conditional or doesn't evaluates to boolean value when assigned to a variable
inside conditional statement any logical operation will evaluate to a boolean value which determines whether or not the conditional block will be executed or not. Like the following statement will determine the IF statement will execute or not

```<code>if(null || 1){} // evaluates to boolean value
</code>```

but the same conditional statement will evaluates to Number value when assigned to a variable.Consider this:

```<code>var x = null || 1 // x will become 1
</code>```

my another question is does the order of null and 1 matters here?

what determines when a conditional operation will become Boolean or Number ?

答: In JavaScript, 1 is "truthy", which is why the if statement is entered. Basically, (null || 1) always evaluates to 1, but if forced, we say that it's true rather than false.

Body:
inside conditional statement any logical operation will evaluate to a boolean value which determines whether or not the conditional block will be executed or not. Like the following statement will determine the IF statement will execute or not

if(null || 1){} // evaluates to boolean value

but the same conditional statement will evaluates to Number value when assigned to a variable.Consider this:

var x = null || 1 // x will become 1

my another question is does the order of null and 1 matters here?

what determines when a conditional operation will become Boolean or Number ?


问:
run release tasks selectively based on project code changes
We are using VSTS for build and release management, and using CI/CD. Typically, our solutions consist of a web application project, and a database project.

Our current release tasks take the application offline (using app_offline.htm), publish the database, then publish the web application. Publishing the database project often results in no changes, as due to CI/CD we are much more frequently updating code on the web app than changing the db schema.

Is there a way to only run the database publish task (using WinRM) when it detects a change in the database project code, in our git repository?

EDIT: This in itself isn't a problem, as typically when the DACPAC gets published, there will be no activity. HOWEVER, I've been requesting that the database is backed up using the /p:BackupDatabaseBeforeChanges=true flag - which seems to back up the database even if there are no changes. This is an issue for large databases.

答:
The simple way is that you can separate web project and database project to two build definitions.

Create a new build definition

Enable Continuous Integration in Triggers tab

Specify Path filter to include database project

Modify Visual Studio Build task, specify /t:[database project name] argument in MSBuild Arguments box to just build database project

The same steps for web project

Create a new related definition

Add artifacts for previous two build definitions and enable Continuous deployment trigger

Add two environments (e.g. database, web)

Open Pre-deployment conditions of an environment (e.g. database)

Enable Artifact filters and select corresponding artifact (e.g. database build artifact), specify build branch (can specify *, it means all branches)

Add tasks to just deploy database in this environment

The same steps for web environment


答:
They both result in the same thing. The difference, however, is that the if statement parses the value as a boolean: the 1 returned is parsed as a boolean.

```<code>> (null || 1)
1
> Boolean(1)
true
</code>```

The if(null || 1){} simply evaluates to if(1){} which in turn evaluates to if(true){} since 1 is truthy.

Thus, there is no deterministic difference, the if statement simply parses the parameter as a boolean while the variable definition merely returns the number itself.

From mozzila.org:

In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false , 0 , "" , null , undefined , and NaN ). JavaScript uses type coercion in Boolean contexts

Title: why conditional or doesn't evaluates to boolean value when assigned to a variable

Body:
They both result in the same thing. The difference, however, is that the if statement parses the value as a boolean: the 1 returned is parsed as a boolean.

> (null || 1)
1
> Boolean(1)
true

The if(null || 1){} simply evaluates to if(1){} which in turn evaluates to if(true){} since 1 is truthy.

Thus, there is no deterministic difference, the if statement simply parses the parameter as a boolean while the variable definition merely returns the number itself.

From mozzila.org:

In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false , 0 , "" , null , undefined , and NaN ). JavaScript uses type coercion in Boolean contexts


问:
Reading a particular column in csv file using numpy in python
How to read string column only using numpy in python?

csv file:

```<code>1,2,3,"Hello"
3,3,3,"New"
4,5,6,"York"
</code>```

How to get array like:

```<code>["Hello","york","New"]
</code>```

without using pandas and sklearn.

答:
A quick file substitute:

```<code>In [275]: txt = b'''
     ...: 1,2,3,"Hello"
     ...: 3,3,3,"New"
     ...: 4,5,6,"York"'''

In [277]: np.genfromtxt(txt.splitlines(), delimiter=',',dtype=None,usecols=3)
Out[277]:
array([b'"Hello"', b'"New"', b'"York"'],
      dtype='|S7')
</code>```

bytestring array in Py3; or a default unicode string dtype:

```<code>In [278]: np.genfromtxt(txt.splitlines(), delimiter=',',dtype=str,usecols=3)
Out[278]:
array(['"Hello"', '"New"', '"York"'],
      dtype='<U7')
</code>```

Or the whole thing:

```<code>In [279]: data=np.genfromtxt(txt.splitlines(), delimiter=',',dtype=None)
In [280]: data
Out[280]:
array([(1, 2, 3, b'"Hello"'), (3, 3, 3, b'"New"'), (4, 5, 6, b'"York"')],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', 'S7')])
</code>```

select the f3 field:

```<code>In [282]: data['f3']
Out[282]:
array([b'"Hello"', b'"New"', b'"York"'],
      dtype='|S7')
</code>```

Speed should be basically the same

Body:
How to read string column only using numpy in python?

csv file:

1,2,3,"Hello"
3,3,3,"New"
4,5,6,"York"

How to get array like:

["Hello","york","New"]

without using pandas and sklearn.

Body:
A quick file substitute:

In [275]: txt = b'''
     ...: 1,2,3,"Hello"
     ...: 3,3,3,"New"
     ...: 4,5,6,"York"'''

In [277]: np.genfromtxt(txt.splitlines(), delimiter=',',dtype=None,usecols=3)
Out[277]:
array([b'"Hello"', b'"New"', b'"York"'],
      dtype='|S7')

bytestring array in Py3; or a default unicode string dtype:

In [278]: np.genfromtxt(txt.splitlines(), delimiter=',',dtype=str,usecols=3)
Out[278]:
array(['"Hello"', '"New"', '"York"'],
      dtype='<U7')

Or the whole thing:

In [279]: data=np.genfromtxt(txt.splitlines(), delimiter=',',dtype=None)
In [280]: data
Out[280]:
array([(1, 2, 3, b'"Hello"'), (3, 3, 3, b'"New"'), (4, 5, 6, b'"York"')],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', 'S7')])

select the f3 field:

In [282]: data['f3']
Out[282]:
array([b'"Hello"', b'"New"', b'"York"'],
      dtype='|S7')

Speed should be basically the same


问:
Retrieving subfolders names in S3 bucket from boto3
Using boto3, I can access my AWS S3 bucket:

```<code>s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket-name')
</code>```

Now, the bucket contains folder first-level, which itself contains several sub-folders named with a timestamp, for instance 1456753904534.
I need to know the name of these sub-folders for another job I'm doing and I wonder whether I could have boto3 retrieve those for me.

So I tried:

```<code>objs = bucket.meta.client.list_objects(Bucket='my-bucket-name')
</code>```

which gives a dictionary, whose key 'Contents' gives me all the third-level files instead of the second-level timestamp directories, in fact I get a list containing things as

{u'ETag': '"etag"',   u'Key': first-level/1456753904534/part-00014',   u'LastModified':
  datetime.datetime(2016, 2, 29, 13, 52, 24, tzinfo=tzutc()),

  u'Owner': {u'DisplayName': 'owner',    u'ID':
  'id'},

  u'Size': size,   u'StorageClass': 'storageclass'}

you can see that the specific files, in this case part-00014 are retrieved, while I'd like to get the name of the directory alone.
In principle I could strip out the directory name from all the paths but it's ugly and expensive to retrieve everything at third level to get the second level!

I also tried something reported here:

```<code>for o in bucket.objects.filter(Delimiter='/'):
    print(o.key)
</code>```

but I do not get the folders at the desired level.

Is there a way to solve this?

答:
The AWS cli does this (presumably without fetching and iterating through all keys in the bucket) when you run aws s3 ls s3://my-bucket/, so I figured there must be a way using boto3.

https://github.com/aws/aws-cli/blob/0fedc4c1b6a7aee13e2ed10c3ada778c702c22c3/awscli/customizations/s3/subcommands.py#L499

It looks like they indeed use Prefix and Delimiter - I was able to write a function that would get me all directories at the root level of a bucket by modifying that code a bit:

```<code>def list_folders_in_bucket(bucket):
    paginator = boto3.client('s3').get_paginator('list_objects')
    folders = []
    iterator = paginator.paginate(Bucket=bucket, Prefix='', Delimiter='/', PaginationConfig={'PageSize': None})
    for response_data in iterator:
        prefixes = response_data.get('CommonPrefixes', [])
        for prefix in prefixes:
            prefix_name = prefix['Prefix']
            if prefix_name.endswith('/'):
                folders.append(prefix_name.rstrip('/'))
    return folders
</code>```

Body:
Using boto3, I can access my AWS S3 bucket:

s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket-name')

Now, the bucket contains folder first-level, which itself contains several sub-folders named with a timestamp, for instance 1456753904534.
I need to know the name of these sub-folders for another job I'm doing and I wonder whether I could have boto3 retrieve those for me.

So I tried:

objs = bucket.meta.client.list_objects(Bucket='my-bucket-name')

which gives a dictionary, whose key 'Contents' gives me all the third-level files instead of the second-level timestamp directories, in fact I get a list containing things as

{u'ETag': '"etag"',   u'Key': first-level/1456753904534/part-00014',   u'LastModified':
  datetime.datetime(2016, 2, 29, 13, 52, 24, tzinfo=tzutc()),

  u'Owner': {u'DisplayName': 'owner',    u'ID':
  'id'},

  u'Size': size,   u'StorageClass': 'storageclass'}

you can see that the specific files, in this case part-00014 are retrieved, while I'd like to get the name of the directory alone.
In principle I could strip out the directory name from all the paths but it's ugly and expensive to retrieve everything at third level to get the second level!

I also tried something reported here:

for o in bucket.objects.filter(Delimiter='/'):
    print(o.key)

but I do not get the folders at the desired level.

Is there a way to solve this?

Body:
The AWS cli does this (presumably without fetching and iterating through all keys in the bucket) when you run aws s3 ls s3://my-bucket/, so I figured there must be a way using boto3.

https://github.com/aws/aws-cli/blob/0fedc4c1b6a7aee13e2ed10c3ada778c702c22c3/awscli/customizations/s3/subcommands.py#L499

It looks like they indeed use Prefix and Delimiter - I was able to write a function that would get me all directories at the root level of a bucket by modifying that code a bit:

def list_folders_in_bucket(bucket):
    paginator = boto3.client('s3').get_paginator('list_objects')
    folders = []
    iterator = paginator.paginate(Bucket=bucket, Prefix='', Delimiter='/', PaginationConfig={'PageSize': None})
    for response_data in iterator:
        prefixes = response_data.get('CommonPrefixes', [])
        for prefix in prefixes:
            prefix_name = prefix['Prefix']
            if prefix_name.endswith('/'):
                folders.append(prefix_name.rstrip('/'))
    return folders


问:
Full iPhone X resolution in Firemonkey app?
If i try to run an simple iOS app (written in 10.1 Berlin ) on iPhone X,  the app can’t use a full iPhone X display size. It is possible to set a full iPhone X resolution for an Delphi/FMX app?</p>

答:
You need to include the additional 2 launch images required for iPhone X as per this chart:

https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/launch-screen/

Also, you'll need to provide a custom .info.plist, which includes entries for the launch images (since the IDE does not do it for you), i.e. add this to the array node for the UILaunchImages key:

```<code>        <dict>
            <key>UILaunchImageSize</key>
            <string>{375, 812}</string>
            <key>UILaunchImageName</key>
            <string>Default-812h</string>
            <key>UILaunchImageMinimumOSVersion</key>
            <string>8.0</string>
            <key>UILaunchImageOrientation</key>
            <string>Portrait</string>
        </dict>
        <dict>
            <key>UILaunchImageSize</key>
            <string>{812, 375}</string>
            <key>UILaunchImageName</key>
            <string>Default-Landscape-812h</string>
            <key>UILaunchImageMinimumOSVersion</key>
            <string>8.0</string>
            <key>UILaunchImageOrientation</key>
            <string>Landscape</string>
        </dict>
</code>```

You'll need to add the images to the project deployment, and edit the Remote Name properties for each to align with the entries in the .info.plist, e.g:

But wait, there's more! You also need to account for spacing as per the other answer from Pimmie. You could do this by having layouts aligned to the top, bottom, left and right that are shown only when on iPhone X, using something like:

```<code>uses
  iOSapi.Helpers;

...

if TiOSHelper.MainScreen.bounds.size.height = 812 then
  // iPhoneX
</code>```

There's also an issue with Delphi providing "space" for the status bar which it might not need to do for iPhone X (still working this out).

For me, this procedure works with both Berlin and Tokyo, however all in all: not trivial

Body:
You need to include the additional 2 launch images required for iPhone X as per this chart:

https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/launch-screen/

Also, you'll need to provide a custom .info.plist, which includes entries for the launch images (since the IDE does not do it for you), i.e. add this to the array node for the UILaunchImages key:

        <dict>
            <key>UILaunchImageSize</key>
            <string>{375, 812}</string>
            <key>UILaunchImageName</key>
            <string>Default-812h</string>
            <key>UILaunchImageMinimumOSVersion</key>
            <string>8.0</string>
            <key>UILaunchImageOrientation</key>
            <string>Portrait</string>
        </dict>
        <dict>
            <key>UILaunchImageSize</key>
            <string>{812, 375}</string>
            <key>UILaunchImageName</key>
            <string>Default-Landscape-812h</string>
            <key>UILaunchImageMinimumOSVersion</key>
            <string>8.0</string>
            <key>UILaunchImageOrientation</key>
            <string>Landscape</string>
        </dict>

You'll need to add the images to the project deployment, and edit the Remote Name properties for each to align with the entries in the .info.plist, e.g:

But wait, there's more! You also need to account for spacing as per the other answer from Pimmie. You could do this by having layouts aligned to the top, bottom, left and right that are shown only when on iPhone X, using something like:

uses
  iOSapi.Helpers;

...

if TiOSHelper.MainScreen.bounds.size.height = 812 then
  // iPhoneX

There's also an issue with Delphi providing "space" for the status bar which it might not need to do for iPhone X (still working this out).

For me, this procedure works with both Berlin and Tokyo, however all in all: not trivial


问:
Is it possible to set the stacking order of pseudo-elements below their parent element?
I am trying to style a element with the :after pseudo element CSS selector

#element {
    position: relative;
    z-index: 1;
}

#element::after {
    position:relative;
    z-index: 0;
    content: " ";
    position: absolute;
    width: 100px;
    height: 100px;
}
```

It seems like the ::after element can not be lower then the element itself.

Is there a way to have the pseudo element lower then the element itself?

答:
Set the z-index of the :before or :after pseudo element to -1 and give it a position that honors the z-index property (absolute, relative, or fixed).  This works because the pseudo element's z-index is relative to its parent element, rather than , which is the default for other elements.  Which makes sense because they are child elements of .

The problem I was having (that lead me to this question and the accepted answer above) was that I was trying to use a :after pseudo element to get fancy with a background to an element with z-index of 15, and even when set with a z-index of 14, it was still being rendered on top of its parent.  This is because, in that stacking context, it's parent has a z-index of 0.

Hopefully that helps clarify a little what's going on.

Body:
I am trying to style a element with the :after pseudo element CSS selector

#element {
    position: relative;
    z-index: 1;
}

#element::after {
    position:relative;
    z-index: 0;
    content: " ";
    position: absolute;
    width: 100px;
    height: 100px;
}

It seems like the ::after element can not be lower then the element itself.

Is there a way to have the pseudo element lower then the element itself?

Body:
Set the z-index of the :before or :after pseudo element to -1 and give it a position that honors the z-index property (absolute, relative, or fixed).  This works because the pseudo element's z-index is relative to its parent element, rather than <html>, which is the default for other elements.  Which makes sense because they are child elements of <html>.

The problem I was having (that lead me to this question and the accepted answer above) was that I was trying to use a :after pseudo element to get fancy with a background to an element with z-index of 15, and even when set with a z-index of 14, it was still being rendered on top of its parent.  This is because, in that stacking context, it's parent has a z-index of 0.

Hopefully that helps clarify a little what's going on.


问:
My value turns to NaN in Pandas
I have the following table:

Year    VTP VTT VKB VDP VCL VLX VVL VCT
2007
2008    50  54  55  56  56  56  56  55
2011    49  49  48  46  46  48  48  49
2013    44  48  47  49  48  49  50  51
2015    47   47 50  49  48  49  50  48
```

<p>And I want to plot it, but before doing that, I want to make sure that all of the value in my table are numeric, so I use the following code:</p>

```df = df1.apply(pd.to_numeric, errors='coerce')
```

<p>When I print it, it turns some values in the table to <code>NaN</code> (please see table below, especially for year 2015).</p>

<pre class="lang-none prettyprint-override"><code>      VTP   VTT   VKB    VDP   VCL  VLX    VVL   VCT
Year
2007   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
2008  50.0  54.0  55.0  56.0  56.0  56.0  56.0  55.0
2011  49.0  49.0  48.0  46.0  46.0  48.0  48.0  49.0
2013  44.0  48.0  47.0  49.0  48.0  49.0  50.0  51.0
2015  47.0   NaN  50.0  49.0   NaN  49.0   NaN  48.0
</code>```

Thus, I would like to ask why does it behave that way and how to solve it?

Title: My value turns to NaN in Pandas

Body:
I have the following table:

Year    VTP VTT VKB VDP VCL VLX VVL VCT
2007
2008    50  54  55  56  56  56  56  55
2011    49  49  48  46  46  48  48  49
2013    44  48  47  49  48  49  50  51
2015    47   47 50  49  48  49  50  48

And I want to plot it, but before doing that, I want to make sure that all of the value in my table are numeric, so I use the following code:

df = df1.apply(pd.to_numeric, errors='coerce')

When I print it, it turns some values in the table to NaN (please see table below, especially for year 2015).

      VTP   VTT   VKB    VDP   VCL  VLX    VVL   VCT
Year
2007   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
2008  50.0  54.0  55.0  56.0  56.0  56.0  56.0  55.0
2011  49.0  49.0  48.0  46.0  46.0  48.0  48.0  49.0
2013  44.0  48.0  47.0  49.0  48.0  49.0  50.0  51.0
2015  47.0   NaN  50.0  49.0   NaN  49.0   NaN  48.0

Thus, I would like to ask why does it behave that way and how to solve it?

Body:
Let's try replace + to_numeric:

df.astype(str).replace('[^\d.]', '', regex=True)\
                   .apply(pd.to_numeric, errors='coerce')

   Year   VTP   VTT   VKB   VDP   VCL   VLX   VVL   VCT
0  2007   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
1  2008  50.0  54.0  55.0  56.0  56.0  56.0  56.0  55.0
2  2011  49.0  49.0  48.0  46.0  46.0  48.0  48.0  49.0
3  2013  44.0  48.0  47.0  49.0  48.0  49.0  50.0  51.0
4  2015  47.0  47.0  50.0  49.0  48.0  49.0  50.0  48.0


问:
Is tweenlite faster/lighter than manual animation?
I was wondering is there a difference between the processor usage when using tweenlite or animating the same clip manually? Considering it's vectors and also dynamic text with it.

Similarly, if we animate manually or copy the code snippet produced by that animation. Would that make a difference on the CPU usage?

答:
I don't really know whether the code generated from IDE tweening is faster (I highly doubt that, as there would be an overhead of initializing motion and easing functions and variables) but performance-wise here are some general factors you need to consider:

Every frame (not keyframe) in a classic motion tween is precalculated and stored, adding some little bytes to your SWF. In particularly long animations these add up to kilobytes. This is not the case with shape tweens, where only keyframes are stored.

Because the motion tweens are precalculated, CPU is free of calculating the transformations, etc. in each frame between keyframes. However this gain really doesn't matter very much as the really intensive CPU demand results from calculating the blending (alpha, layer blending, etc.) and rendering of large areas every frame. That means, if you are moving huge bitmaps or sprites, neither classic nor algorithmic tweening is going to help you much. You should try to minimize the redrawn areas in that situation.

Shape tweens can be really CPU intensive when used on paths with many control points. Still it is generally lighter than blending and transformation.

Texts and sophisticated vectors generally benefit greatly from bitmap caching.

Until recently (ie. prior to Flash CS3, IIRC) you were limited to basic easing in manual tweens, so that was a real show stopper. I still find it clearer to express them as easing functions.