问:
How do I dynamically create html table with angular from a multidimensional array?
I'm trying to dynamically create html table from Json that has an array within it. The problem I'm running into is when trying to create the s from the sub array. Below is an example of what I'm trying to accomplish.

Should I be using <ng-container *ngFor="let m of l.dArray"> ?

```<code> myArray = [   {
        "a": "01",
        "b": "01",
        "c": "03",
        "dArray": [
            {
                "d-1": 1,
                "d-2": 2,
                "d-3": "string1"
            },
            {
                "d-1": 2,
                "d-2": 1,
                "d-3": "string2"
            },
            {
                "d-1": 3,
                "d-2": 4,
                "d-3": "string3"
            }
        ]
    }
]
</code>```

Template:

```<code><table>
<thead>
    <tr><th>A</th></tr>
    <tr><th>B</th></tr>
    <tr><th>C</th></tr>
    <tr><th>D-1</th></tr>
    <tr><th>D-2</th></tr>
    <tr><th>D-3</th></tr>
</thead>
<tbody>
    <tr *ngFor="let l of myArray">
        <td>{{l.a}}</td>
        <td>{{l.b}}</td>
        <td>{{l.c}}</td>
        <ng-container *ngFor="let m of l.dArray">
            <td>
                <div *ngIf="m.d-1 === 1; else my1Else">
                            {{ m.d-3 }}%
                          </div>
                          <ng-template #my1Else>
                            N/A
                          </ng-template>
            </td>
            <td>
                <div *ngIf="m.d-1 === 2; else my2Else">
                            {{ m.d-3 }}%
                          </div>
                          <ng-template #my2Else>
                            N/A
                          </ng-template>
            </td>
            <td>
                <div *ngIf="m.d-1 === 1; else my3Else">
                            {{ m.d-3 }}%
                          </div>
                          <ng-template #my3Else>
                            N/A
                          </ng-template>
            </td>
        </ng-container>
    </tr>
</tbody>
</table>
</code>```

Expected outcome:

```<code>----------------------------
A  | B | C  | D-1         | D-2     | D-3
01 | 01| 03 | string1     | string2 | string3

actual outcome:
----------------------------
A  | B | C
</code>```

答:
A few things which i did:

the name of the array is dArray were 'd-1', 'd-2', 'd-3'... which had an operator as part of the name; i renamed these to d1, d2 & d3

you wanted to display only one value in column 'D-1', so we do an *ngIf='i==0' to ensure that we evaluate the first row of the dArray for this table column 'D-1'

we had to use a nested if and else so that only one valid value is printed, else we get a N/A

relevant HTML:

```<code><table>
    <thead>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
            <th>D-1</th>
            <th>D-2</th>
            <th>D-3</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let l of myArray">
            <td>{{l.a}}</td>
            <td>{{l.b}}</td>
            <td>{{l.c}}</td>
            <ng-container *ngFor="let m of l.dArray; let i=index">
                <td *ngIf='i===0'>
                    <div *ngIf="m.d1 === 1; else my1Else1">
                        {{ m.d3 }}%
                    </div>
                    <ng-template #my1Else1>
                        <div *ngIf="m.d1 === 2; else my2Else2">
                            {{ m.d3 }}%
                        </div>
                        <ng-template #my2Else2>
                            <div *ngIf="m.d1 === 3; else my3Else3">
                                {{ m.d3 }}%
                            </div>
                            <ng-template #my3Else3>
                                N/A
                            </ng-template>
                        </ng-template>
                    </ng-template>
                </td>

                <td *ngIf='i===1'>
                    <div *ngIf="m.d1 === 1; else my1Else1">
                        {{ m.d3 }}%
                    </div>
                    <ng-template #my1Else1>
                        <div *ngIf="m.d1 === 2; else my2Else2">
                            {{ m.d3 }}%
                        </div>
                        <ng-template #my2Else2>
                            <div *ngIf="m.d1 === 3; else my3Else3">
                                {{ m.d3 }}%
                            </div>
                            <ng-template #my3Else3>
                                N/A
                            </ng-template>
                        </ng-template>
                    </ng-template>
                </td>

                <td *ngIf='i===2'>
                    <div *ngIf="m.d1 === 1; else my1Else1">
                        {{ m.d3 }}%
                    </div>
                    <ng-template #my1Else1>
                        <div *ngIf="m.d1 === 2; else my2Else2">
                            {{ m.d3 }}%
                        </div>
                        <ng-template #my2Else2>
                            <div *ngIf="m.d1 === 3; else my3Else3">
                                {{ m.d3 }}%
                            </div>
                            <ng-template #my3Else3>
                                N/A
                            </ng-template>
                        </ng-template>
                    </ng-template>
                </td>

            </ng-container>
        </tr>
    </tbody>
</table>
</code>```

you can check working stackblitz here

Body:
I'm trying to dynamically create html table from Json that has an array within it. The problem I'm running into is when trying to create the s from the sub array. Below is an example of what I'm trying to accomplish.

Should I be using <ng-container *ngFor="let m of l.dArray"> ?

 myArray = [   {
        "a": "01",
        "b": "01",
        "c": "03",
        "dArray": [
            {
                "d-1": 1,
                "d-2": 2,
                "d-3": "string1"
            },
            {
                "d-1": 2,
                "d-2": 1,
                "d-3": "string2"
            },
            {
                "d-1": 3,
                "d-2": 4,
                "d-3": "string3"
            }
        ]
    }
]

Template:

A

B

C

D-1

D-2

D-3

        {{l.a}}
        {{l.b}}
        {{l.c}}
        <ng-container *ngFor="let m of l.dArray">

                            {{ m.d-3 }}%

                          <ng-template #my1Else>
                            N/A
                          </ng-template>

                            {{ m.d-3 }}%

                          <ng-template #my2Else>
                            N/A
                          </ng-template>

                            {{ m.d-3 }}%

                          <ng-template #my3Else>
                            N/A
                          </ng-template>

        </ng-container>

Expected outcome:

----------------------------
A  | B | C  | D-1         | D-2     | D-3
01 | 01| 03 | string1     | string2 | string3

actual outcome:
----------------------------
A  | B | C

Body:
A few things which i did:

the name of the array is dArray were 'd-1', 'd-2', 'd-3'... which had an operator as part of the name; i renamed these to d1, d2 & d3

you wanted to display only one value in column 'D-1', so we do an *ngIf='i==0' to ensure that we evaluate the first row of the dArray for this table column 'D-1'

we had to use a nested if and else so that only one valid value is printed, else we get a N/A

relevant HTML:

<table>
    <thead>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
            <th>D-1</th>
            <th>D-2</th>
            <th>D-3</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let l of myArray">
            <td>{{l.a}}</td>
            <td>{{l.b}}</td>
            <td>{{l.c}}</td>
            <ng-container *ngFor="let m of l.dArray; let i=index">
                <td *ngIf='i===0'>
                    <div *ngIf="m.d1 === 1; else my1Else1">
                        {{ m.d3 }}%
                    </div>
                    <ng-template #my1Else1>
                        <div *ngIf="m.d1 === 2; else my2Else2">
                            {{ m.d3 }}%
                        </div>
                        <ng-template #my2Else2>
                            <div *ngIf="m.d1 === 3; else my3Else3">
                                {{ m.d3 }}%
                            </div>
                            <ng-template #my3Else3>
                                N/A
                            </ng-template>
                        </ng-template>
                    </ng-template>
                </td>

                <td *ngIf='i===1'>
                    <div *ngIf="m.d1 === 1; else my1Else1">
                        {{ m.d3 }}%
                    </div>
                    <ng-template #my1Else1>
                        <div *ngIf="m.d1 === 2; else my2Else2">
                            {{ m.d3 }}%
                        </div>
                        <ng-template #my2Else2>
                            <div *ngIf="m.d1 === 3; else my3Else3">
                                {{ m.d3 }}%
                            </div>
                            <ng-template #my3Else3>
                                N/A
                            </ng-template>
                        </ng-template>
                    </ng-template>
                </td>

                <td *ngIf='i===2'>
                    <div *ngIf="m.d1 === 1; else my1Else1">
                        {{ m.d3 }}%
                    </div>
                    <ng-template #my1Else1>
                        <div *ngIf="m.d1 === 2; else my2Else2">
                            {{ m.d3 }}%
                        </div>
                        <ng-template #my2Else2>
                            <div *ngIf="m.d1 === 3; else my3Else3">
                                {{ m.d3 }}%
                            </div>
                            <ng-template #my3Else3>
                                N/A
                            </ng-template>
                        </ng-template>
                    </ng-template>
                </td>

            </ng-container>
        </tr>
    </tbody>
</table>

you can check working stackblitz here


来源: stackexchange

问:
How to get around the ' (quote) problem when saving text using SQL
I've a textbox that I save to a SQL Database using ASP.NET C#.

The problem is using quotes, for instance with words like he's and it's.  When you save it, I get an SQL error.

From experience to get around the issue, I use to use replace command to find all occurances of quotes and replace them with another character.  Then if I was to read the database and the text that was previously saved, I'd replace again.

Is there a better of doing this? Or do you still have to use this 'old' way.

答:
There's two ways to get around this issue:

Use a parameterised query, e.g. in http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx - this will also help avoid basic SQL injection if you're worried about that

Create 2 new functions, one to double up every apostrophe, so that it's saved into the database correctly, and another to remove extra apostrophes when retrieving data from the database.

I would recommend the first method as it's a lot cleaner (and safer) in my opinion.  If you're using C# for your ASP.NET you can do things like in my below example:

```<code>string clientName = "Test client";
SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Client WHERE UPPER(ClientName) = UPPER(@ClientName)", connection);
sqlCommand.Parameters.AddWithValue("@ClientName", clientName);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There's two ways to get around this issue:

Use a parameterised query, e.g. in http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx - this will also help avoid basic SQL injection if you're worried about that

Create 2 new functions, one to double up every apostrophe, so that it's saved into the database correctly, and another to remove extra apostrophes when retrieving data from the database.

I would recommend the first method as it's a lot cleaner (and safer) in my opinion.  If you're using C# for your ASP.NET you can do things like in my below example:

string clientName = "Test client";
SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Client WHERE UPPER(ClientName) = UPPER(@ClientName)", connection);
sqlCommand.Parameters.AddWithValue("@ClientName", clientName);


问:
Convert csv to parquet file using python
I am trying to convert a .csv file to a .parquet file.

The csv file (Temp.csv) has the following format

```<code>1,Jon,Doe,Denver
</code>```

I am using the following python code to convert it into parquet

```<code>from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
import os

if __name__ == "__main__":
    sc = SparkContext(appName="CSV2Parquet")
    sqlContext = SQLContext(sc)

    schema = StructType([
            StructField("col1", IntegerType(), True),
            StructField("col2", StringType(), True),
            StructField("col3", StringType(), True),
            StructField("col4", StringType(), True)])
    dirname = os.path.dirname(os.path.abspath(__file__))
    csvfilename = os.path.join(dirname,'Temp.csv')
    rdd = sc.textFile(csvfilename).map(lambda line: line.split(","))
    df = sqlContext.createDataFrame(rdd, schema)
    parquetfilename = os.path.join(dirname,'output.parquet')
    df.write.mode('overwrite').parquet(parquetfilename)
</code>```

The result is only a folder named, output.parquet and not a parquet file that I'm looking for, followed by the following error on the console.

I have also tried running the following code to face a similar issue.

```<code>from pyspark.sql import SparkSession
import os

spark = SparkSession \
    .builder \
    .appName("Protob Conversion to Parquet") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

# read csv
dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname,'Temp.csv')
df = spark.read.csv(csvfilename)

# Displays the content of the DataFrame to stdout
df.show()
parquetfilename = os.path.join(dirname,'output.parquet')
df.write.mode('overwrite').parquet(parquetfilename)
</code>```

How to best do it? Using windows, python 2.7.

答:
```<code>import boto3
import pandas as pd
import pyarrow as pa
from s3fs import S3FileSystem
import pyarrow.parquet as pq

s3 = boto3.client('s3',region_name='us-east-2')
obj = s3.get_object(Bucket='ssiworkoutput', Key='file_Folder/File_Name.csv')
df = pd.read_csv(obj['Body'])

table = pa.Table.from_pandas(df)

output_file = "s3://ssiworkoutput/file/output.parquet"  # S3 Path need to mention
s3 = S3FileSystem()

pq.write_to_dataset(table=table,
                    root_path=output_file,partition_cols=['Year','Month'],
                    filesystem=s3)

print("File converted from CSV to parquet completed")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to convert a .csv file to a .parquet file.

The csv file (Temp.csv) has the following format

1,Jon,Doe,Denver

I am using the following python code to convert it into parquet

from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
import os

if __name__ == "__main__":
    sc = SparkContext(appName="CSV2Parquet")
    sqlContext = SQLContext(sc)

    schema = StructType([
            StructField("col1", IntegerType(), True),
            StructField("col2", StringType(), True),
            StructField("col3", StringType(), True),
            StructField("col4", StringType(), True)])
    dirname = os.path.dirname(os.path.abspath(__file__))
    csvfilename = os.path.join(dirname,'Temp.csv')
    rdd = sc.textFile(csvfilename).map(lambda line: line.split(","))
    df = sqlContext.createDataFrame(rdd, schema)
    parquetfilename = os.path.join(dirname,'output.parquet')
    df.write.mode('overwrite').parquet(parquetfilename)

The result is only a folder named, output.parquet and not a parquet file that I'm looking for, followed by the following error on the console.

I have also tried running the following code to face a similar issue.

from pyspark.sql import SparkSession
import os

spark = SparkSession \
    .builder \
    .appName("Protob Conversion to Parquet") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

# read csv
dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname,'Temp.csv')
df = spark.read.csv(csvfilename)

# Displays the content of the DataFrame to stdout
df.show()
parquetfilename = os.path.join(dirname,'output.parquet')
df.write.mode('overwrite').parquet(parquetfilename)

How to best do it? Using windows, python 2.7.


问:
Nth-of-type works just like nth-child, I can't select what I want in a very simple markup
Please see this codepen or the following screenshot and code: https://codepen.io/rockmandash/pen/YbJQqG

My HTML

 I want to select this element(second line)

```

<p>CSS</p>

<pre class="lang-css prettyprint-override"><code>.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}
.line:nth-of-type(2) {  I chosed, but not working as expected
  width: 15px;
  height: 15px;
  background: black;
}

</code>```

Screenshot

Why my nth-of-type works just like nth-child?

答:
:nth-of-type matches the nth sibling of a given type (such as
).

Because the .line elements are
 elements, with .line:nth-of-type(2) you're essentially stating that you want to target the second sibling element which has the same type as .line:

```<code>div
    div
    div - target
    div
    div
</code>```

This turns out to be the first .line.

What you probably want is .line:nth-of-type(4), or, less confusingly, div:nth-of-type(4):

.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}

.line:nth-of-type(4) {
  width: 15px;
  height: 15px;
  background: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child"></div>
  <div class="line"></div>
  <div class="child"></div>
  <div class="line"></div> I want to select this element(second line)
  <div class="child"></div>
  <div class="line"></div>
</div></code>```

Note that there is no such thing as an :nth-of-class, so you will likely need to assign a unique class or ID to the element if you don't want to use such a complex selector.

Body:
Please see this codepen or the following screenshot and code: https://codepen.io/rockmandash/pen/YbJQqG

My HTML

 I want to select this element(second line)

CSS

.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}
.line:nth-of-type(2) {  I chosed, but not working as expected
  width: 15px;
  height: 15px;
  background: black;
}

Screenshot

Why my nth-of-type works just like nth-child?

Body:
:nth-of-type matches the nth sibling of a given type (such as <div>).

Because the .line elements are <div> elements, with .line:nth-of-type(2) you're essentially stating that you want to target the second sibling element which has the same type as .line:

div
    div
    div - target
    div
    div

This turns out to be the first .line.

What you probably want is .line:nth-of-type(4), or, less confusingly, div:nth-of-type(4):

.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}

.line:nth-of-type(4) {
  width: 15px;
  height: 15px;
  background: black;
}

<div class="container">
  <div class="child"></div>
  <div class="line"></div>
  <div class="child"></div>
  <div class="line"></div> I want to select this element(second line)
  <div class="child"></div>
  <div class="line"></div>
</div>

Note that there is no such thing as an :nth-of-class, so you will likely need to assign a unique class or ID to the element if you don't want to use such a complex selector.


问:
How to pass parameters in headers
I need to call an API from my Angular Node application.For that i have to pass username and password along with header request.How to pass parameters?
I tried below code

From Angular service,

```<code>checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
    .set('Authorization', 'my-auth-token')
    .set('Content-Type', 'application/json')
    .set('userName','prismtest')
    .set('password','12345678');
   return this.http.post('/upload/checkUserApi/', { headers })
  .map((response: Response) => {
    console.log(response);
   return response;
   })
}
</code>```

In Node,

```<code>router.post('/checkUserApi',function(req,res,next){
var proxyUrl = 'http://cors-anywhere.herokuapp.com/';

Request.post({
  "headers": { "userName": "prismtest","password":"12345678" },
  "url": proxyUrl+"https://example.com",
  "body": {}
  }, (error, response, body) => {

  if(error) {
   return console.log(error);
  }
   res.send(response);
  });
  });
</code>```

答:
Can you try below code following

/* SERVICE ANGULAR*/
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable,of} from 'rxjs';
import { map,catchError } from 'rxjs/operators';
import {User} from '../_models';

const httpOptions = {
    headers:new HttpHeaders({'Content-Type':'application/json'})
};

const API_URL = "http://localhost/app/api";
@Injectable({
    providedIn:'root',
})

export class UserService{
    constructor(private http:HttpClient){}

    /**
     * POST LOGIN USER
     */
    login(user: any) {
        return this.http.post<any>(API_URL+"/login", user,httpOptions)
            .pipe(map(user => {
                return user;
            }));
    }
}

/*NODEJS*/
/* 1) install $ npm install body-parser --save*/
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies */
/ POST http://localhost:8080/api/users
// parameters sent with
app.post('/api/login', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});```

Can you seen : Use ExpressJS to Get URL and POST Parameters

Login State Angular + Laravel

Title: How to pass parameters in headers

Body:
I need to call an API from my Angular Node application.For that i have to pass username and password along with header request.How to pass parameters?
I tried below code

From Angular service,

checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
    .set('Authorization', 'my-auth-token')
    .set('Content-Type', 'application/json')
    .set('userName','prismtest')
    .set('password','12345678');
   return this.http.post('/upload/checkUserApi/', { headers })
  .map((response: Response) => {
    console.log(response);
   return response;
   })
}

In Node,

router.post('/checkUserApi',function(req,res,next){
var proxyUrl = 'http://cors-anywhere.herokuapp.com/';

Request.post({
  "headers": { "userName": "prismtest","password":"12345678" },
  "url": proxyUrl+"https://example.com",
  "body": {}
  }, (error, response, body) => {

  if(error) {
   return console.log(error);
  }
   res.send(response);
  });
  });

Body:
Can you try below code following

/* SERVICE ANGULAR*/
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable,of} from 'rxjs';
import { map,catchError } from 'rxjs/operators';
import {User} from '../_models';

const httpOptions = {
    headers:new HttpHeaders({'Content-Type':'application/json'})
};

const API_URL = "http://localhost/app/api";
@Injectable({
    providedIn:'root',
})

export class UserService{
    constructor(private http:HttpClient){}

    /**
     * POST LOGIN USER
     */
    login(user: any) {
        return this.http.post<any>(API_URL+"/login", user,httpOptions)
            .pipe(map(user => {
                return user;
            }));
    }
}

/*NODEJS*/
/* 1) install $ npm install body-parser --save*/
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies */
/ POST http://localhost:8080/api/users
// parameters sent with
app.post('/api/login', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});

Can you seen : Use ExpressJS to Get URL and POST Parameters

Login State Angular + Laravel


问:
Vertically align html-entity characters in monospace font?
Sometimes, I need to type text where the character-columns are aligned vertically, and the simplest way of course is to use font-family "monospace", "Courier", etc.

What I noticed, though, is that many of the html entity-code characters (emojis, etc) do not always comply with this fixed font-width,
but will still be wider than normal characters and "push" subsequent characters on the same line to the right, despite using monospace.

Examples of such are:

♡ = ♡ --- slightly too wide in monospace.

♛ = ♛ --- much too wide in monospace.

♥ = ♥ --- this follows monospace width on my windows laptop, but much too wide when viewing with android/chrome.

Is there any fix/workaround available to prevent this anomalous behaviour?

I'm thinking, if there is a way to "compress" the width of such characters, to ensure they all align with the fixed character-width, and preferably that works uniformly across different devices?

Or other feasible solution?

答:
[Edit]
I edited my answer to make it possible to equally space letters without having to add a span tag or use a class on each paragraph per my previous answer. Now, just type the paragraphs and the letters will align.

This will align letters of any font in columns, however I used monospaced since this is what you are interested in using.

Note, I added a border in the example to show alignment, just remove this style.

Run code snippet to see.

window.onload = function() {
    numRows = document.getElementById("spacingcontainer").children;
    for (i=0; i<numRows.length; i++) {
        temp = "";
        for (j=0; j<numRows[i].innerHTML.length; j++) {
            letter = numRows[i].innerHTML[j];
            temp += "" + letter + "";
        }
        numRows[i].innerHTML = temp;
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code> #spacingcontainer {
     display:table;
     font:18px monospace;
 }
 #spacingcontainer p {
     display:table-row;
 }
 #spacingcontainer p span {
     display:table-cell;
     width:12px;
     text-align:center;
     border:1px solid silver; /* remove border */
 }</code>```

Align letters in columns.

♡a♛♥ ®q f® h€j♡i¥ ♥£¢♜♢♡♥

This is monospaced font

```

Body:
[Edit]
I edited my answer to make it possible to equally space letters without having to add a span tag or use a class on each paragraph per my previous answer. Now, just type the paragraphs and the letters will align.

This will align letters of any font in columns, however I used monospaced since this is what you are interested in using.

Note, I added a border in the example to show alignment, just remove this style.

Run code snippet to see.

window.onload = function() {
    numRows = document.getElementById("spacingcontainer").children;
    for (i=0; i<numRows.length; i++) {
        temp = "";
        for (j=0; j<numRows[i].innerHTML.length; j++) {
            letter = numRows[i].innerHTML[j];
            temp += "<span>" + letter + "</span>";
        }
        numRows[i].innerHTML = temp;
    }
}

 #spacingcontainer {
     display:table;
     font:18px monospace;
 }
 #spacingcontainer p {
     display:table-row;
 }
 #spacingcontainer p span {
     display:table-cell;
     width:12px;
     text-align:center;
     border:1px solid silver; /* remove border */
 }

<div id="spacingcontainer">
<p>Align letters in columns.</p>
<p>&#9825;a&#9819;&hearts; &#174;q f&#174; h&#8364;j&#9825;i&#165; &hearts;&#163;&#162;&#9820;&#9826;&#9825;&hearts;</p>
<p>This is monospaced font</p>
</div>


问:
How to mock http request in flutter integration test?
I'm trying to do so using Mockito, this is my test:

import 'package:http/http.dart' as http;
import 'package:utgard/globals.dart' as globals;
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';

class MockClient extends Mock implements http.Client {}

void main() {
  group('Login flow', () {

    final SerializableFinder loginContinuePasswordButton =
        find.byValueKey('login_continue_password_button');

    FlutterDriver driver;

    setUpAll(() async {
      driver = await FlutterDriver.connect();
    });

    tearDownAll(() async {
      if (driver != null) {
        //await driver.close();
      }
    });

    test('login with correct password', () async {
      final client = MockClient();

      when(client.post('http://wwww.google.com'))
          .thenAnswer((_) async => http.Response('{"title": "Test"}', 200));

      globals.httpClient = client;

      await driver.enterText('000000');
      await driver.tap(loginContinuePasswordButton);
    });
  });
}
```

<p>And this is my http request code:</p>

<pre class="lang-dart prettyprint-override"><code>Future<Map<String, dynamic>> post({
  RequestType requestType,
  Map<String, dynamic> body,
}) async {
  final http.Response response =
      await globals.httpClient.post('http://wwww.google.com');

  print(response);

  final Map<String, dynamic> finalResponse = buildResponse(response);

  _managerErrors(finalResponse);

  return finalResponse;
}
</code>```

And here I have the global:

library utgard.globals;

import 'package:http/http.dart' as http;

http.Client httpClient = http.Client();
```

However I continue to receive http errors, that indicates to me that the http wasn't replaced by the mock.

答:
The solution I found was to define the mock in test_driver/app.dart and call the runApp function after that:

import 'package:flutter/widgets.dart';
import 'package:flutter_driver/driver_extension.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:utgard/business/config/globals.dart';
import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  enableFlutterDriverExtension();

  final MockClient client = MockClient();
  // make your mocks here
  httpClient = client;

  runApp(app.MyApp());
}
```

Body:
I'm trying to do so using Mockito, this is my test:

import 'package:http/http.dart' as http;
import 'package:utgard/globals.dart' as globals;
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';

class MockClient extends Mock implements http.Client {}

void main() {
  group('Login flow', () {

    final SerializableFinder loginContinuePasswordButton =
        find.byValueKey('login_continue_password_button');

    FlutterDriver driver;

    setUpAll(() async {
      driver = await FlutterDriver.connect();
    });

    tearDownAll(() async {
      if (driver != null) {
        //await driver.close();
      }
    });

    test('login with correct password', () async {
      final client = MockClient();

      when(client.post('http://wwww.google.com'))
          .thenAnswer((_) async => http.Response('{"title": "Test"}', 200));

      globals.httpClient = client;

      await driver.enterText('000000');
      await driver.tap(loginContinuePasswordButton);
    });
  });
}

And this is my http request code:

Future<Map<String, dynamic>> post({
  RequestType requestType,
  Map<String, dynamic> body,
}) async {
  final http.Response response =
      await globals.httpClient.post('http://wwww.google.com');

  print(response);

  final Map<String, dynamic> finalResponse = buildResponse(response);

  _managerErrors(finalResponse);

  return finalResponse;
}

And here I have the global:

library utgard.globals;

import 'package:http/http.dart' as http;

http.Client httpClient = http.Client();

However I continue to receive http errors, that indicates to me that the http wasn't replaced by the mock.


问:
WARNING in ./node_modules/ng2-charts/fesm5/ng2-charts.js 230:54-72 "export 'ɵɵdefineInjectable' was not found in '@angular/core'
I am using ng2-charts in Angular 7 app and having warning

WARNING in ./node_modules/ng2-charts/fesm5/ng2-charts.js 230:54-72
  "export 'ɵɵdefineInjectable' was not found in '@angular/core'

error in VS Code

error in browser

What could be the reason and how to resolve it?

答:
Update: May 2021

Recently I have used ng2-charts@2.4.2 in Angular v11 and it's working fine. You may try with the latest version

```<code>npm install ng2-charts@latest // it will automatically install latest version
</code>```

Older

ng2-charts v2.2.4 has this bug as lots of users are reporting that so down-grading to ng2-charts v2.2.3 is fine until it is fixed in the future releases.

```<code>npm install ng2-charts@2.2.3
</code>```

Body:
Update: May 2021

Recently I have used ng2-charts@2.4.2 in Angular v11 and it's working fine. You may try with the latest version

npm install ng2-charts@latest // it will automatically install latest version

Older

ng2-charts v2.2.4 has this bug as lots of users are reporting that so down-grading to ng2-charts v2.2.3 is fine until it is fixed in the future releases.

npm install ng2-charts@2.2.3


问:
How to dynamically auto populate a input field uisng Nodejs and MySQL?
I have a field in my website where I want users to enter book names that they can checkout from the database. I want it so that when they start typing the names I want suggestions or drop down under the input box matching the name of the book they are typing.

Is it possible to achieve something like this? I have a books table in my MySQL database and I am using Nodejs as my backend. I have searched a lot online but did not find anything related to this online. Therefore, I decided to ask the question here.

答:
The UI element is commonly called a "typeahead" or autocomplete.

Twitter release their frontend component as a jQuery plugin called typeahead.js. Most frontend frameworks will have an equivalent plugin or component.

The backend datasource for the books is up to you to implement.

For small datasets you can render the required book data within the page so it is directly accessible from your javascript.

For large datasets you will probably need to create a backend "book search" service in Nodejs. Typeahead libraries can send that user input to a URL via an AJAX request and the service returns the matching results, usually as a JSON object.

Code for geek example for your stack.


问:
Combinatorics problem, room configurations
Say I have a bunch of hotel rooms, suitable for 1,2 or 3 persons.

A group of 4 persons would like to book and I want to present them with all the possible configurations, since different configurations have different prices.

Possible combinations include:

4 * 1 person room

2 * 2 person room

1 * 3 person room + 1 * 1 person room

etcetera, etcetera

How would I go about calculating the different groupings?

An added complexity is that some of these persons may be children, which should always be combined with adults in a room. I figured I should just calculate all combinations and filter out the ones who don't satisfy this constraint.

Any hints, tips or pointers?

答:
The way the problem is phrased suggests that the number of room types is small, and so is the largest required group size.

With this in mind, I'd use depth-first search with memoization. In Python:

```<code>@memoized
def search(n, room_types):
  ret = set()
  for t in room_types:
    if t >= n:
      ret.add((t,))
    else:
      for cfg in search(n - t, room_types):
        if sum(cfg) >= n:
          ret.add(cfg)
        else:
          ret.add(tuple(sorted(list(cfg) + [t])))
  return ret

print sorted(search(4, (1, 2, 3)))
</code>```

This produces:

```<code>[(1, 1, 1, 1), (1, 1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
</code>```

@memoized comes from here.

Body:
The way the problem is phrased suggests that the number of room types is small, and so is the largest required group size.

With this in mind, I'd use depth-first search with memoization. In Python:

@memoized
def search(n, room_types):
  ret = set()
  for t in room_types:
    if t >= n:
      ret.add((t,))
    else:
      for cfg in search(n - t, room_types):
        if sum(cfg) >= n:
          ret.add(cfg)
        else:
          ret.add(tuple(sorted(list(cfg) + [t])))
  return ret

print sorted(search(4, (1, 2, 3)))

This produces:

[(1, 1, 1, 1), (1, 1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]

@memoized comes from here.


问:
How to put two pictures on the same level in a word file (.docx) python
I want to put the logo and the barcode on the same level and not one on top of the other.The logo should stay at the very left and the barcode at the very right of the word file.Here is my code , thank you:<img src="https://i.stack.imgur.com/8FBc3.png" alt="enter image description here"> </p>

```<code>import uuid
import pandas as pd
import pyqrcode
from docx import Document
from docx.shared import Inches

qr=pyqrcode.create(str(uuid.uuid4()).replace('-',''))
qr.png('somecode.png')

df=pd.DataFrame(pd.read_excel('Komplette-
GastAccountFHZugangsdatenFertig.xlsx'))

Attributes=['Name', 'Vorname ', 'Geschlecht', 'Adresse (in Marokko)',
       'Telefonnummer', 'E-Mailadresse', 'Studiengang', 'Semester']

document = Document()

document.add_heading('Informationen.',level=0)

document.add_picture('Informatik_Logo.png',height=Inches(1.0))

p = document.add_paragraph()
r = p.add_run()

p_format=p.paragraph_format

p_format.left_indent=Inches(4.5)
r.add_picture('somecode.png',width=Inches(1.0))

table=document.add_table(len(Attributes),2,style='LightGrid-Accent1')

for i in range(len(Attributes)):
        row=table.rows[i]
        row.cells[0].text=Attributes[i]
        Infos=df[Attributes[i]]
        string=str(Infos[49])
        row.cells[1].text=string

document.save('sample.docx')
</code>```

答:
i can help you with that,just add one sentence into your code

```<code>r.add_picture('somecode.png',width=Inches(2.0))
</code>```

that is all. just write the sentence one more time.and if you want more picture in the same level, all you need to do is that add the sentence. i tried and it works to me.

there is my test code

```<code>dc = Document()

run = dc.add_paragraph().add_run()
run.add_picture("./picture/danilise.jpg", width=Inches(1.1))
run.add_picture("./picture/danilise.jpg", width=Inches(1.3))
run.add_picture("./picture/danilise.jpg", width=Inches(1.5))

dc.save("test1.docx")
</code>```

Body:
I want to put the logo and the barcode on the same level and not one on top of the other.The logo should stay at the very left and the barcode at the very right of the word file.Here is my code , thank you:

import uuid
import pandas as pd
import pyqrcode
from docx import Document
from docx.shared import Inches

qr=pyqrcode.create(str(uuid.uuid4()).replace('-',''))
qr.png('somecode.png')

df=pd.DataFrame(pd.read_excel('Komplette-
GastAccountFHZugangsdatenFertig.xlsx'))

Attributes=['Name', 'Vorname ', 'Geschlecht', 'Adresse (in Marokko)',
       'Telefonnummer', 'E-Mailadresse', 'Studiengang', 'Semester']

document = Document()

document.add_heading('Informationen.',level=0)

document.add_picture('Informatik_Logo.png',height=Inches(1.0))

p = document.add_paragraph()
r = p.add_run()

p_format=p.paragraph_format

p_format.left_indent=Inches(4.5)
r.add_picture('somecode.png',width=Inches(1.0))

table=document.add_table(len(Attributes),2,style='LightGrid-Accent1')

for i in range(len(Attributes)):
        row=table.rows[i]
        row.cells[0].text=Attributes[i]
        Infos=df[Attributes[i]]
        string=str(Infos[49])
        row.cells[1].text=string

document.save('sample.docx')

Body:
i can help you with that,just add one sentence into your code

r.add_picture('somecode.png',width=Inches(2.0))

that is all. just write the sentence one more time.and if you want more picture in the same level, all you need to do is that add the sentence. i tried and it works to me.

there is my test code

dc = Document()

run = dc.add_paragraph().add_run()
run.add_picture("./picture/danilise.jpg", width=Inches(1.1))
run.add_picture("./picture/danilise.jpg", width=Inches(1.3))
run.add_picture("./picture/danilise.jpg", width=Inches(1.5))

dc.save("test1.docx")


问:
Extracting JSON arrays and inserting them as separate rows in a new database
I have a database which uses JSON to store values.

```<code>CREATE TABLE JSON(name TEXT, value TEXT);
</code>```

I am trying to convert this into a native format.

```<code>CREATE TABLE NATIVE(name TEXT, KEY1, KEY2, KEY3);
</code>```

The JSON format looks like this:

```<code>[
    {"key1":value1, "key2":value2, "key3":value3},
    {"key1":value4, "key2":value5, "key3":value6},
    ....
]
</code>```

For the above example, I am trying to come up with a query using INSERT INTO NATIVE (name, KEY1, KEY2, KEY3) SELECT <something> FROM JSON to produce this table:

```<code>+------+---------+--------+--------+
| TEXT | KEY1    | KEY2   | KEY3   |
+------+---------+--------+--------+
| TEXT | VALUE1  | VALUE2 | VALUE3 |
| TEXT | VALUE4  | VALUE5 | VALUE3 |
...
+------+---------+--------+--------+
</code>```

I have been using JSON1 for other tables which use simple objects.  So for instance when I have values which are objects and not arrays of objects I can use json_extract for each field.

For an array I think I am supposed to use json_each but I am having a hard time figuring out how to apply it to this specific problem.

答:
I came up with this solution:

```<code>INSERT INTO NATIVE (name, key1, key2, key3)
SELECT name, json_extract(x.value, '$.key1')
           , json_extract(x.value, '$.key2')
           , json_extract(x.value, '$.key3')
FROM JSON, json_each(JSON.value) AS x;
</code>```

The trick is that json_each when used in conjunction with the table containing JSON and a SELECT is returning rows in which there are fields called key and value which contain each key and value.  It is then possible to call json_extract in the select to pick individual fields out, which can then be inserted into the new table.

Body:
I have a database which uses JSON to store values.

CREATE TABLE JSON(name TEXT, value TEXT);

I am trying to convert this into a native format.

CREATE TABLE NATIVE(name TEXT, KEY1, KEY2, KEY3);

The JSON format looks like this:

[
    {"key1":value1, "key2":value2, "key3":value3},
    {"key1":value4, "key2":value5, "key3":value6},
    ....
]

For the above example, I am trying to come up with a query using INSERT INTO NATIVE (name, KEY1, KEY2, KEY3) SELECT <something> FROM JSON to produce this table:

+------+---------+--------+--------+
| TEXT | KEY1    | KEY2   | KEY3   |
+------+---------+--------+--------+
| TEXT | VALUE1  | VALUE2 | VALUE3 |
| TEXT | VALUE4  | VALUE5 | VALUE3 |
...
+------+---------+--------+--------+

I have been using JSON1 for other tables which use simple objects.  So for instance when I have values which are objects and not arrays of objects I can use json_extract for each field.

For an array I think I am supposed to use json_each but I am having a hard time figuring out how to apply it to this specific problem.

Body:
I came up with this solution:

INSERT INTO NATIVE (name, key1, key2, key3)
SELECT name, json_extract(x.value, '$.key1')
           , json_extract(x.value, '$.key2')
           , json_extract(x.value, '$.key3')
FROM JSON, json_each(JSON.value) AS x;

The trick is that json_each when used in conjunction with the table containing JSON and a SELECT is returning rows in which there are fields called key and value which contain each key and value.  It is then possible to call json_extract in the select to pick individual fields out, which can then be inserted into the new table.


问:
Null Pointer exception when I run the selenium test using Junit
I have to click Dresses button on the web page (http://automationpractice.com/index.php), I can open the url and my next step is to click the Dress button, but I am getting following error when I run the selenium test via junit:

```<code>java.lang.NullPointerException
    at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:787)
    at org.openqa.selenium.interactions.PointerInput$Origin.fromElement(PointerInput.java:221)
    at org.openqa.selenium.interactions.Actions.moveInTicks(Actions.java:418)
    at org.openqa.selenium.interactions.Actions.click(Actions.java:324)
    at com.avantica.pageObject.HomePage.clickDresses(HomePage.java:29)
    at Runner.RunnerWebTest.homePageTest(RunnerWebTest.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:305)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:365)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:330)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:78)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:328)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:65)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:292)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:305)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:412)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

</code>```

My Junit Class is like below:

```<code>public class RunnerWebTest extends DriverFactory {

    HomePage hp;

    @Test
    public void homePageTest() throws Exception {
        hp = new HomePage(getDriver());
        hp.getUrl();
        hp.clickDresses();
    }

}
</code>```

Home page class looks like:

```<code>public class HomePage extends BasePage {

    ReadConfigFile config = new ReadConfigFile();

    public @FindBy(xpath = "(//a[contains(@class,'sf-with-ul')])[4]") WebElement dresses;

    public HomePage(WebDriver driver) throws IOException {
        super();
    }

    public HomePage getUrl() throws IOException {
        getDriver().get(config.getURL());
        return new HomePage(driver);
    }

    public HomePage clickDresses() throws Exception {
        System.out.println("Dresses button to click");
        System.out.println("driver=" + driver);
        Actions act = new Actions(driver);
        act.click(dresses).perform();
        return new HomePage(driver);
    }

}
</code>```

答:
I was able to fix this error by changing:

```<code>  public HomePage(WebDriver driver) throws IOException {
        super();
    }
</code>```

to

```<code>  public HomePage(WebDriver driver) throws IOException {
        this.driver = driver;
    }
</code>```

Body:
I have to click Dresses button on the web page (http://automationpractice.com/index.php), I can open the url and my next step is to click the Dress button, but I am getting following error when I run the selenium test via junit:

java.lang.NullPointerException
    at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:787)
    at org.openqa.selenium.interactions.PointerInput$Origin.fromElement(PointerInput.java:221)
    at org.openqa.selenium.interactions.Actions.moveInTicks(Actions.java:418)
    at org.openqa.selenium.interactions.Actions.click(Actions.java:324)
    at com.avantica.pageObject.HomePage.clickDresses(HomePage.java:29)
    at Runner.RunnerWebTest.homePageTest(RunnerWebTest.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:305)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:365)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:330)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:78)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:328)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:65)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:292)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:305)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:412)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

My Junit Class is like below:

public class RunnerWebTest extends DriverFactory {

    HomePage hp;

    @Test
    public void homePageTest() throws Exception {
        hp = new HomePage(getDriver());
        hp.getUrl();
        hp.clickDresses();
    }

}

Home page class looks like:

public class HomePage extends BasePage {

    ReadConfigFile config = new ReadConfigFile();

    public @FindBy(xpath = "(//a[contains(@class,'sf-with-ul')])[4]") WebElement dresses;

    public HomePage(WebDriver driver) throws IOException {
        super();
    }

    public HomePage getUrl() throws IOException {
        getDriver().get(config.getURL());
        return new HomePage(driver);
    }

    public HomePage clickDresses() throws Exception {
        System.out.println("Dresses button to click");
        System.out.println("driver=" + driver);
        Actions act = new Actions(driver);
        act.click(dresses).perform();
        return new HomePage(driver);
    }

}

Body:
I was able to fix this error by changing:

  public HomePage(WebDriver driver) throws IOException {
        super();
    }

to

  public HomePage(WebDriver driver) throws IOException {
        this.driver = driver;
    }


问:
Is it possible to restrict the user to take snapshot of screen in C#
I have an application developed in C#. I need a mechanism to restrict the user to take screen shot when the application window on top.
Is it possible to restrict the user to take screenshot??

I have already listen the PrtScr Button to restrict the built in mechanism of windows to take screenshot.

But if user uses some capturing application to capture the skin.. I think there might be some windows event or such like thing, which is triggered when a a screenshot is taken. I need to know about it. Any help will be appreciated...

答:
In windows form application, Use this code in form keyup event,

```<code>if (e.KeyCode == Keys.PrintScreen)
            {
                Clipboard.Clear();
            }
</code>```

form keypreview should be true.

Body:
In windows form application, Use this code in form keyup event,

if (e.KeyCode == Keys.PrintScreen)
            {
                Clipboard.Clear();
            }

form keypreview should be true.


问:
*ngfor not display any data in Angular7
I 'm using angular7 , and here is my code :
in component.ts

import { Component, OnInit } from "@angular/core";
import { FocusAreasService } from "../../services/focus-areas.service";

@Component({
  selector: "app-about",
  templateUrl: "./about.component.html",
  styleUrls: ["./about.component.scss"]
})
export class AboutComponent implements OnInit {
  public canonical: string;
  public RsFocusArea: any[];
  constructor(public focusareaService: FocusAreasService) {}

  ngOnInit() {
    this.canonical = document.location.origin;

    this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe({
      next(response) {
        console.log("HttpClient handle data");
        console.dir(response);

        this.RsFocusArea = response["focusArea"];
       //I print this.RsFocusArea here , it has values
        console.log("this.RsFocusArea");
        console.dir(this.RsFocusArea);
      },
      error(err) {
        console.error("Error: " + err);
      },
      complete() {
        console.log("Completed");
      }
    });
  }
}

}
```

<p>and in .html</p>

<pre class="lang-html prettyprint-override"><code> <ul class="col-xs-12 row">
        <li *ngFor="let area of RsFocusArea" class="col-xs-12 col-sm-6 col-md-4">{{area}}
        </li>
      </ul>
</code>```

and the li tage did not repeat and gave me this in tag structure:

```

Is there anything wrong with my code? I thought maybe I need to rerender the page when I assign new value to RsFocusArea in ngOnInit?

答:
The problem is in the subscription

The thing is that you never set the variable you actually want, the this.RsFocusArea from your component never gets a value, the this.RsFocusArea variable you call in your subscription is in the scope of the next(response){} function.

Using next(response){...} in your subscribe() will cause the this keyword to reference the next(response){} function, meaning this.RsFocusArea doesn't refer to your component's variable anymore, but it's looking for an undefined variable instead.

(Explained here: Angular2 subscribe understand arrow function)

In short: The this keyword can be tricky inside other functions

To fix it:

Try writing your subscribe with arrow functions instead:

```<code>this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe(
  response => {
    console.log("HttpClient handle data");
    console.dir(response);

    this.RsFocusArea = response["focusArea"];
    //I print this.RsFocusArea here , it has values
    console.log("this.RsFocusArea");
    console.dir(this.RsFocusArea);
  },
  err => {
    console.error("Error: " + err);
  },
  () => {
    console.log("Completed");
  }
});
</code>```

If you really want to use the next() notation you can have a look at how to bind the function.

Hope it helps

Title: *ngfor not display any data in Angular7

Body:
I 'm using angular7 , and here is my code :
in component.ts

import { Component, OnInit } from "@angular/core";
import { FocusAreasService } from "../../services/focus-areas.service";

@Component({
  selector: "app-about",
  templateUrl: "./about.component.html",
  styleUrls: ["./about.component.scss"]
})
export class AboutComponent implements OnInit {
  public canonical: string;
  public RsFocusArea: any[];
  constructor(public focusareaService: FocusAreasService) {}

  ngOnInit() {
    this.canonical = document.location.origin;

    this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe({
      next(response) {
        console.log("HttpClient handle data");
        console.dir(response);

        this.RsFocusArea = response["focusArea"];
       //I print this.RsFocusArea here , it has values
        console.log("this.RsFocusArea");
        console.dir(this.RsFocusArea);
      },
      error(err) {
        console.error("Error: " + err);
      },
      complete() {
        console.log("Completed");
      }
    });
  }
}

}

and in .html

{{area}}

and the li tage did not repeat and gave me this in tag structure:

Is there anything wrong with my code? I thought maybe I need to rerender the page when I assign new value to RsFocusArea in ngOnInit?

Body:
The problem is in the subscription

The thing is that you never set the variable you actually want, the this.RsFocusArea from your component never gets a value, the this.RsFocusArea variable you call in your subscription is in the scope of the next(response){} function.

Using next(response){...} in your subscribe() will cause the this keyword to reference the next(response){} function, meaning this.RsFocusArea doesn't refer to your component's variable anymore, but it's looking for an undefined variable instead.

(Explained here: Angular2 subscribe understand arrow function)

In short: The this keyword can be tricky inside other functions

To fix it:

Try writing your subscribe with arrow functions instead:

this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe(
  response => {
    console.log("HttpClient handle data");
    console.dir(response);

    this.RsFocusArea = response["focusArea"];
    //I print this.RsFocusArea here , it has values
    console.log("this.RsFocusArea");
    console.dir(this.RsFocusArea);
  },
  err => {
    console.error("Error: " + err);
  },
  () => {
    console.log("Completed");
  }
});

If you really want to use the next() notation you can have a look at how to bind the function.

Hope it helps


问:
MPLABX Project stopped compiling when I changed of computer
I'm writing firmware for a PIC18F4550 using the MPLABX and the XC8 compiler. The project was compiling with some warnings, but I was able to compile and use the hexa file to simulate. So I decided to advance the work at home. I zipped the folder where the MPLABX project was and sent it by email. When I got home, I downloaded it. I installed the MPLABX and the XC8 compiler. The version is the same one I originally used, the most recent until now, 2.05.I opened the project without making any changes, I compiled it, however, it did not compile. Errors were found, the first listing was:

error: unknown type name 'far'

This error did not occur before. What could have happened? Does anyone have any ideas ?

答:
I already have the answer. It was given by another person to me in the Microchip forum. This is the link :

https://www.microchip.com/forums/m/tm.aspx?m=1099735

I have noticed that when I unzip a previously packaged project and
  open it (even on the same computer, but in a different directory)
  MPLABX tends not to pay attention to the compiler version and settings
  as they appear in the project's nbproject/configurations.xml file, but
  uses defaults instead.   The default for XC8 version 2.05 is C99 mode,
  and I suspect that if you go to the Project->Properties->->Global
  Options window you will see the C Standard is set to C99

My suggestion: Set it to C90 and see what happens.

Regads,

Dave


问:
not a valid l-value - verilog compiler error
```<code>module fronter ( arc, length, clinic ) ;
 input [7:0] arc;
 output reg [7:0] length ;

 input [1:0] clinic;
 input en0, en1, en2, en3; // 11

 // clock generator  is here

 g_cal A( en0) ;
 g_cal B( en1) ;
 g_cal C( en2) ;
 g_cal D( en3) ;

always @( negedge arc, posedge clk )
  case ( clinic )
    2'b00 : { en3, en2, en1, en0 } = 4'b0001;    // 23
    2'b01 : { en3, en2, en1, en0 } = 4'b0010;    // 24
    2'b10 : { en3, en2, en1, en0 } = 4'b0100;    // 25
    2'b11 : { en3, en2, en1, en0 } = 4'b1000;    // 26
    default : { en3, en2, en1, en0 } = 4'bxxxx;  // 27
  endcase

// I am trying to change value of en to call corresponding intance with that
//corresponding en value

endmodule

module g_cal ( en ) ;

 input en ;
 // some other jobs, calling another instances after making some job

endmodule
</code>```

when I compile, compiler gives me ;

```<code>verilog.v:23: error: en0 is not a valid l-value in Numerator.
verilog.v:11:      : en0 is declared here as wire.
verilog.v:24: error: en1 is not a valid l-value in Numerator.
verilog.v:11:      : en1 is declared here as wire.
verilog.v:25: error: en2 is not a valid l-value in Numerator.
verilog.v:11:      : en2 is declared here as wire.
verilog.v:26: error: en3 is not a valid l-value in Numerator.
verilog.v:11:      : en3 is declared here as wire.
verilog.v:27: error: en3 is not a valid l-value in Numerator.
verilog.v:11:      : en3 is declared here as wire.
segmentation fault
</code>```

How can I fix it ?
Why it gives error?

EDIT:
    I have solved problem as ;

```<code>   // I erased that line "input en0, en1, en2, en3; // 11"

 // clock generator  is here

 g_cal A(  1'b0) ;
 g_cal B(  1'b0) ;
 g_cal C(  1'b0) ;
 g_cal D(  1'b0) ;

always @( negedge arc, posedge clk )
/* erasing all those line
 case ( clinic )
    2'b00 : { en3, en2, en1, en0 } = 4'b0001;    // 23
    2'b01 : { en3, en2, en1, en0 } = 4'b0010;    // 24
    2'b10 : { en3, en2, en1, en0 } = 4'b0100;    // 25
    2'b11 : { en3, en2, en1, en0 } = 4'b1000;    // 26
    default : { en3, en2, en1, en0 } = 4'bxxxx;  // 27
  endcase
</code>```

I will use if and else structure, and calling corresponding instance with 1'b1*/

```<code> // I am trying to change value of en to call corresponding intance with that
//corresponding en value

endmodule
</code>```

答:
Problem has solved when I write ;

```<code>reg en0, en1, en2, en3 ;

initial begin
  en0 <= 1'b0; en1 <= 1'b0;
  en2 <= 1'b0; en3 <= 1'b0;
end

g_cal A(  en0) ;
g_cal B(  en1) ;
g_cal C(  en2) ;
g_cal D(  en3) ;
</code>```

@Marty have emphasized important thing "The reg is necessary since you are assigning to that variable within a procedural block (ie, an always or initial)."

Body:
module fronter ( arc, length, clinic ) ;
 input [7:0] arc;
 output reg [7:0] length ;

 input [1:0] clinic;
 input en0, en1, en2, en3; // 11

 // clock generator  is here

 g_cal A( en0) ;
 g_cal B( en1) ;
 g_cal C( en2) ;
 g_cal D( en3) ;

always @( negedge arc, posedge clk )
  case ( clinic )
    2'b00 : { en3, en2, en1, en0 } = 4'b0001;    // 23
    2'b01 : { en3, en2, en1, en0 } = 4'b0010;    // 24
    2'b10 : { en3, en2, en1, en0 } = 4'b0100;    // 25
    2'b11 : { en3, en2, en1, en0 } = 4'b1000;    // 26
    default : { en3, en2, en1, en0 } = 4'bxxxx;  // 27
  endcase

// I am trying to change value of en to call corresponding intance with that
//corresponding en value

endmodule

module g_cal ( en ) ;

 input en ;
 // some other jobs, calling another instances after making some job

endmodule

when I compile, compiler gives me ;

verilog.v:23: error: en0 is not a valid l-value in Numerator.
verilog.v:11:      : en0 is declared here as wire.
verilog.v:24: error: en1 is not a valid l-value in Numerator.
verilog.v:11:      : en1 is declared here as wire.
verilog.v:25: error: en2 is not a valid l-value in Numerator.
verilog.v:11:      : en2 is declared here as wire.
verilog.v:26: error: en3 is not a valid l-value in Numerator.
verilog.v:11:      : en3 is declared here as wire.
verilog.v:27: error: en3 is not a valid l-value in Numerator.
verilog.v:11:      : en3 is declared here as wire.
segmentation fault

How can I fix it ?
Why it gives error?

EDIT:
    I have solved problem as ;

   // I erased that line "input en0, en1, en2, en3; // 11"

 // clock generator  is here

 g_cal A(  1'b0) ;
 g_cal B(  1'b0) ;
 g_cal C(  1'b0) ;
 g_cal D(  1'b0) ;

always @( negedge arc, posedge clk )
/* erasing all those line
 case ( clinic )
    2'b00 : { en3, en2, en1, en0 } = 4'b0001;    // 23
    2'b01 : { en3, en2, en1, en0 } = 4'b0010;    // 24
    2'b10 : { en3, en2, en1, en0 } = 4'b0100;    // 25
    2'b11 : { en3, en2, en1, en0 } = 4'b1000;    // 26
    default : { en3, en2, en1, en0 } = 4'bxxxx;  // 27
  endcase

I will use if and else structure, and calling corresponding instance with 1'b1*/

 // I am trying to change value of en to call corresponding intance with that
//corresponding en value

endmodule

Body:
Problem has solved when I write ;

reg en0, en1, en2, en3 ;

initial begin
  en0 <= 1'b0; en1 <= 1'b0;
  en2 <= 1'b0; en3 <= 1'b0;
end

g_cal A(  en0) ;
g_cal B(  en1) ;
g_cal C(  en2) ;
g_cal D(  en3) ;

@Marty have emphasized important thing "The reg is necessary since you are assigning to that variable within a procedural block (ie, an always or initial)."


问:
Disable pinch zoom on fancybox images for mobile
I'm currently using Fancybox I'd like to disable image zoom with the pinch gesture on iPad.

I've tried using CSS touch-action:none; and setting options in fancy box.

```<code>$("[data-fancybox]").fancybox({
  clickContent    : false,
});
</code>```

I'd like the image to not respond to pinch zooming.

答:
You can disable gestures by setting touch: false, for example, this would disable for entire page:

$.fancybox.defaults.touch = false;

Or you can disable individually by addingdata-options='{"touch" : false}' to your link.

Body:
I'm currently using Fancybox I'd like to disable image zoom with the pinch gesture on iPad.

I've tried using CSS touch-action:none; and setting options in fancy box.

$("[data-fancybox]").fancybox({
  clickContent    : false,
});

I'd like the image to not respond to pinch zooming.


问:
How to copy the contents of a set to a two dimensional array in Java?
The idea is to have a two dimensional array NxN where all the elements (numbers from 0 to N*N) are in random positions. To generate the random numbers I used:

```<code> // Creates a set so we avoid repetition of generated numbers
        Set<Integer> generatedNumbers = new LinkedHashSet<Integer>();
        while (generatedNumbers.size() < numberOfElements){
            Integer next = rng.nextInt(numberOfElements) ;
            generatedNumbers.add(next);
        }
</code>```

Now I need to copy the elements to a two dimensional array. Basically, something like this:

```<code>   for (Integer number: generatedNumbers){
            // Here I'd like to have:
           // 1st iteration: board[0][0] = number
          // 2nd iteration: board[0][1] = number
          // ...
          // last iteration: board[3][3] = number
        }
</code>```

where:

```<code>board = new int[boardSize][boardSize];
</code>```

with boardSize = 4 for this particular case.
Btw, if there's a better way to achieve the same but using a different method, I'd be happy to read it.

答:
If I understood correctly you want to randomly distribute numbers from a collection into a 2d array. Here is a working code based on what you gave us that will do just that:

```<code>public static Integer[][] getRandomNumbersArray(int base)
{
    Random rng = new Random();
    int numberOfElements = base * base;

    // Let's use a list so we access by index
    List<Integer> generatedNumbers = new ArrayList<>();

    for (int i = 0; i < numberOfElements; i++)
    {
        // Generate our random number
        Integer next = rng.nextInt(numberOfElements) ;

        // Check if the number is already added
        if (!generatedNumbers.contains(next)) {
            generatedNumbers.add(next);
        }
        // Number was a duplicate, redo loop cycle
        else i--;
    }
    // Create our board array here
    Integer[][] array = new Integer[base][base];

    // Index used to access the list
    int i1 = 0;

    for (int i2 = 0; i2 < base; i2++)
    {
        // Populate board row
        for (int i3 = 0; i3 < base; i3++, i1++) {
            array[i2][i3] = generatedNumbers.get(i1);
        }
    }
    return array;
}

public static void main(String[] args)
{
    Integer[][] array = getRandomNumbersArray(4);

    System.out.println("Here is how our board looks like:");
    for (int i = 0; i < array.length; i++) {
        System.out.println(Arrays.toString(array[i]));
    }
}
</code>```

Output

```<code>Here is how our board looks like:
[8, 7, 11, 3]
[15, 5, 1, 0]
[2, 9, 10, 12]
[13, 4, 6, 14]
</code>```

Body:
The idea is to have a two dimensional array NxN where all the elements (numbers from 0 to N*N) are in random positions. To generate the random numbers I used:

 // Creates a set so we avoid repetition of generated numbers
        Set<Integer> generatedNumbers = new LinkedHashSet<Integer>();
        while (generatedNumbers.size() < numberOfElements){
            Integer next = rng.nextInt(numberOfElements) ;
            generatedNumbers.add(next);
        }

Now I need to copy the elements to a two dimensional array. Basically, something like this:

   for (Integer number: generatedNumbers){
            // Here I'd like to have:
           // 1st iteration: board[0][0] = number
          // 2nd iteration: board[0][1] = number
          // ...
          // last iteration: board[3][3] = number
        }

where:

board = new int[boardSize][boardSize];

with boardSize = 4 for this particular case.
Btw, if there's a better way to achieve the same but using a different method, I'd be happy to read it.

Body:
If I understood correctly you want to randomly distribute numbers from a collection into a 2d array. Here is a working code based on what you gave us that will do just that:

public static Integer[][] getRandomNumbersArray(int base)
{
    Random rng = new Random();
    int numberOfElements = base * base;

    // Let's use a list so we access by index
    List<Integer> generatedNumbers = new ArrayList<>();

    for (int i = 0; i < numberOfElements; i++)
    {
        // Generate our random number
        Integer next = rng.nextInt(numberOfElements) ;

        // Check if the number is already added
        if (!generatedNumbers.contains(next)) {
            generatedNumbers.add(next);
        }
        // Number was a duplicate, redo loop cycle
        else i--;
    }
    // Create our board array here
    Integer[][] array = new Integer[base][base];

    // Index used to access the list
    int i1 = 0;

    for (int i2 = 0; i2 < base; i2++)
    {
        // Populate board row
        for (int i3 = 0; i3 < base; i3++, i1++) {
            array[i2][i3] = generatedNumbers.get(i1);
        }
    }
    return array;
}

public static void main(String[] args)
{
    Integer[][] array = getRandomNumbersArray(4);

    System.out.println("Here is how our board looks like:");
    for (int i = 0; i < array.length; i++) {
        System.out.println(Arrays.toString(array[i]));
    }
}

Output

Here is how our board looks like:
[8, 7, 11, 3]
[15, 5, 1, 0]
[2, 9, 10, 12]
[13, 4, 6, 14]


问:
Is there a way to test a mocked function then the actual in the same test file on Jest?
In the same test file, I need to test the actual redux action creator and then, later, if the same action creator was called from another function.

If I jest.mock I'm unable to test the actual. If I don't, I can't mock it later.
I've also tried jest.spyOn with mockImplementation but it doesn't seem to mock it.

```<code>// actionsOne.js
export const myActionOne = ({
  type: 'MY_ACTION_ONE'
})

// test.js
import { dispatch } from './reduxStore.js'
import { myActionOne } from './actionsOne.js'
import { myActionTwo } from './actionsTwo.js'

jest.mock('./actionsOne.js', () => ({
  myActionOne: jest.fn()
}))

test('expectation 1', () => {
  // would pass if no mocking is in place. fail otherwise.
  expect(dispatch(myActionOne())).toEqual({
    type: 'MY_ACTION_ONE'
  })
})

test('expectation 2', () => {
  dispatch(myActionTwo()) // say this would also dispatch myActionOne somewhere
  // would pass if mocking is in place. fail otherwise.
  expect(myActionOne).toHaveBeenCalled()
})
</code>```

Because myActionOne does a lot of stuff when dispatched, I wanted to test it once and for myActionTwo just check if it was called.

Any recommendation? Thanks!

答:
Ok, I got it to work using jest.requireActual():

```<code>test('expectation 1', () => {
  const { myActionOne: myActionOneActual } = jest.requireActual('./actionsOne.js')

  expect(dispatch(myActionOneActual())).toEqual({
    type: 'MY_ACTION_ONE'
  })
})
</code>```

expectation 1 passes because we are asserting with the actual function.

No changes to expectation 2, since it asserts with the mocked function.

Body:
In the same test file, I need to test the actual redux action creator and then, later, if the same action creator was called from another function.

If I jest.mock I'm unable to test the actual. If I don't, I can't mock it later.
I've also tried jest.spyOn with mockImplementation but it doesn't seem to mock it.

// actionsOne.js
export const myActionOne = ({
  type: 'MY_ACTION_ONE'
})

// test.js
import { dispatch } from './reduxStore.js'
import { myActionOne } from './actionsOne.js'
import { myActionTwo } from './actionsTwo.js'

jest.mock('./actionsOne.js', () => ({
  myActionOne: jest.fn()
}))

test('expectation 1', () => {
  // would pass if no mocking is in place. fail otherwise.
  expect(dispatch(myActionOne())).toEqual({
    type: 'MY_ACTION_ONE'
  })
})

test('expectation 2', () => {
  dispatch(myActionTwo()) // say this would also dispatch myActionOne somewhere
  // would pass if mocking is in place. fail otherwise.
  expect(myActionOne).toHaveBeenCalled()
})

Because myActionOne does a lot of stuff when dispatched, I wanted to test it once and for myActionTwo just check if it was called.

Any recommendation? Thanks!

Body:
Ok, I got it to work using jest.requireActual():

test('expectation 1', () => {
  const { myActionOne: myActionOneActual } = jest.requireActual('./actionsOne.js')

  expect(dispatch(myActionOneActual())).toEqual({
    type: 'MY_ACTION_ONE'
  })
})

expectation 1 passes because we are asserting with the actual function.

No changes to expectation 2, since it asserts with the mocked function.


问:
Nth-of-type works just like nth-child, I can't select what I want in a very simple markup
Please see this codepen or the following screenshot and code: https://codepen.io/rockmandash/pen/YbJQqG

My HTML

 I want to select this element(second line)

```

<p>CSS</p>

<pre class="lang-css prettyprint-override"><code>.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}
.line:nth-of-type(2) {  I chosed, but not working as expected
  width: 15px;
  height: 15px;
  background: black;
}

</code>```

Screenshot

Why my nth-of-type works just like nth-child?

答:
The :nth-of-type(n) selector matches every element that is the nth child, of a particular type(like div and p), of its parent and :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.

So use nth-child or span instead of div for line class

.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}

.line:nth-of-type(2) {
  width: 15px;
  height: 15px;
  background: black;
  display:block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child"></div>
  <span class="line"></span>
  <div class="child"></div>
  <span class="line"></span>
  <div class="child"></div>
  <span class="line"></span>
</div></code>```

Body:
Please see this codepen or the following screenshot and code: https://codepen.io/rockmandash/pen/YbJQqG

My HTML

 I want to select this element(second line)

CSS

.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}
.line:nth-of-type(2) {  I chosed, but not working as expected
  width: 15px;
  height: 15px;
  background: black;
}

Screenshot

Why my nth-of-type works just like nth-child?

Body:
The :nth-of-type(n) selector matches every element that is the nth child, of a particular type(like div and p), of its parent and :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.

So use nth-child or span instead of div for line class

.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}

.line:nth-of-type(2) {
  width: 15px;
  height: 15px;
  background: black;
  display:block;
}

<div class="container">
  <div class="child"></div>
  <span class="line"></span>
  <div class="child"></div>
  <span class="line"></span>
  <div class="child"></div>
  <span class="line"></span>
</div>


问:
Pythonic way to store and reference a class method
I have a "World" class, it has several class methods involving generating different types of features, Id like to store references to these methods in a dictionary where they are the value and the key is the "type" of thing they are generating, a river, castle or road or example, what is the most Pythonic way to do this? I could create a dictionary in the "World" class but I'm not sure if storing it there is the best idea, I was thinking it might be better store this dictionary outside the "World" class but then how do I reference the method? I could store the methods as strings, "generate_site_river" for example, then use attrget() to get the method but I'm not sure this is a good idea, what is the most Pythonic thing to do?</p>

答:
You can store the references to the methods themselves in the dict - not as strings.

Here's an example:

```<code>class World(object):

    def __init__(self, name):
        self._name = name

    def create_river(self):
        print(f"Created a river in {self._name}")

if __name__ == '__main__':
    w = World('Earth')

    method_dict = {
        'river': w.create_river
    }

    method_dict.get('river')()
</code>```

Output:

```<code>Created a river in Earth
</code>```

Body:
You can store the references to the methods themselves in the dict - not as strings.

Here's an example:

class World(object):

    def __init__(self, name):
        self._name = name

    def create_river(self):
        print(f"Created a river in {self._name}")

if __name__ == '__main__':
    w = World('Earth')

    method_dict = {
        'river': w.create_river
    }

    method_dict.get('river')()

Output:

Created a river in Earth


问:
CFBundleVersion in the Info.plist Upload Error

"The binary you uploaded was invalid. The key CFBundleVersion in the
  Info.plist file must contain a higher version than that of the
  previously uploaded version."

I’m getting this error when I come to upload my application.

I set the updated version to 1.2 on iTunes Connect and have also updated the .plist file to 1.2.

I don’t understand why I am getting this error. Any help would be appreciated. Thanks.

答:
This article points out that the version number as seen in the app-store is not necessarily the same as the bundle version number. When you view your app's details in iTunes, there's a link named 'Binary Details'. That page shows the bundle version. One of the apps I was working on was at version 1.0, but it's bundle version was 2.0. Uploading a bundle with version 1.1 failed, but 2.1 did work.

So, there's an app version and a bundle version. This problem has to do with the bundle version.


问:
shorting an multideminsiol array according to its key value
i have any array

```<code>[0] => Array
    (
        [value] => 1
        [label] => General
    )

[1] => Array
    (
        [value] => 2
        [label] => Wholesale Customers
    )

[2] => Array
    (
        [value] => 3
        [label] => Public Customers
    )

[3] => Array
    (
        [value] => 4
        [label] => Managers
    )
</code>```

its a multidimensional array in each index i have 2 key value & label is it possible to short out this array according to label (Z-A)
means

```<code>[0] => Array
    (
        [value] => 2
        [label] => Wholesale Customers
    )

[2] => Array
    (
        [value] => 3
        [label] => Public Customers
    )

[3] => Array
    (
        [value] => 4
        [label] => Managers
    )
[4] => Array
    (
        [value] => 1
        [label] => General
    )
</code>```

using array shorting function in php think only short first index 0,1,2,3,4 or 4,3,2,1,0
or our own define pattern but when i have a lots of key in this array it not good practice to write each time a compare array so any way to short according to a particular key's value
in my desire output its take label which hold a value "wholesale customer" sift up & "Genral down bottom"
first i want to knwo any native function here in php to do this thing if not then how can i do this but not with loop re-ordering

答:
function myfun($val1, $val2){
    return ($val1["lable"]<$val2["lable"]) ? 0:1;
}

usort($myarr, "myfun");

print_r($myarr);
```

Body:
i have any array

[0] => Array
    (
        [value] => 1
        [label] => General
    )

[1] => Array
    (
        [value] => 2
        [label] => Wholesale Customers
    )

[2] => Array
    (
        [value] => 3
        [label] => Public Customers
    )

[3] => Array
    (
        [value] => 4
        [label] => Managers
    )

its a multidimensional array in each index i have 2 key value & label is it possible to short out this array according to label (Z-A)
means

[0] => Array
    (
        [value] => 2
        [label] => Wholesale Customers
    )

[2] => Array
    (
        [value] => 3
        [label] => Public Customers
    )

[3] => Array
    (
        [value] => 4
        [label] => Managers
    )
[4] => Array
    (
        [value] => 1
        [label] => General
    )

using array shorting function in php think only short first index 0,1,2,3,4 or 4,3,2,1,0
or our own define pattern but when i have a lots of key in this array it not good practice to write each time a compare array so any way to short according to a particular key's value
in my desire output its take label which hold a value "wholesale customer" sift up & "Genral down bottom"
first i want to knwo any native function here in php to do this thing if not then how can i do this but not with loop re-ordering


问:
Finding mean of a values in a dictionary without using .values() etc
I have a dictionary that looks like:

```<code>G={'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}
</code>```

I have to find the mean of the values e.g. mean(18,17,19,15,0) using a simple for loop without using built in functions like .values(), .items() and so on. I tried the following but am getting an error:

```<code>d=[float(sum(values)) / len(values) for key, values in G]
    return (d)
ValueError: need more than 1 value to unpack
</code>```

Can someone help me fix this????

答:
```<code>import numpy as np
np.mean(list(dict.values()))
</code>```

Body:
I have a dictionary that looks like:

G={'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}

I have to find the mean of the values e.g. mean(18,17,19,15,0) using a simple for loop without using built in functions like .values(), .items() and so on. I tried the following but am getting an error:

d=[float(sum(values)) / len(values) for key, values in G]
    return (d)
ValueError: need more than 1 value to unpack

Can someone help me fix this????


问:
How to inject value to path variable of a web service call URL in Angular?
I want to call this backend URL to receive user profile data

```<code>/users/:userId/profile
</code>```

where :userId will be an actual number for the ID.

What is the syntax to inject the userId value to the URL before sending the request?

答:
You can simply concatenate it like string concatenation.</p>

```<code>http.get('/users'/+this.userId+'/profile').then();
</code>```

Body:
I want to call this backend URL to receive user profile data

/users/:userId/profile

where :userId will be an actual number for the ID.

What is the syntax to inject the userId value to the URL before sending the request?

Body:
You can simply concatenate it like string concatenation.

http.get('/users'/+this.userId+'/profile').then();


问:
How to delete the first row
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

```<code>DB::table('ahah')->first()->delete().
</code>```

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?

答:
Use the oldest method for getting the first record:</p>

```<code>$ahah_first = \DB::table('ahah')->oldest()->first();
\DB::table('ahah')->where('id', $ahah_first->id)->delete();
</code>```

Title: How to delete the first row

Body:
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

DB::table('ahah')->first()->delete().

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?

Body:
Use the oldest method for getting the first record:

$ahah_first = \DB::table('ahah')->oldest()->first();
\DB::table('ahah')->where('id', $ahah_first->id)->delete();


问:
Are Parameters really enough to prevent Sql injections?
I've been preaching both to my colleagues and here on SO about the goodness of using parameters in SQL queries, especially in .NET applications. I've even gone so far as to promise them as giving immunity against SQL injection attacks.

But I'm starting to wonder if this really is true. Are there any known SQL injection attacks that will be successfull against a parameterized query? Can you for example send a string that causes a buffer overflow on the server?

There are of course other considerations to make to ensure that a web application is safe (like sanitizing user input and all that stuff) but now I am thinking of SQL injections. I'm especially interested in attacks against MsSQL 2005 and 2008 since they are my primary databases, but all databases are interesting.

Edit: To clarify what I mean by parameters and parameterized queries. By using parameters I mean using "variables" instead of building the sql query in a string.

So instead of doing this:

```<code>SELECT * FROM Table WHERE Name = 'a name'
</code>```

We do this:

```<code>SELECT * FROM Table WHERE Name = @Name
</code>```

and then set the value of the @Name parameter on the query / command object.

答:
You can run dynamic sql as example</p>

```<code>DECLARE @SQL NVARCHAR(4000);
DECLARE @ParameterDefinition NVARCHAR(4000);

SELECT  @ParameterDefinition = '@date varchar(10)'

SET @SQL='Select CAST(@date AS DATETIME) Date'

EXEC sp_executeSQL @SQL,@ParameterDefinition,@date='04/15/2011'
</code>```

OwnerDisplayName: Rune

ContentLicense: CC BY-SA 2.5

Body:
I've been preaching both to my colleagues and here on SO about the goodness of using parameters in SQL queries, especially in .NET applications. I've even gone so far as to promise them as giving immunity against SQL injection attacks.

But I'm starting to wonder if this really is true. Are there any known SQL injection attacks that will be successfull against a parameterized query? Can you for example send a string that causes a buffer overflow on the server?

There are of course other considerations to make to ensure that a web application is safe (like sanitizing user input and all that stuff) but now I am thinking of SQL injections. I'm especially interested in attacks against MsSQL 2005 and 2008 since they are my primary databases, but all databases are interesting.

Edit: To clarify what I mean by parameters and parameterized queries. By using parameters I mean using "variables" instead of building the sql query in a string.

So instead of doing this:

SELECT * FROM Table WHERE Name = 'a name'

We do this:

SELECT * FROM Table WHERE Name = @Name

and then set the value of the @Name parameter on the query / command object.

LastEditorDisplayName: coldice

Body:
You can run dynamic sql as example

DECLARE @SQL NVARCHAR(4000);
DECLARE @ParameterDefinition NVARCHAR(4000);

SELECT  @ParameterDefinition = '@date varchar(10)'

SET @SQL='Select CAST(@date AS DATETIME) Date'

EXEC sp_executeSQL @SQL,@ParameterDefinition,@date='04/15/2011'