问:
React Native: Override Error on Package without Duplicate
I'm trying to use the react-native-camera package but when I added this to my project, I wasn't able to see the camera, instead it was loading and a warning. Then I search on the internet for this warning and saw that I had to link this library manually and so I did. But when I try to build I got this:

Here is my MainApplication.java

```<code>import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.reactnative.camera.RNCameraPackage;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        public boolean canOverrideExistingModule() {
          return true;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          packages.add(new RNCameraPackage());
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
      };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this); // Remove this line if you don't want Flipper enabled
  }

  /**
   * Loads Flipper in React Native templates.
   *
   * @param context
   */
  private static void initializeFlipper(Context context) {
    if (BuildConfig.DEBUG) {
      try {
        /*
         We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
        Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
        aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}
</code>```

Android Manifest

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.app">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>
</code>```

Getting this when trying to access the camera:

```<code>Possible Unhandled Promise Rejection (id: 0):
TypeError: CameraManager.checkVideoAuthorizationStatus is not a function
TypeError: CameraManager.checkVideoAuthorizationStatus is not a function
    at requestPermissions$ (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:129653:61)
    at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25682:19)
    at Generator.invoke [as _invoke] (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25857:24)
    at Generator.prototype.<computed> [as next] (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25725:23)
    at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25682:19)
    at invoke (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25758:22)
    at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25788:13
    at tryCallTwo (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27046:7)
    at doResolve (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27210:15)
    at new Promise (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27069:5)
</code>```

答:
Well, the message sais it pretty clear in my opinion. Rect-Native 0.60+ uses autlinking to link native packages, so you are not require to use react-native link react-native-camera anymore.

Which means you don't need to import and have packages.add(new RNCameraPackage()); in your MainApplication.java

```<code>protected List<ReactPackage> getPackages() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    List<ReactPackage> packages = new PackageList(this).getPackages();
    packages.add(new RNCameraPackage()); // Remove this line and the import statement
    return packages;
}
</code>```

You also need to remove all the other things that were added when running the react-native link command. Reinstall and your app should open now.

LE:

As backup, you can turn off autolinking for specific packages like below. Edit or create react-native.config.js add have the following.

```<code>module.exports = {
    dependencies: {
        'react-native-camera': {
            platforms: {
                android: null, // disable Android platform, other platforms will still autolink if provided
            },
        },
    },
};
</code>```

Body:
I'm trying to use the react-native-camera package but when I added this to my project, I wasn't able to see the camera, instead it was loading and a warning. Then I search on the internet for this warning and saw that I had to link this library manually and so I did. But when I try to build I got this:

Here is my MainApplication.java

import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.reactnative.camera.RNCameraPackage;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        public boolean canOverrideExistingModule() {
          return true;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          packages.add(new RNCameraPackage());
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
      };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this); // Remove this line if you don't want Flipper enabled
  }

  /**
   * Loads Flipper in React Native templates.
   *
   * @param context
   */
  private static void initializeFlipper(Context context) {
    if (BuildConfig.DEBUG) {
      try {
        /*
         We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
        Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
        aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}

Android Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.app">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

Getting this when trying to access the camera:

Possible Unhandled Promise Rejection (id: 0):
TypeError: CameraManager.checkVideoAuthorizationStatus is not a function
TypeError: CameraManager.checkVideoAuthorizationStatus is not a function
    at requestPermissions$ (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:129653:61)
    at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25682:19)
    at Generator.invoke [as _invoke] (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25857:24)
    at Generator.prototype.<computed> [as next] (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25725:23)
    at tryCatch (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25682:19)
    at invoke (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25758:22)
    at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:25788:13
    at tryCallTwo (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27046:7)
    at doResolve (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27210:15)
    at new Promise (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27069:5)

Body:
Well, the message sais it pretty clear in my opinion. Rect-Native 0.60+ uses autlinking to link native packages, so you are not require to use react-native link react-native-camera anymore.

Which means you don't need to import and have packages.add(new RNCameraPackage()); in your MainApplication.java

protected List<ReactPackage> getPackages() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    List<ReactPackage> packages = new PackageList(this).getPackages();
    packages.add(new RNCameraPackage()); // Remove this line and the import statement
    return packages;
}

You also need to remove all the other things that were added when running the react-native link command. Reinstall and your app should open now.

LE:

As backup, you can turn off autolinking for specific packages like below. Edit or create react-native.config.js add have the following.

module.exports = {
    dependencies: {
        'react-native-camera': {
            platforms: {
                android: null, // disable Android platform, other platforms will still autolink if provided
            },
        },
    },
};


来源: stackexchange

问:
Python pandas if row contains string add to table
I have a spreadsheet that looks as follows:

my goal is to print out which "hmi" controls which "az", which is indicated by an "x" in its corresponding column. Example based on the above spreadsheet:

HMI1 controls AZ1

HMI2 controls AZ2

HMI3 controls AZ3

HMI4 controls AZ3

etc..

My idea output that i can work with and sort to an output excel sheet would be(where "X" is the corresponding number):

```<code>HMIX | AZX
</code>```

ive imported the spreadsheet with pd.read_excel and my thought was using the following code to format it, however i think im close but on the wrong path:

```<code>    for index, row in dfConfig.iterrows():
        if row["az1"] != "NaN":
            print(row["hmi_number"])
</code>```

答:
If your looking for something that checks if something is a string try this </p>

```<code>>>> currentColumn = "x"
>>> isinstance(currentColumn, str)
True
>>> isinstance(currentColumn, int)
False
>>>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a spreadsheet that looks as follows:

my goal is to print out which "hmi" controls which "az", which is indicated by an "x" in its corresponding column. Example based on the above spreadsheet:

HMI1 controls AZ1

HMI2 controls AZ2

HMI3 controls AZ3

HMI4 controls AZ3

etc..

My idea output that i can work with and sort to an output excel sheet would be(where "X" is the corresponding number):

HMIX | AZX

ive imported the spreadsheet with pd.read_excel and my thought was using the following code to format it, however i think im close but on the wrong path:

    for index, row in dfConfig.iterrows():
        if row["az1"] != "NaN":
            print(row["hmi_number"])

Body:
If your looking for something that checks if something is a string try this

>>> currentColumn = "x"
>>> isinstance(currentColumn, str)
True
>>> isinstance(currentColumn, int)
False
>>>


问:
Reading the ID from a file and auto increment it by 1
Currently I'm working on this:

I have a windows form with a text file. I use StreamReader with a while loop in order to read the file line by line and then to display it in a listview but then I don't know how to auto-increment the ID in the text box by one so for example if the last id of a person was 1005, the code should automatically add 1 so i'll get 1006

```<code>using (StreamReader sr = new StreamReader("INCIDENT.txt"))
{
    int iCount = 0;

    while (sr.Peek() != -1)
    {
        ListViewItem lvRead = new ListViewItem();
        lvRead.Text = sr.ReadLine();
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lstViewData.Items.Add(lvRead);

        iCount++;
    }
}
</code>```

Image

答:
Let's say you have a button and it's name SaveData and you saved nom.1 in your TextFile</p>
```<code>private void btnSaveData_Click(object sender, EventArgs e)
{
     StreamReader sr =  new
     StreamReader("INCIDENT.txt");
     int num = sr.Peek();
     sr.Close();
     // here will assign last value in num
     txtID.Text = ( num + 1 ).ToString();
     // here add 1 to num and display result in textBox and you should save last value to use it later
     StreamWriter sw = new StreamWriter("INCIDENT.txt");
     sw.Write( ( num + 1 ).ToString() );
     // here save last value you get to increment this value when you read TextFile again
     sw.Fush();
     sw.Close();
}
</code>```

Body:
Currently I'm working on this:

I have a windows form with a text file. I use StreamReader with a while loop in order to read the file line by line and then to display it in a listview but then I don't know how to auto-increment the ID in the text box by one so for example if the last id of a person was 1005, the code should automatically add 1 so i'll get 1006

using (StreamReader sr = new StreamReader("INCIDENT.txt"))
{
    int iCount = 0;

    while (sr.Peek() != -1)
    {
        ListViewItem lvRead = new ListViewItem();
        lvRead.Text = sr.ReadLine();
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lvRead.SubItems.Add(sr.ReadLine());
        lstViewData.Items.Add(lvRead);

        iCount++;
    }
}

Image

Body:
Let's say you have a button and it's name SaveData and you saved nom.1 in your TextFile

private void btnSaveData_Click(object sender, EventArgs e)
{
     StreamReader sr =  new
     StreamReader("INCIDENT.txt");
     int num = sr.Peek();
     sr.Close();
     // here will assign last value in num
     txtID.Text = ( num + 1 ).ToString();
     // here add 1 to num and display result in textBox and you should save last value to use it later
     StreamWriter sw = new StreamWriter("INCIDENT.txt");
     sw.Write( ( num + 1 ).ToString() );
     // here save last value you get to increment this value when you read TextFile again
     sw.Fush();
     sw.Close();
}


问:
Insert removed element in generic list
I want to remove remove element from the end of ArrayList and set it in the position i. I don't care about order of the elements but i want this operation to be O(1).

My code:

```<code>    private void removeElement(int i, List<? extends MyClass> objects) {
        if (i >= objects.size() - 1) {
            objects.remove(objects.size() - 1);
        } else {
            objects.set(i, objects.remove(objects.size() - 1));
        }
    }
</code>```

By doing this i'm removing object at i index from my ArrayList in O(1) time complexity.

My problem is that Java won't let me set removed element in i position. I'm getting:

Wrong 2nd argument type. Found '? extends MyClass', required '? extends MyClass'.

I know about "producer extends consumer super" rule. I understand that ? extends MyClass object could be different from exact ? extends MyClass List generic type. But shouldn't it be allowed to insert back element retrieved from the same list?

答:
Get rid of the wildcard; and I don't even think you need a bound:</p>

```<code>private void <T> removeElement(int i, List<T> objects) {
</code>```

Title: Insert removed element in generic list

Body:
I want to remove remove element from the end of ArrayList and set it in the position i. I don't care about order of the elements but i want this operation to be O(1).

My code:

    private void removeElement(int i, List<? extends MyClass> objects) {
        if (i >= objects.size() - 1) {
            objects.remove(objects.size() - 1);
        } else {
            objects.set(i, objects.remove(objects.size() - 1));
        }
    }

By doing this i'm removing object at i index from my ArrayList in O(1) time complexity.

My problem is that Java won't let me set removed element in i position. I'm getting:

Wrong 2nd argument type. Found '? extends MyClass', required '? extends MyClass'.

I know about "producer extends consumer super" rule. I understand that ? extends MyClass object could be different from exact ? extends MyClass List generic type. But shouldn't it be allowed to insert back element retrieved from the same list?

Body:
Get rid of the wildcard; and I don't even think you need a bound:

private void <T> removeElement(int i, List<T> objects) {


问:
Input shape for 1D convolution network in keras
I am quite new to keras and I have a problem in understanding shapes.

I wanted to create 1D Conv Keras model as follows, I don't know this is correct or not:

```<code>TIME_PERIODS = 511
num_sensors = 2
num_classes = 4
BATCH_SIZE = 400
EPOCHS = 50
model_m = Sequential()
model_m.add(Conv1D(100, 10, activation='relu', input_shape=(TIME_PERIODS, num_sensors)))
model_m.add(Conv1D(100, 10, activation='relu'))
model_m.add(MaxPooling1D(3))
model_m.add(Conv1D(160, 10, activation='relu'))
model_m.add(Conv1D(160, 10, activation='relu'))
model_m.add(GlobalAveragePooling1D())
model_m.add(Dropout(0.5))
model_m.add(Dense(num_classes, activation='softmax'))
</code>```

The input data I have is 888 different panda data frame where each frame is of shape (511, 3) where 511 is numbers of signal points and 0th column is sensor1 values, 1st column is sensor2 values and 2nd column is labelled signals.

Now how I should combine all my 888 different panda data frame so I have x_train and y_train from X and Y using  Sklearn train_test_split.

Also, I think the input shape I am defining for the model is wrong and I don't think I actually have TIME_PERIODS because, for 1-time point, I have 2 sensor inputs (orange, blue line) value and 1 output label (green line).

The context of the problem I am trying to solve e.g.
 input: time-based 2 sensors values say for 1 AM-2 AM hour from a user, output: the range of times e.g where the user was doing activity 1, activity 2, activity X on 1:10-1:15, 1:15-1:30, 1:30-2:00, The above plot show a sample training input and output.

The problem is inspired from here but in my case, I don't have any time period, my 1-time point has 1 output label.

Update 1:
I am almost certain that my TIME_PERIODS=1 as for the prediction I will give 511 inputs and expects to get 511 output values.

答:
Each dataframe is an independent sequence?

```<code> fileNames = get a list of filenames here, you can maybe os.listdir for that
 allFrames = [pandas.read_csv(filename,... other_things...).values for filename in fileNames]

 allData = np.stack(allFrames, axis=0)
 inputData = allData[:,:num_sensors]
 outputData = allData[:, -1:]
</code>```

You can now use train test split the way you want.
Your input shape is correct.

If you want to predict the whole sequence, then you have to remove the poolings. Every convolution should use padding='same'.

And maybe you should use a Biridectional(LSTM(units, return_sequences=True)) layer somewhere to make your model stronger.

A simple model as an example. (Notice that models are totally open to creativity)

```<code>from keras.layers import *

inputs = Input((TIME_PERIODS,num_sensors)) #Should be called "time_steps" to be precise
outputs = Conv1D(any, 3, padding='same', activation = 'tanh')(inputs)
outputs = Bidirectional(LSTM(any, return_sequences=True))(outputs)
outputs = Conv1D(num_classes, activation='softmax', padding='same')(outputs)

model = keras.models.Model(inputs, outputs)
</code>```

Body:
I am quite new to keras and I have a problem in understanding shapes.

I wanted to create 1D Conv Keras model as follows, I don't know this is correct or not:

TIME_PERIODS = 511
num_sensors = 2
num_classes = 4
BATCH_SIZE = 400
EPOCHS = 50
model_m = Sequential()
model_m.add(Conv1D(100, 10, activation='relu', input_shape=(TIME_PERIODS, num_sensors)))
model_m.add(Conv1D(100, 10, activation='relu'))
model_m.add(MaxPooling1D(3))
model_m.add(Conv1D(160, 10, activation='relu'))
model_m.add(Conv1D(160, 10, activation='relu'))
model_m.add(GlobalAveragePooling1D())
model_m.add(Dropout(0.5))
model_m.add(Dense(num_classes, activation='softmax'))

The input data I have is 888 different panda data frame where each frame is of shape (511, 3) where 511 is numbers of signal points and 0th column is sensor1 values, 1st column is sensor2 values and 2nd column is labelled signals.

Now how I should combine all my 888 different panda data frame so I have x_train and y_train from X and Y using  Sklearn train_test_split.

Also, I think the input shape I am defining for the model is wrong and I don't think I actually have TIME_PERIODS because, for 1-time point, I have 2 sensor inputs (orange, blue line) value and 1 output label (green line).

The context of the problem I am trying to solve e.g.
 input: time-based 2 sensors values say for 1 AM-2 AM hour from a user, output: the range of times e.g where the user was doing activity 1, activity 2, activity X on 1:10-1:15, 1:15-1:30, 1:30-2:00, The above plot show a sample training input and output.

The problem is inspired from here but in my case, I don't have any time period, my 1-time point has 1 output label.

Update 1:
I am almost certain that my TIME_PERIODS=1 as for the prediction I will give 511 inputs and expects to get 511 output values.

Body:
Each dataframe is an independent sequence?

 fileNames = get a list of filenames here, you can maybe os.listdir for that
 allFrames = [pandas.read_csv(filename,... other_things...).values for filename in fileNames]

 allData = np.stack(allFrames, axis=0)
 inputData = allData[:,:num_sensors]
 outputData = allData[:, -1:]

You can now use train test split the way you want.
Your input shape is correct.

If you want to predict the whole sequence, then you have to remove the poolings. Every convolution should use padding='same'.

And maybe you should use a Biridectional(LSTM(units, return_sequences=True)) layer somewhere to make your model stronger.

A simple model as an example. (Notice that models are totally open to creativity)

from keras.layers import *

inputs = Input((TIME_PERIODS,num_sensors)) #Should be called "time_steps" to be precise
outputs = Conv1D(any, 3, padding='same', activation = 'tanh')(inputs)
outputs = Bidirectional(LSTM(any, return_sequences=True))(outputs)
outputs = Conv1D(num_classes, activation='softmax', padding='same')(outputs)

model = keras.models.Model(inputs, outputs)


问:
why Jena fuseki has no response to owl reasoning?
I want to use Jena Fuseki to construct a SPARQL endpoint for some ontology file.
and my fuseki config as follow:

```<code>@prefix fuseki:  <http://jena.apache.org/fuseki#> .
@prefix rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:    <http://www.w3.org/2000/01/rdf-schema#> .
@prefix tdb:     <http://jena.hpl.hp.com/2008/tdb#> .
@prefix ja:      <http://jena.hpl.hp.com/2005/11/Assembler#> .

<#service1> rdf:type fuseki:Service ;
    fuseki:name                       "ds" ;       # http://host:port/ds
    fuseki:serviceQuery               "sparql" ;   # SPARQL query service
    fuseki:serviceQuery               "query" ;    # SPARQL query service (alt name)
    fuseki:serviceUpdate              "update" ;   # SPARQL update service
    fuseki:serviceUpload              "upload" ;   # Non-SPARQL upload service
    fuseki:serviceReadWriteGraphStore "data" ;     # SPARQL Graph store protocol (read and write)
    # A separate read-only graph store endpoint:
    fuseki:serviceReadGraphStore      "get" ;      # SPARQL Graph store protocol (read only)
    fuseki:dataset                   <#dataset> ;
    .

<#dataset> rdf:type ja:RDFDataset ;
    ja:defaultGraph <#inf_model> ;
    .

<#mv_data_model> a ja:MemoryModel;
    ja:content[ja:externalContent <file://D:/Program%20Files/d2rq-0.8.1/movie.nt>] ;
    ja:content[ja:externalContent <file://D:/Program%20Files/apache-jena-fuseki-3.13.1/run/ontology.ttl>]
    .

<#inf_model> a ja:InfModel ;
    ja:baseModel <#mv_data_model>;
    ja:reasoner [ja:reasonerURL <http://jena.hpl.hp.com/2003/OWLFBRuleReasoner>] ;

    #ja:reasoner [
    #    ja:reasonerURL <http://jena.hpl.hp.com/2003/GenericRuleReasoner> ;
    #    ja:rulesFrom <file://D:/Program%20Files/apache-jena-fuseki-3.13.1/run/rule.ttl>; ]
    .

</code>```

I run fuseki as a Standalone Server.when I close the OWL reasoner it works well.But once the OWL reasoner is enabled,the server has no response for the query,even the query like

```<code>SELECT ?s ?p ?o
WHERE {
    ?s ?p ?o
}
limit 10
</code>```

has no response, and then throw a Exception: java.lang.OutOfMemoryError. However,the RuleReasoner works well.
And my ttl file has about 1500000 triples, is the data scale is too large for the OWL Reasoner to have a inference?
All work is done on my pc,can any friend offer me a help? Thanks

答:
In fuseki, when running a Reasoner over a too big DataSet, the inferences will be applied to All Graph in query execution time. Besides that, all inferences will be materialized in Fuseki TDB case reasoner applies forward reasoning. It will burden the system, cause the graph will be to big to materialize and reason using RAM memory.

We have alredy crashed a machine dedicating 1 TD RAM to Fuseki.

A possible solution is to split your dataset into independent parts for tunning the queries.
For more information, look at hadoop and AllegroGraph solution for high-perfomance with Clusters
https://allegrograph.com/hadoop-and-allegrograph-the-semantic-data-lake-for-analytics/

It depends on your demand. In an unlimited scale, cluster solution seems to be the best, but maybe locally increasing the dedicated RAM memory to JVM solve your problem.

Body:
I want to use Jena Fuseki to construct a SPARQL endpoint for some ontology file.
and my fuseki config as follow:

@prefix fuseki:  <http://jena.apache.org/fuseki#> .
@prefix rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:    <http://www.w3.org/2000/01/rdf-schema#> .
@prefix tdb:     <http://jena.hpl.hp.com/2008/tdb#> .
@prefix ja:      <http://jena.hpl.hp.com/2005/11/Assembler#> .

<#service1> rdf:type fuseki:Service ;
    fuseki:name                       "ds" ;       # http://host:port/ds
    fuseki:serviceQuery               "sparql" ;   # SPARQL query service
    fuseki:serviceQuery               "query" ;    # SPARQL query service (alt name)
    fuseki:serviceUpdate              "update" ;   # SPARQL update service
    fuseki:serviceUpload              "upload" ;   # Non-SPARQL upload service
    fuseki:serviceReadWriteGraphStore "data" ;     # SPARQL Graph store protocol (read and write)
    # A separate read-only graph store endpoint:
    fuseki:serviceReadGraphStore      "get" ;      # SPARQL Graph store protocol (read only)
    fuseki:dataset                   <#dataset> ;
    .

<#dataset> rdf:type ja:RDFDataset ;
    ja:defaultGraph <#inf_model> ;
    .

<#mv_data_model> a ja:MemoryModel;
    ja:content[ja:externalContent <file://D:/Program%20Files/d2rq-0.8.1/movie.nt>] ;
    ja:content[ja:externalContent <file://D:/Program%20Files/apache-jena-fuseki-3.13.1/run/ontology.ttl>]
    .

<#inf_model> a ja:InfModel ;
    ja:baseModel <#mv_data_model>;
    ja:reasoner [ja:reasonerURL <http://jena.hpl.hp.com/2003/OWLFBRuleReasoner>] ;

    #ja:reasoner [
    #    ja:reasonerURL <http://jena.hpl.hp.com/2003/GenericRuleReasoner> ;
    #    ja:rulesFrom <file://D:/Program%20Files/apache-jena-fuseki-3.13.1/run/rule.ttl>; ]
    .

I run fuseki as a Standalone Server.when I close the OWL reasoner it works well.But once the OWL reasoner is enabled,the server has no response for the query,even the query like

SELECT ?s ?p ?o
WHERE {
    ?s ?p ?o
}
limit 10

has no response, and then throw a Exception: java.lang.OutOfMemoryError. However,the RuleReasoner works well.
And my ttl file has about 1500000 triples, is the data scale is too large for the OWL Reasoner to have a inference?
All work is done on my pc,can any friend offer me a help? Thanks


问:
JDBC Driver connection not working in NetBeans IDE
I have created a login screen but each time I test it, I get the following error message: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I know my database connection coding is correct because I have used it before and no errors are displayed. I tried adding the database driver through this Stack Overflow How to connect NetBeans to MySQL database? but the problem persists and I have also ensured the database was connected in the driver.

How do I get the driver to work?

答:
Use Connection Properties button and add a property with field name serverTimezone and value UTC.

This should work if error was caused by timezone issue.

It worked for me on Netbeans 11.2 with jdbc driver jar 8.0.17

ContentLicense: CC BY-SA 3.0


问:
Reserving Disk Space on iPhone
I want to be able to 'reserve' a set amount of disk space on my iPhone for my particular application. Before I get flamed I should add this is NOT for a public application.

I assume the simplest way to do this is to actually create blocks of files up to the space I wish to reserve and then delete and use these blocks as necessary.

Is there any filesystem operation which might allow me to do this without actually having to write content for all the space I want to allocate? I'm asking this because I'm not sure lazy the disk space allocator might be.

答: No, this is something well outside the SDK. You'll have to create your own methods to handle this for you.</p>

OwnerDisplayName: Akusete

ContentLicense: CC BY-SA 2.5

Title: Reserving Disk Space on iPhone

OwnerDisplayName: August


问:
boost filesystem version 3 issue?
the example code on the boost website is not working. http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/tutorial.html#Using-path-decomposition

```<code>int main(int argc, char* argv[])
{
  path p (argv[1]);   // p reads clearer than argv[1] in the following code

  try
  {
    if (exists(p))    // does p actually exist?
    {
      if (is_regular_file(p))        // is p a regular file?
        cout << p << " size is " << file_size(p) << '\n';

      else if (is_directory(p))      // is p a directory?
      {
        cout << p << " is a directory containing:\n";

        typedef vector<path> vec;             // store paths,
        vec v;                                // so we can sort them later

        copy(directory_iterator(p), directory_iterator(), back_inserter(v));

        sort(v.begin(), v.end());             // sort, since directory iteration
                                          // is not ordered on some file systems

        for (vec::const_iterator it (v.begin()); it != v.end(); ++it)
        {
          path fn = it->path().filename();   // extract the filename from the path
          v.push_back(fn);                   // push into vector for later sorting
        }
      }

      else
        cout << p << " exists, but is neither a regular file nor a directory\n";
    }
    else
      cout << p << " does not exist\n";
  }

  catch (const filesystem_error& ex)
  {
    cout << ex.what() << '\n';
  }

  return 0;
}
</code>```

two error messages when compiled in visual studio 2010 for the line path fn = it->path().filename();

The first error is: 'function-style cast' : illegal as right side of '->' operator and the second error is: left of '.filename' must have class/struct/union

Also, when I mouse over path() it says: class boost::filesystem3::path Error: typename not allowed

答:
This section (for's body) is problematic:

```<code>  path fn = it->path().filename();   // extract the filename from the path
  v.push_back(fn);                   // push into vector for later sorting
</code>```

it points to path objects, so I don't see why path() is called. Seems that it should be replaced with it->filename()

you push filenames at the end of the same vector, so after the loop you will have the vector containing the list of files twice, first with pathnames then just filenames.

EDIT: Looking at the original example I see that these are your modification. If you want to store filenames instead of printing them, define another vector  of string or path and store filenames in it, don't reuse the first one.  And removing the call to path() should solve the compilation problem.

EDIT 2: as a cute BTW, you can achieve both directory traversal and filename extraction in one pass using std::transform instead of std::copy:

```<code>struct fnameExtractor {  // functor
  string operator() (path& p) { return p.filename().string(); }
};

vector<string> vs;
vector<path> vp;
transform(directory_iterator(p), directory_iterator(), back_inserter(vs),
          fnameExtractor());
</code>```

Same using mem_fun_ref instead of fnameExtractor functor:

```<code>transform(directory_iterator(p), directory_iterator(), back_inserter(vp),
          mem_fun_ref(&path::filename));
</code>```

Title: boost filesystem version 3 issue?

Body:
the example code on the boost website is not working. http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/tutorial.html#Using-path-decomposition

int main(int argc, char* argv[])
{
  path p (argv[1]);   // p reads clearer than argv[1] in the following code

  try
  {
    if (exists(p))    // does p actually exist?
    {
      if (is_regular_file(p))        // is p a regular file?
        cout << p << " size is " << file_size(p) << '\n';

      else if (is_directory(p))      // is p a directory?
      {
        cout << p << " is a directory containing:\n";

        typedef vector<path> vec;             // store paths,
        vec v;                                // so we can sort them later

        copy(directory_iterator(p), directory_iterator(), back_inserter(v));

        sort(v.begin(), v.end());             // sort, since directory iteration
                                          // is not ordered on some file systems

        for (vec::const_iterator it (v.begin()); it != v.end(); ++it)
        {
          path fn = it->path().filename();   // extract the filename from the path
          v.push_back(fn);                   // push into vector for later sorting
        }
      }

      else
        cout << p << " exists, but is neither a regular file nor a directory\n";
    }
    else
      cout << p << " does not exist\n";
  }

  catch (const filesystem_error& ex)
  {
    cout << ex.what() << '\n';
  }

  return 0;
}

two error messages when compiled in visual studio 2010 for the line path fn = it->path().filename();

The first error is: 'function-style cast' : illegal as right side of '->' operator and the second error is: left of '.filename' must have class/struct/union

Also, when I mouse over path() it says: class boost::filesystem3::path Error: typename not allowed

Body:
This section (for's body) is problematic:

  path fn = it->path().filename();   // extract the filename from the path
  v.push_back(fn);                   // push into vector for later sorting

it points to path objects, so I don't see why path() is called. Seems that it should be replaced with it->filename()

you push filenames at the end of the same vector, so after the loop you will have the vector containing the list of files twice, first with pathnames then just filenames.

EDIT: Looking at the original example I see that these are your modification. If you want to store filenames instead of printing them, define another vector  of string or path and store filenames in it, don't reuse the first one.  And removing the call to path() should solve the compilation problem.

EDIT 2: as a cute BTW, you can achieve both directory traversal and filename extraction in one pass using std::transform instead of std::copy:

struct fnameExtractor {  // functor
  string operator() (path& p) { return p.filename().string(); }
};

vector<string> vs;
vector<path> vp;
transform(directory_iterator(p), directory_iterator(), back_inserter(vs),
          fnameExtractor());

Same using mem_fun_ref instead of fnameExtractor functor:

transform(directory_iterator(p), directory_iterator(), back_inserter(vp),
          mem_fun_ref(&path::filename));


问:
aws elasticsearch getting signature error on post request
Got a 403 signature error , when using the below fetch function:

```<code>    function elasticsearchFetch(AWS, elasticsearchDomain, endpointPath, options = {}, region = process.env.AWS_REGION) {
  return new Promise((resolve, reject) => {
    const { body, method = 'GET' } = options;
    const endpoint = new AWS.Endpoint(elasticsearchDomain);
    const request = new AWS.HttpRequest(endpoint, region);
    request.method = method;
    request.path += endpointPath;
    request.headers.host = elasticsearchDomain;
    if (body) {
      request.body = body;
      request.headers['Content-Type'] = 'application/json';
      request.headers['Content-Length'] = request.body.length;
    }
    const credentials = new AWS.EnvironmentCredentials('AWS');
    const signer = new AWS.Signers.V4(request, 'es');
    signer.addAuthorization(credentials, new Date());
    const client = new AWS.HttpClient();
    client.handleRequest(request, null, (res) => {
      let chunks = '';
      res.on('data', (chunk) => {
        chunks += chunk;
      });
      res.on('end', () => {
        if (res.statusCode !== 201) console.log('Got these options STATUSCODE', JSON.stringify(options, false, 2));
        return resolve({ statusCode: res.statusCode, body: chunks });
      });
    }, (error) => {
      console.log('Got these options ERROR', JSON.stringify(options, false, 2));
      return reject(error);
    });
  });
}
</code>```

This is the options used for the request in above function :

```<code>{
    "method": "POST",
    "body": "{\"prefix\":\"image_233/ArtService/articles-0/GB/ART-60297885/\",\"id\":\"ART-60297885\",\"retailUnit\":\"GB\",\"commercial\":{\"name\":{\"en-GB\":\"FÖRBÄTTRA\"}},\"schemaType\":\"product\",\"productType\":\"ART\"}"
}
</code>```

and got this error :

```<code>{
    "statusCode": 403,
    "body": "{\"message\":\"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\"}"
}
</code>```

This is the endpoint : 233/_doc/

答:
I believe your Content-Length header is incorrect, causing the signature mismatch.

Your payload includes the string FÖRBÄTTRA, which has two double-byte characters.

You're setting the Content-Length to request.body.length, which comes to 186.

While this is the number of characters in the body, it is not the number of bytes in the body (188).

To calculate the Content-Length, use Buffer.byteLength(request.body).  For a POST request like this, you can even remove that line of code altogether, and the request will succeed.

```<code>  // Content-Length is only needed for DELETE requests that include a request
  // body, but including it for all requests doesn't seem to hurt anything.
  request.headers['Content-Length'] = Buffer.byteLength(request.body);
</code>```

Source: https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-request-signing.html#es-request-signing-node

Body:
Got a 403 signature error , when using the below fetch function:

    function elasticsearchFetch(AWS, elasticsearchDomain, endpointPath, options = {}, region = process.env.AWS_REGION) {
  return new Promise((resolve, reject) => {
    const { body, method = 'GET' } = options;
    const endpoint = new AWS.Endpoint(elasticsearchDomain);
    const request = new AWS.HttpRequest(endpoint, region);
    request.method = method;
    request.path += endpointPath;
    request.headers.host = elasticsearchDomain;
    if (body) {
      request.body = body;
      request.headers['Content-Type'] = 'application/json';
      request.headers['Content-Length'] = request.body.length;
    }
    const credentials = new AWS.EnvironmentCredentials('AWS');
    const signer = new AWS.Signers.V4(request, 'es');
    signer.addAuthorization(credentials, new Date());
    const client = new AWS.HttpClient();
    client.handleRequest(request, null, (res) => {
      let chunks = '';
      res.on('data', (chunk) => {
        chunks += chunk;
      });
      res.on('end', () => {
        if (res.statusCode !== 201) console.log('Got these options STATUSCODE', JSON.stringify(options, false, 2));
        return resolve({ statusCode: res.statusCode, body: chunks });
      });
    }, (error) => {
      console.log('Got these options ERROR', JSON.stringify(options, false, 2));
      return reject(error);
    });
  });
}

This is the options used for the request in above function :

{
    "method": "POST",
    "body": "{\"prefix\":\"image_233/ArtService/articles-0/GB/ART-60297885/\",\"id\":\"ART-60297885\",\"retailUnit\":\"GB\",\"commercial\":{\"name\":{\"en-GB\":\"FÖRBÄTTRA\"}},\"schemaType\":\"product\",\"productType\":\"ART\"}"
}

and got this error :

{
    "statusCode": 403,
    "body": "{\"message\":\"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.\"}"
}

This is the endpoint : 233/_doc/

Body:
I believe your Content-Length header is incorrect, causing the signature mismatch.

Your payload includes the string FÖRBÄTTRA, which has two double-byte characters.

You're setting the Content-Length to request.body.length, which comes to 186.

While this is the number of characters in the body, it is not the number of bytes in the body (188).

To calculate the Content-Length, use Buffer.byteLength(request.body).  For a POST request like this, you can even remove that line of code altogether, and the request will succeed.

  // Content-Length is only needed for DELETE requests that include a request
  // body, but including it for all requests doesn't seem to hurt anything.
  request.headers['Content-Length'] = Buffer.byteLength(request.body);

Source: https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-request-signing.html#es-request-signing-node


问:
Summarising a data frame in R by 2 elements
I have a large dataset that includes information for multiple sequences, detailing their sequence ID, country of origin, clade, host and many other things. Each country has multiple different sequences and some countries contain sequences from multiple different clades. Is there a way to know the number of different clades for each different country, without having to test each country one by one (there are too many to realistically enter by hand)?</p>

答:
Without example data, I will rephrase your question as:

I have a large dataset that includes information for multiple starwars
  characters, detailing their eye color, homeworld, name, and many other
  things. Each homeworld has multiple different eye colors. Is there a
  way to know the number of different eye colors for each different
  homeworld, without having to test each homeworld one by one (there are
  too many to realistically enter by hand)?

Here, we can count how many times different combinations of homeworld and eye color exist in the data. For instance, we have three brown eyed characters from Alderaan.

```<code>library(dplyr)
starwars %>% count(homeworld, eye_color)
# A tibble: 66 x 3
   homeworld      eye_color     n
   <chr>          <chr>     <int>
 1 Alderaan       brown         3
 2 Aleen Minor    unknown       1
 3 Bespin         blue          1
 4 Bestine IV     blue          1
 5 Cato Neimoidia red           1
 6 Cerea          yellow        1
 7 Champala       blue          1
 8 Chandrila      blue          1
 9 Concord Dawn   brown         1
10 Corellia       brown         1
# … with 56 more rows
</code>```

We could add another step to count how many eye colors appear on each homeworld, by counting the number of rows for each homeworld from the step before. This tells us there is only one eye color found on Alderaan (brown).

```<code>starwars %>% count(homeworld, eye_color) %>% count(homeworld)
# A tibble: 49 x 2
   homeworld          n
   <chr>          <int>
 1 Alderaan           1
 2 Aleen Minor        1
 3 Bespin             1
 4 Bestine IV         1
 5 Cato Neimoidia     1
 6 Cerea              1
 7 Champala           1
 8 Chandrila          1
 9 Concord Dawn       1
10 Corellia           2
</code>```

Body:
Without example data, I will rephrase your question as:

I have a large dataset that includes information for multiple starwars
  characters, detailing their eye color, homeworld, name, and many other
  things. Each homeworld has multiple different eye colors. Is there a
  way to know the number of different eye colors for each different
  homeworld, without having to test each homeworld one by one (there are
  too many to realistically enter by hand)?

Here, we can count how many times different combinations of homeworld and eye color exist in the data. For instance, we have three brown eyed characters from Alderaan.

library(dplyr)
starwars %>% count(homeworld, eye_color)
# A tibble: 66 x 3
   homeworld      eye_color     n
   <chr>          <chr>     <int>
 1 Alderaan       brown         3
 2 Aleen Minor    unknown       1
 3 Bespin         blue          1
 4 Bestine IV     blue          1
 5 Cato Neimoidia red           1
 6 Cerea          yellow        1
 7 Champala       blue          1
 8 Chandrila      blue          1
 9 Concord Dawn   brown         1
10 Corellia       brown         1
# … with 56 more rows

We could add another step to count how many eye colors appear on each homeworld, by counting the number of rows for each homeworld from the step before. This tells us there is only one eye color found on Alderaan (brown).

starwars %>% count(homeworld, eye_color) %>% count(homeworld)
# A tibble: 49 x 2
   homeworld          n
   <chr>          <int>
 1 Alderaan           1
 2 Aleen Minor        1
 3 Bespin             1
 4 Bestine IV         1
 5 Cato Neimoidia     1
 6 Cerea              1
 7 Champala           1
 8 Chandrila          1
 9 Concord Dawn       1
10 Corellia           2


问:
SQLAlchemy and mssql : how to create unique constraint with multiple null value
I am working with SQLAlchemy and MS SQL server and I would like to create a unique constraint that allows multiple NULL value.

I know that MS SQL server  does not ignore the null value and considers it as violation for the UNIQUE KEY.
I also know how to fix it with SQL code (see here)

But is there a way to do the same thing with SQLAlchemy directly ?

Here is my code :

```<code>class Referential(db.Model):
     __tablename__ = "REFERENTIAL"
     id = db.Column("ID", Integer, primary_key=True, autoincrement=True)
     name = db.Column("NAME", String(100), index=True, unique=True, nullable=False)
     internal_code = db.Column("INTERNAL_CODE", String(50), unique=True, index=True)
</code>```

Thanks in advance

答:
MSSQL's implementation when it comes to allowing nulls in a unique column is a little odd.

import sqlalchemy as sa

sa.Table(
    sa.Column('column', sa.String(50), nullable=True),
    sa.Index('uq_column_allows_nulls', mssql_where=sa.text('column IS NOT NULL'),
)
```

<p>If you are planning on using alembic like I was this is the code:</p>

<pre class="lang-py prettyprint-override"><code>import sqlalchemy as sa
import alembic as op

op.create_index(
    name='uq_column_name',
    table_name='table',
    columns=['column'],
    mssql_where=sa.text('column IS NOT NULL'),
)
</code>```

This uses the sql expression text for sqlalchemy and create_index's dialect_expression key word arguments mssql_where=

Body:
I am working with SQLAlchemy and MS SQL server and I would like to create a unique constraint that allows multiple NULL value.

I know that MS SQL server  does not ignore the null value and considers it as violation for the UNIQUE KEY.
I also know how to fix it with SQL code (see here)

But is there a way to do the same thing with SQLAlchemy directly ?

Here is my code :

class Referential(db.Model):
     __tablename__ = "REFERENTIAL"
     id = db.Column("ID", Integer, primary_key=True, autoincrement=True)
     name = db.Column("NAME", String(100), index=True, unique=True, nullable=False)
     internal_code = db.Column("INTERNAL_CODE", String(50), unique=True, index=True)

Thanks in advance

Body:
MSSQL's implementation when it comes to allowing nulls in a unique column is a little odd.

import sqlalchemy as sa

sa.Table(
    sa.Column('column', sa.String(50), nullable=True),
    sa.Index('uq_column_allows_nulls', mssql_where=sa.text('column IS NOT NULL'),
)

If you are planning on using alembic like I was this is the code:

import sqlalchemy as sa
import alembic as op

op.create_index(
    name='uq_column_name',
    table_name='table',
    columns=['column'],
    mssql_where=sa.text('column IS NOT NULL'),
)

This uses the sql expression text for sqlalchemy and create_index's dialect_expression key word arguments mssql_where=


问:
Can't seem to get Boto's dynamodb.update_item to work
I'm trying to use this Boto function,
But can't seem to get it right..
Any idea?
Doc Link

```<code>    tablename = 'name_table'
    response = dynamodb.update_item(
        TableName=tablename,
        Key={
            'name': 'Tony',
        },
        UpdateExpression="set name= :r",
        ExpressionAttributeValues={
            ':r': 'Ralph',
        },
        ReturnValues="UPDATED_NEW"
    )
</code>```

This are the errors I get :

```<code>Invalid type for parameter Key.name, value: set(['Tony', 0]), type: <type 'set'>, valid types: <type 'dict'>
</code>```

I've tried to change the name from str to dict,
So now I'm with this error

```<code>ValueError: dictionary update sequence element #0 has length 1; 2 is required
</code>```

Where to go from here ?
Many thanks..

答:
The key cannot be a dictionary.</p>

```<code>     tablename = 'name_table'
     response = dynamodb.update_item(
        TableName=tablename,
        Key="name = :name",
        UpdateExpression="set name= :r",
        ExpressionAttributeValues={
            ':r': 'Ralph',
            ':name': 'Tony'
        },
        ReturnValues="UPDATED_NEW"
    )
</code>```

Body:
I'm trying to use this Boto function,
But can't seem to get it right..
Any idea?
Doc Link

    tablename = 'name_table'
    response = dynamodb.update_item(
        TableName=tablename,
        Key={
            'name': 'Tony',
        },
        UpdateExpression="set name= :r",
        ExpressionAttributeValues={
            ':r': 'Ralph',
        },
        ReturnValues="UPDATED_NEW"
    )

This are the errors I get :

Invalid type for parameter Key.name, value: set(['Tony', 0]), type: <type 'set'>, valid types: <type 'dict'>

I've tried to change the name from str to dict,
So now I'm with this error

ValueError: dictionary update sequence element #0 has length 1; 2 is required

Where to go from here ?
Many thanks..

Body:
The key cannot be a dictionary.

     tablename = 'name_table'
     response = dynamodb.update_item(
        TableName=tablename,
        Key="name = :name",
        UpdateExpression="set name= :r",
        ExpressionAttributeValues={
            ':r': 'Ralph',
            ':name': 'Tony'
        },
        ReturnValues="UPDATED_NEW"
    )


问:
Collecting all state from mapped components and store state
I have a initial component which maps a second component with information on questions. What I would like to do is to collect the answers of all these questions and save them in the same place(state, array, object I honestly don't mind how).

However as I am updating the state from a mapped component it is only displaying each individual updated state when console logging these results.

How or where can I store the questions answers from this mapped component so that I can use all the answers later to store elsewhere?

This is the mapped component I referred to (it's a bit convoluted due to all the conditional rendering I have going on).

```<code>
class Questions extends React.Component {
  constructor(props) {
    super(props);
    console.log(props);
    this.state = {
      ...props,
      QuestionAnswer: "",
      QuestionAccepted: false,
      problem: false,

      problemDefinition: "",
      completedQuestions: [],
      soloutionForDeclinedQuestion: ""
    };

    this.QuestionDecline = this.QuestionDecline.bind(this);
    this.QuestionOnChange = this.QuestionOnChange.bind(this);
    this.OnCommit = this.OnCommit.bind(this);
    this.RevertDeclinedAnswer = this.RevertDeclinedAnswer.bind(this);
    this.RevertAcceptedAnswer = this.RevertAcceptedAnswer.bind(this);
    this.AdmitProblem = this.AdmitProblem.bind(this);
    this.AdmitNotProblem = this.AdmitNotProblem.bind(this);
    this.QuestionProblem = this.QuestionProblem.bind(this);
    this.SubmitProblemSoloution = this.SubmitProblemSoloution.bind(this);
    this.submitDeclinedQuestionSoloution = this.submitDeclinedQuestionSoloution.bind(
      this
    );

    this.AcceptAnswer = this.AcceptAnswer.bind(this);
  }
  submitDeclinedQuestionSoloution(e) {
    e.preventDefault();
    let answer = this.state.soloutionForDeclinedQuestion;
    let question = this.state.questions.Question;
    let state = "Declined With solution";

    let newItem = {
      answer: answer,
      question: question,
      state: state
    };
    this.state.completedQuestions.push(newItem);
    console.log(this.state.completedQuestions);

    this.setState({
      QuestionComplete: true,
      QuestionAccepted: false,
      problem: true,
      questionProblem: true,
      problemSubmitted: false,
      declineSubmitted: true
    });
  }

  QuestionDecline(e) {
    e.preventDefault();

    if (this.state.ShowInput) {
      this.setState({ ShowInput: false });
      alert(this.state.ShowInput);
    } else if (!this.state.ShowInput) {
      this.setState({ ShowInput: true });
      alert(this.state.ShowInput);
    }
  }
  AdmitProblem(e) {
    e.preventDefault();
    alert("clicked");

    this.setState({
      QuestionComplete: true,
      QuestionAccepted: true
    });
  }
  AdmitNotProblem(e) {
    e.preventDefault();
    alert("clicked not a problem");

    this.setState({
      QuestionComplete: true,
      QuestionAccepted: false,
      problem: true
    });
  }

  QuestionProblem(e) {
    e.preventDefault();
    alert("problem clicked");

    this.setState({
      QuestionAccepted: false,
      problem: true,
      questionProblem: true,
      QuestionComplete: true
    });
  }

  AcceptAnswer(e) {
    e.preventDefault();
    let answer = "yes";
    let question = this.state.questions.Question;
    let state = "Accepted";

    let newItem = {
      answer: answer,
      question: question,
      state: state
    };
///////////////////////////////////////////////////////////////////////////////////////////////////////////Here I am trying to store to the state.

    this.setState(state => ({
      completedQuestions: state.completedQuestions.concat(newItem)
    }));

    this.setState({
      QuestionAccepted: false,
      problem: false,
      questionProblem: false,
      QuestionComplete: true
    });

    console.log(this.state.QuestionAndAnswer);

  }

  RevertAcceptedAnswer(e) {
    e.preventDefault();
    alert("revert clciked answer declined");
    let Email = window.localStorage.getItem("User");
    let WorkStation = window.localStorage.getItem("Workstation");
    const data = {
      QuestionId: this.state.questions.QuestionId,
      QuestionAnswer: this.state.QuestionAnswer,
      Email,
      WorkStation
    };

    fetch("revert-accepted-question-answer", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json,",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then(response => {
      console.log("response before it is broken down " + response);

      // return response.json();
    });
    this.setState({ ShowInput: false, QuestionComplete: false });
    alert("you answer has been deleted from the database");
  }

  RevertDeclinedAnswer(e) {
    e.preventDefault();
    alert("revert clciked answer declined");
    let Email = window.localStorage.getItem("User");
    let WorkStation = window.localStorage.getItem("Workstation");
    const data = {
      QuestionId: this.state.questions.QuestionId,
      QuestionAnswer: this.state.QuestionAnswer,
      Email,
      WorkStation
    };
    fetch("revert-declined-question-answer", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json,",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then(response => {
      console.log("response before it is broken down " + response);

      // return response.json();
    });
    this.setState({ ShowInput: false, QuestionComplete: false });
    alert("you answer has been deleted from the database");
  }

  QuestionOnChange(e) {
    this.setState({ QuestionAnswer: e.target.value });
  }

  ///////////////////////////////////////////
  OnCommit(e) {
    alert(this.state.QuestionAnswer);

    var today = new Date(),
      date = `${today.getUTCFullYear()}-${today.getUTCMonth() +
        1}-${today.getUTCDate()} ${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}.${today.getMilliseconds()} `;

    let User = window.localStorage.getItem("User");
    let WorkStation = window.localStorage.getItem("Workstation");

    const data = {
      QuestionId: this.state.questions.QuestionId,
      QuestionAnswer: this.state.QuestionAnswer,
      date: date,
      User,
      WorkStation
    };

    fetch("/declined-question-response", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json,",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then(response => {
      console.log("response before it is broken down " + response);

      // return response.json();
    });

    this.setState({ QuestionComplete: true, QuestionAccepted: true });
  }

  SubmitProblemSoloution(e) {
    e.preventDefault();
    let answer = this.state.problemDefinition;
    let question = this.state.questions.Question;
    let state = "problem";

    let newItem = {
      question: question,
      answer: answer,
      state: state
    };
    this.state.completedQuestions.push(newItem);
    console.log(this.state.completedQuestions);

    this.setState({
      QuestionAccepted: false,
      problem: true,
      questionProblem: true,
      problemSubmitted: true
    });
  }

  ////////////////////////////////////////////////
  render() {
    console.log(this.state.completedQuestions);
    ////////////////////////////////////////
    if (!this.state.QuestionComplete) {
      if (!this.state.ShowInput) {
        return (
          <div>
            <div style={{ float: "right" }}>
              <label>{"   "}Problem</label>
              <input
                type="checkbox"
                onClick={this.QuestionProblem}
                className="btn btn-danger"
                style={{ float: "right" }}
              />
            </div>
            <div style={{ float: "right" }}>
              <label>{"   "}No</label>
              <input
                type="checkbox"
                onClick={this.QuestionDecline}
                className="btn btn-danger"
                style={{ float: "right" }}
              />
            </div>

            <div style={{ float: "right" }}>
              <label> {"   "}Yes</label>
              <input
                type="checkbox"
                onClick={this.AcceptAnswer}
                className="btn btn-danger"
                style={{ float: "right" }}
              />
            </div>

            <br />
            <li>{this.state.questions.Question}</li>

            <br />
          </div>
          // </div>
        );
      } else if (
        this.state.ShowInput &&
        !this.state.QuestionComplete &&
        !this.state.problem
      ) {
        return (
          <div>
            <button
              onClick={this.QuestionDecline}
              style={{ float: "right", padding: "2px" }}
              className="btn btn-secondary"
            >
              Revert
            </button>

            <li> Question : {this.state.questions.Question}</li>
            <li>Answer: No</li>
            <li>
              Is this causing you a Problem?{" "}
              <div style={{ float: "right" }}>
                <label>{"   "}No</label>
                <input
                  type="checkbox"
                  onClick={this.AdmitNotProblem}
                  className="btn btn-danger"
                  style={{ float: "right" }}
                />
              </div>
              <div style={{ float: "right" }}>
                <label> {"   "}Yes</label>
                <input
                  type="checkbox"
                  onClick={this.AdmitProblem}
                  className="btn btn-danger"
                  style={{ float: "right" }}
                />
                <br />
                <br />
                <br />
              </div>
            </li>

            <br />
          </div>
        );
      }
    } else if (this.state.QuestionComplete) {
      if (
        this.state.QuestionAccepted &&
        !this.state.problem &&
        !this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <h3>
            <button
              onClick={this.RevertDeclinedAnswer}
              style={{ float: "right" }}
              className="btn btn-danger"
            >
              {" "}
              Revert Answer
            </button>
            <br />

            <li style={{ textAlign: "center", color: "grey" }}>
              <b>{this.state.questions.Question}</b>
            </li>

            <textarea
              placeholder="What would you suggest we do to solve this? "
              style={{ width: "100%" }}
              onChange={e =>
                this.setState({ soloutionForDeclinedQuestion: e.target.value })
              }
            />
            <button
              onClick={this.submitDeclinedQuestionSoloution}
              className="btn btn-primary"
              style={{ width: "100%" }}
            >
              Submit suggestion
            </button>
          </h3>
        );
      } else if (
        !this.state.QuestionAccepted &&
        !this.state.problem &&
        !this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <h3>
            <button
              onClick={this.RevertAcceptedAnswer}
              style={{ float: "right" }}
              className="btn btn-danger"
            >
              {" "}
              Revert Answer
            </button>
            <br />

            <li style={{ textAlign: "center", color: "grey" }}>
              <b>{this.state.questions.Question}</b>
            </li>
            <li>
              <b>Status</b>: Yes
            </li>
            <li>Complete : ✔ </li>
          </h3>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        !this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <h3>
            <button
              onClick={this.RevertAcceptedAnswer}
              style={{ float: "right" }}
              className="btn btn-danger"
            >
              {" "}
              Revert Answer
            </button>
            <br />
            <li style={{ textAlign: "center", color: "grey" }}>
              <b>{this.state.questions.Question}</b>
            </li>
            <li>
              <b>Status</b>: No but not a problem
            </li>
            <li>Complete : ✔ </li>
          </h3>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <>
            <h3>
              <button
                onClick={this.RevertAcceptedAnswer}
                style={{ float: "right" }}
                className="btn btn-danger"
              >
                {" "}
                Revert Answer
              </button>
              <br />
              <li> {this.state.questions.Question} </li>

              <textarea
                style={{ width: "100%" }}
                onChange={e =>
                  this.setState({ problemDefinition: e.target.value })
                }
                placeholder={`Please specify the problem`}
              />
            </h3>
            <button
              style={{ width: "100%" }}
              className="btn btn-primary"
              onClick={this.SubmitProblemSoloution}
            >
              Submit Solution{" "}
            </button>
          </>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        this.state.questionProblem &&
        this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <>
            <h3>
              <button
                onClick={this.RevertAcceptedAnswer}
                style={{ float: "right" }}
                className="btn btn-danger"
              >
                {" "}
                Revert Answer
              </button>
              <br />
              <li style={{ textAlign: "center", color: "grey" }}>
                {" "}
                <b>{this.state.questions.Question}</b>{" "}
              </li>{" "}
              <li>
                <b>Status</b>: Problem with soloution submitted
              </li>
              <li>
                <b>Soloution: </b>
                {this.state.problemDefinition}
              </li>
              <li>Complete : ✔ </li>
            </h3>
          </>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        this.state.questionProblem &&
        !this.state.problemSubmitted &&
        this.state.declineSubmitted
      ) {
        return (
          <>
            <h3>
              <button
                onClick={this.RevertAcceptedAnswer}
                style={{ float: "right" }}
                className="btn btn-danger"
              >
                {" "}
                Revert Answer
              </button>
              <br />
              <li style={{ textAlign: "center", color: "grey" }}>
                {" "}
                <b>{this.state.questions.Question}</b>{" "}
              </li>{" "}
              <li>
                <b>Status</b>: Declined with soloution defined
              </li>
              <li>
                <b>Soloution: </b>
                {this.state.soloutionForDeclinedQuestion}
              </li>
              <li>Complete : ✔ </li>
            </h3>
          </>
        );
      }
    }
  }
}
</code>```

As this component is so large I would like to break it down into easier chunks for best advice.

Below is just an accept answer onclick method

```<code>
  AcceptAnswer(e) {
    e.preventDefault();
    let answer = "yes";
    let question = this.state.questions.Question;
    let state = "Accepted";

    let newItem = {
      answer: answer,
      question: question,
      state: state
    };

    this.setState(state => ({
      completedQuestions: state.completedQuestions.concat(newItem)
    }));

</code>```

However when console logged anywhere in this component it will only display the most recently answered question.

答:
I solved this the easiest way I think possible.
I was hoping for a more inspiring way to do this but this is what I have ended up with. </p>

<p>All i simply did was define an array at the top above my first class and just push all these results into there. </p>

Body:
I have a initial component which maps a second component with information on questions. What I would like to do is to collect the answers of all these questions and save them in the same place(state, array, object I honestly don't mind how).

However as I am updating the state from a mapped component it is only displaying each individual updated state when console logging these results.

How or where can I store the questions answers from this mapped component so that I can use all the answers later to store elsewhere?

This is the mapped component I referred to (it's a bit convoluted due to all the conditional rendering I have going on).

class Questions extends React.Component {
  constructor(props) {
    super(props);
    console.log(props);
    this.state = {
      ...props,
      QuestionAnswer: "",
      QuestionAccepted: false,
      problem: false,

      problemDefinition: "",
      completedQuestions: [],
      soloutionForDeclinedQuestion: ""
    };

    this.QuestionDecline = this.QuestionDecline.bind(this);
    this.QuestionOnChange = this.QuestionOnChange.bind(this);
    this.OnCommit = this.OnCommit.bind(this);
    this.RevertDeclinedAnswer = this.RevertDeclinedAnswer.bind(this);
    this.RevertAcceptedAnswer = this.RevertAcceptedAnswer.bind(this);
    this.AdmitProblem = this.AdmitProblem.bind(this);
    this.AdmitNotProblem = this.AdmitNotProblem.bind(this);
    this.QuestionProblem = this.QuestionProblem.bind(this);
    this.SubmitProblemSoloution = this.SubmitProblemSoloution.bind(this);
    this.submitDeclinedQuestionSoloution = this.submitDeclinedQuestionSoloution.bind(
      this
    );

    this.AcceptAnswer = this.AcceptAnswer.bind(this);
  }
  submitDeclinedQuestionSoloution(e) {
    e.preventDefault();
    let answer = this.state.soloutionForDeclinedQuestion;
    let question = this.state.questions.Question;
    let state = "Declined With solution";

    let newItem = {
      answer: answer,
      question: question,
      state: state
    };
    this.state.completedQuestions.push(newItem);
    console.log(this.state.completedQuestions);

    this.setState({
      QuestionComplete: true,
      QuestionAccepted: false,
      problem: true,
      questionProblem: true,
      problemSubmitted: false,
      declineSubmitted: true
    });
  }

  QuestionDecline(e) {
    e.preventDefault();

    if (this.state.ShowInput) {
      this.setState({ ShowInput: false });
      alert(this.state.ShowInput);
    } else if (!this.state.ShowInput) {
      this.setState({ ShowInput: true });
      alert(this.state.ShowInput);
    }
  }
  AdmitProblem(e) {
    e.preventDefault();
    alert("clicked");

    this.setState({
      QuestionComplete: true,
      QuestionAccepted: true
    });
  }
  AdmitNotProblem(e) {
    e.preventDefault();
    alert("clicked not a problem");

    this.setState({
      QuestionComplete: true,
      QuestionAccepted: false,
      problem: true
    });
  }

  QuestionProblem(e) {
    e.preventDefault();
    alert("problem clicked");

    this.setState({
      QuestionAccepted: false,
      problem: true,
      questionProblem: true,
      QuestionComplete: true
    });
  }

  AcceptAnswer(e) {
    e.preventDefault();
    let answer = "yes";
    let question = this.state.questions.Question;
    let state = "Accepted";

    let newItem = {
      answer: answer,
      question: question,
      state: state
    };
///////////////////////////////////////////////////////////////////////////////////////////////////////////Here I am trying to store to the state.

    this.setState(state => ({
      completedQuestions: state.completedQuestions.concat(newItem)
    }));

    this.setState({
      QuestionAccepted: false,
      problem: false,
      questionProblem: false,
      QuestionComplete: true
    });

    console.log(this.state.QuestionAndAnswer);

  }

  RevertAcceptedAnswer(e) {
    e.preventDefault();
    alert("revert clciked answer declined");
    let Email = window.localStorage.getItem("User");
    let WorkStation = window.localStorage.getItem("Workstation");
    const data = {
      QuestionId: this.state.questions.QuestionId,
      QuestionAnswer: this.state.QuestionAnswer,
      Email,
      WorkStation
    };

    fetch("revert-accepted-question-answer", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json,",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then(response => {
      console.log("response before it is broken down " + response);

      // return response.json();
    });
    this.setState({ ShowInput: false, QuestionComplete: false });
    alert("you answer has been deleted from the database");
  }

  RevertDeclinedAnswer(e) {
    e.preventDefault();
    alert("revert clciked answer declined");
    let Email = window.localStorage.getItem("User");
    let WorkStation = window.localStorage.getItem("Workstation");
    const data = {
      QuestionId: this.state.questions.QuestionId,
      QuestionAnswer: this.state.QuestionAnswer,
      Email,
      WorkStation
    };
    fetch("revert-declined-question-answer", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json,",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then(response => {
      console.log("response before it is broken down " + response);

      // return response.json();
    });
    this.setState({ ShowInput: false, QuestionComplete: false });
    alert("you answer has been deleted from the database");
  }

  QuestionOnChange(e) {
    this.setState({ QuestionAnswer: e.target.value });
  }

  ///////////////////////////////////////////
  OnCommit(e) {
    alert(this.state.QuestionAnswer);

    var today = new Date(),
      date = `${today.getUTCFullYear()}-${today.getUTCMonth() +
        1}-${today.getUTCDate()} ${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}.${today.getMilliseconds()} `;

    let User = window.localStorage.getItem("User");
    let WorkStation = window.localStorage.getItem("Workstation");

    const data = {
      QuestionId: this.state.questions.QuestionId,
      QuestionAnswer: this.state.QuestionAnswer,
      date: date,
      User,
      WorkStation
    };

    fetch("/declined-question-response", {
      method: "POST", // or 'PUT'
      headers: {
        Accept: "application/json,",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).then(response => {
      console.log("response before it is broken down " + response);

      // return response.json();
    });

    this.setState({ QuestionComplete: true, QuestionAccepted: true });
  }

  SubmitProblemSoloution(e) {
    e.preventDefault();
    let answer = this.state.problemDefinition;
    let question = this.state.questions.Question;
    let state = "problem";

    let newItem = {
      question: question,
      answer: answer,
      state: state
    };
    this.state.completedQuestions.push(newItem);
    console.log(this.state.completedQuestions);

    this.setState({
      QuestionAccepted: false,
      problem: true,
      questionProblem: true,
      problemSubmitted: true
    });
  }

  ////////////////////////////////////////////////
  render() {
    console.log(this.state.completedQuestions);
    ////////////////////////////////////////
    if (!this.state.QuestionComplete) {
      if (!this.state.ShowInput) {
        return (

              {"   "}Problem
              <input
                type="checkbox"
                onClick={this.QuestionProblem}
                className="btn btn-danger"
                style={{ float: "right" }}
              />

              {"   "}No
              <input
                type="checkbox"
                onClick={this.QuestionDecline}
                className="btn btn-danger"
                style={{ float: "right" }}
              />

               {"   "}Yes
              <input
                type="checkbox"
                onClick={this.AcceptAnswer}
                className="btn btn-danger"
                style={{ float: "right" }}
              />

{this.state.questions.Question}

          //

        );
      } else if (
        this.state.ShowInput &&
        !this.state.QuestionComplete &&
        !this.state.problem
      ) {
        return (

            <button
              onClick={this.QuestionDecline}
              style={{ float: "right", padding: "2px" }}
              className="btn btn-secondary"
            >
              Revert
            </button>

 Question : {this.state.questions.Question}

Answer: No

              Is this causing you a Problem?{" "}

                {"   "}No
                <input
                  type="checkbox"
                  onClick={this.AdmitNotProblem}
                  className="btn btn-danger"
                  style={{ float: "right" }}
                />

                 {"   "}Yes
                <input
                  type="checkbox"
                  onClick={this.AdmitProblem}
                  className="btn btn-danger"
                  style={{ float: "right" }}
                />

        );
      }
    } else if (this.state.QuestionComplete) {
      if (
        this.state.QuestionAccepted &&
        !this.state.problem &&
        !this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (

            <button
              onClick={this.RevertDeclinedAnswer}
              style={{ float: "right" }}
              className="btn btn-danger"
            >
              {" "}
              Revert Answer
            </button>

              {this.state.questions.Question}

            <textarea
              placeholder="What would you suggest we do to solve this? "
              style={{ width: "100%" }}
              onChange={e =>
                this.setState({ soloutionForDeclinedQuestion: e.target.value })
              }
            />
            <button
              onClick={this.submitDeclinedQuestionSoloution}
              className="btn btn-primary"
              style={{ width: "100%" }}
            >
              Submit suggestion
            </button>

        );
      } else if (
        !this.state.QuestionAccepted &&
        !this.state.problem &&
        !this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (

            <button
              onClick={this.RevertAcceptedAnswer}
              style={{ float: "right" }}
              className="btn btn-danger"
            >
              {" "}
              Revert Answer
            </button>

              {this.state.questions.Question}

              Status: Yes

Complete : ✔

        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        !this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (

            <button
              onClick={this.RevertAcceptedAnswer}
              style={{ float: "right" }}
              className="btn btn-danger"
            >
              {" "}
              Revert Answer
            </button>

              {this.state.questions.Question}

              Status: No but not a problem

Complete : ✔

        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        this.state.questionProblem &&
        !this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <>

              <button
                onClick={this.RevertAcceptedAnswer}
                style={{ float: "right" }}
                className="btn btn-danger"
              >
                {" "}
                Revert Answer
              </button>

 {this.state.questions.Question}

              <textarea
                style={{ width: "100%" }}
                onChange={e =>
                  this.setState({ problemDefinition: e.target.value })
                }
                placeholder={`Please specify the problem`}
              />

            <button
              style={{ width: "100%" }}
              className="btn btn-primary"
              onClick={this.SubmitProblemSoloution}
            >
              Submit Solution{" "}
            </button>
          </>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        this.state.questionProblem &&
        this.state.problemSubmitted &&
        !this.state.declineSubmitted
      ) {
        return (
          <>

              <button
                onClick={this.RevertAcceptedAnswer}
                style={{ float: "right" }}
                className="btn btn-danger"
              >
                {" "}
                Revert Answer
              </button>

                {" "}
                {this.state.questions.Question}{" "}

{" "}

                Status: Problem with soloution submitted

                Soloution:
                {this.state.problemDefinition}

Complete : ✔

          </>
        );
      } else if (
        !this.state.QuestionAccepted &&
        this.state.problem &&
        this.state.questionProblem &&
        !this.state.problemSubmitted &&
        this.state.declineSubmitted
      ) {
        return (
          <>

              <button
                onClick={this.RevertAcceptedAnswer}
                style={{ float: "right" }}
                className="btn btn-danger"
              >
                {" "}
                Revert Answer
              </button>

                {" "}
                {this.state.questions.Question}{" "}

{" "}

                Status: Declined with soloution defined

                Soloution:
                {this.state.soloutionForDeclinedQuestion}

Complete : ✔

          </>
        );
      }
    }
  }
}

As this component is so large I would like to break it down into easier chunks for best advice.

Below is just an accept answer onclick method

  AcceptAnswer(e) {
    e.preventDefault();
    let answer = "yes";
    let question = this.state.questions.Question;
    let state = "Accepted";

    let newItem = {
      answer: answer,
      question: question,
      state: state
    };

    this.setState(state => ({
      completedQuestions: state.completedQuestions.concat(newItem)
    }));

However when console logged anywhere in this component it will only display the most recently answered question.

Body:
I solved this the easiest way I think possible.
I was hoping for a more inspiring way to do this but this is what I have ended up with.

All i simply did was define an array at the top above my first class and just push all these results into there.


问:
How to detect portrait lock (orientation lock) in an app that records video?
I have an app which records video. I only supported landscape at first, but now I'm offering portrait and other orientations. I set the transform of the video to the orientation it was filmed in as detected from UIDevice. However, with portrait lock on the phone, UIDevice would tell me the current orientation is portrait even if the user was holding the device in landscape.

How can I determine if it's locked, so I can save the video in the proper orientation?

答:
Use the accelerometer on the device to detect orientation.

Check this link for more info:
Detect iPhone screen orientation


问:
javascript find all the object in an array and convert it into an array to array
I have a list of array with object in it like address and details

Input

```<code>var arr = [
    {id: 1, name: "abc", address: {street: "some text1", pin: 879888, state: "my-state1"}, details: {section: "A", roll: 12, branch:"CSE"}},
    {id: 2, name: "xyz", address: {street: "some text2", pin: 879887, state: "my-state2"}, details: {section: "B", roll: 13, branch:"IT"}}
]
</code>```

I want to iterate on this array and convert all the inner object so that it will look something like below

Expected Result

```<code>var arr = [
    {id: 1, name: "abc", street: "some text1", pin: 879888, state: "my-state1", section: "A", roll: 12, branch: "CSE"},
    {id: 2, name: "xyz", street: "some text2", pin: 879887, state: "my-state2", section: "B", roll: 13, branch: "IT"}
]
</code>```

答:
I think your goal is to flatten the objects in the array. So to achieve this, you could iterate over the object extract the values which are objects, and then spread them into the object. It could look like this:</p>

```<code>var arr = [
    { id: 1, name: "abc", address: { street: "some text1", pin: 879888, state: "my-state1" }, details: { section: "A", roll: 12, branch: "CSE" } },
    { id: 2, name: "xyz", address: { street: "some text2", pin: 879887, state: "my-state2" }, details: { section: "B", roll: 13, branch: "IT" } }
]

const newArray = arr.map(obj => {
    const newObject = obj
    for(let key in newObject) {
        if(typeof newObject[key] === "object") {
            newObject = {
                ...newObject,
                ...newObject[key]
            }
            delete newObject[key]
        }
    }
    return newObject
})

</code>```

Body:
I have a list of array with object in it like address and details

Input

var arr = [
    {id: 1, name: "abc", address: {street: "some text1", pin: 879888, state: "my-state1"}, details: {section: "A", roll: 12, branch:"CSE"}},
    {id: 2, name: "xyz", address: {street: "some text2", pin: 879887, state: "my-state2"}, details: {section: "B", roll: 13, branch:"IT"}}
]

I want to iterate on this array and convert all the inner object so that it will look something like below

Expected Result

var arr = [
    {id: 1, name: "abc", street: "some text1", pin: 879888, state: "my-state1", section: "A", roll: 12, branch: "CSE"},
    {id: 2, name: "xyz", street: "some text2", pin: 879887, state: "my-state2", section: "B", roll: 13, branch: "IT"}
]

Body:
I think your goal is to flatten the objects in the array. So to achieve this, you could iterate over the object extract the values which are objects, and then spread them into the object. It could look like this:

var arr = [
    { id: 1, name: "abc", address: { street: "some text1", pin: 879888, state: "my-state1" }, details: { section: "A", roll: 12, branch: "CSE" } },
    { id: 2, name: "xyz", address: { street: "some text2", pin: 879887, state: "my-state2" }, details: { section: "B", roll: 13, branch: "IT" } }
]

const newArray = arr.map(obj => {
    const newObject = obj
    for(let key in newObject) {
        if(typeof newObject[key] === "object") {
            newObject = {
                ...newObject,
                ...newObject[key]
            }
            delete newObject[key]
        }
    }
    return newObject
})


问:
NodeJS - Return a single status code from an async function using Array.protoype.map() to save multiple files in different locations in a database
I am a little stumped on how to handle this the best way possible. I've decided to rewrite this controller, and I need to (at least I think) make use of promise.all() here.

Premise:

In this application, the Admin user must be able to bulk upload a bunch of .pdf's at once that are for multiple users. The .pdf's adhere to a specific naming convention that my backend upload controller by using a regEx, pulls out a first and last name. These .pdf's are auto-generated in a program, that always names them exactly the same, so there is no human error in misspelling names.

Each call to the database and an AWS S3 Bucket is made within an Array.prototype.map() a function that is looping through and uploading a file to an S3 bucket, and then it takes the Key name of the file returned from s3.upload() and saves that Key to a user model in Mongo DB as a reference to their file(s) within the S3 Bucket.

Example Code:

This is what I currently have (that does work somewhat). This is the block of code responsible for what I described above. employeeFiles is created further up in the controller and contains an array of objects that each have a file and id property. The file name destructuring and user matching happen further up in the controller as well, and the employeeFiles array is a result of that. The id property contains the mongo _id of the employee, and the file property contains the file to be saved. This all works perfectly, and I don't think that code is needed for context here. fileType is a variable available within the scope of the controller:

```<code>const employeeFileUploadToDb = () => {

  employeeFiles.map((employee, i) => {
    const { file, id } = employee;
    const params = {
      Bucket: S3_BUCKET_NAME,
      Body: file.buffer,
      Key: `${filetype}/${file.originalname}`
    };
    s3.upload(params, (err, data) => {
      if (err) {
        next(err);
      }

      if (data) {
        //Save reference to Employee model
        let dataObj = {
          key: data.key,
          fileName: file.originalname,
          date: Date.now()
        };

        Employee.findOneAndUpdate(
          { _id: id },
          { $push: { [`${filetype}`]: dataObj } }
        )
          .then(resp => res.send(200))
          .catch(err => next(err));
      }
    });
  });
};
</code>```

I am making use of next() to handle any errors within the s3.upload() and findOneAndUpdate() functions (I do realize findOneAndUpdate() is deprecated) moving forward. My idea here is that if there is an error with one of the functions, next() will send it to my error handler middleware and keep going, versus ending the process and halting all of it.

Inside of every iteration of s3.upload(), I make a call to my database so that I can save the reference to the file uploaded to the S3 Bucket. Inside of a then() method of Employee.findOneAndUpdate(), I return a (200) response to let my client know everything has been uploaded to S3 and saved in my DB. So on each iteration of this map() function, I am returning a 200. If I have 10 files, I am returning 200 10 times.

I feel that I can convert this into an async function, and make use of a promise.all() to return a single status code upon completion. Returning that many status codes seem a bit crazy to me. But I am not too sure how to approach this while using a map() function to loop and make an async call on every iteration.

Hope this makes sense, and thank you in advance for looking at this!

答:
I would split it up into a 2-step process. Upload in bulk and then save to mongo if it all worked out.</p>

```<code>const employeeFileUploadToDb = () => {

  const uploadFiles = files => files.map((employee, i) => new Promise((resolve, reject) => {
    //...
    s3.upload(params, (err, data) => {
      if (err) {
        return reject(err);
      }
      resolve(data);
     })
    });
  });

  Promise.all(uploadData(employeeFiles)).then((err, data) => {
     // Handle saving to mongo
  })
};
</code>```

Body:
I am a little stumped on how to handle this the best way possible. I've decided to rewrite this controller, and I need to (at least I think) make use of promise.all() here.

Premise:

In this application, the Admin user must be able to bulk upload a bunch of .pdf's at once that are for multiple users. The .pdf's adhere to a specific naming convention that my backend upload controller by using a regEx, pulls out a first and last name. These .pdf's are auto-generated in a program, that always names them exactly the same, so there is no human error in misspelling names.

Each call to the database and an AWS S3 Bucket is made within an Array.prototype.map() a function that is looping through and uploading a file to an S3 bucket, and then it takes the Key name of the file returned from s3.upload() and saves that Key to a user model in Mongo DB as a reference to their file(s) within the S3 Bucket.

Example Code:

This is what I currently have (that does work somewhat). This is the block of code responsible for what I described above. employeeFiles is created further up in the controller and contains an array of objects that each have a file and id property. The file name destructuring and user matching happen further up in the controller as well, and the employeeFiles array is a result of that. The id property contains the mongo _id of the employee, and the file property contains the file to be saved. This all works perfectly, and I don't think that code is needed for context here. fileType is a variable available within the scope of the controller:

const employeeFileUploadToDb = () => {

  employeeFiles.map((employee, i) => {
    const { file, id } = employee;
    const params = {
      Bucket: S3_BUCKET_NAME,
      Body: file.buffer,
      Key: `${filetype}/${file.originalname}`
    };
    s3.upload(params, (err, data) => {
      if (err) {
        next(err);
      }

      if (data) {
        //Save reference to Employee model
        let dataObj = {
          key: data.key,
          fileName: file.originalname,
          date: Date.now()
        };

        Employee.findOneAndUpdate(
          { _id: id },
          { $push: { [`${filetype}`]: dataObj } }
        )
          .then(resp => res.send(200))
          .catch(err => next(err));
      }
    });
  });
};

I am making use of next() to handle any errors within the s3.upload() and findOneAndUpdate() functions (I do realize findOneAndUpdate() is deprecated) moving forward. My idea here is that if there is an error with one of the functions, next() will send it to my error handler middleware and keep going, versus ending the process and halting all of it.

Inside of every iteration of s3.upload(), I make a call to my database so that I can save the reference to the file uploaded to the S3 Bucket. Inside of a then() method of Employee.findOneAndUpdate(), I return a (200) response to let my client know everything has been uploaded to S3 and saved in my DB. So on each iteration of this map() function, I am returning a 200. If I have 10 files, I am returning 200 10 times.

I feel that I can convert this into an async function, and make use of a promise.all() to return a single status code upon completion. Returning that many status codes seem a bit crazy to me. But I am not too sure how to approach this while using a map() function to loop and make an async call on every iteration.

Hope this makes sense, and thank you in advance for looking at this!

Body:
I would split it up into a 2-step process. Upload in bulk and then save to mongo if it all worked out.

const employeeFileUploadToDb = () => {

  const uploadFiles = files => files.map((employee, i) => new Promise((resolve, reject) => {
    //...
    s3.upload(params, (err, data) => {
      if (err) {
        return reject(err);
      }
      resolve(data);
     })
    });
  });

  Promise.all(uploadData(employeeFiles)).then((err, data) => {
     // Handle saving to mongo
  })
};