问:
Letter guessing game Java
I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!

I want the user to try and guess the letter and not the number, but i cannot workout how to do this!

(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)

```<code>Random r = new Random();

char targetLetter = (char)(r.nextInt(26) + 'a');
</code>```

Any help would be greatly appreciated! And i can display my code if it is needed

```<code>public class Stack {

    public static void main(String[] args) {

        Random rand = new Random(); //This is were the computer selects the Target

        int guess;
        int numGuesses = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int bestScore = 0;

        Scanner consoleIn = new Scanner(System.in);
        Scanner name = new Scanner(System.in);

        System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
        userName = name.nextLine();

        System.out.println("Hello " + userName + " :) Welcome to the game!\n");

        while (play = true) {
            session++;
            Target = rand.nextInt(26) + 1;
            System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                numGuesses++;

                if (guess > 26)
                    System.out.println("Error! Above MAXIMUM range");
                else if (guess <= 0)
                    System.out.println("Error! Below MINIMUM range");
                else if (guess > Target)
                    System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
                else if (guess < Target)
                    System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
            } while (guess != Target && numGuesses < 5);

            if (guess == Target) {
                System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
            } else {
                System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
                if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
                    play = true;
                    numGuesses = 0;
                } else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
                    play = false;
                    System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
                    System.out.println("You had  " + session + " Goes");
                    System.out.println("The number of times you guessed correctly: " + sessions + "");
                    break;
                }
            }
        }
    }
}
</code>```

答:
```<code> public static void main(String args[])
        {
            Scanner scan = new Scanner(System.in);
            System.out.println("Guess the Letter");
            String myLetter=scan.nextLine();
                //get the letter of myLetter variable then convert to Uppercase
            char enteredLetter=Character.toUpperCase(myLetter.charAt(0));
                    //26 only because the characters array starts with index 0
            char[] characters ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
                    //I had created a parrallel array symbolizing int value of each letter
            int[] range={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
            //this variable convert user input to one of the array element of range
            int userInputToInt=0;
            //this variable is for knowing what int[] range array element must the value of userInputToInt fall
            int userInputControlLoop=0;
            char randomLetter=characters[(int)(Math.random()*26)];
            // get the random input of computer convert it to int
            int computerInputToInt=0;

                //this loop is for getting the int value of randomLetter input by the computer
                for(int i=0;i<characters.length;++i)
                {
                    if(randomLetter==characters[i])
                    {

                        computerInputToInt=range[i];
                    }
                }
                //this loop is for getting the int value of user inputted letter
                for(char i:characters)
                {
                    if(enteredLetter==i)
                    {
                        userInputToInt=range[userInputControlLoop];
                    }
                    ++userInputControlLoop;
                }

                 //test the entered letter of user
            if(enteredLetter==randomLetter)
            {
                System.out.println("Correct Guess");
                System.out.println("The letter is:"+randomLetter);
            }
            //test the entered letter of user if greater than computer input
            else if(userInputToInt>computerInputToInt)
            {
                System.out.println("Incorrect Guess");
                System.out.println("The letter is too high");
                System.out.println("The letter is:"+randomLetter);
            }
            //test the entered letter of user if lesser than computer input
            else if(userInputToInt<computerInputToInt)
            {
                System.out.println("Incorrect Guess");
                System.out.println("The letter is too low");
                System.out.println("The letter is:"+randomLetter);
            }

        }
</code>```

Title: Letter guessing game Java

Body:
I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!

I want the user to try and guess the letter and not the number, but i cannot workout how to do this!

(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)

Random r = new Random();

char targetLetter = (char)(r.nextInt(26) + 'a');

Any help would be greatly appreciated! And i can display my code if it is needed

public class Stack {

    public static void main(String[] args) {

        Random rand = new Random(); //This is were the computer selects the Target

        int guess;
        int numGuesses = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int bestScore = 0;

        Scanner consoleIn = new Scanner(System.in);
        Scanner name = new Scanner(System.in);

        System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
        userName = name.nextLine();

        System.out.println("Hello " + userName + " :) Welcome to the game!\n");

        while (play = true) {
            session++;
            Target = rand.nextInt(26) + 1;
            System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                numGuesses++;

                if (guess > 26)
                    System.out.println("Error! Above MAXIMUM range");
                else if (guess <= 0)
                    System.out.println("Error! Below MINIMUM range");
                else if (guess > Target)
                    System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
                else if (guess < Target)
                    System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
            } while (guess != Target && numGuesses < 5);

            if (guess == Target) {
                System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
            } else {
                System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
                if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
                    play = true;
                    numGuesses = 0;
                } else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
                    play = false;
                    System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
                    System.out.println("You had  " + session + " Goes");
                    System.out.println("The number of times you guessed correctly: " + sessions + "");
                    break;
                }
            }
        }
    }
}


来源: stackexchange

问:
Making a Callback for AJAX Requests to return the response to the caller
I've looked all over the place and none of the answers I've found have been able to help me out with this problem. Basically I have a function that calls a separate function to make an XMLHttpRequest. The request goes to a server, which generates a random number and returns it to the page.

The problem is that while the request is fetching the data, the caller function continues through its commands. I need to have the data from the request before the caller can move forward. People have mentioned callbacks and promises, neither of which I have been able to grasp with what's available online. I'd rather use callbacks because promises aren't supported in all browsers. Can someone please help walk me through how to use them? I can provide some of the code that I have if needed.

Here's my caller function:

```<code>function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

getRequest();
console.log("x = "+x);
console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
... //rest of the function commands
}
</code>```

Here's my XML Request:

```<code>function getRequest()
{
var request;

if (window.XMLHttpRequest)
{ // Mozilla, Safari, IE7+ ...
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE 6 and older
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
    request.onreadystatechange = function()
    {
        console.log('onReady');
        if (request.readyState === XMLHttpRequest.DONE)
        {
            if (request.status === 200)
            {
                random = request.responseText;
                random = parseInt(random);
                random = random/100;
                random = random.toFixed(2);
                console.log("random = " +random);
                data[1] = random;
                console.log("data = "+data[0]+", "+data[1]);
            }
        else
        {
            alert ('There was a problem with the request');
        }

        }
}
request.open("GET", "lak1010_hw05.php", true);
request.send();
}
</code>```

答:
Promises are the way to go here.  You can use a Promise polyfill to help take care of unsupported browsers.

```<code>var myPromise = (function() {
    return new Promise(function(resolve, reject) {
        $.ajax({
            url:'/page.php?id=123',
            type:'POST',
            success: function(data) {
                resolve(data);
            }
        });
    });
})();
myPromise.then(function(data) {
  // Continue code here
});
</code>```

Basically you create a promise that gets resolved with the data returned from your AJAX call.  myPromise.then() gets fired when the Promise is resolved and you continue your code execution there with the data you passed along in the promise resolution.  You can also reject() a promise if the AJAX error'd or had invalid data etc.

With your code something like this:

```<code>function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph
var myPromise = new Promise(function(resolve, reject) {
    $.ajax({
        url:'/page.php?id=123',
        type:'POST',
        success: function(dataSet) {
            resolve(dataSet);
        }
    });
});

myPromise.then(function(dataSet) {
    console.log("x = "+x);
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    ... //rest of the function commands
});

}
</code>```

Simpler with just the callback:

```<code>function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

    $.ajax({
        url:'/page.php?id=123',
        type:'POST',
        success: function(dataSet) {
            console.log("x = "+x);
            console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
            ... //rest of the function commands
        }
    });

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've looked all over the place and none of the answers I've found have been able to help me out with this problem. Basically I have a function that calls a separate function to make an XMLHttpRequest. The request goes to a server, which generates a random number and returns it to the page.

The problem is that while the request is fetching the data, the caller function continues through its commands. I need to have the data from the request before the caller can move forward. People have mentioned callbacks and promises, neither of which I have been able to grasp with what's available online. I'd rather use callbacks because promises aren't supported in all browsers. Can someone please help walk me through how to use them? I can provide some of the code that I have if needed.

Here's my caller function:

function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

getRequest();
console.log("x = "+x);
console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
... //rest of the function commands
}

Here's my XML Request:

function getRequest()
{
var request;

if (window.XMLHttpRequest)
{ // Mozilla, Safari, IE7+ ...
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE 6 and older
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
    request.onreadystatechange = function()
    {
        console.log('onReady');
        if (request.readyState === XMLHttpRequest.DONE)
        {
            if (request.status === 200)
            {
                random = request.responseText;
                random = parseInt(random);
                random = random/100;
                random = random.toFixed(2);
                console.log("random = " +random);
                data[1] = random;
                console.log("data = "+data[0]+", "+data[1]);
            }
        else
        {
            alert ('There was a problem with the request');
        }

        }
}
request.open("GET", "lak1010_hw05.php", true);
request.send();
}

Body:
Promises are the way to go here.  You can use a Promise polyfill to help take care of unsupported browsers.

var myPromise = (function() {
    return new Promise(function(resolve, reject) {
        $.ajax({
            url:'/page.php?id=123',
            type:'POST',
            success: function(data) {
                resolve(data);
            }
        });
    });
})();
myPromise.then(function(data) {
  // Continue code here
});

Basically you create a promise that gets resolved with the data returned from your AJAX call.  myPromise.then() gets fired when the Promise is resolved and you continue your code execution there with the data you passed along in the promise resolution.  You can also reject() a promise if the AJAX error'd or had invalid data etc.

With your code something like this:

function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph
var myPromise = new Promise(function(resolve, reject) {
    $.ajax({
        url:'/page.php?id=123',
        type:'POST',
        success: function(dataSet) {
            resolve(dataSet);
        }
    });
});

myPromise.then(function(dataSet) {
    console.log("x = "+x);
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    ... //rest of the function commands
});

}

Simpler with just the callback:

function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

    $.ajax({
        url:'/page.php?id=123',
        type:'POST',
        success: function(dataSet) {
            console.log("x = "+x);
            console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
            ... //rest of the function commands
        }
    });

}


问:
Get Firefox URL?
How can I get the url from a running instance of firefox using .NET 2.0 windows/console app? C# or VB codes will do.

Thanks!

答:
Poor man's solution, if anything else fails: activate the Firefox window, send Ctrl+L (activates address bar), send Ctrl+C (copy selection, ie. URL, to clipboard) and read the clipboard.

Lot of issues with this method (among them it does strange stuff for the user if they are in front of the computer) so it is only a backup solution...

OwnerDisplayName: Leon

ContentLicense: CC BY-SA 2.5

Title: Get Firefox URL?

LastEditorDisplayName: Leon

OwnerDisplayName: PhiLho


问:
Platform independent tool to copy text to clipboard
I am trying to write a function that copies a string parameter to the clipboard. I intend to use this in a Python script that I've been working on. This is what I have so far (found most this snippet on another stack overflow post):

```<code>from tkinter import Tk

    def copy_to_clipboard(text):
        text = str(text)
        r = Tk()
        r.withdraw()
        r.clipboard_clear()
        r.clipboard_append(text)
        r.destroy()
</code>```

My problem is that when the script stops, the copied text is no longer on the clipboard.

Is there any possible alternative or fix to this?

Is there a good platform independent solution to my problem? Or will I have to check for what OS the user is on and proceed from there?

答:
I suppose that you're running on Linux with Gnome.

That's normal behavior on Gnome, as soon as the source of the copy vanishes e.g. closing the Browser Window you copied from, the clipboard data gets removed too. Workaround is to install the gnome-clipboard-daemon which will preserve the Clipboard state like Windows and KDE do.

So, there's not much you can do when running under Gnome, besides leaving your script running.

Body:
I am trying to write a function that copies a string parameter to the clipboard. I intend to use this in a Python script that I've been working on. This is what I have so far (found most this snippet on another stack overflow post):

from tkinter import Tk

    def copy_to_clipboard(text):
        text = str(text)
        r = Tk()
        r.withdraw()
        r.clipboard_clear()
        r.clipboard_append(text)
        r.destroy()

My problem is that when the script stops, the copied text is no longer on the clipboard.

Is there any possible alternative or fix to this?

Is there a good platform independent solution to my problem? Or will I have to check for what OS the user is on and proceed from there?


问:
What's the difference between [[1,2,3,4]] and tf.constant( [[1,2,3,4]] ) in tensorflow?
If I use this inside my IPython notebook:

```<code>import tensorflow as tf

with tf.Session():
    input1 = [[1, 2, 3, 5]]
    input2 = [[5], [6], [7], [8]]
    output = tf.matmul( input1, input2 )
    print( output.eval() )
</code>```

I get [[78]]

If I use the following code (with tf.constant), I see the same result:

```<code>import tensorflow as tf

with tf.Session():
    input1 = tf.constant( [[1, 2, 3, 5]] )
    input2 = tf.constant( [[5], [6], [7], [8]] )
    output = tf.matmul( input1, input2 )
    print( output.eval() )
</code>```

Is one preferred over the other? Does this change the computational graph behind the scenes, and if so, in which way that I should care about?

答:
Your two cases are indeed doing the same thing. TensorFlow will convert any list/numpy array to a tensor as soon as it gets the chance. For example, input1 is converted to a constant tensor within tf.matmul for your first case, and directly within tf.constant for your second case. TensorFlow wants to make it so that you don't have to worry about converting from lists to tensors (if possible). For example, anything object that can be passed to tf.convert_to_tensor can also be passed to any TensorFlow function/method that accepts tensors as its arguments (which can be quite handy at times).

In simple cases like these, where your input values are known ahead of time, feel free to do whichever of the two you prefer.

Body:
If I use this inside my IPython notebook:

import tensorflow as tf

with tf.Session():
    input1 = [[1, 2, 3, 5]]
    input2 = [[5], [6], [7], [8]]
    output = tf.matmul( input1, input2 )
    print( output.eval() )

I get [[78]]

If I use the following code (with tf.constant), I see the same result:

import tensorflow as tf

with tf.Session():
    input1 = tf.constant( [[1, 2, 3, 5]] )
    input2 = tf.constant( [[5], [6], [7], [8]] )
    output = tf.matmul( input1, input2 )
    print( output.eval() )

Is one preferred over the other? Does this change the computational graph behind the scenes, and if so, in which way that I should care about?


问:
len() of a numpy array in python
If I use len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]])), I get back 3.

Why is there no argument for len() about which axis I want the length of in multidimensional arrays? This is alarming.  Is there an alternative?

答:
You can transpose the array if you want to get the length of the other dimension.</p>

```<code>len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)
</code>```

Title: len() of a numpy array in python

Body:
You can transpose the array if you want to get the length of the other dimension.

len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)


问:
Spark closures behavior
I have a basic question on spark closures. I am not able to distinguish code behavior between scenario 2 & 3, both produces same output but based on my understanding scenario 3 should not work as expected.

The Below code is common for all scenarios:

```<code>class A implements Serializable{
        String t;
        A(String t){
            this.t=t;
        }
    }

//Initiaze spark context
JavaSparkContext context=....
//create rdd
JavaRDD<String> rdd = context.parallelize(Arrays.asList("a","b","c","d","e"),3);
</code>```

Scenerio 1: don't do this because A is initialize in driver and not visible on executor.

```<code>A a=new A("pqr");
rdd.map(i->i+a.t).collect();
</code>```

Scenerio 2: Recommended way of sharing object

```<code>Broadcast<A> broadCast = context.broadcast(new A("pqr"));
rdd.map(i->broadCast.getValue().t+i).collect();
//output: [pqra, pqrb, pqrc, pqrd, pqre]
</code>```

Scenerio 3: why this code work as expected even when I initiate A in driver?

```<code> class TestFunction implements Function<String, String>, Serializable {
    private A val;
    public TestFunction(){ }
    public TestFunction(A a){
        this.val = a;
    }
    @Override
    public String call(String integer) throws Exception {
        return val.t+integer;
    }
}
    TestFunction mapFunction = new TestFunction(new A("pqr"));
    System.out.println(rdd.map(mapFunction).collect());
    //output: [pqra, pqrb, pqrc, pqrd, pqre]
</code>```

Note: I am running program in cluster mode.

答: The generated Java bytecodes for Scenerio 1 & 3 are almost the same. The benefit of using Broadcast (Scenerio 2) is the broadcast object will only be sent to an executor once and reuse it in other tasks on this executor. Scenerio 1 & 3 will always send the object A to executors for each task. </p>

Title: Spark closures behavior

Body:
I have a basic question on spark closures. I am not able to distinguish code behavior between scenario 2 & 3, both produces same output but based on my understanding scenario 3 should not work as expected.

The Below code is common for all scenarios:

class A implements Serializable{
        String t;
        A(String t){
            this.t=t;
        }
    }

//Initiaze spark context
JavaSparkContext context=....
//create rdd
JavaRDD<String> rdd = context.parallelize(Arrays.asList("a","b","c","d","e"),3);

Scenerio 1: don't do this because A is initialize in driver and not visible on executor.

A a=new A("pqr");
rdd.map(i->i+a.t).collect();

Scenerio 2: Recommended way of sharing object

Broadcast broadCast = context.broadcast(new A("pqr"));
rdd.map(i->broadCast.getValue().t+i).collect();
//output: [pqra, pqrb, pqrc, pqrd, pqre]

Scenerio 3: why this code work as expected even when I initiate A in driver?

 class TestFunction implements Function<String, String>, Serializable {
    private A val;
    public TestFunction(){ }
    public TestFunction(A a){
        this.val = a;
    }
    @Override
    public String call(String integer) throws Exception {
        return val.t+integer;
    }
}
    TestFunction mapFunction = new TestFunction(new A("pqr"));
    System.out.println(rdd.map(mapFunction).collect());
    //output: [pqra, pqrb, pqrc, pqrd, pqre]

Note: I am running program in cluster mode.


问:
Google App Engine - Datastore get_or_insert key_name confusion
I am confused by get_or_insert(..). What should I pass as the key_name? Consider the following example:

```<code>class Person(db.model)
    name = db.StringProperty(required=True)
</code>```

Assume that no two people can have the same name. Say I want to get or insert a new Person with name Peter, what would my get_or_insert statement look like?

Cheers,

Pete

答:
The possibly confusing thing here is that the key doesn't show up directly in your model declaration, so that name = db.StringProperty bit in your example isn't needed. get_or_insert takes the keyname as its first (required) argument, so you're looking for code like:

```<code>person = Person.get_or_insert('Peter')
# other interesting & useful code here...
# later, maybe we need to retrieve that key name from the object:
name = person.key().name()
assert(name == "Peter")
</code>```

Body:
I am confused by get_or_insert(..). What should I pass as the key_name? Consider the following example:

class Person(db.model)
    name = db.StringProperty(required=True)

Assume that no two people can have the same name. Say I want to get or insert a new Person with name Peter, what would my get_or_insert statement look like?

Cheers,

Pete

Body:
The possibly confusing thing here is that the key doesn't show up directly in your model declaration, so that name = db.StringProperty bit in your example isn't needed. get_or_insert takes the keyname as its first (required) argument, so you're looking for code like:

person = Person.get_or_insert('Peter')
# other interesting & useful code here...
# later, maybe we need to retrieve that key name from the object:
name = person.key().name()
assert(name == "Peter")


问:
How do I handle ternary's in flow
I am trying to figure out why a refinement is thrown out when using a ternary operator but not with an if else block.  See the following code snippet.

handleError Fn

答:
These aren't equivalent.

In the first function, your default case is to throw an Error. But in the second function, your default case is to set error === res.message || res.statusText.

What flow is saying here is, "hey, it's possible that res.message and res.statusText is undefined. If that's the case, then there's a conflict with error: string." To mimic the logic in the if-block example, you'd have to add error handling. Here is a working example.

```<code>function handleError(url: string, res: ResponseType): void {
  let error: string;
  if (!res.message || !res.statusText) {
    throw new Error();
  }
  const error: string = res.status === 440 ?
    'Session Timeout' :
    res.message || res.statusText;

  setTopState({error});
}
</code>```

The documentation describes this under "Refinement Invalidations".

Title: How do I handle ternary's in flow

Body:
I am trying to figure out why a refinement is thrown out when using a ternary operator but not with an if else block.  See the following code snippet.

<a href="https://flowtype.org/try/#0PTAEAEDMBsHsHcBQBLAtgB1gJwC6gN4DOApjgCqzoDKOAhjsQL6iRayqgDkAdMIXQ04BuRIhwBPdMVAAlYoUwA7EmUnSAvAUShQqeYVoBzYgC5QAfn5ZkiwwBptofvQCuhM4peoARsSwOdZxw3MmIADxwzSxxrW0RGEURIF0UAYxxkWEVQAAtaRQATaGIAUSw2LAAKFyxoMysbe1AseTM5BSyVNQBKMwA3WGQCrR1ivD8K+pjGkR1kSFBKlsJuILdQdU3QABZtgAZukZ1QCewNrip9TOyyNGJYFxxhR2ZiaBJQecXl7j1CA2Mh3wjgAkKcsOcfn8AcRZqBXu9pF8lvJVgIQuEcEDHDpwZDUWtCKEInCER9gcdQDgcmx4KBFMQ6WUKpVuqTHI4SORKDR6MRKvhwYw2fFRMk0hksrl8kVSuVsNValNYk1lm15EoulJeqABkMjqlOuN5VhlY18StCRstrs9hZQZxLv9rqBbnoHk9QCZQVD9EZpAAfAPNAnoomYuFcijUAT8wUm4UiRiIIA" rel="nofollow noreferrer">handleError Fn

Body:
These aren't equivalent.

In the first function, your default case is to throw an Error. But in the second function, your default case is to set error === res.message || res.statusText.

What flow is saying here is, "hey, it's possible that res.message and res.statusText is undefined. If that's the case, then there's a conflict with error: string." To mimic the logic in the if-block example, you'd have to add error handling. <a href="https://flowtype.org/try/#0PTAEAEDMBsHsHcBQBLAtgB1gJwC6gN4DOApjgCqzoDKOAhjsQL6iRayqgDkAdMIXQ04BuRIhwBPdMVAAlYoUwA7EmUnSAvAUShQqeYVoBzYgC5QAfn5ZkiwwBptofvQCuhM4peoARsSwOdZxw3MmIADxwzSxxrW0RGEURIF0UAYxxkWEVQAAtaRQATaGIAUSw2LAAKFyxoMysbe1AseTM5BSyVNQBKMwA3WGQCrR1ivD8K+pjGkR1kSFBKlsJuILdQdU3QABZtgAZukZ1QCewNrip9TOyyNGJYFxxhR2ZiaBJQecXl7j1CA2Mh3wjgAkKcsOcfn8AcRZqBXu9pF8lvJVgIQuEcEDHDpwZDUWtCKEInCER9gcdQDgcmx4KBFMQ6WUKpVuqTHI4SORKDR6MRKvhwYw2fFRMk0hksrl8kVSuVsNValNYk1lm15EoulJeqABkMjsiAIRQ-RGaQAH3NoGNBPRRMx2J0IOptPpjNAzIVIp0jEcqU643lWGVjXxK0JGy2uz2FlBnEu-2uoFuegeT1AJlBJv+ZtAluattc9pJokCpAo1AE-MFQeFIl9QA" rel="nofollow noreferrer">Here is a working example.

function handleError(url: string, res: ResponseType): void {
  let error: string;
  if (!res.message || !res.statusText) {
    throw new Error();
  }
  const error: string = res.status === 440 ?
    'Session Timeout' :
    res.message || res.statusText;

  setTopState({error});
}

The documentation describes this under "Refinement Invalidations".


问:
How to share components between modules with lazy loading
I'm loading my modules with lazy load. I'm in a situation where I need to use one form of a module in another module.

For example, there is the product module and the brand module. Both are loaded in lazy load. But I wanted to make it possible for the user to register the brands within the product form. But my question is that both modules are loaded lazily.

Do I really need to fully load the two modules? Or could I just load only the required component?

my loading lazy load:

```<code>const productRoutes: Routes = [
  {
    path: 'product',
    loadChildren: 'app/admin/product/product.module#ProductModule',
    canLoad: [AuthGuard]
  }
];

const brandRoutes: Routes = [
  {
    path: 'brand',
    loadChildren: 'app/admin/brand/brand.module#BrandModule',
    canLoad: [AuthGuard]
  }
];
</code>```

my component:

```<code>....

<div class="form-group">
    <label for="exemplo">Create Name Product</label>
    <input type="text" name="name" [(ngModel)]="Product.name" #name="ngModel" >
</div>

<div class="form-group">
    <label for="exemplo">Create Brand</label>
    <brand-form-component></brand-form-component>
</div>
</code>```

EDIT

I created the shared module:

```<code>import { NgModule }            from '@angular/core';

import { FormComponent as
    FormBrandComponent }      from '../../brand/brand-form/form.component'

@NgModule({
  imports:      [  ],
  declarations: [ FormBrandComponent ],
  providers:    [ FormBrandComponent ],
  exports:      [ FormBrandComponent ],
})
export class SharedModule { }
</code>```

And I imported in the other modules:

Brand Module

```<code>import { SharedModule }from '../shared/shared.module';

@NgModule({
  imports: [ SharedModule, DialogModule, GrowlModule, Ng2PaginationModule, BrandRouting ],
  declarations: [ BrandComponent, ListComponent ],
  providers:[ BrandService ]
})
export class BrandModule {}
</code>```

product Module

```<code>import { SharedModule }from './shared/shared.module';

@NgModule({
  imports: [ SharedModule, CurrencyMaskModule, DragulaModule, GrowlModule, DialogModule, Ng2PaginationModule, productRouting, ReactiveFormsModule ],
  declarations: [ ProductComponent, FormComponent, ListComponent ],
  providers:[ FormComponent, ProductService, BreadService, MarcaService, GradeService ]
})
export class ProductModule { }
</code>```

But is giving the following error:

答:
The current implementation of lazy loading is on the module level, and it's all or nothing. If you need to share components between the two (which is what this sounds like), then it's possible you have a hidden shared module that you haven't yet completely identified. So, it's quite possible that you should be creating a new module to house those shared components/services and having that module be imported into the other two lazy loaded modules.

It is your choice whether that new module would be lazy or eagerly loaded - either would work. (Since it is a dependency of both the product and brand modules, once either is loaded, the new module would also get loaded).

Body:
I'm loading my modules with lazy load. I'm in a situation where I need to use one form of a module in another module.

For example, there is the product module and the brand module. Both are loaded in lazy load. But I wanted to make it possible for the user to register the brands within the product form. But my question is that both modules are loaded lazily.

Do I really need to fully load the two modules? Or could I just load only the required component?

my loading lazy load:

const productRoutes: Routes = [
  {
    path: 'product',
    loadChildren: 'app/admin/product/product.module#ProductModule',
    canLoad: [AuthGuard]
  }
];

const brandRoutes: Routes = [
  {
    path: 'brand',
    loadChildren: 'app/admin/brand/brand.module#BrandModule',
    canLoad: [AuthGuard]
  }
];

my component:

....

    Create Name Product
    <input type="text" name="name" [(ngModel)]="Product.name" #name="ngModel" >

    Create Brand
    <brand-form-component></brand-form-component>

EDIT

I created the shared module:

import { NgModule }            from '@angular/core';

import { FormComponent as
    FormBrandComponent }      from '../../brand/brand-form/form.component'

@NgModule({
  imports:      [  ],
  declarations: [ FormBrandComponent ],
  providers:    [ FormBrandComponent ],
  exports:      [ FormBrandComponent ],
})
export class SharedModule { }

And I imported in the other modules:

Brand Module

import { SharedModule }from '../shared/shared.module';

@NgModule({
  imports: [ SharedModule, DialogModule, GrowlModule, Ng2PaginationModule, BrandRouting ],
  declarations: [ BrandComponent, ListComponent ],
  providers:[ BrandService ]
})
export class BrandModule {}

product Module

import { SharedModule }from './shared/shared.module';

@NgModule({
  imports: [ SharedModule, CurrencyMaskModule, DragulaModule, GrowlModule, DialogModule, Ng2PaginationModule, productRouting, ReactiveFormsModule ],
  declarations: [ ProductComponent, FormComponent, ListComponent ],
  providers:[ FormComponent, ProductService, BreadService, MarcaService, GradeService ]
})
export class ProductModule { }

But is giving the following error:


问:
CIImage extent in pixels or points?
I'm working with a CIImage, and while I understand it's not a linear image, it does hold some data.

My question is whether or not a CIImage's extent property returns pixels or points? According to the documentation, which says very little, it's working space coordinates. Does this mean there's no way to get the pixels / points from a CIImage and I must convert to a UIImage to use the .size property to get the points?

I have a UIImage with a certain size, and when I create a CIImage using the UIImage, the extent is shown in points. But if I run a CIImage through a CIFilter that scales it, I sometimes get the extent returned in pixel values.

答:
I'll answer the best I can.

If your source is a UIImage, its size will be the same as the extent. But please, this isn't a UIImageView (which the size is in points). And we're just talking about the source image.

Running something through a CIFilter means you are manipulating things. If all you are doing is manipulating color, its size/extent shouldn't change (the same as creating your own CIColorKernel - it works pixel-by-pixel).

But, depending on the CIFilter, you may well be changing the size/extent. Certain filters create a mask, or tile. These may actually have an extent that is infinite! Others (blurs are a great example) sample surrounding pixels so their extent actually increases because they sample "pixels" beyond the source image's size. (Custom-wise these are a CIWarpKernel.)

Yes, quite a bit. Taking this to a bottom line:

What is the filter doing? Does it need to simply check a pixel's RGB and do something? Then the UIImage size should be the output CIImage extent.

Does the filter produce something that depends on the pixel's surrounding pixels? Then the output CIImage extent is slightly larger. How much may depend on the filter.

There are filters that produce something with no regard to an input. Most of these may have no true extent, as they can be infinite.

Points are what UIKit and CoreGraphics always work with. Pixels? At some point CoreImage does, but it's low-level to a point (unless you want to write your own kernel) you shouldn't care. Extents can usually - but keep in mind the above - be equated to a UIImage size.

EDIT

Many images (particularly RAW ones) can have so large a size as to affect performance. I have an extension for UIImage that resizes an image to a specific rectangle to help maintain consistent CI performance.

```<code>extension UIImage {
    public func resizeToBoundingSquare(_ boundingSquareSideLength : CGFloat) -> UIImage {
        let imgScale = self.size.width > self.size.height ? boundingSquareSideLength / self.size.width : boundingSquareSideLength / self.size.height
        let newWidth = self.size.width * imgScale
        let newHeight = self.size.height * imgScale
        let newSize = CGSize(width: newWidth, height: newHeight)
        UIGraphicsBeginImageContext(newSize)
        self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        return resizedImage!
    }
}
</code>```

Usage:

```<code>image = image.resizeToBoundingSquare(640)
</code>```

In this example, an image size of 3200x2000 would be reduced to 640x400. Or an image size or 320x200 would be enlarged to 640x400. I do this to an image before rendering it and before creating a CIImage to use in a CIFilter.

Title: CIImage extent in pixels or points?

Body:
I'll answer the best I can.

If your source is a UIImage, its size will be the same as the extent. But please, this isn't a UIImageView (which the size is in points). And we're just talking about the source image.

Running something through a CIFilter means you are manipulating things. If all you are doing is manipulating color, its size/extent shouldn't change (the same as creating your own CIColorKernel - it works pixel-by-pixel).

But, depending on the CIFilter, you may well be changing the size/extent. Certain filters create a mask, or tile. These may actually have an extent that is infinite! Others (blurs are a great example) sample surrounding pixels so their extent actually increases because they sample "pixels" beyond the source image's size. (Custom-wise these are a CIWarpKernel.)

Yes, quite a bit. Taking this to a bottom line:

What is the filter doing? Does it need to simply check a pixel's RGB and do something? Then the UIImage size should be the output CIImage extent.

Does the filter produce something that depends on the pixel's surrounding pixels? Then the output CIImage extent is slightly larger. How much may depend on the filter.

There are filters that produce something with no regard to an input. Most of these may have no true extent, as they can be infinite.

Points are what UIKit and CoreGraphics always work with. Pixels? At some point CoreImage does, but it's low-level to a point (unless you want to write your own kernel) you shouldn't care. Extents can usually - but keep in mind the above - be equated to a UIImage size.

EDIT

Many images (particularly RAW ones) can have so large a size as to affect performance. I have an extension for UIImage that resizes an image to a specific rectangle to help maintain consistent CI performance.

extension UIImage {
    public func resizeToBoundingSquare(_ boundingSquareSideLength : CGFloat) -> UIImage {
        let imgScale = self.size.width > self.size.height ? boundingSquareSideLength / self.size.width : boundingSquareSideLength / self.size.height
        let newWidth = self.size.width * imgScale
        let newHeight = self.size.height * imgScale
        let newSize = CGSize(width: newWidth, height: newHeight)
        UIGraphicsBeginImageContext(newSize)
        self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        return resizedImage!
    }
}

Usage:

image = image.resizeToBoundingSquare(640)

In this example, an image size of 3200x2000 would be reduced to 640x400. Or an image size or 320x200 would be enlarged to 640x400. I do this to an image before rendering it and before creating a CIImage to use in a CIFilter.

ContentLicense: CC BY-SA 4.0


问:
mysql left join without duplicate rows
Maybe the title is not the best but I didn't know how to explain it in just a few words.

I've two tables like this:

Table "users"

```<code>id|name
--+--------+
1 |Alice   |
2 |Bob     |
3 |Charlie |
</code>```

Table "article_users"

```<code>user_id|article_id|expired_date
-------+----------+------------+
   1   |    1     |01-01-2016
   1   |    5     |01-01-2018
   3   |    1     |01-01-2016
</code>```

I need to obtain all the users and know whether they have an article relation, obtaining if it's expired in case they have that relation.

I don't need to know which article is expired or not. I mean, in case a user has a relation not expired with (at least) one article, the answer should be: "yeah, he/she has an active relation".

The query I was working on is:

```<code>SELECT u.*, IF(TIMEDIFF(expired_date,CURDATE())<0,'YES',IF(TIMEDIFF(expired_date,CURDATE())>0,'EXPIRED','NO')) relation
FROM users u
LEFT JOIN article_users au ON au.user_id = u.id
</code>```

The problem I have is that I'm getting "duplicate" rows because of the LEFT JOIN, and I just want to know if a user has an active relation. I mean, no matter if the user has one or more active relations. In case he/she has at least one (active relation) then the result should be "yes". In case he has no active relations (but he/she has relations) the result should be "expired", and finally in case he/she has no relations, the result should be "no".

So, the desired result should be:

```<code>id|name    |relation
--+--------+--------
 1|Alice   |   YES
 2|Bob     |    NO
 3|Charlie |  EXPIRED
</code>```

I'm trying to get it with a GROUP_CONCAT function but I'm unabled to get it. I don't know if it's the right way or not.

Any help would be really appreciated.

Thanks in advance.

答:
Try this way:

Setup:

```<code>create table users(
  id integer,
  name varchar(15)
);

create table article_users (
  user_id integer,
  article_id integer,
expired_date date
);

insert into users values (1, 'Alice'), (2, 'Bob'), (3, 'Charlie');
insert into article_users values (1, 1, '2016-01-01'),
                 (1, 2, '2018-01-01'), (3, 1, '2016-01-01');
</code>```

Query:

```<code>select u.name,
       case when a.qtd>0 then 'Yes'
            when a.qtd=0 then 'Expired'
            else 'No' end as relation
  from users u
         left join
         (select user_id,
                 sum(if(timediff(expired_date, curdate())>0, 1, 0)) qtd
            from article_users
           group by user_id) a on u.id = a.user_id
order by u.name;
</code>```

Result:

```<code>name     relation
------------------
Alice    Yes
Bob      No
Charlie  Expired
</code>```

Since SQLFiddle isn't currently working I added it on SQLize. See it working here: http://www.sqlize.com/8cBsHBWCbN

Title: mysql left join without duplicate rows

Body:
Maybe the title is not the best but I didn't know how to explain it in just a few words.

I've two tables like this:

Table "users"

id|name
--+--------+
1 |Alice   |
2 |Bob     |
3 |Charlie |

Table "article_users"

user_id|article_id|expired_date
-------+----------+------------+
   1   |    1     |01-01-2016
   1   |    5     |01-01-2018
   3   |    1     |01-01-2016

I need to obtain all the users and know whether they have an article relation, obtaining if it's expired in case they have that relation.

I don't need to know which article is expired or not. I mean, in case a user has a relation not expired with (at least) one article, the answer should be: "yeah, he/she has an active relation".

The query I was working on is:

SELECT u.*, IF(TIMEDIFF(expired_date,CURDATE())<0,'YES',IF(TIMEDIFF(expired_date,CURDATE())>0,'EXPIRED','NO')) relation
FROM users u
LEFT JOIN article_users au ON au.user_id = u.id

The problem I have is that I'm getting "duplicate" rows because of the LEFT JOIN, and I just want to know if a user has an active relation. I mean, no matter if the user has one or more active relations. In case he/she has at least one (active relation) then the result should be "yes". In case he has no active relations (but he/she has relations) the result should be "expired", and finally in case he/she has no relations, the result should be "no".

So, the desired result should be:

id|name    |relation
--+--------+--------
 1|Alice   |   YES
 2|Bob     |    NO
 3|Charlie |  EXPIRED

I'm trying to get it with a GROUP_CONCAT function but I'm unabled to get it. I don't know if it's the right way or not.

Any help would be really appreciated.

Thanks in advance.

Body:
Try this way:

Setup:

create table users(
  id integer,
  name varchar(15)
);

create table article_users (
  user_id integer,
  article_id integer,
expired_date date
);

insert into users values (1, 'Alice'), (2, 'Bob'), (3, 'Charlie');
insert into article_users values (1, 1, '2016-01-01'),
                 (1, 2, '2018-01-01'), (3, 1, '2016-01-01');

Query:

select u.name,
       case when a.qtd>0 then 'Yes'
            when a.qtd=0 then 'Expired'
            else 'No' end as relation
  from users u
         left join
         (select user_id,
                 sum(if(timediff(expired_date, curdate())>0, 1, 0)) qtd
            from article_users
           group by user_id) a on u.id = a.user_id
order by u.name;

Result:

name     relation
------------------
Alice    Yes
Bob      No
Charlie  Expired

Since SQLFiddle isn't currently working I added it on SQLize. See it working here: http://www.sqlize.com/8cBsHBWCbN


答:
What is the len of the equivalent nested list?

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

With the more general concept of shape, numpy developers choose to implement __len__ as the first dimension.  Python maps len(obj) onto obj.__len__.

X.shape returns a tuple, which does have a len - which is the number of dimensions, X.ndim.  X.shape[i] selects the ith dimension (a straight forward application of tuple indexing).

Title: len() of a numpy array in python

Body:
If I use len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]])), I get back 3.

Why is there no argument for len() about which axis I want the length of in multidimensional arrays? This is alarming.  Is there an alternative?

Body:
What is the len of the equivalent nested list?

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

With the more general concept of shape, numpy developers choose to implement __len__ as the first dimension.  Python maps len(obj) onto obj.__len__.

X.shape returns a tuple, which does have a len - which is the number of dimensions, X.ndim.  X.shape[i] selects the ith dimension (a straight forward application of tuple indexing).


问:
Designing ASP MVC routing - listing child objects of specific objects with pagination and filtering
I have been looking at the feasibility of porting over an intranet web app from ASP DOTNET to ASP MVC. I have not yet decided whether or not this kind of framework would be suitable for the application.

One consideration is what the routing would look like...

The main use of the application is to CRUD 7 main types of objects, which, for illustration, include representations of customers, locations and persons. A customer can have multiple locations (< 10), which can each have many persons (maybe 1000s). Pages will either focus on the details or editing (often by multipage wizards -- another post though) of specific objects, or the listing out (with filtering) of sets of objects (eg persons) related to a particular object (eg a customer).

Just considering customers, beyond CRUD I will want to be able to list the various objects related to a specific customer (like locations and persons), page them, and also filter them by certain properties or keywords from a textbox. Currently, to view a customer's persons you would go to /customer?guid=1234#persons where there is a RadControls data grid containing all the persons (large request but bandwidth is not bottleneck).

So what would you recommend for routes?

Easy:

Customer/Edit/[GUID]

Harder:

Customer/List/[GUID]/Persons/[Page]?filter=xyz&paramX=YZ

or

Customer/List/Persons/customer=guid&...

or ...

答: Do what makes sense to you and your team.</p>


问:
Can't get POST value from AJAX
Can't get value of filter. Don't know why. Am I doing AJAX wrong?
For the record, I'm new to ajax and have looked many places, with many not getting real answers to the same issue.

JQUERY: index.php

```<code>$(document).ready(function(){
    $.ajax({
        url: 'news.php',
        type: "POST",
        data: {filter:'some value'},
    });
});
</code>```

HTML: index.php

```<code><div>
    <div>
        <? include($_SERVER['DOCUMENT_ROOT']."/news/news.php"); ?>
    </div>
</div>
</code>```

PHP: news.php

```<code>$sbFilter = $_POST['filter'];
echo "select* from test_table where status='3'and ('". $sbFilter."') ORDER BY  `test_table`.`date` DESC, nid DESC   limit 0 , 6"
</code>```

Console Log:

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 36

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php on line 36

// HERE IS MY ECHO
select* from test_table where status='3'and press<>1 and ('some value') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 42

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php

On the page, I get:

select* from test_table where status='3' and ('') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

答:
You are not seeing it because you are sending the data as JSON. That's why your $_POST global is empty, to access POST data sent as JSON you need to do following:</p>

```<code>json_decode(file_get_contents("php://input"))
</code>```

Title: Can't get POST value from AJAX

Body:
Can't get value of filter. Don't know why. Am I doing AJAX wrong?
For the record, I'm new to ajax and have looked many places, with many not getting real answers to the same issue.

JQUERY: index.php

$(document).ready(function(){
    $.ajax({
        url: 'news.php',
        type: "POST",
        data: {filter:'some value'},
    });
});

HTML: index.php

        <? include($_SERVER['DOCUMENT_ROOT']."/news/news.php"); ?>

PHP: news.php

$sbFilter = $_POST['filter'];
echo "select* from test_table where status='3'and ('". $sbFilter."') ORDER BY  `test_table`.`date` DESC, nid DESC   limit 0 , 6"

Console Log:

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 36

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php on line 36

// HERE IS MY ECHO
select* from test_table where status='3'and press<>1 and ('some value') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 42

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php

On the page, I get:

select* from test_table where status='3' and ('') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

Body:
You are not seeing it because you are sending the data as JSON. That's why your $_POST global is empty, to access POST data sent as JSON you need to do following:

json_decode(file_get_contents("php://input"))


答:
EDIT: Well shit I missed your edit and thought it was just a general promise question.

This is a function with parameters:

test = function(parameter) {
  if (paramater) {
    return true
  } else {
    return false
  }
}```
</div>
</div>
</p>

<p>This is a function that has an extra parameter called a 'callback'.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>test = function(parameter, callback) {
  if (parameter) {
    callback(null, 'result')
  } else {
    callback('error')
  }
}</code>```

A callback usually has two arguments. An error, and an optional result.

As you can see, if parameter is true, we run a function that returns 'null' as the error, and 'result' as the result.

If you'd like to delay functions using a callback, you simply call the function like this:

test(true, function(err, result) {
  if(err) {
    console.log(err)
  } else {
    console.log(result)
  }
})```
</div>
</div>
</p>

<p>Replace console.log with the function you want upon a successful result or error. It's hard to understand at first, but try writing some code for it - the reading is usually useless when you don't have an ingrained idea of asynchronous code.</p>

<p>You have to manually add the callbacks and stuff - here's an extract from my backend.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>this.findOneByPhone = function(phone, req, res, callback) {
        connection.acquire(function(err, con) {
            con.query('select * from users where phone = ?', [phone], function(err, result) {
                con.release()
                if (err) {
                    callback(err)
                } else {
                    callback(null, JSON.stringify(result[0], null, 4))
                }
            })
        })
    }</code>```

And then calling it;

this.findOneByPhone(user.phone, null, null, function(err, foundUser) {
                if (err) {
                    res.status(500).json({message: 'Signup findOneByPhone failed.', error: err})
                } else {
                    if (foundUser) {
                        var foundUserJSON = JSON.parse(foundUser)
                        res.json({status: 0, message: 'User already found in database, please skip signup', result: 'skip'})
                    } else {
                        res.json({status: 0, message: 'User is not in database, please signup', result: 'signup'})
                    }
                }
            })```

Title: Making a Callback for AJAX Requests to return the response to the caller

Body:
I've looked all over the place and none of the answers I've found have been able to help me out with this problem. Basically I have a function that calls a separate function to make an XMLHttpRequest. The request goes to a server, which generates a random number and returns it to the page.

The problem is that while the request is fetching the data, the caller function continues through its commands. I need to have the data from the request before the caller can move forward. People have mentioned callbacks and promises, neither of which I have been able to grasp with what's available online. I'd rather use callbacks because promises aren't supported in all browsers. Can someone please help walk me through how to use them? I can provide some of the code that I have if needed.

Here's my caller function:

function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

getRequest();
console.log("x = "+x);
console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
... //rest of the function commands
}

Here's my XML Request:

function getRequest()
{
var request;

if (window.XMLHttpRequest)
{ // Mozilla, Safari, IE7+ ...
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE 6 and older
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
    request.onreadystatechange = function()
    {
        console.log('onReady');
        if (request.readyState === XMLHttpRequest.DONE)
        {
            if (request.status === 200)
            {
                random = request.responseText;
                random = parseInt(random);
                random = random/100;
                random = random.toFixed(2);
                console.log("random = " +random);
                data[1] = random;
                console.log("data = "+data[0]+", "+data[1]);
            }
        else
        {
            alert ('There was a problem with the request');
        }

        }
}
request.open("GET", "lak1010_hw05.php", true);
request.send();
}

Body:
EDIT: Well shit I missed your edit and thought it was just a general promise question.

This is a function with parameters:

test = function(parameter) {
  if (paramater) {
    return true
  } else {
    return false
  }
}

This is a function that has an extra parameter called a 'callback'.

test = function(parameter, callback) {
  if (parameter) {
    callback(null, 'result')
  } else {
    callback('error')
  }
}

A callback usually has two arguments. An error, and an optional result.

As you can see, if parameter is true, we run a function that returns 'null' as the error, and 'result' as the result.

If you'd like to delay functions using a callback, you simply call the function like this:

test(true, function(err, result) {
  if(err) {
    console.log(err)
  } else {
    console.log(result)
  }
})

Replace console.log with the function you want upon a successful result or error. It's hard to understand at first, but try writing some code for it - the reading is usually useless when you don't have an ingrained idea of asynchronous code.

You have to manually add the callbacks and stuff - here's an extract from my backend.

this.findOneByPhone = function(phone, req, res, callback) {
        connection.acquire(function(err, con) {
            con.query('select * from users where phone = ?', [phone], function(err, result) {
                con.release()
                if (err) {
                    callback(err)
                } else {
                    callback(null, JSON.stringify(result[0], null, 4))
                }
            })
        })
    }

And then calling it;

this.findOneByPhone(user.phone, null, null, function(err, foundUser) {
                if (err) {
                    res.status(500).json({message: 'Signup findOneByPhone failed.', error: err})
                } else {
                    if (foundUser) {
                        var foundUserJSON = JSON.parse(foundUser)
                        res.json({status: 0, message: 'User already found in database, please skip signup', result: 'skip'})
                    } else {
                        res.json({status: 0, message: 'User is not in database, please signup', result: 'signup'})
                    }
                }
            })


问:
mariadb: force "SELECT STRAIGHT_JOIN" as default parameter
I currently migrate data from Percona 5.5.14 to MariaDB 10.1.22

On a specific query wich is using some JOINs, query plan is different between the 2 versions and response time > 400ms

The only solution I've find to solve this is to use STRAIGHT_JOIN option:

Percona 5.5.14  => 150ms

MariaDB 10.1.22 => 550ms ==> 150ms WITH STRAIGHT_JOIN option

My question is: Is there a parameter to force STRAIGHT_JOIN option on each SELECT queries which using JOINs?

I understand it's not a good solution, but I want to know if it exist because I haven't found it

Query is call in a stored procedure:

```<code>SELECT
            C.NAME                      AS out_Name,
            RC.ID                       AS out_PlanId,
            ISO.A3                      AS out_A3,
            ISO.NAME                    AS out_CountryName,
            ISO.NUMBER                  AS out_countryNumber,
            C.ID                        AS out_CId,
            RC.NAME                     AS out_CName,
            RSG.NAME                    AS out_ServiceGroupName,
            SPE.id                      AS out_EntryId,
            SPE.GOUPID                  AS out_GroupId,
            ZPE.ZONEID                  AS out_zoneId,
            Z.NAME                      AS out_zoneName,
            ZPE.ID                      AS out_zoneEntryId,
            ZPE.PREFIX                  AS out_zonePrefix,
            RC.PLANID                   AS out_zonePlanId,
            SPE.ZONEID                  AS out_zoneGroupId,
            ZSG.NAME                    AS out_zoneGroupName,
            SCPA.ID                     AS out_scpAId,
            SCPA.NAME                   AS out_scpAName,
            ZG.ID                       AS out_zoningpId,
            ZG.NAME                     AS out_zoningName,
            IFNULL(SF1.NAME,"")         AS out_Flag_serviceType_name,
            IFNULL(SF2.NAME,"")         AS out_Flag_service_name,
            IFNULL(SF3.NAME,"")         AS out_Flag_zone_name,
            IFNULL(SF4.NAME,"")         AS out_Flag_Plan_name,
            RC.RULEID                   AS out_ruleId,
            RP.NAME                     AS out_ruleName
    FROM
            table1                      AS M ,
            table2                      AS C,
            table3                      AS RC,
            table3                      AS RP,
            table4                      AS SPE  LEFT JOIN table12 AS SF2 ON SF2.id=SPE.FLAGID,
            table5                      AS ST   LEFT JOIN table11 AS SF1 ON SF1.id=ST.FLAGID,
            table6                      AS RSG,
            table7                      AS ZSG,
            table8                      AS ZPE  LEFT JOIN table14 as SF4 on SF4.id=ZPE.FLAGID,
            table9                      AS ISO,
            table10                     AS NP,
            table11                     AS Z    LEFT JOIN table13 as SF3 on SF3.id=Z.FLAGID ,
            table12                     AS SCPA,
            table13                     AS ZG
    WHERE
            M.name                          ='TSL'
            AND C.mvno_id                   =M.id
            AND C.id                        ='1010'
            AND RC.id                       =C.ID
            AND RP.id                       =RC.RULEID
            AND SPE.SERVICEID               =RC.SERVICEID
            AND RSG.ID                      =SPE.GOUP_ID
            AND ST.NAME                     ='GOR'
            AND SPE.SERVICETYPE_ID          =ST.ID
            AND ZSG.ID                      =SPE.ZONEID
            AND ZPE.ZONE_PLAN_ID            =RC.PLANID
            AND NP.NAME                     ='OSI'
            AND ZPE.NUMBERINGPLAN_ID        =NP.ID
            AND ZPE.ISOCOUNTRY_ID           =ISO.ID
            AND ZPE.ZONEID                  =ZSG.ID
            AND Z.ID                        =ZPE.ZONEID
            AND SCPA.ID                     =Z.ACTIONID
            AND ZG.ID                       =Z.GROUPID
            AND ZSG.ID                      =ZPE.ZONEID
            AND UNIX_TIMESTAMP()
                   BETWEEN UNIX_TIMESTAMP(IFNULL(ZPE.VALIDFROM,0))
                       AND UNIX_TIMESTAMP(IFNULL(ZPE.VALIDUNTIL,"2038-01-01") )
            AND (
                    (
                        '0'=0
                        AND ZPE.PREFIX      ='AUT'
                    )
                OR
                    (   '0'=1
                        AND
                        (
                               substring('AUT',1,1)=ZPE.prefix
                            OR substring('AUT',1,2)=ZPE.prefix
                            OR substring('AUT',1,3)=ZPE.prefix
                            OR substring('AUT',1,4)=ZPE.prefix
                            OR substring('AUT',1,5)=ZPE.prefix
                            OR substring('AUT',1,6)=ZPE.prefix
                            OR substring('AUT',1,7)=ZPE.prefix
                            OR substring('AUT',1,8)=ZPE.prefix
                            OR substring('AUT',1,9)=ZPE.prefix
                            OR substring('AUT',1,10)=ZPE.prefix
                            OR substring('AUT',1,11)=ZPE.prefix
                            OR substring('AUT',1,12)=ZPE.prefix
                            OR substring('AUT',1,13)=ZPE.prefix
                            OR substring('AUT',1,14)=ZPE.prefix
                            OR substring('AUT',1,15)=ZPE.prefix
                            OR  concat('AUT','#') =ZPE.prefix
                        )
                    )
            )
    ORDER BY LENGTH(prefix) DESC
    LIMIT 1;
</code>```

EXPLAIN MariaDB

EXPLAIN IN PRODUCTION (Percona)

答:
Put parentheses around the LEFT JOINs to make sure they are parsed correctly and the same by both versions:

```<code>( table4 AS SPE  LEFT JOIN table12 AS SF2 ON SF2.id=SPE.FLAGID ),
( table5 AS ST   LEFT JOIN table11 AS SF1 ON SF1.id=ST.FLAGID  ),
</code>```

At the same time, change the JOINs away from "commajoin" to JOIN .. ON.  That will make it easier to read.  And, especially, make it obvious what is in the WHERE.

Since you are obviously generating the SQL, work just a little harder to avoid constructs like '0'=1.

Isn't substring('AUT',1,1)=ZPE.prefix OR substring('AUT',1,2)=ZPE.prefix OR ... more simply written as just ZPE.prefix = left('AUT', CHAR_LENGTH(ZPE.prefix))?  Once you have change to that, you can probably further simplify that expression, probably getting rid of the other side of theOR, and perhaps allowingINDEX(prefix)` to be useful.

Be aware that LENGTH() is the byte length; CHAR_LENGTH() is the character length.

All your IDs are BIGINT?  Do you really need that much range?  Shrinking the datatype will help performance.

I see Using intersect.  Please provide SHOW CREATE TABLEZPE` so we can see what is going on.  Usually that optimization is not as good as having a 'composite' index.

I realize I have not answered the question you asked.  But I would rather do the above cleanups first.

Body:
I currently migrate data from Percona 5.5.14 to MariaDB 10.1.22

On a specific query wich is using some JOINs, query plan is different between the 2 versions and response time > 400ms

The only solution I've find to solve this is to use STRAIGHT_JOIN option:

Percona 5.5.14  => 150ms

MariaDB 10.1.22 => 550ms ==> 150ms WITH STRAIGHT_JOIN option

My question is: Is there a parameter to force STRAIGHT_JOIN option on each SELECT queries which using JOINs?

I understand it's not a good solution, but I want to know if it exist because I haven't found it

Query is call in a stored procedure:

SELECT
            C.NAME                      AS out_Name,
            RC.ID                       AS out_PlanId,
            ISO.A3                      AS out_A3,
            ISO.NAME                    AS out_CountryName,
            ISO.NUMBER                  AS out_countryNumber,
            C.ID                        AS out_CId,
            RC.NAME                     AS out_CName,
            RSG.NAME                    AS out_ServiceGroupName,
            SPE.id                      AS out_EntryId,
            SPE.GOUPID                  AS out_GroupId,
            ZPE.ZONEID                  AS out_zoneId,
            Z.NAME                      AS out_zoneName,
            ZPE.ID                      AS out_zoneEntryId,
            ZPE.PREFIX                  AS out_zonePrefix,
            RC.PLANID                   AS out_zonePlanId,
            SPE.ZONEID                  AS out_zoneGroupId,
            ZSG.NAME                    AS out_zoneGroupName,
            SCPA.ID                     AS out_scpAId,
            SCPA.NAME                   AS out_scpAName,
            ZG.ID                       AS out_zoningpId,
            ZG.NAME                     AS out_zoningName,
            IFNULL(SF1.NAME,"")         AS out_Flag_serviceType_name,
            IFNULL(SF2.NAME,"")         AS out_Flag_service_name,
            IFNULL(SF3.NAME,"")         AS out_Flag_zone_name,
            IFNULL(SF4.NAME,"")         AS out_Flag_Plan_name,
            RC.RULEID                   AS out_ruleId,
            RP.NAME                     AS out_ruleName
    FROM
            table1                      AS M ,
            table2                      AS C,
            table3                      AS RC,
            table3                      AS RP,
            table4                      AS SPE  LEFT JOIN table12 AS SF2 ON SF2.id=SPE.FLAGID,
            table5                      AS ST   LEFT JOIN table11 AS SF1 ON SF1.id=ST.FLAGID,
            table6                      AS RSG,
            table7                      AS ZSG,
            table8                      AS ZPE  LEFT JOIN table14 as SF4 on SF4.id=ZPE.FLAGID,
            table9                      AS ISO,
            table10                     AS NP,
            table11                     AS Z    LEFT JOIN table13 as SF3 on SF3.id=Z.FLAGID ,
            table12                     AS SCPA,
            table13                     AS ZG
    WHERE
            M.name                          ='TSL'
            AND C.mvno_id                   =M.id
            AND C.id                        ='1010'
            AND RC.id                       =C.ID
            AND RP.id                       =RC.RULEID
            AND SPE.SERVICEID               =RC.SERVICEID
            AND RSG.ID                      =SPE.GOUP_ID
            AND ST.NAME                     ='GOR'
            AND SPE.SERVICETYPE_ID          =ST.ID
            AND ZSG.ID                      =SPE.ZONEID
            AND ZPE.ZONE_PLAN_ID            =RC.PLANID
            AND NP.NAME                     ='OSI'
            AND ZPE.NUMBERINGPLAN_ID        =NP.ID
            AND ZPE.ISOCOUNTRY_ID           =ISO.ID
            AND ZPE.ZONEID                  =ZSG.ID
            AND Z.ID                        =ZPE.ZONEID
            AND SCPA.ID                     =Z.ACTIONID
            AND ZG.ID                       =Z.GROUPID
            AND ZSG.ID                      =ZPE.ZONEID
            AND UNIX_TIMESTAMP()
                   BETWEEN UNIX_TIMESTAMP(IFNULL(ZPE.VALIDFROM,0))
                       AND UNIX_TIMESTAMP(IFNULL(ZPE.VALIDUNTIL,"2038-01-01") )
            AND (
                    (
                        '0'=0
                        AND ZPE.PREFIX      ='AUT'
                    )
                OR
                    (   '0'=1
                        AND
                        (
                               substring('AUT',1,1)=ZPE.prefix
                            OR substring('AUT',1,2)=ZPE.prefix
                            OR substring('AUT',1,3)=ZPE.prefix
                            OR substring('AUT',1,4)=ZPE.prefix
                            OR substring('AUT',1,5)=ZPE.prefix
                            OR substring('AUT',1,6)=ZPE.prefix
                            OR substring('AUT',1,7)=ZPE.prefix
                            OR substring('AUT',1,8)=ZPE.prefix
                            OR substring('AUT',1,9)=ZPE.prefix
                            OR substring('AUT',1,10)=ZPE.prefix
                            OR substring('AUT',1,11)=ZPE.prefix
                            OR substring('AUT',1,12)=ZPE.prefix
                            OR substring('AUT',1,13)=ZPE.prefix
                            OR substring('AUT',1,14)=ZPE.prefix
                            OR substring('AUT',1,15)=ZPE.prefix
                            OR  concat('AUT','#') =ZPE.prefix
                        )
                    )
            )
    ORDER BY LENGTH(prefix) DESC
    LIMIT 1;

EXPLAIN MariaDB

EXPLAIN IN PRODUCTION (Percona)

Body:
Put parentheses around the LEFT JOINs to make sure they are parsed correctly and the same by both versions:

( table4 AS SPE  LEFT JOIN table12 AS SF2 ON SF2.id=SPE.FLAGID ),
( table5 AS ST   LEFT JOIN table11 AS SF1 ON SF1.id=ST.FLAGID  ),

At the same time, change the JOINs away from "commajoin" to JOIN .. ON.  That will make it easier to read.  And, especially, make it obvious what is in the WHERE.

Since you are obviously generating the SQL, work just a little harder to avoid constructs like '0'=1.

Isn't substring('AUT',1,1)=ZPE.prefix OR substring('AUT',1,2)=ZPE.prefix OR ... more simply written as just ZPE.prefix = left('AUT', CHAR_LENGTH(ZPE.prefix))?  Once you have change to that, you can probably further simplify that expression, probably getting rid of the other side of theOR, and perhaps allowingINDEX(prefix)` to be useful.

Be aware that LENGTH() is the byte length; CHAR_LENGTH() is the character length.

All your IDs are BIGINT?  Do you really need that much range?  Shrinking the datatype will help performance.

I see Using intersect.  Please provide SHOW CREATE TABLEZPE` so we can see what is going on.  Usually that optimization is not as good as having a 'composite' index.

I realize I have not answered the question you asked.  But I would rather do the above cleanups first.


问:
Simple OpenGL engine
I'm thinking about using OpenGL for part of my app, speciffically tile based London tube map. What is the most minimalistic and simplest OpenGL framework that I could use?</p>

答: Maybe, you might find GLSurfaceView handy for your app. Simplest possible OpenGL ES application with the source code is included.</p>

Title: Simple OpenGL engine


答:
Try the new fetch API. Promises with jQuery are pretty broken :/

=> https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

```<code>    var myHeaders = new Headers();

    var myInit = { method: 'GET',
                   headers: myHeaders,
                   mode: 'cors',
                   cache: 'default' };

    fetch('flowers.jpg', myInit)
    .then(function(response) {
      return response.blob();
    })
    .then(function(myBlob) {
      var objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });
</code>```

Body:
Try the new fetch API. Promises with jQuery are pretty broken :/

=> https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    var myHeaders = new Headers();

    var myInit = { method: 'GET',
                   headers: myHeaders,
                   mode: 'cors',
                   cache: 'default' };

    fetch('flowers.jpg', myInit)
    .then(function(response) {
      return response.blob();
    })
    .then(function(myBlob) {
      var objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });


问:
Can I get node --inspect to open Chrome automatically
In the new versions of node, node-inspector is built in and can be fired using the command node --inspect index.js. However, this always provides a command line with the address you have to plug into the address bar. I know this may not be the most "secure" but is there a way to eliminate that copy and paste step?

答:
This is not possible, for multiple reasons.

Starting the Chrome (or other "desktop" application) is platform dependent. Core Node can't do it and it would add unnecessary complexity (e.g. think about discovering the install location, dealing with Chrome not installed, etc).

This would tie Node to Chrome, which is not desirable.

Chrome does not provide a way to pass devtools URL from the command line.


问:
Pointers to Interfaces c++
Disclaimer: I am a complete C++ beginner, and if there is a similar answer to this question, please direct me to it, as I may have missed it, not knowing much in the way of theory.

So I was looking through some c++ code, and I found something like this:

shared_ptr<anObjectsInterface>

Which got me wondering, how can there be a pointer to an interface? Surely a pointer points to an object in memory, or am I reading something wrong here.

Thank you

答: Obviously the pointer points to an object at a memory location. In this case it is supposed to point to some object that implements a particular interface.</p>

Title: Pointers to Interfaces c++


问:
Letter guessing game Java
I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!

I want the user to try and guess the letter and not the number, but i cannot workout how to do this!

(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)

```<code>Random r = new Random();

char targetLetter = (char)(r.nextInt(26) + 'a');
</code>```

Any help would be greatly appreciated! And i can display my code if it is needed

```<code>public class Stack {

    public static void main(String[] args) {

        Random rand = new Random(); //This is were the computer selects the Target

        int guess;
        int numGuesses = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int bestScore = 0;

        Scanner consoleIn = new Scanner(System.in);
        Scanner name = new Scanner(System.in);

        System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
        userName = name.nextLine();

        System.out.println("Hello " + userName + " :) Welcome to the game!\n");

        while (play = true) {
            session++;
            Target = rand.nextInt(26) + 1;
            System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                numGuesses++;

                if (guess > 26)
                    System.out.println("Error! Above MAXIMUM range");
                else if (guess <= 0)
                    System.out.println("Error! Below MINIMUM range");
                else if (guess > Target)
                    System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
                else if (guess < Target)
                    System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
            } while (guess != Target && numGuesses < 5);

            if (guess == Target) {
                System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
            } else {
                System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
                if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
                    play = true;
                    numGuesses = 0;
                } else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
                    play = false;
                    System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
                    System.out.println("You had  " + session + " Goes");
                    System.out.println("The number of times you guessed correctly: " + sessions + "");
                    break;
                }
            }
        }
    }
}
</code>```

答:
Use the same method that you do for your random characters. Assuming you have your guessed character as an int variable called "guess", and it has value 1-26 corresponding A-Z:</p>

```<code>Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');

...

int guess = ...
char guessChar = (char)guess + 'a';
if (guessChar == targetLetter) {
    System.out.println("Correct!");
} else {
    System.out.println("Guess again!")
}
</code>```

Title: Letter guessing game Java

Body:
I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!

I want the user to try and guess the letter and not the number, but i cannot workout how to do this!

(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)

Random r = new Random();

char targetLetter = (char)(r.nextInt(26) + 'a');

Any help would be greatly appreciated! And i can display my code if it is needed

public class Stack {

    public static void main(String[] args) {

        Random rand = new Random(); //This is were the computer selects the Target

        int guess;
        int numGuesses = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int bestScore = 0;

        Scanner consoleIn = new Scanner(System.in);
        Scanner name = new Scanner(System.in);

        System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
        userName = name.nextLine();

        System.out.println("Hello " + userName + " :) Welcome to the game!\n");

        while (play = true) {
            session++;
            Target = rand.nextInt(26) + 1;
            System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                numGuesses++;

                if (guess > 26)
                    System.out.println("Error! Above MAXIMUM range");
                else if (guess <= 0)
                    System.out.println("Error! Below MINIMUM range");
                else if (guess > Target)
                    System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
                else if (guess < Target)
                    System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
            } while (guess != Target && numGuesses < 5);

            if (guess == Target) {
                System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
            } else {
                System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
                if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
                    play = true;
                    numGuesses = 0;
                } else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
                    play = false;
                    System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
                    System.out.println("You had  " + session + " Goes");
                    System.out.println("The number of times you guessed correctly: " + sessions + "");
                    break;
                }
            }
        }
    }
}

Body:
Use the same method that you do for your random characters. Assuming you have your guessed character as an int variable called "guess", and it has value 1-26 corresponding A-Z:

Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');

...

int guess = ...
char guessChar = (char)guess + 'a';
if (guessChar == targetLetter) {
    System.out.println("Correct!");
} else {
    System.out.println("Guess again!")
}


答: You're right that this shared_ptr will always either be empty or will point to a concrete object. But the specific type of that object is unknown to the shared_ptr; all it knows is that whatever object it points to implements (is derived directly or indirectly from) the anObjectsInterface class.</p>

Title: Pointers to Interfaces c++

Body:
Disclaimer: I am a complete C++ beginner, and if there is a similar answer to this question, please direct me to it, as I may have missed it, not knowing much in the way of theory.

So I was looking through some c++ code, and I found something like this:

shared_ptr<anObjectsInterface>

Which got me wondering, how can there be a pointer to an interface? Surely a pointer points to an object in memory, or am I reading something wrong here.

Thank you


问:
How to convert outputStream to a byte array?
How can I convert an OutputStream to a byte array? I have found that first I need to convert this OutputStream to a ByteArrayOutputStream. There is only write() method in this OutputStream class and I don't know what to do. Is there any idea? </p>

答:
If the OutputStream object supplied is not already a ByteArrayOutputStream, one can wrap it inside a delegate class that will "grab" the bytes supplied to the write() methods, e.g.

```<code>public class DrainableOutputStream extends FilterOutputStream {
  private final ByteArrayOutputStream buffer;
  public DrainableOutputStream(OutputStream out) {
    super(out);
    this.buffer = new ByteArrayOutputStream();
  }
  @Override
  public void write(byte b[]) throws IOException {
    this.buffer.write(b);
    super.write(b);
  }
  @Override
  public void write(byte b[], int off, int len) throws IOException {
    this.buffer.write(b, off, len);
    super.write(b, off, len);
  }
  @Override
  public void write(int b) throws IOException {
    this.buffer.write(b);
    super.write(b);
  }
  public byte[] toByteArray() {
    return this.buffer.toByteArray();
  }
}
</code>```

To reduce the overhead, the calls to super in the above class can be omitted - e.g., if only the "conversion" to a byte array is desired.

A more detailed discussion can be found in another StackOverflow question.

Body:
If the OutputStream object supplied is not already a ByteArrayOutputStream, one can wrap it inside a delegate class that will "grab" the bytes supplied to the write() methods, e.g.

public class DrainableOutputStream extends FilterOutputStream {
  private final ByteArrayOutputStream buffer;
  public DrainableOutputStream(OutputStream out) {
    super(out);
    this.buffer = new ByteArrayOutputStream();
  }
  @Override
  public void write(byte b[]) throws IOException {
    this.buffer.write(b);
    super.write(b);
  }
  @Override
  public void write(byte b[], int off, int len) throws IOException {
    this.buffer.write(b, off, len);
    super.write(b, off, len);
  }
  @Override
  public void write(int b) throws IOException {
    this.buffer.write(b);
    super.write(b);
  }
  public byte[] toByteArray() {
    return this.buffer.toByteArray();
  }
}

To reduce the overhead, the calls to super in the above class can be omitted - e.g., if only the "conversion" to a byte array is desired.

A more detailed discussion can be found in another StackOverflow question.


问:
How to remove characters in string after email
I'm using this code to list email addresses from a HTML page.

```<code>require 'nokogiri'

selector = "//a[starts-with(@href, \"mailto:\")]/@href"

doc = Nokogiri::HTML.parse File.read 'in.rb'

nodes = doc.xpath selector

addresses = nodes.collect {|n| n.value[7..-1]}

puts addresses
</code>```

This is sample code I'm parsing:

```<code><a href="mailto:joe@example.com?subject=My Business Is Dying">
</code>```

But I'm getting more than just the email address. I'm getting this in my results:

```<code>joe@example.com?subject=My Business Is Dying
</code>```

How do I drop off everything after the question mark so it's only the email address?

答:
I'd probably use one of these two:

```<code>str = 'joe@example.com?subject=My Business Is Dying'

str.split('?').first # => "joe@example.com"
str[/^[^?]+/] # => "joe@example.com"
</code>```

The second is a simple regular expression embedded in String's [] (slice) method. The pattern basically says "start at the beginning and grab everything up until a question mark."

They're equivalent as far as speed goes. I'd probably use the first because it's easier to read.

Body:
I'm using this code to list email addresses from a HTML page.

require 'nokogiri'

selector = "//a[starts-with(@href, \"mailto:\")]/@href"

doc = Nokogiri::HTML.parse File.read 'in.rb'

nodes = doc.xpath selector

addresses = nodes.collect {|n| n.value[7..-1]}

puts addresses

This is sample code I'm parsing:

But I'm getting more than just the email address. I'm getting this in my results:

joe@example.com?subject=My Business Is Dying

How do I drop off everything after the question mark so it's only the email address?

Body:
I'd probably use one of these two:

str = 'joe@example.com?subject=My Business Is Dying'

str.split('?').first # => "joe@example.com"
str[/^[^?]+/] # => "joe@example.com"

The second is a simple regular expression embedded in String's [] (slice) method. The pattern basically says "start at the beginning and grab everything up until a question mark."

They're equivalent as far as speed goes. I'd probably use the first because it's easier to read.


问:
Structured Streaming 2.1.0 Foreach not called
I am trying to test foreach of structured streaming with Kafka on a yarn cluster and have this little piece of code:

```<code>  val ds1 = spark
  .readStream
  .format("kafka")
  .option("kafka.bootstrap.servers", "data01:9092,data02:9092,data03:9092")
  .option("subscribe", "cluster-topic-01")
  .load()

  /* This block works
  val query = ds1.writeStream
        .format("console")
        .start()
  */

  // this block doesn't have any call to open()
  val query = ds1.writeStream.foreach(new ForeachWriter[Row] {
          override def open(partitionId: Long, version: Long): Boolean = {
                println("open("+partitionId+","+version+")")
                true
          }

          override def process(record: Row) : Unit = {
            // write string to connection
                println("process() :: "+record)
          }

          override def close(errorOrNull: Throwable): Unit = {
            // close the connection
                println("close()")
          }
  }).start()

  query.awaitTermination()
</code>```

When I run this program, there is no call to open(). I have compared other examples from other threads but I can't find out what's missing. There is a start() call after foreach which seems to match what the documentation here.

I can stream to a file or a console but just can't get any call in foreach.

Any suggestion on where to look at? TIA.

答: open, process and close will run in the executors like RDD.foreach, so you won't be able to see it unless you are using local mode.

Body:
I am trying to test foreach of structured streaming with Kafka on a yarn cluster and have this little piece of code:

  val ds1 = spark
  .readStream
  .format("kafka")
  .option("kafka.bootstrap.servers", "data01:9092,data02:9092,data03:9092")
  .option("subscribe", "cluster-topic-01")
  .load()

  /* This block works
  val query = ds1.writeStream
        .format("console")
        .start()
  */

  // this block doesn't have any call to open()
  val query = ds1.writeStream.foreach(new ForeachWriter[Row] {
          override def open(partitionId: Long, version: Long): Boolean = {
                println("open("+partitionId+","+version+")")
                true
          }

          override def process(record: Row) : Unit = {
            // write string to connection
                println("process() :: "+record)
          }

          override def close(errorOrNull: Throwable): Unit = {
            // close the connection
                println("close()")
          }
  }).start()

  query.awaitTermination()

When I run this program, there is no call to open(). I have compared other examples from other threads but I can't find out what's missing. There is a start() call after foreach which seems to match what the documentation here.

I can stream to a file or a console but just can't get any call in foreach.

Any suggestion on where to look at? TIA.


问:
Linking CSS to HTML background color
I am using node.js to run a local website and am having trouble linking the css to html.

The html is:

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

<head>
    <title> Name </title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="style.css" />

</head>

<body id="background">
    <h1> My Website </h1>
    <span style="float:right">
    <a href = "https://google.com/"> Google </a>
    </span>
</body>
</code>```

and css is:

```<code>#background {
  background-color: #0099FF;
}
</code>```

I have not been able to view the effects of the css on the website and am not able to change the background color.

I have checked online resources and it seems as if the syntax is correct. The css file style.css is in the same directory as the html. The html is working on the local website but not the css.

update: i am adding the app.js file

```<code>var http = require('http'),
    fs = require('fs');

fs.readFile('./header.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});
</code>```

答:
try doing class="background"

and then in css do .background instead of #background

Title: Linking CSS to HTML background color

Body:
I am using node.js to run a local website and am having trouble linking the css to html.

The html is:

<!DOCTYPE html>

    <title> Name </title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="style.css" />

 My Website

     Google

and css is:

#background {
  background-color: #0099FF;
}

I have not been able to view the effects of the css on the website and am not able to change the background color.

I have checked online resources and it seems as if the syntax is correct. The css file style.css is in the same directory as the html. The html is working on the local website but not the css.

update: i am adding the app.js file

var http = require('http'),
    fs = require('fs');

fs.readFile('./header.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});