问:
How do I change the width of the country picker in flutter?

I am implementing country code picker and mobile number field.

How do I change the size of the country picker so that both the country picker and the mobile number text field are properly place.

Code is as follow

```<code>Row(
                      children: <Widget>[
                        Expanded(
                          //SizedBox(height: 20.0),
                          child: CountryPicker(
                            dense: true,
                            showFlag: false, //displays flag, true by default
                            showDialingCode:true, //displays dialing code, false by default
                            showName: true, //displays country name, true by default
                            showCurrency: false, //eg. 'British pound'
                            showCurrencyISO: false,
                            onChanged: (Country country) {
                              setState(() => _selected = country);
                              print(country.dialingCode);
                              countryCode = country.dialingCode;
                              },
                            selectedCountry: _selected,
                          ),
                        ),
                        Expanded(
                          //SizedBox(height: 20.0),
                          child: TextFormField(
                            decoration: InputDecoration(
                              labelText: 'Mobile no.',
                              border: OutlineInputBorder(),
                            ),
                            validator: (val) => val.length != 10
                                ? 'Enter a mobile number of 10 digits'
                                : null,
                            onChanged: (val) {
                              setState(() => phone = val);
                              phoneno = phone;
                              },
                          ),
                        ),
                      ],
                    ),
</code>```

Image is attached below

答:
You can simply wrap your widget in containers with width without Expanded. This is the code I used with device width

```<code>Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          Container(
                            width: MediaQuery.of(context).size.width / 3.7,
                            margin: EdgeInsets.only(top: 20),
                            child: CountryPicker(
                              dense: true,
                              showFlag: false, //displays flag, true by default
                              showDialingCode:
                                  true, //displays dialing code, false by default
                              showName:
                                  true, //displays country name, true by default
                              showCurrency: false, //eg. 'British pound'
                              showCurrencyISO: false,
                              onChanged: (Country country) {
                                setState(() => _selected = country);
                                print(country.dialingCode);
                                countryCode = country.dialingCode;
                              },
                              selectedCountry: _selected,
                            ),
                          ),
                          Container(
                            width: MediaQuery.of(context).size.width / 1.6,
                            margin: EdgeInsets.only(top: 40),
                            child: TextFormField(
                              decoration: InputDecoration(
                                labelText: 'Mobile no.',
                                border: OutlineInputBorder(),
                              ),
                              validator: (val) => val.length != 10
                                  ? 'Enter a mobile number of 10 digits'
                                  : null,
                              onChanged: (val) {
                                setState(() => phone = val);
                                phoneno = phone;
                              },
                            ),
                          ),
                        ],
                      ),
</code>```

Body:
I am implementing country code picker and mobile number field.

How do I change the size of the country picker so that both the country picker and the mobile number text field are properly place.

Code is as follow

Row(
                      children: <Widget>[
                        Expanded(
                          //SizedBox(height: 20.0),
                          child: CountryPicker(
                            dense: true,
                            showFlag: false, //displays flag, true by default
                            showDialingCode:true, //displays dialing code, false by default
                            showName: true, //displays country name, true by default
                            showCurrency: false, //eg. 'British pound'
                            showCurrencyISO: false,
                            onChanged: (Country country) {
                              setState(() => _selected = country);
                              print(country.dialingCode);
                              countryCode = country.dialingCode;
                              },
                            selectedCountry: _selected,
                          ),
                        ),
                        Expanded(
                          //SizedBox(height: 20.0),
                          child: TextFormField(
                            decoration: InputDecoration(
                              labelText: 'Mobile no.',
                              border: OutlineInputBorder(),
                            ),
                            validator: (val) => val.length != 10
                                ? 'Enter a mobile number of 10 digits'
                                : null,
                            onChanged: (val) {
                              setState(() => phone = val);
                              phoneno = phone;
                              },
                          ),
                        ),
                      ],
                    ),

Image is attached below

Body:
You can simply wrap your widget in containers with width without Expanded. This is the code I used with device width

Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          Container(
                            width: MediaQuery.of(context).size.width / 3.7,
                            margin: EdgeInsets.only(top: 20),
                            child: CountryPicker(
                              dense: true,
                              showFlag: false, //displays flag, true by default
                              showDialingCode:
                                  true, //displays dialing code, false by default
                              showName:
                                  true, //displays country name, true by default
                              showCurrency: false, //eg. 'British pound'
                              showCurrencyISO: false,
                              onChanged: (Country country) {
                                setState(() => _selected = country);
                                print(country.dialingCode);
                                countryCode = country.dialingCode;
                              },
                              selectedCountry: _selected,
                            ),
                          ),
                          Container(
                            width: MediaQuery.of(context).size.width / 1.6,
                            margin: EdgeInsets.only(top: 40),
                            child: TextFormField(
                              decoration: InputDecoration(
                                labelText: 'Mobile no.',
                                border: OutlineInputBorder(),
                              ),
                              validator: (val) => val.length != 10
                                  ? 'Enter a mobile number of 10 digits'
                                  : null,
                              onChanged: (val) {
                                setState(() => phone = val);
                                phoneno = phone;
                              },
                            ),
                          ),
                        ],
                      ),


来源: stackexchange

问:
Binary format and bit format
how to you know what code format is..?

Is this below code is Binary or bit? and how to convert in any other format or number decimal format

01 00 00 00 04 00 00 00 00 00 00 00 00 00 80 3F 00 00 80 3F 00 00 80 3F 00 00 80 3F 00 00 80 3F 00 00 80 3F 00 00 80 3F 00 00 80 3F 00 00 80 3F 00 00 80 3F 00 00 80 3F

答:
Binary means that you have two possible states (base 2). 1 and 0.

Something that bears that atomic information is usually referred to as a bit.

What you see there are hexadecimal numbers. (base 16)

This notation is often used to display binary data in a more compact form.

The decimal number 255 can be written as 11111111 (binary) or FF (hex)
So each pair is one byte. What they mean depends on where you got those numbers from.

ContentLicense: CC BY-SA 4.0

Title: Binary format and bit format


问:
URL for managing subscription in iOS
A user has subscribed to my auto-renewable in app subscription.
I want to provide a button called "Manage subscription".

This should jump to the App Store under the subscription management for my specific app.

What URL should I redirect to achieve this?

答:
This is the new URL that should be used:

https://apps.apple.com/account/subscriptions

ContentLicense: CC BY-SA 3.0

Title: URL for managing subscription in iOS


问:
CNN model not learning
I'm building a CNN model to classify images, however, I guess that my model is not learning because of the constant values of accuracy and loss function. See my code below:

Building the images train, test and validation datasets

```<code>import pandas as pd
from keras_preprocessing.image import ImageDataGenerator
import numpy as np

#Creating three datasets from the the 3 .txt files.
trainingfile = pd.read_table('data/training.txt', delim_whitespace=True, names=('class', 'image'))
testingfile = pd.read_table('data/testing.txt', delim_whitespace=True, names=('class', 'image'))
validationfile = pd.read_table('data/validation.txt', delim_whitespace=True, names=('class', 'image'))
#Changing target variable type
trainingfile = trainingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
testingfile = testingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
validationfile = validationfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])

#Data augmentation
datagen=ImageDataGenerator()
train_datagen = ImageDataGenerator(
    #Apliquem una mica de rotació no gaire ja que generalment les fotografies estaran centrades
    rotation_range=5,
    zoom_range=0.1)

#Final datasets containing the images
train=train_datagen.flow_from_dataframe(dataframe=trainingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
test=datagen.flow_from_dataframe(dataframe=testingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
#No data augmentation to the validation dataset.
validation=datagen.flow_from_dataframe(dataframe=validationfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb', batch_size=32)
</code>```

CNN model

```<code>from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Activation, Dropout, MaxPooling2D, BatchNormalization
from keras.constraints import maxnorm

#Creació del model
model = Sequential()
#1r bloc convolució
model.add(Conv2D(32, kernel_size = (3, 3), activation='relu', input_shape=(256, 256,3)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#2n bloc convolució
model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#3r bloc convolució
model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#4t bloc convolució
model.add(Conv2D(96, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#5e bloc convolució
model.add(Conv2D(32, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#Dropout
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
#model.add(Dropout(0.3))
model.add(Dense(3, activation = 'softmax'))

from keras import regularizers, optimizers
from keras.optimizers import RMSprop
from keras.callbacks import EarlyStopping
# Compile model
model.compile(optimizer='adam',loss="categorical_crossentropy",metrics=["accuracy"])
# Early stopping
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1,patience=10)
</code>```

Training the model

```<code>h=model.fit_generator(generator=train,
                      validation_data=validation,
                      epochs=50,
                      callbacks=[es])
</code>```

Results

It is the first time that I use fit_generator and perhaps I'm not using it properly?

答:
As I can see from the results images, you are training just for 1 epoch. This could be because the EarlyStopping is too strict. Try adding patience=3to the EarlyStopping callback.

```<code>es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3)
</code>```

EDIT

Overfitting example:

Check this post to know more about how to deal with overfitting.

Title: CNN model not learning

Body:
I'm building a CNN model to classify images, however, I guess that my model is not learning because of the constant values of accuracy and loss function. See my code below:

Building the images train, test and validation datasets

import pandas as pd
from keras_preprocessing.image import ImageDataGenerator
import numpy as np

#Creating three datasets from the the 3 .txt files.
trainingfile = pd.read_table('data/training.txt', delim_whitespace=True, names=('class', 'image'))
testingfile = pd.read_table('data/testing.txt', delim_whitespace=True, names=('class', 'image'))
validationfile = pd.read_table('data/validation.txt', delim_whitespace=True, names=('class', 'image'))
#Changing target variable type
trainingfile = trainingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
testingfile = testingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
validationfile = validationfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])

#Data augmentation
datagen=ImageDataGenerator()
train_datagen = ImageDataGenerator(
    #Apliquem una mica de rotació no gaire ja que generalment les fotografies estaran centrades
    rotation_range=5,
    zoom_range=0.1)

#Final datasets containing the images
train=train_datagen.flow_from_dataframe(dataframe=trainingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
test=datagen.flow_from_dataframe(dataframe=testingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
#No data augmentation to the validation dataset.
validation=datagen.flow_from_dataframe(dataframe=validationfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb', batch_size=32)

CNN model

from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Activation, Dropout, MaxPooling2D, BatchNormalization
from keras.constraints import maxnorm

#Creació del model
model = Sequential()
#1r bloc convolució
model.add(Conv2D(32, kernel_size = (3, 3), activation='relu', input_shape=(256, 256,3)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#2n bloc convolució
model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#3r bloc convolució
model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#4t bloc convolució
model.add(Conv2D(96, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#5e bloc convolució
model.add(Conv2D(32, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
#Dropout
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
#model.add(Dropout(0.3))
model.add(Dense(3, activation = 'softmax'))

from keras import regularizers, optimizers
from keras.optimizers import RMSprop
from keras.callbacks import EarlyStopping
# Compile model
model.compile(optimizer='adam',loss="categorical_crossentropy",metrics=["accuracy"])
# Early stopping
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1,patience=10)

Training the model

h=model.fit_generator(generator=train,
                      validation_data=validation,
                      epochs=50,
                      callbacks=[es])

Results

It is the first time that I use fit_generator and perhaps I'm not using it properly?

Body:
As I can see from the results images, you are training just for 1 epoch. This could be because the EarlyStopping is too strict. Try adding patience=3to the EarlyStopping callback.

es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3)

EDIT

Overfitting example:

Check this post to know more about how to deal with overfitting.


问:
Enable HTTP2 with Tomcat in Spring Boot
Tomcat 8.5, which will be the default in Spring Boot 1.4, supports HTTP/2.

How can HTTP/2 be enabled in a Spring Boot application?

答: Spring Boot 2.2.0+ ships by default with Tomcat 9.0.x which supports HTTP/2 out of the box when using JDK 9 or later. Link</p>

Title: Enable HTTP2 with Tomcat in Spring Boot


问:
Anylogic, mutate the capacity of the resource dynamically
I have a model with a queue and two machines, one of which is used just in case of overcrowding of the queue in front of these resources.
My model has a simple Queue and a Delay block and I tried to mutate the Delay capacity based on a previous queue length using a function like this (written in Delay block capacity text field):

```<code>    if (queue.size() > 5)
      return 2;
    else
      return 1;
</code>```

But it doesn't seem to work... is it possible to change the number of resources dynamically based on a condition?

答:
the capacity value in the delay block is only considered in the beginning of the simulation, so it can only be considered as the initial value...

To change the capacity later, you can put some code in the on enter and on exit of the queue block:

```<code>delay.set_capacity(queue.size() > 5 ? 2 : 1);
</code>```

Something like that.

Body:
I have a model with a queue and two machines, one of which is used just in case of overcrowding of the queue in front of these resources.
My model has a simple Queue and a Delay block and I tried to mutate the Delay capacity based on a previous queue length using a function like this (written in Delay block capacity text field):

    if (queue.size() > 5)
      return 2;
    else
      return 1;

But it doesn't seem to work... is it possible to change the number of resources dynamically based on a condition?

Body:
the capacity value in the delay block is only considered in the beginning of the simulation, so it can only be considered as the initial value...

To change the capacity later, you can put some code in the on enter and on exit of the queue block:

delay.set_capacity(queue.size() > 5 ? 2 : 1);

Something like that.


问:
Create a dict from a list of tuples by summing values for the same keys
I have this list:

```<code>[(2018, '2', '172767270', '202', 'gege', 'French'),
 (2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),
 (2013, 'J21', '186144990', '200', 'sacacs', 'Latin'),
 ...
]
</code>```

I want the output to be a dictionary based on the key in the last column and the sum of values in the 3rd column.

E.g. for (172767270, French) and (1374767888, French) with their sum  172767270 + 1374767888 = 1547535158 the dictionary would have the following key-value pair:

```<code>dic = {'French': 1547535158, ...}
</code>```

and the final result would be something like:

```<code>dic = {'French': 324213424, 'Latin': 34234242, ...}
</code>```

答:
First we have to add all the values based on language.

```<code>lang = [(2018, '2', '172767270', '202', 'gege', 'French'),(2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),(2013, 'J21', '186144990', '200', 'sacacs', 'Latin')]
dic = {}
for l in lang:
    dic[l[5]] = dic.get(l[5], 0) + int(l[2])
</code>```

Now we have a dictionary with the sum of 3rd columns of all languages. Now lets sort it to get the top 5.

```<code>dic2 = dict(sorted(dic.items(),key=dict.get, reverse=True)[:5])
</code>```

Now the dic2 has only the top 5 languages with highest 3rd column sum.

Body:
I have this list:

[(2018, '2', '172767270', '202', 'gege', 'French'),
 (2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),
 (2013, 'J21', '186144990', '200', 'sacacs', 'Latin'),
 ...
]

I want the output to be a dictionary based on the key in the last column and the sum of values in the 3rd column.

E.g. for (172767270, French) and (1374767888, French) with their sum  172767270 + 1374767888 = 1547535158 the dictionary would have the following key-value pair:

dic = {'French': 1547535158, ...}

and the final result would be something like:

dic = {'French': 324213424, 'Latin': 34234242, ...}

Body:
First we have to add all the values based on language.

lang = [(2018, '2', '172767270', '202', 'gege', 'French'),(2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),(2013, 'J21', '186144990', '200', 'sacacs', 'Latin')]
dic = {}
for l in lang:
    dic[l[5]] = dic.get(l[5], 0) + int(l[2])

Now we have a dictionary with the sum of 3rd columns of all languages. Now lets sort it to get the top 5.

dic2 = dict(sorted(dic.items(),key=dict.get, reverse=True)[:5])

Now the dic2 has only the top 5 languages with highest 3rd column sum.


问:
How to I get hot module reloading to work in a typescript monorepo
So I've been trying for the last few days completely in vain to get hot module reloading working in my Typescript/React/Koa/Mongo based monorepo; I feel like I've been banging my head against a brick wall. The documentation for HMR is pitiful (almost everything on the internet only goes part of the way of explaining how to do something). I've done a lot of googling and read lots of different ... similar versions of my problem, but nobody seems to have a useful solution.

I've put together a minimal repo version of the problem: https://github.com/benwainwright/hmr-issue-minimal-repo, that is roughly how my project is set up:

packages/one is a Yarn workspace containing the backend code

packages/two is a Yarn workspace containing the React
components/frontend code

If I build this and run it, I can sometimes get it to notice that I'm trying to do a hot reload in the client, fail, and then do a complete page reload. When that happens, the following error appears on the console

```<code>｢hot｣ Error: Aborted because ../two/renderApp.tsx is not acceptedUpdate propagation:
../two/renderApp.tsx -> ../two/index.tsx -> ./src/frontend-entry-point.tsx -> 1    at
hotApplyInternal (http://localhost/assets/app.js:508:30)    at Object.hotApply [as apply]
(http://localhost/assets/app.js:362:19)    at eval (webpack-internal:///./node_modules/webpack-hot-
client/client/hot.js:121:23)
</code>```

I've tried all sorts of different combinations of the various packages and I've also swapped the code that does the hotswap (https://github.com/benwainwright/hmr-issue-minimal-repo/blob/edcd8ad8c4fb9686abce12237d51a5b6f37dd636/packages/two/renderApp.tsx#L13-L16) with react-hot-loader. Nothing works. If anyone has any idea how to get this working, I'll be eternally greatful!

答:
There are several things that you need to apply in order for react-hot loader to work.

Apply "react-hot-loader/babel" in your babel plugins

Make alias of react-dom to @hot-loader/react-dom

Wrap you App root component with hot hoc which comes from react-hot-loader/root

These steps are basic use-case of React HMR based on https://github.com/gaearon/react-hot-loader/tree/master/examples/typescript.

The thing is that your case is a bit more complicated since your front-end app is located in a node_modules, and by default babel doesn't compiles modules inside node_modules, therefore you need to specify that you want to compile them.

You can read the explanation inside my answer here: Use Webpack HMR with a hoisted Lerna React Project

Body:
So I've been trying for the last few days completely in vain to get hot module reloading working in my Typescript/React/Koa/Mongo based monorepo; I feel like I've been banging my head against a brick wall. The documentation for HMR is pitiful (almost everything on the internet only goes part of the way of explaining how to do something). I've done a lot of googling and read lots of different ... similar versions of my problem, but nobody seems to have a useful solution.

I've put together a minimal repo version of the problem: https://github.com/benwainwright/hmr-issue-minimal-repo, that is roughly how my project is set up:

packages/one is a Yarn workspace containing the backend code

packages/two is a Yarn workspace containing the React
components/frontend code

If I build this and run it, I can sometimes get it to notice that I'm trying to do a hot reload in the client, fail, and then do a complete page reload. When that happens, the following error appears on the console

｢hot｣ Error: Aborted because ../two/renderApp.tsx is not acceptedUpdate propagation:
../two/renderApp.tsx -> ../two/index.tsx -> ./src/frontend-entry-point.tsx -> 1    at
hotApplyInternal (http://localhost/assets/app.js:508:30)    at Object.hotApply [as apply]
(http://localhost/assets/app.js:362:19)    at eval (webpack-internal:///./node_modules/webpack-hot-
client/client/hot.js:121:23)

I've tried all sorts of different combinations of the various packages and I've also swapped the code that does the hotswap (https://github.com/benwainwright/hmr-issue-minimal-repo/blob/edcd8ad8c4fb9686abce12237d51a5b6f37dd636/packages/two/renderApp.tsx#L13-L16) with react-hot-loader. Nothing works. If anyone has any idea how to get this working, I'll be eternally greatful!


问:
How to pass more than one argument to a worker at backgroundrb
I'm trying to pass a list of arguments to a backgroundrb

in documentation it says:
 MiddleMan.worker(:billing_worker).async_charge_customer(:arg => current_customer.id)

but it only works for just one argument, I tried these but none worked for me
args => [1,2,3]
args => {:t=>"t", :r=> "r"}

any ideas how to solve this??

答:
Actually, the second method you've tried (args => {:t=>"t", :r=> "r"}) should work.

In your worker:

```<code>def charge_customer(arg)
  customer_id   = arg[:customer_id]
  customer_name = arg[:customer_name]

  #do whatever you need to do with these arguments...
end
</code>```

And then, you can call the worker like this:

```<code>MiddleMan.worker(:billing_worker).async_charge_customer(:arg => { :customer_id => current_customer.id, :customer_name => current_customer.name })
</code>```

Basically, what you're doing here is pass a single Hash as the one argument the worker accepts. But since a Hash can contain multiple key-value pairs, you can access all of these individually inside your worker.

Body:
Actually, the second method you've tried (args => {:t=>"t", :r=> "r"}) should work.

In your worker:

def charge_customer(arg)
  customer_id   = arg[:customer_id]
  customer_name = arg[:customer_name]

  #do whatever you need to do with these arguments...
end

And then, you can call the worker like this:

MiddleMan.worker(:billing_worker).async_charge_customer(:arg => { :customer_id => current_customer.id, :customer_name => current_customer.name })

Basically, what you're doing here is pass a single Hash as the one argument the worker accepts. But since a Hash can contain multiple key-value pairs, you can access all of these individually inside your worker.


问:
I am facing problem will installing webpack by npm install webpack?
npm ERR! Unexpected end of JSON input while parsing near '...pes/node":"^12.6.9","'

npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\Dubey\AppData\Roaming\npm-cache_logs\2020-05-30T08_45_02_091Z-debug.log

Please help me to get over this error.

答:
try this</p>

```<code>npm cache clean --force
</code>```

Body:
try this

npm cache clean --force


问:
Are both source code changes and environment setting changes of vcproject reflected in git when commit (push)?
In the process of building the team library, I changed the environment settings of some vcprojects and wondered if they are reflected in git when I commit (push) them.

Only changes to the source code are reflected ??

Thank you for your reply.

答:
git versions files.

If it is not in a file, it is not versioned ; if it is in one of the vcproject's files, it will be versioned.


问:
Is there a way to relationship between two table which table one has 3 unique keys and table two has 2 unique keys in SQL Server?
I want to create relation between two tables, here's my table structure

Table1:

```<code>ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
SubDivision VARCHAR(10) UNIQUE
</code>```

Table2:

```<code>ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
ReportNo VARCHAR(10) UNIQUE
</code>```

Table1:

```<code>ID     |CountryCode       |Division      |SubDivision
-------+------------------+--------------+-----------
1      |IDN               |A             |A-1
2      |IDN               |B             |B-1
3      |IDN               |B             |B-2
</code>```

Table2

```<code>ID     |CountryCode       |Division      |ReportNo
-------+------------------+--------------+-----------
1      |IDN               |A             |Re001
2      |IDN               |A             |Re002
3      |IDN               |B             |Re003
</code>```

I want to create a relationship between those two tables which table2 (CountryCode, Division) refers to table1 (CountryCode, Division).

So when I want to delete in table1 with CountryCode = IDN and Division = A, SQL will prompt error when table2 contains CountryCode = IDN and Division = A.

I had tried to create a relationship between those two tables, but SQL Server always throws this error:

The column in table 'table1' do not match an existing primary key or unique constraint

Can anyone guide me how can I create a relationship between those two tables?

Thanks in advance

答:
As GMB has answered you cannot do it in this way because of the duplicates. GMB's answer is the best way to solving your problem. If for some reason you cannot follow his advice then maybe my answer would help.

You could use a composite primary key on the columns CountryCode, Division, SubDivision. Then add subdivision to Table2. And then reference this primary key in the foreignkey restraint. (notice that my example throws an error on purpose to show that the value cannot be deleted)

```<code>DROP TABLE IF EXISTS Table2;
DROP TABLE IF EXISTS Table1;
CREATE TABLE Table1
    (ID INT IDENTITY(1,1)
    , CountryCode CHAR(3)
    , Division VARCHAR(4)
    , SubDivision VARCHAR(10)
    , CONSTRAINT PK_Table1 PRIMARY KEY(CountryCode, Division, SubDivision)
    )
INSERT INTO Table1(CountryCode, Division, SubDivision)
VALUES    ('IDN', 'A', 'A-1')
        , ('IDN', 'B', 'B-1')
        , ('IDN', 'B', 'B-2');

CREATE TABLE Table2
    (ID INT IDENTITY(1,1) PRIMARY KEY
    , CountryCode CHAR(3)
    , Division VARCHAR(4)
    , SubDivision VARCHAR(10)
    , ReportNo VARCHAR(10)
    , CONSTRAINT FK_CountryDivision FOREIGN KEY(CountryCode, Division, SubDivision) REFERENCES Table1(CountryCode, Division, SubDivision)
    );
INSERT INTO Table2(CountryCode, Division, SubDivision, ReportNo)
VALUES    ('IDN', 'A', 'A-1', 'Re001')
        , ('IDN', 'B', 'B-1', 'Re002')
        , ('IDN', 'B', 'B-2', 'Re003');

DELETE FROM Table1
WHERE Division = 'A';
</code>```

Of course this change could add a whole set of new problems for instance when a report is for the whole division what should the subdivision value then be.

ps. i had to change up the example tables a bit because the values did not match, ie string values into an int column.

SQL fiddle

Body:
I want to create relation between two tables, here's my table structure

Table1:

ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
SubDivision VARCHAR(10) UNIQUE

Table2:

ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
ReportNo VARCHAR(10) UNIQUE

Table1:

ID     |CountryCode       |Division      |SubDivision
-------+------------------+--------------+-----------
1      |IDN               |A             |A-1
2      |IDN               |B             |B-1
3      |IDN               |B             |B-2

Table2

ID     |CountryCode       |Division      |ReportNo
-------+------------------+--------------+-----------
1      |IDN               |A             |Re001
2      |IDN               |A             |Re002
3      |IDN               |B             |Re003

I want to create a relationship between those two tables which table2 (CountryCode, Division) refers to table1 (CountryCode, Division).

So when I want to delete in table1 with CountryCode = IDN and Division = A, SQL will prompt error when table2 contains CountryCode = IDN and Division = A.

I had tried to create a relationship between those two tables, but SQL Server always throws this error:

The column in table 'table1' do not match an existing primary key or unique constraint

Can anyone guide me how can I create a relationship between those two tables?

Thanks in advance

Body:
As GMB has answered you cannot do it in this way because of the duplicates. GMB's answer is the best way to solving your problem. If for some reason you cannot follow his advice then maybe my answer would help.

You could use a composite primary key on the columns CountryCode, Division, SubDivision. Then add subdivision to Table2. And then reference this primary key in the foreignkey restraint. (notice that my example throws an error on purpose to show that the value cannot be deleted)

DROP TABLE IF EXISTS Table2;
DROP TABLE IF EXISTS Table1;
CREATE TABLE Table1
    (ID INT IDENTITY(1,1)
    , CountryCode CHAR(3)
    , Division VARCHAR(4)
    , SubDivision VARCHAR(10)
    , CONSTRAINT PK_Table1 PRIMARY KEY(CountryCode, Division, SubDivision)
    )
INSERT INTO Table1(CountryCode, Division, SubDivision)
VALUES    ('IDN', 'A', 'A-1')
        , ('IDN', 'B', 'B-1')
        , ('IDN', 'B', 'B-2');

CREATE TABLE Table2
    (ID INT IDENTITY(1,1) PRIMARY KEY
    , CountryCode CHAR(3)
    , Division VARCHAR(4)
    , SubDivision VARCHAR(10)
    , ReportNo VARCHAR(10)
    , CONSTRAINT FK_CountryDivision FOREIGN KEY(CountryCode, Division, SubDivision) REFERENCES Table1(CountryCode, Division, SubDivision)
    );
INSERT INTO Table2(CountryCode, Division, SubDivision, ReportNo)
VALUES    ('IDN', 'A', 'A-1', 'Re001')
        , ('IDN', 'B', 'B-1', 'Re002')
        , ('IDN', 'B', 'B-2', 'Re003');

DELETE FROM Table1
WHERE Division = 'A';

Of course this change could add a whole set of new problems for instance when a report is for the whole division what should the subdivision value then be.

ps. i had to change up the example tables a bit because the values did not match, ie string values into an int column.

SQL fiddle


问:
How to show specific div based on database value?
I am new to PHP and MySQL. I want to have a simple website, where users can log in to a simple dashboard. (No one can sign up on this website, it is meant only for my clients and I gave them the login details. Yes, I know that the password should be stored hashed, but I don't need it in this scenario.)

In the dashboard, I want to show the specific div based on database value. For example, if the row workout_1 in the table users is true, I want to show the div workout_1 etc. If the value is false, the div should be hide.

Based on some tutorials, I figured out how to set up a simple login/logout process. Now I am stuck on how to set up this show / hide div procedure. What I know is that I have to get the query somehow, but as I said, I am new to PHP and MySQL and a little advice from you I would really appreciate.

This is authentication.php

```<code><?php
session_start();

$DATABASE_HOST = '**';
$DATABASE_USER = '**';
$DATABASE_PASS = '**';
$DATABASE_NAME = 'tablename';

$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {

    exit('Error: ' . mysqli_connect_error());
}

if ( !isset($_POST['username'], $_POST['password']) ) {

    exit('Please fill both the username and password fields!');
}

if ($stmt = $con->prepare('SELECT id, password FROM users WHERE username = ?')) {

    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute();

    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($id, $password);
        $stmt->fetch();

        if ($_POST['password'] === $password) {

            session_regenerate_id();
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['name'] = $_POST['username'];
            $_SESSION['id'] = $id;
            header('Location: ../dashboard.php');
        } else {
            echo 'Incorrect password!';
        }
    } else {
        echo 'Incorrect username!';
    }

    $stmt->close();
}
</code>```

This is dashboard.php

```<code><?php

session_start();

if (!isset($_SESSION['loggedin'])) {
    header('Location: index.php');
    exit;
}
?>
</code>```

And this is HTML I want to show / hide based on MySQL query.

```<code><div id="workout_1">There are some notes for users they attended the 1st workout.</div>
<div id="workout_2">There are some notes for users they attended the 2nd workout.</div>
<div id="workout_3">There are some notes for users they attended the 3rd workout.</div>
</code>```

答:
Those are very basics of the MySQL and my first advice would be to review other similar questions on SO and read about connecting MYSQL to PHP.

You need to change a bit your query and take also workout_1 value from table users.

```<code>$stmt = $con->prepare('SELECT id, password, workout_1 password FROM users WHERE username = ?')
</code>```

And bind value of this parameter to the variable.

```<code>$stmt->bind_result($id, $password, $workout_1);
</code>```

When you have suitable variable you can just make conditional statement in proper place in your code.

```<code><?
if((bool)$workout_1) {
    echo'<div id="workout_1">There are some notes for users they attended the 1st workout.</div>';
}
?>

<div id="workout_2">There are some notes for users they attended the 2nd workout.</div>
<div id="workout_3">There are some notes for users they attended the 3rd workout.</div>
</code>```

Boolean values (true or false) in database should be stored in the columns with type Integer (1 - for true, 0 - for false). Also you should avoid mixing PHP code with View layer (HTML), but for the beginning it's all right.

EDIT:
Second approach. To include in dashboard.php.

```<code>$DATABASE_HOST = '**';
$DATABASE_USER = '**';
$DATABASE_PASS = '**';
$DATABASE_NAME = 'tablename';

$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {

    exit('Error: ' . mysqli_connect_error());
}
if ($stmt = $con->prepare('SELECT workout_1 FROM users WHERE id = ?')) {

    $stmt->bind_param('i', $_SESSION['id']);
    $stmt->execute();

    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($workout_1);
    }
}
</code>```

Body:
I am new to PHP and MySQL. I want to have a simple website, where users can log in to a simple dashboard. (No one can sign up on this website, it is meant only for my clients and I gave them the login details. Yes, I know that the password should be stored hashed, but I don't need it in this scenario.)

In the dashboard, I want to show the specific div based on database value. For example, if the row workout_1 in the table users is true, I want to show the div workout_1 etc. If the value is false, the div should be hide.

Based on some tutorials, I figured out how to set up a simple login/logout process. Now I am stuck on how to set up this show / hide div procedure. What I know is that I have to get the query somehow, but as I said, I am new to PHP and MySQL and a little advice from you I would really appreciate.

This is authentication.php

<?php
session_start();

$DATABASE_HOST = '**';
$DATABASE_USER = '**';
$DATABASE_PASS = '**';
$DATABASE_NAME = 'tablename';

$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {

    exit('Error: ' . mysqli_connect_error());
}

if ( !isset($_POST['username'], $_POST['password']) ) {

    exit('Please fill both the username and password fields!');
}

if ($stmt = $con->prepare('SELECT id, password FROM users WHERE username = ?')) {

    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute();

    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($id, $password);
        $stmt->fetch();

        if ($_POST['password'] === $password) {

            session_regenerate_id();
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['name'] = $_POST['username'];
            $_SESSION['id'] = $id;
            header('Location: ../dashboard.php');
        } else {
            echo 'Incorrect password!';
        }
    } else {
        echo 'Incorrect username!';
    }

    $stmt->close();
}

This is dashboard.php

<?php

session_start();

if (!isset($_SESSION['loggedin'])) {
    header('Location: index.php');
    exit;
}
?>

And this is HTML I want to show / hide based on MySQL query.

There are some notes for users they attended the 1st workout.

There are some notes for users they attended the 2nd workout.

There are some notes for users they attended the 3rd workout.

Body:
Those are very basics of the MySQL and my first advice would be to review other similar questions on SO and read about connecting MYSQL to PHP.

You need to change a bit your query and take also workout_1 value from table users.

$stmt = $con->prepare('SELECT id, password, workout_1 password FROM users WHERE username = ?')

And bind value of this parameter to the variable.

$stmt->bind_result($id, $password, $workout_1);

When you have suitable variable you can just make conditional statement in proper place in your code.

<?
if((bool)$workout_1) {
    echo'<div id="workout_1">There are some notes for users they attended the 1st workout.</div>';
}
?>

<div id="workout_2">There are some notes for users they attended the 2nd workout.</div>
<div id="workout_3">There are some notes for users they attended the 3rd workout.</div>

Boolean values (true or false) in database should be stored in the columns with type Integer (1 - for true, 0 - for false). Also you should avoid mixing PHP code with View layer (HTML), but for the beginning it's all right.

EDIT:
Second approach. To include in dashboard.php.

$DATABASE_HOST = '**';
$DATABASE_USER = '**';
$DATABASE_PASS = '**';
$DATABASE_NAME = 'tablename';

$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {

    exit('Error: ' . mysqli_connect_error());
}
if ($stmt = $con->prepare('SELECT workout_1 FROM users WHERE id = ?')) {

    $stmt->bind_param('i', $_SESSION['id']);
    $stmt->execute();

    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($workout_1);
    }
}


问:
PHP to Ruby snippet translation needed (Basic Authorization and URL access)
I need this in Ruby:

```<code>$context = stream_context_create(array(
    'http' => array(
        'header'  => "Authorization: Basic " . base64_encode("user:pass")
    )
));

$output = file_get_contents("http://example.com/file.php", false, $context);
</code>```

Thanks.

答:
Check out Net::HTTP.</p>

```<code>require 'net/http'

output = nil
Net::HTTP.start('example.com') {|http|
  req = Net::HTTP::Get.new('/file.php')
  req.basic_auth 'user', 'pass'
  response = http.request(req)
  output = response.body
}
</code>```

Body:
I need this in Ruby:

$context = stream_context_create(array(
    'http' => array(
        'header'  => "Authorization: Basic " . base64_encode("user:pass")
    )
));

$output = file_get_contents("http://example.com/file.php", false, $context);

Thanks.

Body:
Check out Net::HTTP.

require 'net/http'

output = nil
Net::HTTP.start('example.com') {|http|
  req = Net::HTTP::Get.new('/file.php')
  req.basic_auth 'user', 'pass'
  response = http.request(req)
  output = response.body
}


问:
try/except issue in Python
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

```<code>sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)
</code>```

答:
The problem with your code is that you are first taking both the variables sh and sr as input. So, even if you don't enter a numeric value it won't throw an error because the variables sh and sr don't care if it is a numeric value or not. After getting both the values the try block is executed.

So, if you want to receive an error message as soon as the user enters any alphabetic input, follow the below modified code. You can comment any doubts. Also, Tick the answer if it is correct.

```<code>try:
    fh = float(input('Enter hours:'))
    fr = float(input('Enter Rate:'))
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)
</code>```

The output for the test case forty is

```<code>Enter hours:Forty
Error, please enter numeric input
</code>```

Title: try/except issue in Python

Body:
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

Body:
The problem with your code is that you are first taking both the variables sh and sr as input. So, even if you don't enter a numeric value it won't throw an error because the variables sh and sr don't care if it is a numeric value or not. After getting both the values the try block is executed.

So, if you want to receive an error message as soon as the user enters any alphabetic input, follow the below modified code. You can comment any doubts. Also, Tick the answer if it is correct.

try:
    fh = float(input('Enter hours:'))
    fr = float(input('Enter Rate:'))
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

The output for the test case forty is

Enter hours:Forty
Error, please enter numeric input


问:
Using Scope_Identity() to add 2 foreign keys in SQL Server
I have a question about Scope_Identity() and transactions.

I have these three tables and the PK in MemberDetails is the FK in the other two tables.

I have been trying to create the stored procedure with Scope_Identity() so that the FK are automatically added in the tables, but I can't figure how to do it.

Do you have any idea?

Thanks in advance

```<code>CREATE TABLE [MarketingTarget]
(
    [MTid] int identity (5000,1) NOT NULL UNIQUE,
    [MDOB] date NOT NULL,
    [MSex] char (1) NOT NULL CHECK (MSex IN ('M','F')) DEFAULT 'M',
    [MemberID] int NULL,
    [MTUpdate] Date Null DEFAULT Getdate(),
    PRIMARY KEY ([MTid]),
    FOREIGN KEY (MemberID) REFERENCES [MemberDetails] ([MemberID])
            ON DELETE SET NULL
            ON UPDATE CASCADE
);

CREATE TABLE [MembershipDetails]
(
    [MDid] int identity (2000,1) NOT NULL UNIQUE,
    [MType] varchar(10) NOT NULL CHECK (MType IN ('Monthly','Quaterly','Yearly'))  DEFAULT 'Monthly',
    [JoinDate] Date NOT NULL DEFAULT GETDATE(),
    [ExpiryDate] Date NULL,
    [MsUpdate] Date DEFAULT GETDATE(),
    [MemberID] int NULL,
    PRIMARY KEY ([MDid]),
    FOREIGN KEY (MemberID) REFERENCES [MemberDetails] ([MemberID])
            ON DELETE SET NULL
            ON UPDATE CASCADE
);

CREATE TABLE [MemberDetails]
(
    [MemberID] int identity (1000,1) NOT NULL UNIQUE,
    [MName] varchar(100) NOT NULL,
    [MSurname] varchar(100) NOT NULL,
    [MPhone] varchar(20) NOT NULL UNIQUE,
    [MEmail] varchar(200) NOT NULL UNIQUE,
    [MAddress] varchar(250) NOT NULL,
    [MActive] char (1) NOT NULL CHECK (MActive IN ('Y','N')) DEFAULT 'Y',
    [MUpdateDate] Date NOT NULL DEFAULT GETDATE(),
    [MPhoto] Image NOT NULL
    PRIMARY KEY ([MemberID])
);
</code>```

```<code>CREATE PROC spInsertMarketingTarget_test1
    @MDOB date,
    @MSex char (1),
    @MemberID int,
    @MTUpdate Date
AS
    BEGIN TRY
        IF (SELECT COUNT(*) FROM MarketingTarget mt
            WHERE MemberID = @MemberID) > 0
            RAISERROR ('Fatal error. Member already exist.', 16, 1)

        BEGIN TRANSACTION
            INSERT INTO MarketingTarget
                SELECT
                    @MDOB, @MSex, @MemberID, @MTUpdate
            COMMIT TRANSACTION
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_STATE() AS ErrorState,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage;

    -- Transaction uncommittable
    IF (XACT_STATE()) = -1
        ROLLBACK TRANSACTION

    -- Transaction committable
    IF (XACT_STATE()) = 1
        COMMIT TRANSACTION
END CATCH;
GO

CREATE PROCEDURE spInsertMemberDetails
    @MemberID int = 0,
    @MName varchar(100),
    @MSurname varchar(100),
    @MPhone varchar(20),
    @MEmail varchar(200),
    @MAddress varchar(250),
    @MActive char (1),
    @MUpdateDate Date,
    @MPhoto image
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO [MemberDetails] (MName, MSurname, MPhone, MEmail, MAddress, MActive, MUpdateDate, MPhoto)
    VALUES (@MName, @MSurname, @MPhone, @MEmail, @MAddress, @MActive, @MUpdateDate, @MPhoto)

    SET @MemberID = SCOPE_IDENTITY()
END
GO
</code>```

答:
Basically, you have two options:

You can write a single stored procedure that takes all the parameters you need to insert the values into your three tables. Then inside that stored procedure, insert into the first table, get the identity value, and then insert into the second and third table, using that identity value.

```<code>CREATE PROCEDURE dbo.InsertAllData
    (--list all the parameters needed for all three inserts--)
AS
BEGIN
    INSERT INTO [MemberDetails] (MName, MSurname, MPhone, MEmail, MAddress, MActive, MUpdateDate, MPhoto)
    VALUES (@MName, @MSurname, @MPhone, @MEmail, @MAddress, @MActive, @MUpdateDate, @MPhoto)

    SELECT @MemberID = SCOPE_IDENTITY()

    INSERT INTO dbo.MarketingTarget (MemberID, -- other columns --)
    VALUES (@MemberID, -- other values);

    INSERT INTO dbo.MembershipDetails (MemberID, -- other columns --)
    VALUES (@MemberID, -- other values);
END;
</code>```

You can have three separate stored procedures, and the first one inserts into the "master" table and returns the newly created identity value back to the calling code. From there, using that value returned, you can then call the second and third stored procedure to insert into the second and third table. Make sure to wrap those three calls into a client-side transaction to ensure proper inserting of the data.

Body:
I have a question about Scope_Identity() and transactions.

I have these three tables and the PK in MemberDetails is the FK in the other two tables.

I have been trying to create the stored procedure with Scope_Identity() so that the FK are automatically added in the tables, but I can't figure how to do it.

Do you have any idea?

Thanks in advance

CREATE TABLE [MarketingTarget]
(
    [MTid] int identity (5000,1) NOT NULL UNIQUE,
    [MDOB] date NOT NULL,
    [MSex] char (1) NOT NULL CHECK (MSex IN ('M','F')) DEFAULT 'M',
    [MemberID] int NULL,
    [MTUpdate] Date Null DEFAULT Getdate(),
    PRIMARY KEY ([MTid]),
    FOREIGN KEY (MemberID) REFERENCES [MemberDetails] ([MemberID])
            ON DELETE SET NULL
            ON UPDATE CASCADE
);

CREATE TABLE [MembershipDetails]
(
    [MDid] int identity (2000,1) NOT NULL UNIQUE,
    [MType] varchar(10) NOT NULL CHECK (MType IN ('Monthly','Quaterly','Yearly'))  DEFAULT 'Monthly',
    [JoinDate] Date NOT NULL DEFAULT GETDATE(),
    [ExpiryDate] Date NULL,
    [MsUpdate] Date DEFAULT GETDATE(),
    [MemberID] int NULL,
    PRIMARY KEY ([MDid]),
    FOREIGN KEY (MemberID) REFERENCES [MemberDetails] ([MemberID])
            ON DELETE SET NULL
            ON UPDATE CASCADE
);

CREATE TABLE [MemberDetails]
(
    [MemberID] int identity (1000,1) NOT NULL UNIQUE,
    [MName] varchar(100) NOT NULL,
    [MSurname] varchar(100) NOT NULL,
    [MPhone] varchar(20) NOT NULL UNIQUE,
    [MEmail] varchar(200) NOT NULL UNIQUE,
    [MAddress] varchar(250) NOT NULL,
    [MActive] char (1) NOT NULL CHECK (MActive IN ('Y','N')) DEFAULT 'Y',
    [MUpdateDate] Date NOT NULL DEFAULT GETDATE(),
    [MPhoto] Image NOT NULL
    PRIMARY KEY ([MemberID])
);

CREATE PROC spInsertMarketingTarget_test1
    @MDOB date,
    @MSex char (1),
    @MemberID int,
    @MTUpdate Date
AS
    BEGIN TRY
        IF (SELECT COUNT(*) FROM MarketingTarget mt
            WHERE MemberID = @MemberID) > 0
            RAISERROR ('Fatal error. Member already exist.', 16, 1)

        BEGIN TRANSACTION
            INSERT INTO MarketingTarget
                SELECT
                    @MDOB, @MSex, @MemberID, @MTUpdate
            COMMIT TRANSACTION
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_STATE() AS ErrorState,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage;

    -- Transaction uncommittable
    IF (XACT_STATE()) = -1
        ROLLBACK TRANSACTION

    -- Transaction committable
    IF (XACT_STATE()) = 1
        COMMIT TRANSACTION
END CATCH;
GO

CREATE PROCEDURE spInsertMemberDetails
    @MemberID int = 0,
    @MName varchar(100),
    @MSurname varchar(100),
    @MPhone varchar(20),
    @MEmail varchar(200),
    @MAddress varchar(250),
    @MActive char (1),
    @MUpdateDate Date,
    @MPhoto image
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO [MemberDetails] (MName, MSurname, MPhone, MEmail, MAddress, MActive, MUpdateDate, MPhoto)
    VALUES (@MName, @MSurname, @MPhone, @MEmail, @MAddress, @MActive, @MUpdateDate, @MPhoto)

    SET @MemberID = SCOPE_IDENTITY()
END
GO

Body:
Basically, you have two options:

You can write a single stored procedure that takes all the parameters you need to insert the values into your three tables. Then inside that stored procedure, insert into the first table, get the identity value, and then insert into the second and third table, using that identity value.

CREATE PROCEDURE dbo.InsertAllData
    (--list all the parameters needed for all three inserts--)
AS
BEGIN
    INSERT INTO [MemberDetails] (MName, MSurname, MPhone, MEmail, MAddress, MActive, MUpdateDate, MPhoto)
    VALUES (@MName, @MSurname, @MPhone, @MEmail, @MAddress, @MActive, @MUpdateDate, @MPhoto)

    SELECT @MemberID = SCOPE_IDENTITY()

    INSERT INTO dbo.MarketingTarget (MemberID, -- other columns --)
    VALUES (@MemberID, -- other values);

    INSERT INTO dbo.MembershipDetails (MemberID, -- other columns --)
    VALUES (@MemberID, -- other values);
END;

You can have three separate stored procedures, and the first one inserts into the "master" table and returns the newly created identity value back to the calling code. From there, using that value returned, you can then call the second and third stored procedure to insert into the second and third table. Make sure to wrap those three calls into a client-side transaction to ensure proper inserting of the data.


问:
Use int64 nanotimes as array dimnames in R
I have some lovely nanotimes:

```<code>> mynames
[1] "2020-04-15T00:29:00.000000000+00:00" "2020-04-15T00:33:00.000000000+00:00"
</code>```

Which I'd like to add as dimnames to my array:

```<code>> a
     [,1] [,2]
[1,]   NA   NA
[2,]   NA   NA
</code>```

However, they seem to be converted into rolled over strings:

```<code>> dimnames(a)[1] <- list(values=mynames)
> a
                      [,1] [,2]
1.39309697650764e-202   NA   NA
1.39315136717363e-202   NA   NA

> dimnames(a)
[[1]]
[1] "1.39309697650764e-202" "1.39315136717363e-202"

</code>```

How can I keep my dimname assignment as nanotime/integer64s?  Or if they are forced to character to be dimnames, how can I at least keep them from being strings of incorrect numbers?

You can see for example that these fail to round-trip back to suitable times:

```<code>> nanotime(dimnames(a)[1][[1]][1])
Error in RcppCCTZ::parseDouble(x, fmt = format, tz = tz) :
  Parse error on 1.39309697650764e-202
</code>```

答:
The documentation of dimnames states that the value is coerced to character. To do all the coercing back and from to nanotime which is based on integer64, you can first coerce your nanotime to integer64 and then to character. Then the back coercion works:

```<code>library(nanotime)

mynames <- c(nanotime("2020-04-15T00:29:00.000000000+00:00"),
             nanotime("2020-04-15T00:33:00.000000000+00:00"))

a <- array(NA, dim = c(2, 2))
# nanotime -> integer64 -> charachter
dimnames(a)[1] <- list(values = as.character(as.integer64(mynames)))

# character -> integer64 -> nanotime
nanotime(as.integer64(dimnames(a)[1][[1]][1]))
[1] "2020-04-15T00:29:00.000000000+00:00"
</code>```

Body:
I have some lovely nanotimes:

> mynames
[1] "2020-04-15T00:29:00.000000000+00:00" "2020-04-15T00:33:00.000000000+00:00"

Which I'd like to add as dimnames to my array:

> a
     [,1] [,2]
[1,]   NA   NA
[2,]   NA   NA

However, they seem to be converted into rolled over strings:

> dimnames(a)[1] <- list(values=mynames)
> a
                      [,1] [,2]
1.39309697650764e-202   NA   NA
1.39315136717363e-202   NA   NA

> dimnames(a)
[[1]]
[1] "1.39309697650764e-202" "1.39315136717363e-202"

How can I keep my dimname assignment as nanotime/integer64s?  Or if they are forced to character to be dimnames, how can I at least keep them from being strings of incorrect numbers?

You can see for example that these fail to round-trip back to suitable times:

> nanotime(dimnames(a)[1][[1]][1])
Error in RcppCCTZ::parseDouble(x, fmt = format, tz = tz) :
  Parse error on 1.39309697650764e-202

Body:
The documentation of dimnames states that the value is coerced to character. To do all the coercing back and from to nanotime which is based on integer64, you can first coerce your nanotime to integer64 and then to character. Then the back coercion works:

library(nanotime)

mynames <- c(nanotime("2020-04-15T00:29:00.000000000+00:00"),
             nanotime("2020-04-15T00:33:00.000000000+00:00"))

a <- array(NA, dim = c(2, 2))
# nanotime -> integer64 -> charachter
dimnames(a)[1] <- list(values = as.character(as.integer64(mynames)))

# character -> integer64 -> nanotime
nanotime(as.integer64(dimnames(a)[1][[1]][1]))
[1] "2020-04-15T00:29:00.000000000+00:00"


问:
Array of filtered data to populate ListBox
Okay so I am filtering a sheet ("Data") by a criteria:

```<code>Sub Filter_Offene()
    Sheets("Data").Range("A:R").AutoFilter Field:=18, Criteria1:="WAHR"
End Sub

</code>```

Then, I want to put the Filtered Table to populate a Listbox
My problem here is, that the amount of rows can vary, so I thought i could try and list where the filtered table "ends" by doing this cells.find routine:

```<code>Dim lRow As Long
Dim lCol As Long

    lRow = ThisWorkbook.Sheets("Data").Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lRow = lRow + 1
</code>```

This unfotunatly also counts "hidden" rows, so in my example it doesnt count 2 but 7..
I've used .Range.SpecialCells(xlCellTypeVisible)before, but It doesn't seem to function with the cells.find above.
Does someone have an Idea on how I can count the visible (=filtered) Table, and then put it in a Listbox?

EDIT: I populate the listbox (unfiltered) like this:

```<code>Dim lastrow As Long
With Sheets("Data")
    lastrow = .Cells(.Rows.Count, "R").End(xlUp).Row
End With

With Offene_PZ_Form.Offene_PZ
.ColumnCount = 18
.ColumnWidths = "0;80;0;100;100;0;50;50;80;50;0;0;0;0;0;150;150;0"
.List = Sheets("Data").Range("A2:R" & lastrow).Value
End With
</code>```

But this won't work with filtered Data.

答:
Here is a fun little fact, Excel creates an hidden named range once you start filtering data. If you have continuous data (headers/rows) this would return your range without looking for it. Though since it seem to resemble UsedRange it may still be better to search your last used column and row and create your own Range variable to filter. For this exercise I'll leave it be. Furthermore, as indicated in the comments above, one can loop over Areas of visible cells. I'd recommend a check beforehand just to be safe that there is filtered data other than headers.

```<code>Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Data")
Dim Area as Range

ws.Cells(1, 1).AutoFilter 18, "WAHR"
With ws.Range("_FilterDatabase")
    If .SpecialCells(12).Count > .Columns.Count Then
        For Each Area In .Offset(1).Resize(.Rows.Count - 1, .Columns.Count).SpecialCells(12).Areas
            Debug.Print Area.Address 'Do something
        Next
    End If
End With

End Sub
</code>```

The above works if no headers are missing obviously.

Body:
Okay so I am filtering a sheet ("Data") by a criteria:

Sub Filter_Offene()
    Sheets("Data").Range("A:R").AutoFilter Field:=18, Criteria1:="WAHR"
End Sub

Then, I want to put the Filtered Table to populate a Listbox
My problem here is, that the amount of rows can vary, so I thought i could try and list where the filtered table "ends" by doing this cells.find routine:

Dim lRow As Long
Dim lCol As Long

    lRow = ThisWorkbook.Sheets("Data").Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lRow = lRow + 1

This unfotunatly also counts "hidden" rows, so in my example it doesnt count 2 but 7..
I've used .Range.SpecialCells(xlCellTypeVisible)before, but It doesn't seem to function with the cells.find above.
Does someone have an Idea on how I can count the visible (=filtered) Table, and then put it in a Listbox?

EDIT: I populate the listbox (unfiltered) like this:

Dim lastrow As Long
With Sheets("Data")
    lastrow = .Cells(.Rows.Count, "R").End(xlUp).Row
End With

With Offene_PZ_Form.Offene_PZ
.ColumnCount = 18
.ColumnWidths = "0;80;0;100;100;0;50;50;80;50;0;0;0;0;0;150;150;0"
.List = Sheets("Data").Range("A2:R" & lastrow).Value
End With

But this won't work with filtered Data.

Body:
Here is a fun little fact, Excel creates an hidden named range once you start filtering data. If you have continuous data (headers/rows) this would return your range without looking for it. Though since it seem to resemble UsedRange it may still be better to search your last used column and row and create your own Range variable to filter. For this exercise I'll leave it be. Furthermore, as indicated in the comments above, one can loop over Areas of visible cells. I'd recommend a check beforehand just to be safe that there is filtered data other than headers.

Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Data")
Dim Area as Range

ws.Cells(1, 1).AutoFilter 18, "WAHR"
With ws.Range("_FilterDatabase")
    If .SpecialCells(12).Count > .Columns.Count Then
        For Each Area In .Offset(1).Resize(.Rows.Count - 1, .Columns.Count).SpecialCells(12).Areas
            Debug.Print Area.Address 'Do something
        Next
    End If
End With

End Sub

The above works if no headers are missing obviously.


问:
websockets in micropython? (esp8266)
I'm working on a project that requires a control interface in the browser, because some controls are proportional and of very high resolution, it would be best to have a constant stream of data without the need for requests. After some research it appears I need to use a websocket (if there is a better way, that would be an equally useful answer) but the micropython websocket module appears completely undocumented and in fact not baked into my build. Does anyone know of a better module that has some really simple examples for an idiot like me?</p>

答:
You might be able to use EventSource. It allows your server to easily send a stream of data chunks over a single long-lived connection that can be easily handled in JavaScript (using the EventSource class).

Check out this example in picoweb.

PS: EventSource has some "icing on the cake" features including automatic reconnect, and replay. Discovering these is left as an exercise to the reader XD

Title: websockets in micropython? (esp8266)


问:
Backing up Jenkins
What is the optimal way to create a backup of your Jenkins CI server?

Currently, we create snapshots of the VM where Jenkins server is running but is there a more Agile/DevOps-y way of doing this?

答:
See my prior response to a similar question.  I'd also really advocate managing your configuration using Configuration as Code plugin, which is well supported now and manage system that way.

ps:It helps to search S/O before asking similar questions.

Title: Backing up Jenkins


答:
If I understand correctly what you want a for loop will do.

```<code>mylist = [] #your list as given above
mydict = {} #here we'll save the values

for(item in mylist):
    #read out the values needed
    value = item[2]
    language = item[-1] #item[6] would also work.

    #check if language is already in. If not? Than make it.
    if(language not in mydict):
        mydict[language] = 0

    #Add value to correct dictionary item.
    mydict[language] += value
</code>```

Than you have your full dictionary. Then check the dictionary for the top 5 items based on value.

```<code>def myfunc(elem): #returns second entry of tuple.
    return elem[1]

#get the list of all the entries
allEntries = list(mydict.items()) #list of tuples
sortedList = sorted(allEntries, key=myfunc, reverse=True) #list sorted on values

print(dict(sortedList[:5])) #dictionary of first five items of the sorted list
</code>```

I hope that is what you want.

Title: Create a dict from a list of tuples by summing values for the same keys

Body:
I have this list:

[(2018, '2', '172767270', '202', 'gege', 'French'),
 (2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),
 (2013, 'J21', '186144990', '200', 'sacacs', 'Latin'),
 ...
]

I want the output to be a dictionary based on the key in the last column and the sum of values in the 3rd column.

E.g. for (172767270, French) and (1374767888, French) with their sum  172767270 + 1374767888 = 1547535158 the dictionary would have the following key-value pair:

dic = {'French': 1547535158, ...}

and the final result would be something like:

dic = {'French': 324213424, 'Latin': 34234242, ...}

Body:
If I understand correctly what you want a for loop will do.

mylist = [] #your list as given above
mydict = {} #here we'll save the values

for(item in mylist):
    #read out the values needed
    value = item[2]
    language = item[-1] #item[6] would also work.

    #check if language is already in. If not? Than make it.
    if(language not in mydict):
        mydict[language] = 0

    #Add value to correct dictionary item.
    mydict[language] += value

Than you have your full dictionary. Then check the dictionary for the top 5 items based on value.

def myfunc(elem): #returns second entry of tuple.
    return elem[1]

#get the list of all the entries
allEntries = list(mydict.items()) #list of tuples
sortedList = sorted(allEntries, key=myfunc, reverse=True) #list sorted on values

print(dict(sortedList[:5])) #dictionary of first five items of the sorted list

I hope that is what you want.


答:
I'm assuming that you have a list of tuples. As you've mentioned, we don't need to import any modules. Use the dict.get() method to find the value of a key if it is present and 0 as a default if it is absent.

So for example if 'French' is not in the dictionary .get() will return 0 else it will return the value associated with 'French'

Then we can simply add the value of the third column to the value we returned by .get().

```<code>dict={}
for tup in lst:
    dict[tup[5]]=dict.get(tup[5],0)+ int(tup[2])

#to get top 5 values
dict2={}
for i in sorted(dict, key=dict.get, reverse=True)[:5]:
    dict2[i]=dict[i]

</code>```

Body:
I'm assuming that you have a list of tuples. As you've mentioned, we don't need to import any modules. Use the dict.get() method to find the value of a key if it is present and 0 as a default if it is absent.

So for example if 'French' is not in the dictionary .get() will return 0 else it will return the value associated with 'French'

Then we can simply add the value of the third column to the value we returned by .get().

dict={}
for tup in lst:
    dict[tup[5]]=dict.get(tup[5],0)+ int(tup[2])

#to get top 5 values
dict2={}
for i in sorted(dict, key=dict.get, reverse=True)[:5]:
    dict2[i]=dict[i]


问:
onClick going off without being clicked
I'm very new to writing with JavaScript and am creating a basic tab navigation interface as a prototype/practice. Right now I'm trying to make an alert appear using the onclick event handler on an unordered list of links just as a test and can't figure it out. Every time I load the page, all 5 onclick events occur without having clicked anything. Take a look at the code and let me know if you have any suggestions:

```<code>window.onload = initAll;
var xhr = false;

function initAll () {
    var navDiv = document.getElementById("tab_navigation");
    var navTabs = navDiv.getElementsByTagName("a");

    for (var i = 0; i < navTabs.length; i++) {
        navTabs[i].onclick = tellTab(i);
    }
}

function tellTab (number) {
    number = number + 1;
    alert("You clicked tab number " + number);
}
</code>```

The HTML structure is as follows:

```<code>    <div id="tab_navigation">
        <ul>
            <li><a href="#1">Tab 1</a></li>
            <li><a href="#2">Tab 2</a></li>
            <li><a href="#3">Tab 3</a></li>
            <li><a href="#4">Tab 4</a></li>
            <li><a href="#5">Tab 5</a></li>
        </ul>
    </div>
</code>```

答:
Closures for dummies:

```<code>function initAll () {
    var navDiv = document.getElementById("tab_navigation");
    var navTabs = navDiv.getElementsByTagName("a");

    for (var i = 0; i < navTabs.length; i++) {
        setTabOnclick(navTabs[i], i);
    }
}

function setTabOnclick(tab, i) {
   tab.onclick = function () { tellTab(i); };
}

function tellTab(i) {
  alert('clicked tab ' + i);
}
</code>```

I've just realized that this is the same as icktoofay's second solution but with a named outer function.

Title: onClick going off without being clicked

Body:
I'm very new to writing with JavaScript and am creating a basic tab navigation interface as a prototype/practice. Right now I'm trying to make an alert appear using the onclick event handler on an unordered list of links just as a test and can't figure it out. Every time I load the page, all 5 onclick events occur without having clicked anything. Take a look at the code and let me know if you have any suggestions:

window.onload = initAll;
var xhr = false;

function initAll () {
    var navDiv = document.getElementById("tab_navigation");
    var navTabs = navDiv.getElementsByTagName("a");

    for (var i = 0; i < navTabs.length; i++) {
        navTabs[i].onclick = tellTab(i);
    }
}

function tellTab (number) {
    number = number + 1;
    alert("You clicked tab number " + number);
}

The HTML structure is as follows:

Tab 1

Tab 2

Tab 3

Tab 4

Tab 5

Body:
Closures for dummies:

function initAll () {
    var navDiv = document.getElementById("tab_navigation");
    var navTabs = navDiv.getElementsByTagName("a");

    for (var i = 0; i < navTabs.length; i++) {
        setTabOnclick(navTabs[i], i);
    }
}

function setTabOnclick(tab, i) {
   tab.onclick = function () { tellTab(i); };
}

function tellTab(i) {
  alert('clicked tab ' + i);
}

I've just realized that this is the same as icktoofay's second solution but with a named outer function.


问:
Main method problems in Black Scholes model
This code gives the following error : ...\ConsoleApplication1.exe does not contain a static 'Main' method suitable for an entry point.

How can I solve this problem ?

```<code>namespace BlackScholes
{
    public class BS
    {
        public static double BlackScholes(double x)
        {
            double s = 100;
            double t = 1;
            double r = 0.10;
            double v = 0.10;
            double y = (float)Math.Pow(v, 2);
            double d1 = 0.0;
            double d2 = 0.0;
            double model = 0.0;

            d1 = ((float)Math.Log(s / x) + (r + 0.5 * y) * t) / v * (float)Math.Sqrt(t);
            d2 = d1 - v * (float)Math.Sqrt(t);

            model = s * cnd(d1) - x * (float)Math.Exp(-r * t) * cnd(d2);

            return model;
        }
        public static double cnd(double x)
        {
            double L = 0.0;
            double K = 0.0;
            double dCND = 0.0;
            const double a1 = 0.31938153;
            const double a2 = -0.356563782;
            const double a3 = 1.781477937;
            const double a4 = -1.821255978;
            const double a5 = 1.330274429;
            L = Math.Abs(x);
            K = 1.0 / (1.0 + 0.2316419 * L);
            dCND = 1.0 - 1.0 / Math.Sqrt(2 * Convert.ToDouble(Math.PI.ToString())) *
            Math.Exp(-L * L / 2.0) * (a1 * K + a2 * K * K + a3 * Math.Pow(K, 3.0) +
            a4 * Math.Pow(K, 4.0) + a5 * Math.Pow(K, 5.0));
            if (x < 0)
            {
                return 1.0 - dCND;
            }
            else
            {
                return dCND;
            }
        }
    }
}
</code>```

答:
You have created a class where are two method will help to calculate call and put price using Black Scholes formula.

```<code>using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OptionCalculater
{
    public class CallPutOptionPrice
    {
        double S, K, r, q, T, v, Call;
        public CallPutOptionPrice(string Is, string Ik, string Ir, string Iq, string It, string Iv)
        {
            S = double.Parse(Is);
            K = double.Parse(Ik);
            r = Math.Round(double.Parse(Ir) / 100, 4);
            q = double.Parse(Iq);
            T = Math.Round((double.Parse(It) - 1) / 365, 6);
            v = Math.Round(double.Parse(Iv) / 100, 4);
        }
        public string callOptionPrice()
        {
            double d1 = (Math.Log(S / K) + (r - q + v * v / 2.0) * T) / v / Math.Sqrt(T);
            double d2 = d1 - v * Math.Sqrt(T);

            double b0 = 0.2316419;
            double b1 = 0.319381530;
            double b2 = -0.356563782;
            double b3 = 1.781477937;
            double b4 = -1.821255978;
            double b5 = 1.330274429;

            double pi = Math.PI;
            double phid1 = Math.Exp(-d1 * d1 / 2.0) / Math.Sqrt(2.0 * pi);
            double td1, cd1;
            double Nd1 = 0.5;
            if (d1 > 0.0)
            {
                td1 = 1.0 / (1.0 + b0 * d1);
                Nd1 = 1.0 - phid1 * (b1 * td1 + b2 * Math.Pow(td1, 2) + b3 * Math.Pow(td1, 3) + b4 * Math.Pow(td1, 4) + b5 * Math.Pow(td1, 5));
            }
            else if (d1 < 0.0)
            {
                d1 = -d1;
                td1 = 1.0 / (1.0 + b0 * d1);
                cd1 = 1.0 - phid1 * (b1 * td1 + b2 * Math.Pow(td1, 2) + b3 * Math.Pow(td1, 3) + b4 * Math.Pow(td1, 4) + b5 * Math.Pow(td1, 5));
                Nd1 = 1.0 - cd1;
            }
            double phid2 = Math.Exp(-d2 * d2 / 2.0) / Math.Sqrt(2.0 * pi);
            double td2, cd2;
            double Nd2 = 0.5;
            if (d2 > 0.0)
            {
                td2 = 1.0 / (1.0 + b0 * d2);
                Nd2 = 1.0 - phid2 * (b1 * td2 + b2 * Math.Pow(td2, 2) + b3 * Math.Pow(td2, 3) + b4 * Math.Pow(td2, 4) + b5 * Math.Pow(td2, 5));
            }
            else if (d2 < 0.0)
            {
                d2 = -d2;
                td2 = 1.0 / (1.0 + b0 * d2);
                cd2 = 1.0 - phid2 * (b1 * td2 + b2 * Math.Pow(td2, 2) + b3 * Math.Pow(td2, 3) + b4 * Math.Pow(td2, 4) + b5 * Math.Pow(td2, 5));
                Nd2 = 1.0 - cd2;
            }
            Call = S * Math.Exp(-q * T) * Nd1 - K * Math.Exp(-r * T) * Nd2;
            return Call.ToString();
        }

        public string putOptionPrice()
        {
            double d1 = (Math.Log(S / K) + (r - q + v * v / 2.0) * T) / v / Math.Sqrt(T);
            double d2 = d1 - v * Math.Sqrt(T);

            d1 = -d1;
            d2 = -d2;

            double b0 = 0.2316419;
            double b1 = 0.319381530;
            double b2 = -0.356563782;
            double b3 = 1.781477937;
            double b4 = -1.821255978;
            double b5 = 1.330274429;

            double pi = Math.PI;
            double phid1 = Math.Exp(-d1 * d1 / 2.0) / Math.Sqrt(2.0 * pi);
            double td1, cd1;
            double Nd1 = 0.5;
            if (d1 > 0.0)
            {
                td1 = 1.0 / (1.0 + b0 * d1);
                Nd1 = 1.0 - phid1 * (b1 * td1 + b2 * Math.Pow(td1, 2) + b3 * Math.Pow(td1, 3) + b4 * Math.Pow(td1, 4) + b5 * Math.Pow(td1, 5));
            }
            else if (d1 < 0.0)
            {
                d1 = -d1;
                td1 = 1.0 / (1.0 + b0 * d1);
                cd1 = 1.0 - phid1 * (b1 * td1 + b2 * Math.Pow(td1, 2) + b3 * Math.Pow(td1, 3) + b4 * Math.Pow(td1, 4) + b5 * Math.Pow(td1, 5));
                Nd1 = 1.0 - cd1;
            }
            double phid2 = Math.Exp(-d2 * d2 / 2.0) / Math.Sqrt(2.0 * pi);
            double td2, cd2;
            double Nd2 = 0.5;
            if (d2 > 0.0)
            {
                td2 = 1.0 / (1.0 + b0 * d2);
                Nd2 = 1.0 - phid2 * (b1 * td2 + b2 * Math.Pow(td2, 2) + b3 * Math.Pow(td2, 3) + b4 * Math.Pow(td2, 4) + b5 * Math.Pow(td2, 5));
            }
            else if (d2 < 0.0)
            {
                d2 = -d2;
                td2 = 1.0 / (1.0 + b0 * d2);
                cd2 = 1.0 - phid2 * (b1 * td2 + b2 * Math.Pow(td2, 2) + b3 * Math.Pow(td2, 3) + b4 * Math.Pow(td2, 4) + b5 * Math.Pow(td2, 5));
                Nd2 = 1.0 - cd2;
            }

            Call = K * Math.Exp(-r * T) * Nd2 - S * Math.Exp(-q * T) * Nd1;
            return Call.ToString();
        }
    }
}
</code>```

Body:
This code gives the following error : ...\ConsoleApplication1.exe does not contain a static 'Main' method suitable for an entry point.

How can I solve this problem ?

namespace BlackScholes
{
    public class BS
    {
        public static double BlackScholes(double x)
        {
            double s = 100;
            double t = 1;
            double r = 0.10;
            double v = 0.10;
            double y = (float)Math.Pow(v, 2);
            double d1 = 0.0;
            double d2 = 0.0;
            double model = 0.0;

            d1 = ((float)Math.Log(s / x) + (r + 0.5 * y) * t) / v * (float)Math.Sqrt(t);
            d2 = d1 - v * (float)Math.Sqrt(t);

            model = s * cnd(d1) - x * (float)Math.Exp(-r * t) * cnd(d2);

            return model;
        }
        public static double cnd(double x)
        {
            double L = 0.0;
            double K = 0.0;
            double dCND = 0.0;
            const double a1 = 0.31938153;
            const double a2 = -0.356563782;
            const double a3 = 1.781477937;
            const double a4 = -1.821255978;
            const double a5 = 1.330274429;
            L = Math.Abs(x);
            K = 1.0 / (1.0 + 0.2316419 * L);
            dCND = 1.0 - 1.0 / Math.Sqrt(2 * Convert.ToDouble(Math.PI.ToString())) *
            Math.Exp(-L * L / 2.0) * (a1 * K + a2 * K * K + a3 * Math.Pow(K, 3.0) +
            a4 * Math.Pow(K, 4.0) + a5 * Math.Pow(K, 5.0));
            if (x < 0)
            {
                return 1.0 - dCND;
            }
            else
            {
                return dCND;
            }
        }
    }
}

Body:
You have created a class where are two method will help to calculate call and put price using Black Scholes formula.

using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OptionCalculater
{
    public class CallPutOptionPrice
    {
        double S, K, r, q, T, v, Call;
        public CallPutOptionPrice(string Is, string Ik, string Ir, string Iq, string It, string Iv)
        {
            S = double.Parse(Is);
            K = double.Parse(Ik);
            r = Math.Round(double.Parse(Ir) / 100, 4);
            q = double.Parse(Iq);
            T = Math.Round((double.Parse(It) - 1) / 365, 6);
            v = Math.Round(double.Parse(Iv) / 100, 4);
        }
        public string callOptionPrice()
        {
            double d1 = (Math.Log(S / K) + (r - q + v * v / 2.0) * T) / v / Math.Sqrt(T);
            double d2 = d1 - v * Math.Sqrt(T);

            double b0 = 0.2316419;
            double b1 = 0.319381530;
            double b2 = -0.356563782;
            double b3 = 1.781477937;
            double b4 = -1.821255978;
            double b5 = 1.330274429;

            double pi = Math.PI;
            double phid1 = Math.Exp(-d1 * d1 / 2.0) / Math.Sqrt(2.0 * pi);
            double td1, cd1;
            double Nd1 = 0.5;
            if (d1 > 0.0)
            {
                td1 = 1.0 / (1.0 + b0 * d1);
                Nd1 = 1.0 - phid1 * (b1 * td1 + b2 * Math.Pow(td1, 2) + b3 * Math.Pow(td1, 3) + b4 * Math.Pow(td1, 4) + b5 * Math.Pow(td1, 5));
            }
            else if (d1 < 0.0)
            {
                d1 = -d1;
                td1 = 1.0 / (1.0 + b0 * d1);
                cd1 = 1.0 - phid1 * (b1 * td1 + b2 * Math.Pow(td1, 2) + b3 * Math.Pow(td1, 3) + b4 * Math.Pow(td1, 4) + b5 * Math.Pow(td1, 5));
                Nd1 = 1.0 - cd1;
            }
            double phid2 = Math.Exp(-d2 * d2 / 2.0) / Math.Sqrt(2.0 * pi);
            double td2, cd2;
            double Nd2 = 0.5;
            if (d2 > 0.0)
            {
                td2 = 1.0 / (1.0 + b0 * d2);
                Nd2 = 1.0 - phid2 * (b1 * td2 + b2 * Math.Pow(td2, 2) + b3 * Math.Pow(td2, 3) + b4 * Math.Pow(td2, 4) + b5 * Math.Pow(td2, 5));
            }
            else if (d2 < 0.0)
            {
                d2 = -d2;
                td2 = 1.0 / (1.0 + b0 * d2);
                cd2 = 1.0 - phid2 * (b1 * td2 + b2 * Math.Pow(td2, 2) + b3 * Math.Pow(td2, 3) + b4 * Math.Pow(td2, 4) + b5 * Math.Pow(td2, 5));
                Nd2 = 1.0 - cd2;
            }
            Call = S * Math.Exp(-q * T) * Nd1 - K * Math.Exp(-r * T) * Nd2;
            return Call.ToString();
        }

        public string putOptionPrice()
        {
            double d1 = (Math.Log(S / K) + (r - q + v * v / 2.0) * T) / v / Math.Sqrt(T);
            double d2 = d1 - v * Math.Sqrt(T);

            d1 = -d1;
            d2 = -d2;

            double b0 = 0.2316419;
            double b1 = 0.319381530;
            double b2 = -0.356563782;
            double b3 = 1.781477937;
            double b4 = -1.821255978;
            double b5 = 1.330274429;

            double pi = Math.PI;
            double phid1 = Math.Exp(-d1 * d1 / 2.0) / Math.Sqrt(2.0 * pi);
            double td1, cd1;
            double Nd1 = 0.5;
            if (d1 > 0.0)
            {
                td1 = 1.0 / (1.0 + b0 * d1);
                Nd1 = 1.0 - phid1 * (b1 * td1 + b2 * Math.Pow(td1, 2) + b3 * Math.Pow(td1, 3) + b4 * Math.Pow(td1, 4) + b5 * Math.Pow(td1, 5));
            }
            else if (d1 < 0.0)
            {
                d1 = -d1;
                td1 = 1.0 / (1.0 + b0 * d1);
                cd1 = 1.0 - phid1 * (b1 * td1 + b2 * Math.Pow(td1, 2) + b3 * Math.Pow(td1, 3) + b4 * Math.Pow(td1, 4) + b5 * Math.Pow(td1, 5));
                Nd1 = 1.0 - cd1;
            }
            double phid2 = Math.Exp(-d2 * d2 / 2.0) / Math.Sqrt(2.0 * pi);
            double td2, cd2;
            double Nd2 = 0.5;
            if (d2 > 0.0)
            {
                td2 = 1.0 / (1.0 + b0 * d2);
                Nd2 = 1.0 - phid2 * (b1 * td2 + b2 * Math.Pow(td2, 2) + b3 * Math.Pow(td2, 3) + b4 * Math.Pow(td2, 4) + b5 * Math.Pow(td2, 5));
            }
            else if (d2 < 0.0)
            {
                d2 = -d2;
                td2 = 1.0 / (1.0 + b0 * d2);
                cd2 = 1.0 - phid2 * (b1 * td2 + b2 * Math.Pow(td2, 2) + b3 * Math.Pow(td2, 3) + b4 * Math.Pow(td2, 4) + b5 * Math.Pow(td2, 5));
                Nd2 = 1.0 - cd2;
            }

            Call = K * Math.Exp(-r * T) * Nd2 - S * Math.Exp(-q * T) * Nd1;
            return Call.ToString();
        }
    }
}


问:
How to use angular animation in child component
I have an animation defined in app component

```<code>@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: [
    trigger('fade', [
      state('void', style({
        opacity: 0
      })),
      transition(':enter, :leave', [
        animate(4000)
      ])
    ])
  ]
})
export class AppComponent {
  title = 'app';
}
</code>```

I want to apply the animation in a child component without redefining it in the child component, how can i achieve this

答:
You have to keep your animations in a shared file. In that way, it will be really helpful for you to manage it.

You can see this - https://github.com/commutatus/angular-starterpack/tree/master/src/app/shared

In shared/animations you will find the animation, and you can then import these animations in your components.

For importing in component -

```<code>import {fadeIn} from '~app/shared/animations/index';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: [
    fadeIn
  ]
})
</code>```

Note - Don't forget to import BrowserAnimationModule in your app.module.ts. Also, export the animations from the shared/animation/index

Body:
I have an animation defined in app component

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: [
    trigger('fade', [
      state('void', style({
        opacity: 0
      })),
      transition(':enter, :leave', [
        animate(4000)
      ])
    ])
  ]
})
export class AppComponent {
  title = 'app';
}

I want to apply the animation in a child component without redefining it in the child component, how can i achieve this

Body:
You have to keep your animations in a shared file. In that way, it will be really helpful for you to manage it.

You can see this - https://github.com/commutatus/angular-starterpack/tree/master/src/app/shared

In shared/animations you will find the animation, and you can then import these animations in your components.

For importing in component -

import {fadeIn} from '~app/shared/animations/index';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: [
    fadeIn
  ]
})

Note - Don't forget to import BrowserAnimationModule in your app.module.ts. Also, export the animations from the shared/animation/index


问:
Winston not Logging to console in typescript
I am confused by winston. I am using the following typescript code to log onto the console in my *.ts file:

```<code>import { Logger, LoggerInstance } from "winston";

const logger:LoggerInstance = new Logger();
logger.info('Now my debug messages are written to the console!');
</code>```

the console remains empty. There are no compile errors or other issues.

At the same time the following works fine:

```<code>const wnstn = require("winston");
wnstn.info('Finally my messages are written to the console!');
</code>```

Does anyone have a clue why that is the case? Do I have to configure the Logger differently? How would I use the defaults I get from the second example?

答:
Well, I am following below file as winston.ts

```<code>import * as appRoot from 'app-root-path';
import * as winston from 'winston';

// define the custom settings for each transport (file, console)
const options = {
    file: {
        level: 'info',
        filename: `${appRoot}/logs/app.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
    },
    console: {
        level: 'debug',
        handleExceptions: true,
        json: false,
        colorize: true,
    },
};

// instantiate a new Winston Logger with the settings defined above
const logger: winston.Logger = winston.createLogger({
    transports: [
        new winston.transports.File(options.file),
        new winston.transports.Console(options.console)
    ],
    exitOnError: false, // do not exit on handled exceptions
});

// create a stream object with a 'write' function that will be used by `morgan`
const myStream = {
    write: (message: string) => {
        // use the 'info' log level so the output will be picked up by both transports (file and console)
        logger.info(message);
    }
};

export default logger;
</code>```

as using inside app.ts as     this.app.use(morgan('combined', { stream: winston.stream }));

Body:
I am confused by winston. I am using the following typescript code to log onto the console in my *.ts file:

import { Logger, LoggerInstance } from "winston";

const logger:LoggerInstance = new Logger();
logger.info('Now my debug messages are written to the console!');

the console remains empty. There are no compile errors or other issues.

At the same time the following works fine:

const wnstn = require("winston");
wnstn.info('Finally my messages are written to the console!');

Does anyone have a clue why that is the case? Do I have to configure the Logger differently? How would I use the defaults I get from the second example?

Body:
Well, I am following below file as winston.ts

import * as appRoot from 'app-root-path';
import * as winston from 'winston';

// define the custom settings for each transport (file, console)
const options = {
    file: {
        level: 'info',
        filename: `${appRoot}/logs/app.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
    },
    console: {
        level: 'debug',
        handleExceptions: true,
        json: false,
        colorize: true,
    },
};

// instantiate a new Winston Logger with the settings defined above
const logger: winston.Logger = winston.createLogger({
    transports: [
        new winston.transports.File(options.file),
        new winston.transports.Console(options.console)
    ],
    exitOnError: false, // do not exit on handled exceptions
});

// create a stream object with a 'write' function that will be used by `morgan`
const myStream = {
    write: (message: string) => {
        // use the 'info' log level so the output will be picked up by both transports (file and console)
        logger.info(message);
    }
};

export default logger;

as using inside app.ts as     this.app.use(morgan('combined', { stream: winston.stream }));


问:
Adding column conditioning on the other columns
I want to create a new column z based on the values of x and y.  If x>y, z=y otherwise z=x.

```<code>x  y
3  4
5  2
6  6
1  7
9  4
</code>```

Output required:

```<code>x  y  z
3  4  3
5  2  2
6  6  6
1  7  1
9  4  4
</code>```

答:
You can use ifelse :

```<code>df$z <- with(df, ifelse(x > y, y, x))
#Or without with
#df$z <- ifelse(df$x > df$y, df$y, df$x)
df

#  x y z
#1 3 4 3
#2 5 2 2
#3 6 6 6
#4 1 7 1
#5 9 4 4
</code>```

In dplyr, you can use if_else which is same as above or case_when which is helpful when you have to list down multiple conditions.

```<code>library(dplyr)
df %>%
 mutate(z = case_when(x > y ~ y,
                      TRUE ~x))
</code>```

Body:
I want to create a new column z based on the values of x and y.  If x>y, z=y otherwise z=x.

x  y
3  4
5  2
6  6
1  7
9  4

Output required:

x  y  z
3  4  3
5  2  2
6  6  6
1  7  1
9  4  4

Body:
You can use ifelse :

df$z <- with(df, ifelse(x > y, y, x))
#Or without with
#df$z <- ifelse(df$x > df$y, df$y, df$x)
df

#  x y z
#1 3 4 3
#2 5 2 2
#3 6 6 6
#4 1 7 1
#5 9 4 4

In dplyr, you can use if_else which is same as above or case_when which is helpful when you have to list down multiple conditions.

library(dplyr)
df %>%
 mutate(z = case_when(x > y ~ y,
                      TRUE ~x))