问:
AppEngine bulk loader and automatically created property values
In my model I have a property:

```<code>created = db.DateTimeProperty(required=True, auto_now_add=True)
</code>```

When an object of this type is created in the datastore, the created property is automatically populated.

When I use the bulk loader tool with a table which does not have this field, the field is not automatically populated when I upload to AppEngine, at which time new objects are created.

How can I make it set the created time on new objects uploaded from the bulk loader?

答:
Add something like the following to bulkloader.yaml:</p>

```<code>- property: created
  external_name: created
  import_transform: "lambda x: datetime.datetime.utcnow()"
</code>```

Body:
In my model I have a property:

created = db.DateTimeProperty(required=True, auto_now_add=True)

When an object of this type is created in the datastore, the created property is automatically populated.

When I use the bulk loader tool with a table which does not have this field, the field is not automatically populated when I upload to AppEngine, at which time new objects are created.

How can I make it set the created time on new objects uploaded from the bulk loader?

Body:
Add something like the following to bulkloader.yaml:

- property: created
  external_name: created
  import_transform: "lambda x: datetime.datetime.utcnow()"


来源: stackexchange

问:
Add link in datatable cell
How can I add html tags inside a column of the datatable?

$('#example').DataTable( {
    "ajax": {
        "url": "ajax/lista_bozze.php",
        "dataSrc": ""
    },
    "columns": [
    { "data": "num_ticket" },
    { "data": "cod_pro" },
    { "data": "name" },
    { "data": "rag_soc" },
    { "data": "date_ticket" },
    { "data": "cod_pro" }
    ]
} );
```

答:
You can use render option to process the data inside a datatable column,

this is example of converting one column into a link:

```<code>$('#example').DataTable( {
  "columnDefs": [ {
    "targets": 0,
    "data": "download_link",
    "render": function ( data, type, row, meta ) {
      return '<a href="'+data+'">Download</a>';
    }
  } ]
} );
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add link in datatable cell

Body:
You can use render option to process the data inside a datatable column,

this is example of converting one column into a link:

$('#example').DataTable( {
  "columnDefs": [ {
    "targets": 0,
    "data": "download_link",
    "render": function ( data, type, row, meta ) {
      return '<a href="'+data+'">Download</a>';
    }
  } ]
} );


问:
Adding string values from previous row to next row in Pandas
I have a dataframe that every once in a while separates the text from the first cell in a row into two rows and fills the column values as None and NaN in the first row and then fills the actual column values into the second row.

Here is an example:

```<code>df

   House_Type       Area          Shape

   Blue House       3456          circle
   Red house        2345          square
   Small Green      NaN           None
   House            987           square
</code>```

On these occasions I want to add the string from the first cell in house type of the split row (Small Green) to the the first cell of house type in the second part of the split row (House). Example below for reference.

The end result looking something like this:

```<code>  df

   House_Type             Area        Shape

   Blue House             3456          circle
   Red house              2345          square
   Small Green            NaN           None
   Small Green House      987           square
</code>```

I wrote a function to do this but it just comes back looking like the original dataframe. I'm not sure what I'm missing here.

Code:

```<code>def row_clean(df):
    for i in range(0, len(df)):
        if df.Shape.values[i] == None:
            df.House_Type.values[i + 1] = df.House_Type.values[i] + ' ' + df.House_Type.values[i + 1]

    return df
</code>```

答:
try this</p>

```<code>def row_clean(df):
for i in range(0, len(df)):
    if pd.isnull(df.Shape.values[i]):
        df.House_Type.values[i + 1] = df.House_Type.values[i] + ' ' + df.House_Type.values[i + 1]

return df
</code>```

Body:
I have a dataframe that every once in a while separates the text from the first cell in a row into two rows and fills the column values as None and NaN in the first row and then fills the actual column values into the second row.

Here is an example:

df

   House_Type       Area          Shape

   Blue House       3456          circle
   Red house        2345          square
   Small Green      NaN           None
   House            987           square

On these occasions I want to add the string from the first cell in house type of the split row (Small Green) to the the first cell of house type in the second part of the split row (House). Example below for reference.

The end result looking something like this:

  df

   House_Type             Area        Shape

   Blue House             3456          circle
   Red house              2345          square
   Small Green            NaN           None
   Small Green House      987           square

I wrote a function to do this but it just comes back looking like the original dataframe. I'm not sure what I'm missing here.

Code:

def row_clean(df):
    for i in range(0, len(df)):
        if df.Shape.values[i] == None:
            df.House_Type.values[i + 1] = df.House_Type.values[i] + ' ' + df.House_Type.values[i + 1]

    return df

Body:
try this

def row_clean(df):
for i in range(0, len(df)):
    if pd.isnull(df.Shape.values[i]):
        df.House_Type.values[i + 1] = df.House_Type.values[i] + ' ' + df.House_Type.values[i + 1]

return df


问:
Check if letters from word are all in string Hangman
I'm trying to create a simple hangman game in Python. I've come quite far for a beginner I guess :) The only thing I can't accomplish is checking wether the word is actually guessed. I need to check if all the letters are actually in a list I've created, yet I'm not sure how.
I do realise there was a topic regarding this, this didn't help me tho. </p>

```<code>import random

with open('randomlist.txt') as bestand:
woordenlijst = bestand.read().splitlines()

print("Welcome to Hangman.")
naam = input("What is your name? ")
print("Hello", naam, ", the computer selecter a secret word.")

woord = random.choice(woordenlijst)
lengte_woord = len(woord)
ingevoerde_letters = []

galg = []

i = 0

print("The length of the word is: \n")
while i < lengte_woord:
    print("_", end=" ")
    i = i + 1

levens = 0
invoer = " "

print(woord)

while levens <= 10:
    letter = input("Letter: ")
    if letter in ingevoerde_letters:
        print("You already tried this letter.")
    elif letter in woord:
        print("This letter is in the word. We'll fill it in for you.")
        i = 0
        while i < lengte_woord:
            if woord[i] == letter:
                print(letter, end=" ")
                ingevoerde_letters.append(letter)
                i = i + 1
            elif woord[i] in ingevoerde_letters:
                print(woord[i], end=" ")
                i = i + 1
            else:
                print("_", end=" ")
                i = i + 1
    else:
        ingevoerde_letters.append(letter)
        print("This letter is not in the word", galg[levens])
        levens = levens + 1
print(galg[10], "\nGame over!")
</code>```

答:
There are some problems in your code. For example, when guessing a wrong letter, this letter is never added to the galg list you later use to print wrong guess. So either replace galg with ingevord_letter or add the letter to both ingevord_letter and galg. Like this:

```<code>else:
    ingevoerde_letters.append(letter)
    galg.append(letter)
</code>```

A second issue is in your read file. When you say .splitline(), you make woord contain whole lines (or everything encompassed between \n). I think you want .split() instead to choose 1 random word from the text.

For your actual question, one way to finish the game upon successful guesses, is to check the letter collection against the collection of letters in the word. See the isWon function. ref this answer

```<code>import random
def isWon(mysteryWord, lettersGuessed):
    return set(lettersGuessed) == set(mysteryWord)

with open('randomlist.txt') as bestand:
    woordenlijst = bestand.read().splitlines()

print("Welkom bij Galgje, voor we beginnen willen we graag het volgende aan je vragen.")
naam = input("Wat is je naam? ")
print("Hallo", naam, ", leuk dat je wilt spelen. De computer heeft een willekeurig woord voor je geselecteerd.")

woord = random.choice(woordenlijst)
lengte_woord = len(woord)
ingevoerde_letters = []

galg = []

i = 0

print("De lengte van het woord is: \n")
while i < lengte_woord:
    print("_", end=" ")
    i = i + 1

levens = 0
invoer = " "

print(woord)

while levens <= 10:
    letter = input("Geef een letter: ")
    if letter in ingevoerde_letters:
        print("Deze letter heb je al ingevoerd.")
    elif letter in woord:
        print("Deze letter zit in het woord. We vullen het voor je in.")
        i = 0
        while i < lengte_woord:
            if woord[i] == letter:
                print(letter, end=" ")
                ingevoerde_letters.append(letter)
                i = i + 1
            elif woord[i] in ingevoerde_letters:
                print(woord[i], end=" ")
                i = i + 1
            else:
                print("_", end=" ")
                i = i + 1
    else:
        ingevoerde_letters.append(letter)
        galg.append(letter)
        print("Deze letter zit niet in het woord", galg[levens])
        levens = levens + 1
    if (isWon(ingevoerde_letters, woord)):
      #successfull code here
      break
print(galg, "\nGame over!")
</code>```

Body:
I'm trying to create a simple hangman game in Python. I've come quite far for a beginner I guess :) The only thing I can't accomplish is checking wether the word is actually guessed. I need to check if all the letters are actually in a list I've created, yet I'm not sure how.
I do realise there was a topic regarding this, this didn't help me tho.

import random

with open('randomlist.txt') as bestand:
woordenlijst = bestand.read().splitlines()

print("Welcome to Hangman.")
naam = input("What is your name? ")
print("Hello", naam, ", the computer selecter a secret word.")

woord = random.choice(woordenlijst)
lengte_woord = len(woord)
ingevoerde_letters = []

galg = []

i = 0

print("The length of the word is: \n")
while i < lengte_woord:
    print("_", end=" ")
    i = i + 1

levens = 0
invoer = " "

print(woord)

while levens <= 10:
    letter = input("Letter: ")
    if letter in ingevoerde_letters:
        print("You already tried this letter.")
    elif letter in woord:
        print("This letter is in the word. We'll fill it in for you.")
        i = 0
        while i < lengte_woord:
            if woord[i] == letter:
                print(letter, end=" ")
                ingevoerde_letters.append(letter)
                i = i + 1
            elif woord[i] in ingevoerde_letters:
                print(woord[i], end=" ")
                i = i + 1
            else:
                print("_", end=" ")
                i = i + 1
    else:
        ingevoerde_letters.append(letter)
        print("This letter is not in the word", galg[levens])
        levens = levens + 1
print(galg[10], "\nGame over!")

Body:
There are some problems in your code. For example, when guessing a wrong letter, this letter is never added to the galg list you later use to print wrong guess. So either replace galg with ingevord_letter or add the letter to both ingevord_letter and galg. Like this:

else:
    ingevoerde_letters.append(letter)
    galg.append(letter)

A second issue is in your read file. When you say .splitline(), you make woord contain whole lines (or everything encompassed between \n). I think you want .split() instead to choose 1 random word from the text.

For your actual question, one way to finish the game upon successful guesses, is to check the letter collection against the collection of letters in the word. See the isWon function. ref this answer

import random
def isWon(mysteryWord, lettersGuessed):
    return set(lettersGuessed) == set(mysteryWord)

with open('randomlist.txt') as bestand:
    woordenlijst = bestand.read().splitlines()

print("Welkom bij Galgje, voor we beginnen willen we graag het volgende aan je vragen.")
naam = input("Wat is je naam? ")
print("Hallo", naam, ", leuk dat je wilt spelen. De computer heeft een willekeurig woord voor je geselecteerd.")

woord = random.choice(woordenlijst)
lengte_woord = len(woord)
ingevoerde_letters = []

galg = []

i = 0

print("De lengte van het woord is: \n")
while i < lengte_woord:
    print("_", end=" ")
    i = i + 1

levens = 0
invoer = " "

print(woord)

while levens <= 10:
    letter = input("Geef een letter: ")
    if letter in ingevoerde_letters:
        print("Deze letter heb je al ingevoerd.")
    elif letter in woord:
        print("Deze letter zit in het woord. We vullen het voor je in.")
        i = 0
        while i < lengte_woord:
            if woord[i] == letter:
                print(letter, end=" ")
                ingevoerde_letters.append(letter)
                i = i + 1
            elif woord[i] in ingevoerde_letters:
                print(woord[i], end=" ")
                i = i + 1
            else:
                print("_", end=" ")
                i = i + 1
    else:
        ingevoerde_letters.append(letter)
        galg.append(letter)
        print("Deze letter zit niet in het woord", galg[levens])
        levens = levens + 1
    if (isWon(ingevoerde_letters, woord)):
      #successfull code here
      break
print(galg, "\nGame over!")


问:
Searching list of words in scrabble with blank tile using Python
I have a scrabble challenge and have the following list of letters:

```<code>letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z']
</code>```

And following list of words:

```<code>word = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']
</code>```

Here is the code I'm using to find the words which can be made for a given list of letters:

```<code>def valid_word(word, letters):
    available_letters = letters[:]

    candidate = True

    for letter in word:
        if letter not in available_letters:
            candidate = False
        else:
            available_letters.remove(letter)
    if candidate == True:
        return candidate
</code>```

It gives me output that two words 'yutz' and 'tux' can be made for the current list of letters.

My challenge is what if we replace one of the letter in the list of letters with blank denoted as '_' in the list. For example 't' is replaced by '_' below:

```<code>letters = ['_', 'u', 'v', 'w', 'x', 'y', 'z']
</code>```

How can code still be able to find the same words 'yutz' and 'tux' but replace the missing letter? The expected output is 'yu_z' and '_ux'.

UPDATE:

Here is the code which I tried which does not completely work but kind of give direction to where I am going:

```<code>rack_list = []
    for letter in letters:
        if letter in string.ascii_lowercase:
            rack_list.append(letter)
        else:
            blank_count = user_input.count("_")

    def valid_word(word, rack):
    available_letters = rack_list[:]
    missed_counter = 0

    for letter in word:
        if letter in available_letters:
            available_letters.remove(letter)
        else:
            missed_counter += 1
    if missed_counter <= blank_count:
        for i in word:
            if i in available_letters:
                word += i
            else:
                word += "_"
        return word
</code>```

答:
Instead of simply setting candidate to False, keep a counter of how many letters have been missed.  When that count exceeds the quantity of blanks in the rack, then you disqualify the word.

Also, please note that if candidate == True is redundant.  Use simply if candidate.  The value is already Boolean; there's no need to test it.

Code changes per OP's added attempt:

Your main problem was having the final print inside the loop; until you've checked all letters (finished the loop), you don't know whether the word is possible.

```<code>def valid_word(word, rack):
    available_letters = rack[:]
    blank_count = available_letters.count('_')
    # print available_letters, blank_count

    missed_counter = 0
    for letter in word:
        if letter in available_letters:
            available_letters.remove(letter)
        else:
            missed_counter += 1

    # print word, missed_counter
    if missed_counter <= blank_count:
        print(word)

# Test program
rack = ['_', 'u', 'v', 'w', 'x', 'y', 'z']
lexicon = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'xyzzy', 'zebra']

for word in lexicon:
    valid_word(word, rack)
</code>```

Output:

```<code>yutz
tux
</code>```

Body:
I have a scrabble challenge and have the following list of letters:

letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z']

And following list of words:

word = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']

Here is the code I'm using to find the words which can be made for a given list of letters:

def valid_word(word, letters):
    available_letters = letters[:]

    candidate = True

    for letter in word:
        if letter not in available_letters:
            candidate = False
        else:
            available_letters.remove(letter)
    if candidate == True:
        return candidate

It gives me output that two words 'yutz' and 'tux' can be made for the current list of letters.

My challenge is what if we replace one of the letter in the list of letters with blank denoted as '_' in the list. For example 't' is replaced by '_' below:

letters = ['_', 'u', 'v', 'w', 'x', 'y', 'z']

How can code still be able to find the same words 'yutz' and 'tux' but replace the missing letter? The expected output is 'yu_z' and '_ux'.

UPDATE:

Here is the code which I tried which does not completely work but kind of give direction to where I am going:

rack_list = []
    for letter in letters:
        if letter in string.ascii_lowercase:
            rack_list.append(letter)
        else:
            blank_count = user_input.count("_")

    def valid_word(word, rack):
    available_letters = rack_list[:]
    missed_counter = 0

    for letter in word:
        if letter in available_letters:
            available_letters.remove(letter)
        else:
            missed_counter += 1
    if missed_counter <= blank_count:
        for i in word:
            if i in available_letters:
                word += i
            else:
                word += "_"
        return word

Body:
Instead of simply setting candidate to False, keep a counter of how many letters have been missed.  When that count exceeds the quantity of blanks in the rack, then you disqualify the word.

Also, please note that if candidate == True is redundant.  Use simply if candidate.  The value is already Boolean; there's no need to test it.

Code changes per OP's added attempt:

Your main problem was having the final print inside the loop; until you've checked all letters (finished the loop), you don't know whether the word is possible.

def valid_word(word, rack):
    available_letters = rack[:]
    blank_count = available_letters.count('_')
    # print available_letters, blank_count

    missed_counter = 0
    for letter in word:
        if letter in available_letters:
            available_letters.remove(letter)
        else:
            missed_counter += 1

    # print word, missed_counter
    if missed_counter <= blank_count:
        print(word)

# Test program
rack = ['_', 'u', 'v', 'w', 'x', 'y', 'z']
lexicon = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'xyzzy', 'zebra']

for word in lexicon:
    valid_word(word, rack)

Output:

yutz
tux


问:
Making my prime/perfect/composite number checker more efficient/cleaner
This program asks the user for a minimum number greater than 1 and a maximum number grater than the min. It then prints out number by number what its divisible by, if its prime or composite, and if its a perfect number in this format:

```<code>2 is divisible by 1
2 is prime.
2 is not perfect

3 is divisible by 1
3 is prime.
3 is not perfect

4 is divisible by 1 2
4 is composite.
4 is not perfect.

5 is divisible by 1
5 is prime.
5 is not perfect

6 is divisible by 1 2 3
6 is composite.
6 is perfect.
</code>```

At the end it displays the number of prime and perfect numbers. The program works but I am wondering if there are any ways to clean up the code/make it more efficient(or if there is anything im doing wrong)

Code:

```<code>public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input = new Scanner(System.in);

    int min;
    int max;

    //declaring min and max values

    System.out.println("Enter minimum value to check (an integer greater than 1:)");
    min=input.nextInt();

    while(!(min>1)) {
        System.out.println("The entry is valid. Please be sure to enter an integer greater than 1");
        System.out.println();
        System.out.println("Enter minimum value to check (an integer greater than 1:)");
        min=input.nextInt();
    }

    System.out.println("Enter maximum value to check (an integer greater than your min value:)");
    max=input.nextInt();

    while(!(max>min)) {
        System.out.println("The entry is valid. Please be sure to enter an integer greater than the min value");
        System.out.println();
        System.out.println("Enter maximum value to check (an integer greater than min:)");
        max=input.nextInt();
    }

    //declaring count and tracking variables

    int count;
    int numPrime=0;
    int numPerfect=0;
    int temp=1;
    String result=" ";
    boolean isPrime=true;
    boolean isPerfect=false;
    int i;
    //main loop

    for(count=min;count<=max;count++) {

        for(i=2;i<=count;i++) {
            if(count%i==0&&i!=count) {
                isPrime=false;
                result=result+i+" ";
                temp+=i;
            }
            else
                isPrime=true;
        }
        //Perfect counter
        if(temp==count) {
            isPerfect=true;
            numPerfect=numPerfect+1;
        }
        else
            isPerfect=false;
        //Composite print
        if(!(result.equals(" "))) {
            System.out.println(count+" is divisible by 1"+result);
            System.out.println(count+" is composite.");
            if(isPerfect==true)
                System.out.println(count+" is perfect.");
            else
                System.out.println(count+ " is not perfect.");
            System.out.println();
        }
        //Prime print
        else {
            numPrime=numPrime+1;
            System.out.println(count+" is divisible by 1");
            System.out.println(count+" is prime.");
            System.out.println(count+" is not perfect");
            System.out.println();
        }
        //reset values
        result=" ";
        temp=1;
    }
    System.out.println("Primes found: "+numPrime);
    System.out.println("Perfect numbers found: "+numPerfect);

}
</code>```

}

答:
I have a hobby of making my python perfect number code as efficient as possible so I know a few extra efficiency things but unfortunately I don't code Java so these will just be some generic efficiency improvements.

Firstly, as has been hinted in the comments you only have to check to the square root of the number to get all the divisors but what you do have to do is then add the number / your divisors to your list of divisors to get every divisor

```<code>e.g. Find the divisors of 20
The square root of 20 is 4.47 so we choose 4.
20 mod 1 == 0 so we add 1 and 20/1 a.k.a. 20 to our list of divisors
20 mod 2 == 0 so we add 2 and 20/2 a.k.a 10 to our list of divisors
20 mod 3 == 2 so we ignore this one.
20 mod 4 == 0 so we add 4 and 20/4 a.k.a. 5 to our list of divisors
Therefore the divisors are 1, 2, 4, 5, 10 and 20.
</code>```

Another good efficiency improvement is that all perfect numbers will end in 6 or 28 so you can quickly check that.

The last efficiency improvement I know is a big change to the prime calculation bit.

```<code>If a number is smaller than or equal to 1 it is not prime.
Else if a number is smaller than or equal to 3 it is prime.
Else if a number mod 2 or a number mod 3 == 0 it is not prime.
Set i to 5
While i squared is smaller than or equal to a number:
    If a number mod i or a number mod (i + 2) == 0:
        It is not prime
    6 is added to i
If nothing has said otherwise then the number is prime.
</code>```

Body:
This program asks the user for a minimum number greater than 1 and a maximum number grater than the min. It then prints out number by number what its divisible by, if its prime or composite, and if its a perfect number in this format:

2 is divisible by 1
2 is prime.
2 is not perfect

3 is divisible by 1
3 is prime.
3 is not perfect

4 is divisible by 1 2
4 is composite.
4 is not perfect.

5 is divisible by 1
5 is prime.
5 is not perfect

6 is divisible by 1 2 3
6 is composite.
6 is perfect.

At the end it displays the number of prime and perfect numbers. The program works but I am wondering if there are any ways to clean up the code/make it more efficient(or if there is anything im doing wrong)

Code:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input = new Scanner(System.in);

    int min;
    int max;

    //declaring min and max values

    System.out.println("Enter minimum value to check (an integer greater than 1:)");
    min=input.nextInt();

    while(!(min>1)) {
        System.out.println("The entry is valid. Please be sure to enter an integer greater than 1");
        System.out.println();
        System.out.println("Enter minimum value to check (an integer greater than 1:)");
        min=input.nextInt();
    }

    System.out.println("Enter maximum value to check (an integer greater than your min value:)");
    max=input.nextInt();

    while(!(max>min)) {
        System.out.println("The entry is valid. Please be sure to enter an integer greater than the min value");
        System.out.println();
        System.out.println("Enter maximum value to check (an integer greater than min:)");
        max=input.nextInt();
    }

    //declaring count and tracking variables

    int count;
    int numPrime=0;
    int numPerfect=0;
    int temp=1;
    String result=" ";
    boolean isPrime=true;
    boolean isPerfect=false;
    int i;
    //main loop

    for(count=min;count<=max;count++) {

        for(i=2;i<=count;i++) {
            if(count%i==0&&i!=count) {
                isPrime=false;
                result=result+i+" ";
                temp+=i;
            }
            else
                isPrime=true;
        }
        //Perfect counter
        if(temp==count) {
            isPerfect=true;
            numPerfect=numPerfect+1;
        }
        else
            isPerfect=false;
        //Composite print
        if(!(result.equals(" "))) {
            System.out.println(count+" is divisible by 1"+result);
            System.out.println(count+" is composite.");
            if(isPerfect==true)
                System.out.println(count+" is perfect.");
            else
                System.out.println(count+ " is not perfect.");
            System.out.println();
        }
        //Prime print
        else {
            numPrime=numPrime+1;
            System.out.println(count+" is divisible by 1");
            System.out.println(count+" is prime.");
            System.out.println(count+" is not perfect");
            System.out.println();
        }
        //reset values
        result=" ";
        temp=1;
    }
    System.out.println("Primes found: "+numPrime);
    System.out.println("Perfect numbers found: "+numPerfect);

}

}

Body:
I have a hobby of making my python perfect number code as efficient as possible so I know a few extra efficiency things but unfortunately I don't code Java so these will just be some generic efficiency improvements.

Firstly, as has been hinted in the comments you only have to check to the square root of the number to get all the divisors but what you do have to do is then add the number / your divisors to your list of divisors to get every divisor

e.g. Find the divisors of 20
The square root of 20 is 4.47 so we choose 4.
20 mod 1 == 0 so we add 1 and 20/1 a.k.a. 20 to our list of divisors
20 mod 2 == 0 so we add 2 and 20/2 a.k.a 10 to our list of divisors
20 mod 3 == 2 so we ignore this one.
20 mod 4 == 0 so we add 4 and 20/4 a.k.a. 5 to our list of divisors
Therefore the divisors are 1, 2, 4, 5, 10 and 20.

Another good efficiency improvement is that all perfect numbers will end in 6 or 28 so you can quickly check that.

The last efficiency improvement I know is a big change to the prime calculation bit.

If a number is smaller than or equal to 1 it is not prime.
Else if a number is smaller than or equal to 3 it is prime.
Else if a number mod 2 or a number mod 3 == 0 it is not prime.
Set i to 5
While i squared is smaller than or equal to a number:
    If a number mod i or a number mod (i + 2) == 0:
        It is not prime
    6 is added to i
If nothing has said otherwise then the number is prime.


问:
Configure the connection_collation with SQLAlchemy
I'm attempting to get SQLAlchemy to connect to MySQL with a collation_connection of utf8mb4_unicode_ci.

My sever and database are both using the utf8mb4_unicode_ci collation. Without any configuration changes my collation_connection is utf8_general_ci. If I set the charset argument in the connection string to charset=utf8mb4 the collation_connection is then set to utf8mb4_general_ci. I have been unable to find any documentation stating how to set the collation_connection when using SQLAlchemy.

答:
This is a variable specific to mysql and all you can do is to run a statement on each connection initialization:</p>

```<code>In [18]: url = 'mysql+pymysql://test:test@localhost/test'

In [19]: connect_args = {'init_command':"SET @@collation_connection='utf8mb4_unicode_ci'"}

In [20]: with sqlalchemy.create_engine(url, connect_args=connect_args).connect() as con:
    ...:     print(con.execute('select @@collation_connection;').fetchall())
    ...:
[('utf8mb4_unicode_ci',)]
</code>```

Body:
This is a variable specific to mysql and all you can do is to run a statement on each connection initialization:

In [18]: url = 'mysql+pymysql://test:test@localhost/test'

In [19]: connect_args = {'init_command':"SET @@collation_connection='utf8mb4_unicode_ci'"}

In [20]: with sqlalchemy.create_engine(url, connect_args=connect_args).connect() as con:
    ...:     print(con.execute('select @@collation_connection;').fetchall())
    ...:
[('utf8mb4_unicode_ci',)]


问:
Error in d3.js v4 - Gauge chart In Angular4
I have tried to implement gauge chart but getting error.

I have tried it in fiddle and trying to implement the same in angular2.
Fiddle link:-  https://jsfiddle.net/wf0y2sLb/42/

Stackblitz link: https://stackblitz.com/edit/angular-nnypbb?file=app%2Fapp.component.ts

I have tried in stackblitz above but it is providing error.
Error "property 'configure' does not exist on type '{ }'"

I am trying to  achieve working gauge in angular2. I am unable to figure out the issue  and how to achieve the task in angular.

Please help me to fix this chart in angular2.

needle-gauge-Chart-Component.ts

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

@Component({
  selector: 'app-needle-gauge-chart',
  templateUrl: './needle-gauge-chart.component.html',
  styleUrls: ['./needle-gauge-chart.component.css']
})

export class PrgNeedleGaugeChartComponent implements OnInit {
  constructor(public jsonDataService: PrgDataService, public injector: Injector) { }

  ngOnInit() {
this.buildNeedleGaugeChart();
  }

buildNeedleGaugeChart() {

var gauge = function(container, configuration) {
    var that = {};
    var config = {
        size                        : 710,
        clipWidth                   : 200,
        clipHeight                  : 110,
        ringInset                   : 20,
        ringWidth                   : 20,

        pointerWidth                : 10,
        pointerTailLength           : 5,
        pointerHeadLengthPercent    : 0.9,

        minValue                    : 0,
        maxValue                    : 10,

        minAngle                    : -90,
        maxAngle                    : 90,

        transitionMs                : 750,

        majorTicks                  : 5,
        labelFormat                 : d3.format('d'),
        labelInset                  : 10,

        arcColorFn                  : d3.interpolateHsl(d3.rgb('#e8e2ca'), d3.rgb('#3e6c0a'))
    };
    var range = undefined;
    var r = undefined;
    var pointerHeadLength = undefined;
    var value = 0;

    var svg = undefined;
    var arc = undefined;
    var scale = undefined;
    var ticks = undefined;
    var tickData = undefined;
    var pointer = undefined;

    var donut = d3.pie();

    function deg2rad(deg) {
        return deg * Math.PI / 180;
    }

    function newAngle(d) {
        var ratio = scale(d);
        var newAngle = config.minAngle + (ratio * range);
        return newAngle;
    }

    function configure(configuration) {
        var prop = undefined;
        for ( prop in configuration ) {
            config[prop] = configuration[prop];
        }

        range = config.maxAngle - config.minAngle;
        r = config.size / 2;
        pointerHeadLength = Math.round(r * config.pointerHeadLengthPercent);

        // a linear scale that maps domain values to a percent from 0..1
        scale = d3.scaleLinear()
            .range([0,1])
            .domain([config.minValue, config.maxValue]);

        ticks = scale.ticks(config.majorTicks);
        tickData = d3.range(config.majorTicks).map(function() {return 1/config.majorTicks;});

        arc = d3.arc()
            .innerRadius(r - config.ringWidth - config.ringInset)
            .outerRadius(r - config.ringInset)
            .startAngle(function(d, i) {
                var ratio = d * i;
                return deg2rad(config.minAngle + (ratio * range));
            })
            .endAngle(function(d, i) {
                var ratio = d * (i+1);
                return deg2rad(config.minAngle + (ratio * range));
            });
    }
    that.configure = configure;

    function centerTranslation() {
        return 'translate('+r +','+ r +')';
    }

    function isRendered() {
        return (svg !== undefined);
    }
    that.isRendered = isRendered;

    function render(newValue) {
        svg = d3.select(container)
            .append('svg:svg')
                .attr('class', 'gauge')
                .attr('width', config.clipWidth)
                .attr('height', config.clipHeight);

        var centerTx = centerTranslation();

        var arcs = svg.append('g')
                .attr('class', 'arc')
                .attr('transform', centerTx);

        arcs.selectAll('path')
                .data(tickData)
            .enter().append('path')
                .attr('fill', function(d, i) {
                    return config.arcColorFn(d * i);
                })
                .attr('d', arc);

        var lg = svg.append('g')
                .attr('class', 'label')
                .attr('transform', centerTx);
        lg.selectAll('text')
                .data(ticks)
            .enter().append('text')
                .attr('transform', function(d) {
                    var ratio = scale(d);
                    var newAngle = config.minAngle + (ratio * range);
                    return 'rotate(' +newAngle +') translate(0,' +(config.labelInset - r) +')';
                })
                .text(config.labelFormat);

        var lineData = [ [config.pointerWidth / 2, 0],
                        [0, -pointerHeadLength],
                        [-(config.pointerWidth / 2), 0],
                        [0, config.pointerTailLength],
                        [config.pointerWidth / 2, 0] ];
        var pointerLine = d3.line().curve(d3.curveLinear)
        var pg = svg.append('g').data([lineData])
                .attr('class', 'pointer')
                .attr('transform', centerTx);

        pointer = pg.append('path')
            .attr('d', pointerLine/*function(d) { return pointerLine(d) +'Z';}*/ )
            .attr('transform', 'rotate(' +config.minAngle +')');

        update(newValue === undefined ? 0 : newValue);
    }
    that.render = render;
    function update(newValue, newConfiguration) {
        if ( newConfiguration  !== undefined) {
            configure(newConfiguration);
        }
        var ratio = scale(newValue);
        var newAngle = config.minAngle + (ratio * range);
        pointer.transition()
            .duration(config.transitionMs)
            .ease(d3.easeElastic)
            .attr('transform', 'rotate(' +newAngle +')');
    }
    that.update = update;

    configure(configuration);

    return that;
};

    var powerGauge = gauge('#power-gauge', {
        size: 300,
        clipWidth: 300,
        clipHeight: 300,
        ringWidth: 60,
        maxValue: 10,
        transitionMs: 4000,
    });
    powerGauge.render();
  }
}
</code>```

答:
This is pretty ugly solution, but this is a reason why I personally don't like JS :) The problem is that you can not refer this from this context, as it kind of a callback.
You can do this trick:

```<code>var self = this;
var gauge = function (container, configuration) {
 ...
 self.gaugemap.configure = configure;
 ... // all other this. should be replaced by self.
}
</code>```

and replace all references to this by self.

Working sample: https://stackblitz.com/edit/angular-tjk9sl?file=app/app.component.ts

ContentLicense: CC BY-SA 4.0

Body:
I have tried to implement gauge chart but getting error.

I have tried it in fiddle and trying to implement the same in angular2.
Fiddle link:-  https://jsfiddle.net/wf0y2sLb/42/

Stackblitz link: https://stackblitz.com/edit/angular-nnypbb?file=app%2Fapp.component.ts

I have tried in stackblitz above but it is providing error.
Error "property 'configure' does not exist on type '{ }'"

I am trying to  achieve working gauge in angular2. I am unable to figure out the issue  and how to achieve the task in angular.

Please help me to fix this chart in angular2.

needle-gauge-Chart-Component.ts

import { Component,OnInit} from '@angular/core';
import * as d3 from "d3";

@Component({
  selector: 'app-needle-gauge-chart',
  templateUrl: './needle-gauge-chart.component.html',
  styleUrls: ['./needle-gauge-chart.component.css']
})

export class PrgNeedleGaugeChartComponent implements OnInit {
  constructor(public jsonDataService: PrgDataService, public injector: Injector) { }

  ngOnInit() {
this.buildNeedleGaugeChart();
  }

buildNeedleGaugeChart() {

var gauge = function(container, configuration) {
    var that = {};
    var config = {
        size                        : 710,
        clipWidth                   : 200,
        clipHeight                  : 110,
        ringInset                   : 20,
        ringWidth                   : 20,

        pointerWidth                : 10,
        pointerTailLength           : 5,
        pointerHeadLengthPercent    : 0.9,

        minValue                    : 0,
        maxValue                    : 10,

        minAngle                    : -90,
        maxAngle                    : 90,

        transitionMs                : 750,

        majorTicks                  : 5,
        labelFormat                 : d3.format('d'),
        labelInset                  : 10,

        arcColorFn                  : d3.interpolateHsl(d3.rgb('#e8e2ca'), d3.rgb('#3e6c0a'))
    };
    var range = undefined;
    var r = undefined;
    var pointerHeadLength = undefined;
    var value = 0;

    var svg = undefined;
    var arc = undefined;
    var scale = undefined;
    var ticks = undefined;
    var tickData = undefined;
    var pointer = undefined;

    var donut = d3.pie();

    function deg2rad(deg) {
        return deg * Math.PI / 180;
    }

    function newAngle(d) {
        var ratio = scale(d);
        var newAngle = config.minAngle + (ratio * range);
        return newAngle;
    }

    function configure(configuration) {
        var prop = undefined;
        for ( prop in configuration ) {
            config[prop] = configuration[prop];
        }

        range = config.maxAngle - config.minAngle;
        r = config.size / 2;
        pointerHeadLength = Math.round(r * config.pointerHeadLengthPercent);

        // a linear scale that maps domain values to a percent from 0..1
        scale = d3.scaleLinear()
            .range([0,1])
            .domain([config.minValue, config.maxValue]);

        ticks = scale.ticks(config.majorTicks);
        tickData = d3.range(config.majorTicks).map(function() {return 1/config.majorTicks;});

        arc = d3.arc()
            .innerRadius(r - config.ringWidth - config.ringInset)
            .outerRadius(r - config.ringInset)
            .startAngle(function(d, i) {
                var ratio = d * i;
                return deg2rad(config.minAngle + (ratio * range));
            })
            .endAngle(function(d, i) {
                var ratio = d * (i+1);
                return deg2rad(config.minAngle + (ratio * range));
            });
    }
    that.configure = configure;

    function centerTranslation() {
        return 'translate('+r +','+ r +')';
    }

    function isRendered() {
        return (svg !== undefined);
    }
    that.isRendered = isRendered;

    function render(newValue) {
        svg = d3.select(container)
            .append('svg:svg')
                .attr('class', 'gauge')
                .attr('width', config.clipWidth)
                .attr('height', config.clipHeight);

        var centerTx = centerTranslation();

        var arcs = svg.append('g')
                .attr('class', 'arc')
                .attr('transform', centerTx);

        arcs.selectAll('path')
                .data(tickData)
            .enter().append('path')
                .attr('fill', function(d, i) {
                    return config.arcColorFn(d * i);
                })
                .attr('d', arc);

        var lg = svg.append('g')
                .attr('class', 'label')
                .attr('transform', centerTx);
        lg.selectAll('text')
                .data(ticks)
            .enter().append('text')
                .attr('transform', function(d) {
                    var ratio = scale(d);
                    var newAngle = config.minAngle + (ratio * range);
                    return 'rotate(' +newAngle +') translate(0,' +(config.labelInset - r) +')';
                })
                .text(config.labelFormat);

        var lineData = [ [config.pointerWidth / 2, 0],
                        [0, -pointerHeadLength],
                        [-(config.pointerWidth / 2), 0],
                        [0, config.pointerTailLength],
                        [config.pointerWidth / 2, 0] ];
        var pointerLine = d3.line().curve(d3.curveLinear)
        var pg = svg.append('g').data([lineData])
                .attr('class', 'pointer')
                .attr('transform', centerTx);

        pointer = pg.append('path')
            .attr('d', pointerLine/*function(d) { return pointerLine(d) +'Z';}*/ )
            .attr('transform', 'rotate(' +config.minAngle +')');

        update(newValue === undefined ? 0 : newValue);
    }
    that.render = render;
    function update(newValue, newConfiguration) {
        if ( newConfiguration  !== undefined) {
            configure(newConfiguration);
        }
        var ratio = scale(newValue);
        var newAngle = config.minAngle + (ratio * range);
        pointer.transition()
            .duration(config.transitionMs)
            .ease(d3.easeElastic)
            .attr('transform', 'rotate(' +newAngle +')');
    }
    that.update = update;

    configure(configuration);

    return that;
};

    var powerGauge = gauge('#power-gauge', {
        size: 300,
        clipWidth: 300,
        clipHeight: 300,
        ringWidth: 60,
        maxValue: 10,
        transitionMs: 4000,
    });
    powerGauge.render();
  }
}

Body:
This is pretty ugly solution, but this is a reason why I personally don't like JS :) The problem is that you can not refer this from this context, as it kind of a callback.
You can do this trick:

var self = this;
var gauge = function (container, configuration) {
 ...
 self.gaugemap.configure = configure;
 ... // all other this. should be replaced by self.
}

and replace all references to this by self.

Working sample: https://stackblitz.com/edit/angular-tjk9sl?file=app/app.component.ts


问:
How can I extract all values of a particular attribute within elements inside a JSON array in MySQL?
I've the below data stored in a column of MySQL table which is of "json" data type (MySQL v5.7.9)

```<code>[{"id": "26", "title": "similar1", "score": "0.97"}, {"id": "27", "title": "similar2", "score": "0.87"}, {"id": "28", "title": "similar2", "score": "0.87"}]
</code>```

I need a MySQL query which will return me all the "title" values i.e. similar1, similar2 and similar3 and so on

答:
you can query like below

```<code>create table testTableforus (datapoint json);
insert into testTableforus
values
 ('{"id": "26", "title": "similar1", "score": "0.97"}'),
 ('{"id": "27", "title": "similar2", "score": "0.87"}'),
 ('{"id": "28", "title": "similar2", "score": "0.87"}');

 select datapoint->"$.title" from testTableforus;

drop table testTableforus;
</code>```

See working demo

Body:
I've the below data stored in a column of MySQL table which is of "json" data type (MySQL v5.7.9)

[{"id": "26", "title": "similar1", "score": "0.97"}, {"id": "27", "title": "similar2", "score": "0.87"}, {"id": "28", "title": "similar2", "score": "0.87"}]

I need a MySQL query which will return me all the "title" values i.e. similar1, similar2 and similar3 and so on

Body:
you can query like below

create table testTableforus (datapoint json);
insert into testTableforus
values
 ('{"id": "26", "title": "similar1", "score": "0.97"}'),
 ('{"id": "27", "title": "similar2", "score": "0.87"}'),
 ('{"id": "28", "title": "similar2", "score": "0.87"}');

 select datapoint->"$.title" from testTableforus;

drop table testTableforus;

See working demo


问:
How do find out the specific jsp technology from source code?
I am currently "assessing" a JSP application. I am no jsp expert, i have some experience in jsp with jsf development only.  I suspected that the technology of this application was in very old j2ee. Is there anyway to find out the detail version, technology, or platform from source code?  Or roughly how old of the jsp version is this application? For following is some the ui code. Please take a look, i find it that it's ridiculously complicated compared with current jsp and jsf platform.

```<code><jsp:include page='header.jsp'></jsp:include>
<%
  StringBuffer htmlBuffer = new StringBuffer();
 // get viewbean interface and cast it to view bean object accordingly
 com.nihb.mtrd.bean.AdminVB vb =
 (com.nihb.mtrd.bean.AdminVB)session.getAttribute(com.nihb.mtrd.bean.AbstractBean.VIEW_BEAN);
 //display message if there is any
 String message = vb.getMessage();
 if(message == null){
  message = new String("");
 }
 htmlBuffer.append("<p><b><font face='Verdana' size='1' color='#cc0000'>");
 htmlBuffer.append( message );
 htmlBuffer.append("</font></b></p>");
 htmlBuffer.append("<div align='center'>");
 htmlBuffer.append("<center>");
 htmlBuffer.append("<table border='3' cellspacing='0' style='border-collapse: collapse' width='800 ' cellpadding='0' id='AutoNumber7' height='9' bgcolor='#E8F3FF' bordercolor='#E8F3FF'>");
 htmlBuffer.append("<TR><td width='800' height='7' colspan='8'>");
 htmlBuffer.append("<br>");
 if( vb.getIndicator() != 0){
  htmlBuffer.append("<a href='MtrdHome.jsp?mysubmit=");
  htmlBuffer.append(com.nihb.mtrd.bean.AbstractBean.ACTION_HYPERLINK_CHANGE_PASSWORD);
  htmlBuffer.append("' >");
 }
 htmlBuffer.append("<b><font face='Verdana' size='2'>Change Password</font></b>");
 if( vb.getIndicator() != 0){
  htmlBuffer.append("</a>");
 }

 htmlBuffer.append("</td></TR>");
</code>```

thanks all!

Update: here are the top lines of my web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp">
    <!-- snip -->
</web-app>
</code>```

答:
What you're facing is indeed a bad design. All that HTML has got to be placed plain in the JSP file. Those beans has just to be prepared by a servlet or eventually <jsp:useBean> and accessed by EL (those ${} things). The flow control has got to be done by JSTL taglib.

As to the concrete question, the JSP version is basically definied in root declaration of web.xml which must indicate the Servlet version. The JSP version is coupled to the Servlet version. Here's an overview:

```
Servlet  JSP  J2EE/Java EE (releasedate)
3.0      2.2  Java EE 6 (Dec 2009)
2.5      2.1  Java EE 5 (May 2006)
2.4      2.0  J2EE 1.4 (Nov 2003)
2.3      1.2  J2EE 1.3 (Sep 2001)
```

Update: as per your edit, that's clearly Servlet 2.3. It's however good to know that you can redeclare it as Servlet 2.4 or higher whenever the servletcontainer in question supports it. If it is for example Tomcat 5.5, then you can redeclare it as Servlet 2.4 and utilize JSP 2.0. Or if it is for example Tomcat 6.0, then Servlet 2.5/JSP 2.1. Or Tomcat 7.0 with Servlet 3.0/JSP 2.2.

ContentLicense: CC BY-SA 2.5

Body:
I am currently "assessing" a JSP application. I am no jsp expert, i have some experience in jsp with jsf development only.  I suspected that the technology of this application was in very old j2ee. Is there anyway to find out the detail version, technology, or platform from source code?  Or roughly how old of the jsp version is this application? For following is some the ui code. Please take a look, i find it that it's ridiculously complicated compared with current jsp and jsf platform.

<jsp:include page='header.jsp'></jsp:include>
<%
  StringBuffer htmlBuffer = new StringBuffer();
 // get viewbean interface and cast it to view bean object accordingly
 com.nihb.mtrd.bean.AdminVB vb =
 (com.nihb.mtrd.bean.AdminVB)session.getAttribute(com.nihb.mtrd.bean.AbstractBean.VIEW_BEAN);
 //display message if there is any
 String message = vb.getMessage();
 if(message == null){
  message = new String("");
 }
 htmlBuffer.append("
");
 htmlBuffer.append( message );
 htmlBuffer.append("
");
 htmlBuffer.append("
");
 htmlBuffer.append("");
 htmlBuffer.append("
");
 htmlBuffer.append("
");
 htmlBuffer.append("
");
 if( vb.getIndicator() != 0){
  htmlBuffer.append("");
 }
 htmlBuffer.append("Change Password");
 if( vb.getIndicator() != 0){
  htmlBuffer.append("");
 }

 htmlBuffer.append("
");

thanks all!

Update: here are the top lines of my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp">

</web-app>

Body:
What you're facing is indeed a bad design. All that HTML has got to be placed plain in the JSP file. Those beans has just to be prepared by a servlet or eventually <jsp:useBean> and accessed by EL (those ${} things). The flow control has got to be done by JSTL taglib.

As to the concrete question, the JSP version is basically definied in root declaration of web.xml which must indicate the Servlet version. The JSP version is coupled to the Servlet version. Here's an overview:

Servlet  JSP  J2EE/Java EE (releasedate)
3.0      2.2  Java EE 6 (Dec 2009)
2.5      2.1  Java EE 5 (May 2006)
2.4      2.0  J2EE 1.4 (Nov 2003)
2.3      1.2  J2EE 1.3 (Sep 2001)

Update: as per your edit, that's clearly Servlet 2.3. It's however good to know that you can redeclare it as Servlet 2.4 or higher whenever the servletcontainer in question supports it. If it is for example Tomcat 5.5, then you can redeclare it as Servlet 2.4 and utilize JSP 2.0. Or if it is for example Tomcat 6.0, then Servlet 2.5/JSP 2.1. Or Tomcat 7.0 with Servlet 3.0/JSP 2.2.


问:
Is it possible to convert a connection object to an array in PHP
I'm wondering if it's possible to convert a database connection object to an array in PHP? I've been researching, it seems you can cast an object as an array, but it doesn't seem to work for a connection object. Here's my script:

```<code><?php

$dbHost="host";
$dbUser="user";
$dbPass="";
$dbName="root";

$dbConn = mysqli_connect($dbHost,$dbUser,$dbPass,$dbName);

$dbParts = (array) $dbConn;

for ($i=0;$i <=3; $i++){

echo $dbParts[$i];

}
?>
</code>```

Any help would be greatly appreciated!

**[EDIT]**Why I need to access the db connection as an array is because I need to be able to call certain urls in a script, based on what database I'm connected to, as each environment has a different database.

答:
Build your own array:

```<code>$db['localhost'] = array('host' => 'localhost',
                         'user' => 'root',
                         'pass' => '****',
                         'name' => 'database1');
</code>```

Then if needed add the connection to it:

```<code>$db['localhost']['conn'] = mysqli_connect($db['localhost']['host'],
                                          $db['localhost']['user'],
                                          $db['localhost']['pass'],
                                          $db['localhost']['name']);
</code>```

Other possibilities depending on your needs; define the database as the lookup key:

```<code>$db['database1'] = array('host' => 'localhost',
                         'user' => 'root',
                         'pass' => '****',
                         'name' => 'database1');
</code>```

Or define the environment:

```<code>$db['production'] = array('host' => 'localhost',
                          'user' => 'root',
                          'pass' => '****',
                          'name' => 'database1');
</code>```

Body:
I'm wondering if it's possible to convert a database connection object to an array in PHP? I've been researching, it seems you can cast an object as an array, but it doesn't seem to work for a connection object. Here's my script:

<?php

$dbHost="host";
$dbUser="user";
$dbPass="";
$dbName="root";

$dbConn = mysqli_connect($dbHost,$dbUser,$dbPass,$dbName);

$dbParts = (array) $dbConn;

for ($i=0;$i <=3; $i++){

echo $dbParts[$i];

}
?>

Any help would be greatly appreciated!

**[EDIT]**Why I need to access the db connection as an array is because I need to be able to call certain urls in a script, based on what database I'm connected to, as each environment has a different database.

Body:
Build your own array:

$db['localhost'] = array('host' => 'localhost',
                         'user' => 'root',
                         'pass' => '****',
                         'name' => 'database1');

Then if needed add the connection to it:

$db['localhost']['conn'] = mysqli_connect($db['localhost']['host'],
                                          $db['localhost']['user'],
                                          $db['localhost']['pass'],
                                          $db['localhost']['name']);

Other possibilities depending on your needs; define the database as the lookup key:

$db['database1'] = array('host' => 'localhost',
                         'user' => 'root',
                         'pass' => '****',
                         'name' => 'database1');

Or define the environment:

$db['production'] = array('host' => 'localhost',
                          'user' => 'root',
                          'pass' => '****',
                          'name' => 'database1');


问:
Trying to make @ tag for usernames
So I tried to use preg_replace to make @ to tag usernames in my php game.

Here is my code:

```<code>$find[13] = '@';
$replace[13] = '<a href="profil.php?username=$1">';

return preg_replace($find,$replace,$text);
</code>```

I only get this warning message:

```<code>Warning: preg_replace(): No ending delimiter '@' found in C:\xampp\htdocs\mafiagamev2\functions\bbcodes.php on line 61
</code>```

Any help?

答:
The problem is that preg_replace() requires a regular expression as search string. Most programming languages have a regex type, but not PHP. Here you define a pattern as string with delimiters enclosing the pattern. You can basically use most alphanumeric characters, including @, but the most commonly used is /. So preg_replace expects a pattern enclosed in delimiters and you provided only one character, which PHP interprets as the opening delimiter.

What you want to do is to replace all words that start with an @ with the link. A lot of this regex depends on how you validate usernames. For this example I am assuming you only allow upper- and lowercase alphanumeric characters, numbers, hyphen and underscore:

```<code>preg_replace('/(^|\s)@([\w\d-_]+)/g', '<a href="profil.php?username=$2">$2</a>')
</code>```

Get the explanation and try it out

Note that you might generate a lot of dead links. I suggest validating with JavaScript during the input or validating the usernames to replace against your database.

Title: Trying to make @ tag for usernames

Body:
So I tried to use preg_replace to make @ to tag usernames in my php game.

Here is my code:

$find[13] = '@';
$replace[13] = '';

return preg_replace($find,$replace,$text);

I only get this warning message:

Warning: preg_replace(): No ending delimiter '@' found in C:\xampp\htdocs\mafiagamev2\functions\bbcodes.php on line 61

Any help?

Body:
The problem is that preg_replace() requires a regular expression as search string. Most programming languages have a regex type, but not PHP. Here you define a pattern as string with delimiters enclosing the pattern. You can basically use most alphanumeric characters, including @, but the most commonly used is /. So preg_replace expects a pattern enclosed in delimiters and you provided only one character, which PHP interprets as the opening delimiter.

What you want to do is to replace all words that start with an @ with the link. A lot of this regex depends on how you validate usernames. For this example I am assuming you only allow upper- and lowercase alphanumeric characters, numbers, hyphen and underscore:

preg_replace('/(^|\s)@([\w\d-_]+)/g', '<a href="profil.php?username=$2">$2</a>')

Get the explanation and try it out

Note that you might generate a lot of dead links. I suggest validating with JavaScript during the input or validating the usernames to replace against your database.


问:
Get a DB-Record ID from a ListView item (LV with CursorAdapter and DB Helper)
I'm trying to build a simple app to serve as a students list.
MainActivity consists of ListView, EditText boxes and an 'add' Button.
My ListView connects with a custom CursorAdapter, and the app uses a custom SQLiteOpenHelper DB.

Upon clicking on the 'add' button ->

New record is inserted to DB ->

DB-Record-ID Of the newly inserted record is updated on the ListView item that was added (through bindView)

What I'm trying to do, is to pass the DB-Record ID of a ListView Item, when clicking on it, to a new activity, using Intent.putExtra, but not sure how to get the child-text-view in the ListView Item that was clicked? (In onItemClick, in order to get its text and pass it with the new Intent to the new activity)

PURPOSE Is to have the DB-Record-ID in the new activity, because the new activity allows the user to UPDATE the grade param in the record (Thus, I need the DB-Record-ID in order to update it on my DB as well upon update)

Can someone suggest a solution? Here's the needed code -

MainActivity:

```<code>public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    /* Our DB model to store student objects */
    private SqlDbHelper mDB;

    /* Custom SQL-Adapter to connect our SQL DB to the ListView */
    private SQLAdapter mAdapter;

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

        /* Init fields & needed views */
        mDB = new SqlDbHelper(getApplicationContext());
        mAdapter = new SQLAdapter(getApplicationContext(), mDB.getAllRows(), false);
        final ListView lvStudents = findViewById(R.id.lv_students);
        final EditText etName = findViewById(R.id.et_name);
        final EditText etGrade = findViewById(R.id.et_grade);

        /* Listen to ADD BUTTON clicks */
        findViewById(R.id.button_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertNewRecord(etName.getText().toString(), etGrade.getText().toString());
                etName.setText("");
                etGrade.setText("");
            }
        });

        /* Set adapter to LV, Listen to list item clicks */
        lvStudents.setAdapter(mAdapter);
        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);

                // ????????????
                // listItemIntent.putExtra("_ID",
                //       "Get textview.text containing the param in the CLICKED list item);

                startActivity(listItemIntent);
            }
        });
    }

    /**
     * Creates a list item for a student name + grade
     * @param name
     * @param grade
     * @return the new student id in the DB
     */
    private long insertNewRecord(final String name, final String grade) {
        int gradeInt = -1;
        try {
            gradeInt = Integer.parseInt(grade);
        } catch (NumberFormatException e) {
            Log.w(TAG, "Invalid grade entered: " + grade);
        }

        /* Add the new student to the DB */
        final long id = mDB.insertNewStudent(name, gradeInt);
        mAdapter.changeCursor(mDB.getAllRows());
        return id;
    }
}
</code>```

Not sure if needed, but just in case -

SQLAdapter:

```<code>final class SQLAdapter extends CursorAdapter {
    private LayoutInflater mInflater;

    public SQLAdapter(Context context, Cursor c, boolean autoRequery) {
        super(context, c, autoRequery);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
        return mInflater.inflate(R.layout.lv_line, viewGroup, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        final String name = cursor.getString(cursor.getColumnIndex(SqlDbHelper.KEY_NAME));
        final int grade = cursor.getInt(cursor.getColumnIndex(SqlDbHelper.KEY_GRADE));
        final long id = cursor.getLong(cursor.getColumnIndex(SqlDbHelper.KEY_ID));

        view.findViewById(R.id.ll_line).setBackgroundColor(Color.RED));
        ((TextView)view.findViewById(R.id.tv_name)).setText(name);
        ((TextView)view.findViewById(R.id.tv_grade)).setText(String.valueOf(grade));
        ((TextView)view.findViewById(R.id.tv_id)).setText(String.valueOf(id));
    }
}
</code>```

SqlDbHelper:

```<code>final class SqlDbHelper extends SQLiteOpenHelper {
    private static final String TAG = "SqlDbHelper";

    /* Database version */
    public static final int VERSION = 1;

    /* Relevant string names, keys represent columns */
    public static final String DB_NAME = "StudentsDB";
    public static final String TABLE_NAME = "students";
    public static final String KEY_ID = "_id";
    public static final String KEY_NAME = "Name";
    public static final String KEY_GRADE = "Grade";

    public SqlDbHelper(Context context) {
        super(context, DB_NAME, null, VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        /* Create sql command to create new table */
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE " + TABLE_NAME + " (")
                .append(KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,")
                .append(KEY_NAME + " TEXT,")
                .append(KEY_GRADE + " INT")
                .append(")");

        /* Execute our sql command:
         * CREATE TABLE StudentsDB(_id INTEGER PRIMARY KEY, Name TEXT, Grade INT) */
        Log.d(TAG, "Query to form table: " + sql.toString());
        sqLiteDatabase.execSQL(sql.toString());
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}

    public long insertNewStudent(final String name, final int grade) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_GRADE, grade);
        return getWritableDatabase().insert(TABLE_NAME, null, cv);
    }

    public Cursor getAllRows() {
        return getReadableDatabase().
                rawQuery("SELECT * FROM " + TABLE_NAME, null);
    }
}
</code>```

答:
The 4th parameter long l passed to onItemClick, for a CursorAdapter, is the id (i.e _id as per the cursor).

So just do listItemIntent.putExtra("_ID",l);

e.g. :-

```<code>        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);
                listItemIntent.putExtra("_ID",l); // ID as per _id in the cursor.
                startActivity(listItemIntent);
            }
        });
</code>```

Edit after comment :-

Thanks, and for the sake of the question - how to get any other
  text-view text from the specific list item, in the onItemClick? will
  view.findViewById(id_of_the_text_box) will get me the correct text?

Yes, if you want to access a a view from the clicked item then use (assuming TextView, otherwsie whatever is appropriate for the View) :-

```<code>                view.findViewById(R.id.your_view_id).getText().toString;
</code>```

So applying this you could have:-

```<code>        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);
                listItemIntent.putExtra("_ID",l); // ID as per _id in the cursor.
                listItemIntent.putExtra("_IDFROMVIEW,
                    view.findViewByID(R.id.tv_id).getText().toString();
                startActivity(listItemIntent);
            }
        });
</code>```

i.e. it finds the View within the clicked Item's list of views (a specific subset/branch of the ListView's (aka adapterView) list of views).

Body:
I'm trying to build a simple app to serve as a students list.
MainActivity consists of ListView, EditText boxes and an 'add' Button.
My ListView connects with a custom CursorAdapter, and the app uses a custom SQLiteOpenHelper DB.

Upon clicking on the 'add' button ->

New record is inserted to DB ->

DB-Record-ID Of the newly inserted record is updated on the ListView item that was added (through bindView)

What I'm trying to do, is to pass the DB-Record ID of a ListView Item, when clicking on it, to a new activity, using Intent.putExtra, but not sure how to get the child-text-view in the ListView Item that was clicked? (In onItemClick, in order to get its text and pass it with the new Intent to the new activity)

PURPOSE Is to have the DB-Record-ID in the new activity, because the new activity allows the user to UPDATE the grade param in the record (Thus, I need the DB-Record-ID in order to update it on my DB as well upon update)

Can someone suggest a solution? Here's the needed code -

MainActivity:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    /* Our DB model to store student objects */
    private SqlDbHelper mDB;

    /* Custom SQL-Adapter to connect our SQL DB to the ListView */
    private SQLAdapter mAdapter;

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

        /* Init fields & needed views */
        mDB = new SqlDbHelper(getApplicationContext());
        mAdapter = new SQLAdapter(getApplicationContext(), mDB.getAllRows(), false);
        final ListView lvStudents = findViewById(R.id.lv_students);
        final EditText etName = findViewById(R.id.et_name);
        final EditText etGrade = findViewById(R.id.et_grade);

        /* Listen to ADD BUTTON clicks */
        findViewById(R.id.button_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertNewRecord(etName.getText().toString(), etGrade.getText().toString());
                etName.setText("");
                etGrade.setText("");
            }
        });

        /* Set adapter to LV, Listen to list item clicks */
        lvStudents.setAdapter(mAdapter);
        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);

                // ????????????
                // listItemIntent.putExtra("_ID",
                //       "Get textview.text containing the param in the CLICKED list item);

                startActivity(listItemIntent);
            }
        });
    }

    /**
     * Creates a list item for a student name + grade
     * @param name
     * @param grade
     * @return the new student id in the DB
     */
    private long insertNewRecord(final String name, final String grade) {
        int gradeInt = -1;
        try {
            gradeInt = Integer.parseInt(grade);
        } catch (NumberFormatException e) {
            Log.w(TAG, "Invalid grade entered: " + grade);
        }

        /* Add the new student to the DB */
        final long id = mDB.insertNewStudent(name, gradeInt);
        mAdapter.changeCursor(mDB.getAllRows());
        return id;
    }
}

Not sure if needed, but just in case -

SQLAdapter:

final class SQLAdapter extends CursorAdapter {
    private LayoutInflater mInflater;

    public SQLAdapter(Context context, Cursor c, boolean autoRequery) {
        super(context, c, autoRequery);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
        return mInflater.inflate(R.layout.lv_line, viewGroup, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        final String name = cursor.getString(cursor.getColumnIndex(SqlDbHelper.KEY_NAME));
        final int grade = cursor.getInt(cursor.getColumnIndex(SqlDbHelper.KEY_GRADE));
        final long id = cursor.getLong(cursor.getColumnIndex(SqlDbHelper.KEY_ID));

        view.findViewById(R.id.ll_line).setBackgroundColor(Color.RED));
        ((TextView)view.findViewById(R.id.tv_name)).setText(name);
        ((TextView)view.findViewById(R.id.tv_grade)).setText(String.valueOf(grade));
        ((TextView)view.findViewById(R.id.tv_id)).setText(String.valueOf(id));
    }
}

SqlDbHelper:

final class SqlDbHelper extends SQLiteOpenHelper {
    private static final String TAG = "SqlDbHelper";

    /* Database version */
    public static final int VERSION = 1;

    /* Relevant string names, keys represent columns */
    public static final String DB_NAME = "StudentsDB";
    public static final String TABLE_NAME = "students";
    public static final String KEY_ID = "_id";
    public static final String KEY_NAME = "Name";
    public static final String KEY_GRADE = "Grade";

    public SqlDbHelper(Context context) {
        super(context, DB_NAME, null, VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        /* Create sql command to create new table */
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE " + TABLE_NAME + " (")
                .append(KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,")
                .append(KEY_NAME + " TEXT,")
                .append(KEY_GRADE + " INT")
                .append(")");

        /* Execute our sql command:
         * CREATE TABLE StudentsDB(_id INTEGER PRIMARY KEY, Name TEXT, Grade INT) */
        Log.d(TAG, "Query to form table: " + sql.toString());
        sqLiteDatabase.execSQL(sql.toString());
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}

    public long insertNewStudent(final String name, final int grade) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_GRADE, grade);
        return getWritableDatabase().insert(TABLE_NAME, null, cv);
    }

    public Cursor getAllRows() {
        return getReadableDatabase().
                rawQuery("SELECT * FROM " + TABLE_NAME, null);
    }
}

Body:
The 4th parameter long l passed to onItemClick, for a CursorAdapter, is the id (i.e _id as per the cursor).

So just do listItemIntent.putExtra("_ID",l);

e.g. :-

        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);
                listItemIntent.putExtra("_ID",l); // ID as per _id in the cursor.
                startActivity(listItemIntent);
            }
        });

Edit after comment :-

Thanks, and for the sake of the question - how to get any other
  text-view text from the specific list item, in the onItemClick? will
  view.findViewById(id_of_the_text_box) will get me the correct text?

Yes, if you want to access a a view from the clicked item then use (assuming TextView, otherwsie whatever is appropriate for the View) :-

                view.findViewById(R.id.your_view_id).getText().toString;

So applying this you could have:-

        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);
                listItemIntent.putExtra("_ID",l); // ID as per _id in the cursor.
                listItemIntent.putExtra("_IDFROMVIEW,
                    view.findViewByID(R.id.tv_id).getText().toString();
                startActivity(listItemIntent);
            }
        });

i.e. it finds the View within the clicked Item's list of views (a specific subset/branch of the ListView's (aka adapterView) list of views).


问:
Xamarin Android - Handling StringBuilders
I am using a string builder to more effectively handle my information(by choice), where on option switched on it appends it to the list.
Im doing this every second(at minimum), and im wondering, is it better to use StringBuilder.Clear(); or StringBuilder.Lenght = 0;

I am not sure which of these two has a better memory management, and im hoping someone here knows. Or is there even a difference.

答:
Clear() was introduced later (since 4.0) than Length. That's the main difference. If you don't consider to support a lower .NET version, go for Clear(). Performancewise Length = 0 should be faster, because Clear() calls it intern, but it also should make no big difference, especially if you call it only once per second. Avoid Premature Optimization. I would go for Clear(), because it is more readable and only use Length = 0 in a performance critical scenario, where I ran out of other options.

This is the source implementation of Microsoft:

```<code>// Convenience method for sb.Length=0;
public StringBuilder Clear() {
    this.Length = 0;
    return this;
}
</code>```

https://referencesource.microsoft.com/#mscorlib/system/text/stringbuilder.cs

Mono is using the same implementation.

https://github.com/mono/mono/blob/master/mcs/class/referencesource/mscorlib/system/text/stringbuilder.cs

Body:
Clear() was introduced later (since 4.0) than Length. That's the main difference. If you don't consider to support a lower .NET version, go for Clear(). Performancewise Length = 0 should be faster, because Clear() calls it intern, but it also should make no big difference, especially if you call it only once per second. Avoid Premature Optimization. I would go for Clear(), because it is more readable and only use Length = 0 in a performance critical scenario, where I ran out of other options.

This is the source implementation of Microsoft:

// Convenience method for sb.Length=0;
public StringBuilder Clear() {
    this.Length = 0;
    return this;
}

https://referencesource.microsoft.com/#mscorlib/system/text/stringbuilder.cs

Mono is using the same implementation.

https://github.com/mono/mono/blob/master/mcs/class/referencesource/mscorlib/system/text/stringbuilder.cs


问:
zappa deployment: deploy to same api gateway with different stages
when I define a new stage in zappa_settings.json a new api-gateway-backend gets created. What I would need is the same gateway but a different stage, ie. /prod instead of /dev.
Is there any way of accomplishing this in zappa?</p>

答: Zappa does not currently support that model.</p>


答:
Use JSON_EXTRACT().

```<code>mysql> create table t ( j json );

mysql> insert into t set j = '[{"id": "26", "title": "similar1", "score": "0.97"}, {"id": "27", "title": "similar2", "score": "0.87"}, {"id": "28", "title": "similar2", "score": "0.87"}]';

mysql> select json_extract(j, '$[*].title') from t;
+--------------------------------------+
| json_extract(j, '$[*].title')        |
+--------------------------------------+
| ["similar1", "similar2", "similar2"] |
+--------------------------------------+
</code>```

If you want to use JSON data in MySQL, you should read the docs on Functions that Search JSON Values, and learn to use the JSON search expressions.

Title: How can I extract all values of a particular attribute within elements inside a JSON array in MySQL?

Body:
Use JSON_EXTRACT().

mysql> create table t ( j json );

mysql> insert into t set j = '[{"id": "26", "title": "similar1", "score": "0.97"}, {"id": "27", "title": "similar2", "score": "0.87"}, {"id": "28", "title": "similar2", "score": "0.87"}]';

mysql> select json_extract(j, '$[*].title') from t;
+--------------------------------------+
| json_extract(j, '$[*].title')        |
+--------------------------------------+
| ["similar1", "similar2", "similar2"] |
+--------------------------------------+

If you want to use JSON data in MySQL, you should read the docs on Functions that Search JSON Values, and learn to use the JSON search expressions.


问:
How to use delta trigger in flink?
I want to use the deltatrigger in apache flink (flink 1.3) but I have some trouble with this code :

```<code>.trigger(DeltaTrigger.of(100, new DeltaFunction[uniqStruct] {
    override def getDelta(oldFp: uniqStruct, newFp: uniqStruct): Double = newFp.time - oldFp.time
  }, TypeInformation[uniqStruct]))
</code>```

And I have this error:

```<code>error: object org.apache.flink.api.common.typeinfo.TypeInformation is not a value [ERROR] }, TypeInformation[uniqStruct]))
</code>```

I don't understand why DeltaTrigger need  TypeSerializer[T]
and I don't know what to do to remove this error.

Thanks a lot everyone.

答:
I would read into this a bit https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/types_serialization.html sounds like you can create a serializer using typeInfo.createSerializer(config) on your type info. Note what you're passing in currently is a type itself and NOT the type info which is why you're getting the error you are.

You would need to do something more like

```<code>val uniqStructTypeInfo: TypeInformation[uniqStruct] = createTypeInformation[uniqStruct]
val uniqStrictTypeSerializer = typeInfo.createSerializer(config)
</code>```

To quote the page above regarding the config param you need to pass to create serializer

The config parameter is of type ExecutionConfig and holds the
  information about the program’s registered custom serializers. Where
  ever possibly, try to pass the programs proper ExecutionConfig. You
  can usually obtain it from DataStream or DataSet via calling
  getExecutionConfig(). Inside functions (like MapFunction), you can get
  it by making the function a Rich Function and calling
  getRuntimeContext().getExecutionConfig().

Title: How to use delta trigger in flink?

Body:
I want to use the deltatrigger in apache flink (flink 1.3) but I have some trouble with this code :

.trigger(DeltaTrigger.of(100, new DeltaFunction[uniqStruct] {
    override def getDelta(oldFp: uniqStruct, newFp: uniqStruct): Double = newFp.time - oldFp.time
  }, TypeInformation[uniqStruct]))

And I have this error:

error: object org.apache.flink.api.common.typeinfo.TypeInformation is not a value [ERROR] }, TypeInformation[uniqStruct]))

I don't understand why DeltaTrigger need  TypeSerializer[T]
and I don't know what to do to remove this error.

Thanks a lot everyone.

Body:
I would read into this a bit https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/types_serialization.html sounds like you can create a serializer using typeInfo.createSerializer(config) on your type info. Note what you're passing in currently is a type itself and NOT the type info which is why you're getting the error you are.

You would need to do something more like

val uniqStructTypeInfo: TypeInformation[uniqStruct] = createTypeInformation[uniqStruct]
val uniqStrictTypeSerializer = typeInfo.createSerializer(config)

To quote the page above regarding the config param you need to pass to create serializer

The config parameter is of type ExecutionConfig and holds the
  information about the program’s registered custom serializers. Where
  ever possibly, try to pass the programs proper ExecutionConfig. You
  can usually obtain it from DataStream or DataSet via calling
  getExecutionConfig(). Inside functions (like MapFunction), you can get
  it by making the function a Rich Function and calling
  getRuntimeContext().getExecutionConfig().


问:
Is it necessary to get a a new Datasource from JNDI for every connection?
Looking at answers from high reputation users such as this it seems that it's appropriate to get a new DataSource object by querying the JNDI naming service on every single connection request. E.g. with code like the following (adapted from the linked answer for more brevity):

```<code>public class ConnectionManager{
       public static Connection getConnection() throws NamingException {
            Context initContext  = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            DataSource dataSource = (DataSource)envContext.lookup("jdbc/test");
            return dataSource.getConnection();
       }
}
</code>```

Is this really, the suggested / idiomatic way? In some of my own "ConnectionManager" utilty classes I used to keep a reference to the DataSource object as an instance variable. Nothing wrong came out of it except when the JBoss administrator disabled and enabled the connection pool from the admin console and then my code was getting errors like the following:

```<code>java.sql.SQLException: javax.resource.ResourceException: IJ000451: The connection manager is shutdown
</code>```

So, is it an anti-pattern to keep around instances of DataSource objects in JDBC?

答:
A DataSource object can be cached and is thread-safe, although JNDI ought to be well-enough optimized that getting the DS out of JNDI every request is negligible (the same instance will be handed back from JNDI).

If you're working in a Java EE environment for example, it's spec standard to be able to inject a DataSource at the class level, such as:

```<code>public class MyServlet extends HttpServlet {

  @Resource
  DataSource ds;

  public void processRequest() {
    try(Connection con = ds.getConnection()) {
      // ...
    }
  }

}
</code>```

Also, it's completely safe to share DataSource objects across multiple threads.  On the other hand, sharing Connection objects across multiple threads is a big mistake, because those are NOT threadsafe per spec.

Body:
Looking at answers from high reputation users such as this it seems that it's appropriate to get a new DataSource object by querying the JNDI naming service on every single connection request. E.g. with code like the following (adapted from the linked answer for more brevity):

public class ConnectionManager{
       public static Connection getConnection() throws NamingException {
            Context initContext  = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            DataSource dataSource = (DataSource)envContext.lookup("jdbc/test");
            return dataSource.getConnection();
       }
}

Is this really, the suggested / idiomatic way? In some of my own "ConnectionManager" utilty classes I used to keep a reference to the DataSource object as an instance variable. Nothing wrong came out of it except when the JBoss administrator disabled and enabled the connection pool from the admin console and then my code was getting errors like the following:

java.sql.SQLException: javax.resource.ResourceException: IJ000451: The connection manager is shutdown

So, is it an anti-pattern to keep around instances of DataSource objects in JDBC?

Body:
A DataSource object can be cached and is thread-safe, although JNDI ought to be well-enough optimized that getting the DS out of JNDI every request is negligible (the same instance will be handed back from JNDI).

If you're working in a Java EE environment for example, it's spec standard to be able to inject a DataSource at the class level, such as:

public class MyServlet extends HttpServlet {

  @Resource
  DataSource ds;

  public void processRequest() {
    try(Connection con = ds.getConnection()) {
      // ...
    }
  }

}

Also, it's completely safe to share DataSource objects across multiple threads.  On the other hand, sharing Connection objects across multiple threads is a big mistake, because those are NOT threadsafe per spec.


问:
Subscribe in Angular2 doesn't work
I have a question about subscribe in Angular2, please, help me...

I have two functions, first function return the value and the second function has to use it.

Here is my example

This is the first function, everything is ok and works works, and it returns this.mapCenter, this value I need later

```<code>   prevId () {
     let name, id, lat, lng;
     this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {

        if (this.previousUrl !== undefined) {

          this.clickedMarker = this.previousUrl.substring(10);

          for (let i = 0; i < this.data.length; i++) {
            if(this.data[i].code === this.clickedMarker) {
              id = this.data[i].code;
              name = this.data[i].displayName;
              lat = parseFloat(this.data[i].lat);
              lng = parseFloat(this.data[i].lng);
              this.mapCenter = L.latLng([lat, lng]);
            }
          }
          // Open up the popup, when user comes back
          let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
          let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
          myMarker.bindPopup(mark).openPopup();
        } else {
          console.log('not yet');
          this.mapCenter = L.latLng([48.145, 11.58]);
        }
        this.previousUrl = (e as NavigationEnd).url;
        return this.mapCenter;

      });
  }
</code>```

Now I need to use the value this. mapCenter of this function as a parameter in second function.

```<code>this.mapInitialize(this.mapCenter);
</code>```

The both functions are in the ngOnInit

```<code>  ngOnInit() {
    this.prevId();

    this.mapInitialize(this.mapCenter);
  }
</code>```

I tried something like this.prevId().subscribe, but I get error subscribe doesn't exist on type void ...

UPD: I can't assign second function in the first function. I need the second function later and if I assign it inside another function, everything brakes

答:
you first method must be as a Observable method. like bellow:

```<code>public getByProvinceId(provinceId: number): Observable<CityModel[]> {

    const url = this.urlBase + `city/province/${provinceId}`;
    return this.http.get(url, this.options)
      .map((response: Response) => {
        const retVal = <CityModel[]>response.json();
        return retVal;
      });
  }
</code>```

and (for example) in your second method use subscribe:

```<code>this.getByProvinceId(this.ProvinceId)
            .subscribe(result => {
                if (result.succeeded == true) {
                    this.regCities = result.returnValue;
                }
                else {
                    this.messageBox.ShowError(result.responseMessage);
                }
            });
</code>```

Title: Subscribe in Angular2 doesn't work

Body:
I have a question about subscribe in Angular2, please, help me...

I have two functions, first function return the value and the second function has to use it.

Here is my example

This is the first function, everything is ok and works works, and it returns this.mapCenter, this value I need later

   prevId () {
     let name, id, lat, lng;
     this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {

        if (this.previousUrl !== undefined) {

          this.clickedMarker = this.previousUrl.substring(10);

          for (let i = 0; i < this.data.length; i++) {
            if(this.data[i].code === this.clickedMarker) {
              id = this.data[i].code;
              name = this.data[i].displayName;
              lat = parseFloat(this.data[i].lat);
              lng = parseFloat(this.data[i].lng);
              this.mapCenter = L.latLng([lat, lng]);
            }
          }
          // Open up the popup, when user comes back
          let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
          let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
          myMarker.bindPopup(mark).openPopup();
        } else {
          console.log('not yet');
          this.mapCenter = L.latLng([48.145, 11.58]);
        }
        this.previousUrl = (e as NavigationEnd).url;
        return this.mapCenter;

      });
  }

Now I need to use the value this. mapCenter of this function as a parameter in second function.

this.mapInitialize(this.mapCenter);

The both functions are in the ngOnInit

  ngOnInit() {
    this.prevId();

    this.mapInitialize(this.mapCenter);
  }

I tried something like this.prevId().subscribe, but I get error subscribe doesn't exist on type void ...

UPD: I can't assign second function in the first function. I need the second function later and if I assign it inside another function, everything brakes

Body:
you first method must be as a Observable method. like bellow:

public getByProvinceId(provinceId: number): Observable<CityModel[]> {

    const url = this.urlBase + `city/province/${provinceId}`;
    return this.http.get(url, this.options)
      .map((response: Response) => {
        const retVal = <CityModel[]>response.json();
        return retVal;
      });
  }

and (for example) in your second method use subscribe:

this.getByProvinceId(this.ProvinceId)
            .subscribe(result => {
                if (result.succeeded == true) {
                    this.regCities = result.returnValue;
                }
                else {
                    this.messageBox.ShowError(result.responseMessage);
                }
            });


问:
Getting the raw value of a c++ ofstream's put pointer (for storage)
To get the position of a c++ ofstream's output pointer, I call ostream::tellp() which returns a streampos object.  I want to store this value, which may be quite large, into a binary file.

However, I cannot find a way to get the raw value of the output pointer's position from this streampos object.  If I were not worried about this value being very large, I would simply convert it to an integer; however, my file may be a few gigabytes in size.  Does anyone have any ideas for this?

Thanks!

答:
streampos is a typedef for some (typically unsigned) integer type. Despite the position in the file often being called the "put pointer", there's not actually a pointer value to obtain.

On most recent compilers, streampos is going to compile to a native 64 bit integer, (i.e. unsigned long long, or unsigned __int64 on msvc++, or uint64_t on GCC), which means you shouldn't have to worry so long as you leave things in terms of streampos values.


问:
Excel - checking for duplicates from a list of values within two columns of different groups of IDs
I am trying to find a way to remove duplicates from a list of values between a column of "have and not have" and includes everything from the original list. I need this to repeat for each set of IDs.

This list would be: A1, B1, C1, D1, E1.

An example of the raw data would be:

```<code>UniqueID | Have | Not Have
---------------------------
Z12345   | A1   | B1
Z12345   | A1   | C1
Z12345   | A1   | D1
Z12345   | A1   | E1
Y12345   | A1   | D1
Y12345   | B1   | E1
Y12345   | C1   | D1
</code>```

The output I'm trying to get is:

```<code>UniqueID | Have | Not Have
---------------------------
Z12345   | A1   | B1
Z12345   |      | C1
Z12345   |      | D1
Z12345   |      | E1
Y12345   | A1   | D1
Y12345   | B1   | E1
Y12345   | C1   |
</code>```

I can't think of any way to approach this. I thought maybe running If statements to check if the IDs are matching and then run an if statement to remove the duplicates, but I couldn't figure out how to run it separately for each set of IDs. Any help or direction on how to approach this would be really appreciated!

答:
I would write a VBA routine to tackle this. It can be done with formulas (which I will post), but I believe it's more straightforward with VBA.

Assuming the list is sorted by UniqueID, you can trying the following code and modify as needed. To use it, first select the range of UniqueIDs before you run the macro. It will output the deduped values next to the original set.

```<code>Sub dedupe()
     Dim strList As String
    Dim strCurId As String
    Dim rng As Range

    curId = Selection(1, 1)
    For Each rng In Selection
        If curId <> rng Then
            strList = ""
            curId = rng
        End If
        rng.Offset(0, 4) = rng
        If InStr(1, strList, rng.Offset(0, 1)) = 0 Then
            rng.Offset(0, 5) = rng.Offset(0, 1)
            strList = strList & "|" & rng.Offset(0, 1)
        End If
        If InStr(1, strList, rng.Offset(0, 2)) = 0 Then
            rng.Offset(0, 6) = rng.Offset(0, 2)
            strList = strList & "|" & rng.Offset(0, 2)
        End If
    Next
End Sub
</code>```

Body:
I am trying to find a way to remove duplicates from a list of values between a column of "have and not have" and includes everything from the original list. I need this to repeat for each set of IDs.

This list would be: A1, B1, C1, D1, E1.

An example of the raw data would be:

UniqueID | Have | Not Have
---------------------------
Z12345   | A1   | B1
Z12345   | A1   | C1
Z12345   | A1   | D1
Z12345   | A1   | E1
Y12345   | A1   | D1
Y12345   | B1   | E1
Y12345   | C1   | D1

The output I'm trying to get is:

UniqueID | Have | Not Have
---------------------------
Z12345   | A1   | B1
Z12345   |      | C1
Z12345   |      | D1
Z12345   |      | E1
Y12345   | A1   | D1
Y12345   | B1   | E1
Y12345   | C1   |

I can't think of any way to approach this. I thought maybe running If statements to check if the IDs are matching and then run an if statement to remove the duplicates, but I couldn't figure out how to run it separately for each set of IDs. Any help or direction on how to approach this would be really appreciated!

Body:
I would write a VBA routine to tackle this. It can be done with formulas (which I will post), but I believe it's more straightforward with VBA.

Assuming the list is sorted by UniqueID, you can trying the following code and modify as needed. To use it, first select the range of UniqueIDs before you run the macro. It will output the deduped values next to the original set.

Sub dedupe()
     Dim strList As String
    Dim strCurId As String
    Dim rng As Range

    curId = Selection(1, 1)
    For Each rng In Selection
        If curId <> rng Then
            strList = ""
            curId = rng
        End If
        rng.Offset(0, 4) = rng
        If InStr(1, strList, rng.Offset(0, 1)) = 0 Then
            rng.Offset(0, 5) = rng.Offset(0, 1)
            strList = strList & "|" & rng.Offset(0, 1)
        End If
        If InStr(1, strList, rng.Offset(0, 2)) = 0 Then
            rng.Offset(0, 6) = rng.Offset(0, 2)
            strList = strList & "|" & rng.Offset(0, 2)
        End If
    Next
End Sub