问:
cleanest way to access value from pointer or get its default value if null
I have a pointer to a struct and I want to get either a member of that struct or a default constructed member of that struct if the pointer is null. Is there a nice short way to do this? The only way I can think of implementing something like this atm is with macros

eg:

```<code>#define safe_dereference(X, Y) (X ? X->Y : decltype(X->Y)())
</code>```

this snippet was written in stack overflow and has not been tested

but then I have a macro and I really hate using macros in c++

答:
Just create a function instead of MACRO, something like:

```<code>template <typename C, typename M>
M safe_dereference(const C* c, M (C::*member))
{
    return c ? c->*member : M();
}
</code>```

Call is a little different though:

```<code>safe_dereference(somePointer, &MyClass::MyMember);
</code>```

Body:
I have a pointer to a struct and I want to get either a member of that struct or a default constructed member of that struct if the pointer is null. Is there a nice short way to do this? The only way I can think of implementing something like this atm is with macros

eg:

#define safe_dereference(X, Y) (X ? X->Y : decltype(X->Y)())

this snippet was written in stack overflow and has not been tested

but then I have a macro and I really hate using macros in c++

Body:
Just create a function instead of MACRO, something like:

template <typename C, typename M>
M safe_dereference(const C* c, M (C::*member))
{
    return c ? c->*member : M();
}

Call is a little different though:

safe_dereference(somePointer, &MyClass::MyMember);


来源: stackexchange

问:
google sheets calulation latency and dependant function calls
Here is a function that pupulates a column with a formula:

```<code>function fillAccount(lastRow) {

  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('B1').activate();
  spreadsheet.getCurrentCell().setValue(' ');
  spreadsheet.getRange('B2').activate()
  .setFormula('=ifna(vlookup(C2,Accounts!$A$1:$A$7,1,false),B1)');
  spreadsheet.getRange('B3').activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getRange('B3:B' + lastRow).activate();
  spreadsheet.getRange('B2').copyTo(spreadsheet.getActiveRange(),
  SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
}
</code>```

There is some latency from the time this function completes and all of the rows in column B are populated with the results of the calculation.  I want to execute another function after this one but that function need to have all rows populated before it can execute.  Here is how it would appear in driver script:

```<code>fillAccount(lastrow);
copyAllData(); // this needs to have all rows in column B fully
               // populated.
</code>```

答:
First of all, your function needs a bit of cleanup (it can be done refined further, but that's a start):

```<code>function fillAccount(lastRow) {
  var spreadsheet = getSpread(); //custom method calling the Spreadsheet, change to your logic;

  var colB = spreadsheet.getRange('B1:B'+lastRow);
  var row1 = colB.getCell(1,1);
  var row2 = colB.getCell(2,1);

  row1.setValue(' ');
  row2.setFormula('=ifna(vlookup(C2,RENAMED!$A$1:$A$7,1,false),B1)');
  row2.copyTo(colB.offset(1,0,lastRow-1), SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);

  SpreadsheetApp.flush(); //make sure changes are applied;
}
</code>```

Then, simply call the second function and make sure you access values to ensure calculation (if you have a pretty long latency (e.g. > 1s for each formula calc), some formulas might end up with #ERROR! value - if you want to account for that, add check ==='#ERROR!' that terminates second function upon encountering such a value and recursively restarts it):

```<code>/**
 * Caller function;
 */
function triggerFill() {

  //...your logic and lastRow initialization here;

  fillAccount(lastRow);
  copyAllData();
}

/**
 * Function accessing updated values;
 */
function copyAllData() {
  var spreadsheet = getSpread(); //custom method calling the Spreadsheet, change to your logic;
  var dataRange = spreadsheet.getDataRange(); //just an example that gets all data;
  var values = dataRange.getValues(); //just an example that gets all values;
  for(var i=0; i<values.length; i++) {
    if(values[i].indexOf('#ERROR!')!==-1) { //for high latency;
      Utilities.sleep(t) //change t to number of ms to wait to your liking;
      return copyAllData();
    }
  }

  //do other stuff, like cell copy;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is a function that pupulates a column with a formula:

function fillAccount(lastRow) {

  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('B1').activate();
  spreadsheet.getCurrentCell().setValue(' ');
  spreadsheet.getRange('B2').activate()
  .setFormula('=ifna(vlookup(C2,Accounts!$A$1:$A$7,1,false),B1)');
  spreadsheet.getRange('B3').activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getRange('B3:B' + lastRow).activate();
  spreadsheet.getRange('B2').copyTo(spreadsheet.getActiveRange(),
  SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
}

There is some latency from the time this function completes and all of the rows in column B are populated with the results of the calculation.  I want to execute another function after this one but that function need to have all rows populated before it can execute.  Here is how it would appear in driver script:

fillAccount(lastrow);
copyAllData(); // this needs to have all rows in column B fully
               // populated.

Body:
First of all, your function needs a bit of cleanup (it can be done refined further, but that's a start):

function fillAccount(lastRow) {
  var spreadsheet = getSpread(); //custom method calling the Spreadsheet, change to your logic;

  var colB = spreadsheet.getRange('B1:B'+lastRow);
  var row1 = colB.getCell(1,1);
  var row2 = colB.getCell(2,1);

  row1.setValue(' ');
  row2.setFormula('=ifna(vlookup(C2,RENAMED!$A$1:$A$7,1,false),B1)');
  row2.copyTo(colB.offset(1,0,lastRow-1), SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);

  SpreadsheetApp.flush(); //make sure changes are applied;
}

Then, simply call the second function and make sure you access values to ensure calculation (if you have a pretty long latency (e.g. > 1s for each formula calc), some formulas might end up with #ERROR! value - if you want to account for that, add check ==='#ERROR!' that terminates second function upon encountering such a value and recursively restarts it):

/**
 * Caller function;
 */
function triggerFill() {

  //...your logic and lastRow initialization here;

  fillAccount(lastRow);
  copyAllData();
}

/**
 * Function accessing updated values;
 */
function copyAllData() {
  var spreadsheet = getSpread(); //custom method calling the Spreadsheet, change to your logic;
  var dataRange = spreadsheet.getDataRange(); //just an example that gets all data;
  var values = dataRange.getValues(); //just an example that gets all values;
  for(var i=0; i<values.length; i++) {
    if(values[i].indexOf('#ERROR!')!==-1) { //for high latency;
      Utilities.sleep(t) //change t to number of ms to wait to your liking;
      return copyAllData();
    }
  }

  //do other stuff, like cell copy;
}


问:
Converting Python Keras NLP Model to Tensorflowjs
I'm trying to learn more about Tensorflowjs, but sadly I'm stuck getting my Keras NLP Model converted to Tensorflowjs.

This is what I'm trying to convert:

```<code>from keras.models import load_model

from keras.preprocessing.sequence import pad_sequences

import pickle

list_classes = ["toxic", "severe_toxic", "obscene", "threat", "insult", "identity_hate"]

model = load_model('Keras_Model/m.hdf5')
with open('Keras_Model/tokenizer.pkl', 'rb') as handler:
    tokenizer = pickle.load(handler)

list_sentences_train = ["I need help Stackoverflow"]

list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)
maxlen = 200
X_t = pad_sequences(list_tokenized_train, maxlen=maxlen)

pred = model.predict(X_t)[0]
</code>```

Tensorflowjs side:

```<code>import tf = require('@tensorflow/tfjs-node')

async function processModel(){
  const model = await tf.loadLayersModel('Server_Model/model.json');
}
</code>```

How I can get the Tokenizer running and make correct predictions?

答:
Actually, I ran into the same problem while classifying text on Android. I had the model ( tflite ) ready to use, but how can I tokenize the sentences just as Keras did in Python.

I found a simple solution which I have discussed here ( for Android ).

The simple idea is to convert the keras.preprocessing.text.Tokenizer
  vocabulary to a JSON file. This JSON file could be parsed in any of
  the programming languages including JavaScript.

The Tokenizer holds a object called word_index.

```<code>index = tokenizer.word_index
</code>```

The word_index object is a dict which can be converted to JSON like,

```<code>import json
with open( 'word_dict.json' , 'w' ) as file:
    json.dump( tokenizer.word_index , file )
</code>```

The JSON file contains pairs of words and indexes. You can parse it in JavaScript as mentioned in this link.

Body:
I'm trying to learn more about Tensorflowjs, but sadly I'm stuck getting my Keras NLP Model converted to Tensorflowjs.

This is what I'm trying to convert:

from keras.models import load_model

from keras.preprocessing.sequence import pad_sequences

import pickle

list_classes = ["toxic", "severe_toxic", "obscene", "threat", "insult", "identity_hate"]

model = load_model('Keras_Model/m.hdf5')
with open('Keras_Model/tokenizer.pkl', 'rb') as handler:
    tokenizer = pickle.load(handler)

list_sentences_train = ["I need help Stackoverflow"]

list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)
maxlen = 200
X_t = pad_sequences(list_tokenized_train, maxlen=maxlen)

pred = model.predict(X_t)[0]

Tensorflowjs side:

import tf = require('@tensorflow/tfjs-node')

async function processModel(){
  const model = await tf.loadLayersModel('Server_Model/model.json');
}

How I can get the Tokenizer running and make correct predictions?

Body:
Actually, I ran into the same problem while classifying text on Android. I had the model ( tflite ) ready to use, but how can I tokenize the sentences just as Keras did in Python.

I found a simple solution which I have discussed here ( for Android ).

The simple idea is to convert the keras.preprocessing.text.Tokenizer
  vocabulary to a JSON file. This JSON file could be parsed in any of
  the programming languages including JavaScript.

The Tokenizer holds a object called word_index.

index = tokenizer.word_index

The word_index object is a dict which can be converted to JSON like,

import json
with open( 'word_dict.json' , 'w' ) as file:
    json.dump( tokenizer.word_index , file )

The JSON file contains pairs of words and indexes. You can parse it in JavaScript as mentioned in this link.


问:
Python cx_Oracle loading CSV using executemany() gives "Required argument 'parameters' (pos 2) not found"
My intention is to load the csv file in a Oracle table using Python.

I'm truncating table, if data already exists - This is working

I'm checking the count for testing purpose - This is working

I'm trying to Insert data from file in to Oracle. I'm getting issue:

'Required argument 'parameters' (pos 2) not found'

Code:

```<code>import cx_Oracle
import pandas as pd

column_names =
['Col1','Col2','Col3','Col4','Col5','Col6','Col7','Col8','Col9']
df = pd.read_csv(r"C:\Users\file.dat", names=column_names, sep='|')

dsn_tns = cx_Oracle.makedsn('*', '*', sid='*')
conn = cx_Oracle.connect(user='*', password='*', dsn=*)
c = conn.cursor()
c.execute('Truncate table Table_Name')
c.execute('select count(1) from Table_Name')
for row in c:
print(row)
for lines in df:
c = conn.cursor()
print("I want to print lines")
res = c.executemany("""Insert into Code_Extract (OPERATION,
                 LIST_COUNTRY_ID,LIST_CODE,SOURCE_SYSTEM_CODE,CODE_USUAL,
                   INT_LIST_CODE,INT_MDM_CODE,CODE_STATUS,MDM_CODE)
                   Values(df['col1'],df['Col2'],df['Col3'],df['Col4'],df['Col5'],df['Col6'],df['Col7'],df['Col8'],df['Col9'])""")
conn.commit()
c.execute('select count(1) from Table_Name')
for row in c:
    print(row)
c.close()
conn.commit()
conn.close()
</code>```

My expectation is whenever I receive files it should be automatically loaded in to Oracle from the specified path.

答:
The parameters to executemany() are indeed required. See the documentation for more information.

You've put the parameters inside the SQL, but instead they should be specified as bind variables, as in values (:1, :2, :3, :4, :5, :6, :7, :8, :9). You would then pass the data as a list of sequences to executemany(). Hopefully that's clear! You can see an example here.

Body:
My intention is to load the csv file in a Oracle table using Python.

I'm truncating table, if data already exists - This is working

I'm checking the count for testing purpose - This is working

I'm trying to Insert data from file in to Oracle. I'm getting issue:

'Required argument 'parameters' (pos 2) not found'

Code:

import cx_Oracle
import pandas as pd

column_names =
['Col1','Col2','Col3','Col4','Col5','Col6','Col7','Col8','Col9']
df = pd.read_csv(r"C:\Users\file.dat", names=column_names, sep='|')

dsn_tns = cx_Oracle.makedsn('*', '*', sid='*')
conn = cx_Oracle.connect(user='*', password='*', dsn=*)
c = conn.cursor()
c.execute('Truncate table Table_Name')
c.execute('select count(1) from Table_Name')
for row in c:
print(row)
for lines in df:
c = conn.cursor()
print("I want to print lines")
res = c.executemany("""Insert into Code_Extract (OPERATION,
                 LIST_COUNTRY_ID,LIST_CODE,SOURCE_SYSTEM_CODE,CODE_USUAL,
                   INT_LIST_CODE,INT_MDM_CODE,CODE_STATUS,MDM_CODE)
                   Values(df['col1'],df['Col2'],df['Col3'],df['Col4'],df['Col5'],df['Col6'],df['Col7'],df['Col8'],df['Col9'])""")
conn.commit()
c.execute('select count(1) from Table_Name')
for row in c:
    print(row)
c.close()
conn.commit()
conn.close()

My expectation is whenever I receive files it should be automatically loaded in to Oracle from the specified path.


问:
create RSA SHA256 using crypto for jsonwebtoken on nodejs
I see how to create HMAC 256 encrypted JWTs in NodeJS using Crypto, and the jsonwebtoken library. It's pretty easy

```<code>    //encrypt & sign with HS256
    const jwt   = require('jsonwebtoken');
    const pass  = crypto.randomBytes(256).toString('hex');
    const A     = {algorithm:'HS256'};

    const token = jwt.sign({ foo: 'bar' }, pass, A);

   //decrypt & verify
   jwt.verify(token, pass, A, function(err, decoded)
   {
      console.log('decode ',decoded);
      console.log('err    ',err);

      res.send({error:err, text:decoded});
   });
</code>```

I would like to replace 'pass' with an 'RSA 256 SHA', and A with {algorithm:'RS256'}

In node crypto JS's documentation I see the command

```<code>const sign = crypto.createSign('RSA-SHA256');
</code>```

to create the rsa-sha256

However then the documentation has the function

```<code>getPrivateKeySomehow()
</code>```

Which is not defined or part of crypto.getPrivateKeySomehow()

So I guess I just need help getting the RSA-SHA-256 string returned from crypto, so that I can pass that into jsonwebtoken to sign my JWT.

Note: I do not want to read a private.key from a static file on my server because i see having a single private key for all my users as too big a security risk, hence why i am generating my own 256 bytes passwords and storing them off-site (not included in this post)

also, i'm not sure if i should do something like this (without using something like openssl from command line?)

```<code>const begin = '-----BEGIN RSA PRIVATE KEY-----\n';
const enc   = crypto.randomBytes(256).toString('base64') + '\n';
const end   = '-----END RSA PRIVATE KEY-----'
const pass = sign.sign(begin + enc + end);
const A = {algorithm:'RS256'};
const token = jwt.sign({ foo: 'bar' }, pass, A);
</code>```

答:
Take a look at this example bellow:

```<code>signExample = (str) => {
    crypto.generateKeyPair('rsa', {
        modulusLength: 1024,
        publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
        },
        privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem'
        }
    }, (err, publicKey, privateKey) => {
        // sign String
        var signerObject = crypto.createSign("RSA-SHA256");
        signerObject.update(str);
        var signature = signerObject.sign({key:privateKey,padding:crypto.constants.RSA_PKCS1_PSS_PADDING}, "base64");
        console.info("signature: %s", signature);
        //verify String
        var verifierObject = crypto.createVerify("RSA-SHA256");
        verifierObject.update(str);
        var verified = verifierObject.verify({key:publicKey, padding:crypto.constants.RSA_PKCS1_PSS_PADDING}, signature, "base64");
        console.info("is signature ok?: %s", verified);
    });
}
</code>```

Steps:

First you create an key pair with crypto.generateKeyPair('rsa', { ... desired key options

Create a Sign object - crypto.createSign("RSA-SHA256")

The string wanted to be signed - SignerObject.update(str)

Sign the string with your private key - signerObject.sign(

Option to salt - padding:crypto.constants.RSA_PKCS1_PSS_PADDING

Body:
I see how to create HMAC 256 encrypted JWTs in NodeJS using Crypto, and the jsonwebtoken library. It's pretty easy

    //encrypt & sign with HS256
    const jwt   = require('jsonwebtoken');
    const pass  = crypto.randomBytes(256).toString('hex');
    const A     = {algorithm:'HS256'};

    const token = jwt.sign({ foo: 'bar' }, pass, A);

   //decrypt & verify
   jwt.verify(token, pass, A, function(err, decoded)
   {
      console.log('decode ',decoded);
      console.log('err    ',err);

      res.send({error:err, text:decoded});
   });

I would like to replace 'pass' with an 'RSA 256 SHA', and A with {algorithm:'RS256'}

In node crypto JS's documentation I see the command

const sign = crypto.createSign('RSA-SHA256');

to create the rsa-sha256

However then the documentation has the function

getPrivateKeySomehow()

Which is not defined or part of crypto.getPrivateKeySomehow()

So I guess I just need help getting the RSA-SHA-256 string returned from crypto, so that I can pass that into jsonwebtoken to sign my JWT.

Note: I do not want to read a private.key from a static file on my server because i see having a single private key for all my users as too big a security risk, hence why i am generating my own 256 bytes passwords and storing them off-site (not included in this post)

also, i'm not sure if i should do something like this (without using something like openssl from command line?)

const begin = '-----BEGIN RSA PRIVATE KEY-----\n';
const enc   = crypto.randomBytes(256).toString('base64') + '\n';
const end   = '-----END RSA PRIVATE KEY-----'
const pass = sign.sign(begin + enc + end);
const A = {algorithm:'RS256'};
const token = jwt.sign({ foo: 'bar' }, pass, A);

Body:
Take a look at this example bellow:

signExample = (str) => {
    crypto.generateKeyPair('rsa', {
        modulusLength: 1024,
        publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
        },
        privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem'
        }
    }, (err, publicKey, privateKey) => {
        // sign String
        var signerObject = crypto.createSign("RSA-SHA256");
        signerObject.update(str);
        var signature = signerObject.sign({key:privateKey,padding:crypto.constants.RSA_PKCS1_PSS_PADDING}, "base64");
        console.info("signature: %s", signature);
        //verify String
        var verifierObject = crypto.createVerify("RSA-SHA256");
        verifierObject.update(str);
        var verified = verifierObject.verify({key:publicKey, padding:crypto.constants.RSA_PKCS1_PSS_PADDING}, signature, "base64");
        console.info("is signature ok?: %s", verified);
    });
}

Steps:

First you create an key pair with crypto.generateKeyPair('rsa', { ... desired key options

Create a Sign object - crypto.createSign("RSA-SHA256")

The string wanted to be signed - SignerObject.update(str)

Sign the string with your private key - signerObject.sign(

Option to salt - padding:crypto.constants.RSA_PKCS1_PSS_PADDING


问:
How to set the global environment variable from jenkins pipeline
I would like to ask if there would be a shortcut way to set the global environment variables generated by aws sts assume-role on one jenkins pipeline. My aim is to have these generated values (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN) reusable to the 3 stage steps on one jenkins pipeline. Currently I have this setup on my stages though I find it too messy and I would like to know if youy can suggest me a better way to set the global variables. My current Pipeline looks like this:

```<code>   pipeline {
   agent any
   stages {
          stage ('S3 CHECK') {
              steps {
                 sh '''
                 unset AWS_SESSION_TOKEN
                 unset AWS_SECRET_ACCESS_KEY
                 unset AWS_ACCESS_KEY_ID
</code>```

```<code>                CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

                export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
                export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
                export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`
                aws s3 ls
                '''
              }
           }
           stage ('CHECK AVAILABLE BEANSTALK PLATFORMS') {
              steps {
                 sh '''
                 unset AWS_SESSION_TOKEN
                 unset AWS_SECRET_ACCESS_KEY
                 unset AWS_ACCESS_KEY_ID

                        CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

                export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
                export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
                export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`
                aws elasticbeanstalk describe-environment-resources --environment-name pogi
                aws elasticbeanstalk list-platform-versions
                '''
              }
           }
           stage ('BEANSTALK CHECK') {
              steps {
                 sh '''
                 unset AWS_SESSION_TOKEN
                 unset AWS_SECRET_ACCESS_KEY
                 unset AWS_ACCESS_KEY_ID

                        CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

                export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
                export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
                export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`
                aws elasticbeanstalk describe-environment-resources --environment-name pogi
                '''
              }
           }
    }
</code>```

}

I really want to elimate on placing this per stage to make the format more clean

```<code>                 unset AWS_SESSION_TOKEN
                 unset AWS_SECRET_ACCESS_KEY
                 unset AWS_ACCESS_KEY_ID

                        CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

                export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
                export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
                export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`
                aws elasticbeanstalk describe-environment-resources --environment-name pogi
</code>```

答:
You can extract out this into a bash file and then use source <bash-file>.sh in each stage.

For example you can call the file init.sh and have the following content:

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

unset AWS_SESSION_TOKEN
unset AWS_SESSION_TOKEN
unset AWS_SECRET_ACCESS_KEY
unset AWS_ACCESS_KEY_ID

CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`
</code>```

For example, this way the CHECK AVAILABLE BEANSTALK PLATFORMS stage would become the following:

source init.sh

aws elasticbeanstalk describe-environment-resources --environment-name pogi
aws elasticbeanstalk list-platform-versions
```

<p>And if different stages has some variables, you can use something like <code>source init.sh var1 var2</code> and <code>var1</code> would be <code>$1</code> in <code>init.sh</code> and <code>var2</code> would be <code>$2</code>.</p>

<p>As an aside, you can get rid of the <code>jq</code> dep and just use <code>awk</code> instead. This is for MFA (but the same approach can be used for assume-role) using AWS <code>text</code> format instead of JSON.</p>

<pre class="lang-sh prettyprint-override"><code># output format "CREDENTIALS <spaces> <access-key-id> <expiry> <secret-access-key> <session-token>"
CREDENTIALS=`aws sts get-session-token --output text \
  --serial-number <mfa-arn> \
  --token-code <otp> \
  --duration-seconds 43200`

export AWS_ACCESS_KEY_ID=$(echo $CREDENTIALS | awk '{print $2}')
export AWS_SECRET_ACCESS_KEY=$(echo $CREDENTIALS | awk '{print $4}')
export AWS_SESSION_TOKEN=$(echo $CREDENTIALS | awk '{print $5}')
</code>```

Body:
I would like to ask if there would be a shortcut way to set the global environment variables generated by aws sts assume-role on one jenkins pipeline. My aim is to have these generated values (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN) reusable to the 3 stage steps on one jenkins pipeline. Currently I have this setup on my stages though I find it too messy and I would like to know if youy can suggest me a better way to set the global variables. My current Pipeline looks like this:

   pipeline {
   agent any
   stages {
          stage ('S3 CHECK') {
              steps {
                 sh '''
                 unset AWS_SESSION_TOKEN
                 unset AWS_SECRET_ACCESS_KEY
                 unset AWS_ACCESS_KEY_ID

                CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

                export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
                export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
                export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`
                aws s3 ls
                '''
              }
           }
           stage ('CHECK AVAILABLE BEANSTALK PLATFORMS') {
              steps {
                 sh '''
                 unset AWS_SESSION_TOKEN
                 unset AWS_SECRET_ACCESS_KEY
                 unset AWS_ACCESS_KEY_ID

                        CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

                export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
                export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
                export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`
                aws elasticbeanstalk describe-environment-resources --environment-name pogi
                aws elasticbeanstalk list-platform-versions
                '''
              }
           }
           stage ('BEANSTALK CHECK') {
              steps {
                 sh '''
                 unset AWS_SESSION_TOKEN
                 unset AWS_SECRET_ACCESS_KEY
                 unset AWS_ACCESS_KEY_ID

                        CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

                export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
                export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
                export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`
                aws elasticbeanstalk describe-environment-resources --environment-name pogi
                '''
              }
           }
    }

}

I really want to elimate on placing this per stage to make the format more clean

                 unset AWS_SESSION_TOKEN
                 unset AWS_SECRET_ACCESS_KEY
                 unset AWS_ACCESS_KEY_ID

                        CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

                export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
                export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
                export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`
                aws elasticbeanstalk describe-environment-resources --environment-name pogi

Body:
You can extract out this into a bash file and then use source <bash-file>.sh in each stage.

For example you can call the file init.sh and have the following content:

#!/usr/bin/env bash

unset AWS_SESSION_TOKEN
unset AWS_SESSION_TOKEN
unset AWS_SECRET_ACCESS_KEY
unset AWS_ACCESS_KEY_ID

CREDENTIALS=`aws sts assume-role --role-arn arn:aws:iam::0123456789123:role/POGI --role-session-name RoleSession`

export AWS_ACCESS_KEY_ID=`echo $CREDENTIALS | jq -r '.Credentials.AccessKeyId'`
export AWS_SECRET_ACCESS_KEY=`echo $CREDENTIALS | jq -r '.Credentials.SecretAccessKey'`
export AWS_SESSION_TOKEN=`echo $CREDENTIALS | jq -r '.Credentials.SessionToken'`

For example, this way the CHECK AVAILABLE BEANSTALK PLATFORMS stage would become the following:

source init.sh

aws elasticbeanstalk describe-environment-resources --environment-name pogi
aws elasticbeanstalk list-platform-versions

And if different stages has some variables, you can use something like source init.sh var1 var2 and var1 would be $1 in init.sh and var2 would be $2.

As an aside, you can get rid of the jq dep and just use awk instead. This is for MFA (but the same approach can be used for assume-role) using AWS text format instead of JSON.

# output format "CREDENTIALS <spaces> <access-key-id> <expiry> <secret-access-key> <session-token>"
CREDENTIALS=`aws sts get-session-token --output text \
  --serial-number <mfa-arn> \
  --token-code <otp> \
  --duration-seconds 43200`

export AWS_ACCESS_KEY_ID=$(echo $CREDENTIALS | awk '{print $2}')
export AWS_SECRET_ACCESS_KEY=$(echo $CREDENTIALS | awk '{print $4}')
export AWS_SESSION_TOKEN=$(echo $CREDENTIALS | awk '{print $5}')


问:
I am trying to get the Seconds since midnight: 86339
I am trying to get the Seconds since midnight:  86339

I tried writing a program and i get the results

Enter hour:11
Enter minute:58
Enter second:59
Enter frame:PM
Seconds since midnight: 43139
```

```hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = raw_input("Enter frame:")

time = ( 3600 * hour + minute * 60 + second )
print "Seconds since midnight:",time
```

<p>This is the actual results i want to produce </p>

<pre class="lang-none prettyprint-override"><code>Enter hour: 11
Enter minute: 58
Enter second: 59
Enter AM or PM: PM
Seconds since midnight:  86339
</code>```

Enter hour: 12
Enter minute: 7
Enter second: 20
Enter AM or PM: AM
Seconds since midnight: 440

Enter hour: 12
Enter minute: 14
Enter second: 57
Enter AM or PM: PM
Seconds since midnight: 44097

答:
PM needs to add 12 hours

Python 2.X :

```<code>hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = input("Enter frame:")

time = ( 3600 * hour +  minute* 60 + second )
if frame == "PM":
    time += 12 * 60 * 60
print "Seconds since midnight:",time
</code>```

Python 3.x:

```<code>hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = input("Enter frame:")

time = ( 3600 *int( hour) + int( minute)* 60 + int( second ))
if frame == "PM":
    time += 12 * 60 * 60
print("Seconds since midnight:",time)
</code>```

Body:
I am trying to get the Seconds since midnight:  86339

I tried writing a program and i get the results

Enter hour:11
Enter minute:58
Enter second:59
Enter frame:PM
Seconds since midnight: 43139

hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = raw_input("Enter frame:")

time = ( 3600 * hour + minute * 60 + second )
print "Seconds since midnight:",time

This is the actual results i want to produce

Enter hour: 11
Enter minute: 58
Enter second: 59
Enter AM or PM: PM
Seconds since midnight:  86339

Enter hour: 12
Enter minute: 7
Enter second: 20
Enter AM or PM: AM
Seconds since midnight: 440

Enter hour: 12
Enter minute: 14
Enter second: 57
Enter AM or PM: PM
Seconds since midnight: 44097

Body:
PM needs to add 12 hours

Python 2.X :

hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = input("Enter frame:")

time = ( 3600 * hour +  minute* 60 + second )
if frame == "PM":
    time += 12 * 60 * 60
print "Seconds since midnight:",time

Python 3.x:

hour = input("Enter hour:")
minute = input("Enter minute:")
second = input("Enter second:")
frame = input("Enter frame:")

time = ( 3600 *int( hour) + int( minute)* 60 + int( second ))
if frame == "PM":
    time += 12 * 60 * 60
print("Seconds since midnight:",time)


问:
what kind of replication should I use?
I can't understand the difference between transactional replication and merge replication.
This is my scenario:
In an organization I have a SQL server which need to collect information from different sql servers which are located in different parts of organization or around the city and some report will create according to gathered information.
Data in different SQL servers update every 5 or 6 minutes.
I don't know should I use transactional or merge replication?</p>

答:
Transactional replication delivers incremental changes from a single publisher to one or more subscribers.

Merge replication brings changes from multiple subcribers together into a central publisher.

It sounds like you'll want merge replication in your scenario.

ContentLicense: CC BY-SA 3.0

Title: what kind of replication should I use?


问:
LORA Sx1276 send same response in every condition
I am usign one of Dorji's pruduct. The products name is DRF1276DM. The image of the product can seen in following images

In the application note the producers state that the module can communicate over serial port with TTL level UART. In their  application note which can be found at http://www.dorji.com/docs/data/DRF1278DM.pdf. They state that if we send a command like AF AF 00 00 AF 80 03 02 00 00 92 0D 0A  the device will response as  AF AF 00 00 AF 00 03 02 00 00 12 0D 0A I try to check this command in order to test the device but I receive same command in my all trial. The device send me that 2400  O 8 1 DRF128X V2.7. In the application note they state that the device will send only one time this command when power is one but In my case the response is always same regardless to command code.

For checking the condition I try to use every command on http://www.dorji.com/docs/data/DRF1278DM.pdf but I recieved same respond. My first question is this. Are there any one who deal with same problem with me or could you give me any solution for this case. I am suspicious that the device get reset in every time when I try to send command over serial port. Is there any way to reset the device to default either using software or hardware.

In the application note they state that the first respond which I quoted above, will give the information for communcating device In our case I expected to communicate with device on odd parity 8 bit data size 2400 baud rate but the device only gives irrelevant or nonlogical bytes in 2400 baud rate. Only logical answer I received from device is on the 9600 baud rate. My second question is this. Is there a bug on this device setting or did I miss someting because as far as I know we cannot communicate with devices over multiple baud rate option.

PS:
I try to use their configuration tool which can be found in http://www.dorji.com/products-detail.php?ProId=61, but I got same "time out"

Error from device, I used 2400 boud rate and even parity but the result cannot changed.

答: I had this problem too, my issue was the EN pin needs to be pulled low. Even with the USB to UART adapter I bought with the modules, that line is allowed to site high by default. Use a jumper to pull it to ground.</p>


问:
Command to make my bot leave a specific guild: discord.py rewrite
I want to make a command to make the bot leave a specific guild. Usage would be -leave [guild]

I don't really know what to try out, but I've messed with some of the arguments a bit; did nothing

@commands.command(hidden=True)
@commands.is_owner()
async def leave(self, ctx, guild: discord.Guild):
    await self.bot.leave_guild(guild)
    await ctx.send(f":ok_hand: Left guild: {guild.name} ({guild.id})")
```

<p>I'm getting the following error: </p>

```AttributeError: module 'discord.ext.commands.converter' has no attribute 'GuildConverter'
```

I'd like the bot to leave the guild and send a confirmation message shown in the code

答:
There is no built in converter for guilds, so you'll have to do it yourself:</p>

```<code>@commands.command()
@commands.is_owner()
async def leave(self, ctx, *, guild_name):
    guild = discord.utils.get(self.bot.guilds, name=guild_name)
    if guild is None:
        await ctx.send("I don't recognize that guild.")
        return
    await self.bot.leave_guild(guild)
    await ctx.send(f":ok_hand: Left guild: {guild.name} ({guild.id})")
</code>```

Body:
I want to make a command to make the bot leave a specific guild. Usage would be -leave [guild]

I don't really know what to try out, but I've messed with some of the arguments a bit; did nothing

@commands.command(hidden=True)
@commands.is_owner()
async def leave(self, ctx, guild: discord.Guild):
    await self.bot.leave_guild(guild)
    await ctx.send(f":ok_hand: Left guild: {guild.name} ({guild.id})")

I'm getting the following error:

AttributeError: module 'discord.ext.commands.converter' has no attribute 'GuildConverter'

I'd like the bot to leave the guild and send a confirmation message shown in the code

Body:
There is no built in converter for guilds, so you'll have to do it yourself:

@commands.command()
@commands.is_owner()
async def leave(self, ctx, *, guild_name):
    guild = discord.utils.get(self.bot.guilds, name=guild_name)
    if guild is None:
        await ctx.send("I don't recognize that guild.")
        return
    await self.bot.leave_guild(guild)
    await ctx.send(f":ok_hand: Left guild: {guild.name} ({guild.id})")


问:
Why does my MSI prompt for administrator rights?
I'm trying get our MSI working for non-admin users.

I'm using WixUI_Advanced, but I'm still getting an admin prompt even when I select "Install just for you":

Looking at the MSI logs I can see that elevation is required, but I don't know why:

```<code>MSI (s) (68:54) [10:45:25:359]: Product not registered: beginning first-time install
MSI (s) (68:54) [10:45:25:359]: PROPERTY CHANGE: Deleting ALLUSERS property. Its current value is '1'.
MSI (s) (68:54) [10:45:25:359]: Product {32799511-D146-40F4-ACA7-5A76E6E38854} is not managed.
MSI (s) (68:54) [10:45:25:359]: Machine policy value 'AlwaysInstallElevated' is 0
MSI (s) (68:54) [10:45:25:359]: User policy value 'AlwaysInstallElevated' is 0
MSI (s) (68:54) [10:45:25:359]: MSI_LUA: Elevation required to install product, will prompt for credentials
</code>```

Any idea why I'm getting prompted for admin rights?

Edit

I created an empty Wix project, used the WixUI_Advanced UI, and I'm getting the same issue :/

答:
Admin Rights Prompt: In the WiX sample below, elevation will be requested and required for per-machine installation, but not for per-user installation.

Heads-Up: I personally do not like per-user setups. I find them to be borderline anti-patterns in my subjective opinion. It relates to poor serviceability (upgrades, patching, etc...) and a number of other details such as dubious folder redirects and some other "high-astonishment" factors. There are also a number of restrictions summarized nicely by the Advanced Installer guys: Advanced Installer: per-user setup limitations.

WiX Issue 5481: I added an answer, but deleted it. It didn't work properly. I had a look in the WiX Issues database and this is a known issue: https://github.com/wixtoolset/issues/issues/5481. The last comment from NicMay looked interesting. I made a quick mock-up below incorporating his / her suggestions with some modifications.

Disclaimer: The below sample has a number of defects, and is only intended as a "runnable sample". There are issues with MSI validation due to the shortcut quick-solution I used (use the shortcut to see where the file installed, right click and go "Properties"). The "Create New Folder" button in the custom installation dialog also has a bug. I will still post it to see if it helps you:

NB!: Create new WiX project, add reference to WixUIExtension.dll, then follow comments. Run setup and click "Advanced" to select per-user or per-machine install.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">

<!--CHANGE #1: Add an UpgradeCode GUID below -->

  <Product Id="*" Name="PerUserOrPerMachine" Language="1033" Version="1.0.0.0"
           Manufacturer="Hobbit" UpgradeCode="PUT-GUID-HERE">
    <Package InstallerVersion="200" Compressed="yes" />

    <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
    <MediaTemplate EmbedCab="yes" />
    <Feature Id="ProductFeature" Title="PerUserOrPerMachine" Level="1" />

<!--CHANGE #2: Here we channel "hacker" NicMay with his / her dialog event tweaks mentioned in the WiX issue 5481 -->

    <UI>
      <UIRef Id="WixUI_Advanced" />
      <Publish Dialog="InstallScopeDlg" Control="Next" Property="MSIINSTALLPERUSER" Value="1" Order="3">WixAppFolder = "WixPerUserFolder"</Publish>
      <Publish Dialog="InstallScopeDlg" Control="Next" Property="MSIINSTALLPERUSER" Value="{}" Order="2">WixAppFolder = "WixPerMachineFolder"</Publish>
      <Publish Dialog="InstallScopeDlg" Control="Next" Event="DoAction" Value="WixSetDefaultPerMachineFolder" Order="3">WixAppFolder = "WixPerMachineFolder"</Publish>
      <Publish Dialog="InstallScopeDlg" Control="Next" Event="DoAction" Value="WixSetDefaultPerUserFolder" Order="3">WixAppFolder = "WixPerUserFolder"</Publish>
    </UI>

    <Property Id="ApplicationFolderName" Value="PerUserPerMachine" />
    <Property Id="WixAppFolder" Value="WixPerMachineFolder" />

<!--CHANGE #3: Add components and files as appropriate -->

    <Directory Id="TARGETDIR" Name="SourceDir">

<!--CHANGE #4: Make sure DesktopFolder is defined -->

      <Directory Id="DesktopFolder" />
      <Directory Id="ProgramFilesFolder">

<!--CHANGE #5: Crucial: Make sure Directory Id is APPLICATIONFOLDER (referenced elsewhere) -->

        <Directory Id="APPLICATIONFOLDER" Name="PerUserOrPerMachine">
          <Component Feature="ProductFeature" Guid="{5A74A1EE-0AD3-4C48-9E6B-4E4E3712A8BB}">

<!--CHANGE #6: Hard coded path below for simplicity, change path or replace construct -->

            <File Source="D:\My Test Files\MyTestApplication.exe">
              <Shortcut Id="AppDesktopShortcut" Name="PerUserOrPerMachine" Directory="DesktopFolder"  />
            </File>

            <RegistryValue Root="HKCU" Key="Software\My Company\My Product" Name="installed" Type="integer" Value="1" KeyPath="yes" />
          </Component>

        </Directory>
      </Directory>
    </Directory>

  </Product>

</Wix>
</code>```

Links:

WiX Simple Setup Per User Installer (sample per-user setup - should not install directly to user profile folders, but set install to ProgramFiles and then allow MSI to do folder redirection).

Body:
I'm trying get our MSI working for non-admin users.

I'm using WixUI_Advanced, but I'm still getting an admin prompt even when I select "Install just for you":

Looking at the MSI logs I can see that elevation is required, but I don't know why:

MSI (s) (68:54) [10:45:25:359]: Product not registered: beginning first-time install
MSI (s) (68:54) [10:45:25:359]: PROPERTY CHANGE: Deleting ALLUSERS property. Its current value is '1'.
MSI (s) (68:54) [10:45:25:359]: Product {32799511-D146-40F4-ACA7-5A76E6E38854} is not managed.
MSI (s) (68:54) [10:45:25:359]: Machine policy value 'AlwaysInstallElevated' is 0
MSI (s) (68:54) [10:45:25:359]: User policy value 'AlwaysInstallElevated' is 0
MSI (s) (68:54) [10:45:25:359]: MSI_LUA: Elevation required to install product, will prompt for credentials

Any idea why I'm getting prompted for admin rights?

Edit

I created an empty Wix project, used the WixUI_Advanced UI, and I'm getting the same issue :/

Body:
Admin Rights Prompt: In the WiX sample below, elevation will be requested and required for per-machine installation, but not for per-user installation.

Heads-Up: I personally do not like per-user setups. I find them to be borderline anti-patterns in my subjective opinion. It relates to poor serviceability (upgrades, patching, etc...) and a number of other details such as dubious folder redirects and some other "high-astonishment" factors. There are also a number of restrictions summarized nicely by the Advanced Installer guys: Advanced Installer: per-user setup limitations.

WiX Issue 5481: I added an answer, but deleted it. It didn't work properly. I had a look in the WiX Issues database and this is a known issue: https://github.com/wixtoolset/issues/issues/5481. The last comment from NicMay looked interesting. I made a quick mock-up below incorporating his / her suggestions with some modifications.

Disclaimer: The below sample has a number of defects, and is only intended as a "runnable sample". There are issues with MSI validation due to the shortcut quick-solution I used (use the shortcut to see where the file installed, right click and go "Properties"). The "Create New Folder" button in the custom installation dialog also has a bug. I will still post it to see if it helps you:

NB!: Create new WiX project, add reference to WixUIExtension.dll, then follow comments. Run setup and click "Advanced" to select per-user or per-machine install.

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">

<!--CHANGE #1: Add an UpgradeCode GUID below -->

  <Product Id="*" Name="PerUserOrPerMachine" Language="1033" Version="1.0.0.0"
           Manufacturer="Hobbit" UpgradeCode="PUT-GUID-HERE">
    <Package InstallerVersion="200" Compressed="yes" />

    <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
    <MediaTemplate EmbedCab="yes" />
    <Feature Id="ProductFeature" Title="PerUserOrPerMachine" Level="1" />

<!--CHANGE #2: Here we channel "hacker" NicMay with his / her dialog event tweaks mentioned in the WiX issue 5481 -->

    <UI>
      <UIRef Id="WixUI_Advanced" />
      <Publish Dialog="InstallScopeDlg" Control="Next" Property="MSIINSTALLPERUSER" Value="1" Order="3">WixAppFolder = "WixPerUserFolder"</Publish>
      <Publish Dialog="InstallScopeDlg" Control="Next" Property="MSIINSTALLPERUSER" Value="{}" Order="2">WixAppFolder = "WixPerMachineFolder"</Publish>
      <Publish Dialog="InstallScopeDlg" Control="Next" Event="DoAction" Value="WixSetDefaultPerMachineFolder" Order="3">WixAppFolder = "WixPerMachineFolder"</Publish>
      <Publish Dialog="InstallScopeDlg" Control="Next" Event="DoAction" Value="WixSetDefaultPerUserFolder" Order="3">WixAppFolder = "WixPerUserFolder"</Publish>
    </UI>

    <Property Id="ApplicationFolderName" Value="PerUserPerMachine" />
    <Property Id="WixAppFolder" Value="WixPerMachineFolder" />

<!--CHANGE #3: Add components and files as appropriate -->

    <Directory Id="TARGETDIR" Name="SourceDir">

<!--CHANGE #4: Make sure DesktopFolder is defined -->

      <Directory Id="DesktopFolder" />
      <Directory Id="ProgramFilesFolder">

<!--CHANGE #5: Crucial: Make sure Directory Id is APPLICATIONFOLDER (referenced elsewhere) -->

        <Directory Id="APPLICATIONFOLDER" Name="PerUserOrPerMachine">
          <Component Feature="ProductFeature" Guid="{5A74A1EE-0AD3-4C48-9E6B-4E4E3712A8BB}">

<!--CHANGE #6: Hard coded path below for simplicity, change path or replace construct -->

            <File Source="D:\My Test Files\MyTestApplication.exe">
              <Shortcut Id="AppDesktopShortcut" Name="PerUserOrPerMachine" Directory="DesktopFolder"  />
            </File>

            <RegistryValue Root="HKCU" Key="Software\My Company\My Product" Name="installed" Type="integer" Value="1" KeyPath="yes" />
          </Component>

        </Directory>
      </Directory>
    </Directory>

  </Product>

</Wix>

Links:

WiX Simple Setup Per User Installer (sample per-user setup - should not install directly to user profile folders, but set install to ProgramFiles and then allow MSI to do folder redirection).


问:
how to check for entities/relationships generically
I have entities/relationships like following A -> B; B -> C, B -> D, B -> E, ...

When a user wants to delete entity A, I check whether any of its children B entities have any records for C entities, and D entities, etc and provide a detailed error message.

However, the requirement is that we might end up adding more entity types such as B -> FutureEntity. Is there a way to either generically check for all of these, or atleast make sure that in the future if such an entity gets added, I modify the deletion functionality to account for such entities?

答:
You can achieve this by adding the following functions to the 'BaseEntity':

```<code>public abstract class BaseEntity
{

    [Key]
    public int Id { get; set; }

    public abstract bool IsChildOfBee();
    public abstract string GetDisplayName();
}
</code>```

When you add a child entity override those methods:

```<code>public class EntityCee :BaseEntity
{
    public string Name { get; set; }

    public override string GetDisplayName()
    {
        return "Entity Cee";
    }

    public override bool IsChildOfBee()
    {
        return true;
    }
}
</code>```

Before you delete entity B, check the associated entities:

```<code>var errors = new List<string>();

var entityBeeToDelete = _exampleRepository.GetEntityBee(1);

var associatedEntities = _exampleRepository.GetAssociatedEntities(entityBeeToDelete);

foreach(var e in associatedEntities)
{
    errors.Add($"{entityBeeToDelete.GetDisplayName()} has some {e} records associated with it. Please delete those before deleting {entityBeeToDelete.GetDisplayName()}");
}
</code>```

Here is the function that checks for associated children:

```<code>public List<string> GetAssociatedEntities(EntityBee bee)
{
    var types = new List<string>();

    foreach (var entityType in this.Model.GetEntityTypes())
    {
        var clr = entityType.ClrType;

        var tableName = entityType.Relational().TableName;

        BaseEntity instance = (BaseEntity)Activator.CreateInstance(clr);

        var isChildOfBee = instance.IsChildOfBee();

        if(isChildOfBee)
        {
            var query = $"select top(1) * from EntityBees where Id IN (select EntityBeeId from {tableName} where EntityBeeId = {bee.Id})";

            var eB = this.EntityBees.FromSql(query).FirstOrDefault();

            if(eB != null)
            {
                types.Add(instance.GetDisplayName());
            }

        }

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

Body:
You can achieve this by adding the following functions to the 'BaseEntity':

public abstract class BaseEntity
{

    [Key]
    public int Id { get; set; }

    public abstract bool IsChildOfBee();
    public abstract string GetDisplayName();
}

When you add a child entity override those methods:

public class EntityCee :BaseEntity
{
    public string Name { get; set; }

    public override string GetDisplayName()
    {
        return "Entity Cee";
    }

    public override bool IsChildOfBee()
    {
        return true;
    }
}

Before you delete entity B, check the associated entities:

var errors = new List<string>();

var entityBeeToDelete = _exampleRepository.GetEntityBee(1);

var associatedEntities = _exampleRepository.GetAssociatedEntities(entityBeeToDelete);

foreach(var e in associatedEntities)
{
    errors.Add($"{entityBeeToDelete.GetDisplayName()} has some {e} records associated with it. Please delete those before deleting {entityBeeToDelete.GetDisplayName()}");
}

Here is the function that checks for associated children:

public List<string> GetAssociatedEntities(EntityBee bee)
{
    var types = new List<string>();

    foreach (var entityType in this.Model.GetEntityTypes())
    {
        var clr = entityType.ClrType;

        var tableName = entityType.Relational().TableName;

        BaseEntity instance = (BaseEntity)Activator.CreateInstance(clr);

        var isChildOfBee = instance.IsChildOfBee();

        if(isChildOfBee)
        {
            var query = $"select top(1) * from EntityBees where Id IN (select EntityBeeId from {tableName} where EntityBeeId = {bee.Id})";

            var eB = this.EntityBees.FromSql(query).FirstOrDefault();

            if(eB != null)
            {
                types.Add(instance.GetDisplayName());
            }

        }

    }
    return types;
}


问:
What is causing the first block of code to work but the second to return a syntax error?
I'm practicing Python with problems on a website and the my program is returning a Syntax error on Line 9, yet on the example answer to the problem provided on the website, the same line of code is that is in my program is working without error. Just curious as to what is causing the problem in my program? The point of the problem is to take numbers from 2 lists, find the even numbers from list one and finding the odd from list 2 and creating a 3rd list using the even and odds. I changed it up to find the even and odd from both and make both an even and an odd list pulling from both list one and two but I was thinking it should still work...

Pretty new to Python. Not quite sure what to even try.

Provided code from Website:

```<code>def mergeList(listOne, listTwo):
  thirdList = []
  for num in listOne:
    if(num % 2 != 0):
      thirdList.append(num)
  for num in listTwo:
    if(num % 2 == 0):
      thirdList.append(num)
  return thirdList

print("Merged List is")
listOne = [10, 20, 23, 11, 17]
listTwo = [13, 43, 24, 36, 12]
print(mergeList(listOne, listTwo))
</code>```

My code

```<code>list1 = [81, 71, 61, 34, 55]
list2 = [14, 19, 48, 32, 91]

def mergelist(list1, list2):
    mergedlist = list1 + list2
    even = []
    odd = []
    for num in mergedlist:
        if (num % 2 = 0):
            even.append(num)
            else:
            odd.append(num)
print("even: " + even)
print("odd: " + odd)
</code>```

My program should merge list 1 and 2 into one list, "mergedlist", and then search the list for even numbers and appending them to the even list. The non even numbers, odds, should be appended to the odd list. Then finally print both the even and odd lists. My program is saying that there is a syntax error on line 9.

答:
```<code>list1 = [81, 71, 61, 34, 55]
list2 = [14, 19, 48, 32, 91]

def mergelist(list1, list2):
  mergedlist = list1 + list2
  even = []
  odd = []
  for num in mergedlist:
    if num % 2 == 0:
        even.append(num)
    else:
        odd.append(num)
  print("even:", even)
  print("odd:", odd)
</code>```

calling the function

```<code>mergelist(list1, list2)
</code>```

Above code is working version of your code with following corrections

1) As said in previous answer you need relational/comparison operator "==" in place of assignment operator "=" with if condition.

2) Indentation for else and following statement was wrong.

3) list can't be concatenated so you should use , in place of +

4) Finally you must call the function with arguments outside .

Body:
I'm practicing Python with problems on a website and the my program is returning a Syntax error on Line 9, yet on the example answer to the problem provided on the website, the same line of code is that is in my program is working without error. Just curious as to what is causing the problem in my program? The point of the problem is to take numbers from 2 lists, find the even numbers from list one and finding the odd from list 2 and creating a 3rd list using the even and odds. I changed it up to find the even and odd from both and make both an even and an odd list pulling from both list one and two but I was thinking it should still work...

Pretty new to Python. Not quite sure what to even try.

Provided code from Website:

def mergeList(listOne, listTwo):
  thirdList = []
  for num in listOne:
    if(num % 2 != 0):
      thirdList.append(num)
  for num in listTwo:
    if(num % 2 == 0):
      thirdList.append(num)
  return thirdList

print("Merged List is")
listOne = [10, 20, 23, 11, 17]
listTwo = [13, 43, 24, 36, 12]
print(mergeList(listOne, listTwo))

My code

list1 = [81, 71, 61, 34, 55]
list2 = [14, 19, 48, 32, 91]

def mergelist(list1, list2):
    mergedlist = list1 + list2
    even = []
    odd = []
    for num in mergedlist:
        if (num % 2 = 0):
            even.append(num)
            else:
            odd.append(num)
print("even: " + even)
print("odd: " + odd)

My program should merge list 1 and 2 into one list, "mergedlist", and then search the list for even numbers and appending them to the even list. The non even numbers, odds, should be appended to the odd list. Then finally print both the even and odd lists. My program is saying that there is a syntax error on line 9.

Body:
list1 = [81, 71, 61, 34, 55]
list2 = [14, 19, 48, 32, 91]

def mergelist(list1, list2):
  mergedlist = list1 + list2
  even = []
  odd = []
  for num in mergedlist:
    if num % 2 == 0:
        even.append(num)
    else:
        odd.append(num)
  print("even:", even)
  print("odd:", odd)

calling the function

mergelist(list1, list2)

Above code is working version of your code with following corrections

1) As said in previous answer you need relational/comparison operator "==" in place of assignment operator "=" with if condition.

2) Indentation for else and following statement was wrong.

3) list can't be concatenated so you should use , in place of +

4) Finally you must call the function with arguments outside .


问:
Java Socket Connection Via Jsch Port Forwarding
I am trying to establish socket connection by local port forwarding. the flow is:

Client --> SSHhost --> TargetHost

Trying to achieve that by port forwarding but keep getting
     IllegalStateException: Can't connect to rHost  error.

I tested that remote host does accepts connection directly and my use case is to connect via SSHhost.

not sure where it went wrong or I am open to different approach or suggestions? Thanks.

```<code> try {
        jsch.addIdentity(privateKeyPath);
        session = jsch.getSession(username, hostL, port);
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        java.util.Properties config = new java.util.Properties();
        session.setConfig(config);
    } catch (JSchException e) {
        throw new RuntimeException("Failed to create Jsch Session object.", e);
    }

    try {
        session.connect();

        session.setPortForwardingL(8080, rHost, rPort);
        try (Socket s = new Socket()) {
            s.connect(new InetSocketAddress(rHost, 8080), timeout);
        } catch (Exception e) {
            String errText = String.format("Can't connect to rHost")
            throw new IllegalStateException(errText);
        }

        session.disconnect();
    } catch (JSchException e) {
        throw new RuntimeException("Error durring session connection );
    }
</code>```

答:
You need to change the following line

s.connect(new InetSocketAddress(rHost, 8080), timeout);

to

s.connect(new InetSocketAddress("localhost", 8080), timeout);

Because you have actually mapped your localhost port 8080 to the remote host port when you used the method session.setPortForwardingL(8080, rHost, rPort);

You can try this code

```<code>try {

            jsch.addIdentity(privateKeyPath);
            session = jsch.getSession(username, hostL, port);
            session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");

            session.setConfig("StrictHostKeyChecking", "no");

            session.connect();

            session.setPortForwardingL(8080, rHost, rPort);
            Socket s = new Socket();
            s.connect(new InetSocketAddress("localhost", 8080), timeout);

            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

Body:
I am trying to establish socket connection by local port forwarding. the flow is:

Client --> SSHhost --> TargetHost

Trying to achieve that by port forwarding but keep getting
     IllegalStateException: Can't connect to rHost  error.

I tested that remote host does accepts connection directly and my use case is to connect via SSHhost.

not sure where it went wrong or I am open to different approach or suggestions? Thanks.

 try {
        jsch.addIdentity(privateKeyPath);
        session = jsch.getSession(username, hostL, port);
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        java.util.Properties config = new java.util.Properties();
        session.setConfig(config);
    } catch (JSchException e) {
        throw new RuntimeException("Failed to create Jsch Session object.", e);
    }

    try {
        session.connect();

        session.setPortForwardingL(8080, rHost, rPort);
        try (Socket s = new Socket()) {
            s.connect(new InetSocketAddress(rHost, 8080), timeout);
        } catch (Exception e) {
            String errText = String.format("Can't connect to rHost")
            throw new IllegalStateException(errText);
        }

        session.disconnect();
    } catch (JSchException e) {
        throw new RuntimeException("Error durring session connection );
    }

Body:
You need to change the following line

s.connect(new InetSocketAddress(rHost, 8080), timeout);

to

s.connect(new InetSocketAddress("localhost", 8080), timeout);

Because you have actually mapped your localhost port 8080 to the remote host port when you used the method session.setPortForwardingL(8080, rHost, rPort);

You can try this code

try {

            jsch.addIdentity(privateKeyPath);
            session = jsch.getSession(username, hostL, port);
            session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");

            session.setConfig("StrictHostKeyChecking", "no");

            session.connect();

            session.setPortForwardingL(8080, rHost, rPort);
            Socket s = new Socket();
            s.connect(new InetSocketAddress("localhost", 8080), timeout);

            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


问:
Why does localhost server start when running React?
create-react-app seems to start localhost server at npm start.

(npx comes with npm 5.2+ and higher, see instructions for older npm versions)

Then open http://localhost:3000/ to see your app.

When you’re ready to deploy to production, create a minified bundle with npm run build.

https://facebook.github.io/create-react-app/docs/getting-started

Why do I need to bring up a server just to run JavaScript?

What are the differences, advantages, and disadvantages of opening the build result file directly in the browser?

Also, is this true for other frameworks regardless of create-react-app?

I read React's repository etc on this issue, but there was no topic on this issue.

答:
One of the main advantages to create-react-app starting a localhost server is hot reloading.

When you write most modern JavaScript, including React, your code needs to be transpiled (essentially converted to a different version of JS) before the browser can understand it. This is called the build process, which takes all the files in the src directory and bundles them into a single static JS file.

You could do this manually with npm run build, which creates an index.html that you can open in a browser without running a server. But you have to go through 2 part process to see your changes: rebuild and then reload the browser to see your changes.

create-react-app is built so that it watches for changes in your files, updates the built JS whenever you hit save, and then restarts the server, loading your changes automatically.

By running a server on localhost, create-react-app can update your page instantly every time you save, without you manually rebuilding OR refreshing the page. Hot reloading!


问:
Can i put border to a form using bootstrap?
I have this code below, and i want to add a border to make like a box using bootstrap class ".border", but i can't figure out why is not working!. Is possible using bootstrap v4?</p>

```<code><div class="d-flex justify-content-center">
      <form>
        <div class="form-group row">
          <div class="col-sm-12">
            <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
          </div>
        </div>
        <div class="form-group row">
          <div class="col-sm-12">
            <input type="password" class="form-control" id="inputPassword3" placeholder="Password">
          </div>
        </div>
        <div class="form-group row">
          <div class=" col-sm-12">
            <button type="submit" class="btn btn-primary">Sign in</button>
          </div>
        </div>
      </form>
    </div>
</code>```

答:
Here is a pretty good combination for a bordered form with background color:

```<code><form class = 'card p-3 bg-light'>
</code>```

Looked good for my case.

Body:
I have this code below, and i want to add a border to make like a box using bootstrap class ".border", but i can't figure out why is not working!. Is possible using bootstrap v4?

      <form>

            <input type="email" class="form-control" id="inputEmail3" placeholder="Email">

            <input type="password" class="form-control" id="inputPassword3" placeholder="Password">

            <button type="submit" class="btn btn-primary">Sign in</button>

      </form>

Body:
Here is a pretty good combination for a bordered form with background color:

<form class = 'card p-3 bg-light'>

Looked good for my case.


问:
PIVOT without aggregation function
I have a single table, and I want to pivot it to new table. I used pivot to implements but the aggregate function will filter data. How to pivot table without aggregate function, or could u can give me recommendation for this question.

Orginal Table

```<code>ID    Name    Value    Date
1     A       5.00     06/01/2019 13:00
2     A       13.15    06/02/2019 15:32
3     B       3.20     06/02/2019 15.32
4     B       33.11    05/11/2019 13:00
5     B       32.00    05/11/2019 13:00
</code>```

trans to new table

```<code>ID    A     B     Date
1     5.00  NULL  06/01/2019 13:00
2     13.15 3.20  06/02/2019 15:32
3     NULL  33.11 05/11/2019 13:00
4     Null  32.00 05/11/2019 13:00
</code>```

notes: ID is identity on two table.

my pivot code, it only keep max value.

PIVOT(
    MAX(Value)
    FOR Name IN (A,B)) AS S
ORDER BY Date DESC
```

答:
A standard pivot query should work here:

```<code>WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Date, Name ORDER BY ID) rn
    FROM yourTable
)

SELECT
    Date,
    MAX(CASE WHEN Name = 'A' THEN [Value] END) AS A,
    MAX(CASE WHEN Name = 'B' THEN [Value] END) AS B
FROM cte
GROUP BY
    Date, rn;
</code>```

Demo

Title: PIVOT without aggregation function

Body:
I have a single table, and I want to pivot it to new table. I used pivot to implements but the aggregate function will filter data. How to pivot table without aggregate function, or could u can give me recommendation for this question.

Orginal Table

ID    Name    Value    Date
1     A       5.00     06/01/2019 13:00
2     A       13.15    06/02/2019 15:32
3     B       3.20     06/02/2019 15.32
4     B       33.11    05/11/2019 13:00
5     B       32.00    05/11/2019 13:00

trans to new table

ID    A     B     Date
1     5.00  NULL  06/01/2019 13:00
2     13.15 3.20  06/02/2019 15:32
3     NULL  33.11 05/11/2019 13:00
4     Null  32.00 05/11/2019 13:00

notes: ID is identity on two table.

my pivot code, it only keep max value.

PIVOT(
    MAX(Value)
    FOR Name IN (A,B)) AS S
ORDER BY Date DESC

Body:
A standard pivot query should work here:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Date, Name ORDER BY ID) rn
    FROM yourTable
)

SELECT
    Date,
    MAX(CASE WHEN Name = 'A' THEN [Value] END) AS A,
    MAX(CASE WHEN Name = 'B' THEN [Value] END) AS B
FROM cte
GROUP BY
    Date, rn;

Demo


问:
Http headers to cache a dynamic page
I have a classic html page generated with PHP.

For this page (served from a same URL) we have 2 cases:

The user is logged (cookie based) => the page is specific to the user (we display a box with user name + personal information.)

The user is not logged in => the page is common to all the user.

How can I set the header to:

have the most agressive cache (with a max-age of 60).

avoid mixing pages between users.

Can I replace my present header:

```<code>header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
</code>```

With this?

```<code>header('Cache-Control: public, max-age=60');
header('Vary: *');
</code>```

Edit: Is it possible (how) to have it Cache-controled private in case "1" and public in case "2"

答: If login is purely cookie based then you only need a Vary: Cookie header to make it unique to a particular user. The Vary: * should work just as well though.</p>

Title: Http headers to cache a dynamic page

Body:
I have a classic html page generated with PHP.

For this page (served from a same URL) we have 2 cases:

The user is logged (cookie based) => the page is specific to the user (we display a box with user name + personal information.)

The user is not logged in => the page is common to all the user.

How can I set the header to:

have the most agressive cache (with a max-age of 60).

avoid mixing pages between users.

Can I replace my present header:

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

With this?

header('Cache-Control: public, max-age=60');
header('Vary: *');

Edit: Is it possible (how) to have it Cache-controled private in case "1" and public in case "2"


问:
Deploying PHP files outside of wwwroot in Azure Web App service
Usually, when you deploy a PHP Web APP in Azure, you will put it under /home/site/wwwroot so that all scripts are accessible from the web.

However, I have some constants (like clientId + clientSecret among others) that I don't want to expose to the internet for safety reasons. I have a constants.php file for that purpose.

As a result, I would like to know if the following folder tree would work as expected and it's safe:

```<code>/home/site/wwwroot/index.php
/home/site/constants.php
</code>```

I'm not doing the deploy and can't test it by myself.

答:
If you only have statements defining constants or variables in constants. php, it's safe to put them anywhere.

What you need to be aware of is that when other files load it, they will not output file contents or variables | constants for any reason.

Body:
Usually, when you deploy a PHP Web APP in Azure, you will put it under /home/site/wwwroot so that all scripts are accessible from the web.

However, I have some constants (like clientId + clientSecret among others) that I don't want to expose to the internet for safety reasons. I have a constants.php file for that purpose.

As a result, I would like to know if the following folder tree would work as expected and it's safe:

/home/site/wwwroot/index.php
/home/site/constants.php

I'm not doing the deploy and can't test it by myself.


问:
what order do cucumber tests get run
I know cucumber runs each test in a feature file from top down, but my question is, in what order do feature files get run?  It doesn't seem to be alphabetically, or in any structure order.</p>

答: Feature files are running in alphabetically order so there is a one way to execute all scenario in a single file like "EndToEnd.feature" where you can specify all scenarios with tags and execute from Runner. Hope it will help you.</p>

Title: what order do cucumber tests get run


问:
Same key, different values: nested dicts of dicts
Borrowing an MWE from this question, I have a set of nested dicts of dicts:

```<code>{
  "type": "A"
    "a": "aaa",
    "payload": {"another":{"dict":"value", "login":"user1"}},
    "actor": {"dict":"value", "login":"user2"}
}
{
  "type": "B"
    "a": "aaa",
    "payload": {"another":{"dict":"value", "login":"user3"}},
    "actor": {"dict":"value", "login":"user4"}
  }
}
{
  "type": "A"
    "a": "aaa",
    "b": "bbb",
    "payload": {"another":{"dict":"value", "login":"user5"}},
    "actor": {"dict":"value", "login":"user6"}
  }
}
{
  "type": "A"
    "a": "aaa",
    "b": "bbb",
    "payload": {"login":"user5"},
    "actor": {"login":"user6"}
  }
}
</code>```

For dictionaries that have "type":"A", I want to get the username from the payload dict and the username from actor dict. The same username can appear multiple times. I would like to store a txt file with a list of actor (ID1) and a list of payload (ID2) like this:

```<code>ID1    ID2
user2  user1
user6  user5
user6  user5
</code>```

Right now, I have a start:

```<code>zgrep "A" | zgrep -o 'login":"[^"]*"' | zgrep -o 'payload":"[^"]*" > usernames_list.txt
</code>```

But of course this won't work, because I need to find login within the payload dict and login within the actor dict for each dict of type A.

Any thoughts?

答:
I am assuming you have the payload and actor dictionaries for all entries of type A.

Parse out the user name from the payload entries and redirect them
to a file named payload.txt

Parse out the user name from actor entries and redirect them to a
different file named actor.txt

Use paste command to join the entries and output them the way you want it

Body:
Borrowing an MWE from this question, I have a set of nested dicts of dicts:

{
  "type": "A"
    "a": "aaa",
    "payload": {"another":{"dict":"value", "login":"user1"}},
    "actor": {"dict":"value", "login":"user2"}
}
{
  "type": "B"
    "a": "aaa",
    "payload": {"another":{"dict":"value", "login":"user3"}},
    "actor": {"dict":"value", "login":"user4"}
  }
}
{
  "type": "A"
    "a": "aaa",
    "b": "bbb",
    "payload": {"another":{"dict":"value", "login":"user5"}},
    "actor": {"dict":"value", "login":"user6"}
  }
}
{
  "type": "A"
    "a": "aaa",
    "b": "bbb",
    "payload": {"login":"user5"},
    "actor": {"login":"user6"}
  }
}

For dictionaries that have "type":"A", I want to get the username from the payload dict and the username from actor dict. The same username can appear multiple times. I would like to store a txt file with a list of actor (ID1) and a list of payload (ID2) like this:

ID1    ID2
user2  user1
user6  user5
user6  user5

Right now, I have a start:

zgrep "A" | zgrep -o 'login":"[^"]*"' | zgrep -o 'payload":"[^"]*" > usernames_list.txt

But of course this won't work, because I need to find login within the payload dict and login within the actor dict for each dict of type A.

Any thoughts?


问:
Create Unlimited DataFrames from other DataFrame Column Category with Time-Series Data
I have three columns in a Time series.

The Time series is hourly and the index value.

I have multiple categories that are being measured hourly.

I have arbitrary lists of levels: these are usually odd names and I may pull anywhere between 40 to 40000 at a time.

I also have their varying values: for score 0 - 100.

So:

I want to make each Level have its own DataFrame:

(FULL DataFrame):

```<code>df =

              date    levels    score
2019-01-01 00:00:00    1005  99.438851
2019-01-01 01:00:00    1005  92.081975
2019-01-01 02:00:00    1005  93.032991
2019-01-01 03:00:00    1005   1.991615
2019-01-01 04:00:00    1005  12.723531
2019-01-01 05:00:00    1005  74.443313
</code>```

(One of hundreds of individual DataFrames I want generated, but NOT in a DICT)

```<code>df_is_1005 =

              date      score
2019-01-01 00:00:00  99.438851
2019-01-01 01:00:00  92.081975
2019-01-01 02:00:00  93.032991
2019-01-01 03:00:00   1.991615
2019-01-01 04:00:00  12.723531
2019-01-01 05:00:00  74.443313
</code>```

.... but for ALL THE LEVELS
.

And
I have a bit of a problem!

I've done quite a lot of digging and have tried making a dict of the dataframes. How do I extract each of these?

Also, how do I name them individually as: df_of_{levels}?

This is the Time Series data I'll create for a toy model. (BUT there should be multiple datetime for each and every level, unlike here)

import pandas as pd
from datetime import datetime
import numpy as np
import pandas as pd

date_rng = pd.date_range(start='1/1/2019', end='3/30/2019', freq='H')

df = pd.DataFrame(date_rng, columns=['date'])

df['level'] = np.random.randint(1000,1033,size=(len(date_rng)))

df['score'] = np.random.uniform(0,100,size=(len(date_rng)))
```

<p>Keep in mind, the levels I may deal with could be hundreds and they are named bizarre things. </p>

<p>I'll have the time stamps for each of these as separate rows. </p>

<p>My desired goal is the have each of the possible levels, which there may well be more than just the small number here, to dynamically create dataframes.</p>

<p>NOW: I know I can create a Dictionary of dataframes.</p>

<p>BUT How do I extract each of dataframes with INDIVIDUAL Numbers?</p>

<p>I want, for example</p>

<pre class="lang-py prettyprint-override"><code>df =

              date    levels    score
2019-01-01 00:00:00    1005  99.438851
2019-01-01 01:00:00    1005  92.081975
2019-01-01 02:00:00    1005  93.032991
2019-01-01 03:00:00    1005   1.991615
2019-01-01 04:00:00    1005  12.723531
2019-01-01 05:00:00    1005  74.443313
2019-01-01 06:00:00    1005  12.154499
2019-01-01 07:00:00    1005  96.439228
2019-01-01 08:00:00    1005  64.283731
2019-01-01 09:00:00    1005  83.165093
2019-01-01 10:00:00    1005  75.740610
2019-01-01 11:00:00    1005  25.721404
2019-01-01 12:00:00    1005  37.493829
2019-01-01 13:00:00    1005  51.783549
2019-01-01 14:00:00    1005   7.223582
2019-01-01 15:00:00    1005   0.932651
2019-01-01 16:00:00    1005  95.916686
2019-01-01 17:00:00    1005  11.579450
</code>```

and same df, far later... :

               date   levels      score
2019-01-01 00:00:00    1027  99.438851
2019-01-01 01:00:00    1027  92.081975
2019-01-01 02:00:00    1027  93.032991
2019-01-01 03:00:00    1027   1.991615
2019-01-01 04:00:00    1027  12.723531
2019-01-01 05:00:00    1027  74.443313
2019-01-01 06:00:00    1027  12.154499
2019-01-01 07:00:00    1027  96.439228
2019-01-01 08:00:00    1027  64.283731
2019-01-01 09:00:00    1027  83.165093
2019-01-01 10:00:00    1027  75.740610
2019-01-01 11:00:00    1027  25.721404
2019-01-01 12:00:00    1027  37.493829
2019-01-01 13:00:00    1027  51.783549
2019-01-01 14:00:00    1027   7.223582
2019-01-01 15:00:00    1027   0.932651
2019-01-01 16:00:00    1027  95.916686
2019-01-01 17:00:00    1027  11.579450
2019-01-01 18:00:00    1027  91.226938
2019-01-01 19:00:00    1027  31.564530
2019-01-01 20:00:00    1027  39.511358
2019-01-01 21:00:00    1027  59.787468
2019-01-01 22:00:00    1027   4.666549
2019-01-01 23:00:00    1027  92.197337
```

<p>...etcetera...</p>

<p>EACH level individually, whatever it may be called (and there may be hundreds of them with random values):</p>

<p>To be converted to </p>

<p>df_{level_value_generated} = </p>

<pre class="lang-py prettyprint-override"><code>
        date           score
2019-01-01 00:00:00   8.040233
2019-01-01 01:00:00  55.736688
2019-01-01 02:00:00  37.910143
2019-01-01 03:00:00  22.907763
2019-01-01 04:00:00   4.586205
2019-01-01 05:00:00  88.090652
2019-01-01 06:00:00  50.474533
2019-01-01 07:00:00  92.890208
2019-01-01 08:00:00  70.949978
2019-01-01 09:00:00  23.191488
2019-01-01 10:00:00  60.506870
2019-01-01 11:00:00  25.689149
2019-01-01 12:00:00  49.234296
2019-01-01 13:00:00  65.369771
2019-01-01 14:00:00  55.550065
2019-01-01 15:00:00  35.112297
2019-01-01 16:00:00  45.989587
2019-01-01 17:00:00  76.829787
2019-01-01 18:00:00   5.982378
2019-01-01 19:00:00  83.603115
2019-01-01 20:00:00   5.995648
2019-01-01 21:00:00  95.658097
2019-01-01 22:00:00  21.877945
2019-01-01 23:00:00  30.428798
2019-01-02 00:00:00  72.450284
2019-01-02 01:00:00  91.947018
2019-01-02 02:00:00  66.741502
2019-01-02 03:00:00  77.535416
2019-01-02 04:00:00  29.624868
2019-01-02 05:00:00  89.652003

</code>```

So I can then list the  these DataFrames that are created DYNAMICALLY.

From here, I'd like to add them to a dictionary, the reason being, is that I want to train a Time-Series model to on each and every one of the individual DataFrames so I can have a different model for each of them, each with their own training and outputs.

If possibly, can I train multiple DataFrames from inside a dictionary individually?

If I just do a pivot table or groupby, I will have a large Dataframe that I'll have to individually call out columns of to train on the time series. So I'd rather not do that.

So, how do I dynamically create:

Newly named DataFrames from levels that are not all known in value,

each named:

df_{level_name}:

DateTime Column:            Score_Column:

some dates...                scores 0-100

that will then drop the 'level_name' column in their own DataFrame, so that I can have as many dataframes as necessary, each named uniquely, programmatically, so I can then take each of these and then plug them into a new model or whatever?

Body:
I have three columns in a Time series.

The Time series is hourly and the index value.

I have multiple categories that are being measured hourly.

I have arbitrary lists of levels: these are usually odd names and I may pull anywhere between 40 to 40000 at a time.

I also have their varying values: for score 0 - 100.

So:

I want to make each Level have its own DataFrame:

(FULL DataFrame):

df =

              date    levels    score
2019-01-01 00:00:00    1005  99.438851
2019-01-01 01:00:00    1005  92.081975
2019-01-01 02:00:00    1005  93.032991
2019-01-01 03:00:00    1005   1.991615
2019-01-01 04:00:00    1005  12.723531
2019-01-01 05:00:00    1005  74.443313

(One of hundreds of individual DataFrames I want generated, but NOT in a DICT)

df_is_1005 =

              date      score
2019-01-01 00:00:00  99.438851
2019-01-01 01:00:00  92.081975
2019-01-01 02:00:00  93.032991
2019-01-01 03:00:00   1.991615
2019-01-01 04:00:00  12.723531
2019-01-01 05:00:00  74.443313

.... but for ALL THE LEVELS
.

And
I have a bit of a problem!

I've done quite a lot of digging and have tried making a dict of the dataframes. How do I extract each of these?

Also, how do I name them individually as: df_of_{levels}?

This is the Time Series data I'll create for a toy model. (BUT there should be multiple datetime for each and every level, unlike here)

import pandas as pd
from datetime import datetime
import numpy as np
import pandas as pd

date_rng = pd.date_range(start='1/1/2019', end='3/30/2019', freq='H')

df = pd.DataFrame(date_rng, columns=['date'])

df['level'] = np.random.randint(1000,1033,size=(len(date_rng)))

df['score'] = np.random.uniform(0,100,size=(len(date_rng)))

Keep in mind, the levels I may deal with could be hundreds and they are named bizarre things.

I'll have the time stamps for each of these as separate rows.

My desired goal is the have each of the possible levels, which there may well be more than just the small number here, to dynamically create dataframes.

NOW: I know I can create a Dictionary of dataframes.

BUT How do I extract each of dataframes with INDIVIDUAL Numbers?

I want, for example

df =

              date    levels    score
2019-01-01 00:00:00    1005  99.438851
2019-01-01 01:00:00    1005  92.081975
2019-01-01 02:00:00    1005  93.032991
2019-01-01 03:00:00    1005   1.991615
2019-01-01 04:00:00    1005  12.723531
2019-01-01 05:00:00    1005  74.443313
2019-01-01 06:00:00    1005  12.154499
2019-01-01 07:00:00    1005  96.439228
2019-01-01 08:00:00    1005  64.283731
2019-01-01 09:00:00    1005  83.165093
2019-01-01 10:00:00    1005  75.740610
2019-01-01 11:00:00    1005  25.721404
2019-01-01 12:00:00    1005  37.493829
2019-01-01 13:00:00    1005  51.783549
2019-01-01 14:00:00    1005   7.223582
2019-01-01 15:00:00    1005   0.932651
2019-01-01 16:00:00    1005  95.916686
2019-01-01 17:00:00    1005  11.579450

and same df, far later... :

               date   levels      score
2019-01-01 00:00:00    1027  99.438851
2019-01-01 01:00:00    1027  92.081975
2019-01-01 02:00:00    1027  93.032991
2019-01-01 03:00:00    1027   1.991615
2019-01-01 04:00:00    1027  12.723531
2019-01-01 05:00:00    1027  74.443313
2019-01-01 06:00:00    1027  12.154499
2019-01-01 07:00:00    1027  96.439228
2019-01-01 08:00:00    1027  64.283731
2019-01-01 09:00:00    1027  83.165093
2019-01-01 10:00:00    1027  75.740610
2019-01-01 11:00:00    1027  25.721404
2019-01-01 12:00:00    1027  37.493829
2019-01-01 13:00:00    1027  51.783549
2019-01-01 14:00:00    1027   7.223582
2019-01-01 15:00:00    1027   0.932651
2019-01-01 16:00:00    1027  95.916686
2019-01-01 17:00:00    1027  11.579450
2019-01-01 18:00:00    1027  91.226938
2019-01-01 19:00:00    1027  31.564530
2019-01-01 20:00:00    1027  39.511358
2019-01-01 21:00:00    1027  59.787468
2019-01-01 22:00:00    1027   4.666549
2019-01-01 23:00:00    1027  92.197337

...etcetera...

EACH level individually, whatever it may be called (and there may be hundreds of them with random values):

To be converted to

df_{level_value_generated} =

        date           score
2019-01-01 00:00:00   8.040233
2019-01-01 01:00:00  55.736688
2019-01-01 02:00:00  37.910143
2019-01-01 03:00:00  22.907763
2019-01-01 04:00:00   4.586205
2019-01-01 05:00:00  88.090652
2019-01-01 06:00:00  50.474533
2019-01-01 07:00:00  92.890208
2019-01-01 08:00:00  70.949978
2019-01-01 09:00:00  23.191488
2019-01-01 10:00:00  60.506870
2019-01-01 11:00:00  25.689149
2019-01-01 12:00:00  49.234296
2019-01-01 13:00:00  65.369771
2019-01-01 14:00:00  55.550065
2019-01-01 15:00:00  35.112297
2019-01-01 16:00:00  45.989587
2019-01-01 17:00:00  76.829787
2019-01-01 18:00:00   5.982378
2019-01-01 19:00:00  83.603115
2019-01-01 20:00:00   5.995648
2019-01-01 21:00:00  95.658097
2019-01-01 22:00:00  21.877945
2019-01-01 23:00:00  30.428798
2019-01-02 00:00:00  72.450284
2019-01-02 01:00:00  91.947018
2019-01-02 02:00:00  66.741502
2019-01-02 03:00:00  77.535416
2019-01-02 04:00:00  29.624868
2019-01-02 05:00:00  89.652003

So I can then list the  these DataFrames that are created DYNAMICALLY.

From here, I'd like to add them to a dictionary, the reason being, is that I want to train a Time-Series model to on each and every one of the individual DataFrames so I can have a different model for each of them, each with their own training and outputs.

If possibly, can I train multiple DataFrames from inside a dictionary individually?

If I just do a pivot table or groupby, I will have a large Dataframe that I'll have to individually call out columns of to train on the time series. So I'd rather not do that.

So, how do I dynamically create:

Newly named DataFrames from levels that are not all known in value,

each named:

df_{level_name}:

DateTime Column:            Score_Column:

some dates...                scores 0-100

that will then drop the 'level_name' column in their own DataFrame, so that I can have as many dataframes as necessary, each named uniquely, programmatically, so I can then take each of these and then plug them into a new model or whatever?

Body:
If I've understood your problem correctly, a MultiIndex should do exactly what you want.

To do this on your dataframe:

df.reset_index(inplace=True)
df.set_index(['levels', 'date'], inplace=True)

# in the case of your example above, this will produce:
df =

levels date                     score
1005   2019-01-01 00:00:00      99.438851
       2019-01-01 01:00:00      92.081975
       2019-01-01 02:00:00      93.032991
       2019-01-01 03:00:00      1.991615
       2019-01-01 04:00:00      12.723531
       2019-01-01 05:00:00      74.443313
       2019-01-01 06:00:00      12.154499
       2019-01-01 07:00:00      96.439228
       2019-01-01 08:00:00      64.283731
       2019-01-01 09:00:00      83.165093
       2019-01-01 10:00:00      75.740610
       2019-01-01 11:00:00      25.721404
       2019-01-01 12:00:00      37.493829
       2019-01-01 13:00:00      51.783549
       2019-01-01 14:00:00      7.223582
       2019-01-01 15:00:00      0.932651
       2019-01-01 16:00:00      95.916686
       2019-01-01 17:00:00      11.579450
1027   2019-01-01 00:00:00      99.438851
       2019-01-01 01:00:00      92.081975
       2019-01-01 02:00:00      93.032991
       2019-01-01 03:00:00      1.991615
       2019-01-01 04:00:00      12.723531
       2019-01-01 05:00:00      74.443313
       2019-01-01 06:00:00      12.154499
       2019-01-01 07:00:00      96.439228
       2019-01-01 08:00:00      64.283731
       2019-01-01 09:00:00      83.165093
       2019-01-01 10:00:00      75.740610
       2019-01-01 11:00:00      25.721404
       2019-01-01 12:00:00      37.493829
       2019-01-01 13:00:00      51.783549
       2019-01-01 14:00:00      7.223582
       2019-01-01 15:00:00      0.932651
       2019-01-01 16:00:00      95.916686
       2019-01-01 17:00:00      11.579450
       2019-01-01 18:00:00      91.226938
       2019-01-01 19:00:00      31.564530
       2019-01-01 20:00:00      39.511358
       2019-01-01 21:00:00      59.787468
       2019-01-01 22:00:00      4.666549
       2019-01-01 23:00:00      92.197337
#... etc

You can then access each level of the data using these indices:

df.loc[1005, :]

  >
date                     score
2019-01-01 00:00:00      99.438851
2019-01-01 01:00:00      92.081975
2019-01-01 02:00:00      93.032991
2019-01-01 03:00:00      1.991615
2019-01-01 04:00:00      12.723531
2019-01-01 05:00:00      74.443313
2019-01-01 06:00:00      12.154499
2019-01-01 07:00:00      96.439228
2019-01-01 08:00:00      64.283731
2019-01-01 09:00:00      83.165093
2019-01-01 10:00:00      75.740610
2019-01-01 11:00:00      25.721404
2019-01-01 12:00:00      37.493829
2019-01-01 13:00:00      51.783549
2019-01-01 14:00:00      7.223582
2019-01-01 15:00:00      0.932651
2019-01-01 16:00:00      95.916686
2019-01-01 17:00:00      11.579450

You can also loop through all the 'levels' of the data using:

for level, data in df.groupby(level=0):
   # do something to 'level'

And, if needed, get a list of all 'levels' contained in the data:

df.index.levels[0]

  > [1005, 1027, ...]

This might prove to be more flexible than creating numerous individually named dataframes, and is closer to the indended use of pandas.


问:
How to use a lis of parameterized property names and type for a java bean
Say I have a bean

```<code>public class SomeBean{
     List<String> messages;
     List<Integer> scores;
     String id;
     int  number;
</code>```

....
    }

I am using the following code to process or dump the propreties

```<code>        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
        PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors();
        int stop = descriptors.length;
        for (int i = 0; i < stop; ++i) {
            PropertyDescriptor descriptor = descriptors[i];
            logger.info(descriptor.getName() + " : " + descriptor.getPropertyType().getName() + ", writemethod :" + descriptor.getWriteMethod());

        }
</code>```

That I want to be able to get the parameterized type for the "scores" and "messages".
When I ruin the code, the value for the " descriptor.getPropertyType().getName()"  is "java.util.List" for both messages and scores .

How do I tell if the property descriptor for "message" is referring to List<String> and for "scores" is referring to List<Integer> ?

答:
There are two cases.

The first case is when the property's parameterized type is not known at compile time:

```<code>public class Pair<A, B> {
  public A getFirst() { ... }
  public B getSecond() { ... }
}
</code>```

In this case, you cannot know at compile time, and is what @darioo is talking about.

The second case is yours, when the properties' type parameters are known at runtime. The code below should help you figure out exactly what you want to do:

```<code>BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor d : descriptors) {
    final Type type = d.getReadMethod().getGenericReturnType();
    if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        System.out.println(d.getDisplayName());
        for (Type atp : pt.getActualTypeArguments()) {
            System.out.println("  " + atp);
        }
    }
}
</code>```

The key here is to get the read or write method, and use the API Method.getGenericReturnType() or Method.getParameterTypes() respectively.

Note that dealing with java.lang.reflect.Type generically gets quite tedious/tricky, consider, for example:

```<code>public Map<Nation, Map<A extends PostCode, B extends Location>> getGlobalPostCodes() { ... }
</code>```

Body:
Say I have a bean

public class SomeBean{
     List<String> messages;
     List<Integer> scores;
     String id;
     int  number;

....
    }

I am using the following code to process or dump the propreties

        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
        PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors();
        int stop = descriptors.length;
        for (int i = 0; i < stop; ++i) {
            PropertyDescriptor descriptor = descriptors[i];
            logger.info(descriptor.getName() + " : " + descriptor.getPropertyType().getName() + ", writemethod :" + descriptor.getWriteMethod());

        }

That I want to be able to get the parameterized type for the "scores" and "messages".
When I ruin the code, the value for the " descriptor.getPropertyType().getName()"  is "java.util.List" for both messages and scores .

How do I tell if the property descriptor for "message" is referring to List<String> and for "scores" is referring to List<Integer> ?

Body:
There are two cases.

The first case is when the property's parameterized type is not known at compile time:

public class Pair<A, B> {
  public A getFirst() { ... }
  public B getSecond() { ... }
}

In this case, you cannot know at compile time, and is what @darioo is talking about.

The second case is yours, when the properties' type parameters are known at runtime. The code below should help you figure out exactly what you want to do:

BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
PropertyDescriptor descriptors[] = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor d : descriptors) {
    final Type type = d.getReadMethod().getGenericReturnType();
    if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        System.out.println(d.getDisplayName());
        for (Type atp : pt.getActualTypeArguments()) {
            System.out.println("  " + atp);
        }
    }
}

The key here is to get the read or write method, and use the API Method.getGenericReturnType() or Method.getParameterTypes() respectively.

Note that dealing with java.lang.reflect.Type generically gets quite tedious/tricky, consider, for example:

public Map<Nation, Map<A extends PostCode, B extends Location>> getGlobalPostCodes() { ... }