问:
After launching the application it gives some unknow error
I have an android application which runs fine on my another laptop but when I run at my laptop it gives error and it only runs when we connect to laptop. If I send .apk by email then it does not work.

Here is my buidl.gradle apply plugin: 'com.android.application'

```<code>android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "realtracker.in.cresol.realtracker"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        //multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    //Date and Calendar picker https://github.com/wdullaer/MaterialDateTimePicker

    //For Camera and video

    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.5.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.android.support:cardview-v7:25.2.0'
    compile 'com.github.lecho:hellocharts-library:1.5.8@aar'
    compile 'com.wdullaer:materialdatetimepicker:3.1.1'
    compile 'com.layer-net:step-indicator:1.1.0'
    compile 'com.sandrios.android:sandriosCamera:1.0.9'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

Here is my manifest file

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="realtracker.in.cresol.realtracker">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:supportsRtl="true"
        android:theme="@style/NoTitle">
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Signup"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Login"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Activities.Activity_Dashboard"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Report"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Welcome"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_medicine_Description"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Reminder"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Event_Description"
            android:screenOrientation="portrait" />

        <receiver android:name=".Util.Reminder"/>
        <receiver android:name=".Util.BootReciever">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>
</code>```

Here is the error code.

```<code>e.android.googlequicksearchbox:search I/MicroRecognitionRunner: Stopping hotword detection.
04-01 15:27:19.422 2153-12482/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
                                                                                com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
                                                                                Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
                                                                                at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
                                                                                at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
                                                                                at java.io.InputStream.read(InputStream.java:101)
                                                                                at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
                                                                                at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
04-01 15:27:19.422 2153-12482/com.google.android.googlequicksearchbox:search I/AudioController: internalShutdown
04-01 15:27:19.430 2153-2153/com.google.android.googlequicksearchbox:search I/MicroDetector: Keeping mic open: false
</code>```

答:
Firstly u have to build apk.
in your android studio- Build > Build APK and build your apk
and open apk location and install it in your real devices, it will work.</p>

Body:
I have an android application which runs fine on my another laptop but when I run at my laptop it gives error and it only runs when we connect to laptop. If I send .apk by email then it does not work.

Here is my buidl.gradle apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "realtracker.in.cresol.realtracker"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        //multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    //Date and Calendar picker https://github.com/wdullaer/MaterialDateTimePicker

    //For Camera and video

    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.5.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.android.support:cardview-v7:25.2.0'
    compile 'com.github.lecho:hellocharts-library:1.5.8@aar'
    compile 'com.wdullaer:materialdatetimepicker:3.1.1'
    compile 'com.layer-net:step-indicator:1.1.0'
    compile 'com.sandrios.android:sandriosCamera:1.0.9'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Here is my manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="realtracker.in.cresol.realtracker">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:supportsRtl="true"
        android:theme="@style/NoTitle">
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Signup"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Login"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Activities.Activity_Dashboard"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Report"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Welcome"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_medicine_Description"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Reminder"
            android:screenOrientation="portrait" />
        <activity
            android:name=".Activities.Activity_Event_Description"
            android:screenOrientation="portrait" />

        <receiver android:name=".Util.Reminder"/>
        <receiver android:name=".Util.BootReciever">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>

Here is the error code.

e.android.googlequicksearchbox:search I/MicroRecognitionRunner: Stopping hotword detection.
04-01 15:27:19.422 2153-12482/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
                                                                                com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
                                                                                Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
                                                                                at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
                                                                                at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
                                                                                at java.io.InputStream.read(InputStream.java:101)
                                                                                at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
                                                                                at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
04-01 15:27:19.422 2153-12482/com.google.android.googlequicksearchbox:search I/AudioController: internalShutdown
04-01 15:27:19.430 2153-2153/com.google.android.googlequicksearchbox:search I/MicroDetector: Keeping mic open: false


来源: stackexchange

问:
Ajax Response JSON data to select box in html
below is my ajax call and i am getting r JSON data

```<code>$.ajax ({
            type: "POST",
            url: "getrecieverlist.php",
            data: { strSenderID: sendmeid },
            success: function (r) {
            }
       });
</code>```

I am getting r response as JSON data below

```<code>{
 "receiverDetails": [
{
  "receiver_id": "55555",
  "name": "Nitin",
  "mobile": "7777777777",
  "ifsc_code": "IFSC54545",
  "acc_no": "16-01-2017"
},
{
  "receiver_id": "66666",
  "name": "Vikram",
  "mobile": "9191919191",
  "ifsc_code": "IFSC54545",
  "acc_no": "13-01-2017"
}
],
 "success": 1
 }
</code>```

and my select box html code is below

```<code><select id="recieverlist" name="select" class="main-form">
      <option value="">None Selected</option>
    </select>
</code>```

what i want is to populate select box options with text as name from the JSON data and value of the options to be receiverid, i tried many things but did not worked out for me need the proper guide how to do it?

答:
Give a try on following.</p>

```<code>success : function (r) {
    var data = r.receiverDetails;
    var options = '';

    for(var i=0; i<data.length; i++) { // Loop through the data & construct the options
        options += '<option value="'+data[i].receiver_id+'">'+data[i].name+'</option>';
    }

    // Append to the html
    $('#recieverlist').append(options);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
below is my ajax call and i am getting r JSON data

$.ajax ({
            type: "POST",
            url: "getrecieverlist.php",
            data: { strSenderID: sendmeid },
            success: function (r) {
            }
       });

I am getting r response as JSON data below

{
 "receiverDetails": [
{
  "receiver_id": "55555",
  "name": "Nitin",
  "mobile": "7777777777",
  "ifsc_code": "IFSC54545",
  "acc_no": "16-01-2017"
},
{
  "receiver_id": "66666",
  "name": "Vikram",
  "mobile": "9191919191",
  "ifsc_code": "IFSC54545",
  "acc_no": "13-01-2017"
}
],
 "success": 1
 }

and my select box html code is below

<select id="recieverlist" name="select" class="main-form">
      <option value="">None Selected</option>
    </select>

what i want is to populate select box options with text as name from the JSON data and value of the options to be receiverid, i tried many things but did not worked out for me need the proper guide how to do it?

Body:
Give a try on following.

success : function (r) {
    var data = r.receiverDetails;
    var options = '';

    for(var i=0; i<data.length; i++) { // Loop through the data & construct the options
        options += '<option value="'+data[i].receiver_id+'">'+data[i].name+'</option>';
    }

    // Append to the html
    $('#recieverlist').append(options);
}


问:
github syncing a fork with a local branch
I may have messed up my workflow with github - I noticed some issues with a repo and wanted to fix them. I cloned the repo (Github Desktop, Mac OS) and made the changes in XCode, I created a local branch to the repo after making the changes and committed the changes. I then tried to push the changes but had an error related to permissions.

I went to the github repo and forked it, now I have the fork in my github account and the local branch. I can't figure out how to merge my local branch changes into the fork without overwriting them (no changes made to the fork).

答:
You'll need to:

Add a new remote repository pointing to your fork

Push your local changes to your remote fork

To add the new remote you'll have to type this in your repository folder:

git remote add myfork {GIT_URL_OF_YOUR_FORK}

After this you simply need to push your branch to your fork

git push myfork {BRANCH_NAME_THAT_HAS_THE_LOCAL_CHANGES}

This should be about it.


问:
Group items in multidimensional array by same value at index
I have a multi-dimensional array like this:

```<code>var arr = [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ];
</code>```

and I want to make it like this (grouping each sub-array according to matching  arr[i][2] values):

```<code>var arr = [ [[x,x,1]] , [[x,x,2],[x,x,2]] , [[x,x,3],[x,x,3],[x,x,3]] ];
</code>```

My attempts are getting increasingly long-winded, and I'm ashamed of posting them here. Any efficient suggestions greatly appreciated!

答:
You can first group arrays by using one object and then use map() and Object.keys() to return array as result.

var arr = [["x","x", 1],["x","x", 2],["x","x", 2],["x","x", 3],["x","x", 3],["x","x", 3]];

var obj = {}
arr.forEach(function(e) {
  if(!obj[e[2]]) obj[e[2]] = []
  obj[e[2]].push(e)
});

var result = Object.keys(obj).map(e => obj[e]);
console.log(JSON.stringify(result))```

Body:
I have a multi-dimensional array like this:

var arr = [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ];

and I want to make it like this (grouping each sub-array according to matching  arr[i][2] values):

var arr = [ [[x,x,1]] , [[x,x,2],[x,x,2]] , [[x,x,3],[x,x,3],[x,x,3]] ];

My attempts are getting increasingly long-winded, and I'm ashamed of posting them here. Any efficient suggestions greatly appreciated!


问:
How to get previous and new selected value from a option DOM element with JavaScript?
How can I retrieve the new selected value and the previous selected value with JavaScript when onChange or similar event is called?

```<code><select size="1" id="x" onchange="doSomething()">
  <option value="47">Value 47</option>
  ...

function doSomething() {
  var oldValue = null; // how to get the old value?
  var newValue = document.getElementById('x').selected.value;
  // ...
</code>```

Thank you! :)

答:
Using straight JavaScript and DOM, something like this (live example):

var box, oldValue;

// Get a reference to the select box's DOM element.
// This can be any of several ways; below I'll look
// it up by ID.
box = document.getElementById('theSelect');
if (box.addEventListener) {
  // DOM2 standard
  box.addEventListener("change", changeHandler, false);
}
else if (box.attachEvent) {
  // IE fallback
  box.attachEvent("onchange", changeHandler);
}
else {
  // DOM0 fallback
  box.onchange = changeHandler;
}

// Our handler
function changeHandler(event) {
  var index, newValue;

  // Get the current index
  index = this.selectedIndex;
  if (index >= 0 && this.options.length > index) {
    // Get the new value
    newValue = this.options[index].value;
  }

  // **Your code here**: old value is `oldValue`, new value is `newValue`
  // Note that `newValue`` may well be undefined
  display("Old value: " + oldValue);
  display("New value: " + newValue);

  // When done processing the change, remember the old value
  oldValue = newValue;
}
```

(I'm assuming all of the above is inside a function, like a page load function or similar, as in the live example, so we're not creating unnecessary global symbols [box, oldValue, 'changeHandler`].)

Note that the change event is raised by different browsers at different times. Some browsers raise the event when the selection changes, others wait until focus leaves the select box.

But you might consider using a library like jQuery, Prototype, YUI, Closure, or any of several others, as they make a lot of this stuff a lot easier.

ContentLicense: CC BY-SA 2.5

Body:
How can I retrieve the new selected value and the previous selected value with JavaScript when onChange or similar event is called?

<select size="1" id="x" onchange="doSomething()">
  <option value="47">Value 47</option>
  ...

function doSomething() {
  var oldValue = null; // how to get the old value?
  var newValue = document.getElementById('x').selected.value;
  // ...

Thank you! :)

Body:
Using straight JavaScript and DOM, something like this (live example):

var box, oldValue;

// Get a reference to the select box's DOM element.
// This can be any of several ways; below I'll look
// it up by ID.
box = document.getElementById('theSelect');
if (box.addEventListener) {
  // DOM2 standard
  box.addEventListener("change", changeHandler, false);
}
else if (box.attachEvent) {
  // IE fallback
  box.attachEvent("onchange", changeHandler);
}
else {
  // DOM0 fallback
  box.onchange = changeHandler;
}

// Our handler
function changeHandler(event) {
  var index, newValue;

  // Get the current index
  index = this.selectedIndex;
  if (index >= 0 && this.options.length > index) {
    // Get the new value
    newValue = this.options[index].value;
  }

  // **Your code here**: old value is `oldValue`, new value is `newValue`
  // Note that `newValue`` may well be undefined
  display("Old value: " + oldValue);
  display("New value: " + newValue);

  // When done processing the change, remember the old value
  oldValue = newValue;
}

(I'm assuming all of the above is inside a function, like a page load function or similar, as in the live example, so we're not creating unnecessary global symbols [box, oldValue, 'changeHandler`].)

Note that the change event is raised by different browsers at different times. Some browsers raise the event when the selection changes, others wait until focus leaves the select box.

But you might consider using a library like jQuery, Prototype, YUI, Closure, or any of several others, as they make a lot of this stuff a lot easier.


问:
Loop through multiple field names
I've got the following input fields:

```<code><input name="file1" type="file">
<input name="file2" type="file">
<input name="files[]" type="file" multiple>
</code>```

I'm trying to figure out the best way to check which of the fields above are not empty and perform some DB action with the ones that have files in them.

I can check them each one manually like this but I am wondering if there is a better way to do this:

```<code>if(!empty($_FILES['file1']['name']) {
    // Perform checks/etc for file1
}

if(!empty($_FILES['file2']['name']) {
    // Perform checks/etc for file2
}

if(!empty($_FILES['files']['name'][0]) {
    // Loop the array, perform checks/etc for each one
}
</code>```

答:
This will loop through all the files and tell you which ones are empty, and put the files that have content in the $submittedFiles array.</p>

```<code>$submittedFiles = [];
foreach ($_FILES as $n => $f) {
        if (!empty($f['name']) && !empty($f['name'][0])) {
                $submittedFiles[] = $f;
        } else {
                echo $n.' is empty';
        }
}
var_dump($submittedFiles);
</code>```

Title: Loop through multiple field names

Body:
I've got the following input fields:

<input name="file1" type="file">
<input name="file2" type="file">
<input name="files[]" type="file" multiple>

I'm trying to figure out the best way to check which of the fields above are not empty and perform some DB action with the ones that have files in them.

I can check them each one manually like this but I am wondering if there is a better way to do this:

if(!empty($_FILES['file1']['name']) {
    // Perform checks/etc for file1
}

if(!empty($_FILES['file2']['name']) {
    // Perform checks/etc for file2
}

if(!empty($_FILES['files']['name'][0]) {
    // Loop the array, perform checks/etc for each one
}

Body:
This will loop through all the files and tell you which ones are empty, and put the files that have content in the $submittedFiles array.

$submittedFiles = [];
foreach ($_FILES as $n => $f) {
        if (!empty($f['name']) && !empty($f['name'][0])) {
                $submittedFiles[] = $f;
        } else {
                echo $n.' is empty';
        }
}
var_dump($submittedFiles);


问:
how to check if a string contains only lower case letters and numbers?
How can I check if a string contains only numbers and lower case letters?

I only managed to check if it contains numbers and lower case letters and doesn't contain upper case letters but I don't know how to check that it doesn't contain any symbols as ^&*(% etc..

```<code>if(any(i.islower() for i in password) and any(i.isdigit() for i in password) and not any(i.isupper() for i in password)):
</code>```

EDIT:
so apparently I need to do this without using any loops and mainly using functions like .islower() , .isdigit() , isalnum() etc.. and I have no idea how I can check if a string contains lower case letters and numbers only , without using loops or something that will check every single char in the string . we only started to learn the basics in python so they told us we can't use "for" and all that even if I know what it does.. now I can check if an entire string is only digits or lower/upper case letters but I don't know how to check the two conditions mentioned above in the simplest way possible

答:
What about:

```<code>if <b>all(c.isdigit() or c.islower()</b> for c in password<b>)</b>:</code>```

after all, you want to check that all characters are either a digit or lowercase letters. So for all characters c, that character is c.isdigit() or c.islower(). Now an all(..) takes as input an iterable of values and checks if the truthiness of all these values is True. So from the moment there is one digit that does not satisfies our condition, the all(..) will return False.

Mind however that all(..) is True if there are no elements. Indeed if the password is the empty string, all the characters satisfy this condition, since there are no characters.

EDIT:

In case you want to check that the password contains both digits and lowercase characters, you can alter the condition to:

```<code>if all(c.isdigit() or c.islower() for c in password) <b>and \</b>
       <b>any(c.isdigit() for c in password) and \</b>
       <b>any(c.islower() for c in password)</b>:</code>```

Now the check will only succeed if there are at least two characters in password: a lower and a digit.

Body:
How can I check if a string contains only numbers and lower case letters?

I only managed to check if it contains numbers and lower case letters and doesn't contain upper case letters but I don't know how to check that it doesn't contain any symbols as ^&*(% etc..

if(any(i.islower() for i in password) and any(i.isdigit() for i in password) and not any(i.isupper() for i in password)):

EDIT:
so apparently I need to do this without using any loops and mainly using functions like .islower() , .isdigit() , isalnum() etc.. and I have no idea how I can check if a string contains lower case letters and numbers only , without using loops or something that will check every single char in the string . we only started to learn the basics in python so they told us we can't use "for" and all that even if I know what it does.. now I can check if an entire string is only digits or lower/upper case letters but I don't know how to check the two conditions mentioned above in the simplest way possible

Body:
What about:

if all(c.isdigit() or c.islower() for c in password):

after all, you want to check that all characters are either a digit or lowercase letters. So for all characters c, that character is c.isdigit() or c.islower(). Now an all(..) takes as input an iterable of values and checks if the truthiness of all these values is True. So from the moment there is one digit that does not satisfies our condition, the all(..) will return False.

Mind however that all(..) is True if there are no elements. Indeed if the password is the empty string, all the characters satisfy this condition, since there are no characters.

EDIT:

In case you want to check that the password contains both digits and lowercase characters, you can alter the condition to:

if all(c.isdigit() or c.islower() for c in password) and \
       any(c.isdigit() for c in password) and \
       any(c.islower() for c in password):

Now the check will only succeed if there are at least two characters in password: a lower and a digit.


问:
calling an instance by a string in c#
I am new at c# and I have a little problem completing my code, I have seen a lot of cases similar to mine, they have been solved by reflection but it didn't work with me.

I have a class which could results two strings and a double as an example
it results:

```<code>room = "bedroom";

device = "TV";

status = ON;  //on =100 double
</code>```

I have another class which is called Room that has the devices as functions of one double variable, examples :

```<code>Room bedroom = new Room();
bedroom.lights(ON);
livingroom.TV(OFF);
kitchen.lights(OFF);
</code>```

The first class could return any room or any device or any statues so there is a lot of probabilities so I want the three variables from the first class to be turned into a line of code like the examples of the other class:

A simple example for I want:

```<code>room = "bedroom";
device = "TV";
status = ON; // double ON = 100;
</code>```

to be this :

```<code>bedroom.TV(ON);
</code>```

If there is another way to do that instead of turning strings into code I don't mind ^_^

答:
I don't recommend to use your syntax. I'm not even sure if it's possible, maybe with some weird reflection stuff.
How about this syntax:

```<code>bedroom("TV", ON );
</code>```

where bedroom is an instance of a room class.
Then, your room class would contain a Dictionary<string,status>, so that you can add devices like TVs, lights, whatever you like, and set their ON/OFF status.

If your choice of possible devices is limited, e.g. only TVs and lights, then you could work with reflection, but IMO it's not worth the hassle.

Title: calling an instance by a string in c#

Body:
I am new at c# and I have a little problem completing my code, I have seen a lot of cases similar to mine, they have been solved by reflection but it didn't work with me.

I have a class which could results two strings and a double as an example
it results:

room = "bedroom";

device = "TV";

status = ON;  //on =100 double

I have another class which is called Room that has the devices as functions of one double variable, examples :

Room bedroom = new Room();
bedroom.lights(ON);
livingroom.TV(OFF);
kitchen.lights(OFF);

The first class could return any room or any device or any statues so there is a lot of probabilities so I want the three variables from the first class to be turned into a line of code like the examples of the other class:

A simple example for I want:

room = "bedroom";
device = "TV";
status = ON; // double ON = 100;

to be this :

bedroom.TV(ON);

If there is another way to do that instead of turning strings into code I don't mind ^_^

Body:
I don't recommend to use your syntax. I'm not even sure if it's possible, maybe with some weird reflection stuff.
How about this syntax:

bedroom("TV", ON );

where bedroom is an instance of a room class.
Then, your room class would contain a Dictionary<string,status>, so that you can add devices like TVs, lights, whatever you like, and set their ON/OFF status.

If your choice of possible devices is limited, e.g. only TVs and lights, then you could work with reflection, but IMO it's not worth the hassle.


问:
Group pandas DataFrame by columns and produce lists out of groups of columns
Assuming we have the following input DataFrame:

```<code>In [80]: %paste
data = {
 'Item_2_id': {0: 24, 1: 41, 2: 34},
 'Item_2_quantity': {0: 4, 1: 1, 2: 4},
 'Item_3_id': {0: 16, 1: 33, 2: 8},
 'Item_3_quantity': {0: 1, 1: 1, 2: 2},
 'customer_name': {0: 'John', 1: 'Paul', 2: 'Andrew'},
 'item_1_id': {0: 4, 1: 8, 2: 1},
 'item_1_quantity': {0: 1, 1: 3, 2: 1},
 'order_id': {0: 1, 1: 2, 2: 3}
}
cols = 'order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity'.split()

df = pd.DataFrame(data)[cols]

df
## -- End pasted text --
Out[80]:
   order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity
0         1          John          4                1         24                4         16                1
1         2          Paul          8                3         41                1         33                1
2         3        Andrew          1                1         34                4          8                2
</code>```

How can we group all id and quantity columns, so that we will get the following desired DataFrame:

```<code>In [85]: result
Out[85]:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]
</code>```

My attempts:

```<code>In [191]: id_vars = ['order_id','customer_name']

In [192]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: x.tolist())
Out[192]:
                                                 id                                       quantity
order_id customer_name
1        John           (i, t, e, m, _, 1, _, i, d)  (i, t, e, m, _, 1, _, q, u, a, n, t, i, t, y)
2        Paul           (I, t, e, m, _, 2, _, i, d)  (I, t, e, m, _, 2, _, q, u, a, n, t, i, t, y)
3        Andrew         (I, t, e, m, _, 3, _, i, d)  (I, t, e, m, _, 3, _, q, u, a, n, t, i, t, y)
</code>```

if i just print it - it works properly:

```<code>In [193]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: print(x.tolist()))
[4, 24, 16]
[8, 41, 33]
[1, 34, 8]
[1, 4, 1]
[3, 1, 1]
[1, 4, 2]
Out[193]:
                          id quantity
order_id customer_name
1        John           None     None
2        Paul           None     None
3        Andrew         None     None
</code>```

PS actually I came to that problem when I was trying to answer another question and i found another solution, but I feel like there must be much more elegant solution, which is using something like:

```<code>df.groupby(..., axis=1).agg(...)
</code>```

or

```<code>df.groupby(..., axis=1).apply(...)
</code>```

答:
using filter

```<code>df[['order_id', 'customer_name']].assign(
    id=df.filter(regex='[Ii]tem_\d+_id').values.tolist(),
    quantity=df.filter(regex='[Ii]tem_\d+_quantity').values.tolist()
)

   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]
</code>```

Body:
Assuming we have the following input DataFrame:

In [80]: %paste
data = {
 'Item_2_id': {0: 24, 1: 41, 2: 34},
 'Item_2_quantity': {0: 4, 1: 1, 2: 4},
 'Item_3_id': {0: 16, 1: 33, 2: 8},
 'Item_3_quantity': {0: 1, 1: 1, 2: 2},
 'customer_name': {0: 'John', 1: 'Paul', 2: 'Andrew'},
 'item_1_id': {0: 4, 1: 8, 2: 1},
 'item_1_quantity': {0: 1, 1: 3, 2: 1},
 'order_id': {0: 1, 1: 2, 2: 3}
}
cols = 'order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity'.split()

df = pd.DataFrame(data)[cols]

df
## -- End pasted text --
Out[80]:
   order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity
0         1          John          4                1         24                4         16                1
1         2          Paul          8                3         41                1         33                1
2         3        Andrew          1                1         34                4          8                2

How can we group all id and quantity columns, so that we will get the following desired DataFrame:

In [85]: result
Out[85]:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]

My attempts:

In [191]: id_vars = ['order_id','customer_name']

In [192]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: x.tolist())
Out[192]:
                                                 id                                       quantity
order_id customer_name
1        John           (i, t, e, m, _, 1, _, i, d)  (i, t, e, m, _, 1, _, q, u, a, n, t, i, t, y)
2        Paul           (I, t, e, m, _, 2, _, i, d)  (I, t, e, m, _, 2, _, q, u, a, n, t, i, t, y)
3        Andrew         (I, t, e, m, _, 3, _, i, d)  (I, t, e, m, _, 3, _, q, u, a, n, t, i, t, y)

if i just print it - it works properly:

In [193]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: print(x.tolist()))
[4, 24, 16]
[8, 41, 33]
[1, 34, 8]
[1, 4, 1]
[3, 1, 1]
[1, 4, 2]
Out[193]:
                          id quantity
order_id customer_name
1        John           None     None
2        Paul           None     None
3        Andrew         None     None

PS actually I came to that problem when I was trying to answer another question and i found another solution, but I feel like there must be much more elegant solution, which is using something like:

df.groupby(..., axis=1).agg(...)

or

df.groupby(..., axis=1).apply(...)

Body:
using filter

df[['order_id', 'customer_name']].assign(
    id=df.filter(regex='[Ii]tem_\d+_id').values.tolist(),
    quantity=df.filter(regex='[Ii]tem_\d+_quantity').values.tolist()
)

   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]


问:
Using GeoMesa Native API to insert data in accumulo
I am trying to insert and read data from accumulo storage using GeoMesa Native API. I have created a class file to use geomesa accumulo storage natively. Here is my java code :

```<code>package org.locationtech.geomesa.api;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.mock.MockInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.security.Authorizations;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.AttributeTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.junit.Assert;
import org.junit.Test;
import org.locationtech.geomesa.accumulo.data.AccumuloDataStore;
import org.locationtech.geomesa.accumulo.index.AccumuloFeatureIndex;
import org.locationtech.geomesa.accumulo.index.AccumuloFeatureIndex$;
import org.locationtech.geomesa.utils.index.IndexMode$;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.filter.FilterFactory2;

import javax.annotation.Nullable;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

public class WorkerBeta {
    public static void main(String[] args){
        try {
            DomainObjectValueSerializer dovs = new DomainObjectValueSerializer();
            final GeoMesaIndex<DomainObject> index = AccumuloGeoMesaIndex.buildWithView(
            "aj_v14",
            "localhost:2181",
            "hps",
            "root", "9869547580",
            false,
            dovs,
            new SimpleFeatureView<DomainObject>() {
              AttributeTypeBuilder atb = new AttributeTypeBuilder();
              private List<AttributeDescriptor> attributeDescriptors =
                Lists.newArrayList(atb.binding(Integer.class).buildDescriptor("rId")
                    , atb.binding(String.class).buildDescriptor("dId")
                    , atb.binding(Integer.class).buildDescriptor("s")
                    , atb.binding(Integer.class).buildDescriptor("a")
                    , atb.binding(Integer.class).buildDescriptor("e")
                );
              @Override
              public void populate(SimpleFeature f, DomainObject domainObject, String id, byte[] payload, Geometry geom, Date dtg) {
                f.setAttribute("rId", domainObject.rideId);
                f.setAttribute("dId", domainObject.deviceId);
                f.setAttribute("s", domainObject.speed);
                f.setAttribute("a", domainObject.angle);
                f.setAttribute("e", domainObject.error);
              }

              @Override
              public List<AttributeDescriptor> getExtraAttributes() {
                return attributeDescriptors;
              }
            }
        );

        //Inserting
        final DomainObject one = new DomainObject(1, "AJJASsP", 12, 40, 1);
        final GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();
        System.out.println(index.insert(
                one,
                gf.createPoint(new Coordinate(-74.0, 34.0)),
                date("2017-03-31T01:15:00.000Z")
            ));

            //Read
            GeoMesaQuery q = GeoMesaQuery.GeoMesaQueryBuilder.builder()
                .within(-90.0, -180, 90, 180)
                .during(date("2017-01-01T00:00:00.000Z"), date("2017-04-01T00:00:00.000Z"))
                .build();
            Iterable<DomainObject> results = index.query(q);
            int counter = 0;
            for(DomainObject dm : results){
                counter += 1;
                System.out.println("result counter: " + counter);
                dovs.toBytes(dm);
            }
        }
        catch (Exception ex){
      ex.printStackTrace();
        }
    }
    public static class DomainObject {
      public final int rideId;
      public final String deviceId;
      public final int angle;
      public final int speed;
      public final int error;

      public DomainObject(int rideId, String deviceId, int angle, int speed, int error) {
          this.rideId = rideId;
          this.deviceId = deviceId;
          this.angle = angle;
          this.speed = speed;
          this.error = error;
      }
    }
    public static class DomainObjectValueSerializer implements ValueSerializer<DomainObject> {
        public static final Gson gson = new Gson();
        @Override
        public byte[] toBytes(DomainObject o) {
            return gson.toJson(o).getBytes();
        }
        @Override
        public DomainObject fromBytes(byte[] bytes) {
            return gson.fromJson(new String(bytes), DomainObject.class);
        }
    }
    public static Date date(String s) {
        return Date.from(ZonedDateTime.parse(s).toInstant());
    }
}
</code>```

Logs for command is :

```<code>suresh@hpss-MacBook-Air:~/GeomesaAccumuloNativeClient $ java -cp target/geomesa-native-api_2.11-1.3.2-SNAPSHOT.jar org.locationtech.geomesa.api.WorkerBeta
WARNING: org.apache.hadoop.metrics.jvm.EventCounter is deprecated. Please use org.apache.hadoop.log.metrics.EventCounter in all the log4j.properties files.
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:host.name=192.168.1.103
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.version=1.8.0_121
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.vendor=Oracle Corporation
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.home=/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.class.path=target/geomesa-native-api_2.11-1.3.2-SNAPSHOT.jar
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.library.path=/Users/suresh/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.io.tmpdir=/var/folders/yk/h858t8h57nz42t6t4nqmwhcc0000gp/T/
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.compiler=<NA>
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:os.name=Mac OS X
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:os.arch=x86_64
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:os.version=10.12.3
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:user.name=suresh
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:user.home=/Users/suresh
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:user.dir=/Users/suresh/GeomesaAccumuloNativeClient
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Initiating client connection, connectString=localhost:2181 sessionTimeout=30000 watcher=org.apache.accumulo.fate.zookeeper.ZooSession$ZooWatcher@73eb439a
17/04/01 15:11:48 INFO zookeeper.ClientCnxn: Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
17/04/01 15:11:48 INFO zookeeper.ClientCnxn: Socket connection established to localhost/0:0:0:0:0:0:0:1:2181, initiating session
17/04/01 15:11:48 INFO zookeeper.ClientCnxn: Session establishment complete on server localhost/0:0:0:0:0:0:0:1:2181, sessionid = 0x15aea0c41f601a1, negotiated timeout = 30000
17/04/01 15:11:52 WARN data.AccumuloDataStore: Configured server-side iterators do not match client version - client version: 1.3.2-SNAPSHOT, server version: 1.3.0
50fa12fb-11f8-4776-bb35-95b32da9225d
[]
</code>```

But when i try to verify the inserted record, I am unable to find any specific entries in created related to data inserted in Tables of accumulo web interface. Here is the screen shot for the accumulo tables. Please correct me if I am missing anything. Tons of thanks in advance.

答:
Two quick notes:

Your type doesn't haven't a field named 'dtg' and GeoMesaQuery assumes one.  To work around this easily, you can use 'GeoMesaQuery.GeoMesaQueryBuilder.builder().include().build()'.  Long term, the native api could use some improvements to make it easy do to what you want fluently.

To see if the records were written to Accumulo, you can use the Accumulo shell and scan the individual tables.  If there is nothing in the tables, it might be worth debugging this code.

Body:
I am trying to insert and read data from accumulo storage using GeoMesa Native API. I have created a class file to use geomesa accumulo storage natively. Here is my java code :

package org.locationtech.geomesa.api;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.mock.MockInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.security.Authorizations;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.AttributeTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.junit.Assert;
import org.junit.Test;
import org.locationtech.geomesa.accumulo.data.AccumuloDataStore;
import org.locationtech.geomesa.accumulo.index.AccumuloFeatureIndex;
import org.locationtech.geomesa.accumulo.index.AccumuloFeatureIndex$;
import org.locationtech.geomesa.utils.index.IndexMode$;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.filter.FilterFactory2;

import javax.annotation.Nullable;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

public class WorkerBeta {
    public static void main(String[] args){
        try {
            DomainObjectValueSerializer dovs = new DomainObjectValueSerializer();
            final GeoMesaIndex<DomainObject> index = AccumuloGeoMesaIndex.buildWithView(
            "aj_v14",
            "localhost:2181",
            "hps",
            "root", "9869547580",
            false,
            dovs,
            new SimpleFeatureView<DomainObject>() {
              AttributeTypeBuilder atb = new AttributeTypeBuilder();
              private List<AttributeDescriptor> attributeDescriptors =
                Lists.newArrayList(atb.binding(Integer.class).buildDescriptor("rId")
                    , atb.binding(String.class).buildDescriptor("dId")
                    , atb.binding(Integer.class).buildDescriptor("s")
                    , atb.binding(Integer.class).buildDescriptor("a")
                    , atb.binding(Integer.class).buildDescriptor("e")
                );
              @Override
              public void populate(SimpleFeature f, DomainObject domainObject, String id, byte[] payload, Geometry geom, Date dtg) {
                f.setAttribute("rId", domainObject.rideId);
                f.setAttribute("dId", domainObject.deviceId);
                f.setAttribute("s", domainObject.speed);
                f.setAttribute("a", domainObject.angle);
                f.setAttribute("e", domainObject.error);
              }

              @Override
              public List<AttributeDescriptor> getExtraAttributes() {
                return attributeDescriptors;
              }
            }
        );

        //Inserting
        final DomainObject one = new DomainObject(1, "AJJASsP", 12, 40, 1);
        final GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();
        System.out.println(index.insert(
                one,
                gf.createPoint(new Coordinate(-74.0, 34.0)),
                date("2017-03-31T01:15:00.000Z")
            ));

            //Read
            GeoMesaQuery q = GeoMesaQuery.GeoMesaQueryBuilder.builder()
                .within(-90.0, -180, 90, 180)
                .during(date("2017-01-01T00:00:00.000Z"), date("2017-04-01T00:00:00.000Z"))
                .build();
            Iterable<DomainObject> results = index.query(q);
            int counter = 0;
            for(DomainObject dm : results){
                counter += 1;
                System.out.println("result counter: " + counter);
                dovs.toBytes(dm);
            }
        }
        catch (Exception ex){
      ex.printStackTrace();
        }
    }
    public static class DomainObject {
      public final int rideId;
      public final String deviceId;
      public final int angle;
      public final int speed;
      public final int error;

      public DomainObject(int rideId, String deviceId, int angle, int speed, int error) {
          this.rideId = rideId;
          this.deviceId = deviceId;
          this.angle = angle;
          this.speed = speed;
          this.error = error;
      }
    }
    public static class DomainObjectValueSerializer implements ValueSerializer<DomainObject> {
        public static final Gson gson = new Gson();
        @Override
        public byte[] toBytes(DomainObject o) {
            return gson.toJson(o).getBytes();
        }
        @Override
        public DomainObject fromBytes(byte[] bytes) {
            return gson.fromJson(new String(bytes), DomainObject.class);
        }
    }
    public static Date date(String s) {
        return Date.from(ZonedDateTime.parse(s).toInstant());
    }
}

Logs for command is :

suresh@hpss-MacBook-Air:~/GeomesaAccumuloNativeClient $ java -cp target/geomesa-native-api_2.11-1.3.2-SNAPSHOT.jar org.locationtech.geomesa.api.WorkerBeta
WARNING: org.apache.hadoop.metrics.jvm.EventCounter is deprecated. Please use org.apache.hadoop.log.metrics.EventCounter in all the log4j.properties files.
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:host.name=192.168.1.103
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.version=1.8.0_121
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.vendor=Oracle Corporation
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.home=/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.class.path=target/geomesa-native-api_2.11-1.3.2-SNAPSHOT.jar
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.library.path=/Users/suresh/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.io.tmpdir=/var/folders/yk/h858t8h57nz42t6t4nqmwhcc0000gp/T/
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:java.compiler=<NA>
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:os.name=Mac OS X
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:os.arch=x86_64
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:os.version=10.12.3
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:user.name=suresh
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:user.home=/Users/suresh
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Client environment:user.dir=/Users/suresh/GeomesaAccumuloNativeClient
17/04/01 15:11:48 INFO zookeeper.ZooKeeper: Initiating client connection, connectString=localhost:2181 sessionTimeout=30000 watcher=org.apache.accumulo.fate.zookeeper.ZooSession$ZooWatcher@73eb439a
17/04/01 15:11:48 INFO zookeeper.ClientCnxn: Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
17/04/01 15:11:48 INFO zookeeper.ClientCnxn: Socket connection established to localhost/0:0:0:0:0:0:0:1:2181, initiating session
17/04/01 15:11:48 INFO zookeeper.ClientCnxn: Session establishment complete on server localhost/0:0:0:0:0:0:0:1:2181, sessionid = 0x15aea0c41f601a1, negotiated timeout = 30000
17/04/01 15:11:52 WARN data.AccumuloDataStore: Configured server-side iterators do not match client version - client version: 1.3.2-SNAPSHOT, server version: 1.3.0
50fa12fb-11f8-4776-bb35-95b32da9225d
[]

But when i try to verify the inserted record, I am unable to find any specific entries in created related to data inserted in Tables of accumulo web interface. Here is the screen shot for the accumulo tables. Please correct me if I am missing anything. Tons of thanks in advance.


答:
var x = 'x';
var arr= [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ];

var working = arr.reduce(function(acc, current) {
  (acc[current[2]] || (acc[current[2]] = [])).push(current);
  return acc;
}, {});

var result = Object.keys(working).map(function(k) { return working[k] });

console.log(JSON.stringify(result)); // stringified just to avoid scrolling```

Title: Group items in multidimensional array by same value at index


问:
Number of possible paths
Why there are 2^k possible paths from S to T in the following graph.
Can anyone explain.
Note:all directions are from left to right in figure .

答:
For every pair of parallel paths you can only select one of them at a time.

 So there are k such pairs of parallel paths.
Therefore, total number of combinations are: 2*2*2...k times= 2k

Title: Number of possible paths


问:
How do I check if a string contains ALL letters of the alphabet in python?
I am trying to write a python program that checks if a given string is a pangram - contains all letters of the alphabet.

Therefore, "We promptly judged antique ivory buckles for the next prize" should return True while any string that does not contain every letter of the alphabet at least once should return False.

I believe I should be using RegEx for this one, but I'm not sure how. It should look similar to this:

```<code>import sys
import re

input_string_array = sys.stdin.readlines()
input_string = input_string_array[0]

if (re.search('string contains every letter of the alphabet',input_string):
    return True
else:
    return False
</code>```

答:
A pangram is a function that contains at least each letter of the alphabet.
I have tried in this way:

```<code>def pangram():
n = str(input('give me a word to check if it is a pangram:\n'))
n = n.lower()
n = n.replace(' ','')
if not isinstance(n, str):
    return n, False
elif set(n) >= set('abcdefghijklmnopqrstuvxywz'):
    return n, True
else:
    return n, False
</code>```

The function isinstance(n, str) checks if n is a string. The function set() gives us a set. For example set('penny') returns {'y', 'e', 'p', 'n'}... as you see it is a set without the repeated letters.

Body:
I am trying to write a python program that checks if a given string is a pangram - contains all letters of the alphabet.

Therefore, "We promptly judged antique ivory buckles for the next prize" should return True while any string that does not contain every letter of the alphabet at least once should return False.

I believe I should be using RegEx for this one, but I'm not sure how. It should look similar to this:

import sys
import re

input_string_array = sys.stdin.readlines()
input_string = input_string_array[0]

if (re.search('string contains every letter of the alphabet',input_string):
    return True
else:
    return False

Body:
A pangram is a function that contains at least each letter of the alphabet.
I have tried in this way:

def pangram():
n = str(input('give me a word to check if it is a pangram:\n'))
n = n.lower()
n = n.replace(' ','')
if not isinstance(n, str):
    return n, False
elif set(n) >= set('abcdefghijklmnopqrstuvxywz'):
    return n, True
else:
    return n, False

The function isinstance(n, str) checks if n is a string. The function set() gives us a set. For example set('penny') returns {'y', 'e', 'p', 'n'}... as you see it is a set without the repeated letters.


问:
doctrine mongodb. can not set array value to a field
we want to update many documents and set an array value [1, 2, 3] for a field.

finally we've come up with this solution:

```<code>$qb->updateMany()->field('targetGeo')->addToSet($qb->expr()->each([1,2,3]));
</code>```

however, the generated query makes mongo fail:

[MongoWriteConcernException] localhost:27017: The argument to $each in $addToSet must be an array but it was of type NumberLong64

debugging query gives us:

```<code>Array (
    [type] => 5
    [multiple] => 1
    [query] => Array
        (
        )

    [newObj] => Array
        (
            [$addToSet] => Array
                (
                    [targetGeo] => Array
                        (
                            [$each] => 1
                        )

                )

        )

)
</code>```

apparently, it's this [$each] => 1 which makes it fail.

We can't figure out what is going wrong here. Is it a bug in query builder or we are not using it the right way?

we are using doctrine-mongodb 1.4 and doctrine-odm 1.1.3

update: we've managed to get it working with the following change in DocumentPersister.php (see added '$each' for in_array test):

答: Turns out to be a bug in doctrine: https://github.com/doctrine/mongodb-odm/issues/1575</p>

Body:
we want to update many documents and set an array value [1, 2, 3] for a field.

finally we've come up with this solution:

$qb->updateMany()->field('targetGeo')->addToSet($qb->expr()->each([1,2,3]));

however, the generated query makes mongo fail:

[MongoWriteConcernException] localhost:27017: The argument to $each in $addToSet must be an array but it was of type NumberLong64

debugging query gives us:

Array (
    [type] => 5
    [multiple] => 1
    [query] => Array
        (
        )

    [newObj] => Array
        (
            [$addToSet] => Array
                (
                    [targetGeo] => Array
                        (
                            [$each] => 1
                        )

                )

        )

)

apparently, it's this [$each] => 1 which makes it fail.

We can't figure out what is going wrong here. Is it a bug in query builder or we are not using it the right way?

we are using doctrine-mongodb 1.4 and doctrine-odm 1.1.3

update: we've managed to get it working with the following change in DocumentPersister.php (see added '$each' for in_array test):


问:
Cannot automatically bind the navigation property 'Players' on entity type 'Data.Team' for the source entity set 'Teams'
I'm using EF6 Code First.

I have the following classes:

```<code>public class Player
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Player name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public int TeamClubId { get; set; }

    [ForeignKey("TeamClubId")]
    public virtual Team Club { get; set; }

    [Required]
    public int TeamNationalId { get; set; }

    [ForeignKey("TeamNationalId")]
    public virtual Team National { get; set; }

}

public class Team
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public TeamType Type { get; set; }

    public virtual ICollection<Player> Players { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
}

public class Tournament
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Tournament name must be at least 2 characters length")]
    public string Name { get; set; }

    public int Year { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public ICollection<Match> Matches { get; set; }

}
</code>```

In the DBContext class I have:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //player - national team relations
    modelBuilder.Entity<Player>()
        .HasRequired<Team>(p => p.National)
        .WithMany()
        .WillCascadeOnDelete(false);

    //player - club team relations
    modelBuilder.Entity<Player>()
        .HasRequired<Team>(p => p.Club)
        .WithMany()
        .WillCascadeOnDelete(false);

    //match - home team relations
    modelBuilder.Entity<Match>()
        .HasRequired<Team>(p => p.HomeTeam)
        .WithMany()
        .WillCascadeOnDelete(false);

    //match - away team relations
    modelBuilder.Entity<Match>()
        .HasRequired<Team>(p => p.AwayTeam)
        .WithMany()
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}
</code>```

I get the following error when trying to connect via OData:

Cannot automatically bind the navigation property 'Players' on entity type 'Data.Team' for the source entity set 'Teams' because there are two or more matching target entity sets. The matching entity sets are: Players, Tournaments.

[NotSupportedException: Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.Http.OData.Builder.EntitySetConfiguration.FindBinding(NavigationPropertyConfiguration
  navigationConfiguration, Boolean autoCreate) +736

  System.Web.Http.OData.Builder.EdmModelHelperMethods.AddNavigationBindings(EntitySetConfiguration
  configuration, EdmEntitySet entitySet, EntitySetLinkBuilderAnnotation
  linkBuilder, ODataModelBuilder builder, Dictionary2 edmTypeMap,
  Dictionary2 edmEntitySetMap) +391

  System.Web.Http.OData.Builder.EdmModelHelperMethods.AddEntitySets(EdmModel
  model, ODataModelBuilder builder, EdmEntityContainer container,
  Dictionary2 edmTypeMap) +635

  System.Web.Http.OData.Builder.EdmModelHelperMethods.BuildEdmModel(ODataModelBuilder
  builder) +200

  System.Web.Http.OData.Builder.ODataConventionModelBuilder.GetEdmModel()
  +664    ODataAPI.WebApiConfig.Register(HttpConfiguration config) +221    System.Web.Http.GlobalConfiguration.Configure(Action1
  configurationCallback) +65

[HttpException (0x80004005): Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext
  context, HttpApplication app) +12582201

  System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
  appContext, HttpContext context, MethodInfo[] handlers) +175

  System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
  MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304

  System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
  appContext, HttpContext context) +404

  System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
  appContext) +475

[HttpException (0x80004005): Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12599232
  System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
  +159    System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
  wr, HttpContext context) +12438981

What's my problem?

Thanks

答:
What you are in effect describing is a Many:Many relationship between Player and Team. Even though you want to specify a 1:2 relationship (player:team) the EntityFramework works with 1:1-0, 1:1, 1:many. 2 needs to be many to work properly with EF, you can use business logic to constrain it to just two if that is neccesary.

Why is this an issue? EF requires that for each Navigation Property there is a single Collection Property on the Principal Entity... so that it can support the convention of automatically setting the ForeignKey property when an entity is added to the collection.

In your expected model, say you want to add a Player to the Team with the following code, how will EF know which of the team Ids to set on player record?

```<code>Player newPlayer = new Player();
Team team = db.Teams.FirstOrDefault(t => t.Id == 1); // Just illustrating that team is an existing data entity;
team.Players.Add(newPlayer);
// should this set TeamNationalId = 1
// or TeamClubId = 1
</code>```

Just because you might not want to use the code above to add the players to a team does not mean that EF will simply ignore the convention.

What are your options:

Separate Team into 2 tables, NationalTeam and ClubTeam

Split the navigation property into two properties, NationalPlayers, ClubPlayers

Add an intermediary table TeamPlayer

I don't want you to consider option 1, and I don't think that you want to either, so I'll skip past that one...

Then there is another issue... you have a similar relationship with Team and Match, a Match has a HomeTeam and an AwayTeam, only in Match it probably bares more resemblance to reality that a Team has a Collection of HomeMatches and AwayMatches but it is essentially the same situation with different data types.

So of the 3 options above, here is some code for option 2: (thanks to E-Bat's answer for attribute notation of Inverse Properties)

```<code>public class Team
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public TeamType Type { get; set; }

    //public virtual ICollection<Player> Players { get; set; }
    [InverseProperty("Club")]
    public virtual ICollection<Player> ClubPlayers { get; set; }
    [InverseProperty("National")]
    public virtual ICollection<Player> NationalPlayers { get; set; }

    //public virtual ICollection<Match> Matches { get; set; }
    [InverseProperty("HomeTeam")]
    public virtual ICollection<Match> HomeMatches { get; set; }
    [InverseProperty("AwayTeam")]
    public virtual ICollection<Match> AwayMatches { get; set; }

}
</code>```

Now if that is an issue for some of your business logic code, the following class definition might help, by adding the Players and Matches properties to Team it might simplify processing, note that you also have to initialize the collections in the constructor to avoid errors, but you would do this anyway for navigation properties to avoid issues during serialization:

```<code>public class Team
{
    public Team()
    {
        ClubPlayers = new HashSet<Player>();
        NationalPlayers = new HashSet<Player>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public TeamType Type { get; set; }

    [InverseProperty("Club")]
    public virtual ICollection<Player> ClubPlayers { get; set; }
    [InverseProperty("National")]
    public virtual ICollection<Player> NationalPlayers { get; set; }

    public virtual IEnumerable<Player> Players
    {
        get
        {
            return ClubPlayers.Union(NationalPlayers);
        }
    }

    [InverseProperty("HomeTeam")]
    public virtual ICollection<Match> HomeMatches { get; set; }
    [InverseProperty("AwayTeam")]
    public virtual ICollection<Match> AwayMatches { get; set; }
    public virtual IEnumerable<Match> Matches
    {
        get
        {
            return HomeMatches.Union(AwayMatches);
        }
    }

}
</code>```

Lets consider Option 3. An Intermediary table of TeamPlayers. This will allow you to add more metadata about the relationship, such as Sign/from date and end date. Maybe they are a temporary transfer or loan player?

Note that the above reasons do not really apply for option 3 in the context of the Matches relationship, a match will always have exactly 2 teams, and these teams wont change over time. Option 2 is in IMO the best one for the matches scenario.

You already have Year in the matches, which means you want to track and keep data over many seasons, there is a good probability that over the years players will change teams, your current model will not support this, for instance to run a report on the players in a grand final 5 years ago will either show too many or not enough players depending on player attrition rates... it's just a thought. Option 3 opens up some new possibilities for future functionality and reporting.

Body:
I'm using EF6 Code First.

I have the following classes:

public class Player
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Player name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public int TeamClubId { get; set; }

    [ForeignKey("TeamClubId")]
    public virtual Team Club { get; set; }

    [Required]
    public int TeamNationalId { get; set; }

    [ForeignKey("TeamNationalId")]
    public virtual Team National { get; set; }

}

public class Team
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public TeamType Type { get; set; }

    public virtual ICollection<Player> Players { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
}

public class Tournament
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Tournament name must be at least 2 characters length")]
    public string Name { get; set; }

    public int Year { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public ICollection<Match> Matches { get; set; }

}

In the DBContext class I have:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //player - national team relations
    modelBuilder.Entity<Player>()
        .HasRequired<Team>(p => p.National)
        .WithMany()
        .WillCascadeOnDelete(false);

    //player - club team relations
    modelBuilder.Entity<Player>()
        .HasRequired<Team>(p => p.Club)
        .WithMany()
        .WillCascadeOnDelete(false);

    //match - home team relations
    modelBuilder.Entity<Match>()
        .HasRequired<Team>(p => p.HomeTeam)
        .WithMany()
        .WillCascadeOnDelete(false);

    //match - away team relations
    modelBuilder.Entity<Match>()
        .HasRequired<Team>(p => p.AwayTeam)
        .WithMany()
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}

I get the following error when trying to connect via OData:

Cannot automatically bind the navigation property 'Players' on entity type 'Data.Team' for the source entity set 'Teams' because there are two or more matching target entity sets. The matching entity sets are: Players, Tournaments.

[NotSupportedException: Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.Http.OData.Builder.EntitySetConfiguration.FindBinding(NavigationPropertyConfiguration
  navigationConfiguration, Boolean autoCreate) +736

  System.Web.Http.OData.Builder.EdmModelHelperMethods.AddNavigationBindings(EntitySetConfiguration
  configuration, EdmEntitySet entitySet, EntitySetLinkBuilderAnnotation
  linkBuilder, ODataModelBuilder builder, Dictionary2 edmTypeMap,
  Dictionary2 edmEntitySetMap) +391

  System.Web.Http.OData.Builder.EdmModelHelperMethods.AddEntitySets(EdmModel
  model, ODataModelBuilder builder, EdmEntityContainer container,
  Dictionary2 edmTypeMap) +635

  System.Web.Http.OData.Builder.EdmModelHelperMethods.BuildEdmModel(ODataModelBuilder
  builder) +200

  System.Web.Http.OData.Builder.ODataConventionModelBuilder.GetEdmModel()
  +664    ODataAPI.WebApiConfig.Register(HttpConfiguration config) +221    System.Web.Http.GlobalConfiguration.Configure(Action1
  configurationCallback) +65

[HttpException (0x80004005): Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext
  context, HttpApplication app) +12582201

  System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
  appContext, HttpContext context, MethodInfo[] handlers) +175

  System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
  MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304

  System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
  appContext, HttpContext context) +404

  System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
  appContext) +475

[HttpException (0x80004005): Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12599232
  System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
  +159    System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
  wr, HttpContext context) +12438981

What's my problem?

Thanks

Body:
What you are in effect describing is a Many:Many relationship between Player and Team. Even though you want to specify a 1:2 relationship (player:team) the EntityFramework works with 1:1-0, 1:1, 1:many. 2 needs to be many to work properly with EF, you can use business logic to constrain it to just two if that is neccesary.

Why is this an issue? EF requires that for each Navigation Property there is a single Collection Property on the Principal Entity... so that it can support the convention of automatically setting the ForeignKey property when an entity is added to the collection.

In your expected model, say you want to add a Player to the Team with the following code, how will EF know which of the team Ids to set on player record?

Player newPlayer = new Player();
Team team = db.Teams.FirstOrDefault(t => t.Id == 1); // Just illustrating that team is an existing data entity;
team.Players.Add(newPlayer);
// should this set TeamNationalId = 1
// or TeamClubId = 1

Just because you might not want to use the code above to add the players to a team does not mean that EF will simply ignore the convention.

What are your options:

Separate Team into 2 tables, NationalTeam and ClubTeam

Split the navigation property into two properties, NationalPlayers, ClubPlayers

Add an intermediary table TeamPlayer

I don't want you to consider option 1, and I don't think that you want to either, so I'll skip past that one...

Then there is another issue... you have a similar relationship with Team and Match, a Match has a HomeTeam and an AwayTeam, only in Match it probably bares more resemblance to reality that a Team has a Collection of HomeMatches and AwayMatches but it is essentially the same situation with different data types.

So of the 3 options above, here is some code for option 2: (thanks to E-Bat's answer for attribute notation of Inverse Properties)

public class Team
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public TeamType Type { get; set; }

    //public virtual ICollection<Player> Players { get; set; }
    [InverseProperty("Club")]
    public virtual ICollection<Player> ClubPlayers { get; set; }
    [InverseProperty("National")]
    public virtual ICollection<Player> NationalPlayers { get; set; }

    //public virtual ICollection<Match> Matches { get; set; }
    [InverseProperty("HomeTeam")]
    public virtual ICollection<Match> HomeMatches { get; set; }
    [InverseProperty("AwayTeam")]
    public virtual ICollection<Match> AwayMatches { get; set; }

}

Now if that is an issue for some of your business logic code, the following class definition might help, by adding the Players and Matches properties to Team it might simplify processing, note that you also have to initialize the collections in the constructor to avoid errors, but you would do this anyway for navigation properties to avoid issues during serialization:

public class Team
{
    public Team()
    {
        ClubPlayers = new HashSet<Player>();
        NationalPlayers = new HashSet<Player>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public TeamType Type { get; set; }

    [InverseProperty("Club")]
    public virtual ICollection<Player> ClubPlayers { get; set; }
    [InverseProperty("National")]
    public virtual ICollection<Player> NationalPlayers { get; set; }

    public virtual IEnumerable<Player> Players
    {
        get
        {
            return ClubPlayers.Union(NationalPlayers);
        }
    }

    [InverseProperty("HomeTeam")]
    public virtual ICollection<Match> HomeMatches { get; set; }
    [InverseProperty("AwayTeam")]
    public virtual ICollection<Match> AwayMatches { get; set; }
    public virtual IEnumerable<Match> Matches
    {
        get
        {
            return HomeMatches.Union(AwayMatches);
        }
    }

}

Lets consider Option 3. An Intermediary table of TeamPlayers. This will allow you to add more metadata about the relationship, such as Sign/from date and end date. Maybe they are a temporary transfer or loan player?

Note that the above reasons do not really apply for option 3 in the context of the Matches relationship, a match will always have exactly 2 teams, and these teams wont change over time. Option 2 is in IMO the best one for the matches scenario.

You already have Year in the matches, which means you want to track and keep data over many seasons, there is a good probability that over the years players will change teams, your current model will not support this, for instance to run a report on the players in a grand final 5 years ago will either show too many or not enough players depending on player attrition rates... it's just a thought. Option 3 opens up some new possibilities for future functionality and reporting.


问:
How to access static methode when its in class
Here I write some code in static methode which is in class file please Help me how can i create instance of static class</p>

```<code>public class ConnectionString
    {

       public static void CreateCommand(string querystring, string connectionString)
        {
           using(SqlConnection cn = new SqlConnection(connectionString))
           {
               SqlCommand cmd = new SqlCommand(querystring, cn);
               cmd.Connection.Open();
               cmd.ExecuteNonQuery();
           }
        }

    }
</code>```

答:
Your ConnectionString class can be refactored to implement an interface like this:

```<code>  public interface IDataAccess
    {
        void CreateCommand(string querystring, string connectionString);
    }
</code>```

this interface allows us to inject its implementation in the controller  that you mentioned in the comments. So your ConnectionString class (renamed to more meaningful name DataAccess) should look like this:

```<code> public class DataAccess : IDataAccess
    {

        public void CreateCommand(string querystring, string connectionString)
        {
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();
                using (SqlCommand cmd = new SqlCommand(querystring, cn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
</code>```

then in your controller / client class you can have the concrete implementation injected at the run time..

```<code>public class DataController : Controller
{
    private readonly IDataAccess dataAccess;
    public DataController(IDataAccess dataAcces)
    {
        this.dataAccess = dataAcces;
    }

    public ActionResult ShowData()
    {
        string querystring = "you t-sql query";
        string connectionString = "<you sql connection string>";

        this.dataAccess.CreateCommand(querystring, connectionString);

        return this.View();
    }
}
</code>```

If you are using MVC and dont know how to resolve the dependencies then refer to this article

Alternatively you can just new up the instance of DataAccess class like this:

```<code>public class DataController : Controller
    {
        private readonly IDataAccess dataAccess;
        public DataController()
        {
            this.dataAccess = new DataAccess();
        }

        public ActionResult ShowData()
        {
            string querystring = "you t-sql query";
            string connectionString = "<you sql connection string>";

            this.dataAccess.CreateCommand(querystring, connectionString);

            return this.View();
        }
    }
</code>```

I will not recommend this approach as it wont be possible to unit test it.

Hope this helps!

Body:
Here I write some code in static methode which is in class file please Help me how can i create instance of static class

public class ConnectionString
    {

       public static void CreateCommand(string querystring, string connectionString)
        {
           using(SqlConnection cn = new SqlConnection(connectionString))
           {
               SqlCommand cmd = new SqlCommand(querystring, cn);
               cmd.Connection.Open();
               cmd.ExecuteNonQuery();
           }
        }

    }

Body:
Your ConnectionString class can be refactored to implement an interface like this:

  public interface IDataAccess
    {
        void CreateCommand(string querystring, string connectionString);
    }

this interface allows us to inject its implementation in the controller  that you mentioned in the comments. So your ConnectionString class (renamed to more meaningful name DataAccess) should look like this:

 public class DataAccess : IDataAccess
    {

        public void CreateCommand(string querystring, string connectionString)
        {
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();
                using (SqlCommand cmd = new SqlCommand(querystring, cn))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }

then in your controller / client class you can have the concrete implementation injected at the run time..

public class DataController : Controller
{
    private readonly IDataAccess dataAccess;
    public DataController(IDataAccess dataAcces)
    {
        this.dataAccess = dataAcces;
    }

    public ActionResult ShowData()
    {
        string querystring = "you t-sql query";
        string connectionString = "<you sql connection string>";

        this.dataAccess.CreateCommand(querystring, connectionString);

        return this.View();
    }
}

If you are using MVC and dont know how to resolve the dependencies then refer to this article

Alternatively you can just new up the instance of DataAccess class like this:

public class DataController : Controller
    {
        private readonly IDataAccess dataAccess;
        public DataController()
        {
            this.dataAccess = new DataAccess();
        }

        public ActionResult ShowData()
        {
            string querystring = "you t-sql query";
            string connectionString = "<you sql connection string>";

            this.dataAccess.CreateCommand(querystring, connectionString);

            return this.View();
        }
    }

I will not recommend this approach as it wont be possible to unit test it.

Hope this helps!


问:
react-router withRouter does not provide props in mapStateToProps?
I'm currently facing a weird issue where the HOC withRouter provided by react-router does not pass on the props to the mapStateToProps function. Am I doing it wrong here?

```<code>import React, { Component } from 'react';
import { Link, withRouter } from 'react-router';
import { connect } from 'react-redux';

class ThisClass extends Component {
    render() {
        console.log(this.props.router); // Returns object with router keys (params, router, go, routes, ...)
        // Render stuff
    }
}

const mapStateToProps = (state, props) => {
    console.log(state); // returns state of redux
    console.log(props); // returns empty object -> {}, how come this is empty?!

    return {
        consultations: patientThisClassSelector(state, props)
    };
}

export default connect(mapStateToProps)(withRouter(ThisClass));
</code>```

答:
You have to inject the router props before you connect the component.

To achieve that you have to use

```<code>export default withRouter(connect(mapStateToProps)(ThisClass));
</code>```

instead of

export default connect(mapStateToProps)(withRouter(ThisClass));

Body:
I'm currently facing a weird issue where the HOC withRouter provided by react-router does not pass on the props to the mapStateToProps function. Am I doing it wrong here?

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router';
import { connect } from 'react-redux';

class ThisClass extends Component {
    render() {
        console.log(this.props.router); // Returns object with router keys (params, router, go, routes, ...)
        // Render stuff
    }
}

const mapStateToProps = (state, props) => {
    console.log(state); // returns state of redux
    console.log(props); // returns empty object -> {}, how come this is empty?!

    return {
        consultations: patientThisClassSelector(state, props)
    };
}

export default connect(mapStateToProps)(withRouter(ThisClass));

Body:
You have to inject the router props before you connect the component.

To achieve that you have to use

export default withRouter(connect(mapStateToProps)(ThisClass));

instead of

export default connect(mapStateToProps)(withRouter(ThisClass));


问:
disable button untill form filled with specific length
i am trying to create a form which needs to be filled with 9 numeric digits. I would like the submit button to be disabled untill the form is filled exactly with 9 digits. I have found many scripts with button disabled untill form is filled but not with specific length. Could you please help me?

```<code><form name="form1">
    <input type="text" name='text1' maxlength="9" class="phone-input">
    <input type="button" value="submit" onclick="phonenumber(document.form1.text1); changeDiv();"/>
    </form>
</code>```

Thank You!

答:
You can try to use a pattern. Didn't try it, but it must be something like this:</p>

```<code><input pattern=".{9}">
</code>```

Body:
i am trying to create a form which needs to be filled with 9 numeric digits. I would like the submit button to be disabled untill the form is filled exactly with 9 digits. I have found many scripts with button disabled untill form is filled but not with specific length. Could you please help me?

<form name="form1">
    <input type="text" name='text1' maxlength="9" class="phone-input">
    <input type="button" value="submit" onclick="phonenumber(document.form1.text1); changeDiv();"/>
    </form>

Thank You!

Body:
You can try to use a pattern. Didn't try it, but it must be something like this:

<input pattern=".{9}">


问:
Error on only Azure - 'Microsoft.ACE.OleDb.12.0' provider is not registered on the local machine
I am working with MS Excel files in my web application built in Azure environment. I never run into following error when I am trying to access the excel file on my development fabric.
But once I deploy to Azure in cloud, I get this error message.

The 'Microsoft.ACE.OleDb.12.0' provider is not registered on the local machine.

I was under impression that development fabric for Azure is replica of the environment you would expect in Cloud.

Is there something wrong I am doing here?
Is ACE.OleDb provider not present in Azure?

答:
I also faced the same issue today. I am using Standard plan of Azure and access to deployment server is through Azure Web portal. I am not using Azure VM because it is a costlier option.

One of my colleagues suggested to use OpenSDK, using which I ultimately could do Excel manipulation without using OleDb drivers.

Some of the resources which helped me to accomplish what I wanted are these:

https://www.microsoft.com/en-us/download/details.aspx?id=30425

https://msdn.microsoft.com/en-us/library/office/hh298534.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-15

reading Excel Open XML is ignoring blank cells

Please make sure open sdk dll is copied to local. In my case, it was referencing the dll installed in my computer in program files. So when I uploaded to Azure, it gave a dll missing error. I had copy the dll separately to the bin folder. I think if we try nuget option of referencing the dll then this issue would not show up, 've not tried it myself though.

Hope this helps someone who is looking for an alternative to Oledb, in case where installation of the dll on the server is not possible.


问:
Microsoft ANGLE for uwp
guys! I'm currently working on new cross-platform application (iOS, Android, UWP). I have graphical library for UI written in c++, using freeglut for opengGL.
The problem is, I don't know how to use this library in my UWP application. I have read a lot of information about all the wrappers for OpenGL, but they all for WPF or written in C++. I also know about Microsoft ANGLE Project, but it is written in the c++ too, but I need to write the application in C# language.

So, how can I modify my own library using excluding freeglut and import it into my C# application?

By the way, sorry for mistakes in my English.

答:
According to https://msdn.microsoft.com/library/windows/desktop/jj714080.aspx there is an option to use DirectX and some native API functions including LoadLibrary and GetProcAddress functions https://msdn.microsoft.com/library/windows/desktop/jj714080.aspx
This should give you ability to use any native dll.
You can try to make RuntimeComponent project and put it there. Also you can try clr oldsyntax option to use native code as it is.</p>

Title: Microsoft ANGLE for uwp