问:
Python: 'ValueError: too many values to unpack (expected 2)' for a username password system
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

```<code>database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse
</code>```

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked

答:
Try this,

```<code>import ast

with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        eval_dict = ast.literal_eval(line) # This gives you a dictionary
        database[name] = eval_dict["name"]
</code>```

Note:

As per @jaggers comment,

I have consider {"name" : "hello", "man" : "mane"} line in text file.

Body:
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked

Body:
Try this,

import ast

with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        eval_dict = ast.literal_eval(line) # This gives you a dictionary
        database[name] = eval_dict["name"]

Note:

As per @jaggers comment,

I have consider {"name" : "hello", "man" : "mane"} line in text file.


来源: stackexchange

问:
How to extract elements of a list in R?
I have a list with several vectors which looks like this : </p>

```<code>$`56`
[1] "OTU2998"             "UniRef90_A0A1Z9FS94" "UniRef90_A0A257ESC3"
[4] "UniRef90_A0A293NAV3" "UniRef90_A0A2E1NMU8" "UniRef90_A0A2E1NPX9"
[7] "UniRef90_A0A2E1NQL1" "UniRef90_A0A2E1NRD2" "UniRef90_X0UC66"

$`57`
[1] "OTU3820"             "UniRef90_A0A1Z9H3N2" "UniRef90_A0A2D5I161"
[4] "UniRef90_A0A2E6PRN5"

$`58`
[1] "OTU4452"                "UniRef90_A0A1Z9KBI8"    "UniRef90_A0A2E1VTI6"
[4] "UniRef90_A0A2G2KCN6"    "UniRef90_UPI000BFEC744"

$`59`
[1] "OTU0245"             "UniRef90_A0A1Z9MPM9" "UniRef90_A0A2E2ME98"
[4] "UniRef90_A0A2E8X9N7"

</code>```

<p>Is there a way to only extract the "OTUXXX" information? I mean, I would like to get something like this : </p>

```<code>$`56`
[1] "OTU2998"

$`57`
[1] "OTU3820"

$`58`
[1] "OTU4452"

$`59`
[1] "OTU0245"

</code>```

答:
I like the purrr::map family of functions for their ease of passing functions and arguments. Two quick options for extracting those elements are with grep using value = T to return the matching strings, not just their indices, or with stringr::str_subset which does the same.

The regex here matches strings that begin with "OTU", followed by 1 or more digits to the end.

Both methods scale for multiple matches at a time: I added an item "OTU1234" in the last list element to illustrate this.

dl <- list(
  `56` = c("OTU2998", "UniRef90_A0A1Z9FS94", "UniRef90_A0A257ESC3", "UniRef90_A0A293NAV3", "UniRef90_A0A2E1NMU8", "UniRef90_A0A2E1NPX9", "UniRef90_A0A2E1NQL1", "UniRef90_A0A2E1NRD2", "UniRef90_X0UC66"),
  `57` = c("OTU3820", "UniRef90_A0A1Z9H3N2", "UniRef90_A0A2D5I161", "UniRef90_A0A2E6PRN5"),
  `58` = c("OTU4452", "UniRef90_A0A1Z9KBI8", "UniRef90_A0A2E1VTI6", "UniRef90_A0A2G2KCN6", "UniRef90_UPI000BFEC744"),
  `59` = c("OTU0245", "UniRef90_A0A1Z9MPM9", "UniRef90_A0A2E2ME98", "UniRef90_A0A2E8X9N7", "OTU1234")
)

purrr::map(dl, ~grep("^OTU\\d+$", ., value = T))
#> $`56`
#> [1] "OTU2998"
#>
#> $`57`
#> [1] "OTU3820"
#>
#> $`58`
#> [1] "OTU4452"
#>
#> $`59`
#> [1] "OTU0245" "OTU1234"
purrr::map(dl, stringr::str_subset, "^OTU\\d+$")
# same output as above
```

ContentLicense: CC BY-SA 4.0

Title: How to extract elements of a list in R?

Body:
I have a list with several vectors which looks like this :

$`56`
[1] "OTU2998"             "UniRef90_A0A1Z9FS94" "UniRef90_A0A257ESC3"
[4] "UniRef90_A0A293NAV3" "UniRef90_A0A2E1NMU8" "UniRef90_A0A2E1NPX9"
[7] "UniRef90_A0A2E1NQL1" "UniRef90_A0A2E1NRD2" "UniRef90_X0UC66"

$`57`
[1] "OTU3820"             "UniRef90_A0A1Z9H3N2" "UniRef90_A0A2D5I161"
[4] "UniRef90_A0A2E6PRN5"

$`58`
[1] "OTU4452"                "UniRef90_A0A1Z9KBI8"    "UniRef90_A0A2E1VTI6"
[4] "UniRef90_A0A2G2KCN6"    "UniRef90_UPI000BFEC744"

$`59`
[1] "OTU0245"             "UniRef90_A0A1Z9MPM9" "UniRef90_A0A2E2ME98"
[4] "UniRef90_A0A2E8X9N7"

Is there a way to only extract the "OTUXXX" information? I mean, I would like to get something like this :

$`56`
[1] "OTU2998"

$`57`
[1] "OTU3820"

$`58`
[1] "OTU4452"

$`59`
[1] "OTU0245"


问:
onclick disable submit button
i wanna disable a submit button when onclick. im able to disable the button but i cant submit the post value to php.</p>

答:
Using jQuery, add onClick handler that returns false:

```<code><input type="submit" value="Submit" onClick="$(this).click(function() {return false;});"/>
</code>```

ContentLicense: CC BY-SA 2.5

Title: onclick disable submit button

Body:
Using jQuery, add onClick handler that returns false:

<input type="submit" value="Submit" onClick="$(this).click(function() {return false;});"/>

ContentLicense: CC BY-SA 3.0


问:
Input data to database using rest api (Login)
I have an API that is trying to check a if a user is on the database. However, I'm not sure how to post the data from the input to my API to allow a user to login.

HTML Login page

```<code>  <ion-item class='ion-padding'>
    <ion-label position="floating">Username (Email)</ion-label>
    <ion-input type='text'name="email" #email [(ngModel)]="email"></ion-input>
  </ion-item>

  <ion-item class='ion-padding'>
    <ion-label position="floating">Password</ion-label>
    <ion-input type='password'  name="password" #password [(ngModel)]="password"></ion-input>
  </ion-item>
   <router-outlet></router-outlet>
</ion-content>
</ion-app>
</code>```

Login.ts

```<code>import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController } from '@ionic/angular';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-login',
  templateUrl: 'login.page.html',

})
export class HomePage {
  username = '';
  password = '';

  constructor(
    public navCtrl: NavController, public alertCtrl: AlertController,
    private http: HttpClient,
    private httpH: HttpHeaders,
    public loading: LoadingController) { }

  }
</code>```

答:
Have a button in HTML and bind (click)="onSubmit()"

TS:

```<code>  onSubmit() {
    let data = {
      username: this.username,
      password: this.password
    }

    this.http.post(this.apiUrl, data)
      .subscribe((resp) => {
        console.log(resp)
      }, (error) => {
      })
  }
</code>```

Body:
I have an API that is trying to check a if a user is on the database. However, I'm not sure how to post the data from the input to my API to allow a user to login.

HTML Login page

  <ion-item class='ion-padding'>
    <ion-label position="floating">Username (Email)</ion-label>
    <ion-input type='text'name="email" #email [(ngModel)]="email"></ion-input>
  </ion-item>

  <ion-item class='ion-padding'>
    <ion-label position="floating">Password</ion-label>
    <ion-input type='password'  name="password" #password [(ngModel)]="password"></ion-input>
  </ion-item>
   <router-outlet></router-outlet>
</ion-content>
</ion-app>

Login.ts

import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController } from '@ionic/angular';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-login',
  templateUrl: 'login.page.html',

})
export class HomePage {
  username = '';
  password = '';

  constructor(
    public navCtrl: NavController, public alertCtrl: AlertController,
    private http: HttpClient,
    private httpH: HttpHeaders,
    public loading: LoadingController) { }

  }

Body:
Have a button in HTML and bind (click)="onSubmit()"

TS:

  onSubmit() {
    let data = {
      username: this.username,
      password: this.password
    }

    this.http.post(this.apiUrl, data)
      .subscribe((resp) => {
        console.log(resp)
      }, (error) => {
      })
  }


问:
Not able to predict output in fastai
Noob here.

Here's the dataset that I'm working on https://www.kaggle.com/arpitjain007/game-of-deep-learning-ship-datasets

and I'm using fastai, I've successfully built the model but I have no idea how to test it with 'test.csv' file.

Here's my code

```<code>from fastai import *
from fastai.vision import *

path = '../input/train'
path = Path(path)
path.ls()
df = pd.read_csv(path/'train.csv')
data = ImageDataBunch.from_df('../input/train/images', df, ds_tfms=get_transforms(), size=224, bs=64 ).normalize(imagenet_stats)
learn = cnn_learner(data, models.resnet50, metrics=accuracy,  model_dir='/kaggle/working/models')
learn.fit_one_cycle(5)
df_test = pd.read_csv('../input/test_ApKoW4T.csv')
</code>```

I don't know how to use the Test Dataframe to predict.

答:
Check out this kernel
https://www.kaggle.com/matejthetree/digit-recognizer-fast-ai-customimagelist?scriptVersionId=14597759

when initializing data you add test bunch to it

```<code>data = (CustomImageList.from_csv_custom(path=path, csv_name='train.csv', imgIdx=1)
                .split_by_rand_pct(.2)
                .label_from_df(cols='label')
                .add_test(test, label=0)
                .transform(tfms)
                .databunch(bs=128, num_workers=0)
                .normalize(imagenet_stats))
</code>```

later you get predictions

```<code>predictions, *_ = learn.get_preds(DatasetType.Test)
labels = np.argmax(predictions, 1)
# output to a file
submission_df = pd.DataFrame({'ImageId': list(range(1,len(labels)+1)), 'Label': labels})
submission_df.to_csv(f'submission.csv', index=False)
</code>```

Title: Not able to predict output in fastai

Body:
Noob here.

Here's the dataset that I'm working on https://www.kaggle.com/arpitjain007/game-of-deep-learning-ship-datasets

and I'm using fastai, I've successfully built the model but I have no idea how to test it with 'test.csv' file.

Here's my code

from fastai import *
from fastai.vision import *

path = '../input/train'
path = Path(path)
path.ls()
df = pd.read_csv(path/'train.csv')
data = ImageDataBunch.from_df('../input/train/images', df, ds_tfms=get_transforms(), size=224, bs=64 ).normalize(imagenet_stats)
learn = cnn_learner(data, models.resnet50, metrics=accuracy,  model_dir='/kaggle/working/models')
learn.fit_one_cycle(5)
df_test = pd.read_csv('../input/test_ApKoW4T.csv')

I don't know how to use the Test Dataframe to predict.

Body:
Check out this kernel
https://www.kaggle.com/matejthetree/digit-recognizer-fast-ai-customimagelist?scriptVersionId=14597759

when initializing data you add test bunch to it

data = (CustomImageList.from_csv_custom(path=path, csv_name='train.csv', imgIdx=1)
                .split_by_rand_pct(.2)
                .label_from_df(cols='label')
                .add_test(test, label=0)
                .transform(tfms)
                .databunch(bs=128, num_workers=0)
                .normalize(imagenet_stats))

later you get predictions

predictions, *_ = learn.get_preds(DatasetType.Test)
labels = np.argmax(predictions, 1)
# output to a file
submission_df = pd.DataFrame({'ImageId': list(range(1,len(labels)+1)), 'Label': labels})
submission_df.to_csv(f'submission.csv', index=False)


问:
Check if current row cell date is in the past
I'm currently trying to access numerous rows in a loop to check if the END DATE (in Column C) is in the past.

If the END DATE is in the past I want to check if Column M contains the string "Cancel", if it doesn't I want to write "cancel" to column M, before moving to the next row.

答:
There are probably several ways to go about it, but this macro should look at each value in the column (the macro stops if it reaches a blank cell) and checks if it is less than the system date. If the date is less, it assigns the value "Cancel" to the cell in Column M in the same row.</p>

```<code>Sub checkDate()
    Dim x As Integer
    x = 1 'Starts on row one.
    With ThisWorkbook.Worksheets("Sheet1")
        Do While .Range("C" & x).Value <> "" 'Checks each row in Column C until it reaches an empty row. Could be replaced with a For statement.
            If .Range("C" & x).Value < Date Then
                .Range("M" & x).Value = "Cancel"
            End If
            x = x + 1
        Loop
    End With
End Sub
</code>```

Body:
There are probably several ways to go about it, but this macro should look at each value in the column (the macro stops if it reaches a blank cell) and checks if it is less than the system date. If the date is less, it assigns the value "Cancel" to the cell in Column M in the same row.

Sub checkDate()
    Dim x As Integer
    x = 1 'Starts on row one.
    With ThisWorkbook.Worksheets("Sheet1")
        Do While .Range("C" & x).Value <> "" 'Checks each row in Column C until it reaches an empty row. Could be replaced with a For statement.
            If .Range("C" & x).Value < Date Then
                .Range("M" & x).Value = "Cancel"
            End If
            x = x + 1
        Loop
    End With
End Sub


问:
numpy get row index where elements in certain columns are zero
I want to find indexes of row based on criteria over certain columns

So, something like:

```<code>import numpy as np
x = np.random.rand(4, 5)

x[2, 2] = 0
x[2, 3] = 0
x[3, 1] = 0
x[1, 3] = 0
</code>```

Now, I want to get the index of the rows where either of columns 3 or 4 are zeros. How can one do that with numpy? Do I need to make multiple calls to nonzero for each column and combine these indices using a set or something like that?

答:
Using np.where first array within the tuple is row index

```<code>np.where(x[:,[3,4]]==0)

Out[79]: (array([1, 2], dtype=int64), array([0, 0], dtype=int64))
</code>```

Body:
I want to find indexes of row based on criteria over certain columns

So, something like:

import numpy as np
x = np.random.rand(4, 5)

x[2, 2] = 0
x[2, 3] = 0
x[3, 1] = 0
x[1, 3] = 0

Now, I want to get the index of the rows where either of columns 3 or 4 are zeros. How can one do that with numpy? Do I need to make multiple calls to nonzero for each column and combine these indices using a set or something like that?

Body:
Using np.where first array within the tuple is row index

np.where(x[:,[3,4]]==0)

Out[79]: (array([1, 2], dtype=int64), array([0, 0], dtype=int64))


答: HTML5 now doesn't require the mimetype to be declared in a script tag, as "text/javascript" is implied; so yes, I think it's safe to assume that this is the default.</p>

Title: Can "text/javascript" be assumed a de facto default for the <script> element?

Body: Despite that the HTML4 standard states there is no default for the


问:
Python-generated XML via PyXB does not validate against XSD file: How to generate and how to validate?
I am learning how to use an XML Schema document to generate an XML file which complies with said schema.

I have learned about PyXB to generate Python bindings for data structures defined by an XML Schema.

This SO post presents an "end-to-end" example of how to go about generating an XML file which complies with a given XML Schema. In order to provide information, the post helps digest information in these two links:

http://pyxb.sourceforge.net/userref_pyxbgen.html#pyxbgen

http://pyxb.sourceforge.net/userref_usebind.html

Both of these links present a decent explanation of how to use the bindings to generate the required XML file.

Here's the XSD file used:

```<code>  <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
  <xsd:element name="comment" type="xsd:string"/>
  <xsd:complexType name="PurchaseOrderType">
    <xsd:sequence>
      <xsd:element name="shipTo" type="USAddress"/>
      <xsd:element name="billTo" type="USAddress"/>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="items"  type="Items"/>
    </xsd:sequence>
    <xsd:attribute name="orderDate" type="xsd:date"/>
  </xsd:complexType>
  <xsd:complexType name="USAddress">
    <xsd:sequence>
      <xsd:element name="name"   type="xsd:string"/>
      <xsd:element name="street" type="xsd:string"/>
      <xsd:element name="city"   type="xsd:string"/>
      <xsd:element name="state"  type="xsd:string"/>
      <xsd:element name="zip"    type="xsd:decimal"/>
    </xsd:sequence>
    <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
  </xsd:complexType>
  <xsd:complexType name="Items">
    <xsd:sequence>
      <xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="productName" type="xsd:string"/>
            <xsd:element name="quantity">
              <xsd:simpleType>
                <xsd:restriction base="xsd:positiveInteger">
                  <xsd:maxExclusive value="100"/>
                </xsd:restriction>
              </xsd:simpleType>
            </xsd:element>
            <xsd:element name="USPrice"  type="xsd:decimal"/>
            <xsd:element ref="comment"   minOccurs="0"/>
            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
          </xsd:sequence>
          <xsd:attribute name="partNum" type="SKU" use="required"/>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
  </xsd:complexType>
  <!-- Stock Keeping Unit, a code for identifying products -->
  <xsd:simpleType name="SKU">
    <xsd:restriction base="xsd:string">
      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
    </xsd:restriction>
  </xsd:simpleType>
</xsd:schema>
</code>```

Here's the command I use to generate the Python bindings:

```<code>pyxbgen -u po1.xsd -m po1
</code>```

This command generates a po1.py file which can then be used to generate an XML document as follows (content of demo2.py):

```<code>from __future__ import print_function
import po1 as address

addr = address.USAddress()
addr.name = 'Robert Smith'
addr.street = '8 Oak Avenue'
addr.city = 'Anytown'
addr.state = 'AK'
addr.zip = 12341

with open('demo2.xml', 'w') as f:
    f.write(addr.toxml("utf-8", element_name='USAddress').decode('utf-8'))
</code>```

Executing this code yields the following well-formed XML file (demo2.xml):

```<code><?xml version="1.0" encoding="utf-8"?>
<USAddress>
    <name>Robert Smith</name>
    <street>8 Oak Avenue</street>
    <city>Anytown</city>
    <state>AK</state>
    <zip>12341.0</zip>
</USAddress>
</code>```

Actual questions:

How can I automate the validation of the generated XML file against
the used XSD Schema?

Why (using this validator) does the
generated XML file (demo2.xml) fail to be validated against the
XML Schema? Specifically, I get the following error: Not valid.
Error - Line 1, 50: org.xml.sax.SAXParseException; lineNumber: 1;
columnNumber: 50; cvc-elt.1.a: Cannot find the declaration of
element 'USAddress'.

What modifications should I consider adding to
demo2.py to produce XML files that do pass the validation against
the Schema?

答:
After doing additional reading, I realized that using the Python bindings does NOT guarantee the generated XML document complies with the schema.

Answer 2 and part of 3:

In this case, the validation fails because the Python code is indeed constructing a non-valid XML document with respect to the schema given. Consider a much simpler XSD-XML pair of files:

Simpler XSD:

```<code><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="a" type="AType"/>
<xsd:complexType name="AType">
  <xsd:sequence>
    <xsd:element name="b" type="xsd:string" />
  </xsd:sequence>
</xsd:complexType>
</xsd:schema>
</code>```

Simpler Python code using bindings generated for the schema:

```<code>from __future__ import print_function
import po2

hey = po2.AType()
hey.b = "Eduardo"

with open('demo4.xml', 'w') as f:
    f.write(hey.toxml("utf-8", element_name='a').decode('utf-8'))
</code>```

When executing the Python code, this XML is generated:

```<code><?xml version="1.0" encoding="utf-8"?>
<a><b>Eduardo</b></a>
</code>```

In the original case (USAddress), the original schema presented a root type for the DOM that is not the USAddress type. Yet, the Python code neglected this and went straight ahead to generate a XML file only using an instance of this type. The generated XML is indeed well-formed, yet it does not comply with the schema. In the much simpler case here depicted, not only is the XML valid, but using Python bindings also yields an XML file that complies with the XSD schema.

Answer 1:

You can automate the validation of the generated file against a given XSD schema using the explanation provided here.

```<code>from lxml import etree
from StringIO import StringIO

# Check https://lxml.de/validation.html

f = StringIO('''\
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="a" type="AType"/>
<xsd:complexType name="AType">
  <xsd:sequence>
    <xsd:element name="b" type="xsd:string" />
  </xsd:sequence>
</xsd:complexType>
</xsd:schema>
''')
xmlschema_doc = etree.parse(f)
xmlschema = etree.XMLSchema(xmlschema_doc)

valid = StringIO('''\
<?xml version="1.0" encoding="utf-8"?>
<a><b>Eduardo</b></a>
''')
doc = etree.parse(valid)

print('Is XML is valid?', xmlschema.validate(doc))
</code>```

Body:
I am learning how to use an XML Schema document to generate an XML file which complies with said schema.

I have learned about PyXB to generate Python bindings for data structures defined by an XML Schema.

This SO post presents an "end-to-end" example of how to go about generating an XML file which complies with a given XML Schema. In order to provide information, the post helps digest information in these two links:

http://pyxb.sourceforge.net/userref_pyxbgen.html#pyxbgen

http://pyxb.sourceforge.net/userref_usebind.html

Both of these links present a decent explanation of how to use the bindings to generate the required XML file.

Here's the XSD file used:

  <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
  <xsd:element name="comment" type="xsd:string"/>
  <xsd:complexType name="PurchaseOrderType">
    <xsd:sequence>
      <xsd:element name="shipTo" type="USAddress"/>
      <xsd:element name="billTo" type="USAddress"/>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="items"  type="Items"/>
    </xsd:sequence>
    <xsd:attribute name="orderDate" type="xsd:date"/>
  </xsd:complexType>
  <xsd:complexType name="USAddress">
    <xsd:sequence>
      <xsd:element name="name"   type="xsd:string"/>
      <xsd:element name="street" type="xsd:string"/>
      <xsd:element name="city"   type="xsd:string"/>
      <xsd:element name="state"  type="xsd:string"/>
      <xsd:element name="zip"    type="xsd:decimal"/>
    </xsd:sequence>
    <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
  </xsd:complexType>
  <xsd:complexType name="Items">
    <xsd:sequence>
      <xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="productName" type="xsd:string"/>
            <xsd:element name="quantity">
              <xsd:simpleType>
                <xsd:restriction base="xsd:positiveInteger">
                  <xsd:maxExclusive value="100"/>
                </xsd:restriction>
              </xsd:simpleType>
            </xsd:element>
            <xsd:element name="USPrice"  type="xsd:decimal"/>
            <xsd:element ref="comment"   minOccurs="0"/>
            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
          </xsd:sequence>
          <xsd:attribute name="partNum" type="SKU" use="required"/>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
  </xsd:complexType>

  <xsd:simpleType name="SKU">
    <xsd:restriction base="xsd:string">
      <xsd:pattern value="\d{3}-[A-Z]{2}"/>
    </xsd:restriction>
  </xsd:simpleType>
</xsd:schema>

Here's the command I use to generate the Python bindings:

pyxbgen -u po1.xsd -m po1

This command generates a po1.py file which can then be used to generate an XML document as follows (content of demo2.py):

from __future__ import print_function
import po1 as address

addr = address.USAddress()
addr.name = 'Robert Smith'
addr.street = '8 Oak Avenue'
addr.city = 'Anytown'
addr.state = 'AK'
addr.zip = 12341

with open('demo2.xml', 'w') as f:
    f.write(addr.toxml("utf-8", element_name='USAddress').decode('utf-8'))

Executing this code yields the following well-formed XML file (demo2.xml):

<?xml version="1.0" encoding="utf-8"?>
<USAddress>
    <name>Robert Smith</name>
    <street>8 Oak Avenue</street>
    <city>Anytown</city>
    <state>AK</state>
    <zip>12341.0</zip>
</USAddress>

Actual questions:

How can I automate the validation of the generated XML file against
the used XSD Schema?

Why (using this validator) does the
generated XML file (demo2.xml) fail to be validated against the
XML Schema? Specifically, I get the following error: Not valid.
Error - Line 1, 50: org.xml.sax.SAXParseException; lineNumber: 1;
columnNumber: 50; cvc-elt.1.a: Cannot find the declaration of
element 'USAddress'.

What modifications should I consider adding to
demo2.py to produce XML files that do pass the validation against
the Schema?

Body:
After doing additional reading, I realized that using the Python bindings does NOT guarantee the generated XML document complies with the schema.

Answer 2 and part of 3:

In this case, the validation fails because the Python code is indeed constructing a non-valid XML document with respect to the schema given. Consider a much simpler XSD-XML pair of files:

Simpler XSD:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="a" type="AType"/>
<xsd:complexType name="AType">
  <xsd:sequence>
    <xsd:element name="b" type="xsd:string" />
  </xsd:sequence>
</xsd:complexType>
</xsd:schema>

Simpler Python code using bindings generated for the schema:

from __future__ import print_function
import po2

hey = po2.AType()
hey.b = "Eduardo"

with open('demo4.xml', 'w') as f:
    f.write(hey.toxml("utf-8", element_name='a').decode('utf-8'))

When executing the Python code, this XML is generated:

<?xml version="1.0" encoding="utf-8"?>
<a><b>Eduardo</b></a>

In the original case (USAddress), the original schema presented a root type for the DOM that is not the USAddress type. Yet, the Python code neglected this and went straight ahead to generate a XML file only using an instance of this type. The generated XML is indeed well-formed, yet it does not comply with the schema. In the much simpler case here depicted, not only is the XML valid, but using Python bindings also yields an XML file that complies with the XSD schema.

Answer 1:

You can automate the validation of the generated file against a given XSD schema using the explanation provided here.

from lxml import etree
from StringIO import StringIO

# Check https://lxml.de/validation.html

f = StringIO('''\
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="a" type="AType"/>
<xsd:complexType name="AType">
  <xsd:sequence>
    <xsd:element name="b" type="xsd:string" />
  </xsd:sequence>
</xsd:complexType>
</xsd:schema>
''')
xmlschema_doc = etree.parse(f)
xmlschema = etree.XMLSchema(xmlschema_doc)

valid = StringIO('''\
<?xml version="1.0" encoding="utf-8"?>
<a><b>Eduardo</b></a>
''')
doc = etree.parse(valid)

print('Is XML is valid?', xmlschema.validate(doc))


问:
How database master key protect the certificate
In Sql Server system, If I need to create a symmetric key, I need to create a Database Master Key first, then a certificate, then the symmetric key, with the following code:

```<code>-- Create database master key
CREATE MASTER KEY ENCRYPTION BY PASSWORD = ‘GoodLuckWithExam!’
-- Create certificate
CREATE CERTIFICATE Cert_BAN
WITH SUBJECT = ‘Bank Account Number’;
-- Create SMK
CREATE SYMMETRIC KEY Key_BAN
WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE Cert_BAN;
</code>```

From here we could see that the SMK is protected by the certificate. However the certificate is NOT protected by the database master key, then my question is why we need the database master key at all?

Thanks

答:
Certificate private key is encrypted using the database master key.

From CREATE CERTIFICATE:

ENCRYPTION BY PASSWORD ='password'

Specifies the password used to encrypt the private key. Use this option only if you want to encrypt the certificate with a password. If this clause is omitted, the private key is encrypted using the database master key. Password must meet the Windows password policy requirements of the computer that is running the instance of SQL Server.

Body:
In Sql Server system, If I need to create a symmetric key, I need to create a Database Master Key first, then a certificate, then the symmetric key, with the following code:

-- Create database master key
CREATE MASTER KEY ENCRYPTION BY PASSWORD = ‘GoodLuckWithExam!’
-- Create certificate
CREATE CERTIFICATE Cert_BAN
WITH SUBJECT = ‘Bank Account Number’;
-- Create SMK
CREATE SYMMETRIC KEY Key_BAN
WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE Cert_BAN;

From here we could see that the SMK is protected by the certificate. However the certificate is NOT protected by the database master key, then my question is why we need the database master key at all?

Thanks


问:
How to combine two df with two different timestamps?
I have two different dfs each with a timestamp. One is collecting data every minute, the other just in case of a change, so sometimes every second, sometimes a couple hours in between two rows. How can I append the columns of df2 to df1 so the timestamp would be the same? df2 would show the same value in each row (so each minute) until something changes (so ffill the NaN's). It's okay to loose some information through that, it's more important to put the dfs together. I'm still a beginner so help would be appreciated. Thanks in advance!

At the moment it looks like this:

```<code>In[10]: df1
Out[10]:
timestamp, X, Y, Z
2018-12-15 08:00:00, 134, 7, 276
2018-12-15 08:01:00, 130, 7, 278
2018-12-15 08:02:00, 136, 8, 291

In[11]: df2
Out[11]:
timestamp, A, B, C
2018-12-15 07:34:36, 1, 44, 21
2018-12-15 08:00:46, NaN, 50, 20
2018-12-15 08:00:52, 0, NaN, 30
</code>```

It's supposed to look like this:

```<code>In[12]: df
Out[12]:
timestamp, X, Y, Z, A, B, C
2018-12-15 08:00:00, 134, 7, 276, 1, 44, 21
2018-12-15 08:01:00, 130, 7, 278, 0, 50, 30
2018-12-15 08:02:00, 136, 8, 291, 0, 50, 30
</code>```

答:
I guess you need resample. First, be sure that 'timestamp' is of type datetime and set it as the index of your dataframes.

```<code>df1['timestamp'] = pd.to_datetime(df1['timestamp'])
df2['timestamp'] = pd.to_datetime(df2['timestamp'])
</code>```

This to make them of datetime type

```<code>df1.set_index('timestamp', inplace=True)
df2.set_index('timestamp', inplace=True)
</code>```

This to set them as index.

Then you just need to resample df2 to bin of 1 minute:

```<code>rsdf2 = df2.resample('1T').sum()
</code>```

The sum() method will sums togheter values in the same bin, and put 0 in empty bins. You can use different functions of course, depending on your needs. .mean() for example if you want the mean value instead of the sum.

Now depends on how do you want to join them. The function is pandas.concat.

You want to keep all indexes? Use:

```<code>pd.concat([df1, rsdf2], axis=1)
</code>```

It will fill with NaN rows absent in one of the dataframe.

You want to keep common indexes only? Use:

```<code>pd.concat([df1, rsdf2], axis=1, join='inner')
</code>```

You want to keep the exact indexes of the first dataframe? Use:

```<code>pd.concat([df1, rsdf2], axis=1, join_axes=[df1.index])
</code>```

For example, this last one, using your sample dataframes, will give:

```<code>                       X  Y    Z    A     B     C
timestamp
2018-12-15 08:00:00  134  7  276  0.0  50.0  50.0
2018-12-15 08:01:00  130  7  278  NaN   NaN   NaN
2018-12-15 08:02:00  136  8  291  NaN   NaN   NaN
</code>```

Body:
I have two different dfs each with a timestamp. One is collecting data every minute, the other just in case of a change, so sometimes every second, sometimes a couple hours in between two rows. How can I append the columns of df2 to df1 so the timestamp would be the same? df2 would show the same value in each row (so each minute) until something changes (so ffill the NaN's). It's okay to loose some information through that, it's more important to put the dfs together. I'm still a beginner so help would be appreciated. Thanks in advance!

At the moment it looks like this:

In[10]: df1
Out[10]:
timestamp, X, Y, Z
2018-12-15 08:00:00, 134, 7, 276
2018-12-15 08:01:00, 130, 7, 278
2018-12-15 08:02:00, 136, 8, 291

In[11]: df2
Out[11]:
timestamp, A, B, C
2018-12-15 07:34:36, 1, 44, 21
2018-12-15 08:00:46, NaN, 50, 20
2018-12-15 08:00:52, 0, NaN, 30

It's supposed to look like this:

In[12]: df
Out[12]:
timestamp, X, Y, Z, A, B, C
2018-12-15 08:00:00, 134, 7, 276, 1, 44, 21
2018-12-15 08:01:00, 130, 7, 278, 0, 50, 30
2018-12-15 08:02:00, 136, 8, 291, 0, 50, 30

Body:
I guess you need resample. First, be sure that 'timestamp' is of type datetime and set it as the index of your dataframes.

df1['timestamp'] = pd.to_datetime(df1['timestamp'])
df2['timestamp'] = pd.to_datetime(df2['timestamp'])

This to make them of datetime type

df1.set_index('timestamp', inplace=True)
df2.set_index('timestamp', inplace=True)

This to set them as index.

Then you just need to resample df2 to bin of 1 minute:

rsdf2 = df2.resample('1T').sum()

The sum() method will sums togheter values in the same bin, and put 0 in empty bins. You can use different functions of course, depending on your needs. .mean() for example if you want the mean value instead of the sum.

Now depends on how do you want to join them. The function is pandas.concat.

You want to keep all indexes? Use:

pd.concat([df1, rsdf2], axis=1)

It will fill with NaN rows absent in one of the dataframe.

You want to keep common indexes only? Use:

pd.concat([df1, rsdf2], axis=1, join='inner')

You want to keep the exact indexes of the first dataframe? Use:

pd.concat([df1, rsdf2], axis=1, join_axes=[df1.index])

For example, this last one, using your sample dataframes, will give:

                       X  Y    Z    A     B     C
timestamp
2018-12-15 08:00:00  134  7  276  0.0  50.0  50.0
2018-12-15 08:01:00  130  7  278  NaN   NaN   NaN
2018-12-15 08:02:00  136  8  291  NaN   NaN   NaN


问:
Adding a shadow over an image in Swift
This project is taken from SwiftOCR by garnele007. There is a NSImage (That is also converted into a .png for saving)in the Swift project that I would like to add a shadow on top of. Several examples of adding a shadow inside the viewcontroller etc exist but so far an example of how to use something like Core Graphics/Image to add a shadow has eluded me. My imagination gives me something like

randomImg.CGAddShadow(shadow: true, weight: medium)

A few of the instructions floating around use UIKit which won't work for this MacOS project. Others add a temporary layer for the benefit of the user but don't save the file with the shadow still applied.

The code currently looks like this:

```<code>
            let customImage: (String) -> OCRImage = { code in
                let randomImg = randomImage()
                randomImg.lockFocus()

                randomImg.draw(in: CGRect(origin: CGPoint.zero, size: randomImg.size))

                NSString(string: code).draw(in: CGRect(origin: CGPoint(x: 0, y: -15.5 ), size: randomImg.size), withAttributes: randomFontAttributes())

                randomImg.unlockFocus()

                let data = NSBitmapImageRep(data: randomImg.tiffRepresentation!)?.representation(using: .png, properties: [:])

                 return randomImg
            }

</code>```

The end result is hopefully a modified file with a shadow over it that can be saved and viewed later.

Thanks for any suggestions

答:
The solution I ended up using (A random Sepia filter):</p>

```<code>
            let context = CIContext()

            // Load originalCIImage with contents of the URL
            var imageURL = Bundle.main.urlForImageResource(NSImage.Name(rawValue: "image.png"))
            var originalCIImage = CIImage(contentsOf: imageURL!)

            // Declare func for filter
            func sepiaFilter(_ input: CIImage, intensity: Double) -> CIImage?
            {
                let sepiaFilter = CIFilter(name:"CISepiaTone")
                sepiaFilter?.setValue(input, forKey: kCIInputImageKey)
                sepiaFilter?.setValue(intensity, forKey: kCIInputIntensityKey)
                return sepiaFilter?.outputImage
            }

            // call the filter func on the image
            let sepiaCIImage = sepiaFilter(originalCIImage!, intensity:0.9)

            // change the image from CIImage type to NSImage type
            let rep = NSCIImageRep(ciImage: sepiaCIImage!)
            let filteredImage = NSImage(size: rep.size)
            filteredImage.addRepresentation(rep)

            // change from NSImage type to .png format
            let filterData = NSBitmapImageRep(data: filteredImage.tiffRepresentation!)?.representation(using: .png, properties: [:])

            // save the png file to the desktop
            do {
                try filterData?.write(to: (FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first?.appendingPathComponent("FILTEREDIMAGE.png"))!)
            }
            catch _ {
                print("Adding filter to picture error")
            }

// END Sepia Filter
</code>```

Title: Adding a shadow over an image in Swift

Body:
This project is taken from SwiftOCR by garnele007. There is a NSImage (That is also converted into a .png for saving)in the Swift project that I would like to add a shadow on top of. Several examples of adding a shadow inside the viewcontroller etc exist but so far an example of how to use something like Core Graphics/Image to add a shadow has eluded me. My imagination gives me something like

randomImg.CGAddShadow(shadow: true, weight: medium)

A few of the instructions floating around use UIKit which won't work for this MacOS project. Others add a temporary layer for the benefit of the user but don't save the file with the shadow still applied.

The code currently looks like this:

            let customImage: (String) -> OCRImage = { code in
                let randomImg = randomImage()
                randomImg.lockFocus()

                randomImg.draw(in: CGRect(origin: CGPoint.zero, size: randomImg.size))

                NSString(string: code).draw(in: CGRect(origin: CGPoint(x: 0, y: -15.5 ), size: randomImg.size), withAttributes: randomFontAttributes())

                randomImg.unlockFocus()

                let data = NSBitmapImageRep(data: randomImg.tiffRepresentation!)?.representation(using: .png, properties: [:])

                 return randomImg
            }

The end result is hopefully a modified file with a shadow over it that can be saved and viewed later.

Thanks for any suggestions

Body:
The solution I ended up using (A random Sepia filter):

            let context = CIContext()

            // Load originalCIImage with contents of the URL
            var imageURL = Bundle.main.urlForImageResource(NSImage.Name(rawValue: "image.png"))
            var originalCIImage = CIImage(contentsOf: imageURL!)

            // Declare func for filter
            func sepiaFilter(_ input: CIImage, intensity: Double) -> CIImage?
            {
                let sepiaFilter = CIFilter(name:"CISepiaTone")
                sepiaFilter?.setValue(input, forKey: kCIInputImageKey)
                sepiaFilter?.setValue(intensity, forKey: kCIInputIntensityKey)
                return sepiaFilter?.outputImage
            }

            // call the filter func on the image
            let sepiaCIImage = sepiaFilter(originalCIImage!, intensity:0.9)

            // change the image from CIImage type to NSImage type
            let rep = NSCIImageRep(ciImage: sepiaCIImage!)
            let filteredImage = NSImage(size: rep.size)
            filteredImage.addRepresentation(rep)

            // change from NSImage type to .png format
            let filterData = NSBitmapImageRep(data: filteredImage.tiffRepresentation!)?.representation(using: .png, properties: [:])

            // save the png file to the desktop
            do {
                try filterData?.write(to: (FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first?.appendingPathComponent("FILTEREDIMAGE.png"))!)
            }
            catch _ {
                print("Adding filter to picture error")
            }

// END Sepia Filter


问:
Subtracting months in Java
I am using two string variables to store two different dates. The dates are being stored in this format(May 28, 2019) and I need to find a difference in months.I am not able to figure if I need to first convert these dates to another format before doing the subtraction.

I am using getText() to get these dates from the following location
//span[@class='expiry_date']

答: You can use the DateFormat class to convert your String to a Date object. The easiest way to do addition or subtraction is using the Calendar class. You can convert the Date object to a Calendar object and do the calculation. Keep in mind the Calendar object won't keep the time information, but that doesn't seem to be an issue with your problem.

Title: Subtracting months in Java


问:
Specifying which cells a formula looks into, with a formula
Apologies for the title, unsure of how to ask this question. I am trying to specify the range of data I have in a column on excel, where the range of relevant values change. So to visualize, data could be in cells A1-A4, with zeros below (or data in cells A1-A3, or A1-A25, etc.). By using countif, I can get the number of non-zero values in the changing range, which is useful because it specifies the ending row I want for my range. My issue is how I use this value in a formula. In my head (if I put the countif formula in B1), the range would look something like this: $A$1:$A$(the value from B1) but I am not sure how to put this into practice. Any ideas?</p>

答:
Indirect and Offset are volatile, and while one volatile formula will not cause an issue many will slow down the calcs.  Volatile functions re-calc every time Excel recalcs, whether the data changed or not.

I prefer INDEX to them:

```<code>$A$1:INDEX(A:A,COUNTIF(A:A,">0"))
</code>```

But even COUNTIF() if used too many times can slow down the calcs.  You can use MATCH in this instance:

```<code>$A$1:INDEX(A:A,MATCH(0,A:A,0)-1)
</code>```

Which will now find the first 0 and set the cell above that as the last in the range.

Body:
Indirect and Offset are volatile, and while one volatile formula will not cause an issue many will slow down the calcs.  Volatile functions re-calc every time Excel recalcs, whether the data changed or not.

I prefer INDEX to them:

$A$1:INDEX(A:A,COUNTIF(A:A,">0"))

But even COUNTIF() if used too many times can slow down the calcs.  You can use MATCH in this instance:

$A$1:INDEX(A:A,MATCH(0,A:A,0)-1)

Which will now find the first 0 and set the cell above that as the last in the range.


问:
How to create a function that will apply on a condition
Total noob here so any and all help would be so greatly appreciated.
I need to create a function that will apply to pandas series (zipcode) on a DataFrame based on a conditional value on a different series (country) from the same DataFrame

The function I created

```<code>## function for retrieving only numeric characters
num_pattern = '(\d+)'

def numeric(x,y):
    try :
        a = re.search(x,y).group()
    except:
        a = None
    return a

df['zip'] = df['zip'].apply(lambda x: numeric(num_pattern,x))
</code>```

I need this function to only be passed if the values in my df['country'] column equals 'US'

答:
You can make your apply on your df rows:</p>

```<code>df['zip'] = df.apply(lambda x: numeric(num_pattern,x['zip']) if x['country']=='US' else x['zip'], axis=1)
</code>```

Body:
Total noob here so any and all help would be so greatly appreciated.
I need to create a function that will apply to pandas series (zipcode) on a DataFrame based on a conditional value on a different series (country) from the same DataFrame

The function I created

## function for retrieving only numeric characters
num_pattern = '(\d+)'

def numeric(x,y):
    try :
        a = re.search(x,y).group()
    except:
        a = None
    return a

df['zip'] = df['zip'].apply(lambda x: numeric(num_pattern,x))

I need this function to only be passed if the values in my df['country'] column equals 'US'

Body:
You can make your apply on your df rows:

df['zip'] = df.apply(lambda x: numeric(num_pattern,x['zip']) if x['country']=='US' else x['zip'], axis=1)


问:
Silverlight - Animating Rectangle stroke in Code Behind
I want to be able to Fade In a Border in Code Behind (C#) when the user hovers over a Rectangle in my application.

I've seen a few examples of creating animations in Code behind but cannot get them to work for this instance.

As you can see, I have a MouseEnter event that at the moment, created a border around the object but I want this to Fade In (and out when I have a MouseLeave event)

Can you please help to understand what I need?

private void ImageRect_MouseEnter(object sender, MouseEventArgs e)
        {
            SolidColorBrush blueBrush = new SolidColorBrush();
            blueBrush.Color = SystemColors.HighlightColor;
            ImageRect.StrokeThickness = 3;
            ImageRect.Stroke = blueBrush;
        }

Thanks very much

Shaun

答:
try to use this when you want to  create storyboard in code behind.</p>

```<code>Storyboard strybrd = new Storyboard();

            var mycolor = new ColorAnimation { };

            Storyboard.SetTarget(mycolor, ImageRect);
            Storyboard.SetTargetProperty(mycolor, new PropertyPath("(Rectangle.Stroke).(SolidColorBrush.Color)"));
            mycolor.To = Color.FromArgb(255, 150, 150, 151);

            strybrd.Begin();
</code>```

Body:
try to use this when you want to  create storyboard in code behind.

Storyboard strybrd = new Storyboard();

            var mycolor = new ColorAnimation { };

            Storyboard.SetTarget(mycolor, ImageRect);
            Storyboard.SetTargetProperty(mycolor, new PropertyPath("(Rectangle.Stroke).(SolidColorBrush.Color)"));
            mycolor.To = Color.FromArgb(255, 150, 150, 151);

            strybrd.Begin();


问:
How to I resolve a deprecation issue?
I'm creating Ansible Playbook for IT Automation.

This is the console output, I am getting:

```<code>Apache web server.

web.yml
- hosts: 192.168.1.80
  remote_user: ksouthall
  become: yes
  become_method: sudo

  tasks:
  - name: Install Apache
    apt:
      name: apache2
      update_cache: yes
  - name: Copying the demo file
    template: src=/etc/ansible/index.html dest=/var/www/html
              owner=www-data group=www-data mode=0644

ansible-playbook web.yml -f 1 --ask-become-pass
BECOME password:
[DEPRECATION WARNING]: The TRANSFORM_INVALID_GROUP_CHARS settings is set to allow bad characters
in group names by default, this will change, but still be user configurable on deprecation. This
feature will be removed in version 2.10. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
 [WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see
details

 [WARNING]: Could not match supplied host pattern, ignoring: 192.168.1.80

PLAY [192.168.1.80] ******************************************************************************
skipping: no hosts matched

PLAY RECAP ******************************************************************************
</code>```

Question: Is the BECOME password my system password?

答:
Most likely you have dashes in your inventory group names.

Check your inventory file (default is /etc/ansible/hosts) and remove invalid characters from the group names, characters which are not letters, digits or underscore are considered invalid.
(Also group names starting with digits are invalid)

See:

https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#creating-valid-variable-names

https://docs.ansible.com/ansible/latest/reference_appendices/config.html#transform-invalid-group-chars

https://github.com/ansible/ansible/blob/v2.8.0/lib/ansible/config/base.yml#L1489

https://github.com/ansible/ansible/blob/v2.8.0/lib/ansible/constants.py#L122

Title: How to I resolve a deprecation issue?

Body:
I'm creating Ansible Playbook for IT Automation.

This is the console output, I am getting:

Apache web server.

web.yml
- hosts: 192.168.1.80
  remote_user: ksouthall
  become: yes
  become_method: sudo

  tasks:
  - name: Install Apache
    apt:
      name: apache2
      update_cache: yes
  - name: Copying the demo file
    template: src=/etc/ansible/index.html dest=/var/www/html
              owner=www-data group=www-data mode=0644

ansible-playbook web.yml -f 1 --ask-become-pass
BECOME password:
[DEPRECATION WARNING]: The TRANSFORM_INVALID_GROUP_CHARS settings is set to allow bad characters
in group names by default, this will change, but still be user configurable on deprecation. This
feature will be removed in version 2.10. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
 [WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see
details

 [WARNING]: Could not match supplied host pattern, ignoring: 192.168.1.80

PLAY [192.168.1.80] ******************************************************************************
skipping: no hosts matched

PLAY RECAP ******************************************************************************

Question: Is the BECOME password my system password?


问:
What's the meaning of these two lines of PHP code?
I'm currently programming a script to login the user if the user types the right information in the Password- and Login-field on a login page. The script is working just fine, but I don't actually know what these two lines of code means and does for the overall user experience.

I'm soon going to an exam where I have to explain the meaning of the code, and it would be absolutely amazing if you guys helped me out by explaining what the two lines of code does below. This is the full script:

```<code><?php

require('db_connect.php');

if (isset($_POST['user_id']) and isset($_POST['user_pass'])) {

    $username = $_POST['user_id'];
    $password = $_POST['user_pass'];

    $query = "SELECT * FROM dataforlogin WHERE username='$username' and password='$password'";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);

    if ($count == 1) {

        header("location: ../staudal/dashboard/index.php");

    } else {

        echo "Fail";

  }
}

?>
</code>```

The two lines of code that I'm having trouble understanding is:

```<code>$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
</code>```

What do they do and why?

答:
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));

This executes the MySQL query, such as SELECT * FROM table WHERE id = ? and then saves the results. Or it returns an error message if the query fails.

$count = mysqli_num_rows($result);

This just returns the number of rows your query returned.

Body:
I'm currently programming a script to login the user if the user types the right information in the Password- and Login-field on a login page. The script is working just fine, but I don't actually know what these two lines of code means and does for the overall user experience.

I'm soon going to an exam where I have to explain the meaning of the code, and it would be absolutely amazing if you guys helped me out by explaining what the two lines of code does below. This is the full script:

<?php

require('db_connect.php');

if (isset($_POST['user_id']) and isset($_POST['user_pass'])) {

    $username = $_POST['user_id'];
    $password = $_POST['user_pass'];

    $query = "SELECT * FROM dataforlogin WHERE username='$username' and password='$password'";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);

    if ($count == 1) {

        header("location: ../staudal/dashboard/index.php");

    } else {

        echo "Fail";

  }
}

?>

The two lines of code that I'm having trouble understanding is:

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);

What do they do and why?


问:
Access Spring beans from Alfresco integration test context
Now that Alfresco integration tests of custom modules are run using Docker, I wonder how to make additional Spring beans available in this context and how to access existing Spring beans in test classes.

Until Alfresco 5.x, I used to annotate the test class with

```<code>@ContextConfiguration("classpath:alfresco/application-context.xml")
</code>```

This made the Spring context available. To make Spring beans from this context available in the test class, I annotated members like this:

```<code>@Autowired
@Qualifier("authenticationComponent")
private AuthenticationComponent authenticationComponent;
</code>```

In addition I was able to define additional Spring beans in src/test/resources/alfresco/extension/test-context.xml.

Is this the approach to use when writing integration tests for 6.x and Docker?

At least the annotation org.springframework.test.context.ContextConfiguration is no longer included in a module build using the Maven 4.0.0 SDK archetype.

This blog post talks about the above mentioned annotations. But the dependencies pulled in by the pom.xml created from the SDK 4 archetype don't include these annotations.

A different approach seems to be to only use

```<code>@RunWith(value = AlfrescoTestRunner.class)
</code>```

on the integration test class. But how do I get the Spring beans like nodeService injected into it? And how do I declare and make available additional Spring beans which are part of my custom module and required by the integration test to succeed?

答:
You can get the Spring context via AlfrescoTestRunner as follows:

@Before
public void setUp() {
    this.nodeService = (NodeService) super.getApplicationContext().getBean("nodeService");
}
```

<p>I do the same with custom beans:
<code>super.getApplicationContext().getBean(MyType.class);</code></p>

<p>Since the integration tests run in the repository, all of the Spring context is automatically available.</p>

<p>Note that your test class needs to extend <code>AbstractAlfrescoIT</code> for this to work.</p>

<p>An example class may look like this:</p>

<pre class="lang-java prettyprint-override"><code>package nl.open.mystuff;

import org.alfresco.rad.test.AbstractAlfrescoIT;
import org.alfresco.rad.test.AlfrescoTestRunner;
import org.alfresco.service.cmr.repository.NodeService;

@RunWith(value = AlfrescoTestRunner.class)
public class MyCustomIT extends AbstractAlfrescoIT {

    private NodeService nodeService;
    private MyType myType;

    @Before
    public void setUp() {
        this.nodeService = (NodeService) super.getApplicationContext().getBean("NodeService");
        this.myType = super.getApplicationContext().getBean(MyType.class);
    }
}

</code>```

In Alfresco SDK 3, you can even add your own Spring XML files under src/test/resources/alfresco/extension/*-context.xml. I imagine this still works, but I haven't tried it with SDK 4 myself.

Body:
Now that Alfresco integration tests of custom modules are run using Docker, I wonder how to make additional Spring beans available in this context and how to access existing Spring beans in test classes.

Until Alfresco 5.x, I used to annotate the test class with

@ContextConfiguration("classpath:alfresco/application-context.xml")

This made the Spring context available. To make Spring beans from this context available in the test class, I annotated members like this:

@Autowired
@Qualifier("authenticationComponent")
private AuthenticationComponent authenticationComponent;

In addition I was able to define additional Spring beans in src/test/resources/alfresco/extension/test-context.xml.

Is this the approach to use when writing integration tests for 6.x and Docker?

At least the annotation org.springframework.test.context.ContextConfiguration is no longer included in a module build using the Maven 4.0.0 SDK archetype.

This blog post talks about the above mentioned annotations. But the dependencies pulled in by the pom.xml created from the SDK 4 archetype don't include these annotations.

A different approach seems to be to only use

@RunWith(value = AlfrescoTestRunner.class)

on the integration test class. But how do I get the Spring beans like nodeService injected into it? And how do I declare and make available additional Spring beans which are part of my custom module and required by the integration test to succeed?

Body:
You can get the Spring context via AlfrescoTestRunner as follows:

@Before
public void setUp() {
    this.nodeService = (NodeService) super.getApplicationContext().getBean("nodeService");
}

I do the same with custom beans:
super.getApplicationContext().getBean(MyType.class);

Since the integration tests run in the repository, all of the Spring context is automatically available.

Note that your test class needs to extend AbstractAlfrescoIT for this to work.

An example class may look like this:

package nl.open.mystuff;

import org.alfresco.rad.test.AbstractAlfrescoIT;
import org.alfresco.rad.test.AlfrescoTestRunner;
import org.alfresco.service.cmr.repository.NodeService;

@RunWith(value = AlfrescoTestRunner.class)
public class MyCustomIT extends AbstractAlfrescoIT {

    private NodeService nodeService;
    private MyType myType;

    @Before
    public void setUp() {
        this.nodeService = (NodeService) super.getApplicationContext().getBean("NodeService");
        this.myType = super.getApplicationContext().getBean(MyType.class);
    }
}

In Alfresco SDK 3, you can even add your own Spring XML files under src/test/resources/alfresco/extension/*-context.xml. I imagine this still works, but I haven't tried it with SDK 4 myself.


问:
"Object is not defined" in TabView
Trying to get this to work in Qt version 5.9

It seems that whenever I create an object within a QML Tab it is unrecognizable by the parent object (or any of the parent's parents, and so on). How do I get the parent objects to recognize the object in the Tab? Or, if impossible, then what is a work-around to call the function of the object within the Tab?

I've boiled down the code to this simplified example:

```<code>import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    Rectangle {
        id: myFunctionCaller

        Component.onCompleted: {
            myParent.myFunction();
            myChild.myFunction();
            myGrandChild.myFunction();
        }
    }

    TabView {
        id: myParent
        property Rectangle grandchild: myGrandChild
        onGrandchildChanged: console.log("Parent recognizes GrandChild");

        function myFunction() {
            console.log("I'm the Parent");
        }

        Tab{
            id: myChild
            property Rectangle grandchild: myGrandChild
            onGrandchildChanged: console.log("Child recognizes GrandChild");

            function myFunction() {
                console.log("I'm the Child");
            }

            Rectangle {
                id: myGrandChild
                function myFunction() {
                    console.log("I'm the GrandChild");
                }
            }
        }
    }
}
</code>```

I expect this output:

```<code>I'm the Parent
I'm the Child
I'm the GrandChild
Parent recognizes Grandchild
Child recognizes Grandchild
</code>```

However, I get this output:

```<code>I'm the Parent
I'm the Child
ReferenceError: myGrandChild is not defined.
ReferenceError: myGrandChild is not defined.
ReferenceError: myGrandChild is not defined.
</code>```

The error occurs on these lines:

```<code>myGrandChild.myFunction();
onGrandchildChanged: console.log("Parent recognizes GrandChild");
onGrandchildChanged: console.log("Child recognizes GrandChild");
</code>```

答:
The Tab is a subclass of Loader, so the Rectangle is not created until the Tab becomes active.

Tabs are lazily loaded; only tabs that have been made current (for example, by clicking on them) will have valid content. You can force loading of tabs by setting the active property to true

Thus the id: myGrandChild is only available within the (source)Component automatically created in the Loader.

The solution is, to activate the Tab and address the child with myChild.item

(Not tested)

Title: "Object is not defined" in TabView

Body:
Trying to get this to work in Qt version 5.9

It seems that whenever I create an object within a QML Tab it is unrecognizable by the parent object (or any of the parent's parents, and so on). How do I get the parent objects to recognize the object in the Tab? Or, if impossible, then what is a work-around to call the function of the object within the Tab?

I've boiled down the code to this simplified example:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    Rectangle {
        id: myFunctionCaller

        Component.onCompleted: {
            myParent.myFunction();
            myChild.myFunction();
            myGrandChild.myFunction();
        }
    }

    TabView {
        id: myParent
        property Rectangle grandchild: myGrandChild
        onGrandchildChanged: console.log("Parent recognizes GrandChild");

        function myFunction() {
            console.log("I'm the Parent");
        }

        Tab{
            id: myChild
            property Rectangle grandchild: myGrandChild
            onGrandchildChanged: console.log("Child recognizes GrandChild");

            function myFunction() {
                console.log("I'm the Child");
            }

            Rectangle {
                id: myGrandChild
                function myFunction() {
                    console.log("I'm the GrandChild");
                }
            }
        }
    }
}

I expect this output:

I'm the Parent
I'm the Child
I'm the GrandChild
Parent recognizes Grandchild
Child recognizes Grandchild

However, I get this output:

I'm the Parent
I'm the Child
ReferenceError: myGrandChild is not defined.
ReferenceError: myGrandChild is not defined.
ReferenceError: myGrandChild is not defined.

The error occurs on these lines:

myGrandChild.myFunction();
onGrandchildChanged: console.log("Parent recognizes GrandChild");
onGrandchildChanged: console.log("Child recognizes GrandChild");


问:
Incorrect type. Expected "object"
I am having this json but Visual Studio Code gives me the warning  in the title.

```<code>[
    {
      "title": "Book A",
      "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ6B1bizZf6gt_7vtUZXx0cPf81u07iJf9ZPBMPn5kM_5pyIRnE",
      "description": "Cool book!",
      "price": "10",
      "id": "0.9910457947149673"
    },
    {
      "title": "Book B",
      "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ6B1bizZf6gt_7vtUZXx0cPf81u07iJf9ZPBMPn5kM_5pyIRnE",
      "description": "Nice!",
      "price": "12",
      "id": "0.3677736742556723"
    },
    {
      "id": "0.2599869075653567",
      "title": "Αχίλλιου Πόλης",
      "imageUrl": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMSERUTEhIWFhUXGRgZGBgWGBgYHRYZGBsaGB4YGxkYHSggGBolIBgXITEhJSkrLi4uGB8zODMtNygtLisBCgoKDg0OGBAQGi0dHh8rKy0tLSsrLS0tLSsrKy0tKy0rLS0tLS0tLS0tLS0tLS0tLS03LS0tLTcrLTc3NzcrLf/AABEIAOEA4AMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAABQQGAgMHAQj/xABGEAABAwEGBAMEBggFAgcBAAABAAIRAwQFEiExQQZRYXETIpEygbHBBxRCUqHwIzM0YnJz0eEVJILC8RayNURTVIOSoiX/xAAYAQEBAQEBAAAAAAAAAAAAAAAAAQIDBP/EACERAQEAAgIDAAMBAQAAAAAAAAABAhESIQMxQSJRkTIT/9oADAMBAAIRAxEAPwC/IQhUCEIQCELCvWaxpe8hrWiSTsEGaFjTeHAOaZBEgjcHdZIBCEIBCEIBCEIBCEIBCEIBCEIBCEIBCEIBCEIBCEIBKbzv+lQfgdLjEnDEN7k79Ej4r4mdTqOoU3YSMIJGpxbA7Kr2yyP8NgY5jsbnE43VJAxHzZHTJB0SzcR0H6OcO7T8VNpXhSdo9use/wB65lcdpfSfUpOmWhj83NIe06Fpw/hOyd0ra7EQ9hJfu1khw2g4vL26oL2qjx1UqVm/VKAlxaalToxuje52Vmr120qRe4w1jZPQAJHwq9pa+01XsFSucRBc2WsGTW68vis39OuHV5If0bXv4tnNFx81LIdWHT00VwXK7RUF3XnjY4Gk8ycJBAY45j3HNdTa4ESDkcx2KY34vmx1dz6UXxxHRspiqKgGzgwlp6A81sua/aVqzpB5bn5i0gZbTzUy8LEyvTdSqNlrhB/r3XNLJba10Wh9J4L6TgSP3vuuB2OxUtsMMMc5qe11tvFdClU8J7aofsPDJxdRGoUm237TpUxUf",
      "description": "A cool book. Everyone should buy it!",
      "price": "10"
    },
    {
      "id": "0.8862598606325078",
      "title": "xvbxb",
      "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ6B1bizZf6gt_7vtUZXx0cPf81u07iJf9ZPBMPn5kM_5pyIRnE",
      "description": "xvcxv",
      "price": "20"
    }
]
</code>```

Why?

答:
The top level JSON is historically expected be an object. Not an array or primitive.

In practice the enforcement of that rule varies. VSCode is reminding you that you're not looking at JSON in the most interoperable sense.

Edit:
There are various RFCs which define JSON, the historical ones are usually stricter, but have nowdays been mostly superseded.

I am at a loss as to finding an official JSON definition that enforces the 'top level item is an object' rule. I suspect it's just been the reality with regards to browser support, and other parsers for a while, so it became a de-facto standard, before being properly standardized.

See for example:
rfc4627 rfc7159 rfc8259

Title: Incorrect type. Expected "object"

Body:
I am having this json but Visual Studio Code gives me the warning  in the title.

[
    {
      "title": "Book A",
      "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ6B1bizZf6gt_7vtUZXx0cPf81u07iJf9ZPBMPn5kM_5pyIRnE",
      "description": "Cool book!",
      "price": "10",
      "id": "0.9910457947149673"
    },
    {
      "title": "Book B",
      "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ6B1bizZf6gt_7vtUZXx0cPf81u07iJf9ZPBMPn5kM_5pyIRnE",
      "description": "Nice!",
      "price": "12",
      "id": "0.3677736742556723"
    },
    {
      "id": "0.2599869075653567",
      "title": "Αχίλλιου Πόλης",
      "imageUrl": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMSERUTEhIWFhUXGRgZGBgWGBgYHRYZGBsaGB4YGxkYHSggGBolIBgXITEhJSkrLi4uGB8zODMtNygtLisBCgoKDg0OGBAQGi0dHh8rKy0tLSsrLS0tLSsrKy0tKy0rLS0tLS0tLS0tLS0tLS0tLS03LS0tLTcrLTc3NzcrLf/AABEIAOEA4AMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAABQQGAgMHAQj/xABGEAABAwEGBAMEBggFAgcBAAABAAIRAwQFEiExQQZRYXETIpEygbHBBxRCUqHwIzM0YnJz0eEVJILC8RayNURTVIOSoiX/xAAYAQEBAQEBAAAAAAAAAAAAAAAAAQIDBP/EACERAQEAAgIDAAMBAQAAAAAAAAABAhESIQMxQSJRkTIT/9oADAMBAAIRAxEAPwC/IQhUCEIQCELCvWaxpe8hrWiSTsEGaFjTeHAOaZBEgjcHdZIBCEIBCEIBCEIBCEIBCEIBCEIBCEIBCEIBCEIBCEIBKbzv+lQfgdLjEnDEN7k79Ej4r4mdTqOoU3YSMIJGpxbA7Kr2yyP8NgY5jsbnE43VJAxHzZHTJB0SzcR0H6OcO7T8VNpXhSdo9use/wB65lcdpfSfUpOmWhj83NIe06Fpw/hOyd0ra7EQ9hJfu1khw2g4vL26oL2qjx1UqVm/VKAlxaalToxuje52Vmr120qRe4w1jZPQAJHwq9pa+01XsFSucRBc2WsGTW68vis39OuHV5If0bXv4tnNFx81LIdWHT00VwXK7RUF3XnjY4Gk8ycJBAY45j3HNdTa4ESDkcx2KY34vmx1dz6UXxxHRspiqKgGzgwlp6A81sua/aVqzpB5bn5i0gZbTzUy8LEyvTdSqNlrhB/r3XNLJba10Wh9J4L6TgSP3vuuB2OxUtsMMMc5qe11tvFdClU8J7aofsPDJxdRGoUm237TpUxUf",
      "description": "A cool book. Everyone should buy it!",
      "price": "10"
    },
    {
      "id": "0.8862598606325078",
      "title": "xvbxb",
      "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ6B1bizZf6gt_7vtUZXx0cPf81u07iJf9ZPBMPn5kM_5pyIRnE",
      "description": "xvcxv",
      "price": "20"
    }
]

Why?


问:
How to include images with html-webpack-plugin + twig-loader?
I'm trying to include an image in my twig template just like simple  tag, but it doesn't want to include. For build, I use HtmlWebpackPlugin and twig-loader;
But if I do the same with html-loader and html template - it works fine.
How to do it right with twig-loader?

my webpack-config:

```<code>const path              = require( 'path' );
const HtmlWebpackPlugin = require( 'html-webpack-plugin' );

const PATHS = {
    source: path.join( __dirname, './source' ),
    build:  path.join( __dirname, './build' )
};

module.exports = {
    entry:   `${ PATHS.source }/index.js`,
    output: {
        path:     PATHS.build,
        filename: 'webpack.bundle.js'
    },
    module:  {
        rules: [
            {
                test:   /\.twig/,
                loader: 'twig-loader'
            },
            {
                test: /.*\.(gif|png|jpe?g)$/i,
                use:  [
                    {
                        loader: 'file-loader?name=[name].[ext]'
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin( {
            filename: 'index.html',
            template: `${PATHS.source}/index.twig`,
        } )
    ],
};
</code>```

my twig template:

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <img src="./chuck-norris.jpg" alt="">
</body>
</html>
</code>```

my package.json:

```<code>{
  "name": "htmlWebpackPlugin-twigLoader",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "author": "evisotskiy",
  "license": "ISC",
  "devDependencies": {
    "file-loader": "^0.11.2",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.30.1",
    "twig-loader": "^0.3.1",
    "webpack": "^3.6.0"
  }
}
</code>```

my project's structure:

```<code>.
├── webpack.config.js
├── package.json
├── source
|   ├──index.twig
|   ├──index.js (empty)
|   ├──chuck-norris.jpg
</code>```

and when I execute npm run build I get dir:

```<code>├── build
|   ├──index.html
|   ├──webpack.bundle.js
</code>```

without chuck-norris.jpg

And when I use html-loader instead twig-loader and html-template instead twig-template - image builds fine. But for my project, I need to use twig templates.
How to do it right with twig-loader?

答:
If it's any help, I fixed this very same problem by simply changing the loader that processes the twig template files and adding "html-loader".

This would be the change:

```<code>{
    test:   /\.twig$/,
    loader: 'twig-loader'
}
</code>```

to

```<code>{
    test: /\.twig$/,
    exclude: /node_modules/,
    use: [
      'html-loader',
      'twig-html-loader'
    ]
}
</code>```

Of course, you must install those loaders previously if you didn't do it yet.

```<code>npm install twig-html-loader html-loader --save-dev
</code>```

Henceforth, the images will be processed ;)

Body:
I'm trying to include an image in my twig template just like simple  tag, but it doesn't want to include. For build, I use HtmlWebpackPlugin and twig-loader;
But if I do the same with html-loader and html template - it works fine.
How to do it right with twig-loader?

my webpack-config:

const path              = require( 'path' );
const HtmlWebpackPlugin = require( 'html-webpack-plugin' );

const PATHS = {
    source: path.join( __dirname, './source' ),
    build:  path.join( __dirname, './build' )
};

module.exports = {
    entry:   `${ PATHS.source }/index.js`,
    output: {
        path:     PATHS.build,
        filename: 'webpack.bundle.js'
    },
    module:  {
        rules: [
            {
                test:   /\.twig/,
                loader: 'twig-loader'
            },
            {
                test: /.*\.(gif|png|jpe?g)$/i,
                use:  [
                    {
                        loader: 'file-loader?name=[name].[ext]'
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin( {
            filename: 'index.html',
            template: `${PATHS.source}/index.twig`,
        } )
    ],
};

my twig template:

<!doctype html>

    <meta charset="UTF-8">
    <title>Document</title>

my package.json:

{
  "name": "htmlWebpackPlugin-twigLoader",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "author": "evisotskiy",
  "license": "ISC",
  "devDependencies": {
    "file-loader": "^0.11.2",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.30.1",
    "twig-loader": "^0.3.1",
    "webpack": "^3.6.0"
  }
}

my project's structure:

.
├── webpack.config.js
├── package.json
├── source
|   ├──index.twig
|   ├──index.js (empty)
|   ├──chuck-norris.jpg

and when I execute npm run build I get dir:

├── build
|   ├──index.html
|   ├──webpack.bundle.js

without chuck-norris.jpg

And when I use html-loader instead twig-loader and html-template instead twig-template - image builds fine. But for my project, I need to use twig templates.
How to do it right with twig-loader?

Body:
If it's any help, I fixed this very same problem by simply changing the loader that processes the twig template files and adding "html-loader".

This would be the change:

{
    test:   /\.twig$/,
    loader: 'twig-loader'
}

to

{
    test: /\.twig$/,
    exclude: /node_modules/,
    use: [
      'html-loader',
      'twig-html-loader'
    ]
}

Of course, you must install those loaders previously if you didn't do it yet.

npm install twig-html-loader html-loader --save-dev

Henceforth, the images will be processed ;)


问:
Disable or Force Close Mobile Keyboard
I have deployed my UI5 project in Fiori Launchpad (Fiori Client) with mobile Barcode Scanner (Zebra TC20). We are using input to capture the barcode value in the application. When we focus on input field by default soft keyboard of mobile device opens. Please give me some suggestion how to disable the soft keyboard in mobile device.

Fiori Mobile Disable Keyboard Input

```<code>_focusEannr: function() {
            var oEan11 = this.byId("iEan11");

        oEan11.addEventDelegate({

            onfocusin: function(e) {
                try {
                debugger;
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    blur();
                } catch (err) {
                    alert(err.toString());
                }
            },
            onfocus: function(oEvent) {
                debugger;
            }
        });
    },
</code>```

答:
Make the input field read-only by setting editable="false"

<Input value="{myBinding}" editable="false" />
```

<p><img src="https://i.stack.imgur.com/l027q.png" alt="ui5 non-editable input field"></p>

<blockquote>
  <p><em>editable:</em> Defines whether the control can be modified by the user or not. <strong>Note:</strong> A user can tab to non-editable control, highlight it, and copy the text from it.</p>
</blockquote>

<p>API reference: <code>sap.m.InputBase#setEditable</code></p>

<hr>

<p>Alternatively, you can close soft keyboard manually with the following method:</p>

<pre class="lang-js prettyprint-override"><code>sap.ui.require(["sap/m/library"], sapMLib => sapMLib.closeKeyboard());
</code>```

API reference: sap.m.closeKeyboard

Title: Disable or Force Close Mobile Keyboard

Body:
I have deployed my UI5 project in Fiori Launchpad (Fiori Client) with mobile Barcode Scanner (Zebra TC20). We are using input to capture the barcode value in the application. When we focus on input field by default soft keyboard of mobile device opens. Please give me some suggestion how to disable the soft keyboard in mobile device.

Fiori Mobile Disable Keyboard Input

_focusEannr: function() {
            var oEan11 = this.byId("iEan11");

        oEan11.addEventDelegate({

            onfocusin: function(e) {
                try {
                debugger;
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    blur();
                } catch (err) {
                    alert(err.toString());
                }
            },
            onfocus: function(oEvent) {
                debugger;
            }
        });
    },

Body:
Make the input field read-only by setting editable="false"

<Input value="{myBinding}" editable="false" />

editable: Defines whether the control can be modified by the user or not. Note: A user can tab to non-editable control, highlight it, and copy the text from it.

API reference: sap.m.InputBase#setEditable

Alternatively, you can close soft keyboard manually with the following method:

sap.ui.require(["sap/m/library"], sapMLib => sapMLib.closeKeyboard());

API reference: sap.m.closeKeyboard


问:
How do I perform a simple one-statement SQL search across tables?
Suppose that two tables exist: users and groups.

How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text?

The result of the search must distinguish between the two types.

答:
If you use "UNION ALL" then the db doesn't try to remove duplicates - you won't have duplicates between the two queries anyway (since the first column is different), so UNION ALL will be faster.

(I assume that you don't have duplicates inside each query that you want to remove)

OwnerDisplayName: Bobby Jack

OwnerDisplayName: hamishmcn


问:
How to experiment with Xcode on OS X 10.4x
I'd like to start experimenting with Cocoa, Objective-C and Xcode, but the only Apple computer I own is an old PowerBook with OS X 10.4.7 installed and as far as I can tell I would have to buy and install OS X 10.5 (Leopard I think) just to be able to install Xcode 3.2 - the currently available version. The thing is I'm a Windows developer and I don't want to have to upgrade this barely functional Mac laptop just to be able to play around with Xcode. So, I'm wondering is there any way that I can download some older 2.x version of Xcode that will run on OS X 10.4.7?</p>

答:
Create a free account at Apple Developer Connection at http://connect.apple.com (if you haven't already) and in the Developer Tools subsection of Downloads (about halfway down) you will find:

Xcode 2.5 Developer Tools

Xcode 2.5 is an update release of
  Xcode developer tools, providing bug
  fixes over Xcode 2.4.1. Xcode 2.5 can
  be installed on Tiger (Mac OS X 10.4)
  ...

LastEditorDisplayName: gs

OwnerDisplayName: Stuart Dunkeld


问:
double js not working
Can someone please tell me how to get two times #videoContainer on the same page:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>My Videos</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<script type="text/javascript">
function loadVideo(playerUrl, autoplay) {
    swfobject.embedSWF(
        playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
        (autoplay?1:0)+'&version=3', 'player', '585', '355', '9.0.0', false,
        false, {allowfullscreen: 'true'});

        /*Parse the facebook like button*/
        $('#like').html('<fb:like href="'+playerUrl+'" layout="button_count" show_faces="false" width="65" action="like" font="segoe ui" colorscheme="light" />')
        if (typeof FB  != "undefined"){
            FB.XFBML.parse(document.getElementById('like'))
        }
}

function showMyVideos(data) {
    var feed = data.feed;
    var entries = feed.entry || [];
    var html = ['<ul class="videos">'];
    for (var i = 0; i < entries.length; i++) {
        var entry = entries[i];
        var title = entry.title.$t.substr(0, 20);
        var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
        var playerUrl = entries[i].media$group.media$content[0].url;
        var videoId = playerUrl.substr(playerUrl.indexOf('v/')+2, 11);
        playerUrl = "http://www.youtube.com/v/" + videoId;
        html.push('<li onclick="loadVideo(\'', playerUrl, '\', true)">',
                  '<img src="',
                  thumbnailUrl, '" width="94" height="58"/>', '</span></li>');
    }
    html.push('</ul>');
    document.getElementById('videos').innerHTML = html.join('');
    if (entries.length > 0) {
        loadVideo(entries[0].media$group.media$content[0].url, false);
    }
}

$(function(){
      $.ajax({
            type: "GET",
            url: "http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?time=today&alt=json-in-script&max-results=5&format=5",
            cache: false,
            dataType:'jsonp',
            success: function(data){
                showMyVideos(data);
          },
            error: function(XMLHttpRequest, textStatus, errorThrown, data){
                alert("Not able to fetch the data due to feed unavailability!!!");
            }
        });
})
</script>

<style>

body{
    background:#fff;
    color:#c0c0c0;
    font-family:Arial, Helvetica, sans-serif;
    font-size:100%;
    line-height:1.125em;
    }

#videoContainer {
    font-size:.75em;
    overflow:hidden;
    position:absolute;
      left:0px;
      top:0px;
      margin-left:40px;
      margin-top:5px;
    }

#playerContainer {

    }

#like {
    height: 15px;
    margin-top: 10px;
    text-align: right;

    }

object {

  -moz-box-shadow: 5px 5px 5px #ccc;
  -webkit-box-shadow: 5px 5px 5px #ccc;
  box-shadow: 5px 5px 5px #ccc;
}

ul.videos {
    list-style: none;
    margin-bottom: 1em;
    margin-left: 0em;
    padding-left : 0em;

    }
    ul.videos li {
        cursor: pointer;
        display: inline;
        margin-bottom: 1em;
        padding-right: 28px;
    }

img {
 -moz-box-shadow: 0px 0px 0px #ccc;
  -webkit-box-shadow: 0px 0px 0px#ccc;
  box-shadow: 0px 0px 0px #ccc;
}

img:hover {
  -moz-box-shadow: 5px 5px 5px #ccc;
  -webkit-box-shadow: 5px 5px 5px #ccc;
  box-shadow: 5px 5px 5px #ccc;

}

</style>

</head>
<body>
<div id="videoContainer">

    <div id="playerContainer">
        <div id="player"></div>

        <div id="like"></div>
        <div id="videos"></div>

    </div>
        </div>

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

I tried it myself and it worked exept for the large video player which only displayed one time.

答:
First, add another container:

```<code><div id="player"></div>
<div id="player2"></div>
</code>```

And load the flash into the proper container according to function argument:

```<code>function loadVideo(playerUrl, autoplay, containerId) {
   if (typeof containerId == "undefined")
      containerId = "player";

   swfobject.embedSWF(
       playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
       (autoplay?1:0)+'&version=3', containerId, '585', '355', '9.0.0', false,
       false, {allowfullscreen: 'true'});

   ...
}
</code>```

Now call the function like this to load the video in the second container:

```<code>onclick="loadVideo(\'', playerUrl, '\', true, 'player2')"
</code>```

Title: double js not working

Body:
Can someone please tell me how to get two times #videoContainer on the same page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>My Videos</title>

I tried it myself and it worked exept for the large video player which only displayed one time.

Body:
First, add another container:

<div id="player"></div>
<div id="player2"></div>

And load the flash into the proper container according to function argument:

function loadVideo(playerUrl, autoplay, containerId) {
   if (typeof containerId == "undefined")
      containerId = "player";

   swfobject.embedSWF(
       playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
       (autoplay?1:0)+'&version=3', containerId, '585', '355', '9.0.0', false,
       false, {allowfullscreen: 'true'});

   ...
}

Now call the function like this to load the video in the second container:

onclick="loadVideo(\'', playerUrl, '\', true, 'player2')"


问:
Parsing XML Response In GateWayScript
Hi i am new to API connect ... i have a use case where i have to merge responses coming from two endpoints in XML format based on certain conditions.

My flow in the assemble section is like this

1) INVOKE

(i make my
first service call
and capture the response
in a custom 'Response
object varibale' -XMLResponse1

2) INVOKE

(i make my
second service call
and here i am not using any
custom 'Response object varibale'
Instead i am using apim.getvaribale('message.body') to get the response

3)GATEWAYSCRIPT

Here i want to write my script for parsing the xml and merging the two responses
and send back the merged response to the consumer

I observed that  the xml response is not getting captured in a  custom Response object variable when i try to capture it like below

var test1= apim.getvariable('XMLResponse1');
test1.item(0).childNodes

it throws me an exception like this

test1.item is not a function

now for the second response like below where i am not capturing the response  in a custom Response object variable it works well

var test2= apim.getvariable('message.body');

My question:

1)How do i capture the xml responses in a custom Response object variable?

2)How can i parse the response into a javascript object? are there any libraries supported in api connect?

答:
Why do you want to merge them in a GatewayScript node??

You could merge them in a mapping node, in wich you have 2 variables as input (refered to the output objects of your invokes)  and one XML object as output...

If you have to apply some conditions or comparisons, you could do them in the code part of the mapping nodes

Title: Parsing XML Response In GateWayScript


问:
How to speed up grep/awk command?
I am going to process the text file (>300 GB) and split it into small text files (~1 GB). I want to speed up grep/awk commands.

I need to grep the line which has values on column b, here are my ways:

```<code># method 1:
awk -F',' '$2 ~ /a/ { print }' input

# method 2:
grep -e ".a" < inpuy
</code>```

Both of ways cost 1min for each file. So how can I speed up this operation?

Sample of input file:

```<code>a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
9,,3,12
10,0,34,45
24,4a83944,3,22
45,,435,34
</code>```

Expected output file:

```<code>a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
24,4a83944,3,22
</code>```

答:
I suspect your real problem is that you're calling awk repeatedly (probably in a loop), once per set of values of $2 and generating an output file each time, e.g.:

```<code>awk -F, '$2==""' input > novals
awk -F, '$2!=""' input > yesvals
etc.
</code>```

Don't do that as it's very inefficient since it's reading the whole file on every iteration. Do this instead:

```<code>awk '{out=($2=="" ? "novals" : "yesvals")} {print > out}' input
</code>```

That will create all of your output files with one call to awk. Once you get past about 15 output files it would require GNU awk for internal handling of open file descriptors or you need to add close(out)s when $2 changes and use >> instead of >:

```<code>awk '$2!=prev{close(out); out=($2=="" ? "novals" : "yesvals"); prev=$2} {print >> out}' input
</code>```

and that would be more efficient if you sorted your input file first with (requires GNU sort for -s for stable sort if you care about preserving input ordering for the unique $2 values):

```<code>sort -t, -k2,2 -s
</code>```

Title: How to speed up grep/awk command?

Body:
I am going to process the text file (>300 GB) and split it into small text files (~1 GB). I want to speed up grep/awk commands.

I need to grep the line which has values on column b, here are my ways:

# method 1:
awk -F',' '$2 ~ /a/ { print }' input

# method 2:
grep -e ".a" < inpuy

Both of ways cost 1min for each file. So how can I speed up this operation?

Sample of input file:

a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
9,,3,12
10,0,34,45
24,4a83944,3,22
45,,435,34

Expected output file:

a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
24,4a83944,3,22

Body:
I suspect your real problem is that you're calling awk repeatedly (probably in a loop), once per set of values of $2 and generating an output file each time, e.g.:

awk -F, '$2==""' input > novals
awk -F, '$2!=""' input > yesvals
etc.

Don't do that as it's very inefficient since it's reading the whole file on every iteration. Do this instead:

awk '{out=($2=="" ? "novals" : "yesvals")} {print > out}' input

That will create all of your output files with one call to awk. Once you get past about 15 output files it would require GNU awk for internal handling of open file descriptors or you need to add close(out)s when $2 changes and use >> instead of >:

awk '$2!=prev{close(out); out=($2=="" ? "novals" : "yesvals"); prev=$2} {print >> out}' input

and that would be more efficient if you sorted your input file first with (requires GNU sort for -s for stable sort if you care about preserving input ordering for the unique $2 values):

sort -t, -k2,2 -s


答:
First i like to say, Please use prepared statement.

```<code>$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
</code>```

The mysqli_query() function performs a query against the database and $connection variable opens a new connection to the MySQL server which you already created in db_connect.php and you checking whether the connection is established or not. If not then, die() function will run. It is used to print message and exit from the current php script.

```<code>$count = mysqli_num_rows($result);
</code>```

mysqli_num_rows() function will returns the number of rows in a result set and you are storing that number into $count variable.

Hope this helps you

Title: What's the meaning of these two lines of PHP code?

Body:
First i like to say, Please use prepared statement.

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));

The mysqli_query() function performs a query against the database and $connection variable opens a new connection to the MySQL server which you already created in db_connect.php and you checking whether the connection is established or not. If not then, die() function will run. It is used to print message and exit from the current php script.

$count = mysqli_num_rows($result);

mysqli_num_rows() function will returns the number of rows in a result set and you are storing that number into $count variable.

Hope this helps you


问:
Initializing properties inside ngOnInit scope
I'm using ngOnInit in order to get a response from a Loopback API call.
The property I initialize inside this scope can't be used outside the subscribe scope. I know this is a simple answer but I'm just not seeing it

```<code>private siteData: Kiosk;

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             console.log(this.siteData); // This outputs correctly
    });
    console.log(this.siteData); // This is undefined
  }

  site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];
</code>```

I expect output to not be undefined and be the data that is in the response

答:
This is because observables are asynchronous. sideData isn't defined until after the assignment is made in the subscribe call – it's similar to a promise.

If you try to access the value set by a promise before a .then is called, then it will also be undefined. The way around this would be to use the tap operator to set it in a pipe, and then operate on it in other ways in the subscribe. Alternatively, you could use something like ngrx that will automatically update the to latest value.

Body:
I'm using ngOnInit in order to get a response from a Loopback API call.
The property I initialize inside this scope can't be used outside the subscribe scope. I know this is a simple answer but I'm just not seeing it

private siteData: Kiosk;

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             console.log(this.siteData); // This outputs correctly
    });
    console.log(this.siteData); // This is undefined
  }

  site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];

I expect output to not be undefined and be the data that is in the response


问:
My-Location Button of GoogleMaps v2 Android, not displayed
I'm doing an app, with google maps, but when I try to add "my-location" button, as the reference says doesn't work...

thats how I do:

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        locManager = (LocationManager)getSystemService(LOCATION_SERVICE);
        providersList = locManager.getAllProviders();
        provider =locManager.getProvider(providersList.get(0));
        precision = provider.getAccuracy();
        req = new Criteria();
        req.setAccuracy(Criteria.ACCURACY_FINE);
        inside = false;

        map.getUiSettings().setMyLocationButtonEnabled(true);

        buildPolygon();
        drawPolygon();
        startLocalization();
    }
</code>```

I used map.getUiSettings().setMyLocationButtonEnabled(true); as shows in the reference of google. I don't know what's going on..

答:
The above answers didn't work.</p>

```<code>override fun onMapReady(googleMap: GoogleMap?) {
    this.googleMap = googleMap

    setupMap()
}

private fun setupMap() {
    if (ActivityCompat.checkSelfPermission(context!!,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        // Before enabling the My Location layer, you must request location permission from the user.
        googleMap?.isMyLocationEnabled = true
        // *** Use this method ***
        googleMap?.uiSettings?.isMyLocationButtonEnabled = true

        // See https://developers.google.com/maps/documentation/android-sdk/location
        googleMap?.setOnMyLocationButtonClickListener(this)
        googleMap?.setOnMyLocationClickListener(this)
    } else {
        // Show rationale and request permission.
        requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            LOCATION_REQUEST_CODE)
    }
}
</code>```

Body:
I'm doing an app, with google maps, but when I try to add "my-location" button, as the reference says doesn't work...

thats how I do:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        locManager = (LocationManager)getSystemService(LOCATION_SERVICE);
        providersList = locManager.getAllProviders();
        provider =locManager.getProvider(providersList.get(0));
        precision = provider.getAccuracy();
        req = new Criteria();
        req.setAccuracy(Criteria.ACCURACY_FINE);
        inside = false;

        map.getUiSettings().setMyLocationButtonEnabled(true);

        buildPolygon();
        drawPolygon();
        startLocalization();
    }

I used map.getUiSettings().setMyLocationButtonEnabled(true); as shows in the reference of google. I don't know what's going on..

Body:
The above answers didn't work.

override fun onMapReady(googleMap: GoogleMap?) {
    this.googleMap = googleMap

    setupMap()
}

private fun setupMap() {
    if (ActivityCompat.checkSelfPermission(context!!,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        // Before enabling the My Location layer, you must request location permission from the user.
        googleMap?.isMyLocationEnabled = true
        // *** Use this method ***
        googleMap?.uiSettings?.isMyLocationButtonEnabled = true

        // See https://developers.google.com/maps/documentation/android-sdk/location
        googleMap?.setOnMyLocationButtonClickListener(this)
        googleMap?.setOnMyLocationClickListener(this)
    } else {
        // Show rationale and request permission.
        requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            LOCATION_REQUEST_CODE)
    }
}