问:
Caesar's Cipher rotate with all possible combinations
In this program method encode and decode are working, but I have to include a third method rotation. The user has to type in a decode word, for example "eadaf eals" and the program uses the algorithm decode to show all 25 possibiliies.

For example:

```<code>Rotation     text
1            eadaf eal  //original text from user
2            eolwk wkk
3            hello you
....
25           klsjd ddk
</code>```

But I have problems with the last method. There has to be a for loop for all 25
possibilities.

```<code>public class CaesarsChiffre {

    public static void main(String[] args) {

        char benutzerBefehl;
        String benutzerText;
        int rotation=0;

        System.out.println("Caesars Chiffre encode, decode, rotate.");
        System.out.println("Waehlen Sie:");
        System.out.println("V for encode");
        System.out.println("E for decode");
        System.out.println("B for rotation");
        benutzerBefehl=Input.readChar();

        switch (benutzerBefehl){
        case 'V':   System.out.println("Enter text to encode:");
                    benutzerText=Input.readString();

                    System.out.println("which rotation do you want?");
                    rotation=Input.readInt();
                      while (rotation < 1 || rotation > 25) {
                          System.out.println(" The key must be between 1 and 25, you entered: "+ benutzerBefehl);
                          break;
                          }
                    System.out.print("Encoded text: ");
                    System.out.println(Caesarencode(benutzerText,rotation));
        break;
        case 'E':   System.out.println("Enter text to decode:");
                    benutzerText=Input.readString();

                    System.out.println("which rotation do you want?");
                    rotation=Input.readInt();
                      while (rotation < 1 || rotation > 25) {
                          System.out.println(" The key must be between 1 and 25, you entered: "+ benutzerBefehl);
                          break;
                      }
                     System.out.println("Decoded Text :");
                     System.out.println(Caesardecode(benutzerText,rotation));
        break;
        case 'B':       System.out.println("Enter the rotated text:");
                        benutzerText=Input.readString();
                        System.out.println("Rotation        Text: ");
                        System.out.println(Caesardecode(benutzerText));

        default:
            System.out.println("Invalid option..");
        }

    }

        public static String Caesarencode(String original_text, int rot){

            int length =original_text.length();
            String cypherText="";

            for(int i=0;i<length;i++){
                char  ch=original_text.charAt(i);
                    if(Character.isLetter(ch)){
                        if(Character.isLowerCase(ch)){
                            char c=(char)(ch+rot);
                            if(c>'z'){
                                cypherText += (char)(ch-(26-rot));
                            }
                            else{
                                cypherText+=c;
                            }
                        }
                        else if(Character.isUpperCase(ch)){
                            char c=(char)(ch+rot);
                            if(c>'Z'){
                                cypherText += (char)(ch-(26-rot));
                            }
                            else{
                            cypherText += c;
                            }
                        }
                    }
                    else{
                        cypherText+=ch;
                    }
            }
            return cypherText;
        }
        public static String Caesardecode(String original_text, int rot){

            int length =original_text.length();
            String cypherText="";

            for(int i=0;i<length;i++){
                char  ch=original_text.charAt(i);
                    if(Character.isLetter(ch)){
                        if(Character.isLowerCase(ch)){
                            char c=(char)(ch-rot);
                            if(c<'a'){
                                cypherText += (char)(ch+(26-rot));
                            }
                            else{
                                cypherText+=c;
                            }
                        }
                        else if(Character.isUpperCase(ch)){
                            char c=(char)(ch-rot);
                            if(c<'A'){
                                cypherText += (char)(ch+(26-rot));
                            }
                            else{
                            cypherText += c;
                            }
                        }
                    }
                    else{
                        cypherText+=ch;
                    }
            }
            return cypherText.toString();
        }

    public static String[] Caesardecode(String secret_text){

    String[] textNeu= new String[25];  //problems with this part

    for(int i=0;i<textNeu.length;i++){

        textNeu[i]= Caesardecode(secret_text, i)+" ";

    }
    return textNeu;
    }
}
</code>```

答:
For your problem, you are print an array

```<code> System.out.println(Caesardecode(benutzerText));
</code>```

As you can see

```<code> public static String[] Caesardecode(String secret_text){
</code>```

you need to Arrays.toString(array) to get something more readable.

For the invalid option is because you forgot the break statement at the end of the case

```<code>case 'B':       System.out.println("Enter the rotated text:");
                benutzerText=Input.readString();
                System.out.println("Rotation        Text: ");
                System.out.println(Caesardecode(benutzerText));
    break; // ADD IT HERE
    default:
        System.out.println("Invalid option..");
    }
</code>```

Just because you have already done a lot of thing, here is a cleaner solution using a method taking a parameter for the increment.

I clean the code a bit, used some Character method that you missed (is lower/upper case.

But most important, the usage of %26 to allow a z + 1 to become a a

```<code>public static String ceasar(String s, int inc){
    char[] input = s.toCharArray();
    char[] output = new char[input.length];
    for(int i = 0; i < output.length; ++i){
        char c = input[i];

        if(Character.isAlphabetic(c)){
            char a;
            if(Character.isUpperCase(c)){
                a = 'A';
            } else if(Character.isLowerCase(c)){
                a = 'a';
            } else { //not a letter, no evaluation needed
                output[i] = input[i];
                continue;
            }
            //encode the letter
            output[i] = (char)(((c - a + inc) % 26) + a);
        } else {
            output[i] = input[i];
        }
    }
    return new String(output);
}
</code>```

You can easily put that into a loop to call

```<code>for(int i = 0; i < 26; ++i){
    ceasar("youCode", i);
}
</code>```

Body:
In this program method encode and decode are working, but I have to include a third method rotation. The user has to type in a decode word, for example "eadaf eals" and the program uses the algorithm decode to show all 25 possibiliies.

For example:

Rotation     text
1            eadaf eal  //original text from user
2            eolwk wkk
3            hello you
....
25           klsjd ddk

But I have problems with the last method. There has to be a for loop for all 25
possibilities.

public class CaesarsChiffre {

    public static void main(String[] args) {

        char benutzerBefehl;
        String benutzerText;
        int rotation=0;

        System.out.println("Caesars Chiffre encode, decode, rotate.");
        System.out.println("Waehlen Sie:");
        System.out.println("V for encode");
        System.out.println("E for decode");
        System.out.println("B for rotation");
        benutzerBefehl=Input.readChar();

        switch (benutzerBefehl){
        case 'V':   System.out.println("Enter text to encode:");
                    benutzerText=Input.readString();

                    System.out.println("which rotation do you want?");
                    rotation=Input.readInt();
                      while (rotation < 1 || rotation > 25) {
                          System.out.println(" The key must be between 1 and 25, you entered: "+ benutzerBefehl);
                          break;
                          }
                    System.out.print("Encoded text: ");
                    System.out.println(Caesarencode(benutzerText,rotation));
        break;
        case 'E':   System.out.println("Enter text to decode:");
                    benutzerText=Input.readString();

                    System.out.println("which rotation do you want?");
                    rotation=Input.readInt();
                      while (rotation < 1 || rotation > 25) {
                          System.out.println(" The key must be between 1 and 25, you entered: "+ benutzerBefehl);
                          break;
                      }
                     System.out.println("Decoded Text :");
                     System.out.println(Caesardecode(benutzerText,rotation));
        break;
        case 'B':       System.out.println("Enter the rotated text:");
                        benutzerText=Input.readString();
                        System.out.println("Rotation        Text: ");
                        System.out.println(Caesardecode(benutzerText));

        default:
            System.out.println("Invalid option..");
        }

    }

        public static String Caesarencode(String original_text, int rot){

            int length =original_text.length();
            String cypherText="";

            for(int i=0;i<length;i++){
                char  ch=original_text.charAt(i);
                    if(Character.isLetter(ch)){
                        if(Character.isLowerCase(ch)){
                            char c=(char)(ch+rot);
                            if(c>'z'){
                                cypherText += (char)(ch-(26-rot));
                            }
                            else{
                                cypherText+=c;
                            }
                        }
                        else if(Character.isUpperCase(ch)){
                            char c=(char)(ch+rot);
                            if(c>'Z'){
                                cypherText += (char)(ch-(26-rot));
                            }
                            else{
                            cypherText += c;
                            }
                        }
                    }
                    else{
                        cypherText+=ch;
                    }
            }
            return cypherText;
        }
        public static String Caesardecode(String original_text, int rot){

            int length =original_text.length();
            String cypherText="";

            for(int i=0;i<length;i++){
                char  ch=original_text.charAt(i);
                    if(Character.isLetter(ch)){
                        if(Character.isLowerCase(ch)){
                            char c=(char)(ch-rot);
                            if(c<'a'){
                                cypherText += (char)(ch+(26-rot));
                            }
                            else{
                                cypherText+=c;
                            }
                        }
                        else if(Character.isUpperCase(ch)){
                            char c=(char)(ch-rot);
                            if(c<'A'){
                                cypherText += (char)(ch+(26-rot));
                            }
                            else{
                            cypherText += c;
                            }
                        }
                    }
                    else{
                        cypherText+=ch;
                    }
            }
            return cypherText.toString();
        }

    public static String[] Caesardecode(String secret_text){

    String[] textNeu= new String[25];  //problems with this part

    for(int i=0;i<textNeu.length;i++){

        textNeu[i]= Caesardecode(secret_text, i)+" ";

    }
    return textNeu;
    }
}

Body:
For your problem, you are print an array

 System.out.println(Caesardecode(benutzerText));

As you can see

 public static String[] Caesardecode(String secret_text){

you need to Arrays.toString(array) to get something more readable.

For the invalid option is because you forgot the break statement at the end of the case

case 'B':       System.out.println("Enter the rotated text:");
                benutzerText=Input.readString();
                System.out.println("Rotation        Text: ");
                System.out.println(Caesardecode(benutzerText));
    break; // ADD IT HERE
    default:
        System.out.println("Invalid option..");
    }

Just because you have already done a lot of thing, here is a cleaner solution using a method taking a parameter for the increment.

I clean the code a bit, used some Character method that you missed (is lower/upper case.

But most important, the usage of %26 to allow a z + 1 to become a a

public static String ceasar(String s, int inc){
    char[] input = s.toCharArray();
    char[] output = new char[input.length];
    for(int i = 0; i < output.length; ++i){
        char c = input[i];

        if(Character.isAlphabetic(c)){
            char a;
            if(Character.isUpperCase(c)){
                a = 'A';
            } else if(Character.isLowerCase(c)){
                a = 'a';
            } else { //not a letter, no evaluation needed
                output[i] = input[i];
                continue;
            }
            //encode the letter
            output[i] = (char)(((c - a + inc) % 26) + a);
        } else {
            output[i] = input[i];
        }
    }
    return new String(output);
}

You can easily put that into a loop to call

for(int i = 0; i < 26; ++i){
    ceasar("youCode", i);
}


来源: stackexchange

问:
I want to copy only changed files in my git repo that is shown by git diff command to a folder of same structure as in git repo using groovy
I just want to copy only the changed files shown by the output of git diff command at groovy console.However this code is copying all the files and folder of 'C:/git/dev1/server'.</p>

```<code>def command2 = "git diff --stat @{12.hours.ago}"
Process process = command2.execute(null, new File('C:/git/dev1/server'))
println "Std Err: ${process.err.text}"
println "Std Out: ${process.in.text}"

def sourceDir ="C:/git/dev1/server"
def destinationDir ="D:/demo1"
new AntBuilder().copy(todir: destinationDir) {
fileset(dir: sourceDir) }

}
</code>```

答:
As I already told you in your other question, you should not use porcellain commands for scripting actions. If you use git diff --stat, the process can hang forever if you get enough output to be more than one page, bcause then the pager process (less by default) is started, paths will be abbreviated if long enough, output and parameters might be instable between different Git versions and so on.

Instead you have to use some plumbing command or variant that is meant for script consumptions, does not "suffer" from the things specific for porcellain commands and should be pretty stable between Git versions usually.

Also you don't have to just consider copying over files, there could also be files that get deleted. So what you need is something like the following to reliably do what you want:

```<code>['git', 'diff', '--raw', '--no-renames', '@{12.hours.ago}']
    .execute(null, new File('C:/git/dev1/server'))
    .text
    .readLines()
    .collect() { it.split(' ')[4].split('\t') as List }
    .each { action, file ->
        if (action == 'D') {
            Files.deleteIfExists(Paths.get("D:/demo1/$file"))
        } else {
            Files.copy(Paths.get("C:/git/dev1/server/$file"), Paths.get("D:/demo1/$file"), StandardCopyOption.REPLACE_EXISTING)
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I just want to copy only the changed files shown by the output of git diff command at groovy console.However this code is copying all the files and folder of 'C:/git/dev1/server'.

def command2 = "git diff --stat @{12.hours.ago}"
Process process = command2.execute(null, new File('C:/git/dev1/server'))
println "Std Err: ${process.err.text}"
println "Std Out: ${process.in.text}"

def sourceDir ="C:/git/dev1/server"
def destinationDir ="D:/demo1"
new AntBuilder().copy(todir: destinationDir) {
fileset(dir: sourceDir) }

}

Body:
As I already told you in your other question, you should not use porcellain commands for scripting actions. If you use git diff --stat, the process can hang forever if you get enough output to be more than one page, bcause then the pager process (less by default) is started, paths will be abbreviated if long enough, output and parameters might be instable between different Git versions and so on.

Instead you have to use some plumbing command or variant that is meant for script consumptions, does not "suffer" from the things specific for porcellain commands and should be pretty stable between Git versions usually.

Also you don't have to just consider copying over files, there could also be files that get deleted. So what you need is something like the following to reliably do what you want:

['git', 'diff', '--raw', '--no-renames', '@{12.hours.ago}']
    .execute(null, new File('C:/git/dev1/server'))
    .text
    .readLines()
    .collect() { it.split(' ')[4].split('\t') as List }
    .each { action, file ->
        if (action == 'D') {
            Files.deleteIfExists(Paths.get("D:/demo1/$file"))
        } else {
            Files.copy(Paths.get("C:/git/dev1/server/$file"), Paths.get("D:/demo1/$file"), StandardCopyOption.REPLACE_EXISTING)
        }
    }


问:
How to detect 'leave' button on window.onbeforeunload js php
I'm developing a simple LMS system for my project. The code below will block user if they leave the current exam page and it will pop out js message if user wants to leave the page (has 2 button leave and stay)

comfirmExit

```<code><script type="text/javascript">
  var hook = true;
  window.onbeforeunload = function() {
    if (hook) {
      return "You have attempted to leave this page. Are you sure?";
   //if leave --> markzero.php
   //else stay --> do nothing
    }
  }
  function unhook() {
    hook=false;
  }
</script>
</code>```

What I want to implement here is that - if user click 'leave' the mark will be given as 0. I'm not sure how to detect that 'leave' button.

答:
Try this-</p>

```<code><script type="text/javascript" language="javascript">
               window.onbeforeunload = function() {
                   var Ans = confirm("You have attempted to leave this page. Are you sure?");
                   if(Ans==true)
                       return true;
                   else
                       return false;
               };
</script>
</code>```

Body:
I'm developing a simple LMS system for my project. The code below will block user if they leave the current exam page and it will pop out js message if user wants to leave the page (has 2 button leave and stay)

comfirmExit

What I want to implement here is that - if user click 'leave' the mark will be given as 0. I'm not sure how to detect that 'leave' button.

Body:
Try this-

<script type="text/javascript" language="javascript">
               window.onbeforeunload = function() {
                   var Ans = confirm("You have attempted to leave this page. Are you sure?");
                   if(Ans==true)
                       return true;
                   else
                       return false;
               };
</script>


问:
How to check if a table exists in a MySQL database using shell script?
i am trying to check whether a table is empty or not using shell script
the code that i have is

```<code>#!/bin/bash

if [ "mysql -u user -ppassword -hserver dbname -e 'select count(*) from test_dec;'" != 0 ];
then
        echo "table not empty"
else
        echo "table empty"
fi
</code>```

but when i run this it always displays "table not empty" even if the output of the query is 0.

```<code>user@server$ ./table_check.sh
table not empty
</code>```

what is wrong here?

答:
I think below will do your work,

```<code>#!/bin/bash

if [ $(mysql -u user -ppassword -hserver dbname -sse "select count(*) from test_dec;") -gt 0 ];
then
        echo "table not empty"
else
        echo "table empty"
fi
</code>```

3 changes from your script,

enclose whole mysql statement part inside $(..) --> to make LHS the result of what goes inside $(...)

change -e to -sse in mysql connection statement --> to get only result of query to output without header and table structure.

Change != to -gt --> operator for integer comparison in bash

ContentLicense: CC BY-SA 4.0

Body:
i am trying to check whether a table is empty or not using shell script
the code that i have is

#!/bin/bash

if [ "mysql -u user -ppassword -hserver dbname -e 'select count(*) from test_dec;'" != 0 ];
then
        echo "table not empty"
else
        echo "table empty"
fi

but when i run this it always displays "table not empty" even if the output of the query is 0.

user@server$ ./table_check.sh
table not empty

what is wrong here?

Body:
I think below will do your work,

#!/bin/bash

if [ $(mysql -u user -ppassword -hserver dbname -sse "select count(*) from test_dec;") -gt 0 ];
then
        echo "table not empty"
else
        echo "table empty"
fi

3 changes from your script,

enclose whole mysql statement part inside $(..) --> to make LHS the result of what goes inside $(...)

change -e to -sse in mysql connection statement --> to get only result of query to output without header and table structure.

Change != to -gt --> operator for integer comparison in bash


问:
Solr highlighting does not work with multiple fields hl.fl when dynamic field is present
I have a dynamic text field bar_* in my index and want Solr to return highlightings for that field. So what I run is:

```<code>q=gold&hl=true&hl.fl=bar_*
</code>```

It works as expected BUT in case I add some more fields to hl.fl it stops working. E.g.

```<code>q=gold&hl=true&hl.fl=bar_*,foo
</code>```

Notes:

bar_* and foo fields are in the index/schema and there is no error here.

just rewriting request as q=gold&hl=true&hl.fl=bar_*&hl.fl=foo or q=gold&hl=true&hl.fl=bar_* foo does NOT help.

I didn't find any bugs in Solr JIRA on that topic.

Does anyone have an idea how to bit this. The possible workarounds that I see are:

Use hl.fl=*. But this one is not good for performance.

Explicitly specify all possible fields names for my dynamic field. But I don't like that at all.

答:
After digging into Solr sources (org.apache.solr.highlight.SolrHighlighter#getHighlightFields) I have found a workaround for this. As appears Solr interprets hl.fl content as a regular expression pattern. So I've specified hl.fl as:

```<code>hl.fl=bar_*|foo
</code>```

I.e. using | instead of comma. That worked perfectly for me.

Btw, I have found no documentation of this in the internet.

Body:
I have a dynamic text field bar_* in my index and want Solr to return highlightings for that field. So what I run is:

q=gold&hl=true&hl.fl=bar_*

It works as expected BUT in case I add some more fields to hl.fl it stops working. E.g.

q=gold&hl=true&hl.fl=bar_*,foo

Notes:

bar_* and foo fields are in the index/schema and there is no error here.

just rewriting request as q=gold&hl=true&hl.fl=bar_*&hl.fl=foo or q=gold&hl=true&hl.fl=bar_* foo does NOT help.

I didn't find any bugs in Solr JIRA on that topic.

Does anyone have an idea how to bit this. The possible workarounds that I see are:

Use hl.fl=*. But this one is not good for performance.

Explicitly specify all possible fields names for my dynamic field. But I don't like that at all.

Body:
After digging into Solr sources (org.apache.solr.highlight.SolrHighlighter#getHighlightFields) I have found a workaround for this. As appears Solr interprets hl.fl content as a regular expression pattern. So I've specified hl.fl as:

hl.fl=bar_*|foo

I.e. using | instead of comma. That worked perfectly for me.

Btw, I have found no documentation of this in the internet.


问:
Ionic populating thumbnails with base64 images from a database
So i have an object of the type Patient that gets its values from a database and gets a base64 image to use as an avatar but so far the list is displayed correctly with no images and my console logs give me:

"WARNING: sanitizing unsafe URL value"

My code so far is this:

```<code><ion-list danger>
<ion-item-sliding *ngFor="let patient of patientsList">

       <ion-avatar item-left>
         <img src="data:image/png;base64,{{patient.photo}}">
       </ion-avatar>

        <ion-item (click)="openPage(patient)">
            {{patient.name}}
        </ion-item>

        <ion-item-options>

        <button round (click)="editPatient(patient)" light>
        <ion-icon name="paper"></ion-icon>
        </button>

        <button (click)="deletePatient(patient)">
        <ion-icon name="trash"></ion-icon>
        </button>

        </ion-item-options>

</ion-item-sliding>
</ion-list>
</code>```

Anybody has a clue of what im doing wrong?

答:
Paulo Botelho

Only http, https, ftp and mailto are safe to use in AngularJS. Angular will prefix a non-whitelisted URL with unsafe: and base 64 string is also considered as unsafe url since it doesn't contain http or any other.

So if you are using angular 2 or angular 4 then you could add following code.

```<code>import {DomSanitizer} from '@angular/platform-browser';
...
constructor(private sanitizer:DomSanitizer){}
...
let sanitizedUrl = this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,'+patient.photo)
</code>```

then in your html file add this

```<code><img src="sanitizedUrl">
</code>```

I hope it would help you.

Body:
So i have an object of the type Patient that gets its values from a database and gets a base64 image to use as an avatar but so far the list is displayed correctly with no images and my console logs give me:

"WARNING: sanitizing unsafe URL value"

My code so far is this:

<ion-list danger>
<ion-item-sliding *ngFor="let patient of patientsList">

       <ion-avatar item-left>

       </ion-avatar>

        <ion-item (click)="openPage(patient)">
            {{patient.name}}
        </ion-item>

        <ion-item-options>

        <button round (click)="editPatient(patient)" light>
        <ion-icon name="paper"></ion-icon>
        </button>

        <button (click)="deletePatient(patient)">
        <ion-icon name="trash"></ion-icon>
        </button>

        </ion-item-options>

</ion-item-sliding>
</ion-list>

Anybody has a clue of what im doing wrong?

Body:
Paulo Botelho

Only http, https, ftp and mailto are safe to use in AngularJS. Angular will prefix a non-whitelisted URL with unsafe: and base 64 string is also considered as unsafe url since it doesn't contain http or any other.

So if you are using angular 2 or angular 4 then you could add following code.

import {DomSanitizer} from '@angular/platform-browser';
...
constructor(private sanitizer:DomSanitizer){}
...
let sanitizedUrl = this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,'+patient.photo)

then in your html file add this

<img src="sanitizedUrl">

I hope it would help you.


问:
Getting a JSON object from javascript to php
I am sending a JSON object from js to post.php

```<code>$.ajax({
    type:'post',
    url:'post.php',
    data:{jsonobject:json_str}
});
</code>```

but I am not able to retrieve the result in a post.php file

```<code>$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;

function jsonString2Obj($str){
    return json_decode(stripcslashes($str));
}
</code>```

答:
I have no idea about your $jsonr_str.

It's my example:

```<code>$json = '{"people":[{"user":"Amy"},{"user":"Lee"},{"user":"David"}]}';

// covert into object
$data = json_decode(stripcslashes($json));
echo "People[0]=" . $data->people[0]->user;

// or covert info array
$data = json_decode($json, true);

// Using print_r()
echo "```" .print_r($data, true). "```";
</code>```

Body:
I am sending a JSON object from js to post.php

$.ajax({
    type:'post',
    url:'post.php',
    data:{jsonobject:json_str}
});

but I am not able to retrieve the result in a post.php file

$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;

function jsonString2Obj($str){
    return json_decode(stripcslashes($str));
}

Body:
I have no idea about your $jsonr_str.

It's my example:

$json = '{"people":[{"user":"Amy"},{"user":"Lee"},{"user":"David"}]}';

// covert into object
$data = json_decode(stripcslashes($json));
echo "People[0]=" . $data->people[0]->user;

// or covert info array
$data = json_decode($json, true);

// Using print_r()
echo "<pre>" .print_r($data, true). "</pre>";


问:
super in a metaclass
Recently, I used a metaclass to implement a singleton. Then, I tried to understand how this __metaclass__ stuff works. To do so, I wrote this piece of code:

```<code>import numpy as np

class Meta(type):
    _instance = None
    def __init__(cls, *args, **kwargs):
        print('meta: init')
        #return super(Meta, cls).__init__(*args, **kwargs)

    def __new__(cls, *args, **kwargs):
        print('meta: new')
        return super(Meta, cls).__new__(cls, *args, **kwargs)

    def __call__(cls, *args, **kwargs):
        print('meta: call')
        if cls._instance is None:
            cls._instance = super(Meta, cls).__call__(*args, **kwargs)
        print(cls._instance.__class__)
        return cls._instance

class ClassA():

    __metaclass__ = Meta
    def __init__(self, *args, **kwargs):
        self.val = np.random.randint(1000)
        print('classA: init')

    def __new__(cls, *args, **kwargs):
        print('classA: new')
        return super(ClassA, cls).__new__(cls, *args, **kwargs)

    def __call__(cls, *args, **kwargs):
        print('classA: call')
        return super(ClassA, cls).__call__(*args, **kwargs)

class ClassB():

    __metaclass__ = Meta
    def __init__(self, *args, **kwargs):
        print('classB: init')
        self.val = np.random.randint(1000)

    def __new__(cls, *args, **kwargs):
        print('classB: new')
        return super(ClassB, cls).__new__(cls, *args, **kwargs)

    def __call__(cls, *args, **kwargs):
        print('classB: call')
        return super(ClassB, cls).__call__(*args, **kwargs)

class ClassC(ClassB):

    def __init__(self, *args, **kwargs):
        print('classC: init')

        super(ClassC, self).__init__(self, *args, **kwargs)
        self.test = 3

    def __new__(cls, *args, **kwargs):
        print('classC: new')
        return super(ClassC, cls).__new__(cls, *args, **kwargs)

    def __call__(cls, *args, **kwargs):
        print('classC: call')
        return super(ClassC, cls).__call__(*args, **kwargs)

if __name__ == '__main__':

    a1 = ClassA()
    b1 = ClassB()
    a2 = ClassA()
    b2 = ClassB()
    c1 = ClassC()

    print(a1.val)
    print(b1.val)
    print(a2.val)
    print(b2.val)
</code>```

I have two questions about it:

Why does cls._instance is __main__.ClassA object (or __main__.ClassA object)? Should it not be a parent instance as it is created with super?

Why nothing (neither __call__ nor __init__) inside ClassC is called when creating a ClassC instance but only the ClassB.__call__ (as it inherits from it)?

答:
First, here's a stripped-down version of your code with some "noise" removed for readability.

```<code>import random

class Meta(type):
    _instance = None

    def __call__(cls, *args, **kwargs):
        print('meta: call: %s' % cls)
        if cls._instance is None:
            cls._instance = super(Meta, cls).__call__(*args, **kwargs)
        print("meta: call: returning %s@%s" % (cls._instance.__class__, id(cls._instance)))
        return cls._instance

class ClassA(object):
    __metaclass__ = Meta

    def __new__(cls, *args, **kwargs):
        print('classA: new')
        return super(ClassA, cls).__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        self.val = random.randint(1, 1000)
        print('classA: init')

class ClassB(object):
    __metaclass__ = Meta

    def __new__(cls, *args, **kwargs):
        print('classB: new')
        return super(ClassB, cls).__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        print('classB: init')
        self.val = random.randint(1, 1000)

class ClassC(ClassB):
    def __new__(cls, *args, **kwargs):
        print('classC: new')
        return super(ClassC, cls).__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        print('classC: init')
        super(ClassC, self).__init__(self, *args, **kwargs)
        self.test = 3

def main():
    a1 = ClassA()
    b1 = ClassB()
    a2 = ClassA()
    b2 = ClassB()
    c1 = ClassC()

    print(a1.val)
    print(b1.val)
    print(a2.val)
    print(b2.val)

if __name__ == '__main__':
    main()
</code>```

Now your questions:

Why does cls._instance is main.ClassA object (or main.ClassA object)? Should it not be a parent instance as it is created with super?

No, why ? In your case, when calling ClassA(), you actually invoke Meta.__call__(ClassA). super(Meta, cls) will select the next class in Meta.__mro__, which is type, and so invoke type.__call__(Meta, ClassA). type.__call__(Meta, ClassA) will in turn invoke ClassA.__new__() and ClassA.__init__(). So of course (hopefully, else you could hardly use inheritance at all), you do get a ClassA instance back.

As a general rule: super(CurrentClass, obj_or_cls).something() will select the something implementation in the "parent" class (actually in the next class in the __mro__) but the self (or cls or whatever) first argument will still point to self (or cls etc). IOW, you are selecting a parent implementation of a method, but this method will still get the current object/class as first argument.

Why nothing (neither __call__ nor __init__) inside ClassC is called when creating a ClassC instance but only the ClassB.__call__ (as it inherits from it)

ClassC.__call__() is not called because nothing in your code calls it. It's ClassC.__metaclass__.__call__() which is responsible for ClassC instanciation. You'd need to call an instance of ClassC to have ClassC.__call__() invoked.

ClassC.__init__() is not invoked because actually no instance of ClassC is ever created. The reason here is that you first create an instance of ClassB. At this point (first instanciation of ClassB), ClassB has no attribute _instance, so the attribute is looked up on it's parent class object. Since object has no attribute _instance either, the lookup continues on ClassB.__class__, which is Meta. This one does have an _instance attribute, which is None, so you do create a ClassB instance and bind it to ClassB._instance (sus creating the attribute in ClassB.__dict__).

Then when you try to instanciate ClassC, the if cls._instance is None test will first lookup _instance on ClassC. At this point, ClassC does not have an _instance attribute, so it's looked up on ClassC first parent (next class in the mro), which is ClassB. Since you already instanciated ClassB once, the lookup ends here, resolving ClassC._instance to ClassB.__dict__["_instance"] , so what you get back is the already created ClassB instance.

If you want a working implementation, you have to get rid of Meta._instance and either set _instance to None on each class in Meta.__init__():

```<code>class Meta(type):
    def __init__(cls, *args, **kw):
        cls._instance = None

    def __call__(cls, *args, **kwargs):
        print('meta: call: %s' % cls)
        if cls._instance is None:
            cls._instance = super(Meta, cls).__call__(*args, **kwargs)
        print("meta: call: returning %s@%s" % (cls._instance.__class__, id(cls._instance)))
        return cls._instance
</code>```

or replace the test in Meta.__call__() with a getattr():

```<code>class Meta(type):

    def __call__(cls, *args, **kwargs):
        print('meta: call: %s' % cls)
        if not getattr(cls, "_instance", None):
            cls._instance = super(Meta, cls).__call__(*args, **kwargs)
        print("meta: call: returning %s@%s" % (cls._instance.__class__, id(cls._instance)))
        return cls._instance
</code>```

Title: super in a metaclass

Body:
Recently, I used a metaclass to implement a singleton. Then, I tried to understand how this __metaclass__ stuff works. To do so, I wrote this piece of code:

import numpy as np

class Meta(type):
    _instance = None
    def __init__(cls, *args, **kwargs):
        print('meta: init')
        #return super(Meta, cls).__init__(*args, **kwargs)

    def __new__(cls, *args, **kwargs):
        print('meta: new')
        return super(Meta, cls).__new__(cls, *args, **kwargs)

    def __call__(cls, *args, **kwargs):
        print('meta: call')
        if cls._instance is None:
            cls._instance = super(Meta, cls).__call__(*args, **kwargs)
        print(cls._instance.__class__)
        return cls._instance

class ClassA():

    __metaclass__ = Meta
    def __init__(self, *args, **kwargs):
        self.val = np.random.randint(1000)
        print('classA: init')

    def __new__(cls, *args, **kwargs):
        print('classA: new')
        return super(ClassA, cls).__new__(cls, *args, **kwargs)

    def __call__(cls, *args, **kwargs):
        print('classA: call')
        return super(ClassA, cls).__call__(*args, **kwargs)

class ClassB():

    __metaclass__ = Meta
    def __init__(self, *args, **kwargs):
        print('classB: init')
        self.val = np.random.randint(1000)

    def __new__(cls, *args, **kwargs):
        print('classB: new')
        return super(ClassB, cls).__new__(cls, *args, **kwargs)

    def __call__(cls, *args, **kwargs):
        print('classB: call')
        return super(ClassB, cls).__call__(*args, **kwargs)

class ClassC(ClassB):

    def __init__(self, *args, **kwargs):
        print('classC: init')

        super(ClassC, self).__init__(self, *args, **kwargs)
        self.test = 3

    def __new__(cls, *args, **kwargs):
        print('classC: new')
        return super(ClassC, cls).__new__(cls, *args, **kwargs)

    def __call__(cls, *args, **kwargs):
        print('classC: call')
        return super(ClassC, cls).__call__(*args, **kwargs)

if __name__ == '__main__':

    a1 = ClassA()
    b1 = ClassB()
    a2 = ClassA()
    b2 = ClassB()
    c1 = ClassC()

    print(a1.val)
    print(b1.val)
    print(a2.val)
    print(b2.val)

I have two questions about it:

Why does cls._instance is __main__.ClassA object (or __main__.ClassA object)? Should it not be a parent instance as it is created with super?

Why nothing (neither __call__ nor __init__) inside ClassC is called when creating a ClassC instance but only the ClassB.__call__ (as it inherits from it)?

Body:
First, here's a stripped-down version of your code with some "noise" removed for readability.

import random

class Meta(type):
    _instance = None

    def __call__(cls, *args, **kwargs):
        print('meta: call: %s' % cls)
        if cls._instance is None:
            cls._instance = super(Meta, cls).__call__(*args, **kwargs)
        print("meta: call: returning %s@%s" % (cls._instance.__class__, id(cls._instance)))
        return cls._instance

class ClassA(object):
    __metaclass__ = Meta

    def __new__(cls, *args, **kwargs):
        print('classA: new')
        return super(ClassA, cls).__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        self.val = random.randint(1, 1000)
        print('classA: init')

class ClassB(object):
    __metaclass__ = Meta

    def __new__(cls, *args, **kwargs):
        print('classB: new')
        return super(ClassB, cls).__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        print('classB: init')
        self.val = random.randint(1, 1000)

class ClassC(ClassB):
    def __new__(cls, *args, **kwargs):
        print('classC: new')
        return super(ClassC, cls).__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        print('classC: init')
        super(ClassC, self).__init__(self, *args, **kwargs)
        self.test = 3

def main():
    a1 = ClassA()
    b1 = ClassB()
    a2 = ClassA()
    b2 = ClassB()
    c1 = ClassC()

    print(a1.val)
    print(b1.val)
    print(a2.val)
    print(b2.val)

if __name__ == '__main__':
    main()

Now your questions:

Why does cls._instance is main.ClassA object (or main.ClassA object)? Should it not be a parent instance as it is created with super?

No, why ? In your case, when calling ClassA(), you actually invoke Meta.__call__(ClassA). super(Meta, cls) will select the next class in Meta.__mro__, which is type, and so invoke type.__call__(Meta, ClassA). type.__call__(Meta, ClassA) will in turn invoke ClassA.__new__() and ClassA.__init__(). So of course (hopefully, else you could hardly use inheritance at all), you do get a ClassA instance back.

As a general rule: super(CurrentClass, obj_or_cls).something() will select the something implementation in the "parent" class (actually in the next class in the __mro__) but the self (or cls or whatever) first argument will still point to self (or cls etc). IOW, you are selecting a parent implementation of a method, but this method will still get the current object/class as first argument.

Why nothing (neither __call__ nor __init__) inside ClassC is called when creating a ClassC instance but only the ClassB.__call__ (as it inherits from it)

ClassC.__call__() is not called because nothing in your code calls it. It's ClassC.__metaclass__.__call__() which is responsible for ClassC instanciation. You'd need to call an instance of ClassC to have ClassC.__call__() invoked.

ClassC.__init__() is not invoked because actually no instance of ClassC is ever created. The reason here is that you first create an instance of ClassB. At this point (first instanciation of ClassB), ClassB has no attribute _instance, so the attribute is looked up on it's parent class object. Since object has no attribute _instance either, the lookup continues on ClassB.__class__, which is Meta. This one does have an _instance attribute, which is None, so you do create a ClassB instance and bind it to ClassB._instance (sus creating the attribute in ClassB.__dict__).

Then when you try to instanciate ClassC, the if cls._instance is None test will first lookup _instance on ClassC. At this point, ClassC does not have an _instance attribute, so it's looked up on ClassC first parent (next class in the mro), which is ClassB. Since you already instanciated ClassB once, the lookup ends here, resolving ClassC._instance to ClassB.__dict__["_instance"] , so what you get back is the already created ClassB instance.

If you want a working implementation, you have to get rid of Meta._instance and either set _instance to None on each class in Meta.__init__():

class Meta(type):
    def __init__(cls, *args, **kw):
        cls._instance = None

    def __call__(cls, *args, **kwargs):
        print('meta: call: %s' % cls)
        if cls._instance is None:
            cls._instance = super(Meta, cls).__call__(*args, **kwargs)
        print("meta: call: returning %s@%s" % (cls._instance.__class__, id(cls._instance)))
        return cls._instance

or replace the test in Meta.__call__() with a getattr():

class Meta(type):

    def __call__(cls, *args, **kwargs):
        print('meta: call: %s' % cls)
        if not getattr(cls, "_instance", None):
            cls._instance = super(Meta, cls).__call__(*args, **kwargs)
        print("meta: call: returning %s@%s" % (cls._instance.__class__, id(cls._instance)))
        return cls._instance


问:
Selenium Webdriver in VS with C# - Using promises
I actually haven't found a definitive yes or no answer for this question. Can Selenium WebDriver use promises or callbacks rather than having to use Thread.Sleep or some other polling method?

Currently working with an automation solution using C# with WebDriver added via NuGet to test React based Javascript web pages.

Any help is appreciated

Thanks

答:
Yes, WebDriver C# allow you to wait based on some conditions to avoid using Sleeps. A typical example would be to wait for some DOM element(s) to show up after an async operation is performed:

```<code>var node = new WebDriverWait(driver, new TimeSpan(0, 0, 0, 3, 0)).Until(
                ExpectedConditions.PresenceOfAllElementsLocatedBy(
                    By.XPath(".//*[contains(@ng-bind,'item.Value')]"))).First();
node.Click();
</code>```

This waits a maximum of three seconds for at least one element matching provided XPath to show up.

ExpectedConditions class has various static methods to test for existence, visibility, clickability and so on.

Side note: Related to the comment - which WebDriver flavor is used may a matter of taste, but a very short analysis has been performed in this article.

Body:
Yes, WebDriver C# allow you to wait based on some conditions to avoid using Sleeps. A typical example would be to wait for some DOM element(s) to show up after an async operation is performed:

var node = new WebDriverWait(driver, new TimeSpan(0, 0, 0, 3, 0)).Until(
                ExpectedConditions.PresenceOfAllElementsLocatedBy(
                    By.XPath(".//*[contains(@ng-bind,'item.Value')]"))).First();
node.Click();

This waits a maximum of three seconds for at least one element matching provided XPath to show up.

ExpectedConditions class has various static methods to test for existence, visibility, clickability and so on.

Side note: Related to the comment - which WebDriver flavor is used may a matter of taste, but a very short analysis has been performed in this article.


问:
Facebook Registration Plugin?
How would I take the results of the Facebook Registration Plugin and email it to myself? </p>

答:
Well, you should post what you have got so far..anyway, as described in the documentation:

The data is passed to your application
  as a signed request. The
  signed_request parameter is a simple
  way to make sure that the data you're
  receiving is the actual data sent by
  Facebook.

So you need to specify the redirect_uri and then process/extract the data you want from the signed_request and email it with the method you are using. How to process the data is described in the bottom of the document I linked above:

```<code><?php
define('FACEBOOK_APP_ID', 'your_app_id');
define('FACEBOOK_SECRET', 'your_app_secret');

function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2);

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
}

if ($_REQUEST) {
  echo '<p>signed_request contents:</p>';
  $response = parse_signed_request($_REQUEST['signed_request'],
                                   FACEBOOK_SECRET);
  echo '```';
  print_r($response);
  echo '```';
} else {
  echo '$_REQUEST is empty';
}
?>
</code>```

So instead of the print_r and echo functions, send the fields you want!

ContentLicense: CC BY-SA 2.5

Title: Facebook Registration Plugin?

Body:
Well, you should post what you have got so far..anyway, as described in the documentation:

The data is passed to your application
  as a signed request. The
  signed_request parameter is a simple
  way to make sure that the data you're
  receiving is the actual data sent by
  Facebook.

So you need to specify the redirect_uri and then process/extract the data you want from the signed_request and email it with the method you are using. How to process the data is described in the bottom of the document I linked above:

<?php
define('FACEBOOK_APP_ID', 'your_app_id');
define('FACEBOOK_SECRET', 'your_app_secret');

function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2);

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
}

if ($_REQUEST) {
  echo '<p>signed_request contents:</p>';
  $response = parse_signed_request($_REQUEST['signed_request'],
                                   FACEBOOK_SECRET);
  echo '<pre>';
  print_r($response);
  echo '</pre>';
} else {
  echo '$_REQUEST is empty';
}
?>

So instead of the print_r and echo functions, send the fields you want!


问:
How can i fix NumberFormatException?
I know this error is caused by a number format exception but i don't know how to fix it. i'v tried to do a function to Check if the variable is a Number or String
and here is my code

```<code>public boolean checkNumber(String x) {
   try{
       Integer.parseInt(x);
       return true;
   }catch(NumberFormatException ex){
       return false;
   }
}
</code>```

and this is a function takes a parameter of format dd/mm/yyyy,
split and store it in an array, then call the previous function to determine if all index are integer number or not.

```<code>public boolean CheckBirthDate(String birthdate){
    int B = 0;
    String Line = birthdate;
    String[] seprated = Line.split("/");
    if( checkNumber(seprated[0])  && checkNumber(seprated[1])  && checkNumber(seprated[2])) {
        B = 1;
    }
    if(seprated.length == 3 && Integer.parseInt(seprated[0]) <= 31  && Integer.parseInt(seprated[1]) <=   12 && Integer.parseInt(seprated[2]) >= 1950 &&  Integer.parseInt(seprated[2]) <= 2017 && B == 1){
        return true;
    }else{
        return false;
    }
}
</code>```

答:
Why not use a DateFormat?

```<code>String birthday = "25/05/1973";
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
    Date date = format.parse(birthday);
    System.out.println("date = " + date);
}
catch (ParseException e) {
     //date was bad format
}
</code>```

Result:

```<code>date = Fri May 25 00:00:00 CET 1973
</code>```

Title: How can i fix NumberFormatException?

Body:
I know this error is caused by a number format exception but i don't know how to fix it. i'v tried to do a function to Check if the variable is a Number or String
and here is my code

public boolean checkNumber(String x) {
   try{
       Integer.parseInt(x);
       return true;
   }catch(NumberFormatException ex){
       return false;
   }
}

and this is a function takes a parameter of format dd/mm/yyyy,
split and store it in an array, then call the previous function to determine if all index are integer number or not.

public boolean CheckBirthDate(String birthdate){
    int B = 0;
    String Line = birthdate;
    String[] seprated = Line.split("/");
    if( checkNumber(seprated[0])  && checkNumber(seprated[1])  && checkNumber(seprated[2])) {
        B = 1;
    }
    if(seprated.length == 3 && Integer.parseInt(seprated[0]) <= 31  && Integer.parseInt(seprated[1]) <=   12 && Integer.parseInt(seprated[2]) >= 1950 &&  Integer.parseInt(seprated[2]) <= 2017 && B == 1){
        return true;
    }else{
        return false;
    }
}

Body:
Why not use a DateFormat?

String birthday = "25/05/1973";
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
    Date date = format.parse(birthday);
    System.out.println("date = " + date);
}
catch (ParseException e) {
     //date was bad format
}

Result:

date = Fri May 25 00:00:00 CET 1973


问:
Angular 2 Get request error response,
I need to send POST request to the API and if response code == 400 get info from response.
http://joxi.ru/l2ZM0KES0M8ZmJ

```<code>public contactUsSendPost(params): Observable<{}> {
    return this.contactUsSendPostWithHttpInfo(params)
        .map((response: Response) => response.json());
}

public contactUsSendPostWithHttpInfo(params): Observable<Response> {
    const path = this.basePath + `/contact-us/send`;

    let queryParameters = new URLSearchParams();
    let headers = new Headers(this.defaultHeaders.toJSON());
    let formParams = new URLSearchParams();
    headers.set('Content-Type', 'application/x-www-form-urlencoded');
    headers.set('Accept', 'application/json');

    if (params.email !== undefined) {
        formParams.set('email', <any>params.email);
    }
    if (params.fullName !== undefined) {
        formParams.set('fullName', <any>params.fullName);
    }
    if (params.question !== undefined) {
        formParams.set('question', <any>params.question);
    }

    let requestOptions: RequestOptionsArgs = new RequestOptions({
        method: RequestMethod.Post,
        headers: headers,
        body: formParams.toString(),
        search: queryParameters
    });

    return this.http.request(path, requestOptions);
}
</code>```

Then im trying to get response from the service, but cant get response body.

```<code>this.fqService.contactUsSendPost(formValues).subscribe(
        data => console.log(data ),
        err => console.log(err) <------
    );
</code>```

So, how can i get response body in angular 2 from http response with 400 status code ?

答:
You can upgrade to HttpClient module angular 4.3 and above application,

If you pass the entire request object as a input the http.request method you will get an complete response object.

Title: Angular 2 Get request error response,

Body:
I need to send POST request to the API and if response code == 400 get info from response.
http://joxi.ru/l2ZM0KES0M8ZmJ

public contactUsSendPost(params): Observable<{}> {
    return this.contactUsSendPostWithHttpInfo(params)
        .map((response: Response) => response.json());
}

public contactUsSendPostWithHttpInfo(params): Observable<Response> {
    const path = this.basePath + `/contact-us/send`;

    let queryParameters = new URLSearchParams();
    let headers = new Headers(this.defaultHeaders.toJSON());
    let formParams = new URLSearchParams();
    headers.set('Content-Type', 'application/x-www-form-urlencoded');
    headers.set('Accept', 'application/json');

    if (params.email !== undefined) {
        formParams.set('email', <any>params.email);
    }
    if (params.fullName !== undefined) {
        formParams.set('fullName', <any>params.fullName);
    }
    if (params.question !== undefined) {
        formParams.set('question', <any>params.question);
    }

    let requestOptions: RequestOptionsArgs = new RequestOptions({
        method: RequestMethod.Post,
        headers: headers,
        body: formParams.toString(),
        search: queryParameters
    });

    return this.http.request(path, requestOptions);
}

Then im trying to get response from the service, but cant get response body.

this.fqService.contactUsSendPost(formValues).subscribe(
        data => console.log(data ),
        err => console.log(err) <------
    );

So, how can i get response body in angular 2 from http response with 400 status code ?


问:
ColdFusion Dynamic SQL with cfif
I'm trying to write a query which would accept 1 of 4 possible parameters passed from another page.  The user would select one of these parameters to search on and then the query would evaluate which of those was selected based on the passed parameter.  I'm trying to use a cfif to accomplish this but I must be missing something.  Maybe a cfelse, and OR, or maybe I'm way off.  Would this be better as cffunction? I get an error "variable DivisionCode" is undefined.  Thank you.</p>

```<code><cfquery name="Summary" datasource="dsn">
    SELECT
        *
    FROM
        disposal
    WHERE 1=1

    <cfif DivisionCode NEQ "false">
    AND DivisionCode = <cfqueryparam value="#url.DivisionCode#"
   cfsqltype="cf_sql_varchar">
   </cfif>
   <cfif DistrictCode NEQ "false">
    AND DistrictCode = <cfqueryparam value="#url.DistrictCode#"
   cfsqltype="cf_sql_varchar">
   </cfif>
   <cfif SiteCode NEQ "false">
    AND SiteCode = <cfqueryparam value="#url.SiteCode#"
   cfsqltype="cf_sql_varchar">
  </cfif>
  <cfif RegionCode NEQ "false">
    AND RegionCode = <cfqueryparam value="#url.RegionCode#"
  cfsqltype="cf_sql_varchar">
  </cfif>
  ORDER By
    CYear DESC
  </cfquery>
</code>```

答:
I would look at variable scoping and checking to make sure the variable exists. So, let's just look at one of your conditionals.

```<code><cfif StructKeyExists(url,"DivisionCode") AND url.DivisionCode NEQ "false">
   AND DivisionCode = <cfqueryparam value="#url.DivisionCode#" cfsqltype="cf_sql_varchar">
 </cfif>
</code>```

Adding the "url." prefix before your "DivisionCode" will specify the scope in which you are looking for your variable. This won't really help to solve your problem directly, but it will make your code a bit clearer and error messages a bit more helpful.

Adding the StructKeyExists() checks to make sure that variable is available in the URL in the first place. based on how you wrote your code, I'm guessing you don't want to filter by a URL variable that wasn't included, so that will take care of that.

Just do the same thing on each cfif and you should be right as rain.

Title: ColdFusion Dynamic SQL with cfif

Body:
I'm trying to write a query which would accept 1 of 4 possible parameters passed from another page.  The user would select one of these parameters to search on and then the query would evaluate which of those was selected based on the passed parameter.  I'm trying to use a cfif to accomplish this but I must be missing something.  Maybe a cfelse, and OR, or maybe I'm way off.  Would this be better as cffunction? I get an error "variable DivisionCode" is undefined.  Thank you.

<cfquery name="Summary" datasource="dsn">
    SELECT
        *
    FROM
        disposal
    WHERE 1=1

    <cfif DivisionCode NEQ "false">
    AND DivisionCode = <cfqueryparam value="#url.DivisionCode#"
   cfsqltype="cf_sql_varchar">
   </cfif>
   <cfif DistrictCode NEQ "false">
    AND DistrictCode = <cfqueryparam value="#url.DistrictCode#"
   cfsqltype="cf_sql_varchar">
   </cfif>
   <cfif SiteCode NEQ "false">
    AND SiteCode = <cfqueryparam value="#url.SiteCode#"
   cfsqltype="cf_sql_varchar">
  </cfif>
  <cfif RegionCode NEQ "false">
    AND RegionCode = <cfqueryparam value="#url.RegionCode#"
  cfsqltype="cf_sql_varchar">
  </cfif>
  ORDER By
    CYear DESC
  </cfquery>

Body:
I would look at variable scoping and checking to make sure the variable exists. So, let's just look at one of your conditionals.

<cfif StructKeyExists(url,"DivisionCode") AND url.DivisionCode NEQ "false">
   AND DivisionCode = <cfqueryparam value="#url.DivisionCode#" cfsqltype="cf_sql_varchar">
 </cfif>

Adding the "url." prefix before your "DivisionCode" will specify the scope in which you are looking for your variable. This won't really help to solve your problem directly, but it will make your code a bit clearer and error messages a bit more helpful.

Adding the StructKeyExists() checks to make sure that variable is available in the URL in the first place. based on how you wrote your code, I'm guessing you don't want to filter by a URL variable that wasn't included, so that will take care of that.

Just do the same thing on each cfif and you should be right as rain.


问:
Window BAT - Loop Exit Without Continue
I am try to loop all the source file in array and make sure it is exits in the folder with the file path I have set, below is my code

```<code>@echo OFF

setlocal EnableExtensions EnableDelayedExpansion
set "string_list=A.txt B.txt C.txt D.txt"

set count=0
For %%j in (%string_list%) Do Set /A count+=1
rem echo.Total count: %count%

set current_count=0
REM for %%s in (%string_list%) do (
for %%s in (%string_list%) do (
set "var=C:\Users\ABC\Desktop\TESTING\%%s"
rem echo "!var!"

:START
if not exist "!var!" GOTO WAIT
GOTO COPY

:WAIT
timeout 5
ECHO "MISSING !var!, WAITING SOURCE FILE TO LOAD IN"
GOTO START

:COPY
ECHO "!var! FILES IS AVAIALBLE"

set /A current_count+=1
if /I %current_count%==%count% (
    echo "ALL THE FILE IS IS AVAILABLE"
) else (
    echo "CONTINUE CHECK FOR OTHER FILE"
)
)
rem echo %current_count%
pause
</code>```

It will exit the loop once it found the first file. The code is to check and make sure all the files are in the folder, if one of the file is not there then continue loop until the file is there.

I am not sure can the function add in the FOR loop.

I'm expecting this:

C:\Users\ABC\Desktop\TESTING\A.txt FILES IS AVAILABLE <- A.txt is in the folder

Waiting for 0 seconds, press a key to continue ...

But I'm getting this:

MISSING C:\Users\ABC\Desktop\TESTING\B.txt, WAITING SOURCE FILE TO LOAD IN <- B.txt is not in the folder for the first time.

C:\Users\ABC\Desktop\TESTING\B.txt FILES IS AVAIALBLE <- B.txt is in the folder for the second loop

C:\Users\ABC\Desktop\TESTING\C.txt FILES IS AVAIALBLE <- C.txt is in the folder

C:\Users\ABC\Desktop\TESTING\D.txt FILES IS AVAIALBLE <- D.txt is in the folder

The loop should only exit if all the files are in the folder, or else it will continue loop.

答:
What an extraordinarily complex method to fail to do a very simple task! (oh, well - we all have to start somewhere)

It would help if the actual objective of the code was stated. As it is, we've got a method that fails (otherwise there would be no question) to do a task - and we have to analyse the code to determine the desired task.

Fundamentally, the code fails because labels are not allowed within a code block (a parenthesised sequence of commands).

```<code>@echo OFF
:: switch to the destination directory as exit is required with tat directory current
cd /d "C:\Users\ABC\Desktop\TESTING"
setlocal EnableExtensions EnableDelayedExpansion
set "string_list=A.txt B.txt C.txt D.txt"

:wait
timeout /t 5 >nul
cls
for %%j in (%string_list%) do if exist "%%~j" (
 echo "%%~j" exists
) else (
 echo "%%~j" missing
 goto wait
)
echo all files found
</code>```

Obviously, add in the counter if required. I've added a cls to reduce screen clutter. Omit it if desired.

So - for each nominated file (since we changed to the desired directory first-off), see whether it exists. If it does, report it. Otherwise report that it's missing and wait. Repeat until all found.

Title: Window BAT - Loop Exit Without Continue

Body:
I am try to loop all the source file in array and make sure it is exits in the folder with the file path I have set, below is my code

@echo OFF

setlocal EnableExtensions EnableDelayedExpansion
set "string_list=A.txt B.txt C.txt D.txt"

set count=0
For %%j in (%string_list%) Do Set /A count+=1
rem echo.Total count: %count%

set current_count=0
REM for %%s in (%string_list%) do (
for %%s in (%string_list%) do (
set "var=C:\Users\ABC\Desktop\TESTING\%%s"
rem echo "!var!"

:START
if not exist "!var!" GOTO WAIT
GOTO COPY

:WAIT
timeout 5
ECHO "MISSING !var!, WAITING SOURCE FILE TO LOAD IN"
GOTO START

:COPY
ECHO "!var! FILES IS AVAIALBLE"

set /A current_count+=1
if /I %current_count%==%count% (
    echo "ALL THE FILE IS IS AVAILABLE"
) else (
    echo "CONTINUE CHECK FOR OTHER FILE"
)
)
rem echo %current_count%
pause

It will exit the loop once it found the first file. The code is to check and make sure all the files are in the folder, if one of the file is not there then continue loop until the file is there.

I am not sure can the function add in the FOR loop.

I'm expecting this:

C:\Users\ABC\Desktop\TESTING\A.txt FILES IS AVAILABLE <- A.txt is in the folder

Waiting for 0 seconds, press a key to continue ...

But I'm getting this:

MISSING C:\Users\ABC\Desktop\TESTING\B.txt, WAITING SOURCE FILE TO LOAD IN <- B.txt is not in the folder for the first time.

C:\Users\ABC\Desktop\TESTING\B.txt FILES IS AVAIALBLE <- B.txt is in the folder for the second loop

C:\Users\ABC\Desktop\TESTING\C.txt FILES IS AVAIALBLE <- C.txt is in the folder

C:\Users\ABC\Desktop\TESTING\D.txt FILES IS AVAIALBLE <- D.txt is in the folder

The loop should only exit if all the files are in the folder, or else it will continue loop.

Body:
What an extraordinarily complex method to fail to do a very simple task! (oh, well - we all have to start somewhere)

It would help if the actual objective of the code was stated. As it is, we've got a method that fails (otherwise there would be no question) to do a task - and we have to analyse the code to determine the desired task.

Fundamentally, the code fails because labels are not allowed within a code block (a parenthesised sequence of commands).

@echo OFF
:: switch to the destination directory as exit is required with tat directory current
cd /d "C:\Users\ABC\Desktop\TESTING"
setlocal EnableExtensions EnableDelayedExpansion
set "string_list=A.txt B.txt C.txt D.txt"

:wait
timeout /t 5 >nul
cls
for %%j in (%string_list%) do if exist "%%~j" (
 echo "%%~j" exists
) else (
 echo "%%~j" missing
 goto wait
)
echo all files found

Obviously, add in the counter if required. I've added a cls to reduce screen clutter. Omit it if desired.

So - for each nominated file (since we changed to the desired directory first-off), see whether it exists. If it does, report it. Otherwise report that it's missing and wait. Repeat until all found.


问:
How to handle gridview contentY , Y position from parent Flickable in QML
I have a backGroundList and on top gridview in a Flickable.

I want handle gridview contentY , Y position from parent Flickable, it is working when i assign gridview height as content height but due to memory issues i dont want create items before.

Code:

```<code>Flickable {
            id: mainFlickable
            width: 1920
            height: 1080
            contentHeight: gridView.contentHeight + 660 + 140 // topmargin + bottom margin

            ListView {
                id:backGroundList
                width: 1920
                height: 1080
                y: mainFlickable.contentY
                orientation: ListView.Horizontal

                MouseArea {
                    id: myMA12
                    anchors.fill: parent
                    hoverEnabled: true
                }
            }

            GridView {
                id: gridView
                objectName: "gridView"

                width: 1920
                height: 1080

                cellWidth: 372
                cellHeight: 290

                interactive: false
                 y: {
                    if (mainFlickable.contentY > 660)
                        return 660 + (mainFlickable.contentY - 660)
                    else
                        return 660
                }

                contentY: {
                    if (mainFlickable.contentY > 660){
                        return (mainFlickable.contentY - 660)
                    }
                    else {
                        return 0
                    }
                }

                delegate: Rectangle {
                    width: 352
                    height: 270
                    color: "blue"
                    opacity: 0.5

                    Text {
                        text: index
                        anchors.centerIn: parent
                    }
                }
                model:100
                anchors {
                    left: parent.left
                    leftMargin: 30
                    right: parent.right
                    rightMargin: 30
                }
            }
}
</code>```

Its not working as expected. When I update Y value ContentY is updating to zero automatically

Constraint: Qt5.9.0

Can some one help me on this.

答:
If I understood you right, you want to have two ...Views one ontop of the other. When one of them has flicked to the end, you want to have that View flicked out of the Window, with the second one apprearing and start flicking through this.

In my opinion this is not cleanly achivable with one Flickable nesting the other two.

It is easily achived by using a Flickable that is a sibling to them. In my example code I use two Flickables. One for the control of the contentY-properties, and one that is responsible for scrolling inbetween the two Views. Latter could be easily and more efficiently solved by just using an Item instead.

```<code>Window {
    id: rootWin
    width: 800; height: 600; visible: true

    Flickable {
        id: flck
        anchors.fill: parent
        contentHeight: lv1.height + lv2.height
        interactive: false
        contentY: Math.min(Math.max(0, mainFlick.contentY - lv1.contentHeight + lv1.height), contentHeight - height)

        ListView {
            id: lv1
            height: rootWin.height
            width: 100
            model: 90
            delegate: Rectangle {
                border.width: 1
                width: 100
                height: 50
                Text {
                    anchors.centerIn: parent
                    text: index
                }
            }
            interactive: false
            contentY: Math.min(mainFlick.contentY, contentHeight - height)
            onContentYChanged: console.log(contentY, contentHeight, height)
        }
        ListView {
            id: lv2
            height: rootWin.height
            anchors.top: lv1.bottom
            width: 100
            model: 90
            delegate: Rectangle {
                border.width: 1
                width: 100
                height: 50
                Text {
                    anchors.centerIn: parent
                    text: index
                }
            }
            interactive: false
            contentY: Math.min(Math.max(0, mainFlick.contentY - lv1.contentHeight), contentHeight - height)
        }
    }
    Flickable {
        id: mainFlick
        anchors.fill: parent
        contentHeight: lv1.contentHeight + lv2.contentHeight
    }
}
</code>```

Body:
I have a backGroundList and on top gridview in a Flickable.

I want handle gridview contentY , Y position from parent Flickable, it is working when i assign gridview height as content height but due to memory issues i dont want create items before.

Code:

Flickable {
            id: mainFlickable
            width: 1920
            height: 1080
            contentHeight: gridView.contentHeight + 660 + 140 // topmargin + bottom margin

            ListView {
                id:backGroundList
                width: 1920
                height: 1080
                y: mainFlickable.contentY
                orientation: ListView.Horizontal

                MouseArea {
                    id: myMA12
                    anchors.fill: parent
                    hoverEnabled: true
                }
            }

            GridView {
                id: gridView
                objectName: "gridView"

                width: 1920
                height: 1080

                cellWidth: 372
                cellHeight: 290

                interactive: false
                 y: {
                    if (mainFlickable.contentY > 660)
                        return 660 + (mainFlickable.contentY - 660)
                    else
                        return 660
                }

                contentY: {
                    if (mainFlickable.contentY > 660){
                        return (mainFlickable.contentY - 660)
                    }
                    else {
                        return 0
                    }
                }

                delegate: Rectangle {
                    width: 352
                    height: 270
                    color: "blue"
                    opacity: 0.5

                    Text {
                        text: index
                        anchors.centerIn: parent
                    }
                }
                model:100
                anchors {
                    left: parent.left
                    leftMargin: 30
                    right: parent.right
                    rightMargin: 30
                }
            }
}

Its not working as expected. When I update Y value ContentY is updating to zero automatically

Constraint: Qt5.9.0

Can some one help me on this.

Body:
If I understood you right, you want to have two ...Views one ontop of the other. When one of them has flicked to the end, you want to have that View flicked out of the Window, with the second one apprearing and start flicking through this.

In my opinion this is not cleanly achivable with one Flickable nesting the other two.

It is easily achived by using a Flickable that is a sibling to them. In my example code I use two Flickables. One for the control of the contentY-properties, and one that is responsible for scrolling inbetween the two Views. Latter could be easily and more efficiently solved by just using an Item instead.

Window {
    id: rootWin
    width: 800; height: 600; visible: true

    Flickable {
        id: flck
        anchors.fill: parent
        contentHeight: lv1.height + lv2.height
        interactive: false
        contentY: Math.min(Math.max(0, mainFlick.contentY - lv1.contentHeight + lv1.height), contentHeight - height)

        ListView {
            id: lv1
            height: rootWin.height
            width: 100
            model: 90
            delegate: Rectangle {
                border.width: 1
                width: 100
                height: 50
                Text {
                    anchors.centerIn: parent
                    text: index
                }
            }
            interactive: false
            contentY: Math.min(mainFlick.contentY, contentHeight - height)
            onContentYChanged: console.log(contentY, contentHeight, height)
        }
        ListView {
            id: lv2
            height: rootWin.height
            anchors.top: lv1.bottom
            width: 100
            model: 90
            delegate: Rectangle {
                border.width: 1
                width: 100
                height: 50
                Text {
                    anchors.centerIn: parent
                    text: index
                }
            }
            interactive: false
            contentY: Math.min(Math.max(0, mainFlick.contentY - lv1.contentHeight), contentHeight - height)
        }
    }
    Flickable {
        id: mainFlick
        anchors.fill: parent
        contentHeight: lv1.contentHeight + lv2.contentHeight
    }
}


答:
This will work:

```<code>public boolean CheckBirthDate(String birthdate) {
    int B = 0;
    String Line = birthdate;
    String[] seprated = Line.split("/");
    if (checkNumber(seprated[0]) && checkNumber(seprated[1]) && checkNumber(seprated[2])) {
        B = 1;
    }
    if (B == 1 && seprated.length == 3 && Integer.parseInt(seprated[0]) <= 31 && Integer.parseInt(seprated[1]) <= 12
        && Integer.parseInt(seprated[2]) >= 1950 && Integer.parseInt(seprated[2]) <= 2017) {
        return true;
    } else {
        return false;
    }
}
</code>```

The problem is, that you check if B == 1 at the end of the if-clause and not the beginning. Therefore java tries to parse the Integer, even though it hasn't verified that it is actually a number yet.

I would also use a boolean vor B instead of an int. But generally speaking SurfMan's solution is probably the best and prettiest

Title: How can i fix NumberFormatException?

Body:
This will work:

public boolean CheckBirthDate(String birthdate) {
    int B = 0;
    String Line = birthdate;
    String[] seprated = Line.split("/");
    if (checkNumber(seprated[0]) && checkNumber(seprated[1]) && checkNumber(seprated[2])) {
        B = 1;
    }
    if (B == 1 && seprated.length == 3 && Integer.parseInt(seprated[0]) <= 31 && Integer.parseInt(seprated[1]) <= 12
        && Integer.parseInt(seprated[2]) >= 1950 && Integer.parseInt(seprated[2]) <= 2017) {
        return true;
    } else {
        return false;
    }
}

The problem is, that you check if B == 1 at the end of the if-clause and not the beginning. Therefore java tries to parse the Integer, even though it hasn't verified that it is actually a number yet.

I would also use a boolean vor B instead of an int. But generally speaking SurfMan's solution is probably the best and prettiest


问:
LINQ: Using AssociateWith and Distinct together
I haven't found a way to use these two elements together.

Here is my issue:

A web page has many bookmarks.  A user owns a bookmark. A user can bookmark the same page multiple times (for my purposes).

What I want is a list of the distinct users who have bookmarked a page.  I'm trying to use the LoadWith() and AssociateWith() methods of the DataContext, because I don't want to have to write a completely new query everytime I want a slight variant of the data.  So, sometimes I want a page, sometimes I want a page and a list of bookmarks, etc.

I can have code like this that gets me the page and it's bookmarks:

```<code>dlo.LoadWith<Page>(p => p.Bookmarks);
</code>```

And add this to get me users:

```<code>dlo.LoadWith<Bookmark>(b => b.User);
</code>```

But I don't know how I can constrain the users to be distinct.  I assume it's via an AssociateWith() command, but that doesn't support the Distinct() operator: http://msdn.microsoft.com/en-us/library/bb548919.aspx

Is what I'm doing possible, or am I going to have to write a new query for it?

答:
Suppose that there are two pages and two users and that both users have bookmarked both pages.

If you issue

```<code>dlo.LoadWith<Page>(p => p.Bookmarks);
dlo.LoadWith<Bookmark>(b => b.User);
dc.DataLoadOptions = dlo;
List<Page> myPages = dc.Page.ToList();
</code>```

Then LinqToSql will load 2 pages, 4 bookmarks and 2 users and construct the object graph you'd expect.

Then, to get distinct users without hitting the database, you have to traverse the graph and do something like this:

```<code>List<User> myUsers = myPages
  .SelectMany(p => p.Bookmarks)
  .Select(b => b.User)
  .Distinct()
  .ToList()
</code>```

a user can bookmark the same page multiple times in this case, so they're not distinct

Ok, here's an untested shot at it.

```<code>List<PageWithUsers> myPages = dc.Pages
  .Select(p => new PageWithUsers()
  {
    Page = p
    Users = p.Bookmarks
      .Select(b => b.UserId)
      .Distinct()
      .Take(10)
      .Select(i => dc.Users.Where(u => u.UserId = i))
  })
  .ToList();
</code>```

OwnerDisplayName: tlianza

Body:
I haven't found a way to use these two elements together.

Here is my issue:

A web page has many bookmarks.  A user owns a bookmark. A user can bookmark the same page multiple times (for my purposes).

What I want is a list of the distinct users who have bookmarked a page.  I'm trying to use the LoadWith() and AssociateWith() methods of the DataContext, because I don't want to have to write a completely new query everytime I want a slight variant of the data.  So, sometimes I want a page, sometimes I want a page and a list of bookmarks, etc.

I can have code like this that gets me the page and it's bookmarks:

dlo.LoadWith<Page>(p => p.Bookmarks);

And add this to get me users:

dlo.LoadWith<Bookmark>(b => b.User);

But I don't know how I can constrain the users to be distinct.  I assume it's via an AssociateWith() command, but that doesn't support the Distinct() operator: http://msdn.microsoft.com/en-us/library/bb548919.aspx

Is what I'm doing possible, or am I going to have to write a new query for it?

LastEditorDisplayName: Jay Bazuzi

Body:
Suppose that there are two pages and two users and that both users have bookmarked both pages.

If you issue

dlo.LoadWith<Page>(p => p.Bookmarks);
dlo.LoadWith<Bookmark>(b => b.User);
dc.DataLoadOptions = dlo;
List<Page> myPages = dc.Page.ToList();

Then LinqToSql will load 2 pages, 4 bookmarks and 2 users and construct the object graph you'd expect.

Then, to get distinct users without hitting the database, you have to traverse the graph and do something like this:

List<User> myUsers = myPages
  .SelectMany(p => p.Bookmarks)
  .Select(b => b.User)
  .Distinct()
  .ToList()

a user can bookmark the same page multiple times in this case, so they're not distinct

Ok, here's an untested shot at it.

List<PageWithUsers> myPages = dc.Pages
  .Select(p => new PageWithUsers()
  {
    Page = p
    Users = p.Bookmarks
      .Select(b => b.UserId)
      .Distinct()
      .Take(10)
      .Select(i => dc.Users.Where(u => u.UserId = i))
  })
  .ToList();

OwnerDisplayName: David B

LastEditorDisplayName: David B


问:
Swap memory pointers atomically on CUDA
I have two pointers in memory and I want to swap it atomically but atomic operation in CUDA support only int types. There is a way to do the following swap?</p>

```<code>classA* a1 = malloc(...);
classA* a2 = malloc(...);
atomicSwap(a1,a2);
</code>```

答:
I managed to have the needed behaviour, it is not atomic swap but still safe. The context was a monotonic Linked List working both on CPU and GPU:</p>

```<code>template<typename T>
union readablePointer
{
    T* ptr;
    unsigned long long int address;
};

template<typename T>
struct LinkedList
{

    struct Node
    {
        T value;
        readablePointer<Node> previous;
    };

    Node start;
    Node end;

    int size;

    __host__ __device__ void initialize()
    {
        size = 0;

        start.previous.ptr = nullptr;
        end.previous.ptr = &start;
    }

    __host__ __device__ void push_back(T value)
    {
        Node* node = nullptr;
        malloc(&node, sizeof(Node));

        readablePointer<Node> nodePtr;
        nodePtr.ptr = node;

        nodePtr.ptr->value = value;

#ifdef __CUDA_ARCH__
        nodePtr.ptr->previous.address = atomicExch(&end.previous.address, nodePtr.address);
        atomicAdd(&size,1);
#else
        nodePtr.ptr->previous.address = end.previous.address;
        end.previous.address = nodePtr.address;
        size += 1;
#endif

    }

    __host__ __device__ T pop_back()
    {
        assert(end.previous.ptr != &start);

        readablePointer<Node> lastNodePtr;
        lastNodePtr.ptr = nullptr;

#ifdef __CUDA_ARCH__
        lastNodePtr.address = atomicExch(&end.previous.address,end.previous.ptr->previous.address);
        atomicSub(&size,1);
#else
        lastNodePtr.address = end.previous.address;
        end.previous.address = end.previous.ptr->previous.address;
        size -= 1;
#endif
        T toReturn = lastNodePtr.ptr->value;

        free(lastNodePtr.ptr);

        return toReturn;
    }

    __host__ __device__ void clear()
    {
        while(size > 0)
        {
            pop_back();
        }
    }
};
</code>```

Title: Swap memory pointers atomically on CUDA

Body:
I have two pointers in memory and I want to swap it atomically but atomic operation in CUDA support only int types. There is a way to do the following swap?

classA* a1 = malloc(...);
classA* a2 = malloc(...);
atomicSwap(a1,a2);

Body:
I managed to have the needed behaviour, it is not atomic swap but still safe. The context was a monotonic Linked List working both on CPU and GPU:

template<typename T>
union readablePointer
{
    T* ptr;
    unsigned long long int address;
};

template<typename T>
struct LinkedList
{

    struct Node
    {
        T value;
        readablePointer<Node> previous;
    };

    Node start;
    Node end;

    int size;

    __host__ __device__ void initialize()
    {
        size = 0;

        start.previous.ptr = nullptr;
        end.previous.ptr = &start;
    }

    __host__ __device__ void push_back(T value)
    {
        Node* node = nullptr;
        malloc(&node, sizeof(Node));

        readablePointer<Node> nodePtr;
        nodePtr.ptr = node;

        nodePtr.ptr->value = value;

#ifdef __CUDA_ARCH__
        nodePtr.ptr->previous.address = atomicExch(&end.previous.address, nodePtr.address);
        atomicAdd(&size,1);
#else
        nodePtr.ptr->previous.address = end.previous.address;
        end.previous.address = nodePtr.address;
        size += 1;
#endif

    }

    __host__ __device__ T pop_back()
    {
        assert(end.previous.ptr != &start);

        readablePointer<Node> lastNodePtr;
        lastNodePtr.ptr = nullptr;

#ifdef __CUDA_ARCH__
        lastNodePtr.address = atomicExch(&end.previous.address,end.previous.ptr->previous.address);
        atomicSub(&size,1);
#else
        lastNodePtr.address = end.previous.address;
        end.previous.address = end.previous.ptr->previous.address;
        size -= 1;
#endif
        T toReturn = lastNodePtr.ptr->value;

        free(lastNodePtr.ptr);

        return toReturn;
    }

    __host__ __device__ void clear()
    {
        while(size > 0)
        {
            pop_back();
        }
    }
};


问:
wsgen error on Netbeans
I'm trying to create Java web-service with Netbeans 8.2 and use it's tools to generate WSDL file. However it always fails with the error. After scouring the internet, apparently, it's because Netbeans does not put a space after WSGEN when generating the command.

And people who found it says to either enter the correct command manually or manually fix the error in ANT, however nowhere it's clarified how to actually do either of those things. And half-year old posts that can be found here, where people ask for this exact clarification, were never answered.

Therefore I want to try my luck now, can someone help fixing this problem?

答:
Found the way myself. Need to copy the faulty command from Netbeans output to cmd and fix the space. Before that - adding "wsgen" system path to %SYSTEM%\Program Files\Java\jdk1.8.0_102\bin and then running the command from cmd.
Guess Netbeans community really not much nowadays.

Title: wsgen error on Netbeans


问:
add data to elastic using angularjs
I am working in a project where to search from firebase data using elastic search and trying to  add data to elastic using angularjs but giving error as :

```<code>{"data":"","status":0,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],
</code>```

my code is:

```<code>var inputJson =
{
    "mappings": {
        "carprev": {
            "properties": {
                "agepolicy33": {
                    "type": "text"
                },
                "aircondition33": {
                    "type": "text"
                },
                "year33": {
                    "type": "integer"
                }
            }
        }
    }
}

var corsHeaders = {
origin: ["*"],
headers: ['Origin', 'X-Requested-With', { 'Content-Type':
 'application/x-www-form-urlencoded' }],
credentials: true,
additionalHeaders: ['access-control-allow-headers', 'Access-Control-
Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With,
Content-Type, CORRELATION_ID'],
additionalExposedHeaders: ['access-control-allow-headers', 'Access-
 Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-
 Requested-With, Content-Type, CORRELATION_ID']
 };

$http({
method: "PUT",
// headers: ['Origin', 'X-Requested-With', 'Content-Type'],
url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
data: inputJson
}).then(function mySuccess(response) {
console.log(response);
}, function myError(err) {
var cjson = JSON.stringify(err);
console.log(err);
});
</code>```

but the same json in inserted into elasticsearch using postman and query data to retrieve from elastic

if anyone can resolve, appreciated

答:
You can try changing the content type to json.</p>

```<code>$http({
    method: "PUT",
    headers: {'Content-Type': 'application/json'},
    url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
    data: inputJson
    }).then(function mySuccess(response) {
    console.log(response);
    }, function myError(err) {
    var cjson = JSON.stringify(err);
    console.log(err);
});
</code>```

Title: add data to elastic using angularjs

Body:
I am working in a project where to search from firebase data using elastic search and trying to  add data to elastic using angularjs but giving error as :

{"data":"","status":0,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],

my code is:

var inputJson =
{
    "mappings": {
        "carprev": {
            "properties": {
                "agepolicy33": {
                    "type": "text"
                },
                "aircondition33": {
                    "type": "text"
                },
                "year33": {
                    "type": "integer"
                }
            }
        }
    }
}

var corsHeaders = {
origin: ["*"],
headers: ['Origin', 'X-Requested-With', { 'Content-Type':
 'application/x-www-form-urlencoded' }],
credentials: true,
additionalHeaders: ['access-control-allow-headers', 'Access-Control-
Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With,
Content-Type, CORRELATION_ID'],
additionalExposedHeaders: ['access-control-allow-headers', 'Access-
 Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-
 Requested-With, Content-Type, CORRELATION_ID']
 };

$http({
method: "PUT",
// headers: ['Origin', 'X-Requested-With', 'Content-Type'],
url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
data: inputJson
}).then(function mySuccess(response) {
console.log(response);
}, function myError(err) {
var cjson = JSON.stringify(err);
console.log(err);
});

but the same json in inserted into elasticsearch using postman and query data to retrieve from elastic

if anyone can resolve, appreciated

Body:
You can try changing the content type to json.

$http({
    method: "PUT",
    headers: {'Content-Type': 'application/json'},
    url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
    data: inputJson
    }).then(function mySuccess(response) {
    console.log(response);
    }, function myError(err) {
    var cjson = JSON.stringify(err);
    console.log(err);
});


问:
Spring @Entity Annotation findById
I have the below Student entity, trying to make a REST API for this.

```<code>@Entity
public class Student {
    @Id
    private int id;
    private String name;
    private String email;
    private List<Course> enrolledCourses;

    public Student() {
        // default constructor
    }

    // getters and setters
}
</code>```

When using @RestController, I am able to do @GetMapping("/api/students) and the page returns all the student's JSON. However when I try @GetMapping("/api/students/{id}") and specify @PathVariable the page returns something but all the fields are null. Anyone know what's the problem?

EDIT:

```<code>@RestController
public class StudentRestController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/api/students")
    public List<Student> getAllStudents() {
        return studentService.getAllStudents();
    }

    @GetMapping("/api/students/{id}")
    public Student getStudentById(@PathVariable int id) {
        return studentService.getStudentById(id);
    }
}
</code>```

The StudentService gets from the StudentRepository which gets from PostgreSQL database. But the StudentRepository here uses JdbcTemplate to fetch from database instead of extending CrudRepository or JpaRepository, I'm not sure if that might be the problem. I'm using code passed to me from my team. Here's the repo method findById, using ResultSetExtractor and RowMapper.

```<code>public Student findById(int id) {
        String selectSQL = "SELECT s.id as s_id, s.name as s_name, " +
            "s.email as s_email, " +
            "c1.id as c1_id, c1.name as c1_name, c1.alias as c1_alias, " +
            "c2.id as c2_id, c2.name as c2_name, c2.alias as c2_alias," +
            "c3.id as c3_id, c3.name as c3_name, c3.alias as c3_alias," +
            "c4.id as c4_id, c4.name as c4_name, c4.alias as c4_alias " +
            "FROM students s " +
            "JOIN courses c1 ON s.course1_id = c1.id " +
            "JOIN courses c2 ON s.course2_id = c2.id " +
            "JOIN courses c3 ON s.course3_id = c3.id " +
            "JOIN courses c4 ON s.course4_id = c4.id " +
            "WHERE s.id = ?";

    return (Student) jdbcTemplate.queryForObject(selectSQL, new Object[]{id},
            new BeanPropertyRowMapper(Student.class));
}
</code>```

EDIT2:

I created a custom StudentRowMapper and StudentResultSetExtractor, now there's another error, Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table: student, for columns: [org.hibernate.mapping.Column(enrolled_courses)]. Do I use @OneToMany?

EDIT3:

Using @OneToMany worked. Thanks.

答:
you have renamed the bean property attributes in your sql with aliases like s_id for id ,s_name for name so you used use a custom row mapper to convert your results.

```<code>public class StudentRowMapper implements RowMapper
{
    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        Student student = new Customer();
        student.setId(rs.getInt("s_id"));
        student.setName(rs.getString("s_name"));
    //and so on
        return student;
    }

}

 return (Student) jdbcTemplate.queryForObject(selectSQL, new Object[]{id},
            new StudentRowMapper(Student.class));
</code>```

may be useful article
https://www.mkyong.com/spring/spring-jdbctemplate-querying-examples/

Title: Spring @Entity Annotation findById

Body:
I have the below Student entity, trying to make a REST API for this.

@Entity
public class Student {
    @Id
    private int id;
    private String name;
    private String email;
    private List<Course> enrolledCourses;

    public Student() {
        // default constructor
    }

    // getters and setters
}

When using @RestController, I am able to do @GetMapping("/api/students) and the page returns all the student's JSON. However when I try @GetMapping("/api/students/{id}") and specify @PathVariable the page returns something but all the fields are null. Anyone know what's the problem?

EDIT:

@RestController
public class StudentRestController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/api/students")
    public List<Student> getAllStudents() {
        return studentService.getAllStudents();
    }

    @GetMapping("/api/students/{id}")
    public Student getStudentById(@PathVariable int id) {
        return studentService.getStudentById(id);
    }
}

The StudentService gets from the StudentRepository which gets from PostgreSQL database. But the StudentRepository here uses JdbcTemplate to fetch from database instead of extending CrudRepository or JpaRepository, I'm not sure if that might be the problem. I'm using code passed to me from my team. Here's the repo method findById, using ResultSetExtractor and RowMapper.

public Student findById(int id) {
        String selectSQL = "SELECT s.id as s_id, s.name as s_name, " +
            "s.email as s_email, " +
            "c1.id as c1_id, c1.name as c1_name, c1.alias as c1_alias, " +
            "c2.id as c2_id, c2.name as c2_name, c2.alias as c2_alias," +
            "c3.id as c3_id, c3.name as c3_name, c3.alias as c3_alias," +
            "c4.id as c4_id, c4.name as c4_name, c4.alias as c4_alias " +
            "FROM students s " +
            "JOIN courses c1 ON s.course1_id = c1.id " +
            "JOIN courses c2 ON s.course2_id = c2.id " +
            "JOIN courses c3 ON s.course3_id = c3.id " +
            "JOIN courses c4 ON s.course4_id = c4.id " +
            "WHERE s.id = ?";

    return (Student) jdbcTemplate.queryForObject(selectSQL, new Object[]{id},
            new BeanPropertyRowMapper(Student.class));
}

EDIT2:

I created a custom StudentRowMapper and StudentResultSetExtractor, now there's another error, Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table: student, for columns: [org.hibernate.mapping.Column(enrolled_courses)]. Do I use @OneToMany?

EDIT3:

Using @OneToMany worked. Thanks.

Body:
you have renamed the bean property attributes in your sql with aliases like s_id for id ,s_name for name so you used use a custom row mapper to convert your results.

public class StudentRowMapper implements RowMapper
{
    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        Student student = new Customer();
        student.setId(rs.getInt("s_id"));
        student.setName(rs.getString("s_name"));
    //and so on
        return student;
    }

}

 return (Student) jdbcTemplate.queryForObject(selectSQL, new Object[]{id},
            new StudentRowMapper(Student.class));

may be useful article
https://www.mkyong.com/spring/spring-jdbctemplate-querying-examples/


问:
Java String.matches regex with OR pipe
I am trying to make the following match, but it is not returning true as I would expect:

```<code>String attrs = "id|fullname|email|title";
String regex = "fullname|email";
return attrs.matches(regex);
</code>```

Instead it returns false.

Why is this? I expect the | pipe in attrs to be interpreted literally as an ASCII character, and the | pipe in regex to be interpreted according to regular expressions (i.e. OR).

The reason I ask is because I am writing an application where I let the user set the attributes in the format attr1|attr2|attr3|..., and I want to verify his/her input by matching it against the possible attribute values: attr1|attr2|attr3|...|attr[n].

Help appreciated,

ktm

Got it working by doing

```<code>String regex = "id.*|fullname.*|email.*|title.*";
String attrs = "fullname|email";
return attrs.matches(regex);
</code>```

答: You're using matches, not find, so it must correspond with the whole string.

Title: Java String.matches regex with OR pipe

Body:
I am trying to make the following match, but it is not returning true as I would expect:

String attrs = "id|fullname|email|title";
String regex = "fullname|email";
return attrs.matches(regex);

Instead it returns false.

Why is this? I expect the | pipe in attrs to be interpreted literally as an ASCII character, and the | pipe in regex to be interpreted according to regular expressions (i.e. OR).

The reason I ask is because I am writing an application where I let the user set the attributes in the format attr1|attr2|attr3|..., and I want to verify his/her input by matching it against the possible attribute values: attr1|attr2|attr3|...|attr[n].

Help appreciated,

ktm

Got it working by doing

String regex = "id.*|fullname.*|email.*|title.*";
String attrs = "fullname|email";
return attrs.matches(regex);