问:
'DataFrame' object has no attribute 'map'
I have the following command below:

```<code>datamax['Date'] = pd.to_datetime(datamax['Date'])
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax2015["day_of_year"] = datamax["Date"].dt.dayofyear
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper = upper.rename(columns={"Date_new":"Date","Data_Value_new":"Data_Value"})
lower = lower.rename(columns={"Date_new":"Date","Data_Value_new":"Data_Value"})
upper['Date'] = upper['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))
lower['Date'] = lower['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))
</code>```

However, I keep getting the error:

'DataFrame' object has no attribute 'map'

I am confused as to why this is. Could anybody help me out here?

The dataframe lower looks like this:

upper:

```<code>     Date           ID Element  Data_Value  day_of_year       Date  \
3  2015-01-04  USW00094889    TMAX          44            4 2005-01-05
4  2015-01-05  USW00094889    TMAX          28            5 2005-01-06
5  2015-01-06  USW00094889    TMAX          33            6 2005-01-07
14 2015-01-15  USW00094889    TMAX          -5           15 2005-01-16
15 2015-01-16  USW00094889    TMAX           6           16 2005-01-17

         ID_new Element_new  Data_Value  day_of_year_new
3   USW00094889        TMAX          33                5
4   USW00094889        TMAX           0                6
5   USW00094889        TMAX           6                7
14  USW00094889        TMAX         -33               16
15  USW00094889        TMAX         -50               17
</code>```

lower:

```<code>   Date           ID Element  Data_Value  day_of_year       Date  \
0 2015-01-01  USC00200032    TMIN        -133            1 2005-01-02
1 2015-01-02  USC00200032    TMIN        -122            2 2005-01-03
2 2015-01-03  USC00200032    TMIN         -67            3 2005-01-04
4 2015-01-05  USC00200032    TMIN        -155            5 2005-01-06
5 2015-01-06  USC00200032    TMIN        -182            6 2005-01-07

        ID_new Element_new  Data_Value  day_of_year_new
0  USC00200032        TMIN         -56                2
1  USC00200032        TMIN           0                3
2  USC00200032        TMIN         -39                4
4  USC00200032        TMIN        -106                6
5  USC00200032        TMIN        -111                7
</code>```

datamax:

```<code>     Date           ID Element  Data_Value  day_of_year
    0 2005-01-01  USW00094889    TMAX         156            1
    1 2005-01-02  USW00094889    TMAX         139            2
    2 2005-01-03  USW00094889    TMAX         133            3
    3 2005-01-04  USW00094889    TMAX          39            4
    4 2005-01-05  USW00094889    TMAX          33            5
</code>```

datamin:

```<code> Date           ID Element  Data_Value  day_of_year
0 2005-01-01  USC00200032    TMIN         -56            1
1 2005-01-02  USC00200032    TMIN         -56            2
2 2005-01-03  USC00200032    TMIN           0            3
3 2005-01-04  USC00200032    TMIN         -39            4
4 2005-01-05  USC00200032    TMIN         -94            5
</code>```

The dataframe data:

```<code>                 ID        Date Element  Data_Value
0       USW00094889  2014-11-12    TMAX          22
1       USC00208972  2009-04-29    TMIN          56
2       USC00200032  2008-05-26    TMAX         278
3       USC00205563  2005-11-11    TMAX         139
4       USC00200230  2014-02-27    TMAX        -106
5       USW00014833  2010-10-01    TMAX         194
6       USC00207308  2010-06-29    TMIN         144
7       USC00203712  2005-10-04    TMAX         289
8       USW00004848  2007-12-14    TMIN         -16
9       USC00200220  2011-04-21    TMAX          72
10      USC00205822  2013-01-16    TMAX          11
11      USC00205822  2008-05-29    TMIN          28
12      USC00203712  2008-10-17    TMIN          17
13      USC00205563  2006-05-14    TMAX         183
</code>```

答:
upper and lower dataframes have two columns called Date. You are extracting both by using upper['Date'].

Solution:
Rename at least one of the columns to sth different than date and than apply your function to each column seperately.

See https://stackoverflow.com/a/54608016/6646710 for further details.

Body:
I have the following command below:

datamax['Date'] = pd.to_datetime(datamax['Date'])
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax2015["day_of_year"] = datamax["Date"].dt.dayofyear
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper = upper.rename(columns={"Date_new":"Date","Data_Value_new":"Data_Value"})
lower = lower.rename(columns={"Date_new":"Date","Data_Value_new":"Data_Value"})
upper['Date'] = upper['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))
lower['Date'] = lower['Date'].map(lambda x: x.strftime("%d/%m/%Y, %H:%M:%S"))

However, I keep getting the error:

'DataFrame' object has no attribute 'map'

I am confused as to why this is. Could anybody help me out here?

The dataframe lower looks like this:

upper:

     Date           ID Element  Data_Value  day_of_year       Date  \
3  2015-01-04  USW00094889    TMAX          44            4 2005-01-05
4  2015-01-05  USW00094889    TMAX          28            5 2005-01-06
5  2015-01-06  USW00094889    TMAX          33            6 2005-01-07
14 2015-01-15  USW00094889    TMAX          -5           15 2005-01-16
15 2015-01-16  USW00094889    TMAX           6           16 2005-01-17

         ID_new Element_new  Data_Value  day_of_year_new
3   USW00094889        TMAX          33                5
4   USW00094889        TMAX           0                6
5   USW00094889        TMAX           6                7
14  USW00094889        TMAX         -33               16
15  USW00094889        TMAX         -50               17

lower:

   Date           ID Element  Data_Value  day_of_year       Date  \
0 2015-01-01  USC00200032    TMIN        -133            1 2005-01-02
1 2015-01-02  USC00200032    TMIN        -122            2 2005-01-03
2 2015-01-03  USC00200032    TMIN         -67            3 2005-01-04
4 2015-01-05  USC00200032    TMIN        -155            5 2005-01-06
5 2015-01-06  USC00200032    TMIN        -182            6 2005-01-07

        ID_new Element_new  Data_Value  day_of_year_new
0  USC00200032        TMIN         -56                2
1  USC00200032        TMIN           0                3
2  USC00200032        TMIN         -39                4
4  USC00200032        TMIN        -106                6
5  USC00200032        TMIN        -111                7

datamax:

     Date           ID Element  Data_Value  day_of_year
    0 2005-01-01  USW00094889    TMAX         156            1
    1 2005-01-02  USW00094889    TMAX         139            2
    2 2005-01-03  USW00094889    TMAX         133            3
    3 2005-01-04  USW00094889    TMAX          39            4
    4 2005-01-05  USW00094889    TMAX          33            5

datamin:

 Date           ID Element  Data_Value  day_of_year
0 2005-01-01  USC00200032    TMIN         -56            1
1 2005-01-02  USC00200032    TMIN         -56            2
2 2005-01-03  USC00200032    TMIN           0            3
3 2005-01-04  USC00200032    TMIN         -39            4
4 2005-01-05  USC00200032    TMIN         -94            5

The dataframe data:

                 ID        Date Element  Data_Value
0       USW00094889  2014-11-12    TMAX          22
1       USC00208972  2009-04-29    TMIN          56
2       USC00200032  2008-05-26    TMAX         278
3       USC00205563  2005-11-11    TMAX         139
4       USC00200230  2014-02-27    TMAX        -106
5       USW00014833  2010-10-01    TMAX         194
6       USC00207308  2010-06-29    TMIN         144
7       USC00203712  2005-10-04    TMAX         289
8       USW00004848  2007-12-14    TMIN         -16
9       USC00200220  2011-04-21    TMAX          72
10      USC00205822  2013-01-16    TMAX          11
11      USC00205822  2008-05-29    TMIN          28
12      USC00203712  2008-10-17    TMIN          17
13      USC00205563  2006-05-14    TMAX         183

OwnerDisplayName: PalimPalim


来源: stackexchange

问:
Python - Convert a roman numeral to an integer
I've tried the following Python 3 code that transform from Roman to Integer.

The code is working fine at a glance. But there are certain problem happened when I input X, V or related to X and V value.

For example: when I try V the code is not working but for IV showing correct value.

My code:

```<code>class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
if message <= ("MMMCMXCIX"):
   print (ob1.romanToInt(message))
else:
    print ("Try again")
</code>```

I've set the condition which is, if the input roman number is equal or less than MMMCMXCIX, it will print the roman number; else it will print Try again.

The problem is when I input X, V or related to X and V value the output is showing Try again

Please help me to understand where I went wrong.

答:
As mentioned in the comments, the problem was caused because you compared string rather than first transform to int and then do the comparison.

Other approach that you can try is:

```<code>def romanToInt(s):
  d = {'m': 1000, 'd': 500, 'c': 100, 'l': 50, 'x': 10, 'v': 5, 'i': 1}
  n = [d[i] for i in s.lower() if i in d]
  return sum([i if i>=n[min(j+1, len(n)-1)] else -i for j,i in enumerate(n)])

print(romanToInt('X')) # 10
print(romanToInt('V')) # 5
print(romanToInt('IV')) # 4
print(romanToInt('XV')) # 15
</code>```

In my opinion both are more pythonic.

ContentLicense: CC BY-SA 4.0

Body:
I've tried the following Python 3 code that transform from Roman to Integer.

The code is working fine at a glance. But there are certain problem happened when I input X, V or related to X and V value.

For example: when I try V the code is not working but for IV showing correct value.

My code:

class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
if message <= ("MMMCMXCIX"):
   print (ob1.romanToInt(message))
else:
    print ("Try again")

I've set the condition which is, if the input roman number is equal or less than MMMCMXCIX, it will print the roman number; else it will print Try again.

The problem is when I input X, V or related to X and V value the output is showing Try again

Please help me to understand where I went wrong.

Body:
As mentioned in the comments, the problem was caused because you compared string rather than first transform to int and then do the comparison.

Other approach that you can try is:

def romanToInt(s):
  d = {'m': 1000, 'd': 500, 'c': 100, 'l': 50, 'x': 10, 'v': 5, 'i': 1}
  n = [d[i] for i in s.lower() if i in d]
  return sum([i if i>=n[min(j+1, len(n)-1)] else -i for j,i in enumerate(n)])

print(romanToInt('X')) # 10
print(romanToInt('V')) # 5
print(romanToInt('IV')) # 4
print(romanToInt('XV')) # 15

In my opinion both are more pythonic.


问:
Can I check if a list contains any item from another list?
using Python, I want to check if a list contains an item/value that is also present in another list. For example, here is what I am trying to do:

```<code>list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if list1 contains any items also in list2:
    print("Duplicates found.")
else:
    print("No duplicates found.")
</code>```

As you can see, list2 contains an item that is also found in list1, which is 'item3'. Is there any way I can detect if this occurs?

Thanks.

答:
Using any() along with a generator expression:

```<code>list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if any(x in list1 for x in list2):
    print("Duplicates found.")
else:
    print("No duplicates found.")
</code>```

Body:
using Python, I want to check if a list contains an item/value that is also present in another list. For example, here is what I am trying to do:

list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if list1 contains any items also in list2:
    print("Duplicates found.")
else:
    print("No duplicates found.")

As you can see, list2 contains an item that is also found in list1, which is 'item3'. Is there any way I can detect if this occurs?

Thanks.

Body:
Using any() along with a generator expression:

list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if any(x in list1 for x in list2):
    print("Duplicates found.")
else:
    print("No duplicates found.")


Title: How to remove one of two consecutive duplicate strings in list?

Body:
I have a list that has duplicated 'STRING' elements and looks like this:

a = ['32', '55', '74', '58', 'STRING', 'STRING','STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', 'STRING', '90', '84', '82', '85', '86', 'STRING', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', 'STRING', '86', '89', '88', '66', '70', 'STRING', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']

One of every two consecuitive 'STRING' elements has to be in its place. I need to remove every second of the consecutive STRINGelements. And the list should look like this:

a = ['32', '55', '74', '58', 'STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', '90', '84', '82', '85', '86', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', '86', '89', '88', '66', '70', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']

This is what I tried:

    for i in reversed(range(len(a)-1)):
        if (list1[i] == list1[i-1]) & (list1[i] == 'STRING'):
            list1.remove(list1[i-1])

but it doesn't work. When it's not reversed I get the IndexError.

Body:
You can try

for i, val in enumerate(a):
    if i > 0:
        if val == 'STRING' and a[i - 1] == 'STRING':
            del a[i]

This will remove the second STRING value that folloeing a STRING value.
Output

['32', '55', '74', '58', 'STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', '90', '84', '82', '85', '86', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', '86', '89', '88', '66', '70', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']


问:
can any one suggest a good math function in javascript to round integer?
i have to round the value from 2.3456789 to 2.345 .

After . there must be three number only remaining should be removed

答:
Try Math.floor(2.3456789 * 1000) / 100. This might result in floating-point errors, so it might be a better idea to just do it via string functions

```<code>var parts = String(2.3456789).split(".");
var out = parts[0] + "." + parts[1].substring(0, 3);
</code>```

Of course, the second method may choke on numbers with exponents.

ContentLicense: CC BY-SA 3.0

Body:
Try Math.floor(2.3456789 * 1000) / 100. This might result in floating-point errors, so it might be a better idea to just do it via string functions

var parts = String(2.3456789).split(".");
var out = parts[0] + "." + parts[1].substring(0, 3);

Of course, the second method may choke on numbers with exponents.


问:
Redirect to Firebase Hosting custom domain
I have setup a custom domain with Firebase Hosting (eg. myapp.domain.com).

How can one redirect (or turn off) the default Firebase Hosting URL (eg. myapp.firebaseapp.com) so that the app is only accessible from the custom domain?

答:
In addition to specifying canonical link as mentioned in Frank van Puffelen's answer. We can also add front end JavaScript code to do the actual redirect like this without disclosing default url.</p>

```<code>if (location.hostname.indexOf('custom.url') === -1) {
    location.replace("https://custom.url");
}
</code>```

Body:
In addition to specifying canonical link as mentioned in Frank van Puffelen's answer. We can also add front end JavaScript code to do the actual redirect like this without disclosing default url.

if (location.hostname.indexOf('custom.url') === -1) {
    location.replace("https://custom.url");
}


问:
Is there a way in airflow where a Daily DAG is dependent on weekly (on weekends) DAG?
I have these Dags DAG_A (runs daily) , DAG_B (runs mon-fri) and DAG_C (runs on sat and sun) where DAG_A is dependent on both DAG_B and DAG_C.
I tried setting the dependencies using External Task Sensor but everytime my scheduler stops running and any of Dags aren't succeeding

答:
You can try to use TriggerDagRunOperator for calling one DAG from another.

The details can be found in operator TriggerDagRunOperator Airflow documentation.

https://airflow.apache.org/docs/stable/_api/airflow/operators/dagrun_operator/index.html#airflow.operators.dagrun_operator.TriggerDagRunOperator

call DAG_A from DAG_B and DAG_C when they finish the run.


问:
Constant validation accuracy in binary classification using ResNet50
I am training a deep learning network to classify thyroid nodules (binary classification as 0 or 1). Therefore, I am realizing that my model is with constant validation accuracy. I tried everything, changed the learning rate, some callbacks if the loss doesn't increse. So, I need help, some ideas to deal with it. I will give you a example with 10 epochs, but, even if I change to 100 epochs, it still with the same behavior. Here is the architecture's network code:</p>

```<code>callbacks = [
    EarlyStopping(patience=20, verbose=1),
    ReduceLROnPlateau(factor=0.1, patience=5, min_lr=0.0001, verbose=1),
]

epochs=10
model = Sequential()
model.add(tf.keras.applications.ResNet50( include_top=False, pooling='avg', weights='imagenet'))
model.add(BatchNormalization())
model.add(Dropout(0.4))
model.add(Dense(2, activation='sigmoid'))
model.layers[0].trainable = False
weights=class_weight.compute_class_weight('balanced', np.unique(y_train), y_train)
opt =Adam(learning_rate=0.001)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
tf.random.set_seed(2)
rede=model.fit(X_train, y_train_2d, epochs=epochs, batch_size=18, class_weight=weights, callbacks=callbacks,\
               validation_data=(X_valid, y_valid_2d))

Train on 360 samples, validate on 46 samples
Epoch 1/10
342/360 [===========================>..] - ETA: 1s - loss: 0.7582 - accuracy: 0.5673
Epoch 00001: val_loss did not improve from 0.16301
360/360 [==============================] - 44s 123ms/sample - loss: 0.7706 - accuracy: 0.5583 - val_loss: 0.5528 - val_accuracy: 0.8043
Epoch 2/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5604 - accuracy: 0.7135
Epoch 00002: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5525 - accuracy: 0.7222 - val_loss: 0.5047 - val_accuracy: 0.8043
Epoch 3/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5056 - accuracy: 0.7485
Epoch 00003: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4993 - accuracy: 0.7500 - val_loss: 0.4946 - val_accuracy: 0.8043
Epoch 4/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5004 - accuracy: 0.7661
Epoch 00004: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5019 - accuracy: 0.7667 - val_loss: 0.4942 - val_accuracy: 0.8043
Epoch 5/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4967 - accuracy: 0.8070
Epoch 00005: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4897 - accuracy: 0.8083 - val_loss: 0.4952 - val_accuracy: 0.8043
Epoch 6/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4615 - accuracy: 0.7427
Epoch 00006: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4750 - accuracy: 0.7361 - val_loss: 0.4985 - val_accuracy: 0.8043
Epoch 7/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4119 - accuracy: 0.7924
Epoch 00007: val_loss did not improve from 0.16301
360/360 [==============================] - 40s 111ms/sample - loss: 0.4164 - accuracy: 0.7944 - val_loss: 0.4953 - val_accuracy: 0.8043
Epoch 8/10
342/360 [===========================>..] - ETA: 0s - loss: 0.4182 - accuracy: 0.8158
Epoch 00008: val_loss did not improve from 0.16301
360/360 [==============================] - 20s 55ms/sample - loss: 0.4155 - accuracy: 0.8194 - val_loss: 0.4957 - val_accuracy: 0.8043
Epoch 9/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3892 - accuracy: 0.8304
Epoch 00009: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 00009: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 57ms/sample - loss: 0.3853 - accuracy: 0.8278 - val_loss: 0.4997 - val_accuracy: 0.8043
Epoch 10/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3395 - accuracy: 0.8333
Epoch 00010: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 58ms/sample - loss: 0.3375 - accuracy: 0.8333 - val_loss: 0.5003 - val_accuracy: 0.8043
</code>```

答:
I tried to change the output dense to 1, instead of 2. The accuracy still with the same behavior. </p>

```<code>epochs=10
model = Sequential()
model.add(tf.keras.applications.ResNet50( include_top=False, pooling='avg', weights='imagenet'))
model.add(BatchNormalization())
model.add(Dropout(0.4))
model.add(Dense(1, activation='sigmoid'))
model.layers[0].trainable = False
weights=class_weight.compute_class_weight('balanced', np.unique(y_train), y_train)
opt =Adam(learning_rate=0.001)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
tf.random.set_seed(2)
rede=model.fit(X_train, y_train, epochs=epochs, batch_size=18, class_weight=weights, callbacks=callbacks,\
               validation_data=(X_valid, y_valid))
Train on 360 samples, validate on 46 samples
Epoch 1/10
360/360 [==============================] - 17s 48ms/sample - loss: 0.8778 - accuracy: 0.5639 - val_loss: 0.3967 - val_accuracy: 0.8696
Epoch 2/10
360/360 [==============================] - 9s 24ms/sample - loss: 0.6527 - accuracy: 0.7028 - val_loss: 0.3973 - val_accuracy: 0.8696
Epoch 3/10
360/360 [==============================] - 9s 26ms/sample - loss: 0.6054 - accuracy: 0.7222 - val_loss: 0.4171 - val_accuracy: 0.8696
Epoch 4/10
360/360 [==============================] - 10s 28ms/sample - loss: 0.5388 - accuracy: 0.7500 - val_loss: 0.4211 - val_accuracy: 0.8696
Epoch 5/10
360/360 [==============================] - 11s 30ms/sample - loss: 0.4830 - accuracy: 0.7694 - val_loss: 0.4367 - val_accuracy: 0.8696
Epoch 6/10
342/360 [===========================>..] - ETA: 0s - loss: 0.4986 - accuracy: 0.8070
Epoch 00006: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.
360/360 [==============================] - 11s 29ms/sample - loss: 0.4952 - accuracy: 0.8056 - val_loss: 0.4576 - val_accuracy: 0.8696
Epoch 7/10
360/360 [==============================] - 11s 30ms/sample - loss: 0.4257 - accuracy: 0.8306 - val_loss: 0.4661 - val_accuracy: 0.8696
Epoch 8/10
360/360 [==============================] - 17s 46ms/sample - loss: 0.4054 - accuracy: 0.8250 - val_loss: 0.4722 - val_accuracy: 0.8696
Epoch 9/10
360/360 [==============================] - 17s 48ms/sample - loss: 0.4484 - accuracy: 0.7917 - val_loss: 0.4761 - val_accuracy: 0.8696
Epoch 10/10
360/360 [==============================] - 16s 44ms/sample - loss: 0.3844 - accuracy: 0.8472 - val_loss: 0.4785 - val_accuracy: 0.8696
</code>```

Body:
I am training a deep learning network to classify thyroid nodules (binary classification as 0 or 1). Therefore, I am realizing that my model is with constant validation accuracy. I tried everything, changed the learning rate, some callbacks if the loss doesn't increse. So, I need help, some ideas to deal with it. I will give you a example with 10 epochs, but, even if I change to 100 epochs, it still with the same behavior. Here is the architecture's network code:

callbacks = [
    EarlyStopping(patience=20, verbose=1),
    ReduceLROnPlateau(factor=0.1, patience=5, min_lr=0.0001, verbose=1),
]

epochs=10
model = Sequential()
model.add(tf.keras.applications.ResNet50( include_top=False, pooling='avg', weights='imagenet'))
model.add(BatchNormalization())
model.add(Dropout(0.4))
model.add(Dense(2, activation='sigmoid'))
model.layers[0].trainable = False
weights=class_weight.compute_class_weight('balanced', np.unique(y_train), y_train)
opt =Adam(learning_rate=0.001)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
tf.random.set_seed(2)
rede=model.fit(X_train, y_train_2d, epochs=epochs, batch_size=18, class_weight=weights, callbacks=callbacks,\
               validation_data=(X_valid, y_valid_2d))

Train on 360 samples, validate on 46 samples
Epoch 1/10
342/360 [===========================>..] - ETA: 1s - loss: 0.7582 - accuracy: 0.5673
Epoch 00001: val_loss did not improve from 0.16301
360/360 [==============================] - 44s 123ms/sample - loss: 0.7706 - accuracy: 0.5583 - val_loss: 0.5528 - val_accuracy: 0.8043
Epoch 2/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5604 - accuracy: 0.7135
Epoch 00002: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5525 - accuracy: 0.7222 - val_loss: 0.5047 - val_accuracy: 0.8043
Epoch 3/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5056 - accuracy: 0.7485
Epoch 00003: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4993 - accuracy: 0.7500 - val_loss: 0.4946 - val_accuracy: 0.8043
Epoch 4/10
342/360 [===========================>..] - ETA: 1s - loss: 0.5004 - accuracy: 0.7661
Epoch 00004: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.5019 - accuracy: 0.7667 - val_loss: 0.4942 - val_accuracy: 0.8043
Epoch 5/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4967 - accuracy: 0.8070
Epoch 00005: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4897 - accuracy: 0.8083 - val_loss: 0.4952 - val_accuracy: 0.8043
Epoch 6/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4615 - accuracy: 0.7427
Epoch 00006: val_loss did not improve from 0.16301
360/360 [==============================] - 41s 114ms/sample - loss: 0.4750 - accuracy: 0.7361 - val_loss: 0.4985 - val_accuracy: 0.8043
Epoch 7/10
342/360 [===========================>..] - ETA: 1s - loss: 0.4119 - accuracy: 0.7924
Epoch 00007: val_loss did not improve from 0.16301
360/360 [==============================] - 40s 111ms/sample - loss: 0.4164 - accuracy: 0.7944 - val_loss: 0.4953 - val_accuracy: 0.8043
Epoch 8/10
342/360 [===========================>..] - ETA: 0s - loss: 0.4182 - accuracy: 0.8158
Epoch 00008: val_loss did not improve from 0.16301
360/360 [==============================] - 20s 55ms/sample - loss: 0.4155 - accuracy: 0.8194 - val_loss: 0.4957 - val_accuracy: 0.8043
Epoch 9/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3892 - accuracy: 0.8304
Epoch 00009: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 00009: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 57ms/sample - loss: 0.3853 - accuracy: 0.8278 - val_loss: 0.4997 - val_accuracy: 0.8043
Epoch 10/10
342/360 [===========================>..] - ETA: 0s - loss: 0.3395 - accuracy: 0.8333
Epoch 00010: val_loss did not improve from 0.16301
360/360 [==============================] - 21s 58ms/sample - loss: 0.3375 - accuracy: 0.8333 - val_loss: 0.5003 - val_accuracy: 0.8043

Body:
I tried to change the output dense to 1, instead of 2. The accuracy still with the same behavior.

epochs=10
model = Sequential()
model.add(tf.keras.applications.ResNet50( include_top=False, pooling='avg', weights='imagenet'))
model.add(BatchNormalization())
model.add(Dropout(0.4))
model.add(Dense(1, activation='sigmoid'))
model.layers[0].trainable = False
weights=class_weight.compute_class_weight('balanced', np.unique(y_train), y_train)
opt =Adam(learning_rate=0.001)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
tf.random.set_seed(2)
rede=model.fit(X_train, y_train, epochs=epochs, batch_size=18, class_weight=weights, callbacks=callbacks,\
               validation_data=(X_valid, y_valid))
Train on 360 samples, validate on 46 samples
Epoch 1/10
360/360 [==============================] - 17s 48ms/sample - loss: 0.8778 - accuracy: 0.5639 - val_loss: 0.3967 - val_accuracy: 0.8696
Epoch 2/10
360/360 [==============================] - 9s 24ms/sample - loss: 0.6527 - accuracy: 0.7028 - val_loss: 0.3973 - val_accuracy: 0.8696
Epoch 3/10
360/360 [==============================] - 9s 26ms/sample - loss: 0.6054 - accuracy: 0.7222 - val_loss: 0.4171 - val_accuracy: 0.8696
Epoch 4/10
360/360 [==============================] - 10s 28ms/sample - loss: 0.5388 - accuracy: 0.7500 - val_loss: 0.4211 - val_accuracy: 0.8696
Epoch 5/10
360/360 [==============================] - 11s 30ms/sample - loss: 0.4830 - accuracy: 0.7694 - val_loss: 0.4367 - val_accuracy: 0.8696
Epoch 6/10
342/360 [===========================>..] - ETA: 0s - loss: 0.4986 - accuracy: 0.8070
Epoch 00006: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.
360/360 [==============================] - 11s 29ms/sample - loss: 0.4952 - accuracy: 0.8056 - val_loss: 0.4576 - val_accuracy: 0.8696
Epoch 7/10
360/360 [==============================] - 11s 30ms/sample - loss: 0.4257 - accuracy: 0.8306 - val_loss: 0.4661 - val_accuracy: 0.8696
Epoch 8/10
360/360 [==============================] - 17s 46ms/sample - loss: 0.4054 - accuracy: 0.8250 - val_loss: 0.4722 - val_accuracy: 0.8696
Epoch 9/10
360/360 [==============================] - 17s 48ms/sample - loss: 0.4484 - accuracy: 0.7917 - val_loss: 0.4761 - val_accuracy: 0.8696
Epoch 10/10
360/360 [==============================] - 16s 44ms/sample - loss: 0.3844 - accuracy: 0.8472 - val_loss: 0.4785 - val_accuracy: 0.8696


问:
Modern OpenGL: Object picking (C#, OpenTK)
I am trying to implement object picking in OpenGL using C# and OpenTK. I have written a class for this purpose based on two sources:

OpenGL ray casting (picking): account for object's transform

https://www.bfilipek.com/2012/06/select-mouse-opengl.html

Currently my code is only for calculating the distance of the mouse pointer from an arbitrary test coordinate of (0,0,0), but once working it would not take much to iterate through objects in a scene to find a match.

The method is to define a ray underneath the mouse pointer between the near and far clipping planes. Then find the point on that ray which is closest to the point being tested and return the distance between the two. This should be zero when the mouse pointer is directly over (0,0,0) and increase as it moves away in any direction.

Can anyone help troubleshoot this? It executes without errors but the distance being returned clearly isn't correct. I understand the principles but not the finer points of the calculations.

Although I have found various examples online which almost do it, they are generally in a different language or framework and/or use deprecated methods and/or are incomplete or not working.

```<code>public class ObjectPicker{

    public static float DistanceFromPoint(Point mouseLocation, Vector3 testPoint, Matrix4 modelView, Matrix4 projection)
    {
        Vector3 near = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 0), modelView, projection); // start of ray
        Vector3 far = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 1), modelView, projection); // end of ray
        Vector3 pt = ClosestPoint(near, far, testPoint); // find point on ray which is closest to test point
        return Vector3.Distance(pt, testPoint); // return the distance
    }
    private static Vector3 ClosestPoint(Vector3 A, Vector3 B, Vector3 P)
    {
        Vector3 AB = B - A;
        float ab_square = Vector3.Dot(AB, AB);
        Vector3 AP = P - A;
        float ap_dot_ab = Vector3.Dot(AP, AB);
        // t is a projection param when we project vector AP onto AB
        float t = ap_dot_ab / ab_square;
        // calculate the closest point
        Vector3 Q = A + Vector3.Multiply(AB, t);
        return Q;
    }
    private static Vector3 UnProject(Vector3 screen, Matrix4 modelView, Matrix4 projection)
    {
        int[] viewport = new int[4];
        OpenTK.Graphics.OpenGL.GL.GetInteger(OpenTK.Graphics.OpenGL.GetPName.Viewport, viewport);

        Vector4 pos = new Vector4();

        // Map x and y from window coordinates, map to range -1 to 1
        pos.X = (screen.X - (float)viewport[0]) / (float)viewport[2] * 2.0f - 1.0f;
        pos.Y = 1 - (screen.Y - (float)viewport[1]) / (float)viewport[3] * 2.0f;
        pos.Z = screen.Z * 2.0f - 1.0f;
        pos.W = 1.0f;

        Vector4 pos2 = Vector4.Transform( pos, Matrix4.Invert(modelView) * projection );
        Vector3 pos_out = new Vector3(pos2.X, pos2.Y, pos2.Z);

        return pos_out / pos2.W;
    }
}
</code>```

It is called like this:

```<code>    private void GlControl1_MouseMove(object sender, MouseEventArgs e)
    {

        float dist = ObjectPicker.DistanceFromPoint(new Point(e.X,e.Y), new Vector3(0,0,0), model, projection);
        this.Text = dist.ToString(); // display in window caption for debugging

    }
</code>```

I know how the matrices are being passed in (as per above code). I'm fairly sure that the contents of those matrices must be correct, since the rendering works fine, and I can rotate/zoom successfully. This is the vertex shader FWIW:

```<code>        string vertexShaderSource =
            "# version 330 core\n" +
            "layout(location = 0) in vec3 aPos;" +
            "layout(location = 1) in vec3 aNormal;" +
            "uniform mat4 model;    " +
            "uniform mat4 view;" +
            "uniform mat4 projection;" +
            "out vec3 FragPos;" +
            "out vec3 Normal;" +
            "void main()" +
            "{" +
            "gl_Position = projection * view * model * vec4(aPos, 1.0);" +
            "FragPos = vec3(model * vec4(aPos, 1.0));" +
            "Normal = vec3(model * vec4(aNormal, 1.0))";
            "}";
</code>```

I use an implementation of Arcball for rotation. Zooming is done using a translation, like this:

```<code>private void glControl1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        zoom += (float)e.Delta / 240;
        view = Matrix4.CreateTranslation(0.0f, 0.0f, zoom);
        SetMatrix4(Handle, "view", view);
        glControl1.Invalidate();
    }
</code>```

答:
Answering my own question here so that I can post the working code for the benefit of other users, but at least half the answer was provided by Rabbid76, whose help I am very grateful for.

There were two errors in my original code:

Vector4 pos2 = Vector4.Transform( pos, Matrix4.Invert(modelView) * projection );

where the two matrixes were multiplied in the wrong order, and the projection matrix was not inverted.

float dist = ObjectPicker.DistanceFromPoint(new Point(e.X,e.Y), new Vector3(0,0,0), model, projection);

where I passed in the model matrix not the modelview matrix (which is the product of the model and view matrices).

This works:

```<code>private void GlControl1_MouseMove(object sender, MouseEventArgs e)
{

    float dist = ObjectPicker.DistanceFromPoint(new Point(e.X,e.Y), new Vector3(0,0,0), model * view, projection);
    // do something with the result

}

public class ObjectPicker{

    public static float DistanceFromPoint(Point mouseLocation, Vector3 testPoint, Matrix4 modelView, Matrix4 projection)
    {

        int[] viewport = new int[4];
        OpenTK.Graphics.OpenGL.GL.GetInteger(OpenTK.Graphics.OpenGL.GetPName.Viewport, viewport);
        Vector3 near = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 0), modelView, projection); // start of ray (near plane)
        Vector3 far = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 1), modelView, projection); // end of ray (far plane)
        Vector3 pt = ClosestPoint(near, far, testPoint); // find point on ray which is closest to test point

        return Vector3.Distance(pt, testPoint); // return the distance
    }
    private static Vector3 ClosestPoint(Vector3 A, Vector3 B, Vector3 P)
    {
        Vector3 AB = B - A;
        float ab_square = Vector3.Dot(AB, AB);
        Vector3 AP = P - A;
        float ap_dot_ab = Vector3.Dot(AP, AB);
        // t is a projection param when we project vector AP onto AB
        float t = ap_dot_ab / ab_square;
        // calculate the closest point
        Vector3 Q = A + Vector3.Multiply(AB, t);
        return Q;
    }
    private static Vector3 UnProject(Vector3 screen, Matrix4 modelView, Matrix4 projection)
    {
        int[] viewport = new int[4];
        OpenTK.Graphics.OpenGL.GL.GetInteger(OpenTK.Graphics.OpenGL.GetPName.Viewport, viewport);

        Vector4 pos = new Vector4();

        // Map x and y from window coordinates, map to range -1 to 1
        pos.X = (screen.X - (float)viewport[0]) / (float)viewport[2] * 2.0f - 1.0f;
        pos.Y = 1 - (screen.Y - (float)viewport[1]) / (float)viewport[3] * 2.0f;
        pos.Z = screen.Z * 2.0f - 1.0f;
        pos.W = 1.0f;

        Vector4 pos2 = Vector4.Transform( pos, Matrix4.Invert(projection) * Matrix4.Invert(modelView) );
        Vector3 pos_out = new Vector3(pos2.X, pos2.Y, pos2.Z);

        return pos_out / pos2.W;
    }

}
</code>```

Since posting this question I have learned that the method is generally called ray casting, and have found a couple of excellent explanations of it:

Mouse Picking with Ray Casting by Anton Gerdelan

OpenGL 3D Game Tutorial 29: Mouse Picking by ThinMatrix

Body:
I am trying to implement object picking in OpenGL using C# and OpenTK. I have written a class for this purpose based on two sources:

OpenGL ray casting (picking): account for object's transform

https://www.bfilipek.com/2012/06/select-mouse-opengl.html

Currently my code is only for calculating the distance of the mouse pointer from an arbitrary test coordinate of (0,0,0), but once working it would not take much to iterate through objects in a scene to find a match.

The method is to define a ray underneath the mouse pointer between the near and far clipping planes. Then find the point on that ray which is closest to the point being tested and return the distance between the two. This should be zero when the mouse pointer is directly over (0,0,0) and increase as it moves away in any direction.

Can anyone help troubleshoot this? It executes without errors but the distance being returned clearly isn't correct. I understand the principles but not the finer points of the calculations.

Although I have found various examples online which almost do it, they are generally in a different language or framework and/or use deprecated methods and/or are incomplete or not working.

public class ObjectPicker{

    public static float DistanceFromPoint(Point mouseLocation, Vector3 testPoint, Matrix4 modelView, Matrix4 projection)
    {
        Vector3 near = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 0), modelView, projection); // start of ray
        Vector3 far = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 1), modelView, projection); // end of ray
        Vector3 pt = ClosestPoint(near, far, testPoint); // find point on ray which is closest to test point
        return Vector3.Distance(pt, testPoint); // return the distance
    }
    private static Vector3 ClosestPoint(Vector3 A, Vector3 B, Vector3 P)
    {
        Vector3 AB = B - A;
        float ab_square = Vector3.Dot(AB, AB);
        Vector3 AP = P - A;
        float ap_dot_ab = Vector3.Dot(AP, AB);
        // t is a projection param when we project vector AP onto AB
        float t = ap_dot_ab / ab_square;
        // calculate the closest point
        Vector3 Q = A + Vector3.Multiply(AB, t);
        return Q;
    }
    private static Vector3 UnProject(Vector3 screen, Matrix4 modelView, Matrix4 projection)
    {
        int[] viewport = new int[4];
        OpenTK.Graphics.OpenGL.GL.GetInteger(OpenTK.Graphics.OpenGL.GetPName.Viewport, viewport);

        Vector4 pos = new Vector4();

        // Map x and y from window coordinates, map to range -1 to 1
        pos.X = (screen.X - (float)viewport[0]) / (float)viewport[2] * 2.0f - 1.0f;
        pos.Y = 1 - (screen.Y - (float)viewport[1]) / (float)viewport[3] * 2.0f;
        pos.Z = screen.Z * 2.0f - 1.0f;
        pos.W = 1.0f;

        Vector4 pos2 = Vector4.Transform( pos, Matrix4.Invert(modelView) * projection );
        Vector3 pos_out = new Vector3(pos2.X, pos2.Y, pos2.Z);

        return pos_out / pos2.W;
    }
}

It is called like this:

    private void GlControl1_MouseMove(object sender, MouseEventArgs e)
    {

        float dist = ObjectPicker.DistanceFromPoint(new Point(e.X,e.Y), new Vector3(0,0,0), model, projection);
        this.Text = dist.ToString(); // display in window caption for debugging

    }

I know how the matrices are being passed in (as per above code). I'm fairly sure that the contents of those matrices must be correct, since the rendering works fine, and I can rotate/zoom successfully. This is the vertex shader FWIW:

        string vertexShaderSource =
            "# version 330 core\n" +
            "layout(location = 0) in vec3 aPos;" +
            "layout(location = 1) in vec3 aNormal;" +
            "uniform mat4 model;    " +
            "uniform mat4 view;" +
            "uniform mat4 projection;" +
            "out vec3 FragPos;" +
            "out vec3 Normal;" +
            "void main()" +
            "{" +
            "gl_Position = projection * view * model * vec4(aPos, 1.0);" +
            "FragPos = vec3(model * vec4(aPos, 1.0));" +
            "Normal = vec3(model * vec4(aNormal, 1.0))";
            "}";

I use an implementation of Arcball for rotation. Zooming is done using a translation, like this:

private void glControl1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        zoom += (float)e.Delta / 240;
        view = Matrix4.CreateTranslation(0.0f, 0.0f, zoom);
        SetMatrix4(Handle, "view", view);
        glControl1.Invalidate();
    }

Body:
Answering my own question here so that I can post the working code for the benefit of other users, but at least half the answer was provided by Rabbid76, whose help I am very grateful for.

There were two errors in my original code:

Vector4 pos2 = Vector4.Transform( pos, Matrix4.Invert(modelView) * projection );

where the two matrixes were multiplied in the wrong order, and the projection matrix was not inverted.

float dist = ObjectPicker.DistanceFromPoint(new Point(e.X,e.Y), new Vector3(0,0,0), model, projection);

where I passed in the model matrix not the modelview matrix (which is the product of the model and view matrices).

This works:

private void GlControl1_MouseMove(object sender, MouseEventArgs e)
{

    float dist = ObjectPicker.DistanceFromPoint(new Point(e.X,e.Y), new Vector3(0,0,0), model * view, projection);
    // do something with the result

}

public class ObjectPicker{

    public static float DistanceFromPoint(Point mouseLocation, Vector3 testPoint, Matrix4 modelView, Matrix4 projection)
    {

        int[] viewport = new int[4];
        OpenTK.Graphics.OpenGL.GL.GetInteger(OpenTK.Graphics.OpenGL.GetPName.Viewport, viewport);
        Vector3 near = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 0), modelView, projection); // start of ray (near plane)
        Vector3 far = UnProject(new Vector3(mouseLocation.X, mouseLocation.Y, 1), modelView, projection); // end of ray (far plane)
        Vector3 pt = ClosestPoint(near, far, testPoint); // find point on ray which is closest to test point

        return Vector3.Distance(pt, testPoint); // return the distance
    }
    private static Vector3 ClosestPoint(Vector3 A, Vector3 B, Vector3 P)
    {
        Vector3 AB = B - A;
        float ab_square = Vector3.Dot(AB, AB);
        Vector3 AP = P - A;
        float ap_dot_ab = Vector3.Dot(AP, AB);
        // t is a projection param when we project vector AP onto AB
        float t = ap_dot_ab / ab_square;
        // calculate the closest point
        Vector3 Q = A + Vector3.Multiply(AB, t);
        return Q;
    }
    private static Vector3 UnProject(Vector3 screen, Matrix4 modelView, Matrix4 projection)
    {
        int[] viewport = new int[4];
        OpenTK.Graphics.OpenGL.GL.GetInteger(OpenTK.Graphics.OpenGL.GetPName.Viewport, viewport);

        Vector4 pos = new Vector4();

        // Map x and y from window coordinates, map to range -1 to 1
        pos.X = (screen.X - (float)viewport[0]) / (float)viewport[2] * 2.0f - 1.0f;
        pos.Y = 1 - (screen.Y - (float)viewport[1]) / (float)viewport[3] * 2.0f;
        pos.Z = screen.Z * 2.0f - 1.0f;
        pos.W = 1.0f;

        Vector4 pos2 = Vector4.Transform( pos, Matrix4.Invert(projection) * Matrix4.Invert(modelView) );
        Vector3 pos_out = new Vector3(pos2.X, pos2.Y, pos2.Z);

        return pos_out / pos2.W;
    }

}

Since posting this question I have learned that the method is generally called ray casting, and have found a couple of excellent explanations of it:

Mouse Picking with Ray Casting by Anton Gerdelan

OpenGL 3D Game Tutorial 29: Mouse Picking by ThinMatrix


问:
How to add multiple calendar events using Microsoft graph
I am able to create a single outlook calendar event but how to create multiple at the same time, is there is any way using Microsoft graph api?

I have tried passing an array of events to api, throwing JSON error

```<code>var event = {
    "subject": "Let's go for lunch",
    "body": {
        "contentType": "HTML",
        "content": "Does late morning work for you?"
    },
    "start": {
        "dateTime": "2017-04-15T12:00:00",
        "timeZone": "Pacific Standard Time"
    },
    "end": {
        "dateTime": "2017-04-15T14:00:00",
        "timeZone": "Pacific Standard Time"
    },
    "location": {
        "displayName": "Harry's Bar"
    },
    "attendees": [{
        "emailAddress": {
            "address": "samanthab@contoso.onmicrosoft.com",
            "name": "Samantha Booth"
        },
        "type": "required"
    }]
}

client
    .api('/me/events')
    .post(event, (err, res) => {
        console.log(res)
    })
</code>```

for one event it's working but I need to add multiple events lets say 2 pm to 3 pm and 6 pm to 7 pm, for loop consuming too much time

答:
Currently the 'Events' api's post method allows to send request body with information only for a single event.

In order to create multiple events in a single request you can batch your request for various endpoints as a request body and post it to
Batch Graph Request Endpoint.

You can find more info on
Json Batching Multiple Graph Requests here

Body:
I am able to create a single outlook calendar event but how to create multiple at the same time, is there is any way using Microsoft graph api?

I have tried passing an array of events to api, throwing JSON error

var event = {
    "subject": "Let's go for lunch",
    "body": {
        "contentType": "HTML",
        "content": "Does late morning work for you?"
    },
    "start": {
        "dateTime": "2017-04-15T12:00:00",
        "timeZone": "Pacific Standard Time"
    },
    "end": {
        "dateTime": "2017-04-15T14:00:00",
        "timeZone": "Pacific Standard Time"
    },
    "location": {
        "displayName": "Harry's Bar"
    },
    "attendees": [{
        "emailAddress": {
            "address": "samanthab@contoso.onmicrosoft.com",
            "name": "Samantha Booth"
        },
        "type": "required"
    }]
}

client
    .api('/me/events')
    .post(event, (err, res) => {
        console.log(res)
    })

for one event it's working but I need to add multiple events lets say 2 pm to 3 pm and 6 pm to 7 pm, for loop consuming too much time


问:
ES lint init setup not shown VS Code Windows OS
I trying to set up the Eslint in VS Code IDE, however after installing the eslint dependency,
by $ npm install eslint --save-dev command then
executing the below command for configuration

```<code>$ ./node_modules/.bin/eslint --init
</code>```

getting the following error, what is the problem?

eslint : File \AppData\Roaming\npm\eslint.ps1 cannot be
  loaded because running scripts is disabled on this system. For more
  information, see  about_Execution_Policies at
  https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1
  + eslint --init
  + ~~~~~~
      + CategoryInfo          : SecurityError: (:) [], PSSecurityException

      + FullyQualifiedErrorId : UnauthorizedAccess

答:
In your powershell you might need to execute

```<code>Set-ExecutionPolicy RemoteSigned
</code>```

Try

```<code>npx eslint --init
</code>```

Also what is the output with

```<code>npm run eslint --init
</code>```

Body:
I trying to set up the Eslint in VS Code IDE, however after installing the eslint dependency,
by $ npm install eslint --save-dev command then
executing the below command for configuration

$ ./node_modules/.bin/eslint --init

getting the following error, what is the problem?

eslint : File \AppData\Roaming\npm\eslint.ps1 cannot be
  loaded because running scripts is disabled on this system. For more
  information, see  about_Execution_Policies at
  https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1
  + eslint --init
  + ~~~~~~
      + CategoryInfo          : SecurityError: (:) [], PSSecurityException

      + FullyQualifiedErrorId : UnauthorizedAccess

Body:
In your powershell you might need to execute

Set-ExecutionPolicy RemoteSigned

Try

npx eslint --init

Also what is the output with

npm run eslint --init


问:
How to properly interconnect Apollo Server / mongodb / express?
I am attemping to use express to serve my static images.  I have attempted to integrate express with Apollo Server in the code below.  Unfortunately, when doing so, the mongodb data no longer displays on the front end.  Is there any issue with my code OR are ApolloServer/Mongodb/Express not compatible?

As a sidenote, when I remove all express content and simply return server.listen() etc it works perfectly (so I realize the disconnect is with express implementation)

index.js

```<code>const { ApolloServer, PubSub } = require("apollo-server-express");
const mongoose = require("mongoose");

const { createWriteStream, existsSync, mkdirSync } = require("fs");
const path = require("path");
const express = require("express");

const typeDefs = require("./graphql/typeDefs");
const resolvers = require("./graphql/resolvers");
const { MONGODB } = require("./config.js");

const pubsub = new PubSub();

//server instance
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => ({ req, pubsub }),
});

const app = express();
app.use("/images", express.static(path.join(__dirname, "../images")));
server.applyMiddleware({ app });

mongoose
  .connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log("MongoDB Connected");
    return app.listen(5000, () => {
      console.log(`  Server ready at http://localhost:5000/`);
    });
  })
</code>```

答: By default, apollo-server-express exposes your GraphQL endpoint at /graphql, not / like apollo-server does. You can customize this behavior by providing a path option to applyMiddleware. However, I wouldn't change the path back to / in this case -- instead just modify your client code to send requests to the correct URL.

Body:
I am attemping to use express to serve my static images.  I have attempted to integrate express with Apollo Server in the code below.  Unfortunately, when doing so, the mongodb data no longer displays on the front end.  Is there any issue with my code OR are ApolloServer/Mongodb/Express not compatible?

As a sidenote, when I remove all express content and simply return server.listen() etc it works perfectly (so I realize the disconnect is with express implementation)

index.js

const { ApolloServer, PubSub } = require("apollo-server-express");
const mongoose = require("mongoose");

const { createWriteStream, existsSync, mkdirSync } = require("fs");
const path = require("path");
const express = require("express");

const typeDefs = require("./graphql/typeDefs");
const resolvers = require("./graphql/resolvers");
const { MONGODB } = require("./config.js");

const pubsub = new PubSub();

//server instance
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => ({ req, pubsub }),
});

const app = express();
app.use("/images", express.static(path.join(__dirname, "../images")));
server.applyMiddleware({ app });

mongoose
  .connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log("MongoDB Connected");
    return app.listen(5000, () => {
      console.log(`  Server ready at http://localhost:5000/`);
    });
  })


问:
AMP-Email security
I am successfully sending forms with data from amp-email, but there is a security issue.

Can a hacker intercept the data that the user sends via the form in amp-email? If it can, what is the probability and how easy it is to do it.

答:
Hacker can see your requests from email to backend API in chrome devTools.

Example of expluatation:

Let's say that our site has a page showing the history of weather observations for a single city. The ID of this city is passed by the link in the request parameter: /weather.php?city_id=<ID>, where ID - is the primary key of the city.
In a PHP script, we use this parameter for substitutions in an SQL query:

```<code>$city_id = $_GET['city_id'];
$res = mysqli_query($link, "SELECT * FROM weather_log WHERE city_id = " . $city_id);
</code>```

If the server passed the city_id parameter equal to 10 /weather.php?city_id=10, an SQL query is executed:

SELECT * FROM weather_log WHERE city_id = 10

But if the attacker passes the string -1 OR 1=1 as the id parameter, the request is executed:

SELECT * FROM weather_log WHERE city_id = -1 OR 1=1

Adding SQL language constructs to the input parameters (instead of simple values) changes the execution logic of the entire SQL query!

In this example, instead of showing data for one city, data for all cities will be received, because the expression 1=1 is always true. Instead of the SELECT ... expression, there could be an expression for updating data, and then the consequences would be even more serious.

The lack of proper processing of SQL query parameters is one of the most serious vulnerabilities. Never insert data from the user in SQL queries "as is"!

Title: AMP-Email security

Body:
Hacker can see your requests from email to backend API in chrome devTools.

Example of expluatation:

Let's say that our site has a page showing the history of weather observations for a single city. The ID of this city is passed by the link in the request parameter: /weather.php?city_id=<ID>, where ID - is the primary key of the city.
In a PHP script, we use this parameter for substitutions in an SQL query:

$city_id = $_GET['city_id'];
$res = mysqli_query($link, "SELECT * FROM weather_log WHERE city_id = " . $city_id);

If the server passed the city_id parameter equal to 10 /weather.php?city_id=10, an SQL query is executed:

SELECT * FROM weather_log WHERE city_id = 10

But if the attacker passes the string -1 OR 1=1 as the id parameter, the request is executed:

SELECT * FROM weather_log WHERE city_id = -1 OR 1=1

Adding SQL language constructs to the input parameters (instead of simple values) changes the execution logic of the entire SQL query!

In this example, instead of showing data for one city, data for all cities will be received, because the expression 1=1 is always true. Instead of the SELECT ... expression, there could be an expression for updating data, and then the consequences would be even more serious.

The lack of proper processing of SQL query parameters is one of the most serious vulnerabilities. Never insert data from the user in SQL queries "as is"!


答:
You could use a set. isdisjoint is a method which returns True if two sets have nothing in common and False if the sets overlap. After converting list1 and list2 into sets, they both contain 'item3' so isdisjoint returns False.

set(list1).isdisjoint(set(list2))
```

<pre class="lang-py prettyprint-override"><code>>>> list1 = ['item1','item2','item3']
>>> list2 = ['item4','item5','item3']
>>> set(list1).isdisjoint(set(list2))
False
</code>```

You can combine this with the not operator to do what you want.

list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if not set(list1).isdisjoint(set(list2)):
    print("Duplicates found.")
else:
    print("No duplicates found.")
```

Title: Can I check if a list contains any item from another list?

Body:
You could use a set. isdisjoint is a method which returns True if two sets have nothing in common and False if the sets overlap. After converting list1 and list2 into sets, they both contain 'item3' so isdisjoint returns False.

set(list1).isdisjoint(set(list2))

>>> list1 = ['item1','item2','item3']
>>> list2 = ['item4','item5','item3']
>>> set(list1).isdisjoint(set(list2))
False

You can combine this with the not operator to do what you want.

list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if not set(list1).isdisjoint(set(list2)):
    print("Duplicates found.")
else:
    print("No duplicates found.")


问:
Argument of type is not assignable to parameter of type 'MiddlewareFunc'. app.use(oakCors());
I am getting this error when I am trying to add cors in deno.

Argument of type '(context: { request: any; response: any; }, next: (...args: any) => any) => any' is not assignable to parameter of type 'MiddlewareFunc'.
app.use(oakCors());

import { Application } from "https://deno.land/x/abc@v1.0.0-rc8/mod.ts";
import { getAllBlogs, getBlogById, addNewBlog } from './controllers/index.ts';
import { oakCors } from "https://deno.land/x/cors/mod.ts";

const app = new Application();

app
.use(oakCors())
.get('/blogs', getAllBlogs)
.get('/blog/:id', getBlogById)
.post('/add-blog', addNewBlog)
.start({ port: 8000 })```

Error Image

答:
cors exports middlewares for different frameworks, you should use abcCors for abc and not oakCors which is for Oak.

```<code>import { abcCors } from "https://deno.land/x/cors/mod.ts";
</code>```

Body:
I am getting this error when I am trying to add cors in deno.

Argument of type '(context: { request: any; response: any; }, next: (...args: any) => any) => any' is not assignable to parameter of type 'MiddlewareFunc'.
app.use(oakCors());

import { Application } from "https://deno.land/x/abc@v1.0.0-rc8/mod.ts";
import { getAllBlogs, getBlogById, addNewBlog } from './controllers/index.ts';
import { oakCors } from "https://deno.land/x/cors/mod.ts";

const app = new Application();

app
.use(oakCors())
.get('/blogs', getAllBlogs)
.get('/blog/:id', getBlogById)
.post('/add-blog', addNewBlog)
.start({ port: 8000 })

Error Image

Body:
cors exports middlewares for different frameworks, you should use abcCors for abc and not oakCors which is for Oak.

import { abcCors } from "https://deno.land/x/cors/mod.ts";


问:
Local Storage - React Native
As Async Storage is deprecated what other way is there to store a variable locally??

I have a React Native ios App with a Notification Centre.
Each time the user enters the Notification Centre a Cognito access Token was generated. To avoid excess of token generation the Tokens were saved through Async storage and their expiry was checked.

Now is there some other local storage in React Native that i can use??

答:
It is moved to @react-native-community/async-storage

Install it and import it from lib:

import AsyncStorage from '@react-native-community/async-storage';
```

Title: Local Storage - React Native


问:
I'm trying to merge two sorted arrays but getting java.lang.ArrayIndexOutOfBoundsException: 5 can't figure out why
It is going out bounds on the first if statement even after I'm checking the values of j and k before incrementing

```<code>`int[] Merge(int[]a,int[]b){
int n=a.length+b.length;
int[] sol= new int[n];
int i=0,j=0,k=0;

while(i<n){

if(a[j]<b[k]){

    sol[i]=a[j];

    if(j<a.length)j++;
}
else if(b[k]<a[j]){

        sol[i]=b[k];

        if(k<b.length)k++;

}

i++;

}

return sol;

}`
</code>```

I can't understand where the array is going out of bounds

答:
The problem is here:

```<code>if(j<a.length)j++;
</code>```

Here when j = a.length - 1 then it will become a.length because of j++.
Now, a[j] will be out of bounds because j  = a.length. a[a.length] is always out bounds. The indexing starts from 0, so last index is a.length - 1.

Body:
It is going out bounds on the first if statement even after I'm checking the values of j and k before incrementing

`int[] Merge(int[]a,int[]b){
int n=a.length+b.length;
int[] sol= new int[n];
int i=0,j=0,k=0;

while(i<n){

if(a[j]<b[k]){

    sol[i]=a[j];

    if(j<a.length)j++;
}
else if(b[k]<a[j]){

        sol[i]=b[k];

        if(k<b.length)k++;

}

i++;

}

return sol;

}`

I can't understand where the array is going out of bounds

Body:
The problem is here:

if(j<a.length)j++;

Here when j = a.length - 1 then it will become a.length because of j++.
Now, a[j] will be out of bounds because j  = a.length. a[a.length] is always out bounds. The indexing starts from 0, so last index is a.length - 1.


问:
Measuring elapsed time with the Time module
With the Time module in python is it possible to measure elapsed time? If so, how do I do that? </p>

<p>I need to do this so that if the cursor has been in a widget for a certain duration an event happens.  </p>

答:
In programming, there are 2 main ways to measure time, with different results:

```<code>>>> print(time.process_time()); time.sleep(10); print(time.process_time())
0.11751394000000001
0.11764988400000001  # took  0 seconds and a bit
>>> print(time.perf_counter()); time.sleep(10); print(time.perf_counter())
3972.465770326
3982.468109075       # took 10 seconds and a bit
</code>```

Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.

Use time.process_time()

Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.

Use time.perf_counter()

time.time() also measures wall-clock time but can be reset, so you could go back in time

time.monotonic() cannot be reset (monotonic = only goes  forward) but has lower precision than time.perf_counter()

ContentLicense: CC BY-SA 2.5

Body:
With the Time module in python is it possible to measure elapsed time? If so, how do I do that?

I need to do this so that if the cursor has been in a widget for a certain duration an event happens.

Body:
In programming, there are 2 main ways to measure time, with different results:

>>> print(time.process_time()); time.sleep(10); print(time.process_time())
0.11751394000000001
0.11764988400000001  # took  0 seconds and a bit
>>> print(time.perf_counter()); time.sleep(10); print(time.perf_counter())
3972.465770326
3982.468109075       # took 10 seconds and a bit

Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.

Use time.process_time()

Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.

Use time.perf_counter()

time.time() also measures wall-clock time but can be reset, so you could go back in time

time.monotonic() cannot be reset (monotonic = only goes  forward) but has lower precision than time.perf_counter()


问:
Confusion over class resolution in Oracle java stored procedures
I'm trying to use a third-party java library within oracle.  The library seems compatible with the same 1.4 version of the jvm that our Oracle 10g server hosts, since it runs fine outside of Oracle, so I feel like I should be able to get this to work.  This library ends up making SOAP-based http requests, and I get class resolution errors when I run in Oracle.

Here's a line that shows the difference:

```<code>Class msgfact = Class.forName("com.sun.xml.messaging.saaj.soap.MessageFactoryImpl");
</code>```

I tried to register these libraries into Oracle with the loadjava utility, and I got what I thought was a successful result:

```
C:\>loadjava -verbose -schema MYUSER -user MYUSER/MYPWD@dbinstance -force saaj-impl.jar
```

It looks like everything gets loaded, and I can see this MessageFactoryImpl class in that list.  But then I try to run this line of code from Oracle SQL (inside another class I wrote and loaded with loadjava), this line throws a ClassNotFoundException (java.lang.ClassNotFoundException: com/sun/xml/messaging/saaj/soap/MessageFactoryImpl).

Then I went back and tried to add the "-resolve" switch at the loadjava command line.  It acts like these saaj classes are getting registered, but they aren't resolving properly.

How can I successfully get these saaj classes into Oracle,  or if for some reason Oracle already has these loaded, how can I convince my own code to successfully use the existing class?

FWIW, I already took the steps to make sure that the appropriate socket permissions were granted and my code can successfully make a generic http request to the target url.  It just has trouble using the library's SOAP stack to make it happen.

EDIT:
Here is a sample of my loadjava result.  This seems to be showing exactly what's failing, but I'm confused as to why these particular classes aren't being resolved when they seem to be handled properly in the pre-resolution steps.  I've eliminated about 80% of the file here, but there are other classes that show the same class resolution issues.

```
arguments: '-verbose' '-schema' 'MYSCHEMA' '-user' 'MYSCHEMA/MYSCHEMA@actest' '-resolve' '-force' 'saaj-impl.jar'
[snip]
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
[snip]
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/AttachmentPartImpl
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/Envelope
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/SOAPPartImpl could not be resolved
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/impl/EnvelopeImpl could not be resolved
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
skipping : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$2
[snip]
The following operations failed
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1: resolution
[snip]
exiting  : Failures occurred during processing
```

答:
Is this the first time your executing Java on the database?  Here is hello world implementation to make sure your Oracle JVM is running properly and you have the necessary permissions.  You said "my database schema, so I can do whatever I want" -doesn't mean you have the proper grants.

```<code>SQL> create or replace and compile java source named "Hello" as
   public class Hello{
      public static String world() {
         return "Hello World ";
      }
   };
/

Java created.
</code>```

Now the wrapper function

```<code>SQL> create or replace function Hello RETURN VARCHAR2
     as LANGUAGE JAVA NAME 'Hello.world() return String';
     /

Function created.
</code>```

Now test it

```<code>SQL> select Hello from dual;

HELLO
-----------------------------------
Hello World
</code>```

OwnerDisplayName: Chris Farmer

Body:
I'm trying to use a third-party java library within oracle.  The library seems compatible with the same 1.4 version of the jvm that our Oracle 10g server hosts, since it runs fine outside of Oracle, so I feel like I should be able to get this to work.  This library ends up making SOAP-based http requests, and I get class resolution errors when I run in Oracle.

Here's a line that shows the difference:

Class msgfact = Class.forName("com.sun.xml.messaging.saaj.soap.MessageFactoryImpl");

I tried to register these libraries into Oracle with the loadjava utility, and I got what I thought was a successful result:

C:\>loadjava -verbose -schema MYUSER -user MYUSER/MYPWD@dbinstance -force saaj-impl.jar

It looks like everything gets loaded, and I can see this MessageFactoryImpl class in that list.  But then I try to run this line of code from Oracle SQL (inside another class I wrote and loaded with loadjava), this line throws a ClassNotFoundException (java.lang.ClassNotFoundException: com/sun/xml/messaging/saaj/soap/MessageFactoryImpl).

Then I went back and tried to add the "-resolve" switch at the loadjava command line.  It acts like these saaj classes are getting registered, but they aren't resolving properly.

How can I successfully get these saaj classes into Oracle,  or if for some reason Oracle already has these loaded, how can I convince my own code to successfully use the existing class?

FWIW, I already took the steps to make sure that the appropriate socket permissions were granted and my code can successfully make a generic http request to the target url.  It just has trouble using the library's SOAP stack to make it happen.

EDIT:
Here is a sample of my loadjava result.  This seems to be showing exactly what's failing, but I'm confused as to why these particular classes aren't being resolved when they seem to be handled properly in the pre-resolution steps.  I've eliminated about 80% of the file here, but there are other classes that show the same class resolution issues.

arguments: '-verbose' '-schema' 'MYSCHEMA' '-user' 'MYSCHEMA/MYSCHEMA@actest' '-resolve' '-force' 'saaj-impl.jar'
[snip]
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
[snip]
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/AttachmentPartImpl
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/Envelope
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/SOAPPartImpl could not be resolved
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/impl/EnvelopeImpl could not be resolved
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
skipping : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$2
[snip]
The following operations failed
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1: resolution
[snip]
exiting  : Failures occurred during processing

LastEditorDisplayName: Chris Farmer

Body:
Is this the first time your executing Java on the database?  Here is hello world implementation to make sure your Oracle JVM is running properly and you have the necessary permissions.  You said "my database schema, so I can do whatever I want" -doesn't mean you have the proper grants.

SQL> create or replace and compile java source named "Hello" as
   public class Hello{
      public static String world() {
         return "Hello World ";
      }
   };
/

Java created.

Now the wrapper function

SQL> create or replace function Hello RETURN VARCHAR2
     as LANGUAGE JAVA NAME 'Hello.world() return String';
     /

Function created.

Now test it

SQL> select Hello from dual;

HELLO
-----------------------------------
Hello World

OwnerDisplayName: Brian


答:
Try using sets:

Following https://stackoverflow.com/a/2541823/1021819,

```<code>i=set.intersection(set(list1),set(list2))
if len(i) > 0:
    print('duplicates found')
else:
    print('no duplicates found')
</code>```

Body:
using Python, I want to check if a list contains an item/value that is also present in another list. For example, here is what I am trying to do:

list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if list1 contains any items also in list2:
    print("Duplicates found.")
else:
    print("No duplicates found.")

As you can see, list2 contains an item that is also found in list1, which is 'item3'. Is there any way I can detect if this occurs?

Thanks.

Body:
Try using sets:

Following https://stackoverflow.com/a/2541823/1021819,

i=set.intersection(set(list1),set(list2))
if len(i) > 0:
    print('duplicates found')
else:
    print('no duplicates found')


问:
Click checkbox within TR element
I'd like to select the checkbox based on the user email. I try somethig like this but doesn't work: "InvalidStateError: An exception was thrown  debugger eval code:1".

$x("//span[text()='my.user@mydomain.com']/parent::div/previousElementSibling::td");
```

<p>What am I doing wrong? Thanks!</p>

<pre class="lang-html prettyprint-override"><code>    <td class="col checkUser selection">
        <div class="checkbox um-checkbox">
            <input type="checkbox" value="option1">
            <label data-select-checkbox="" data-ngretain="u-cd324c08-f215-5784-87b7-98944b18819f"></label>
        </div>
    </td>
    <td class="col userData item-collapse item-top">
        <div class="showUserDetails" title="My User" data-id="u-cd324c08-f215-5784-87b7-98944b18819f">
            <span class="text-overflow " style="max-width: 90%;display: inline-block;">
            <span class="first-name">My </span>
            <span class="first-name">User </span>
            </span>
            <span>
        <img style="height: 24px;width:24px;margin-left: 5px;" src="/Admin/img/admin-gray.svg">
        </span>
        </div>
    </td>
    <td class="col userData item-collapse item-top">
        <div class="showUserDetails text-overflow" title="my.user@mydomain.com" data-id="u-cd324c08-f215-5784-87b7-98944b18819f">
            <span class="first-name">my.user@mydomain.com </span>
        </div>
    </td>
</code>```

答:
previousElementSibling is not a XPath selector but a property on a element: https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/previousElementSibling

An almost similar selector for a XPath is the preceding-sibling selector. But that will return all the preceding siblings so you will have to maximize the result to 1 with the [1] selector:

```<code>/preceding-sibling::div[1]
</code>```

And then you still need to only select the divs containing the checkbox class so you will need the [contains(@class, 'checkbox')] selector and select the input with the /input selector.

The complete selector for the checkbox then looks like this:

$x("//span[text()='my.user@mydomain.com']/parent::div/preceding-sibling::div[contains(@class, 'checkbox')][1]/input")
```

<p>If however you are using <code>document.evaluate</code> instead of <code>$x</code> you will need to replace the <code>text()='the text'</code> selector with the <code>contains(. ,'the text')</code> selector because the text() selector does not work in the <code>document.evaluate</code> method.</p>

<p>The complete executable code snippet:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var doc = document.children[0].children[1];
var checkbox = document.evaluate(
    "//span[contains(., 'my.user@mydomain.com')]/parent::div/preceding-sibling::div[contains(@class, 'checkbox')][1]/input",
    doc,
    null,
    XPathResult.ANY_TYPE,
    null
).iterateNext()

console.log(checkbox)
alert(checkbox)</code>```

            <input type="checkbox" value="option1">

            My
            User

            my.user@mydomain.com

    	```

Title: Click checkbox within TR element

Body:
I'd like to select the checkbox based on the user email. I try somethig like this but doesn't work: "InvalidStateError: An exception was thrown  debugger eval code:1".

$x("//span[text()='my.user@mydomain.com']/parent::div/previousElementSibling::td");

What am I doing wrong? Thanks!

            <input type="checkbox" value="option1">

            My
            User

            my.user@mydomain.com

Body:
previousElementSibling is not a XPath selector but a property on a element: https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/previousElementSibling

An almost similar selector for a XPath is the preceding-sibling selector. But that will return all the preceding siblings so you will have to maximize the result to 1 with the [1] selector:

/preceding-sibling::div[1]

And then you still need to only select the divs containing the checkbox class so you will need the [contains(@class, 'checkbox')] selector and select the input with the /input selector.

The complete selector for the checkbox then looks like this:

$x("//span[text()='my.user@mydomain.com']/parent::div/preceding-sibling::div[contains(@class, 'checkbox')][1]/input")

If however you are using document.evaluate instead of $x you will need to replace the text()='the text' selector with the contains(. ,'the text') selector because the text() selector does not work in the document.evaluate method.

The complete executable code snippet:

var doc = document.children[0].children[1];
var checkbox = document.evaluate(
    "//span[contains(., 'my.user@mydomain.com')]/parent::div/preceding-sibling::div[contains(@class, 'checkbox')][1]/input",
    doc,
    null,
    XPathResult.ANY_TYPE,
    null
).iterateNext()

console.log(checkbox)
alert(checkbox)

 <td class="col checkUser selection">
        <div class="checkbox um-checkbox">
            <input type="checkbox" value="option1">
            <label data-select-checkbox="" data-ngretain="u-cd324c08-f215-5784-87b7-98944b18819f"></label>
        </div>
    </td>
    <td class="col userData item-collapse item-top">
        <div class="showUserDetails" title="My User" data-id="u-cd324c08-f215-5784-87b7-98944b18819f">
            <span class="text-overflow " style="max-width: 90%;display: inline-block;">
            <span class="first-name">My </span>
            <span class="first-name">User </span>
            </span>
            <span>
        <a href="#" class="hide" style="display: inline-block;"><img style="height: 24px;width:24px;margin-left: 5px;" src="/Admin/img/admin-gray.svg"></a>
        </span>
        </div>
    </td>
    <td class="col userData item-collapse item-top">
        <div class="showUserDetails text-overflow" title="my.user@mydomain.com" data-id="u-cd324c08-f215-5784-87b7-98944b18819f">
            <span class="first-name">my.user@mydomain.com </span>
        </div>
    </td>


问:
How can I initialize a color array that shows color cubes in Swift 3?
I found this code part on GitHub and it works really fine, I can even change the color by clicking on the color cube. Also, I could copy the color cube and use anywhere I wanted. I want to know how to initialize this in Swift 3.

I tried this but couldn't figure it out.

```<code>    let cc = [UIColor(red: CGFloat(160/255), green: CGFloat(183.0/255), blue: CGFloat(227.0/255), alpha: 1), UIColor(red: CGFloat(160/255), green: CGFloat(183.0/255), blue: CGFloat(227.0/255), alpha: 1)]
</code>```

答: If you are creating color literals in one of your model files, do not forget import UIKit before you do this. </p>

Body:
I found this code part on GitHub and it works really fine, I can even change the color by clicking on the color cube. Also, I could copy the color cube and use anywhere I wanted. I want to know how to initialize this in Swift 3.

I tried this but couldn't figure it out.

    let cc = [UIColor(red: CGFloat(160/255), green: CGFloat(183.0/255), blue: CGFloat(227.0/255), alpha: 1), UIColor(red: CGFloat(160/255), green: CGFloat(183.0/255), blue: CGFloat(227.0/255), alpha: 1)]


问:
Passing data from a class which is Lifecycle observer to the Activity
I have a class BatteryInfo which is a life-cycle observer and in this class, there is a BroadCastReceiver which is responsible for getting all battery information. This class is working perfectly with the lifecycle of Activity from where I have called it. This means it is registering the broadcast on activity created and unRegister on closing activity. But I am confused about how to access this broadcast live information in Activity.

```<code>class BatteryInfo(
        private val _context: Context,
        private val _lifecycle: Lifecycle,
    ): LifecycleObserver {

        private var _enabled = false

        init {
            _lifecycle.addObserver(this)
        }

        private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

            override fun onReceive(context: Context?, intent: Intent?) {

                intent?.let {

                    val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                    val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                    val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                    val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                    val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                    val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                  //  Log.d("TAG", String.format("%.1f", voltage / 1000f) + " V")
                }
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun start() {
          //  if (_enabled) {
                _context.registerReceiver(broadcastBatteryInfoListener,
                    IntentFilter(Intent.ACTION_BATTERY_CHANGED)
                )
          // }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun stop() {
            _context.unregisterReceiver(broadcastBatteryInfoListener)
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun destroy() {
            _lifecycle.removeObserver(this)
        }

        // connect if not connected
        fun enable() {
            _enabled = true

            if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                start()
            }
        }
    }
</code>```

I am Calling this class from MainActivity onCreate method like this

```<code>BatteryInfo(this, lifecycle)
</code>```

答:
A simple listener would work :</p>

```<code>data class Stats(val level : Int,
                 val temp : Int,
                 val voltage : Int,
                 val technology : Int,
                 val plugged : Int,
                 val health : Int)

class BatteryInfo(
    private val _context: Context,
    private val _lifecycle: Lifecycle
): LifecycleObserver {

    private var _enabled = false
    private var listener: ((Stats) -> Unit)? = null

    init {
        _lifecycle.addObserver(this)
    }

    private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent?) {

            intent?.let {

                val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                listener?.invoke(Stats(level, temperature, voltage, technology, plugged, health))
                //  Log.d("TAG", String.format("%.1f", voltage / 1000f) + " V")
            }
        }
    }

    fun setListener(listener: ((Stats) -> Unit)?) {
        this.listener = listener
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun start() {
        //  if (_enabled) {
        _context.registerReceiver(broadcastBatteryInfoListener,
            IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        )
        // }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stop() {
        _context.unregisterReceiver(broadcastBatteryInfoListener)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun destroy() {
        _lifecycle.removeObserver(this)
        listener = null
    }

    // connect if not connected
    fun enable() {
        _enabled = true

        if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
            start()
        }
    }
}

class SomeActivity : AppCompatActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        BatteryInfo(this, lifecycle)
            .apply { setListener { stats: Stats -> Log.d(TAG, stats.toString()) } }

    }
}
</code>```

Body:
I have a class BatteryInfo which is a life-cycle observer and in this class, there is a BroadCastReceiver which is responsible for getting all battery information. This class is working perfectly with the lifecycle of Activity from where I have called it. This means it is registering the broadcast on activity created and unRegister on closing activity. But I am confused about how to access this broadcast live information in Activity.

class BatteryInfo(
        private val _context: Context,
        private val _lifecycle: Lifecycle,
    ): LifecycleObserver {

        private var _enabled = false

        init {
            _lifecycle.addObserver(this)
        }

        private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

            override fun onReceive(context: Context?, intent: Intent?) {

                intent?.let {

                    val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                    val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                    val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                    val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                    val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                    val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                  //  Log.d("TAG", String.format("%.1f", voltage / 1000f) + " V")
                }
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun start() {
          //  if (_enabled) {
                _context.registerReceiver(broadcastBatteryInfoListener,
                    IntentFilter(Intent.ACTION_BATTERY_CHANGED)
                )
          // }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun stop() {
            _context.unregisterReceiver(broadcastBatteryInfoListener)
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun destroy() {
            _lifecycle.removeObserver(this)
        }

        // connect if not connected
        fun enable() {
            _enabled = true

            if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                start()
            }
        }
    }

I am Calling this class from MainActivity onCreate method like this

BatteryInfo(this, lifecycle)

Body:
A simple listener would work :

data class Stats(val level : Int,
                 val temp : Int,
                 val voltage : Int,
                 val technology : Int,
                 val plugged : Int,
                 val health : Int)

class BatteryInfo(
    private val _context: Context,
    private val _lifecycle: Lifecycle
): LifecycleObserver {

    private var _enabled = false
    private var listener: ((Stats) -> Unit)? = null

    init {
        _lifecycle.addObserver(this)
    }

    private val broadcastBatteryInfoListener = object : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent?) {

            intent?.let {

                val level = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                val temperature = it.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)
                val voltage = it.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)
                val technology = it.getIntExtra(BatteryManager.EXTRA_TECHNOLOGY, -1)
                val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                val health = it.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)

                listener?.invoke(Stats(level, temperature, voltage, technology, plugged, health))
                //  Log.d("TAG", String.format("%.1f", voltage / 1000f) + " V")
            }
        }
    }

    fun setListener(listener: ((Stats) -> Unit)?) {
        this.listener = listener
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun start() {
        //  if (_enabled) {
        _context.registerReceiver(broadcastBatteryInfoListener,
            IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        )
        // }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stop() {
        _context.unregisterReceiver(broadcastBatteryInfoListener)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun destroy() {
        _lifecycle.removeObserver(this)
        listener = null
    }

    // connect if not connected
    fun enable() {
        _enabled = true

        if (_lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
            start()
        }
    }
}

class SomeActivity : AppCompatActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        BatteryInfo(this, lifecycle)
            .apply { setListener { stats: Stats -> Log.d(TAG, stats.toString()) } }

    }
}


问:
replace row values in a single column pandas
I keep getting warning "A value is trying to be set on a copy of a slice from a DataFrame".
How could I fix it? Any  alternative</p>

```<code> //check for NAN
 //capitalise first letter
//assign 'Male' for 'm',
//assign 'Female for 'f'

myDataFrame.to_csv('new_H.csv')
genderList = myDataFrame.loc[:,"Gender"] //extract Gender column

for i in range(0, len(genderList)):

    if type(genderList[i]) == float:   #check for empty spaces
         genderList[i] = 'NAN'
    elif genderList[i].startswith('f'):
          genderList[i] = 'Female'
    elif genderList[i].startswith('m'):
          genderList[i] = 'Male'
</code>```

答:
for row in myDataFrame.itertuples():
    if type(row["Gender"]) == float:
        row["Gender"] = 'NAN'
    elif row["Gender"].startswith('f'):
        row["Gender"] = 'Female'
    elif row["Gender"].startswith('m'):
        row["Gender"] = 'Male'
```

<p>The line <code>genderList = myDataFrame.loc[:,"Gender"]</code> cause warning since you are assigning a piece of your data frame, which could result a copy so update may not be applied to original dataframe. In code above, I used <code>itertuples</code> method which is a more "correct" way to iterate through rows in pandas. If you want to perform an action on a specific row, you do need to create a slice of it first - you just update the value of this column in every row.</p>

<p>From what I see, you goal is to replace values on Gender based on previous values. In that case I recommend to check pandas's <code>replace</code> method which is made for that exact reason together with <code>filter</code>. But, since your filter is quite simple, you can do the following:</p>

<pre class="lang-py prettyprint-override"><code>myDataFrame[myDataFrame["Gender"].str.contains('^f')] = "Female"
</code>```

To update all female. I used slicing of dataframe (myDataFrame[...]) and the condition is myDataFrame["Gender"].str.contains('^f').

Body:
I keep getting warning "A value is trying to be set on a copy of a slice from a DataFrame".
How could I fix it? Any  alternative

 //check for NAN
 //capitalise first letter
//assign 'Male' for 'm',
//assign 'Female for 'f'

myDataFrame.to_csv('new_H.csv')
genderList = myDataFrame.loc[:,"Gender"] //extract Gender column

for i in range(0, len(genderList)):

    if type(genderList[i]) == float:   #check for empty spaces
         genderList[i] = 'NAN'
    elif genderList[i].startswith('f'):
          genderList[i] = 'Female'
    elif genderList[i].startswith('m'):
          genderList[i] = 'Male'

Body:
for row in myDataFrame.itertuples():
    if type(row["Gender"]) == float:
        row["Gender"] = 'NAN'
    elif row["Gender"].startswith('f'):
        row["Gender"] = 'Female'
    elif row["Gender"].startswith('m'):
        row["Gender"] = 'Male'

The line genderList = myDataFrame.loc[:,"Gender"] cause warning since you are assigning a piece of your data frame, which could result a copy so update may not be applied to original dataframe. In code above, I used itertuples method which is a more "correct" way to iterate through rows in pandas. If you want to perform an action on a specific row, you do need to create a slice of it first - you just update the value of this column in every row.

From what I see, you goal is to replace values on Gender based on previous values. In that case I recommend to check pandas's replace method which is made for that exact reason together with filter. But, since your filter is quite simple, you can do the following:

myDataFrame[myDataFrame["Gender"].str.contains('^f')] = "Female"

To update all female. I used slicing of dataframe (myDataFrame[...]) and the condition is myDataFrame["Gender"].str.contains('^f').