问:
Where is the documentation for the return values of the IBM Weather Service?
I do not find a full documentation of all return values of the Weather Service REST Api calls

The is only the JSON description like https://twcservice.mybluemix.net/rest-api/
But was does each value mean?

For example what is:
"rh":  ?
"wspd": ?
"wdir": ?

There is a getting started https://new-console.ng.bluemix.net/docs/services/Weather/index.html?pos=2 , but I do not find the full documentation.

Here is a example for the JSON ...

```<code> "forecasts": [
    {
      "class": "string",
      "expire_time_gmt": 0,
      "fcst_valid": 0,
      "fcst_valid_local": "2016-09-05",
      "temp": 0,
      "icon_extd": 0,
      "icon_code": 0,
      "dow": "string",
      "phrase_12char": "string",
      "phrase_22char": "string",
      "phrase_32char": "string",
      "pop": 0,
      "precip_type": "string",
      "rh": 0,
      "wspd": 0,
      "wdir": 0,
      "wdir_cardinal": "string",
      "gust": 0,
      "mslp": 0,
      "num": 0,
      "day_ind": "string",
      "dewpt": 0,
      "hi": 0,
      "wc": 0,
      "feels_like": 0,
      "subphrase_pt1": "string",
      "subphrase_pt2": "string",
      "subphrase_pt3": "string",
      "qpf": 0,
      "snow_qpf": 0,
      "clds": 0,
      "uv_index_raw": 0,
      "uv_index": 0,
      "uv_desc": "string",
      "uv_warning": 0,
      "golf_index": 0,
      "golf_category": "string",
      "severity": 0
    }
</code>```

答: Pretty complete documentation of all the return values can be found here: https://www.worldcommunitygrid.org/lt/images/climate/The_Weather_Company_APIs.pdf</p>

Body:
I do not find a full documentation of all return values of the Weather Service REST Api calls

The is only the JSON description like https://twcservice.mybluemix.net/rest-api/
But was does each value mean?

For example what is:
"rh":  ?
"wspd": ?
"wdir": ?

There is a getting started https://new-console.ng.bluemix.net/docs/services/Weather/index.html?pos=2 , but I do not find the full documentation.

Here is a example for the JSON ...

 "forecasts": [
    {
      "class": "string",
      "expire_time_gmt": 0,
      "fcst_valid": 0,
      "fcst_valid_local": "2016-09-05",
      "temp": 0,
      "icon_extd": 0,
      "icon_code": 0,
      "dow": "string",
      "phrase_12char": "string",
      "phrase_22char": "string",
      "phrase_32char": "string",
      "pop": 0,
      "precip_type": "string",
      "rh": 0,
      "wspd": 0,
      "wdir": 0,
      "wdir_cardinal": "string",
      "gust": 0,
      "mslp": 0,
      "num": 0,
      "day_ind": "string",
      "dewpt": 0,
      "hi": 0,
      "wc": 0,
      "feels_like": 0,
      "subphrase_pt1": "string",
      "subphrase_pt2": "string",
      "subphrase_pt3": "string",
      "qpf": 0,
      "snow_qpf": 0,
      "clds": 0,
      "uv_index_raw": 0,
      "uv_index": 0,
      "uv_desc": "string",
      "uv_warning": 0,
      "golf_index": 0,
      "golf_category": "string",
      "severity": 0
    }


来源: stackexchange

问:
How to Detect the Vowels and Consonants in my program
```<code>    String text;
    System.out.print ("Enter a String:");
    text = console.nextLine();

    int spaces = 0;
    int consonants = 0;
    int vowelcount = 0 ;

    for (int index = 0; index < text.length(); index++) {
    char letters = text.charAt(index);

    if (letters == 'A' || letters == 'a')
        vowelcount++;

    else if (letters != 'a' && letters != 'e' && letters != 'i' && letters != 'o' && letters != 'u')
        consonants++;

    }

        System.out.println ("Vowels:" + vowelcount  + "\nConsonants :" + consonants + "\nSpaces : " + spaces);
</code>```

Sample Output
String: Hannah
Last Portion of Output
Vowels Detected: a a
Consonants Detected: h n n h

答:
I needed to do this function using 'loops for', follow the example in JavaScript:</p>

```<code>const defaultListVowels = ['a', 'e', 'i', 'o', 'u'];

function isVowel(value) {
    return defaultListVowels.indexOf(value) >= 0;
}

function printLetters(values) {
    console.log(values + '\r');
}

function vowelsAndConsonants(s) {
    var consonants = [];
    var vowels = [];

    for (let letter of s) {
        if (isVowel(letter)) {
            vowels.push(letter);
        } else {
            consonants.push(letter);
        }
    }

    vowels.forEach(printLetters);
    consonants.forEach(printLetters);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
    String text;
    System.out.print ("Enter a String:");
    text = console.nextLine();

    int spaces = 0;
    int consonants = 0;
    int vowelcount = 0 ;

    for (int index = 0; index < text.length(); index++) {
    char letters = text.charAt(index);

    if (letters == 'A' || letters == 'a')
        vowelcount++;

    else if (letters != 'a' && letters != 'e' && letters != 'i' && letters != 'o' && letters != 'u')
        consonants++;

    }

        System.out.println ("Vowels:" + vowelcount  + "\nConsonants :" + consonants + "\nSpaces : " + spaces);

Sample Output
String: Hannah
Last Portion of Output
Vowels Detected: a a
Consonants Detected: h n n h

Body:
I needed to do this function using 'loops for', follow the example in JavaScript:

const defaultListVowels = ['a', 'e', 'i', 'o', 'u'];

function isVowel(value) {
    return defaultListVowels.indexOf(value) >= 0;
}

function printLetters(values) {
    console.log(values + '\r');
}

function vowelsAndConsonants(s) {
    var consonants = [];
    var vowels = [];

    for (let letter of s) {
        if (isVowel(letter)) {
            vowels.push(letter);
        } else {
            consonants.push(letter);
        }
    }

    vowels.forEach(printLetters);
    consonants.forEach(printLetters);
}

ContentLicense: CC BY-SA 4.0


问:
cytoscape js traverse nodes by selector
How can I traverse the nodes in a cytoscape js network based on their selector?

I understand I can use the

```<code>cy.filter(".myselector")
</code>```

which returns a complex object like:

```<code>0: ua {0: ua, length: 1, _private: Object, instanceString: function, spawn: function, spawnSelf: function, …}

1: ua {0: ua, length: 1, _private: Object, instanceString: function, spawn: function, spawnSelf: function, …}

2: ua {0: ua, length: 1, _private: Object, instanceString: function, spawn: function, spawnSelf: function, …}

_private: {cy: Wa, map: Map}

length: 3
</code>```

答:
This is the method I developed to traverse the graph based on the selector (and obtain the element of interest, which in my case was the name of the node)

NB note how the name is retrieved, ie _private.data.name

```<code>var entire_object, no_of_objects, objects_array = [];
entire_object = cy.filter(".myselector"); //returns a complex object with nodes matching ".myselector" filter
no_of_objects = entire_object.length; //the number of cytoscape nodes

for (var i = 0; i < no_of_objects; i++){
  object_name = {};
  object_name = entire_object[i]._private.data.name;
  objects_array.push(object_name);
}
</code>```

Title: cytoscape js traverse nodes by selector

Body:
How can I traverse the nodes in a cytoscape js network based on their selector?

I understand I can use the

cy.filter(".myselector")

which returns a complex object like:

0: ua {0: ua, length: 1, _private: Object, instanceString: function, spawn: function, spawnSelf: function, …}

1: ua {0: ua, length: 1, _private: Object, instanceString: function, spawn: function, spawnSelf: function, …}

2: ua {0: ua, length: 1, _private: Object, instanceString: function, spawn: function, spawnSelf: function, …}

_private: {cy: Wa, map: Map}

length: 3

Body:
This is the method I developed to traverse the graph based on the selector (and obtain the element of interest, which in my case was the name of the node)

NB note how the name is retrieved, ie _private.data.name

var entire_object, no_of_objects, objects_array = [];
entire_object = cy.filter(".myselector"); //returns a complex object with nodes matching ".myselector" filter
no_of_objects = entire_object.length; //the number of cytoscape nodes

for (var i = 0; i < no_of_objects; i++){
  object_name = {};
  object_name = entire_object[i]._private.data.name;
  objects_array.push(object_name);
}


问:
Uses of Embedding/ Embedding layer in deep learning
I am exploring deep learning methods especially LSTM to predict next word. Suppose, My data set is like this: Each data point consists of 7 features (7 different words)(A-G here) of different length.

```<code> Group1  Group2............ Group 38
   A        B                   F
   E        C                   A
   B        E                   G
   C        D                   G
   C        F                   F
   D        G                   G
   .        .                   .
   .        .                   .
</code>```

I used one hot encoding as an Input layer. Here is the model

```<code>main_input= Input(shape=(None,action_count),name='main_input')
lstm_out= LSTM(units=64,activation='tanh')(main_input)
lstm_out=Dropout(0.2)(lstm_out)
lstm_out=Dense(action_count)(lstm_out)
main_output=Activation('softmax')(lstm_out)
model=Model(inputs=[main_input],outputs=main_output)
print(model.summary())
</code>```

Using this model. I got an accuracy of about 60%.
My question is how can I use embedding layer for my problem. Actually, I do not know much about embedding (why, when and how it works)[I only know one hot vector does not carry much information]. I am wondering if embedding can improve accuracy. If someone can provide me guidance in these regards, it will be greatly beneficial for me. (At least whether uses of embedding is logical or not for my case)

答:
What are Embedding layers?

They are layers which converts positive integers ( maybe word counts ) into fixed size dense vectors. They learn the so called embeddings for a particular text dataset ( in NLP tasks ).

Why are they useful?

Embedding layers slowly learn the relationships between words. Hence, if you have a large enough corpus ( which probably contains all possible English words ), then vectors for words like "king" and "queen" will show some similarity in the mutidimensional space of the embedding.

How are used in Keras?

The keras.layers.Embedding has the following configurations:

```<code>keras.layers.Embedding(input_dim, output_dim, embeddings_initializer='uniform', embeddings_regularizer=None, activity_regularizer=None, embeddings_constraint=None, mask_zero=False, input_length=None)
</code>```

Turns positive integers (indexes) into dense vectors of fixed size. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]
This layer can only be used as the first layer in a model.

When the input_dim is the vocabulary size + 1. Vocabulary is the corpus of all the words used in the dataset. The input_length is the length of the input sequences whereas output_dim is the dimensionality of the output vectors ( the dimensions for the vector of a particular word ).

The layer can also be used wih pretrained word embeddings like Word2Vec or GloVE.

Are they suitable for my use case?

Absolutely, yes. For sentiment analysis, if we could generate a context ( embedding ) for a particular word then we could definitely increase its efficiency.

How can I use them in my use case?

Follow the steps:

You need to tokenize the sentences. Maybe with keras.preprocessing.text.Tokenizer.

Pad the sequences to a fixed length using keras.preprocessing.sequence.pad_sequences. This will be the input_length parameter for the Embedding layer.

Initialize the model with Embedding layer as the first layer.

Hope this helps.

Body:
I am exploring deep learning methods especially LSTM to predict next word. Suppose, My data set is like this: Each data point consists of 7 features (7 different words)(A-G here) of different length.

 Group1  Group2............ Group 38
   A        B                   F
   E        C                   A
   B        E                   G
   C        D                   G
   C        F                   F
   D        G                   G
   .        .                   .
   .        .                   .

I used one hot encoding as an Input layer. Here is the model

main_input= Input(shape=(None,action_count),name='main_input')
lstm_out= LSTM(units=64,activation='tanh')(main_input)
lstm_out=Dropout(0.2)(lstm_out)
lstm_out=Dense(action_count)(lstm_out)
main_output=Activation('softmax')(lstm_out)
model=Model(inputs=[main_input],outputs=main_output)
print(model.summary())

Using this model. I got an accuracy of about 60%.
My question is how can I use embedding layer for my problem. Actually, I do not know much about embedding (why, when and how it works)[I only know one hot vector does not carry much information]. I am wondering if embedding can improve accuracy. If someone can provide me guidance in these regards, it will be greatly beneficial for me. (At least whether uses of embedding is logical or not for my case)

Body:
What are Embedding layers?

They are layers which converts positive integers ( maybe word counts ) into fixed size dense vectors. They learn the so called embeddings for a particular text dataset ( in NLP tasks ).

Why are they useful?

Embedding layers slowly learn the relationships between words. Hence, if you have a large enough corpus ( which probably contains all possible English words ), then vectors for words like "king" and "queen" will show some similarity in the mutidimensional space of the embedding.

How are used in Keras?

The keras.layers.Embedding has the following configurations:

keras.layers.Embedding(input_dim, output_dim, embeddings_initializer='uniform', embeddings_regularizer=None, activity_regularizer=None, embeddings_constraint=None, mask_zero=False, input_length=None)

Turns positive integers (indexes) into dense vectors of fixed size. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]
This layer can only be used as the first layer in a model.

When the input_dim is the vocabulary size + 1. Vocabulary is the corpus of all the words used in the dataset. The input_length is the length of the input sequences whereas output_dim is the dimensionality of the output vectors ( the dimensions for the vector of a particular word ).

The layer can also be used wih pretrained word embeddings like Word2Vec or GloVE.

Are they suitable for my use case?

Absolutely, yes. For sentiment analysis, if we could generate a context ( embedding ) for a particular word then we could definitely increase its efficiency.

How can I use them in my use case?

Follow the steps:

You need to tokenize the sentences. Maybe with keras.preprocessing.text.Tokenizer.

Pad the sequences to a fixed length using keras.preprocessing.sequence.pad_sequences. This will be the input_length parameter for the Embedding layer.

Initialize the model with Embedding layer as the first layer.

Hope this helps.


问:
How do I add an icon to a mingw-gcc compiled executable?
In Windows, using mingw's gcc, is there anyway to specify that the output exe file is to take an icon file, so that the exe file shows with that icon in explorer?</p>

答:
Try Resource Hacker.  I was able to cross compile my project in Linux (WSL) and generate an icon from the logo on the homepage.  Just needed a simple way to embed it in the exe and this program worked great.
Resource Hacker by Angus Johnson </p>

OwnerDisplayName: myforwik

LastEditorDisplayName: moocha

ContentLicense: CC BY-SA 2.5


问:
How to end game in hangman if ALL letters in the secret word are in guessed_letters list
Im trying to create a for loop end game by doing for "every letter in my secret word if All letters are in gussed_letters then end game."

Ive tried to make a correct_letters list and see if all the letters in my secret word are in my correct_letters list then end the game but i cant seem to get it to work.

```<code>import random

words = ['apple',' python','parent'] #Make list of words
def randomword(words): #takes in list words
  return random.choice(words) #returns a random element back
chosenword = randomword(words) # make a variable equal to the function

#variables (tries you get and list to letters gussed. )
tries = 10
guess_letters = []

def dashshow(guess_letters): #takes in guess_letters
  for letter in chosenword: #checks each letter in chosenword
    if letter in guess_letters: #if letter in guess_letters print that letter
      print(letter)
    else: #or else print a dash
      print('-')

def playgame(tries):# Takes tries
  while  tries != 0: #While tries is not 0
    guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
    guess_letters.append(guess) #add guess to guess_letters list
    if guess in chosenword: #if your guess in chosenword
      print("You got a letter correct!")
      tries -= 1
    elif guess not in chosenword:
      print("That letter is not in the word")
      tries -= 1
    dashshow(guess_letters) # last call the dashshow function

randomword(words)
playgame(tries)
</code>```

答:
I made the dashshow function count how many dashes left and return a value for whether any are left. If not, the game is over and has been won.</p>

```<code>import random

words = ['apple',' python','parent'] #Make list of words
def randomword(words): #takes in list words
  return random.choice(words) #returns a random element back
chosenword = randomword(words) # make a variable equal to the function

#variables (tries you get and list to letters gussed. )
tries = 10
guess_letters = []

def dashshow(guess_letters): #takes in guess_letters
  dashes = 0
  for letter in chosenword: #checks each letter in chosenword
    if letter in guess_letters: #if letter in guess_letters print that letter
      print(letter)
    else: #or else print a dash
      print('-')
      dashes = dashes+1
  return(dashes>0)

def playgame(tries):# Takes tries
  keepPlaying = True
  while  (tries != 0) and keepPlaying: #While tries is not 0
    guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
    guess_letters.append(guess) #add guess to guess_letters list
    if guess in chosenword: #if your guess in chosenword
      print("You got a letter correct!")
      tries -= 1
    elif guess not in chosenword:
      print("That letter is not in the word")
      tries -= 1
    if not dashshow(guess_letters): # last call the dashshow function
      keepPlaying=False
      print("you win!")

randomword(words)
playgame(tries)
</code>```

Body:
Im trying to create a for loop end game by doing for "every letter in my secret word if All letters are in gussed_letters then end game."

Ive tried to make a correct_letters list and see if all the letters in my secret word are in my correct_letters list then end the game but i cant seem to get it to work.

import random

words = ['apple',' python','parent'] #Make list of words
def randomword(words): #takes in list words
  return random.choice(words) #returns a random element back
chosenword = randomword(words) # make a variable equal to the function

#variables (tries you get and list to letters gussed. )
tries = 10
guess_letters = []

def dashshow(guess_letters): #takes in guess_letters
  for letter in chosenword: #checks each letter in chosenword
    if letter in guess_letters: #if letter in guess_letters print that letter
      print(letter)
    else: #or else print a dash
      print('-')

def playgame(tries):# Takes tries
  while  tries != 0: #While tries is not 0
    guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
    guess_letters.append(guess) #add guess to guess_letters list
    if guess in chosenword: #if your guess in chosenword
      print("You got a letter correct!")
      tries -= 1
    elif guess not in chosenword:
      print("That letter is not in the word")
      tries -= 1
    dashshow(guess_letters) # last call the dashshow function

randomword(words)
playgame(tries)

Body:
I made the dashshow function count how many dashes left and return a value for whether any are left. If not, the game is over and has been won.

import random

words = ['apple',' python','parent'] #Make list of words
def randomword(words): #takes in list words
  return random.choice(words) #returns a random element back
chosenword = randomword(words) # make a variable equal to the function

#variables (tries you get and list to letters gussed. )
tries = 10
guess_letters = []

def dashshow(guess_letters): #takes in guess_letters
  dashes = 0
  for letter in chosenword: #checks each letter in chosenword
    if letter in guess_letters: #if letter in guess_letters print that letter
      print(letter)
    else: #or else print a dash
      print('-')
      dashes = dashes+1
  return(dashes>0)

def playgame(tries):# Takes tries
  keepPlaying = True
  while  (tries != 0) and keepPlaying: #While tries is not 0
    guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
    guess_letters.append(guess) #add guess to guess_letters list
    if guess in chosenword: #if your guess in chosenword
      print("You got a letter correct!")
      tries -= 1
    elif guess not in chosenword:
      print("That letter is not in the word")
      tries -= 1
    if not dashshow(guess_letters): # last call the dashshow function
      keepPlaying=False
      print("you win!")

randomword(words)
playgame(tries)


问:
get state value from store redux
how can I get the value of the state from the store?

I already tried using store.getState().isLoggedIn but it didn't work:

```<code>import * as actions from 'actions/actions'
import store from 'store/store'

store.dispatch(actions.login(this.state.username,this.state.password)).then(() => {
        state = store.getState();
          alert(state.isLoggedIn);
      });
</code>```

I'm trying to get the value of the state "isLoggedIn" but it returns "undefined". how can i properly get the state value from the store?

here is my source code

Reducer:

```<code>const INITIAL_STATE={
  isLoggedIn:false,
  isLoading:false,
  userData:{},
  error:undefined
}

export default function auth(state=INITIAL_STATE,action){
  console.log(action.type);
  switch (action.type) {
    case 'LOGIN_ATTEMPT':
      return{
        ...state,
        isLoading:true,
        isLoggedIn:false
      }
      break;
    case 'LOGIN_SUCCESS':
    return {
        ...state,
        isLoading:false,
        isLoggedIn:true,
        userData:action.userData,
        error:undefined
      }
      break;
    case 'LOGIN_FAILED':
      return{
        ...state,
        isLoading:false,
        isLoggedIn:false,
        error:action.error
      }
      break;
    case 'LOGOUT':
      return{
        ...state,
        isLoading:false,
        isLoggedIn:false
      }
      break;
    default:
      return state
  }
}
</code>```

actions:

```<code>export function isLoading(bool:Boolean){
  return{
    type:'LOGIN_ATTEMPT',
    isLoading:bool
  }
}

export function loginSuccess(userData:Object){
  return{
    type:'LOGIN_SUCCESS',
    userData
  }
}

export function loginFailed(error:Object){
  return{
    type:'LOGIN_FAILED',
    error
  }
}

export function login(uname,pass){
  return dispatch => {
    dispatch(isLoading(true));
    return fetch('http://192.168.99.1:5000/user/login',{
      method:'POST',
      headers:{
        'Content-Type':'application/json'
      },
      body:JSON.stringify({
        username:uname
      })
    })
    .then((response) => {
      if(response.status < 300){
        dispatch(isLoading(false))
        response.json().then((responseJSON) => {
          if(responseJSON['message'] == "True" && bcrypt.compareSync(pass, responseJSON['hash']) ){
            console.log("responseJSON",responseJSON);
            dispatch(loginSuccess(responseJSON));
          }
          else{
            dispatch(isLoading(false))
            dispatch(loginFailed(responseJSON.message))
          }
        })
      }
      else{
        response.json().then((responseJSON) => {
          console.log("responseJSON",responseJSON);
          dispatch(isLoading(false))
          dispatch(loginFailed(responseJSON.message))
        })
      }
    })
    .catch((error) => {
      console.log("error",error);
      dispatch(isLoading(false))
      dispatch(loginFailed(error))
    })
  }
}
</code>```

store:

```<code>import {combineReducers} from 'redux'
import auth from './authReducer'
import {createStore,applyMiddleware} from 'redux'
import thunk from 'redux-thunk';

const rootReducer = combineReducers({
  auth
})

let store = createStore(rootReducer,applyMiddleware(thunk))

export default store;
</code>```

答:
I was able to view the data by using JSON.stringify

```<code>  JSON.stringify(store.getState())
</code>```

it returns json data. using this method makes it easy to view objects

Title: get state value from store redux

Body:
how can I get the value of the state from the store?

I already tried using store.getState().isLoggedIn but it didn't work:

import * as actions from 'actions/actions'
import store from 'store/store'

store.dispatch(actions.login(this.state.username,this.state.password)).then(() => {
        state = store.getState();
          alert(state.isLoggedIn);
      });

I'm trying to get the value of the state "isLoggedIn" but it returns "undefined". how can i properly get the state value from the store?

here is my source code

Reducer:

const INITIAL_STATE={
  isLoggedIn:false,
  isLoading:false,
  userData:{},
  error:undefined
}

export default function auth(state=INITIAL_STATE,action){
  console.log(action.type);
  switch (action.type) {
    case 'LOGIN_ATTEMPT':
      return{
        ...state,
        isLoading:true,
        isLoggedIn:false
      }
      break;
    case 'LOGIN_SUCCESS':
    return {
        ...state,
        isLoading:false,
        isLoggedIn:true,
        userData:action.userData,
        error:undefined
      }
      break;
    case 'LOGIN_FAILED':
      return{
        ...state,
        isLoading:false,
        isLoggedIn:false,
        error:action.error
      }
      break;
    case 'LOGOUT':
      return{
        ...state,
        isLoading:false,
        isLoggedIn:false
      }
      break;
    default:
      return state
  }
}

actions:

export function isLoading(bool:Boolean){
  return{
    type:'LOGIN_ATTEMPT',
    isLoading:bool
  }
}

export function loginSuccess(userData:Object){
  return{
    type:'LOGIN_SUCCESS',
    userData
  }
}

export function loginFailed(error:Object){
  return{
    type:'LOGIN_FAILED',
    error
  }
}

export function login(uname,pass){
  return dispatch => {
    dispatch(isLoading(true));
    return fetch('http://192.168.99.1:5000/user/login',{
      method:'POST',
      headers:{
        'Content-Type':'application/json'
      },
      body:JSON.stringify({
        username:uname
      })
    })
    .then((response) => {
      if(response.status < 300){
        dispatch(isLoading(false))
        response.json().then((responseJSON) => {
          if(responseJSON['message'] == "True" && bcrypt.compareSync(pass, responseJSON['hash']) ){
            console.log("responseJSON",responseJSON);
            dispatch(loginSuccess(responseJSON));
          }
          else{
            dispatch(isLoading(false))
            dispatch(loginFailed(responseJSON.message))
          }
        })
      }
      else{
        response.json().then((responseJSON) => {
          console.log("responseJSON",responseJSON);
          dispatch(isLoading(false))
          dispatch(loginFailed(responseJSON.message))
        })
      }
    })
    .catch((error) => {
      console.log("error",error);
      dispatch(isLoading(false))
      dispatch(loginFailed(error))
    })
  }
}

store:

import {combineReducers} from 'redux'
import auth from './authReducer'
import {createStore,applyMiddleware} from 'redux'
import thunk from 'redux-thunk';

const rootReducer = combineReducers({
  auth
})

let store = createStore(rootReducer,applyMiddleware(thunk))

export default store;

Body:
I was able to view the data by using JSON.stringify

  JSON.stringify(store.getState())

it returns json data. using this method makes it easy to view objects


问:
Why does this for loop don't work in java?
I have this exercise code to calculate the future hour:

```<code>public static void main(String[]   args) {
Scanner scanner = new Scanner (System.in);
String amPm;
System.out.println("Write an hour (lower o equal to 12) ");
int startHour = scanner.nextInt();
System.out.println("write the number of hours to sum ");
scanner.nextLine();
int hoursToSum = scanner.nextInt();

System.out.println("am or pm? (1/0)");
int selection = scanner.nextInt();

if (selection == 1) {
amPm = ".am";
}
else {
amPm = ".pm";
}

for(int i = 0; i == hoursToSum; i++) {
startHour ++;
if (startHour > 12) {
startHour = 1;
if (amPm.equals(".am")) {
amPm = ".pm";
}
else {
amPm = ".am";
}
}
}
System.out.println("it´s gonna be: " + startHour + amPm);
}
</code>```

But it doesn't work, except with the values 12  to startHour and 0 to hourToSum.

I tried with while loop and it worked!

I Know both, for and while loop, are able to perform the same task.
So, why does this happen?

```<code> int i = 0;
while(i < hoursToSum) {
startHour ++;
if (startHour > 12) {
startHour = 1;
if (amPm.equals(".am")) {
amPm = ".pm";
}
else {
amPm = ".am";
}
}
i ++;

}
</code>```

答:
To elaborate on Amadan's comment, a for loop consists of three parts:
 1. An initialization with variable declaration
 2. A condition
 3. An iteration, or change of state at the end of the loop

These things happen in a while loop also, but are placed differently

```<code>for (int i = 0; i < 12; i++) {  //(initialization;condition;iteration)
    doStuff();
}
</code>```

This initializes i to 0, increments it each time the code in the block completes, and breaks out of the loop if i exceeds 12.

```<code>int i = 0;       // initialization
while (i < 12) { //condition
    doStuff();
    i++;         //iteration
}
</code>```

The error is in the condition portion of the for loop, where you are checking i == hoursToSum instead of i < hoursToSum, as you did in the while loop

Body:
I have this exercise code to calculate the future hour:

public static void main(String[]   args) {
Scanner scanner = new Scanner (System.in);
String amPm;
System.out.println("Write an hour (lower o equal to 12) ");
int startHour = scanner.nextInt();
System.out.println("write the number of hours to sum ");
scanner.nextLine();
int hoursToSum = scanner.nextInt();

System.out.println("am or pm? (1/0)");
int selection = scanner.nextInt();

if (selection == 1) {
amPm = ".am";
}
else {
amPm = ".pm";
}

for(int i = 0; i == hoursToSum; i++) {
startHour ++;
if (startHour > 12) {
startHour = 1;
if (amPm.equals(".am")) {
amPm = ".pm";
}
else {
amPm = ".am";
}
}
}
System.out.println("it´s gonna be: " + startHour + amPm);
}

But it doesn't work, except with the values 12  to startHour and 0 to hourToSum.

I tried with while loop and it worked!

I Know both, for and while loop, are able to perform the same task.
So, why does this happen?

 int i = 0;
while(i < hoursToSum) {
startHour ++;
if (startHour > 12) {
startHour = 1;
if (amPm.equals(".am")) {
amPm = ".pm";
}
else {
amPm = ".am";
}
}
i ++;

}

Body:
To elaborate on Amadan's comment, a for loop consists of three parts:
 1. An initialization with variable declaration
 2. A condition
 3. An iteration, or change of state at the end of the loop

These things happen in a while loop also, but are placed differently

for (int i = 0; i < 12; i++) {  //(initialization;condition;iteration)
    doStuff();
}

This initializes i to 0, increments it each time the code in the block completes, and breaks out of the loop if i exceeds 12.

int i = 0;       // initialization
while (i < 12) { //condition
    doStuff();
    i++;         //iteration
}

The error is in the condition portion of the for loop, where you are checking i == hoursToSum instead of i < hoursToSum, as you did in the while loop


问:
sqlalchemy - data doesnt get pushed to database while commit but present in session(in memory)
I am adding data to sqlalchemy. But sometimes data is not getting updated or inserted to database. But the commit is successful and I can see the data in memory of session's object.
ie

```<code>session.identity_map
</code>```

Running on sqlalchemy 1.3.3. python 2.7. ubuntu 18.04

```<code>from sqlalchemy.orm import Session
from . import Errors as ExecuteErrors

class Errors(object):
    def __init__(self, sqlalchemy_engine, d):
        self.sqlalchemy_engine = sqlalchemy_engine
        self.d = d

    def upsert(self, error):
        session = Session(self.sqlalchemy_engine)
        row = session.query(ExecuteErrors).filter_by(**{'c_name':error['c_name'], 'c_type':error['c_type'],
                                               'f_name':error['f_name']}).scalar()
        session.close()
        if row:
            self.update(error)
        else:
            self.insert(error)

    def insert(self, error):
        e = ExecuteErrors(**{'c_name':error['c_name'], 'c_type':error['c_type'], 'f_name':error['f_name'],
                          'msg':error['msg'], 'details':error['details']})
        session = Session(self.sqlalchemy_engine, expire_on_commit=False)
        session.add(e)
        session.identity_map
        session.commit()
        session.close()

    def update(self, error):
        session = Session(self.sqlalchemy_engine, expire_on_commit=False)
        session.query(ExecuteErrors).filter_by(**{'c_name':error['c_name'], 'c_type':error['c_type'],
                                               'f_name':error['f_name']}).update({'msg': error['msg'], 'details': error['details']})
        session.commit()
        session.close()

    def get_errors(self):
        session = Session(self.sqlalchemy_engine)
        e = session.query(ExecuteErrors).all()
        session.close()
        return e

    def clear(self):
        session = Session(self.sqlalchemy_engine)
        session.query(ExecuteErrors).delete()
        session.commit()
        session.close()
</code>```

Calling this with:

```<code>e = Error(engine, 'emp')
e.upsert({'c_name':'filter','c_type':'task','f_name':'f1','msg':'TypeError','details':'xyz'})
</code>```

This should add row in database or update row with new data.
Its working for some insert and for some not.

答:
You could find a possible workaround by explicitely flushing your session when needed.

That said, I think you should reconsider the way you're using sessions. Sessions are intended to manage database connections but you're using them as if there where actual connections.

IMHO, a better way to do would be to create a session at Error instanciation and use it when needed in all your methods.
An even better way to proceed could be to create a session at begining of your "calling" module and pass it to the Error instanciation, and to any other object which need access to database.
Doing this, you could even experience better performance and it may solve your problem (?)

More details about how to manage sessions in the sqlalchemy doc.

EDIT: In addition, the sqlalchemy doc lists some potential problems when used with sqlite. One of them could be the cause of your problem.

Body:
I am adding data to sqlalchemy. But sometimes data is not getting updated or inserted to database. But the commit is successful and I can see the data in memory of session's object.
ie

session.identity_map

Running on sqlalchemy 1.3.3. python 2.7. ubuntu 18.04

from sqlalchemy.orm import Session
from . import Errors as ExecuteErrors

class Errors(object):
    def __init__(self, sqlalchemy_engine, d):
        self.sqlalchemy_engine = sqlalchemy_engine
        self.d = d

    def upsert(self, error):
        session = Session(self.sqlalchemy_engine)
        row = session.query(ExecuteErrors).filter_by(**{'c_name':error['c_name'], 'c_type':error['c_type'],
                                               'f_name':error['f_name']}).scalar()
        session.close()
        if row:
            self.update(error)
        else:
            self.insert(error)

    def insert(self, error):
        e = ExecuteErrors(**{'c_name':error['c_name'], 'c_type':error['c_type'], 'f_name':error['f_name'],
                          'msg':error['msg'], 'details':error['details']})
        session = Session(self.sqlalchemy_engine, expire_on_commit=False)
        session.add(e)
        session.identity_map
        session.commit()
        session.close()

    def update(self, error):
        session = Session(self.sqlalchemy_engine, expire_on_commit=False)
        session.query(ExecuteErrors).filter_by(**{'c_name':error['c_name'], 'c_type':error['c_type'],
                                               'f_name':error['f_name']}).update({'msg': error['msg'], 'details': error['details']})
        session.commit()
        session.close()

    def get_errors(self):
        session = Session(self.sqlalchemy_engine)
        e = session.query(ExecuteErrors).all()
        session.close()
        return e

    def clear(self):
        session = Session(self.sqlalchemy_engine)
        session.query(ExecuteErrors).delete()
        session.commit()
        session.close()

Calling this with:

e = Error(engine, 'emp')
e.upsert({'c_name':'filter','c_type':'task','f_name':'f1','msg':'TypeError','details':'xyz'})

This should add row in database or update row with new data.
Its working for some insert and for some not.


问:
Can you "Create a new download URL" in Firebase Storage programmatically?

In Firebase Storage console, you are able to generate a new download url

.. via that small gray link at the bottom of the image

Can this Reset URL Event be triggered programmatically via Google Cloud Functions?

答: There is currently no public API for this.  Please feel free to file a feature request stating your specific use case.</p>


问:
How to Comma separate multiple rows obtained from a SQL Query
```<code>Select s.FirstName, glTitle.LookupItem Title
    from ClientStaff cs
    left outer join Staff s on s.Id = cs.StaffId
    left outer join StaffTitle st on st.StaffId = s.Id
    left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
</code>```

It returns these rows:

As you can see, the first column has all same rows because one employee can have multiple titles.

How can I merge all of the titles for each employee into a comma separated value so that there is only one row per employee?

答: This is one of those things that's difficult (or impossible) to do in standard SQL. Many vendors have extended SQL to support "rollups" like that; unfortunately, each vendor's syntax is different. Sorry, I don't have an example handy at the moment. So what DBMS are you using?</p>

Body:
Select s.FirstName, glTitle.LookupItem Title
    from ClientStaff cs
    left outer join Staff s on s.Id = cs.StaffId
    left outer join StaffTitle st on st.StaffId = s.Id
    left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId

It returns these rows:

As you can see, the first column has all same rows because one employee can have multiple titles.

How can I merge all of the titles for each employee into a comma separated value so that there is only one row per employee?


问:
Redirect HTTPS on multidomain Varnish
i have got two domain based on same framework (magento2)
domain1.it
domain2.com

I would like to redirect them to their respective SSL version.
https://domain1.it
https://domain2.com

Domain 1 is correctly configured to redirect to HTTPS and my varnish Config file is:

```<code>sub vcl_recv {
if ( (req.http.host ~ "^(?i)www.domain1.it" || req.http.host ~ "^(?i)domain1.it") && req.http.X-Forwarded-Proto !~ "(?i)https") {
return (synth(750, ""));
    }

sub vcl_synth {
if (resp.status == 750) {
    set resp.status = 301;
    set resp.http.Location = "https://domain1.it" + req.url;
return(deliver);
}
</code>```

the problem is the synth always redirect to the same domain.

I should add an if condition where i could call a subroutines that redirect to https for domain2

答:
For the love of everything that is good, please stop using otherworldly status codes, 301 and 302 are perfectly fine, clearer and save you a line.

I would advise against using x-forwarded-proto and use an SSL/TLS terminator that supports the PROXY protocol, but since this is what you have, here you go:

```<code>sub vcl_recv {
    if (req.http.X-Forwarded-Proto !~ "https") {
        set req.http.location = "https://" + req.http.host + req.url;
        return(synth(301));
    }
}

sub vcl_synth {
    if (resp.status == 301 || resp.status == 302) {
        set resp.http.location = req.http.location;
        return (deliver);
    }
}
</code>```

relevant link: https://info.varnish-software.com/blog/rewriting-urls-with-varnish-redirection

Title: Redirect HTTPS on multidomain Varnish

Body:
i have got two domain based on same framework (magento2)
domain1.it
domain2.com

I would like to redirect them to their respective SSL version.
https://domain1.it
https://domain2.com

Domain 1 is correctly configured to redirect to HTTPS and my varnish Config file is:

sub vcl_recv {
if ( (req.http.host ~ "^(?i)www.domain1.it" || req.http.host ~ "^(?i)domain1.it") && req.http.X-Forwarded-Proto !~ "(?i)https") {
return (synth(750, ""));
    }

sub vcl_synth {
if (resp.status == 750) {
    set resp.status = 301;
    set resp.http.Location = "https://domain1.it" + req.url;
return(deliver);
}

the problem is the synth always redirect to the same domain.

I should add an if condition where i could call a subroutines that redirect to https for domain2

Body:
For the love of everything that is good, please stop using otherworldly status codes, 301 and 302 are perfectly fine, clearer and save you a line.

I would advise against using x-forwarded-proto and use an SSL/TLS terminator that supports the PROXY protocol, but since this is what you have, here you go:

sub vcl_recv {
    if (req.http.X-Forwarded-Proto !~ "https") {
        set req.http.location = "https://" + req.http.host + req.url;
        return(synth(301));
    }
}

sub vcl_synth {
    if (resp.status == 301 || resp.status == 302) {
        set resp.http.location = req.http.location;
        return (deliver);
    }
}

relevant link: https://info.varnish-software.com/blog/rewriting-urls-with-varnish-redirection


问:
Where is the right place to store server files in AWS
In aws where is the best place to store files like user uploaded files or static files that will not cost much.

Normally what I do is to save the files in the ec2 server where i upload my code. I want to know if that is better or i should use s3 or move to elastic beanstack.

答:
Definitely Amazon S3. Reasons include:

It is separating compute from storage. This way, you can launch more application servers, or replace failed servers, and the user files remain accessible in Amazon S3.

Amazon S3 is a regional service, with data replicated between Availability Zones. Data stored on an instance in Amazon Block Storage (EBS) is kept in only one AZ.

There are no storage limits in Amazon S3.

It has a lower cost (S3 is around 2c/GB/month, EBS is around 10c/GB/month)

Your application can provide links to objects stored in Amazon S3. Your users can then use these links to access the objects directly from S3 without having to go via your web server. This reduces the load on your web server, which means you don't need to pay for larger instances. (There are many ways to secure your data in S3 so that only the right users can access it, such as using pre-signed URLs.)

These are just general recommendations. Your particular application might have non-standard needs.


问:
Undefined variable in blade view (single valued data)
I'm trying to pass variable $cMonth to my view. I tried looping it using foreach even if its a single valued data and error still says undefined variable .. I tried dd($cMonth) and the correct output is shown.

This is a snippet of my controller.

```<code>$cMonth = date("F", mktime(0, 0, 0, $month, 1));

return view('admin.request',compact('showData','cMonth', 'year'));
</code>```

In view, I am calling cMonth like this --

```<code>{{ ($cMonth) }}
</code>```

答:
With this route code

```<code>Route::get('/test', function() {
    $month = 3;
    $showData = true;
    $year = 2019;
    $cMonth = date("F", mktime(0, 0, 0, $month, 1));
    return view('test', compact('cMonth', 'showData', 'year'));
});
</code>```

And this view

```<code>{{ $cMonth }}
</code>```

It works as expected.
Have you tried using just that code for the view and see if it works?

You should post your complete view code, because it seems that somewhere/somehow the variable get unset.

Body:
I'm trying to pass variable $cMonth to my view. I tried looping it using foreach even if its a single valued data and error still says undefined variable .. I tried dd($cMonth) and the correct output is shown.

This is a snippet of my controller.

$cMonth = date("F", mktime(0, 0, 0, $month, 1));

return view('admin.request',compact('showData','cMonth', 'year'));

In view, I am calling cMonth like this --

{{ ($cMonth) }}

Body:
With this route code

Route::get('/test', function() {
    $month = 3;
    $showData = true;
    $year = 2019;
    $cMonth = date("F", mktime(0, 0, 0, $month, 1));
    return view('test', compact('cMonth', 'showData', 'year'));
});

And this view

{{ $cMonth }}

It works as expected.
Have you tried using just that code for the view and see if it works?

You should post your complete view code, because it seems that somewhere/somehow the variable get unset.


答:
You're using combineReducers to produce rootReducer.

The state produced by combineReducers() namespaces the states of each reducer under their keys as passed to combineReducers()

So store.getState() will return object like this

```<code>{ auth:
    { isLoggedIn:false,
      isLoading:false,
      userData:{},
      error:undefined
    }
}
</code>```

To refer to isLoggedIn  you have to do alert(state.auth.isLoggedIn);

Title: get state value from store redux

Body:
You're using combineReducers to produce rootReducer.

The state produced by combineReducers() namespaces the states of each reducer under their keys as passed to combineReducers()

So store.getState() will return object like this

{ auth:
    { isLoggedIn:false,
      isLoading:false,
      userData:{},
      error:undefined
    }
}

To refer to isLoggedIn  you have to do alert(state.auth.isLoggedIn);


问:
Cloud Run Memory Restriction
How do I get a Cloud Run container that uses more than 2 GB run on custom GKE cluster?

Since Cloud Run uses knative, I wonder if it is possible to tweak deployment describtor with more allocated/allowed memory limit to run it on GKE.

```<code>apiVersion: serving.knative.dev/v1alpha1
kind: Revision
metadata:
 ...
</code>```

答:
How do I get a Cloud Run container that uses more than 2 GB run on
custom GKE cluster?

The maximum memory that you can allocate to a container in Cloud Run Managed is 2 GB.

[UPDATE 2]

Cloud Run now supports 32 GB, but the larger memory features are in preview. This document provides details on memory limits.

Set and update memory limits

[UPDATE]

Cloud Run Managed now supports 8 GB. Release Notes.

For Cloud Run on Kubernetes, you can request more memory:

```<code>gcloud beta run deploy --image gcr.io/cloudrun/hello --memory=4G --cluster ha-cluster-1
</code>```

Since Cloud Run uses knative, I wonder if it is possible to tweak
deployment describtor with more allocated/allowed memory limit to run
it on GKE.

Cloud Run Managed does not run in Knative, it runs in gVisor. I wrote an article that describes the Cloud Run infrastructure plus the Knative API that both Cloud Run Managed and Cloud Run on Kubernetes expose here. However, even with direct access to the Cloud Run Knative API, you cannot get around the imposed service limits.

The purpose of Cloud Run is to simplify deployments by abstracting away implementation details of the underlying infrastructure. There are cases where you should deploy directly to Kubernetes.

Title: Cloud Run Memory Restriction

Body:
How do I get a Cloud Run container that uses more than 2 GB run on custom GKE cluster?

Since Cloud Run uses knative, I wonder if it is possible to tweak deployment describtor with more allocated/allowed memory limit to run it on GKE.

apiVersion: serving.knative.dev/v1alpha1
kind: Revision
metadata:
 ...

Body:
How do I get a Cloud Run container that uses more than 2 GB run on
custom GKE cluster?

The maximum memory that you can allocate to a container in Cloud Run Managed is 2 GB.

[UPDATE 2]

Cloud Run now supports 32 GB, but the larger memory features are in preview. This document provides details on memory limits.

Set and update memory limits

[UPDATE]

Cloud Run Managed now supports 8 GB. Release Notes.

For Cloud Run on Kubernetes, you can request more memory:

gcloud beta run deploy --image gcr.io/cloudrun/hello --memory=4G --cluster ha-cluster-1

Since Cloud Run uses knative, I wonder if it is possible to tweak
deployment describtor with more allocated/allowed memory limit to run
it on GKE.

Cloud Run Managed does not run in Knative, it runs in gVisor. I wrote an article that describes the Cloud Run infrastructure plus the Knative API that both Cloud Run Managed and Cloud Run on Kubernetes expose here. However, even with direct access to the Cloud Run Knative API, you cannot get around the imposed service limits.

The purpose of Cloud Run is to simplify deployments by abstracting away implementation details of the underlying infrastructure. There are cases where you should deploy directly to Kubernetes.


问:
How do I remove the splash screen when I move the screen in React-native or Expo eject?
My app is standalone app on Expo using expo eject.

My problem is that when  move the screen, I can see the splash screen for a very short time and the screen is rendered. What is the reason, and how can I keep the splash screen off?

I want to get rid of this problem because it is quite intrusive in UI.

App.js

import React, { Component } from "react";
import HomeScreen from "./screen/HomeScreen";
import { Text, Image, View, Platform } from "react-native";
import { Asset, AppLoading, SplashScreen } from "expo";
export default class AwesomeApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      areReasourcesReady: false
    };
  }

  async componentDidMount() {
    SplashScreen.hide();
    this.cacheResourcesAsync() // ask for resources
      .then(() => this.setState({ areReasourcesReady: true })) // mark reasources as loaded
      .catch(error =>
        console.error(`Unexpected error thrown when loading:
    ${error.stack}`)
      );
    await Expo.Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
      Ionicons: require("native-base/Fonts/Ionicons.ttf")
    });
  }

  async cacheResourcesAsync() {
    const images = [require("./image/testimage.png")];
    const cacheImages = images.map(image =>
      Asset.fromModule(image).downloadAsync()
    );
    return Promise.all(cacheImages);
  }

  render() {
    if (!this.state.areReasourcesReady) {
      return Platform.OS !== "ios" ? (
        <View
          style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
        />
      ) : (
        <View
          style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
        >
          <Image
            source={require("./image/logo_name_01.png")}
            resizeMode="contain"
            onLoad={this.cacheResourcesAsync}
          />
        </View>
      );
    }
    return <HomeScreen />;
  }
}
```

<p>HomeScreen.js</p>

<pre class="lang-js prettyprint-override"><code>window.randomBytes = asyncRandomBytes;
window.scryptsy = safeCrypto.scrypt;

const Drawers = createDrawerNavigator(
  {
    FirstAgree: {
      screen: RegisterWalletScreen
    },
    Test: { screen: TestScreen }
  },
  {
    initialRouteName: "FirstAgree",
    contentComponent: props => <SideBar {...props} />
  }
);
...

const stackScreen = createStackNavigator(
  {
    Drawers: {
      screen: Drawers
    },
    UserRight: {
      screen: UserRightScreen
    },
    RegisterWalletIndex: {
      screen: RegisterWalletScreen
    },
...
  },
  {
    initialRouteName: "StartScreen",
    headerMode: "none"
  }
);

const HomeScreenRouter = createAppContainer(stackScreen);

export default HomeScreenRouter;

</code>```

StartScreen.js

import React, { Component } from "react";
import {
  AsyncStorage,
  Text,
  View,
  ActivityIndicator,
  Image
} from "react-native";
import { Permissions } from "expo";

class StartScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isReady: false,
      text: "1000"
    };
  }

  async componentDidMount() {
    let powersucess = await AsyncStorage.getItem("powersucess");
    if (powersucess !== null) {
      const permission = await Permissions.getAsync(Permissions.CAMERA_ROLL);
      if (permission.status !== "granted") {
        const newPermission = await Permissions.askAsync(
          Permissions.CAMERA_ROLL
        );
        console.log("---" + newPermission);
        if (newPermission.status === "granted") {
          console.log("동의함 첫번째");
          console.log(newPermission.status);
        } else {
        }
      } else {
        console.log("동의함 첫번째");
      }
    }
  }

  async componentWillMount() {
    let version = this.state.text;
    let powersucess = await AsyncStorage.getItem("powersucess");
    let useTouchId = await AsyncStorage.getItem("useTouchId");
    let RealPinNumber = await AsyncStorage.getItem("RealPinNumberLogin");

    if (version !== "1000") {
      this.props.navigation.navigate("Test");
    } else {
      if (powersucess === null) {
        this.props.navigation.navigate("CusterMizingAlert");
      } else {
        if (RealPinNumber === null && useTouchId === null) {
          this.props.navigation.navigate("RegisterWalletIndex");
        } else {
          if (useTouchId === null) {
            this.props.navigation.navigate("RealPinNumberLogin");
          } else {
            if (useTouchId === "useTouchId") {
              this.props.navigation.navigate("TouchIdLogin");
            } else {
              this.props.navigation.navigate("FaceIdLogin");
            }
          }
        }
      }
    }

    this.setState({ isReady: true });
  }
  render() {
    return this.state.isReady === false ? (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Image
          style={{ width: 180, height: 180 }}
          source={require("../../image/logo_name_01.png")}
          resizeMode="contain"
        />
        <View
          style={{
            flexDirection: "column",
            position: "absolute",
            bottom: "30%"
          }}
        >
          <ActivityIndicator size="small" color="#ffd90d" />
        </View>
      </View>
    ) : (
      <View>
        <Text style={{ color: "#ffffff" }}>{this.state.text}</Text>
      </View>
    );
  }
}
export default StartScreen;
```

<p>The screen that clicks the Move Screen button:</p>

<pre class="lang-js prettyprint-override"><code>import React from "react";
import {
  View,
  Text,
  Dimensions,
  ActivityIndicator,
  AsyncStorage,
  Alert,
  Image,
  Platform,
  NativeModules,
  Modal,
  TextInput,
  BackHandler,
  SafeAreaView,
  TouchableHighlight
} from "react-native";
import "../../global";
import PinView from "react-native-pin-view";
import styles from "./styles.js";
import Wallet from "../../components/wallet";
import { V3_OPTIONS } from "../../components/walletapi";
import {
  backHandlerAdd,
  BackHandlerRemove,
  setDisable,
  setColor
} from "../../util/gbrick";

const windowHeight = Dimensions.get("window").height;
const windowWidth = Dimensions.get("window").width;
const { RNExitApp } = NativeModules;

class RealPinNumberLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      numbering: "",
      alertVisibility: false,
      password: "",
      keystoredata: ""
    };
  }

  componentWillMount() {
    backHandlerAdd();
  }

  componentWillUnmount() {
    BackHandlerRemove();
  }

  async componentDidMount() {
    await AsyncStorage.setItem("RealPinNumberLogin", "RealPinNumberLogin");
    let pinnum = await AsyncStorage.getItem("pinnumber");
    let publicaddress = await AsyncStorage.getItem("publicaddress");
          let registerdata = {
            user_address: publicaddress,
          };
          let data = JSON.stringify(registerdata);
          this.setState({
            numbering: pinnum,
            data: data,
          });

          console.log(data);
  }

  //핀번호 일치여부 확인하는 함수.
  onFinishCheckingCode(number, clear) {
    console.log(number);
    if (this.state.numbering !== number) {
      clear();
    }
    if (this.state.numbering === number) {
      BackHandlerRemove();
      this.props.navigation.push("WebView", {
        data: this.state.data
      });
    }
  }

  showCustomAlert(visible) {
    this.setState({ alertVisibility: visible });
  }

  async check() {
    try {
      wallet = await Wallet.fromV3(
        JSON.parse(this.state.keystoredata),
        this.state.password,
        V3_OPTIONS
      );
      this.setState({
        alertVisibility: false
      });
      setDisable();
      setColor("#ffffff");
      this.props.navigation.push("RegisterSecurity", {
        data: this.state.data
      });
    } catch (error) {
      this.setState({
        disabled: false
      });
      alert(error);
    }
  }

  render() {
    return this.state.numbering === "" ? (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Image
          style={{ width: 180, height: 180 }}
          source={require("../../image/logo_name_01.png")}
          resizeMode="contain"
        />
        <View
          style={{
            flexDirection: "column",
            position: "absolute",
            bottom: "30%"
          }}
        >
          <ActivityIndicator size="small" color="#ffd90d" />
        </View>
      </View>
    ) : (
      <SafeAreaView style={styles.container}>

        <View style={styles.realpinloginlayout1}>
          <View style={{ paddingBottom: Platform.OS === "ios" ? "5%" : "10%" }}>
            <Image
              style={{
                resizeMode: "contain"
              }}
              source={require("../../image/realloginpin.png")}
            />
          </View>
          <PinView
            onComplete={this.onFinishCheckingCode.bind(this)}
            pinLength={4}
            inputBgColor="#888888"
            inputActiveBgColor="#ffd90d"
            buttonBgColor="#ffffff"
            buttonTextColor="black"
            keyboardViewStyle={{
              borderColor: "#dfdfdf",
              borderWidth: 1,
              width: windowHeight / 11,
              height: windowHeight / 11
            }}
            inputViewStyle={{ width: 18, height: 18, margin: 18 }}
          />
        </View>
      </SafeAreaView>
    );
  }
}

export default RealPinNumberLogin;

</code>```

```<code>this.props.navigation.push("WebView", {
    data: this.state.data
  });
</code>```

And that's where the splash screen comes out.

Click this to see the problem screen.

Please Help me a lot

Thanks you in  advance

答:
I solved this problem by deleting the default splash screen set by Android.

splash_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/splashBackground"/>

</layer-list>
```

Body:
My app is standalone app on Expo using expo eject.

My problem is that when  move the screen, I can see the splash screen for a very short time and the screen is rendered. What is the reason, and how can I keep the splash screen off?

I want to get rid of this problem because it is quite intrusive in UI.

App.js

import React, { Component } from "react";
import HomeScreen from "./screen/HomeScreen";
import { Text, Image, View, Platform } from "react-native";
import { Asset, AppLoading, SplashScreen } from "expo";
export default class AwesomeApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      areReasourcesReady: false
    };
  }

  async componentDidMount() {
    SplashScreen.hide();
    this.cacheResourcesAsync() // ask for resources
      .then(() => this.setState({ areReasourcesReady: true })) // mark reasources as loaded
      .catch(error =>
        console.error(`Unexpected error thrown when loading:
    ${error.stack}`)
      );
    await Expo.Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
      Ionicons: require("native-base/Fonts/Ionicons.ttf")
    });
  }

  async cacheResourcesAsync() {
    const images = [require("./image/testimage.png")];
    const cacheImages = images.map(image =>
      Asset.fromModule(image).downloadAsync()
    );
    return Promise.all(cacheImages);
  }

  render() {
    if (!this.state.areReasourcesReady) {
      return Platform.OS !== "ios" ? (
        <View
          style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
        />
      ) : (
        <View
          style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
        >
          <Image
            source={require("./image/logo_name_01.png")}
            resizeMode="contain"
            onLoad={this.cacheResourcesAsync}
          />
        </View>
      );
    }
    return <HomeScreen />;
  }
}

HomeScreen.js

window.randomBytes = asyncRandomBytes;
window.scryptsy = safeCrypto.scrypt;

const Drawers = createDrawerNavigator(
  {
    FirstAgree: {
      screen: RegisterWalletScreen
    },
    Test: { screen: TestScreen }
  },
  {
    initialRouteName: "FirstAgree",
    contentComponent: props => <SideBar {...props} />
  }
);
...

const stackScreen = createStackNavigator(
  {
    Drawers: {
      screen: Drawers
    },
    UserRight: {
      screen: UserRightScreen
    },
    RegisterWalletIndex: {
      screen: RegisterWalletScreen
    },
...
  },
  {
    initialRouteName: "StartScreen",
    headerMode: "none"
  }
);

const HomeScreenRouter = createAppContainer(stackScreen);

export default HomeScreenRouter;

StartScreen.js

import React, { Component } from "react";
import {
  AsyncStorage,
  Text,
  View,
  ActivityIndicator,
  Image
} from "react-native";
import { Permissions } from "expo";

class StartScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isReady: false,
      text: "1000"
    };
  }

  async componentDidMount() {
    let powersucess = await AsyncStorage.getItem("powersucess");
    if (powersucess !== null) {
      const permission = await Permissions.getAsync(Permissions.CAMERA_ROLL);
      if (permission.status !== "granted") {
        const newPermission = await Permissions.askAsync(
          Permissions.CAMERA_ROLL
        );
        console.log("---" + newPermission);
        if (newPermission.status === "granted") {
          console.log("동의함 첫번째");
          console.log(newPermission.status);
        } else {
        }
      } else {
        console.log("동의함 첫번째");
      }
    }
  }

  async componentWillMount() {
    let version = this.state.text;
    let powersucess = await AsyncStorage.getItem("powersucess");
    let useTouchId = await AsyncStorage.getItem("useTouchId");
    let RealPinNumber = await AsyncStorage.getItem("RealPinNumberLogin");

    if (version !== "1000") {
      this.props.navigation.navigate("Test");
    } else {
      if (powersucess === null) {
        this.props.navigation.navigate("CusterMizingAlert");
      } else {
        if (RealPinNumber === null && useTouchId === null) {
          this.props.navigation.navigate("RegisterWalletIndex");
        } else {
          if (useTouchId === null) {
            this.props.navigation.navigate("RealPinNumberLogin");
          } else {
            if (useTouchId === "useTouchId") {
              this.props.navigation.navigate("TouchIdLogin");
            } else {
              this.props.navigation.navigate("FaceIdLogin");
            }
          }
        }
      }
    }

    this.setState({ isReady: true });
  }
  render() {
    return this.state.isReady === false ? (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Image
          style={{ width: 180, height: 180 }}
          source={require("../../image/logo_name_01.png")}
          resizeMode="contain"
        />
        <View
          style={{
            flexDirection: "column",
            position: "absolute",
            bottom: "30%"
          }}
        >
          <ActivityIndicator size="small" color="#ffd90d" />
        </View>
      </View>
    ) : (
      <View>
        <Text style={{ color: "#ffffff" }}>{this.state.text}</Text>
      </View>
    );
  }
}
export default StartScreen;

The screen that clicks the Move Screen button:

import React from "react";
import {
  View,
  Text,
  Dimensions,
  ActivityIndicator,
  AsyncStorage,
  Alert,
  Image,
  Platform,
  NativeModules,
  Modal,
  TextInput,
  BackHandler,
  SafeAreaView,
  TouchableHighlight
} from "react-native";
import "../../global";
import PinView from "react-native-pin-view";
import styles from "./styles.js";
import Wallet from "../../components/wallet";
import { V3_OPTIONS } from "../../components/walletapi";
import {
  backHandlerAdd,
  BackHandlerRemove,
  setDisable,
  setColor
} from "../../util/gbrick";

const windowHeight = Dimensions.get("window").height;
const windowWidth = Dimensions.get("window").width;
const { RNExitApp } = NativeModules;

class RealPinNumberLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      numbering: "",
      alertVisibility: false,
      password: "",
      keystoredata: ""
    };
  }

  componentWillMount() {
    backHandlerAdd();
  }

  componentWillUnmount() {
    BackHandlerRemove();
  }

  async componentDidMount() {
    await AsyncStorage.setItem("RealPinNumberLogin", "RealPinNumberLogin");
    let pinnum = await AsyncStorage.getItem("pinnumber");
    let publicaddress = await AsyncStorage.getItem("publicaddress");
          let registerdata = {
            user_address: publicaddress,
          };
          let data = JSON.stringify(registerdata);
          this.setState({
            numbering: pinnum,
            data: data,
          });

          console.log(data);
  }

  //핀번호 일치여부 확인하는 함수.
  onFinishCheckingCode(number, clear) {
    console.log(number);
    if (this.state.numbering !== number) {
      clear();
    }
    if (this.state.numbering === number) {
      BackHandlerRemove();
      this.props.navigation.push("WebView", {
        data: this.state.data
      });
    }
  }

  showCustomAlert(visible) {
    this.setState({ alertVisibility: visible });
  }

  async check() {
    try {
      wallet = await Wallet.fromV3(
        JSON.parse(this.state.keystoredata),
        this.state.password,
        V3_OPTIONS
      );
      this.setState({
        alertVisibility: false
      });
      setDisable();
      setColor("#ffffff");
      this.props.navigation.push("RegisterSecurity", {
        data: this.state.data
      });
    } catch (error) {
      this.setState({
        disabled: false
      });
      alert(error);
    }
  }

  render() {
    return this.state.numbering === "" ? (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Image
          style={{ width: 180, height: 180 }}
          source={require("../../image/logo_name_01.png")}
          resizeMode="contain"
        />
        <View
          style={{
            flexDirection: "column",
            position: "absolute",
            bottom: "30%"
          }}
        >
          <ActivityIndicator size="small" color="#ffd90d" />
        </View>
      </View>
    ) : (
      <SafeAreaView style={styles.container}>

        <View style={styles.realpinloginlayout1}>
          <View style={{ paddingBottom: Platform.OS === "ios" ? "5%" : "10%" }}>
            <Image
              style={{
                resizeMode: "contain"
              }}
              source={require("../../image/realloginpin.png")}
            />
          </View>
          <PinView
            onComplete={this.onFinishCheckingCode.bind(this)}
            pinLength={4}
            inputBgColor="#888888"
            inputActiveBgColor="#ffd90d"
            buttonBgColor="#ffffff"
            buttonTextColor="black"
            keyboardViewStyle={{
              borderColor: "#dfdfdf",
              borderWidth: 1,
              width: windowHeight / 11,
              height: windowHeight / 11
            }}
            inputViewStyle={{ width: 18, height: 18, margin: 18 }}
          />
        </View>
      </SafeAreaView>
    );
  }
}

export default RealPinNumberLogin;

this.props.navigation.push("WebView", {
    data: this.state.data
  });

And that's where the splash screen comes out.

Click this to see the problem screen.

Please Help me a lot

Thanks you in  advance

Body:
I solved this problem by deleting the default splash screen set by Android.

splash_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/splashBackground"/>

    <!--<item><bitmap android:gravity="center" android:src="@drawable/logo_name_01" /></item>-->

</layer-list>


问:
How can I get a large list of followers from a Twitter user and then follow them?
How can I get a list of followers from a Twitter account with a lot of followers? My code is meant to get followers from a user and then follow them but max I can get and follow is 200 with my code and then after 200 it gets new users but way slower. Is there a way to get thousands more?</p>

```<code>import tweepy
from time import sleep

consumer_key = ''
consumer_secret = ''
access_key = ''
access_secret = ''

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)

api = tweepy.API(auth)

users = tweepy.Cursor(api.followers, screen_name='twitter', count=200).items()
count = 0

while True:
    try:
        user = next(users)
        api.create_friendship(user.screen_name)
        sleep(1)
        print(user.screen_name)

    except tweepy.TweepError as e:
        if e.api_code == 161:
            while(count < 901):
                print(count, end='\r')
                sleep(1)
                count +=1
        if e.api_code == 160:
            pass
    except StopIteration:
        pass
</code>```

答:
Twitter documentation says there is a limit of 200 to the count parameter of the api. I would guess that is causing you your trouble.

The number of users to return per page, up to a maximum of 200. Defaults to 20.

Body:
How can I get a list of followers from a Twitter account with a lot of followers? My code is meant to get followers from a user and then follow them but max I can get and follow is 200 with my code and then after 200 it gets new users but way slower. Is there a way to get thousands more?

import tweepy
from time import sleep

consumer_key = ''
consumer_secret = ''
access_key = ''
access_secret = ''

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)

api = tweepy.API(auth)

users = tweepy.Cursor(api.followers, screen_name='twitter', count=200).items()
count = 0

while True:
    try:
        user = next(users)
        api.create_friendship(user.screen_name)
        sleep(1)
        print(user.screen_name)

    except tweepy.TweepError as e:
        if e.api_code == 161:
            while(count < 901):
                print(count, end='\r')
                sleep(1)
                count +=1
        if e.api_code == 160:
            pass
    except StopIteration:
        pass


答:
Check your Twitter rate limits.

Servers normally have a limit on the number of calls you can make to them before they begin to restrict access. The reason for this is that if they let every server ping them 1000+ times a minute, the cost of their servers will be higher and it will make it harder to spot a DNS attack (aggressive servers have a high limit of calls they can make while still looking like non-aggressive servers).

Title: How can I get a large list of followers from a Twitter user and then follow them?


问:
Parsing date form dd-MM-yyyy to dd MMM yyyy
I want to parse dd-MM-yyyy date format into dd MMM yyyy I get the reference but it cannot convert date in a proper manner it mismatches the date and month.

Suppose my date is

```<code>string dat = "11-01-2019"
</code>```

and I am using

```<code>string date = DateTime.Parse(dat).ToString("dd MMM yyyy");
</code>```

but it returns 01 Nov 2019. But actually, it is 11 Jan 2019 because the format of date is dd-MM-yyyy I don't understand how to correct it any method of parsing I am using it returns 01 Nov 2019 that is wrong. Please help me to resolve the issue

答:
Adding to John's great answer, here's a list of CultureInfo codes for reference:
http://www.csharp-examples.net/culture-names/</p>

Body:
I want to parse dd-MM-yyyy date format into dd MMM yyyy I get the reference but it cannot convert date in a proper manner it mismatches the date and month.

Suppose my date is

string dat = "11-01-2019"

and I am using

string date = DateTime.Parse(dat).ToString("dd MMM yyyy");

but it returns 01 Nov 2019. But actually, it is 11 Jan 2019 because the format of date is dd-MM-yyyy I don't understand how to correct it any method of parsing I am using it returns 01 Nov 2019 that is wrong. Please help me to resolve the issue


问:
Json Serialisation adding string element at root
I am using netownsoft json.net to serlize an object but its adding string at the start I dont under stand why its doing this.

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

```<code>public async Task<T> GetDataFromSageService<T>(string url, params string[] args)
where T : class
{
    var uri = new Uri(string.Format(url, args));

    var response = await _client.GetAsync(uri);

        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
        }

        return default(T);
}
</code>```

I am using the following to encode my end point which is hosted in a wcf service.

```<code>public string GetWarehouses()
{
        DataSet ds = new SqlDa().GetWarehouses();
        ds.Tables[0].TableName = "Warehouses";
        return JsonConvert.SerializeObject(ds, Formatting.Indented);
}
</code>```

But the string i am getting back is as such

```<code> <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
{
 "Warehouses": [
 {
 "WarehouseID": 13016489,
 "Name": "B",
 "Description": "Belfast "
 },
 {
 "WarehouseID": 13016647,
 "Name": "B",
 "Description": "B"
 },
 {
 "WarehouseID": 13815467,
 "Name": "Direct Delivery",
 "Description": ""
 },
 {
 "WarehouseID": 1008,
 "Name": "PW",
 "Description": "Postal Way"
 },
 {
 "WarehouseID": 13016234,
 "Name": "H",
 "Description": "Hospital"
 },
 {
 "WarehouseID": 13016238,
 "Name": "MPC",
 "Description": "Clinic"
 },
 {
 "WarehouseID": 13029366,
 "Name": "O",
 "Description": "Outpatient"
 },
 {
 "WarehouseID": 13815466,
 "Name": "Returns",
 "Description": ""
 }
 ]
 }
</string>
</code>```

As You can see its enclosed it as a string for some reason and don't understand as to why. Is their a way with the data set to make sure that it gets converted into proper json.

答:
If you don't want to modify your server code, you could use regex to extract legal json string from your response.</p>

```<code>       string content ="your context with xml"
        Regex regex = new Regex("<string\\s*xmlns=\".*\">([\\s\\S]*)</string>");
       Match match =  regex.Match(content);
        Response.Write(match.Groups[1].Value);
        Newtonsoft.Json.JsonConvert.DeserializeObject(match.Groups[1].Value);
</code>```

Body:
I am using netownsoft json.net to serlize an object but its adding string at the start I dont under stand why its doing this.

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

public async Task<T> GetDataFromSageService<T>(string url, params string[] args)
where T : class
{
    var uri = new Uri(string.Format(url, args));

    var response = await _client.GetAsync(uri);

        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
        }

        return default(T);
}

I am using the following to encode my end point which is hosted in a wcf service.

public string GetWarehouses()
{
        DataSet ds = new SqlDa().GetWarehouses();
        ds.Tables[0].TableName = "Warehouses";
        return JsonConvert.SerializeObject(ds, Formatting.Indented);
}

But the string i am getting back is as such

 <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
{
 "Warehouses": [
 {
 "WarehouseID": 13016489,
 "Name": "B",
 "Description": "Belfast "
 },
 {
 "WarehouseID": 13016647,
 "Name": "B",
 "Description": "B"
 },
 {
 "WarehouseID": 13815467,
 "Name": "Direct Delivery",
 "Description": ""
 },
 {
 "WarehouseID": 1008,
 "Name": "PW",
 "Description": "Postal Way"
 },
 {
 "WarehouseID": 13016234,
 "Name": "H",
 "Description": "Hospital"
 },
 {
 "WarehouseID": 13016238,
 "Name": "MPC",
 "Description": "Clinic"
 },
 {
 "WarehouseID": 13029366,
 "Name": "O",
 "Description": "Outpatient"
 },
 {
 "WarehouseID": 13815466,
 "Name": "Returns",
 "Description": ""
 }
 ]
 }
</string>

As You can see its enclosed it as a string for some reason and don't understand as to why. Is their a way with the data set to make sure that it gets converted into proper json.

Body:
If you don't want to modify your server code, you could use regex to extract legal json string from your response.

       string content ="your context with xml"
        Regex regex = new Regex("<string\\s*xmlns=\".*\">([\\s\\S]*)</string>");
       Match match =  regex.Match(content);
        Response.Write(match.Groups[1].Value);
        Newtonsoft.Json.JsonConvert.DeserializeObject(match.Groups[1].Value);


问:
How to pass a c++ class function as callback
I am having a bit trouble understanding how to pass this to a callback function which is passed to a library. The function needs to have a specific signature.

the library in question is OCILIB (https://vrogier.github.io/ocilib/doc/html/classocilib_1_1_subscription.html) and trying to pass a class function as the 4th parameter of Register().

It is possible for me to pass it as following without problem

&database::callback // a static function of database
```

<p>or</p>

<pre class="lang-c prettyprint-override"><code>[](ocilib::Event &event) // as lambda function
{
}
</code>```

but it does not have the access to instance variables. I tried to use it like

[&](ocilib::Event &event) // as lambda function
{
}
```

<p>but the signature do not match, and I get the following error</p>

```database.cpp: In member function ‘bool dcn::database::watch(std::__cxx11::string)’:
database.cpp:104:44: error: no matching function for call to ‘ocilib::Subscription::Register(ocilib::Connection&, std::__cxx11::string&, ocilib::Subscription::ChangeTypesValues, dcn::database::watch(std::__cxx11::string)::<lambda(ocilib::Event&)>, unsigned int, unsigned int)’
    }, (unsigned int) 7778, (unsigned int) 0);
                                            ^
In file included from /usr/include/ocilib.hpp:9194:0,
                 from /home/ai/dcn/include/main.h:17,
                 from database.cpp:1:
/usr/include/ocilib_impl.hpp:6650:13: note: candidate: void ocilib::Subscription::Register(const ocilib::Connection&, const ostring&, ocilib::Subscription::ChangeTypes, ocilib::Subscription::NotifyHandlerProc, unsigned int, unsigned int)
 inline void Subscription::Register(const Connection &connection, const ostring& name, ChangeTypes changeTypes, NotifyHandlerProc handler, unsigned int port, unsigned int timeout)
             ^~~~~~~~~~~~
/usr/include/ocilib_impl.hpp:6650:13: note:   no known conversion for argument 4 from ‘dcn::database::watch(std::__cxx11::string)::<lambda(ocilib::Event&)>’ to ‘ocilib::Subscription::NotifyHandlerProc {aka void (*)(ocilib::Event&)}’
make[1]: *** [database.o] Error 1
```

<p>function is defined as</p>

```static void callback(ocilib::Event &);
```

Need your help to untangle this. thanks in advance.

答:
That is a horrible API.  Anyone who has a callback function without also asking for a void* is writing code we knew was a bad idea in the 70s.

You have no choice but to use global state to dispatch back to your class.

```<code>template<std::size_t N, class R, class...Args>
struct crappy_api_fix{
  static std::array< std::function<R(Args&&...)>, N >& table(){
    static std::array< std::function<R(Args&&...)>, N > arr;
    return arr;
  }
  template<std::size_t I>
  static R call( Args...args ){ return table()[I]( std::forward<Args>(args)... ); }
  using sig=R(Args...);
  template<std::size_t I=N-1>
  static sig* make(std::function<R(Args&&...)> f){
    if(!table()[I]){
      table()[I]=f;
      return &call<I>;
    }
    if(I==0) return nullptr;
    return make< (I-1)%N >(f);
  }
  template<std::size_t I=N-1>
  static void recycle( sig* f ){
    if (f==call<I>){
      table()[I]={};
      return;
    }
    if (I==0) return;
    recycle< (I-1)%N >( f);
  }
};
</code>```

something like that.  It maintains a global table of N std functions, and returns a function pointer that knows which std function to call.

```<code>// up to 50 callbacks alive at once:
using cb_helper = crappy_api_fix<50, void, ocilib::Event &>;

// "stateless" function pointer wrapping a lambda:
void(*f)(ocilib::Event&) = cb_helper::make([&](ocilib::Event &event) {});

// blah is the API class with the Register method.  We pass the f from above:
blah->Register(arg1, arg2, f, arg4);

// This might be far away fron the above code:
// we should keep copy of the f; when we have unregistered, we shoukd recyle it:
cb_helper::recycle(f); // when `f` is no longer needed
</code>```

Apologies for typos, typing this on my phone.

Body:
I am having a bit trouble understanding how to pass this to a callback function which is passed to a library. The function needs to have a specific signature.

the library in question is OCILIB (https://vrogier.github.io/ocilib/doc/html/classocilib_1_1_subscription.html) and trying to pass a class function as the 4th parameter of Register().

It is possible for me to pass it as following without problem

&database::callback // a static function of database

or

[](ocilib::Event &event) // as lambda function
{
}

but it does not have the access to instance variables. I tried to use it like

[&](ocilib::Event &event) // as lambda function
{
}

but the signature do not match, and I get the following error

database.cpp: In member function ‘bool dcn::database::watch(std::__cxx11::string)’:
database.cpp:104:44: error: no matching function for call to ‘ocilib::Subscription::Register(ocilib::Connection&, std::__cxx11::string&, ocilib::Subscription::ChangeTypesValues, dcn::database::watch(std::__cxx11::string)::<lambda(ocilib::Event&)>, unsigned int, unsigned int)’
    }, (unsigned int) 7778, (unsigned int) 0);
                                            ^
In file included from /usr/include/ocilib.hpp:9194:0,
                 from /home/ai/dcn/include/main.h:17,
                 from database.cpp:1:
/usr/include/ocilib_impl.hpp:6650:13: note: candidate: void ocilib::Subscription::Register(const ocilib::Connection&, const ostring&, ocilib::Subscription::ChangeTypes, ocilib::Subscription::NotifyHandlerProc, unsigned int, unsigned int)
 inline void Subscription::Register(const Connection &connection, const ostring& name, ChangeTypes changeTypes, NotifyHandlerProc handler, unsigned int port, unsigned int timeout)
             ^~~~~~~~~~~~
/usr/include/ocilib_impl.hpp:6650:13: note:   no known conversion for argument 4 from ‘dcn::database::watch(std::__cxx11::string)::<lambda(ocilib::Event&)>’ to ‘ocilib::Subscription::NotifyHandlerProc {aka void (*)(ocilib::Event&)}’
make[1]: *** [database.o] Error 1

function is defined as

static void callback(ocilib::Event &);

Need your help to untangle this. thanks in advance.

Body:
That is a horrible API.  Anyone who has a callback function without also asking for a void* is writing code we knew was a bad idea in the 70s.

You have no choice but to use global state to dispatch back to your class.

template<std::size_t N, class R, class...Args>
struct crappy_api_fix{
  static std::array< std::function<R(Args&&...)>, N >& table(){
    static std::array< std::function<R(Args&&...)>, N > arr;
    return arr;
  }
  template<std::size_t I>
  static R call( Args...args ){ return table()[I]( std::forward<Args>(args)... ); }
  using sig=R(Args...);
  template<std::size_t I=N-1>
  static sig* make(std::function<R(Args&&...)> f){
    if(!table()[I]){
      table()[I]=f;
      return &call<I>;
    }
    if(I==0) return nullptr;
    return make< (I-1)%N >(f);
  }
  template<std::size_t I=N-1>
  static void recycle( sig* f ){
    if (f==call<I>){
      table()[I]={};
      return;
    }
    if (I==0) return;
    recycle< (I-1)%N >( f);
  }
};

something like that.  It maintains a global table of N std functions, and returns a function pointer that knows which std function to call.

// up to 50 callbacks alive at once:
using cb_helper = crappy_api_fix<50, void, ocilib::Event &>;

// "stateless" function pointer wrapping a lambda:
void(*f)(ocilib::Event&) = cb_helper::make([&](ocilib::Event &event) {});

// blah is the API class with the Register method.  We pass the f from above:
blah->Register(arg1, arg2, f, arg4);

// This might be far away fron the above code:
// we should keep copy of the f; when we have unregistered, we shoukd recyle it:
cb_helper::recycle(f); // when `f` is no longer needed

Apologies for typos, typing this on my phone.


问:
How to get svn to ignore symbolic links to folders
I have a project tracked in svn.  On our server, the "index" and "log" folders are symbolic links to folders in a shared directory.  I don't want either of these in svn, and they are causing problems committing and updating:  i get an error doing "svn update" on the server:

Expected 'log' to be a directory but found a file

I tried setting them to be ignored, like

```<code>svn propset svn:ignore index .
svn propset svn:ignore log .
</code>```

But update still breaks, and i can't commit these changes to . because i get this error:

Expected '/ebs/www/apps/e_learning_resource/releases/20110121171004/log' to be a directory but found a file

grateful for any advice - max

答: Sounds like log is already committed in SVN. Delete it (be careful to keep your local link or be ready to recreate it!), commit the deletion, and your ignore should be good from then on.</p>

Body:
I have a project tracked in svn.  On our server, the "index" and "log" folders are symbolic links to folders in a shared directory.  I don't want either of these in svn, and they are causing problems committing and updating:  i get an error doing "svn update" on the server:

Expected 'log' to be a directory but found a file

I tried setting them to be ignored, like

svn propset svn:ignore index .
svn propset svn:ignore log .

But update still breaks, and i can't commit these changes to . because i get this error:

Expected '/ebs/www/apps/e_learning_resource/releases/20110121171004/log' to be a directory but found a file

grateful for any advice - max


问:
Creating signed S3 and Cloudfront URLs via the AWS SDK
Has anyone successfully used the AWS SDK to generate signed URLs to objects in an S3 bucket which also work over CloudFront? I'm using the JavaScript AWS SDK and it's really simple to generate signed URLs via the S3 links. I just created a private bucket and use the following code to generate the URL:

```<code>var AWS = require('aws-sdk')
  , s3 = new AWS.S3()
  , params = {Bucket: 'my-bucket', Key: 'path/to/key', Expiration: 20}

s3.getSignedUrl('getObject', params, function (err, url) {
  console.log('Signed URL: ' + url)
})
</code>```

This works great but I also want to expose a CloudFront URL to my users so they can get the increased download speeds of using the CDN. I setup a CloudFront distribution which modified the bucket policy to allow access. However, after doing this any file could be accessed via the CloudFront URL and Amazon appeared to ignore the signature in my link. After reading some more on this I've seen that people generate a .pem file to get signed URLs working with CloudFront but why is this not necessary for S3? It seems like the getSignedUrl method simply does the signing with the AWS Secret Key and AWS Access Key. Has anyone gotten a setup like this working before?

Update:
After further research it appears that CloudFront handles URL signatures completely different from S3 [link]. However, I'm still unclear as to how to create a signed CloudFront URL using Javascript.

答:
AWS includes some built in classes and structures to assist in the creation of signed URLs and Cookies for CloudFront. I utilized these alongside the excellent answer by Jason Sims to get it working in a slightly different pattern (which appears to be very similar to the NPM package he created).

Namely, the AWS.CloudFront.Signer type description which abstracts the process of creating signed URLs and Cookies.

```<code>export class Signer {
    /**
     * A signer object can be used to generate signed URLs and cookies for granting access to content on restricted CloudFront distributions.
     *
     * @param {string} keyPairId - The ID of the CloudFront key pair being used.
     * @param {string} privateKey - A private key in RSA format.
     */
    constructor(keyPairId: string, privateKey: string);

    ....
}
</code>```

And either an options with a policy JSON string or without a policy with a url and expiration time.

```<code>export interface SignerOptionsWithPolicy {
    /**
     * A CloudFront JSON policy. Required unless you pass in a url and an expiry time.
     */
    policy: string;
}
export interface SignerOptionsWithoutPolicy {
    /**
     * The URL to which the signature will grant access. Required unless you pass in a full policy.
     */
    url: string
    /**
     * A Unix UTC timestamp indicating when the signature should expire. Required unless you pass in a full policy.
     */
    expires: number
}
</code>```

Sample implementation:

```<code>import aws, { CloudFront } from 'aws-sdk';

export async function getSignedUrl() {

    // https://abc.cloudfront.net/my-resource.jpg
    const url = <cloud front url/resource>;

    // Create signer object - requires a public key id and private key value
    const signer = new CloudFront.Signer(<public-key-id>, <private-key>);

    // Setup expiration time (one hour in the future, in this case)
    const expiration = new Date();
    expiration.setTime(expiration.getTime() + 1000 * 60 * 60);
    const expirationEpoch = expiration.valueOf();

    // Set options (Without policy in this example, but a JSON policy string can be substituted)
    const options = {
        url: url,
        expires: expirationEpoch
    };

    return new Promise((resolve, reject) => {
        // Call getSignedUrl passing in options, to be handled either by callback or synchronously without callback
        signer.getSignedUrl(options, (err, url) => {
            if (err) {
                console.error(err.stack);
                reject(err);
            }
            resolve(url);
        });
    });
}
</code>```

Body:
Has anyone successfully used the AWS SDK to generate signed URLs to objects in an S3 bucket which also work over CloudFront? I'm using the JavaScript AWS SDK and it's really simple to generate signed URLs via the S3 links. I just created a private bucket and use the following code to generate the URL:

var AWS = require('aws-sdk')
  , s3 = new AWS.S3()
  , params = {Bucket: 'my-bucket', Key: 'path/to/key', Expiration: 20}

s3.getSignedUrl('getObject', params, function (err, url) {
  console.log('Signed URL: ' + url)
})

This works great but I also want to expose a CloudFront URL to my users so they can get the increased download speeds of using the CDN. I setup a CloudFront distribution which modified the bucket policy to allow access. However, after doing this any file could be accessed via the CloudFront URL and Amazon appeared to ignore the signature in my link. After reading some more on this I've seen that people generate a .pem file to get signed URLs working with CloudFront but why is this not necessary for S3? It seems like the getSignedUrl method simply does the signing with the AWS Secret Key and AWS Access Key. Has anyone gotten a setup like this working before?

Update:
After further research it appears that CloudFront handles URL signatures completely different from S3 [link]. However, I'm still unclear as to how to create a signed CloudFront URL using Javascript.

Body:
AWS includes some built in classes and structures to assist in the creation of signed URLs and Cookies for CloudFront. I utilized these alongside the excellent answer by Jason Sims to get it working in a slightly different pattern (which appears to be very similar to the NPM package he created).

Namely, the AWS.CloudFront.Signer type description which abstracts the process of creating signed URLs and Cookies.

export class Signer {
    /**
     * A signer object can be used to generate signed URLs and cookies for granting access to content on restricted CloudFront distributions.
     *
     * @param {string} keyPairId - The ID of the CloudFront key pair being used.
     * @param {string} privateKey - A private key in RSA format.
     */
    constructor(keyPairId: string, privateKey: string);

    ....
}

And either an options with a policy JSON string or without a policy with a url and expiration time.

export interface SignerOptionsWithPolicy {
    /**
     * A CloudFront JSON policy. Required unless you pass in a url and an expiry time.
     */
    policy: string;
}
export interface SignerOptionsWithoutPolicy {
    /**
     * The URL to which the signature will grant access. Required unless you pass in a full policy.
     */
    url: string
    /**
     * A Unix UTC timestamp indicating when the signature should expire. Required unless you pass in a full policy.
     */
    expires: number
}

Sample implementation:

import aws, { CloudFront } from 'aws-sdk';

export async function getSignedUrl() {

    // https://abc.cloudfront.net/my-resource.jpg
    const url = <cloud front url/resource>;

    // Create signer object - requires a public key id and private key value
    const signer = new CloudFront.Signer(<public-key-id>, <private-key>);

    // Setup expiration time (one hour in the future, in this case)
    const expiration = new Date();
    expiration.setTime(expiration.getTime() + 1000 * 60 * 60);
    const expirationEpoch = expiration.valueOf();

    // Set options (Without policy in this example, but a JSON policy string can be substituted)
    const options = {
        url: url,
        expires: expirationEpoch
    };

    return new Promise((resolve, reject) => {
        // Call getSignedUrl passing in options, to be handled either by callback or synchronously without callback
        signer.getSignedUrl(options, (err, url) => {
            if (err) {
                console.error(err.stack);
                reject(err);
            }
            resolve(url);
        });
    });
}


问:
Using a Pooling Layer in a classical code opencv c++
I would like to use a Pooling Layer from the module opencv2/dnn/ in c (without any link to Deep Learning, I only want to use the Pool function in my code
which get a Mat).

However, I did not find documentation about that.
How can I use the opencv implementation of MaxPooling ?
Thanks

答: Take a look at https://github.com/opencv/opencv/blob/master/modules/dnn/test/test_halide_layers.cpp . There are examples of how to build single layer networks or just run separate layers.</p>