问:
Formatting a date returned from an Observable array
I am trying to format a date value returned from a rest service as an observable. The createdOn and modifiedOn dates are being rendered in my HTML as /Date(1298937600000)/, I would like them formatted as dd/MM/yyyy. I have seen a few similar posts but none seem to point me in the right direction or are beyond my current understanding of Angular 2.

I am making a call to my API as such:

```<code>getUnLocationsList(): Observable<UnLocations[]> {

    var url = "http://localhost:5000/api/unlocations"
    return this._http.get(url)
        .map((response: Response) => <UnLocations[]>response.json().unLocations)
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
</code>```

From my Angular 2 Component I am then calling the getUnLocationsList() function, like this:

```<code>export class StandingDataComponent implements OnInit {

 pageTitle: string = 'UnLocation Codes';
 unLocationsList: UnLocations[];

 constructor(private _staticDataService: StaticDataService) { }

 ngOnInit() {
 this.getUnLocationsList();
 }
 getUnLocationsList() {
  this._staticDataService.getUnLocationsList().subscribe(unLocationsList => this.unLocationsList = unLocationsList),
  err => console.error(err),
  () => console.log("finished loading unlocations");
</code>```

}

finally I am using then using a simple *ngFor to display the data

```<code><tbody *ngFor="let unLocation of unLocationsList | paginate: {itemsPerPage: 30, currentPage:page, id: '1'}; let i = index">
    <td style="width:100px"> {{unLocation.code}} </td>
    <td style="width:200px"> {{unLocation.name}} </td>
    <td style="width:200px">{{unLocation.isActive}}</td>
    <td style="width:200px">{{unLocation.createdOn }}</td>
     <td style="width:200px">{{unLocation.modifiedOn }}</td>
  </tbody>
</code>```

答:
One option would be to use the DatePipe to transform the output of your binding. This will leave your data unchanged, which might be desirable. It's in the CommonModule so you shouldn't have to import anything.

Something like this:

```<code><td style="width:200px">{{unLocation.createdOn | date:'dd/MM/y' }}</td>
</code>```

Otherwise you can turn it into a Date object somewhere (loop through them all) and use this:

```<code>new Date(1298937600000);
// Tue Mar 01 2011 01:00:00 GMT+0100 (W. Europe Standard Time)
</code>```

Body:
I am trying to format a date value returned from a rest service as an observable. The createdOn and modifiedOn dates are being rendered in my HTML as /Date(1298937600000)/, I would like them formatted as dd/MM/yyyy. I have seen a few similar posts but none seem to point me in the right direction or are beyond my current understanding of Angular 2.

I am making a call to my API as such:

getUnLocationsList(): Observable<UnLocations[]> {

    var url = "http://localhost:5000/api/unlocations"
    return this._http.get(url)
        .map((response: Response) => <UnLocations[]>response.json().unLocations)
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}

From my Angular 2 Component I am then calling the getUnLocationsList() function, like this:

export class StandingDataComponent implements OnInit {

 pageTitle: string = 'UnLocation Codes';
 unLocationsList: UnLocations[];

 constructor(private _staticDataService: StaticDataService) { }

 ngOnInit() {
 this.getUnLocationsList();
 }
 getUnLocationsList() {
  this._staticDataService.getUnLocationsList().subscribe(unLocationsList => this.unLocationsList = unLocationsList),
  err => console.error(err),
  () => console.log("finished loading unlocations");

}

finally I am using then using a simple *ngFor to display the data

     {{unLocation.code}}
     {{unLocation.name}}
    {{unLocation.isActive}}
    {{unLocation.createdOn }}
     {{unLocation.modifiedOn }}

Body:
One option would be to use the DatePipe to transform the output of your binding. This will leave your data unchanged, which might be desirable. It's in the CommonModule so you shouldn't have to import anything.

Something like this:

<td style="width:200px">{{unLocation.createdOn | date:'dd/MM/y' }}</td>

Otherwise you can turn it into a Date object somewhere (loop through them all) and use this:

new Date(1298937600000);
// Tue Mar 01 2011 01:00:00 GMT+0100 (W. Europe Standard Time)


来源: stackexchange

问:
CryptoJS encrypt Go decrypt
I have the following Go code

```<code>ciphertext := "Zff9c+F3gZu/lsARvPhpMau50KUkMAie4j8MYfb12HMWhkLqZreTk8RPbtRB7RDG3QFw7Y0FXJsCq/EBEAz//XoeSZmqZXoyq2Cx8ZV+/Rw="
decodedText, _ := base64.StdEncoding.DecodeString(ciphertext)
decodedIv, _ := base64.StdEncoding.DecodeString("u9CV7oR2w+IIk8R0hppxaw==")
newCipher, _ := aes.NewCipher([]byte("~NB8CcOL#J!H?|Yr"))
cfbdec := cipher.NewCBCDecrypter(newCipher, decodedIv)
cfbdec.CryptBlocks(decodedText, decodedText)
data, _ := base64.StdEncoding.DecodeString(string(decodedText))
println(string(data))
</code>```

The output is {"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!!"

It's encrypted with the following CryptoJS

```<code>function encrypt(message, key) {
  let keyHex = CryptoJS.enc.Hex.parse(parseToHex(key))
  let iv = CryptoJS.lib.WordArray.random(128 / 8);
  let wordArray = CryptoJS.enc.Utf8.parse(message);
  let base64 = CryptoJS.enc.Base64.stringify(wordArray);
  let encrypted = CryptoJS.AES.encrypt(base64, keyHex, { iv: iv });
  return {
    cipher: encrypted.ciphertext.toString(CryptoJS.enc.Base64),
    iv: CryptoJS.enc.Base64.stringify(iv),
    length: base64.length,
    size: encrypted.ciphertext.sigBytes,
  }
}
</code>```

And can be decrypted with

```<code>function decrypt(message, key, iv) {
  let ivEX = CryptoJS.enc.Hex.parse(decodeToHex(iv));
  let keyEX = CryptoJS.enc.Hex.parse(parseToHex(key));
  let bytes = CryptoJS.AES.decrypt(message, keyEX , { iv: ivEX});
  let plaintext = bytes.toString(CryptoJS.enc.Base64);
  return decodeToString(decodeToString(plaintext));
}
</code>```

The output is {"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!!" } - this is the correct output

Why Go has different output?

答:
Check your errors please. ALWAYS

illegal base64 data at input byte 75

https://play.golang.org/p/dRLIT51u4I

More specifically, the value at byte 75 is 5, which is out of the range of characters available to base64. In ascii, it is the ENQ (enquiry) character. As to why this ends up in your final base64 string is beyond me.

EDIT: OK found the issue. For whatever reason, the base64 padding character = at the end is being decrypted as 5 consecutive bytes containing the value 5. Here is a playground link that shows it fixed. https://play.golang.org/p/tf3OZ9XG1M

EDIT: As per matt's comments. I updated the fix function to simply remove all the PKCS7 block padding and use RawStdEncoding for the last base64 decode. This should now be a reasonable fix.

ContentLicense: CC BY-SA 3.0

Title: CryptoJS encrypt Go decrypt

Body:
I have the following Go code

ciphertext := "Zff9c+F3gZu/lsARvPhpMau50KUkMAie4j8MYfb12HMWhkLqZreTk8RPbtRB7RDG3QFw7Y0FXJsCq/EBEAz//XoeSZmqZXoyq2Cx8ZV+/Rw="
decodedText, _ := base64.StdEncoding.DecodeString(ciphertext)
decodedIv, _ := base64.StdEncoding.DecodeString("u9CV7oR2w+IIk8R0hppxaw==")
newCipher, _ := aes.NewCipher([]byte("~NB8CcOL#J!H?|Yr"))
cfbdec := cipher.NewCBCDecrypter(newCipher, decodedIv)
cfbdec.CryptBlocks(decodedText, decodedText)
data, _ := base64.StdEncoding.DecodeString(string(decodedText))
println(string(data))

The output is {"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!!"

It's encrypted with the following CryptoJS

function encrypt(message, key) {
  let keyHex = CryptoJS.enc.Hex.parse(parseToHex(key))
  let iv = CryptoJS.lib.WordArray.random(128 / 8);
  let wordArray = CryptoJS.enc.Utf8.parse(message);
  let base64 = CryptoJS.enc.Base64.stringify(wordArray);
  let encrypted = CryptoJS.AES.encrypt(base64, keyHex, { iv: iv });
  return {
    cipher: encrypted.ciphertext.toString(CryptoJS.enc.Base64),
    iv: CryptoJS.enc.Base64.stringify(iv),
    length: base64.length,
    size: encrypted.ciphertext.sigBytes,
  }
}

And can be decrypted with

function decrypt(message, key, iv) {
  let ivEX = CryptoJS.enc.Hex.parse(decodeToHex(iv));
  let keyEX = CryptoJS.enc.Hex.parse(parseToHex(key));
  let bytes = CryptoJS.AES.decrypt(message, keyEX , { iv: ivEX});
  let plaintext = bytes.toString(CryptoJS.enc.Base64);
  return decodeToString(decodeToString(plaintext));
}

The output is {"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!!" } - this is the correct output

Why Go has different output?


问:
Coldfusion looping over query and display html tag only one time
I have  a problem with looping over sql queries and if the query is not null then i must display some html tag. The problem is that let's say that query find 3 items, it will display 3x file instead of 1x.

Here is my code:

```<code><cfquery name="client_id" datasource="#application.dsn#">
    Select borrower_id,client_id,id from contracts where borrower_id = <cfqueryparam cfsqltype="cf_sql_integer" value="#trim(url.ID)#">
</cfquery>

<cfloop query="client_id">
    <cfquery name="Payment_log" datasource="#application.dsn#">
        SELECT *
        FROM paymentLog
        WHERE contract_id = <cfqueryparam value="#client_id.id#" maxlength="36" cfsqltype="CF_SQL_BIGINT">
            AND DateDelete IS NULL
        ORDER BY date_log, id
    </cfquery>

    <cfloop query="Payment_log">

        <cfquery name="payment_log_file" datasource="#application.dsn#">
            SELECT file_name
            FROM paymentLog_file
            WHERE log_id = #Payment_log.id#
        </cfquery>

        <cfloop query="payment_log_file">

            <cfif payment_log_file.recordCount neq 0>
                <th>file name</th>
            </cfif>
        </cfloop>
    </cfloop>
</cfloop>
</code>```

This is the result

```<code><th>file name</th>
<th>file name</th>
<th>file name</th>
</code>```

This is what i want/need

```<code><th>file name</th>
</code>```

Okay so I changed my sql query as suggested by Matt Busche and Dan Bracuk to this:

```<code>SELECT plf.log_id
FROM paymentLog pl
        LEFT JOIN paymentLog_file plf ON pl.id = plf.log_id
WHERE contract_id = <cfqueryparam value="#client_id.id#" maxlength="36" cfsqltype="CF_SQL_BIGINT">
        AND DateDelete IS NULL
ORDER BY plf.log_id, date_log, id
</code>```

And I get this:

This is what i get

This is what i want/need

答:
I'd recommend combining the whole query into one dataset, then working with that to build your output.

```<code>SELECT c.borrower_id,c.client_id,c.id AS contracts_id
    , pl.* /* But don't use *. Explicitly call only column names that you need. */
    , plf.[file_name] /* Brackets because "file_name" is a built-in SQL function. */
FROM  contracts c
        LEFT OUTER JOIN paymentLog pl ON c.id = pl.contract_id
            AND pl.DateDelete IS NULL
        LEFT OUTER JOIN paymentLog_file plf ON plf.log_id = pl.id
WHERE c.borrower_id = <cfqueryparam cfsqltype="cf_sql_integer" value="#trim(url.ID)#">
ORDER BY pl.log_id, pl.date_log, pl.id /* Is this last ORDER BY needed? Which id are you wanting to sort on? Make sure it's in the SELECT. */
</code>```

This will also let you dump out your entire dataset in one batch so that you can see what you're actually working with. From here you should be able to get it to output what you are looking for.

And I would also validate your url.ID before you pass it to your cfqueryparam.

Body:
I have  a problem with looping over sql queries and if the query is not null then i must display some html tag. The problem is that let's say that query find 3 items, it will display 3x file instead of 1x.

Here is my code:

<cfquery name="client_id" datasource="#application.dsn#">
    Select borrower_id,client_id,id from contracts where borrower_id = <cfqueryparam cfsqltype="cf_sql_integer" value="#trim(url.ID)#">
</cfquery>

<cfloop query="client_id">
    <cfquery name="Payment_log" datasource="#application.dsn#">
        SELECT *
        FROM paymentLog
        WHERE contract_id = <cfqueryparam value="#client_id.id#" maxlength="36" cfsqltype="CF_SQL_BIGINT">
            AND DateDelete IS NULL
        ORDER BY date_log, id
    </cfquery>

    <cfloop query="Payment_log">

        <cfquery name="payment_log_file" datasource="#application.dsn#">
            SELECT file_name
            FROM paymentLog_file
            WHERE log_id = #Payment_log.id#
        </cfquery>

        <cfloop query="payment_log_file">

            <cfif payment_log_file.recordCount neq 0>
                file name
            </cfif>
        </cfloop>
    </cfloop>
</cfloop>

This is the result

file name
file name
file name

This is what i want/need

file name

Okay so I changed my sql query as suggested by Matt Busche and Dan Bracuk to this:

SELECT plf.log_id
FROM paymentLog pl
        LEFT JOIN paymentLog_file plf ON pl.id = plf.log_id
WHERE contract_id = <cfqueryparam value="#client_id.id#" maxlength="36" cfsqltype="CF_SQL_BIGINT">
        AND DateDelete IS NULL
ORDER BY plf.log_id, date_log, id

And I get this:

This is what i get

This is what i want/need

Body:
I'd recommend combining the whole query into one dataset, then working with that to build your output.

SELECT c.borrower_id,c.client_id,c.id AS contracts_id
    , pl.* /* But don't use *. Explicitly call only column names that you need. */
    , plf.[file_name] /* Brackets because "file_name" is a built-in SQL function. */
FROM  contracts c
        LEFT OUTER JOIN paymentLog pl ON c.id = pl.contract_id
            AND pl.DateDelete IS NULL
        LEFT OUTER JOIN paymentLog_file plf ON plf.log_id = pl.id
WHERE c.borrower_id = <cfqueryparam cfsqltype="cf_sql_integer" value="#trim(url.ID)#">
ORDER BY pl.log_id, pl.date_log, pl.id /* Is this last ORDER BY needed? Which id are you wanting to sort on? Make sure it's in the SELECT. */

This will also let you dump out your entire dataset in one batch so that you can see what you're actually working with. From here you should be able to get it to output what you are looking for.

And I would also validate your url.ID before you pass it to your cfqueryparam.


问:
Is this the best/secure method for encryption in Java?
I am new in security and I'm wondering if I can make my program better, like changing or adding something to make it better ( more secure )

(I have doubt from the program output)

Here is the output:

```<code>Encrypted Message: +g@þóv«5Ùû`ž
keybyte: [B@71e7a66b
Original string: Message
Original string (Hex): [B@2ac1fdc4
</code>```

Here is the code:

```<code>public class AES {

  public static void main(String ... args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    final String Algo="AES";
    String key = "aaaaaaaaaaaaaaaa";
    byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);

    MessageDigest sha= MessageDigest.getInstance("SHA-1");
    keyBytes=sha.digest(keyBytes);
    keyBytes=Arrays.copyOf(keyBytes, 16);

    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, Algo);
    Cipher cipher = Cipher.getInstance(Algo);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] ciphertext = cipher.doFinal("Message".getBytes());
    System.out.println("Encrypted Message: " +new String(ciphertext));

    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] original = cipher.doFinal(ciphertext);
    String originalString = new String(original);
    System.out.println("keybyte: "+keyBytes);
    System.out.println("Original string: " + originalString + "\nOriginal string (Hex): " +original);
  }
}
</code>```

答:
There are at least two problems with your implementation:

Unless you specify otherwise, you are using AES in ECB mode.  ECB mode is not secure regardless of what cipher is under the hood.  There are a number of secure modes, but usually people implement CBC mode, which is accomplished by changing your Algo to "AES/CBC/PKCS5Padding" (which really is PKCS7 padding, Java just does not know better).  Then, you need to choose an IV via SecureRandom() to encrypt this way.  This OWASP example seems to do it right (FYI -- 99% of the implementations you will find on the web have security problems somewhere).

Your key is not a key, instead it is a password that is being turned into a key.  You shouldn't be hardcoding this, but I assume you are doing that for proof of concept only.  In any case, the problem is using a hash function such as SHA-1 to turn a password into a key is not a good decision because passwords tend to have low entropy and can be brute forced.  For this reason, you should be using a function that is dedicated to resisting brute force when turning a password into a key.  Such functions include pbkdf2, bcrypt, scrypt, and argon2.  For more information, Troy Hunt (a .Net guy) gives a good overview on the problems with using something like SHA-1 (or anything from the SHA2 family for that matter) in this context.

The other thing to keep in mind is that encryption does not generally provide message integrity.  What this means is that just because you have encrypted the data does not mean somebody cannot modify it, and your software will still decrypt the modified data without being aware that it is modified.  If you need to know that your data was not modified, then you will need to add on something like HMAC, or else you will need to switch to a mode of operation such as GCM.

Finally, AES is an excellent choice for security.  But you need to use it in the right mode, you need to implement it right, and you need to understand whether you need more than just encryption.

Body:
I am new in security and I'm wondering if I can make my program better, like changing or adding something to make it better ( more secure )

(I have doubt from the program output)

Here is the output:

Encrypted Message: +g@þóv«5Ùû`ž
keybyte: [B@71e7a66b
Original string: Message
Original string (Hex): [B@2ac1fdc4

Here is the code:

public class AES {

  public static void main(String ... args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    final String Algo="AES";
    String key = "aaaaaaaaaaaaaaaa";
    byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);

    MessageDigest sha= MessageDigest.getInstance("SHA-1");
    keyBytes=sha.digest(keyBytes);
    keyBytes=Arrays.copyOf(keyBytes, 16);

    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, Algo);
    Cipher cipher = Cipher.getInstance(Algo);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] ciphertext = cipher.doFinal("Message".getBytes());
    System.out.println("Encrypted Message: " +new String(ciphertext));

    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] original = cipher.doFinal(ciphertext);
    String originalString = new String(original);
    System.out.println("keybyte: "+keyBytes);
    System.out.println("Original string: " + originalString + "\nOriginal string (Hex): " +original);
  }
}


问:
How to use jquery.hover() using jquery.bind()?
I am creating a table and replacing it in to a div in an aspx page. In that table I have four columns and in each columns i have a particular class. The content of div (ie table) will be changed using $ajax() everytime when a dropdownlist changes it value.I am getting the table and it will be coming inside the div.What i requires is I need to do jquery.hover() in that particular class.So how can i do by giving the class name. I have already tested $.('.ovr')bind(mouseover,mouseout).But this is also not works. Can u pls give a solution?

答:
Try something like this:</p>

```<code>$(document).ready( function(){

  $('#id_of_your_table')
    .delegate('.ovr','mouseover',function(){
      your_mouseover_behavior();
    })
    .delegate('.ovr','mouseout',function(){
      your_mouseout_behavior();
    });

});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try something like this:

$(document).ready( function(){

  $('#id_of_your_table')
    .delegate('.ovr','mouseover',function(){
      your_mouseover_behavior();
    })
    .delegate('.ovr','mouseout',function(){
      your_mouseout_behavior();
    });

});


问:
Can't both add extra newlines in find -printf and pipe output through sort
I'm trying to print out the top 10 largest files in my current directory.

For now I'm using

```<code>find . -maxdepth 1 -printf '%s %p\n'|sort -nr| head
</code>```

I'm not sure how to add an additional newline after each file size. Typing \n\n doesn't do anything, or \n\\n. I also need a tab before each line as well.

答:
Don't use newlines here. They're the wrong tool for the job: Filenames can contain literal newlines, so you don't know if a newline in find's output here came from your format string or a literal filename. Moreover, by default, sort uses newlines as record separators, so the empty lines and the names they were previously next to are no longer next to each other when it's done (since they've been... well... sorted into different locations).

So -- generate your output in a format that makes sense given the content restraints, and then reformat it into what you actually want for output later:

```<code>while IFS= read -r -d$'\t' size && IFS= read -r -d '' filename; do
  printf '\t%s\n\n' "$filename"
done < <(find . -maxdepth 1 -printf '%s\t%p\0'|sort -znr|head -z)
</code>```

Note that this is full of GNUisms (sort -z, head -z) -- but find -printf is a GNUism itself.

By way of understanding this code, some pointers:

BashFAQ #1: "How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?"

BashFAQ #3: "How can I sort or compare files based on some metadata attribute (newest / oldest modification time, size, etc)?"

Process substitution: The <( ... ) syntax used to expose the output from the pipeline as a file.

The printf builtin: A discussion of the bash printf command.

Body:
I'm trying to print out the top 10 largest files in my current directory.

For now I'm using

find . -maxdepth 1 -printf '%s %p\n'|sort -nr| head

I'm not sure how to add an additional newline after each file size. Typing \n\n doesn't do anything, or \n\\n. I also need a tab before each line as well.

Body:
Don't use newlines here. They're the wrong tool for the job: Filenames can contain literal newlines, so you don't know if a newline in find's output here came from your format string or a literal filename. Moreover, by default, sort uses newlines as record separators, so the empty lines and the names they were previously next to are no longer next to each other when it's done (since they've been... well... sorted into different locations).

So -- generate your output in a format that makes sense given the content restraints, and then reformat it into what you actually want for output later:

while IFS= read -r -d$'\t' size && IFS= read -r -d '' filename; do
  printf '\t%s\n\n' "$filename"
done < <(find . -maxdepth 1 -printf '%s\t%p\0'|sort -znr|head -z)

Note that this is full of GNUisms (sort -z, head -z) -- but find -printf is a GNUism itself.

By way of understanding this code, some pointers:

BashFAQ #1: "How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?"

BashFAQ #3: "How can I sort or compare files based on some metadata attribute (newest / oldest modification time, size, etc)?"

Process substitution: The <( ... ) syntax used to expose the output from the pipeline as a file.

The printf builtin: A discussion of the bash printf command.


问:
How to calculate correlation between all columns and remove highly correlated ones using pandas?
I have a huge data set and prior to machine learning modeling it is always suggested that first you should remove highly correlated descriptors(columns) how can i calculate the column wice correlation and remove the column with a threshold value say remove all the columns or descriptors having  >0.8 correlation.  also it should retained the headers in reduce data..

Example data set

```<code> GA      PN       PC     MBP      GR     AP
0.033   6.652   6.681   0.194   0.874   3.177
0.034   9.039   6.224   0.194   1.137   3.4
0.035   10.936  10.304  1.015   0.911   4.9
0.022   10.11   9.603   1.374   0.848   4.566
0.035   2.963   17.156  0.599   0.823   9.406
0.033   10.872  10.244  1.015   0.574   4.871
0.035   21.694  22.389  1.015   0.859   9.259
0.035   10.936  10.304  1.015   0.911   4.5
</code>```

Please help....

答:
Plug your features dataframe in this function and just set your correlation threshold. It'll auto drop columns, but will also give you a diagnostic of the columns it drops if you want to do it manually.</p>

```<code>def corr_df(x, corr_val):
    '''
    Obj: Drops features that are strongly correlated to other features.
          This lowers model complexity, and aids in generalizing the model.
    Inputs:
          df: features df (x)
          corr_val: Columns are dropped relative to the corr_val input (e.g. 0.8)
    Output: df that only includes uncorrelated features
    '''

    # Creates Correlation Matrix and Instantiates
    corr_matrix = x.corr()
    iters = range(len(corr_matrix.columns) - 1)
    drop_cols = []

    # Iterates through Correlation Matrix Table to find correlated columns
    for i in iters:
        for j in range(i):
            item = corr_matrix.iloc[j:(j+1), (i+1):(i+2)]
            col = item.columns
            row = item.index
            val = item.values
            if val >= corr_val:
                # Prints the correlated feature set and the corr val
                print(col.values[0], "|", row.values[0], "|", round(val[0][0], 2))
                drop_cols.append(i)

    drops = sorted(set(drop_cols))[::-1]

    # Drops the correlated columns
    for i in drops:
        col = x.iloc[:, (i+1):(i+2)].columns.values
        df = x.drop(col, axis=1)

    return df
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a huge data set and prior to machine learning modeling it is always suggested that first you should remove highly correlated descriptors(columns) how can i calculate the column wice correlation and remove the column with a threshold value say remove all the columns or descriptors having  >0.8 correlation.  also it should retained the headers in reduce data..

Example data set

 GA      PN       PC     MBP      GR     AP
0.033   6.652   6.681   0.194   0.874   3.177
0.034   9.039   6.224   0.194   1.137   3.4
0.035   10.936  10.304  1.015   0.911   4.9
0.022   10.11   9.603   1.374   0.848   4.566
0.035   2.963   17.156  0.599   0.823   9.406
0.033   10.872  10.244  1.015   0.574   4.871
0.035   21.694  22.389  1.015   0.859   9.259
0.035   10.936  10.304  1.015   0.911   4.5

Please help....

Body:
Plug your features dataframe in this function and just set your correlation threshold. It'll auto drop columns, but will also give you a diagnostic of the columns it drops if you want to do it manually.

def corr_df(x, corr_val):
    '''
    Obj: Drops features that are strongly correlated to other features.
          This lowers model complexity, and aids in generalizing the model.
    Inputs:
          df: features df (x)
          corr_val: Columns are dropped relative to the corr_val input (e.g. 0.8)
    Output: df that only includes uncorrelated features
    '''

    # Creates Correlation Matrix and Instantiates
    corr_matrix = x.corr()
    iters = range(len(corr_matrix.columns) - 1)
    drop_cols = []

    # Iterates through Correlation Matrix Table to find correlated columns
    for i in iters:
        for j in range(i):
            item = corr_matrix.iloc[j:(j+1), (i+1):(i+2)]
            col = item.columns
            row = item.index
            val = item.values
            if val >= corr_val:
                # Prints the correlated feature set and the corr val
                print(col.values[0], "|", row.values[0], "|", round(val[0][0], 2))
                drop_cols.append(i)

    drops = sorted(set(drop_cols))[::-1]

    # Drops the correlated columns
    for i in drops:
        col = x.iloc[:, (i+1):(i+2)].columns.values
        df = x.drop(col, axis=1)

    return df


问:
How to avoid dependency conflict when using dropwizard + jersey client
I have a DropWizard REST API written and works. One of the resource endpoints actually writes an email, however as soon as I add the following dependencies DropWizard starts to fail on start up

```<code><dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.18.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-core</artifactId>
        <version>1.18.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey.contribs</groupId>
        <artifactId>jersey-multipart</artifactId>
        <version>1.18.1</version>
    </dependency>
</code>```

The DropWizard dependency is:

```<code><dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>0.8.1</version>
    </dependency>
</code>```

The error on startup is really long, summarised below

```<code>    WARN  [2015-05-01 20:06:08,887] org.glassfish.jersey.internal.Errors: The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 2
java.lang.NullPointerException
    at com.sun.jersey.core.provider.jaxb.AbstractJAXBProvider.setConfiguration(AbstractJAXBProvider.java:113)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    ....
    MultiException stack 2 of 2
java.lang.IllegalStateException: Unable to perform operation: method inject on com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:395)
    ....
    MultiException stack 3 of 3
java.lang.IllegalStateException: Unable to perform operation: create on org.glassfish.jersey.message.internal.MessageBodyFactory
    ...
</code>```

I'm guessing DropWizard is using another conflicting dependency so how do I deal with this?

Thanks in advance

答:
I had the same problem (I'm using DW 0.9.2 and have unwanted transitive dependencies of both DW 0.7.2 and Jersey 1.x)

The solution was pretty simple: in the dependency that's bringing you those two family of libraries, declare an exclusion and it should work, for instance, this is how I did it in Gradle:

```<code>compile("com.example.culprit:culprit:1.2.3") {
    exclude group: 'io.dropwizard'
    exclude group: 'com.sun.jersey'
}
</code>```

The syntax for Maven is pretty similar (more verbose actually ;-) )

Hope this helps someone.

Body:
I have a DropWizard REST API written and works. One of the resource endpoints actually writes an email, however as soon as I add the following dependencies DropWizard starts to fail on start up

<dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.18.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-core</artifactId>
        <version>1.18.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey.contribs</groupId>
        <artifactId>jersey-multipart</artifactId>
        <version>1.18.1</version>
    </dependency>

The DropWizard dependency is:

<dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>0.8.1</version>
    </dependency>

The error on startup is really long, summarised below

    WARN  [2015-05-01 20:06:08,887] org.glassfish.jersey.internal.Errors: The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 2
java.lang.NullPointerException
    at com.sun.jersey.core.provider.jaxb.AbstractJAXBProvider.setConfiguration(AbstractJAXBProvider.java:113)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    ....
    MultiException stack 2 of 2
java.lang.IllegalStateException: Unable to perform operation: method inject on com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:395)
    ....
    MultiException stack 3 of 3
java.lang.IllegalStateException: Unable to perform operation: create on org.glassfish.jersey.message.internal.MessageBodyFactory
    ...

I'm guessing DropWizard is using another conflicting dependency so how do I deal with this?

Thanks in advance

Body:
I had the same problem (I'm using DW 0.9.2 and have unwanted transitive dependencies of both DW 0.7.2 and Jersey 1.x)

The solution was pretty simple: in the dependency that's bringing you those two family of libraries, declare an exclusion and it should work, for instance, this is how I did it in Gradle:

compile("com.example.culprit:culprit:1.2.3") {
    exclude group: 'io.dropwizard'
    exclude group: 'com.sun.jersey'
}

The syntax for Maven is pretty similar (more verbose actually ;-) )

Hope this helps someone.


问:
How to write a HQL query for a many to many association
So I have spent several hours trying to write a HQL query for a many to many relationship. With all the queries that I have tried nothing worked even after reading the hibernate docs. Can someone please assist me? Thank you in advance.

I have tried inner join, join and outer join with or without fetch. I think the issue may be related to the one to many relationship within the fragrance class.

```<code>@Query("FROM Category c INNER JOIN FETCH c.fragrances f WITH c.referencedId = 1")
List<Category> getCatalog();
</code>```

Category Class without get/setters

```<code>@Entity
public class Category extends AbstractEntity {

   @Column(name = "name", nullable = false)
   private String name;

   @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinTable(name = "Category_has_Fragrance",
        joinColumns = @JoinColumn(name = "category_id"),
        inverseJoinColumns = @JoinColumn(name = "fragrance_id")
   )
   @OrderBy("name")
   private List<Fragrance> fragrances;

   @Column(name = "referenced_id", nullable = false)
   private int referencedId;
]
</code>```

Fragrance Class without get/setters

```<code>@Entity
public class Fragrance extends AbstractEntity {

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "description", nullable = false)
    private String description;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "fragrances")
    private Set<Category> categories;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "fragrance")
    private List<FragrancedProduct> fragrancedProducts;

    @Column(name = "image_path")
    private String imagePath;
}
</code>```

答:
Try this:

```<code>select c from Category c join c.fragrances f where c.referencedId = :id
</code>```

You can check a similar question here: How do I do with HQL, many to many?

Body:
So I have spent several hours trying to write a HQL query for a many to many relationship. With all the queries that I have tried nothing worked even after reading the hibernate docs. Can someone please assist me? Thank you in advance.

I have tried inner join, join and outer join with or without fetch. I think the issue may be related to the one to many relationship within the fragrance class.

@Query("FROM Category c INNER JOIN FETCH c.fragrances f WITH c.referencedId = 1")
List<Category> getCatalog();

Category Class without get/setters

@Entity
public class Category extends AbstractEntity {

   @Column(name = "name", nullable = false)
   private String name;

   @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinTable(name = "Category_has_Fragrance",
        joinColumns = @JoinColumn(name = "category_id"),
        inverseJoinColumns = @JoinColumn(name = "fragrance_id")
   )
   @OrderBy("name")
   private List<Fragrance> fragrances;

   @Column(name = "referenced_id", nullable = false)
   private int referencedId;
]

Fragrance Class without get/setters

@Entity
public class Fragrance extends AbstractEntity {

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "description", nullable = false)
    private String description;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "fragrances")
    private Set<Category> categories;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "fragrance")
    private List<FragrancedProduct> fragrancedProducts;

    @Column(name = "image_path")
    private String imagePath;
}

Body:
Try this:

select c from Category c join c.fragrances f where c.referencedId = :id

You can check a similar question here: How do I do with HQL, many to many?


问:
How to combine mulitple column adding '-' and removing '-' with value is NULL
this is my Data

```<code>col1    col2    col col3    col4    col5    col6
42      A       11  18      89      16      empty
42      B       12  empty   89      14      C
36      8       9   empty   empty   2       empty
</code>```

this is the Script I'm running

```<code>select col1 + COALESCE ([col2]+'-','')
+COALESCE([col3]+'-','')+COALESCE([col4]+'-','')
+COALESCE([col5]+'-','')+COALESCE([col6],'') as totalCol
FROM ...
</code>```

This is what I get

```<code>totalCol
42A-11-18-89-16-
42B-12- -89-14-C
368-9- - -2 -
</code>```

This is what I want

```<code>totalCol
42A-11-18-89-16
42B-12-89-14-C
368-9-2
</code>```

答:
run a replace of "- " to "" after your script

also you have to remember that nulls and blank space are two different things.

Updated script

```<code>select ltrim(rtrim(replace(replace(
col1 + COALESCE ([col2]+'-','')
+COALESCE([col3]+'-','')+COALESCE([col4]+'-','')
+COALESCE([col5]+'-','')+COALESCE([col6],'') + ' ','--','-'),
'- ','')))
as totalCol
FROM ...
</code>```

or  assuming only blank space and not nulls

```<code>select ltrim(rtrim(replace(
[col1] + [col2]+'-' + [col3]+'-' + [col4]+'-' + [col5]+'-' + [col6] + ' '
'- ','')))
as totalCol
FROM ...
</code>```

Body:
this is my Data

col1    col2    col col3    col4    col5    col6
42      A       11  18      89      16      empty
42      B       12  empty   89      14      C
36      8       9   empty   empty   2       empty

this is the Script I'm running

select col1 + COALESCE ([col2]+'-','')
+COALESCE([col3]+'-','')+COALESCE([col4]+'-','')
+COALESCE([col5]+'-','')+COALESCE([col6],'') as totalCol
FROM ...

This is what I get

totalCol
42A-11-18-89-16-
42B-12- -89-14-C
368-9- - -2 -

This is what I want

totalCol
42A-11-18-89-16
42B-12-89-14-C
368-9-2

Body:
run a replace of "- " to "" after your script

also you have to remember that nulls and blank space are two different things.

Updated script

select ltrim(rtrim(replace(replace(
col1 + COALESCE ([col2]+'-','')
+COALESCE([col3]+'-','')+COALESCE([col4]+'-','')
+COALESCE([col5]+'-','')+COALESCE([col6],'') + ' ','--','-'),
'- ','')))
as totalCol
FROM ...

or  assuming only blank space and not nulls

select ltrim(rtrim(replace(
[col1] + [col2]+'-' + [col3]+'-' + [col4]+'-' + [col5]+'-' + [col6] + ' '
'- ','')))
as totalCol
FROM ...


问:
Spring REST repository not exposed
It is strange but when I have in Spring Boot the following Spring Data Rest in  config

```<code>spring:
  data:
    rest:
      default-media-type: application/json
      detection-strategy: annotated
</code>```

and class

```<code>@RepositoryRestResource
public interface RestRestaurantRepo extends CrudRepository<Restaurant, Long> {

}
</code>```

It is not exposed. However when I change it to any config where I leave out of the config props like

```<code>spring:
  data:
    rest:
      detection-strategy: annotated
</code>```

or:

```<code>spring:
  data:
    rest:
      default-media-type: application/json
</code>```

it works. What can be done about this ?

答: It is working perfectly fine for me. Do recheck. By default the mediatype is application/hal+json. But when you override it from application.properties, it is changed to application/json. But the Rest endpoints work perfectlyy fine. It is working even with or without detection-strategy. I am using spring-data-rest 2.6.1

Title: Spring REST repository not exposed

Body:
It is strange but when I have in Spring Boot the following Spring Data Rest in  config

spring:
  data:
    rest:
      default-media-type: application/json
      detection-strategy: annotated

and class

@RepositoryRestResource
public interface RestRestaurantRepo extends CrudRepository<Restaurant, Long> {

}

It is not exposed. However when I change it to any config where I leave out of the config props like

spring:
  data:
    rest:
      detection-strategy: annotated

or:

spring:
  data:
    rest:
      default-media-type: application/json

it works. What can be done about this ?


问:
How to extract value of an element based on its sibling element in a parent node using xpath or xquery?
I have a payload which like this,

```<code><Payload>
  <Identifier>
    <Type>typeA</Type>
    <Value>valueOfA</Value>
  </Identifier>
  <Identifier>
    <Type>typeB</Type>
    <Value>valueOfB</Value>
  </Identifier>
</Payload>
</code>```

I want to extract the value of element 'typeA' using xpath or xquery to proceed further so that my transformed payload looks like this

```<code><transformedPayload>
<typeA>valueOfA</typeA>
<typeB><valueOfB</typeB>
</transformedPayload>
</code>```

Please help.
Thanks in advance.

答:
This is very easily done in XQuery. The following query does what you want:

```<code><transformedPayload>{
  for $ident in /Payload/Identifier
  return element { $ident/Type } { $ident/Value/text() }
}</transformedPayload>
</code>```

If you want to select only a subset of all Identifiers, you can use the where clause:

```<code><transformedPayload>{
  for $ident in /Payload/Identifier
  where $ident/Type eq 'typeA'
     or $ident/Type eq 'typeB'
  return element { $ident/Type } { $ident/Value/text() }
}</transformedPayload>
</code>```

You can also use the = operator and its existantial semantics to make this more compact:

```<code><transformedPayload>{
  for $ident in /Payload/Identifier
  where $ident/Type = ('typeA', 'typeB')
  return element { $ident/Type } { $ident/Value/text() }
}</transformedPayload>
</code>```

Body:
I have a payload which like this,

<Payload>
  <Identifier>
    <Type>typeA</Type>
    <Value>valueOfA</Value>
  </Identifier>
  <Identifier>
    <Type>typeB</Type>
    <Value>valueOfB</Value>
  </Identifier>
</Payload>

I want to extract the value of element 'typeA' using xpath or xquery to proceed further so that my transformed payload looks like this

<transformedPayload>
<typeA>valueOfA</typeA>
<typeB><valueOfB</typeB>
</transformedPayload>

Please help.
Thanks in advance.

Body:
This is very easily done in XQuery. The following query does what you want:

<transformedPayload>{
  for $ident in /Payload/Identifier
  return element { $ident/Type } { $ident/Value/text() }
}</transformedPayload>

If you want to select only a subset of all Identifiers, you can use the where clause:

<transformedPayload>{
  for $ident in /Payload/Identifier
  where $ident/Type eq 'typeA'
     or $ident/Type eq 'typeB'
  return element { $ident/Type } { $ident/Value/text() }
}</transformedPayload>

You can also use the = operator and its existantial semantics to make this more compact:

<transformedPayload>{
  for $ident in /Payload/Identifier
  where $ident/Type = ('typeA', 'typeB')
  return element { $ident/Type } { $ident/Value/text() }
}</transformedPayload>


问:
Creating a table of counts by some factor level in R
I have some data of foods eaten on different days.

```<code>day <- c(1,1,1,1,2,2,2,3,3,3,3,3)
food <- c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
all <- data.frame(day, food)
</code>```

I'd like to create a table with food on the x axis, day on the y axis, and the number of foods per day in the matrices such that

```<code>food.list <- unique(all$food)
 day.list <- unique(all$day )
output <- data.frame(c(2,1,1),c(0,2,1),c(2,2,1))
output
      1 2 3
pizza 2 0 2
taco  1 2 2
snake 1 1 1
</code>```

What is a straightforward way to solve this problem?

答:
It would be "tidier" to leave day, food and count in different columns. Note: I added stringsAsFactors = FALSE when creating the data frame, it avoids issues later.

```<code>library(dplyr)
all %>%
  group_by(day, food) %>%
  tally()
</code>```

But you can always spread if you really want days as columns:

```<code>library(tidyr)
all %>%
  group_by(day, food) %>%
  tally() %>%
  spread(day, n)

# A tibble: 3 × 4
    food   `1`   `2`   `3`
* <chr> <int> <int> <int>
1  pizza     2    NA     2
2  snake     1     1     1
3   taco     1     2     2
</code>```

and if you want NA to be 0, add:

```<code>%>%
  mutate_if(is.integer, funs(replace(., is.na(.), 0)))
</code>```

Body:
I have some data of foods eaten on different days.

day <- c(1,1,1,1,2,2,2,3,3,3,3,3)
food <- c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
all <- data.frame(day, food)

I'd like to create a table with food on the x axis, day on the y axis, and the number of foods per day in the matrices such that

food.list <- unique(all$food)
 day.list <- unique(all$day )
output <- data.frame(c(2,1,1),c(0,2,1),c(2,2,1))
output
      1 2 3
pizza 2 0 2
taco  1 2 2
snake 1 1 1

What is a straightforward way to solve this problem?

Body:
It would be "tidier" to leave day, food and count in different columns. Note: I added stringsAsFactors = FALSE when creating the data frame, it avoids issues later.

library(dplyr)
all %>%
  group_by(day, food) %>%
  tally()

But you can always spread if you really want days as columns:

library(tidyr)
all %>%
  group_by(day, food) %>%
  tally() %>%
  spread(day, n)

# A tibble: 3 × 4
    food   `1`   `2`   `3`
* <chr> <int> <int> <int>
1  pizza     2    NA     2
2  snake     1     1     1
3   taco     1     2     2

and if you want NA to be 0, add:

%>%
  mutate_if(is.integer, funs(replace(., is.na(.), 0)))


问:
Python wildcard in the middle of a string
I have a directory with a number of files which all have the same basic filename format (below is a sample)

```<code>roll_0_oe_2008-03-24_AAA.XNGS
roll_0_oe_2008-03-24_AAB.XNGS
roll_1_oe_2008-03-31_AAC.XNGS
roll_1_oe_2008-03-31_AAG.XNGS
roll_2_oe_2008-04-07_AAR.XNGS
roll_2_oe_2008-04-07_AAJ.XNGS
</code>```

I am trying to select a file based on using:

```<code>filename = 'roll_'+str(roll)'_'*ID
</code>```

where roll is an int that I convert to a string and ID is a string.  I'm using the wildcard * for the _oe_date element as i don't care about this part. I however get the following error:

```<code>TypeError: can't multiply sequence by non-int of type 'str'
</code>```

How can I construct a filename using  wildcard in the middle?

答:
I think you want the glob module, and the str.format(...) method:

```<code># Don't know where this comes from.
roll = 2
id = 'AAC'

# Format: roll_2_oe_2008-04-07_AAJ.XNGS
Fn_format= "roll_{}_oe_*_{}.XNGS"

# Make a file-glob by putting the roll into format.
rolled_files = Fn_format.format(roll, id)

import glob

for fname in glob.iglob(rolled_files):
    print("Rolled file:", fname)
</code>```

Body:
I have a directory with a number of files which all have the same basic filename format (below is a sample)

roll_0_oe_2008-03-24_AAA.XNGS
roll_0_oe_2008-03-24_AAB.XNGS
roll_1_oe_2008-03-31_AAC.XNGS
roll_1_oe_2008-03-31_AAG.XNGS
roll_2_oe_2008-04-07_AAR.XNGS
roll_2_oe_2008-04-07_AAJ.XNGS

I am trying to select a file based on using:

filename = 'roll_'+str(roll)'_'*ID

where roll is an int that I convert to a string and ID is a string.  I'm using the wildcard * for the _oe_date element as i don't care about this part. I however get the following error:

TypeError: can't multiply sequence by non-int of type 'str'

How can I construct a filename using  wildcard in the middle?

Body:
I think you want the glob module, and the str.format(...) method:

# Don't know where this comes from.
roll = 2
id = 'AAC'

# Format: roll_2_oe_2008-04-07_AAJ.XNGS
Fn_format= "roll_{}_oe_*_{}.XNGS"

# Make a file-glob by putting the roll into format.
rolled_files = Fn_format.format(roll, id)

import glob

for fname in glob.iglob(rolled_files):
    print("Rolled file:", fname)


问:
Regex - Find Name With No Middle Initial
I'm doing a query on an SQL database and need to write a regular expression to find names with no middle initial.

For example.

Michael J. Fox - Should fail

Michael J Fox - Should fail

Michael Fox - Should pass

Full names in the database are stored in a single string for reference.

答:
You can count space and filter out result like

where length('Michael J Fox')-length(replace('Michael J Fox',' ',''))<2


问:
ts2304 cannot find name 'OnInit'
I've worked through the Angular superhero tutorial. It all works.

If i close the cmd window running NPM, then re-open a CMD window and reissue the NPM START command I get two errors

```<code>src/app/DashBoard.component.ts(12,44)  TS2304 : Cannot find name 'OnInit'.
src/app/hero-list.component.ts(16, 434)  TS2304 : Cannot find name 'OnInit'.
</code>```

I can resolve this by removing

```<code>Implements OnInit
</code>```

from both these classes,
run NPM start
re-add them  (simply CTL Z in the editor)
make some change , save.
The app recompiles and I am off and running.

I have 4 classes that implement this function. I have studied them and can not figure out what makes 2 fail...

I have read posts that reference TS2304, but this seems to be a generic Function/Variable/Symbol not found message ...

I don't know what to post. I'm happy to post any of the code.

Is this caused by errors in modules this depends on (hero.ts)?

Here is one class that is failing in this manner.
This is the hero-list.component.ts file
(at various points in the demo/online examples, this is also named Heroes.component..)

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { Hero  } from './hero';
import { HeroService  } from './hero.service';

@Component({
  selector: 'hero-list',
  templateUrl: './hero-list.component.html' ,
  providers: [HeroService],
  styleUrls: [ './hero-list.component.css']
})

export class HeroListComponent implements OnInit   {

    heroes : Hero[];
    selectedHero: Hero;

    constructor(
        private router : Router ,
        private heroService: HeroService
        ) { }

    ngOnInit(): void {
        this.getHeroes();
    }

    onSelect(hero: Hero): void {
        this.selectedHero = hero;
    }

    getHeroes(): void {
        this.heroService.getHeroes().then(heroes => this.heroes = heroes);
    }

    gotoDetail() {
        this.router.navigate(['/detail', this.selectedHero.id]);
    }

    add(name: string): void {
        name = name.trim();
        if (!name) { return; }
        this.heroService.create(name)
            .then(hero => {
                this.heroes.push(hero);
                this.selectedHero = null;
            });
    }
    delete(hero: Hero): void {
        this.heroService
            .delete(hero.id)
            .then(() => {
                this.heroes = this.heroes.filter(h => h !== hero);
                if (this.selectedHero === hero) { this.selectedHero = null; }
            });
    }
}
</code>```

答:
You have to import OnInit.</p>

```<code>import { Component, OnInit } from '@angular/core';
</code>```

Title: ts2304 cannot find name 'OnInit'

Body:
I've worked through the Angular superhero tutorial. It all works.

If i close the cmd window running NPM, then re-open a CMD window and reissue the NPM START command I get two errors

src/app/DashBoard.component.ts(12,44)  TS2304 : Cannot find name 'OnInit'.
src/app/hero-list.component.ts(16, 434)  TS2304 : Cannot find name 'OnInit'.

I can resolve this by removing

Implements OnInit

from both these classes,
run NPM start
re-add them  (simply CTL Z in the editor)
make some change , save.
The app recompiles and I am off and running.

I have 4 classes that implement this function. I have studied them and can not figure out what makes 2 fail...

I have read posts that reference TS2304, but this seems to be a generic Function/Variable/Symbol not found message ...

I don't know what to post. I'm happy to post any of the code.

Is this caused by errors in modules this depends on (hero.ts)?

Here is one class that is failing in this manner.
This is the hero-list.component.ts file
(at various points in the demo/online examples, this is also named Heroes.component..)

import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { Hero  } from './hero';
import { HeroService  } from './hero.service';

@Component({
  selector: 'hero-list',
  templateUrl: './hero-list.component.html' ,
  providers: [HeroService],
  styleUrls: [ './hero-list.component.css']
})

export class HeroListComponent implements OnInit   {

    heroes : Hero[];
    selectedHero: Hero;

    constructor(
        private router : Router ,
        private heroService: HeroService
        ) { }

    ngOnInit(): void {
        this.getHeroes();
    }

    onSelect(hero: Hero): void {
        this.selectedHero = hero;
    }

    getHeroes(): void {
        this.heroService.getHeroes().then(heroes => this.heroes = heroes);
    }

    gotoDetail() {
        this.router.navigate(['/detail', this.selectedHero.id]);
    }

    add(name: string): void {
        name = name.trim();
        if (!name) { return; }
        this.heroService.create(name)
            .then(hero => {
                this.heroes.push(hero);
                this.selectedHero = null;
            });
    }
    delete(hero: Hero): void {
        this.heroService
            .delete(hero.id)
            .then(() => {
                this.heroes = this.heroes.filter(h => h !== hero);
                if (this.selectedHero === hero) { this.selectedHero = null; }
            });
    }
}

Body:
You have to import OnInit.

import { Component, OnInit } from '@angular/core';


问:
How to implement a command that allows user to add and delete tabs in the application?
I am trying to make an app with tabs at the top that link a website too each one, such as a computer that uses tabs in safari or firefox. What I am trying to do is implement an add and delete class that will allow the user to delete a tab if wanted and add another that will link to a different website. Any help would be greatly appreciated.

Here is the main java file.

```<code>public class UniversityofColorado extends TabActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TabHost host=getTabHost();

    host.addTab(host.newTabSpec("one")
            .setIndicator("Google")
            .setContent(new Intent(this, Hello.class)));

    host.addTab(host.newTabSpec("two")
                    .setIndicator("Colorado Main Site")
                    .setContent(new Intent(this, ColoradoMainSiteBrowser.class)));

    host.addTab(host.newTabSpec("three")
                    .setIndicator("CULearn")
                    .setContent(new Intent(this, CULearnBrowser.class)));

    host.addTab(host.newTabSpec("four")
            .setIndicator("CULink")
            .setContent(new Intent(this, CULinkBrowser.class)));

    host.addTab(host.newTabSpec("five")
            .setIndicator("MyCUInfo")
            .setContent(new Intent(this, MyCUInfoBrowser.class)));

    host.addTab(host.newTabSpec("six")
            .setIndicator("Campus Map")
            .setContent(new Intent(this, CampusBrowser.class)));

    host.addTab(host.newTabSpec("Seven")
            .setIndicator("Notes")
            .setContent(new Intent(this, Notepadv3.class)));
}

    // Inflates menu when "menu Key" is pressed
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
}
</code>```

This is one of the java files that the main java file uses:

```<code>public class ColoradoMainSiteBrowser extends Activity {

WebView webview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://colorado.edu/");
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
</code>```

How would I implement the add and delete buttons to have this same format when the new tabs were added.

答:
In order to achieve the desired effect, you probably need to drop an activity for each tab approach.

Instead, you would create a "default" view that you can use to all websites that accept the URL as a parameter.

Then, instead of "intenting" a new activity to each tab, you Inflate that view to the new tab, passing the URL as a parameter.

To create and delete tabs dinamically would be easy. A simple button that Inflates/removes the view would sufice.

XML

res/layout/main.xml

```<code><TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp" />
    </LinearLayout>
</TabHost>
</code>```

res/layout/tab.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
>
<TextView
android:id="@+id/url_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HELLO TAB!"
>
</TextView>
</LinearLayout>
</code>```

res/menu/menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:enabled="true" android:visible="true" android:icon="@android:drawable/ic_menu_add" android:title="Add Website" android:titleCondensed="add" android:id="@+id/add"></item>
<item android:titleCondensed="Delete" android:enabled="true" android:visible="true" android:icon="@android:drawable/ic_menu_delete" android:id="@+id/delete" android:title="Delete Website"></item>
</menu>
</code>```

JAVA CODE

main.java

```<code>import android.app.TabActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;

public class Main extends TabActivity implements TabHost.TabContentFactory {

    TabHost tabHost;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.tabHost = getTabHost();  // The activity TabHost

        tabHost.addTab(tabHost.newTabSpec("http://www.google.com/").setIndicator("Google").setContent(this));
        tabHost.addTab(tabHost.newTabSpec("http://www.stackoverflow.com/").setIndicator("StackOverflow").setContent(this));
    }

    public View createTabContent(String tag) {

        // Inflation per se.
        // we don't return anything yet so we can work with this view
        View tab = View.inflate(this, R.layout.tab, null);

        // Here we work with the view
        // in this case we set the textview to match our tag
        // its a good way to parse arguments to the new tab
        TextView tv = (TextView) tab.findViewById(R.id.url_tv);
        tv.setText(tag);

        //After work we can return view
        return tab;
    }

    private void addMethod(String webSiteURL, String webSiteName) {

        // Find a way that suits you to pass arguments to here

        tabHost.addTab(tabHost.newTabSpec(webSiteURL).setIndicator(webSiteName).setContent(this));

    }

    private void deleteMethod() {

        // Create a way to decide which tab to delete.
        // for instance, FindViewByTag is a method of ViewGroup and works
        // then call the parent of the view with
        // ViewGroup parent = (ViewGroup) viewToDelete.getParent();
        // finally use oarent.removeView(viewToDelete);

    }

    // Inflates menu when "menu Key" is pressed
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    // This method is called once the menu is selected
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.add:

                // These variable is created artificially so that something is passed to our addMethod
                // You should find a way to pass these argument to our method
                // can be a dialog screen, or getting the URL from somewhere
                // its your call
                String webSiteURL = "http://www.evonytools.org/";
                String webSiteName = "Tivie's Tools";

                addMethod(webSiteURL, webSiteName);

            case R.id.delete:

                deleteMethod();

                break;
        }
        return true;
    }
}
</code>```

Body:
I am trying to make an app with tabs at the top that link a website too each one, such as a computer that uses tabs in safari or firefox. What I am trying to do is implement an add and delete class that will allow the user to delete a tab if wanted and add another that will link to a different website. Any help would be greatly appreciated.

Here is the main java file.

public class UniversityofColorado extends TabActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TabHost host=getTabHost();

    host.addTab(host.newTabSpec("one")
            .setIndicator("Google")
            .setContent(new Intent(this, Hello.class)));

    host.addTab(host.newTabSpec("two")
                    .setIndicator("Colorado Main Site")
                    .setContent(new Intent(this, ColoradoMainSiteBrowser.class)));

    host.addTab(host.newTabSpec("three")
                    .setIndicator("CULearn")
                    .setContent(new Intent(this, CULearnBrowser.class)));

    host.addTab(host.newTabSpec("four")
            .setIndicator("CULink")
            .setContent(new Intent(this, CULinkBrowser.class)));

    host.addTab(host.newTabSpec("five")
            .setIndicator("MyCUInfo")
            .setContent(new Intent(this, MyCUInfoBrowser.class)));

    host.addTab(host.newTabSpec("six")
            .setIndicator("Campus Map")
            .setContent(new Intent(this, CampusBrowser.class)));

    host.addTab(host.newTabSpec("Seven")
            .setIndicator("Notes")
            .setContent(new Intent(this, Notepadv3.class)));
}

    // Inflates menu when "menu Key" is pressed
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
}

This is one of the java files that the main java file uses:

public class ColoradoMainSiteBrowser extends Activity {

WebView webview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://colorado.edu/");
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

How would I implement the add and delete buttons to have this same format when the new tabs were added.

Body:
In order to achieve the desired effect, you probably need to drop an activity for each tab approach.

Instead, you would create a "default" view that you can use to all websites that accept the URL as a parameter.

Then, instead of "intenting" a new activity to each tab, you Inflate that view to the new tab, passing the URL as a parameter.

To create and delete tabs dinamically would be easy. A simple button that Inflates/removes the view would sufice.

XML

res/layout/main.xml

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp" />
    </LinearLayout>
</TabHost>

res/layout/tab.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
>
<TextView
android:id="@+id/url_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HELLO TAB!"
>
</TextView>
</LinearLayout>

res/menu/menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:enabled="true" android:visible="true" android:icon="@android:drawable/ic_menu_add" android:title="Add Website" android:titleCondensed="add" android:id="@+id/add"></item>
<item android:titleCondensed="Delete" android:enabled="true" android:visible="true" android:icon="@android:drawable/ic_menu_delete" android:id="@+id/delete" android:title="Delete Website"></item>
</menu>

JAVA CODE

main.java

import android.app.TabActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;

public class Main extends TabActivity implements TabHost.TabContentFactory {

    TabHost tabHost;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.tabHost = getTabHost();  // The activity TabHost

        tabHost.addTab(tabHost.newTabSpec("http://www.google.com/").setIndicator("Google").setContent(this));
        tabHost.addTab(tabHost.newTabSpec("http://www.stackoverflow.com/").setIndicator("StackOverflow").setContent(this));
    }

    public View createTabContent(String tag) {

        // Inflation per se.
        // we don't return anything yet so we can work with this view
        View tab = View.inflate(this, R.layout.tab, null);

        // Here we work with the view
        // in this case we set the textview to match our tag
        // its a good way to parse arguments to the new tab
        TextView tv = (TextView) tab.findViewById(R.id.url_tv);
        tv.setText(tag);

        //After work we can return view
        return tab;
    }

    private void addMethod(String webSiteURL, String webSiteName) {

        // Find a way that suits you to pass arguments to here

        tabHost.addTab(tabHost.newTabSpec(webSiteURL).setIndicator(webSiteName).setContent(this));

    }

    private void deleteMethod() {

        // Create a way to decide which tab to delete.
        // for instance, FindViewByTag is a method of ViewGroup and works
        // then call the parent of the view with
        // ViewGroup parent = (ViewGroup) viewToDelete.getParent();
        // finally use oarent.removeView(viewToDelete);

    }

    // Inflates menu when "menu Key" is pressed
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    // This method is called once the menu is selected
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.add:

                // These variable is created artificially so that something is passed to our addMethod
                // You should find a way to pass these argument to our method
                // can be a dialog screen, or getting the URL from somewhere
                // its your call
                String webSiteURL = "http://www.evonytools.org/";
                String webSiteName = "Tivie's Tools";

                addMethod(webSiteURL, webSiteName);

            case R.id.delete:

                deleteMethod();

                break;
        }
        return true;
    }
}


问:
Does anyone see the error in this simple Ruby function?
This function is supposed to take a string and return the characters in reverse order.

```<code>def reverse(string)

    reversedString = "";

        i = string.length - 1
        while i >= 0
          reversedString = reversedString + string[i]
          i -= 1
        end
    puts reversedString

end
</code>```

however all the tests return false:

```<code>puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)

puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)

puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)
</code>```

Does anyone see what the problem is?

答:
To make this more Ruby-like yet avoid using the built-in String#reverse method you'd do this:

```<code>def reverse(string)
  string.chars.reverse.join('')
end
</code>```

Remember that in Ruby the result of the last operation is automatically the return value of the method. In your case the last operation is puts which always returns nil, eating your value. You want to pass it through.

Try to design methods with a simple mandate, that is, this function should focus on doing one job and one job only: reversing a string. Displaying it is beyond that mandate, so that's a job for another method, like perhaps the caller.

To avoid calling any sort of reverse method at all:

```<code>def reverse(string)
  result = ''
  length = string.length

  length.times do |i|
    result << string[length - 1 - i]
  end

  result
end
</code>```

You can often avoid for almost completely and while frequently if you use things like times or ranges (0..n) to iterate over.

Body:
This function is supposed to take a string and return the characters in reverse order.

def reverse(string)

    reversedString = "";

        i = string.length - 1
        while i >= 0
          reversedString = reversedString + string[i]
          i -= 1
        end
    puts reversedString

end

however all the tests return false:

puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)

puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)

puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)

Does anyone see what the problem is?

Body:
To make this more Ruby-like yet avoid using the built-in String#reverse method you'd do this:

def reverse(string)
  string.chars.reverse.join('')
end

Remember that in Ruby the result of the last operation is automatically the return value of the method. In your case the last operation is puts which always returns nil, eating your value. You want to pass it through.

Try to design methods with a simple mandate, that is, this function should focus on doing one job and one job only: reversing a string. Displaying it is beyond that mandate, so that's a job for another method, like perhaps the caller.

To avoid calling any sort of reverse method at all:

def reverse(string)
  result = ''
  length = string.length

  length.times do |i|
    result << string[length - 1 - i]
  end

  result
end

You can often avoid for almost completely and while frequently if you use things like times or ranges (0..n) to iterate over.


问:
Microsoft Botframework and Data Protection
I'm using MS Bot Framework with Directline for webchat and our client has raised an issue about Data Protection i.e. the user is sending personal data via a Microsoft api.

I don't really know how to reply to this since (a) Pretty much every bot uses a cloud service if you want any sort of assistance and (b) I assume that Directline does nothing with the data and it is purely a conduit, but I don't know that for a fact.

Was going to post on bot builder github issues, but they say it's just for bugs and suggested that I come here. I am looking for some clarification (or a contact at MS) about the privacy and data protection of the conversations if you are using Microsoft's bot framework with any one of their connection services - particularly Directline.

Thanks,
Jarrod

答:
Our official handling terms are listed under the Bot Framework Terms of Service and Privacy statement found on the Bot Framework portal. Are there specific questions your customer has?

-jim


问:
Traversing a binary tree using linked list
I am trying to do a preorder traversal of binary tree using a linked list.

```<code>class BTNode:
"""A node in a binary tree."""

    def __init__(self: 'BTNode', item: object,
             left: 'BTNode' =None, right: 'BTNode' =None) -> None:

        self.item, self.left, self.right = item, left, right

class LLNode:
    """A node in a linked list."""

    def __init__(self: 'LLNode', item: object, link: 'LLNode' =None) -> None:

        self.item, self.link = item, link

    def __str__(self: 'LLNode') -> str:
        """Return an informative string showing self

        >>> b = LLNode(1, LLNode(2, LLNode(3)))
        >>> str(b)
        '1 -> 2 -> 3'
        """
        return str(self.item) + (' -> ' + str(self.link) if self.link else '')

def preorder(root: BTNode) -> LLNode:
    """Return the first node in a linked list that contains every value from the
    binary tree rooted at root, listed according to an preorder traversal.

    >>> b = BTNode(1, BTNode(2), BTNode(3))
    >>> repr(preorder(b))
   'LLNode(1, LLNode(2, LLNode(3)))'
   >>> b2 = BTNode(4, BTNode(5))
   >>> b3 = BTNode(7, b, b2)
   >>> str(preorder(b3))
   '7 -> 1 -> 2 -> 3 -> 4 -> 5'
    """

    return _preorder(root)[0]

def _preorder(root: BTNode) -> (LLNode, LLNode):
    """Return the first and last nodes in a linked list that contains every
    value from the binary tree rooted at root, listed according to an preorder
    traversal.
    """

    if not root:
        return None, None

    left_head, left_tail = _preorder(root.left)

    right_head, right_tail = _preorder(root.right)

    # change from right_tail = left_tail to right_tail = left_head
    if not right_tail:
        right_tail = left_head

    if not left_head:
        left_head = right_head

    if left_tail:
        left_tail.link = right_head

    root_node = LLNode(root.item, left_head)

    return root_node, right_tail
</code>```

I am always getting '7 -> 1 -> 2' instead of '7 -> 1 -> 2 -> 3 -> 4 -> 5' as my output in preorder function. I am not quite sure why. Could someone please tell me how I can edit my current code to fix this problem?

答:
You haven't returned the tail of the list properly.  I added some debugging instrumentation to trace the operation of _preorder -- which is something you should do before posting here.  Debugging is a critical skill.

```<code>indent = ""
def _preorder(root: BTNode) -> (LLNode, LLNode):
    """Return the first and last nodes in a linked list that contains every
    value from the binary tree rooted at root, listed according to an preorder
    traversal.
    """
    global indent
    print(indent, "  ENTER", root.item if root else "NULL")

    if not root:
        return None, None

    indent += "  "
    left_head, left_tail = _preorder(root.left)
    print (indent, root.item, "Left ", left_head, left_tail, str(left_head))
    right_head, right_tail = _preorder(root.right)
    print (indent, root.item, "Right", right_head, right_tail, str(right_head))

    if not right_tail:
        right_tail = left_tail

    if not left_head:
        left_head = right_head

    if left_tail:
        left_tail.link = right_head

    root_node = LLNode(root.item, left_head)

    print (indent, "LEAVE", root.item, right_tail.item if right_tail else "NULL")
    indent = indent[2:]
    return root_node, right_tail
</code>```

Output for the full traversal is below.  You can see that you never link in the right side properly; I'll leave the repair as an exercise for the student.  :-)

```<code>   ENTER 7
     ENTER 1
       ENTER 2
         ENTER NULL
       2 Left  None None None
         ENTER NULL
       2 Right None None None
       LEAVE 2 NULL
     1 Left  2 None 2
       ENTER 3
         ENTER NULL
       3 Left  None None None
         ENTER NULL
       3 Right None None None
       LEAVE 3 NULL
     1 Right 3 None 3
     LEAVE 1 NULL
   7 Left  1 -> 2 None 1 -> 2
     ENTER 4
       ENTER 5
         ENTER NULL
       5 Left  None None None
         ENTER NULL
       5 Right None None None
       LEAVE 5 NULL
     4 Left  5 None 5
       ENTER NULL
     4 Right None None None
     LEAVE 4 NULL
   7 Right 4 -> 5 None 4 -> 5
   LEAVE 7 NULL

Main: 7 -> 1 -> 2
</code>```

RESPONSE TO OP UPDATE

Obviously, that fixed part of your problem.  Now, let's look at what happens when you return from the calls for node 1's left and right subtrees, and try to link those properly into the linear list:

```<code>left_head, left_tail = _preorder(root.left)
# returns 2, None
right_head, right_tail = _preorder(root.right)
# returns 3, None

if not right_tail:
    right_tail = left_head
# right_tail is now node 2; this isn't correct: node 3 should be in that spot.

if not left_head:
# left_head is node 2; not an issue now

if left_tail:
# left_tail is None; not an issue now

return root_node, right_tail
# You return nodes 1 and 2;
#   you never linked node 2 to node 3.
# You need to fix this.
</code>```

Body:
I am trying to do a preorder traversal of binary tree using a linked list.

class BTNode:
"""A node in a binary tree."""

    def __init__(self: 'BTNode', item: object,
             left: 'BTNode' =None, right: 'BTNode' =None) -> None:

        self.item, self.left, self.right = item, left, right

class LLNode:
    """A node in a linked list."""

    def __init__(self: 'LLNode', item: object, link: 'LLNode' =None) -> None:

        self.item, self.link = item, link

    def __str__(self: 'LLNode') -> str:
        """Return an informative string showing self

        >>> b = LLNode(1, LLNode(2, LLNode(3)))
        >>> str(b)
        '1 -> 2 -> 3'
        """
        return str(self.item) + (' -> ' + str(self.link) if self.link else '')

def preorder(root: BTNode) -> LLNode:
    """Return the first node in a linked list that contains every value from the
    binary tree rooted at root, listed according to an preorder traversal.

    >>> b = BTNode(1, BTNode(2), BTNode(3))
    >>> repr(preorder(b))
   'LLNode(1, LLNode(2, LLNode(3)))'
   >>> b2 = BTNode(4, BTNode(5))
   >>> b3 = BTNode(7, b, b2)
   >>> str(preorder(b3))
   '7 -> 1 -> 2 -> 3 -> 4 -> 5'
    """

    return _preorder(root)[0]

def _preorder(root: BTNode) -> (LLNode, LLNode):
    """Return the first and last nodes in a linked list that contains every
    value from the binary tree rooted at root, listed according to an preorder
    traversal.
    """

    if not root:
        return None, None

    left_head, left_tail = _preorder(root.left)

    right_head, right_tail = _preorder(root.right)

    # change from right_tail = left_tail to right_tail = left_head
    if not right_tail:
        right_tail = left_head

    if not left_head:
        left_head = right_head

    if left_tail:
        left_tail.link = right_head

    root_node = LLNode(root.item, left_head)

    return root_node, right_tail

I am always getting '7 -> 1 -> 2' instead of '7 -> 1 -> 2 -> 3 -> 4 -> 5' as my output in preorder function. I am not quite sure why. Could someone please tell me how I can edit my current code to fix this problem?

Body:
You haven't returned the tail of the list properly.  I added some debugging instrumentation to trace the operation of _preorder -- which is something you should do before posting here.  Debugging is a critical skill.

indent = ""
def _preorder(root: BTNode) -> (LLNode, LLNode):
    """Return the first and last nodes in a linked list that contains every
    value from the binary tree rooted at root, listed according to an preorder
    traversal.
    """
    global indent
    print(indent, "  ENTER", root.item if root else "NULL")

    if not root:
        return None, None

    indent += "  "
    left_head, left_tail = _preorder(root.left)
    print (indent, root.item, "Left ", left_head, left_tail, str(left_head))
    right_head, right_tail = _preorder(root.right)
    print (indent, root.item, "Right", right_head, right_tail, str(right_head))

    if not right_tail:
        right_tail = left_tail

    if not left_head:
        left_head = right_head

    if left_tail:
        left_tail.link = right_head

    root_node = LLNode(root.item, left_head)

    print (indent, "LEAVE", root.item, right_tail.item if right_tail else "NULL")
    indent = indent[2:]
    return root_node, right_tail

Output for the full traversal is below.  You can see that you never link in the right side properly; I'll leave the repair as an exercise for the student.  :-)

   ENTER 7
     ENTER 1
       ENTER 2
         ENTER NULL
       2 Left  None None None
         ENTER NULL
       2 Right None None None
       LEAVE 2 NULL
     1 Left  2 None 2
       ENTER 3
         ENTER NULL
       3 Left  None None None
         ENTER NULL
       3 Right None None None
       LEAVE 3 NULL
     1 Right 3 None 3
     LEAVE 1 NULL
   7 Left  1 -> 2 None 1 -> 2
     ENTER 4
       ENTER 5
         ENTER NULL
       5 Left  None None None
         ENTER NULL
       5 Right None None None
       LEAVE 5 NULL
     4 Left  5 None 5
       ENTER NULL
     4 Right None None None
     LEAVE 4 NULL
   7 Right 4 -> 5 None 4 -> 5
   LEAVE 7 NULL

Main: 7 -> 1 -> 2

RESPONSE TO OP UPDATE

Obviously, that fixed part of your problem.  Now, let's look at what happens when you return from the calls for node 1's left and right subtrees, and try to link those properly into the linear list:

left_head, left_tail = _preorder(root.left)
# returns 2, None
right_head, right_tail = _preorder(root.right)
# returns 3, None

if not right_tail:
    right_tail = left_head
# right_tail is now node 2; this isn't correct: node 3 should be in that spot.

if not left_head:
# left_head is node 2; not an issue now

if left_tail:
# left_tail is None; not an issue now

return root_node, right_tail
# You return nodes 1 and 2;
#   you never linked node 2 to node 3.
# You need to fix this.


问:
activate_page doesn't work in intelXDK
I'm building an mobile app using IntelXDK. I want to switch page (it has different layout than current one) and I want to use activate_page method.

If I enter it through "design view" it works fine, but when I copypaste it to my custom event I've got an error:

```<code>'activate_page' is not defined. (W117)
</code>```

What I'm doing wrong? Please help.

This is my code, everything works fine till the last code line:

```<code>$("#product-list").on("click", "li a", function(evt)
{
  /* your code goes here */
  productId = $(this).data('id'); //this is variable defined in outer scope - not important right now
  showProduct(productId); // this is my other custom function which works - not important right now
  activate_page("#product-details-view");  //this line doesn't work - very important right now ;)
});
</code>```

To answer futere questions - yes, I have product-details-view page.

答:
You need to include jshint global directive before calling activate_page:

```<code>/* global activate_page */
activate_page("#product-details-view");
</code>```

or you can configure it manually using a jshint resource file.

See http://www.jshint.com/docs/ for more information regarding jshint.

Title: activate_page doesn't work in intelXDK

Body:
I'm building an mobile app using IntelXDK. I want to switch page (it has different layout than current one) and I want to use activate_page method.

If I enter it through "design view" it works fine, but when I copypaste it to my custom event I've got an error:

'activate_page' is not defined. (W117)

What I'm doing wrong? Please help.

This is my code, everything works fine till the last code line:

$("#product-list").on("click", "li a", function(evt)
{
  /* your code goes here */
  productId = $(this).data('id'); //this is variable defined in outer scope - not important right now
  showProduct(productId); // this is my other custom function which works - not important right now
  activate_page("#product-details-view");  //this line doesn't work - very important right now ;)
});

To answer futere questions - yes, I have product-details-view page.

Body:
You need to include jshint global directive before calling activate_page:

/* global activate_page */
activate_page("#product-details-view");

or you can configure it manually using a jshint resource file.

See http://www.jshint.com/docs/ for more information regarding jshint.


问:
iOS Swift 3 Storing NSArray Values To Realm
In my Application we are using Realm Storage for storing values locally. I can Able To Store my Array Values As Sting. But Not Able To Store and Retrive Values As Array. Is It Possible To Store NSArray Values To Realm Object and Retrieve It As NSArray.
Here Is The Code I Have Used To Store String Values:

```<code>class PracticeView: Object
{
    dynamic var PracticeArray = ""
}
</code>```

And Usage:

```<code>let realm:Realm = try! Realm()
let PracticeDetails = PracticeView()
PracticeDetails.PracticeArray = "Test String Values"
try! realm.write
{
   realm.add(PracticeDetails)
}
print("Values In Realm Object: \(PracticeDetails.PracticeArray)")

//Result Will Be
Values In Realm Object: Test String Values
</code>```

答:
No, Realm cannot store native arrays (Whether Objective-C NSArray objects or Swift arrays) as properties of the Object model classes.

In Realm Swift, there is an object called List that lets you store an array of Realm Object instances as children. These still can't be strings though, so it's necessary to encapsulate the strings in another Realm Object subclass.

```<code>class Practice: Object {
   dynamic var practice = ""
}

class PracticeView: Object {
   let practiceList = List<Practice>()
}

let newPracticeView = PracticeView()

let newPractice = Practice()
newPractice.practice = "Test String Value"
newPracticeView.practiceList.append(newPractice)

let realm = try! Realm()
try! realm.write {
    realm.add(newPracticeView)
}
</code>```

For more information, I recommend checking out the 'To-Many Relationships' section of the Realm Swift documentation. :)

Body:
In my Application we are using Realm Storage for storing values locally. I can Able To Store my Array Values As Sting. But Not Able To Store and Retrive Values As Array. Is It Possible To Store NSArray Values To Realm Object and Retrieve It As NSArray.
Here Is The Code I Have Used To Store String Values:

class PracticeView: Object
{
    dynamic var PracticeArray = ""
}

And Usage:

let realm:Realm = try! Realm()
let PracticeDetails = PracticeView()
PracticeDetails.PracticeArray = "Test String Values"
try! realm.write
{
   realm.add(PracticeDetails)
}
print("Values In Realm Object: \(PracticeDetails.PracticeArray)")

//Result Will Be
Values In Realm Object: Test String Values

Body:
No, Realm cannot store native arrays (Whether Objective-C NSArray objects or Swift arrays) as properties of the Object model classes.

In Realm Swift, there is an object called List that lets you store an array of Realm Object instances as children. These still can't be strings though, so it's necessary to encapsulate the strings in another Realm Object subclass.

class Practice: Object {
   dynamic var practice = ""
}

class PracticeView: Object {
   let practiceList = List<Practice>()
}

let newPracticeView = PracticeView()

let newPractice = Practice()
newPractice.practice = "Test String Value"
newPracticeView.practiceList.append(newPractice)

let realm = try! Realm()
try! realm.write {
    realm.add(newPracticeView)
}

For more information, I recommend checking out the 'To-Many Relationships' section of the Realm Swift documentation. :)


问:
Highcharts width exceeds container div on first load
I'm using Highcharts with jQuery Mobile.

I have an area graph being drawn within a jQM data-role="content" container and within that container I have the following divs:

```

My highcharts graph is a basic graph taken from one of their examples where I have not set the chart width property.

On the first load the graph exceeds the width of the containing divs, but when I resize the browser it snaps to the appropriate width.

How can I make it so that the width of it is right on first page load and not just on resize?

I've reviewed similar posts on stack overflow and none of the solutions seem to work.

UPDATES

I've identified the problem is that the dynamically generated <rect> tag by Highcharts is taking the full width of the browser window on page load and not taking it from the containiner div width at all.  Here's the html generated when I inspect:

<rect rx="5" ry="5" fill="#FFFFFF" x="0" y="0" **width="1920"** height="200"></rect>

I tried to reproduce in JSFiddle, but it seems to work fine there, which really has me stumped. Here's my JSFiddle code: http://jsfiddle.net/meandnotyou/rMXnY

答:
For those using angular and custom-built components, remember to define a dimensioned display in css (such as block or flex) for the host element.

And when the chart container has padding, you might find this indispensable:

html

```<code><chart (load)="saveInstance($event.context)">
...
</chart>
</code>```

ts

```<code>  saveInstance(chartInstance: any) {
    this.chart = chartInstance;
    setTimeout(() => {
      this.chart.reflow();
    }, 0);
  }
</code>```

Otherwise the chart will bleed past the container on load and get its correct width only at next browser reflow (eg. when you start to resize window).

Body:
I'm using Highcharts with jQuery Mobile.

I have an area graph being drawn within a jQM data-role="content" container and within that container I have the following divs:

My highcharts graph is a basic graph taken from one of their examples where I have not set the chart width property.

On the first load the graph exceeds the width of the containing divs, but when I resize the browser it snaps to the appropriate width.

How can I make it so that the width of it is right on first page load and not just on resize?

I've reviewed similar posts on stack overflow and none of the solutions seem to work.

UPDATES

I've identified the problem is that the dynamically generated <rect> tag by Highcharts is taking the full width of the browser window on page load and not taking it from the containiner div width at all.  Here's the html generated when I inspect:

<rect rx="5" ry="5" fill="#FFFFFF" x="0" y="0" **width="1920"** height="200"></rect>

I tried to reproduce in JSFiddle, but it seems to work fine there, which really has me stumped. Here's my JSFiddle code: http://jsfiddle.net/meandnotyou/rMXnY

Body:
For those using angular and custom-built components, remember to define a dimensioned display in css (such as block or flex) for the host element.

And when the chart container has padding, you might find this indispensable:

html

<chart (load)="saveInstance($event.context)">
...
</chart>

ts

  saveInstance(chartInstance: any) {
    this.chart = chartInstance;
    setTimeout(() => {
      this.chart.reflow();
    }, 0);
  }

Otherwise the chart will bleed past the container on load and get its correct width only at next browser reflow (eg. when you start to resize window).


问:
Converting class using an array of references to Point2d objects to using a java.util.ArrayList<Point2d>
```<code>package polygongeneric;

import java.util.ArrayList;

public class Polygon {

private ArrayList <Point2d> p = null;
private int points = 0;

public Polygon() { }

public Polygon(int numPoints) {
    p = new ArrayList<>();
}

public boolean addPoint(Point2d point) {
   p.add(points, point);
    points++;
    return true;
}

public boolean addPoint(double x, double y) {
   Point2d a = new Point2d(x,y);
   p.add(points, a);
   return true;
}

@Override
public String toString() {
    String s = "";
    for (int i=0; i<points; i++)
        s += p.get(i).toString() + "\n";
    return s;
}
</code>```

}

I'm trying to convert a class from using an array of references to Point2d objects as type Point2d. This is what I have so far but it's not outputting the answer that it's supposed to.

This is what my code outputs

```<code>(0.1,0.9)

(0.5,0.5)

(0.2,0.5)
</code>```

This is what it's supposed to output

```<code>(0.1,0.9)

(0.3,0.7)

(0.5,0.5)

(0.4,0.8)

(0.2,0.5)
</code>```

Do you guys have any idea. What I'm doing wrong?

This is my Point2d class

```<code>package polygongeneric;

public class Point2d {

private double x = 0, y = 0;

public Point2d() { }

public Point2d(double x, double y) {
    setX(x);
    setY(y);
}

public void setX(double initX) {
    if (initX >= 0 && initX <= 1)
        x = initX;
}

public void setY(double y) {
    if (y >= 0 && y <= 1)
        this.y = y;
}

public double getX() { return x; }

public double getY() { return y; }

public String toString() {
    return "(" + x + "," + y + ")";
}
</code>```

}

This is my main method

```<code>package polygongeneric;

public class PolygonGeneric {

public static void main(String[] args) {

    Polygon p = new Polygon(5);

    p.addPoint(new Point2d(.1, .9));
    p.addPoint(.3, .7);
    p.addPoint(new Point2d(.5, .5));
    p.addPoint(.4, .8);
    p.addPoint(new Point2d(.2, .5));

    System.out.println(p);
}

 }
</code>```

答: You did not increment points in the addPoint(double x, double y) function.</p>

Body:
package polygongeneric;

import java.util.ArrayList;

public class Polygon {

private ArrayList <Point2d> p = null;
private int points = 0;

public Polygon() { }

public Polygon(int numPoints) {
    p = new ArrayList<>();
}

public boolean addPoint(Point2d point) {
   p.add(points, point);
    points++;
    return true;
}

public boolean addPoint(double x, double y) {
   Point2d a = new Point2d(x,y);
   p.add(points, a);
   return true;
}

@Override
public String toString() {
    String s = "";
    for (int i=0; i<points; i++)
        s += p.get(i).toString() + "\n";
    return s;
}

}

I'm trying to convert a class from using an array of references to Point2d objects as type Point2d. This is what I have so far but it's not outputting the answer that it's supposed to.

This is what my code outputs

(0.1,0.9)

(0.5,0.5)

(0.2,0.5)

This is what it's supposed to output

(0.1,0.9)

(0.3,0.7)

(0.5,0.5)

(0.4,0.8)

(0.2,0.5)

Do you guys have any idea. What I'm doing wrong?

This is my Point2d class

package polygongeneric;

public class Point2d {

private double x = 0, y = 0;

public Point2d() { }

public Point2d(double x, double y) {
    setX(x);
    setY(y);
}

public void setX(double initX) {
    if (initX >= 0 && initX <= 1)
        x = initX;
}

public void setY(double y) {
    if (y >= 0 && y <= 1)
        this.y = y;
}

public double getX() { return x; }

public double getY() { return y; }

public String toString() {
    return "(" + x + "," + y + ")";
}

}

This is my main method

package polygongeneric;

public class PolygonGeneric {

public static void main(String[] args) {

    Polygon p = new Polygon(5);

    p.addPoint(new Point2d(.1, .9));
    p.addPoint(.3, .7);
    p.addPoint(new Point2d(.5, .5));
    p.addPoint(.4, .8);
    p.addPoint(new Point2d(.2, .5));

    System.out.println(p);
}

 }