问:
How do you set the text of an EditText menu item?
I am trying to set the text of an item in a toolbar menu with the EditText property. The textbox shows up on the app, but always empty. I'm trying to get "Hello World!" to show up in the textbox using 3 different ways, but it still is empty. Below is the XML:</p>

```<code>    <item android:id="@+id/DisplayPath"
    android:title="Hello World!"
    android:text="Hello World!"
    android:hint="Hello WOrld"
    app:showAsAction="always"
    app:actionViewClass="android.widget.EditText" />
</code>```

答:
First find your MenuItem by id, then get its action view, cast it to EditText and set its text:

```<code>((android.widget.EditText)menu.findItem(R.id.DisplayPath).getActionView()).setText("Hello World");
</code>```

Get the reference to menu inside your onCreateOptionsMenu() method, after you inflated the menu.

Body:
I am trying to set the text of an item in a toolbar menu with the EditText property. The textbox shows up on the app, but always empty. I'm trying to get "Hello World!" to show up in the textbox using 3 different ways, but it still is empty. Below is the XML:

    <item android:id="@+id/DisplayPath"
    android:title="Hello World!"
    android:text="Hello World!"
    android:hint="Hello WOrld"
    app:showAsAction="always"
    app:actionViewClass="android.widget.EditText" />

Body:
First find your MenuItem by id, then get its action view, cast it to EditText and set its text:

((android.widget.EditText)menu.findItem(R.id.DisplayPath).getActionView()).setText("Hello World");

Get the reference to menu inside your onCreateOptionsMenu() method, after you inflated the menu.


来源: stackexchange

问:
rails 6 foreign key can't be null
I have a migration file as the following:

```<code>def change
    create_table :carts do |t|
      t.string :order_number
      t.decimal :total_price
      t.bigint :user_id, null: true
      t.string :status

      t.timestamps
    end
  end
</code>```

I want to allow the user_id to be null, but my schema file translate this migration to:

```<code>t.bigint "user_id", null: false
</code>```

So in my cart.rb model even if I have

```<code>belongs_to :user, optional: true
</code>```

it doesn't work and when I try to save a cart object I get the ForeignKey can't be null error !

How I can allow null value for a foreign key ?

答:
Migrations are not a declaration of current db structure, they are changes that when combined - produce it. For combined structure rails have db/schema.rb (or schema.sql for more complex scenarios)

If the column is null: false then it must have been changed by some later migration (or directly in db, if so - db structure may be out of sync between development and production). If you want it again to be null: true - add another migration that will change that. But first I'd figure out why it ended up in current state, may be there's a reason.

```<code>change_column :carts, :user_id, :bigint, null:true
</code>```

ContentLicense: CC BY-SA 4.0

Title: rails 6 foreign key can't be null

Body:
I have a migration file as the following:

def change
    create_table :carts do |t|
      t.string :order_number
      t.decimal :total_price
      t.bigint :user_id, null: true
      t.string :status

      t.timestamps
    end
  end

I want to allow the user_id to be null, but my schema file translate this migration to:

t.bigint "user_id", null: false

So in my cart.rb model even if I have

belongs_to :user, optional: true

it doesn't work and when I try to save a cart object I get the ForeignKey can't be null error !

How I can allow null value for a foreign key ?

Body:
Migrations are not a declaration of current db structure, they are changes that when combined - produce it. For combined structure rails have db/schema.rb (or schema.sql for more complex scenarios)

If the column is null: false then it must have been changed by some later migration (or directly in db, if so - db structure may be out of sync between development and production). If you want it again to be null: true - add another migration that will change that. But first I'd figure out why it ended up in current state, may be there's a reason.

change_column :carts, :user_id, :bigint, null:true


问:
Is there a concise way to check if an int variable is equal to a series of ints? | C#
Rather than something like this:

```<code>switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}
</code>```

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

答:
Perhaps a solution using LINQ:</p>

```<code>List<int> ints = new List<int> {2, 5, 11, 15};

void Search(int s) {
    int result = ints.Where(x => x == s).FirstOrDefault();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Rather than something like this:

switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

Body:
Perhaps a solution using LINQ:

List<int> ints = new List<int> {2, 5, 11, 15};

void Search(int s) {
    int result = ints.Where(x => x == s).FirstOrDefault();
}


问:
WebView example android
There is a error in mView, I need solution

```<code>package com.example.account;

import android.app.Activity;
import android.os.Bundle;

public class WebView extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("http://www.google.com");

}

}
</code>```

My xml

```<code><?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</code>```

Cannot cast from view to webview

```<code>WebView mView = (WebView) findViewById(R.id.webView1)
</code>```

答:
Do not use reserved words as your variable, class and method name.

Here, WebView is reserved or already used by SDK. If you use that word again, Compiler will get confused.

activity_main.xml

```<code><WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</code>```

MainActivity.java

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity
{
private WebView webview;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

webview=(WebView)findViewById(R.id.webview);
//loads androidride homepage to webview
webview.loadUrl("https://www.androidride.com");
}
}
</code>```

Title: WebView example android

Body:
There is a error in mView, I need solution

package com.example.account;

import android.app.Activity;
import android.os.Bundle;

public class WebView extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("http://www.google.com");

}

}

My xml

<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

Cannot cast from view to webview

WebView mView = (WebView) findViewById(R.id.webView1)

Body:
Do not use reserved words as your variable, class and method name.

Here, WebView is reserved or already used by SDK. If you use that word again, Compiler will get confused.

activity_main.xml

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity
{
private WebView webview;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

webview=(WebView)findViewById(R.id.webview);
//loads androidride homepage to webview
webview.loadUrl("https://www.androidride.com");
}
}


问:
Native JNI File Can't Find Path to Java File in Android Studio
I have a native C file in android studio, which I'm using to generate the library with JNI. but when I run the app I get error of file not finding the java file. So the C file has a pointer to the java file using the path to that file. and this is what I'm having problem finding. I guess, I'm not providing the right path. This is in a windows machine. here's the error.

```<code>A/zygote: java_vm_ext.cc:504] JNI DETECTED ERROR IN APPLICATION: JNI RegisterNatives called with pending exception java.lang.ClassNotFoundException: Didn't find class "java.org.techgeorge.tracehost.Tracepath" on path: DexPathList[[zip file "/data/app/org.techgeorge.tracehost-W_AzDnbsP-K7alPTKabP6Q==/base.apk", zip  file "/data/app/org.tech
</code>```

I think this is the part of the code that is failing

```<code>jclass kClass = (*env)->FindClass(env, "java/org/techgeorge/tracehost/Tracepath");
</code>```

here's the file

```<code>#include "org_techgeorge_tracehost_Tracepath.h"
#include <jni.h>
#include <unistd.h>
#include "tracepath.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>

typedef struct {
    jobject gObject;

    JNIEnv * g_Env;

    jclass kClass;

    jmethodID  updateMethodId;

    jmethodID  endMethodId;

} Nofication;

Nofication nofication;

JNIEXPORT void JNICALL beginTrace(JNIEnv *env, jobject object, jstring path){
    nofication.gObject = object;
    nofication.g_Env = env;

    nofication.kClass = (*env)->FindClass(env, "java/org/techgeorge/tracehost/Tracepath");
    nofication.updateMethodId = (*env)->GetMethodID(env, nofication.kClass, "callback", "(Ljava/lang/String;)V");
    nofication.endMethodId = (*env)->GetMethodID(env, nofication.kClass, "end", "()V");

    jboolean tmp = 1;
    const char * domin = (*env)->GetStringUTFChars(env, path, &tmp);

    struct hostent* host = gethostbyname(domin);
    if(host){
        notifyUpdateToJava("To %s ",  host->h_name);

        for (;;){
            if (*host->h_aliases){
                notifyUpdateToJava("(%s )",  *host->h_aliases);
                host->h_aliases++;
            } else {
                break;
            }
        }

        for (;;){
           if (*host->h_addr_list){
               notifyUpdateToJava("(%s )",  inet_ntoa(*(struct in_addr*)(*host->h_addr_list)));
               host->h_addr_list++;
           } else {
               break;
           }
        }

//        notifyUpdateToJava(" %s ",  inet_ntoa(*(struct in_addr*)(host->h_addr_list[1])));
        notifyUpdateToJava("\n");
    } else {
        notifyUpdateToJava("Net error! %s\n", strerror(errno));
        notifyEnd();
    }

    LOGD(domin);
    char * ret[] = {"tracepath", domin};
    traceroute(2, ret);
    LOGD(strerror(errno));
//
}

char line[1000];
int notifyUpdateToJava(const char* logs, ...){
    int ret = 0;
    char value[200];
    va_list arg;
    va_start(arg, logs);
    ret = vsprintf(value, logs, arg);
    va_end(arg);

    strcat(line, value);
    if(value[strlen(value) - 1] == '\n'){
        LOGD(line);
        if (line){
            jstring value = (*nofication.g_Env)->NewStringUTF(nofication.g_Env, line);
            (*nofication.g_Env)->CallVoidMethod(nofication.g_Env, nofication.gObject, nofication.updateMethodId, value);
        }
        memset(line, 0, sizeof(line));
    }

    return ret;
}

void notifyEnd(){
    (*nofication.g_Env)->CallVoidMethod(nofication.g_Env, nofication.gObject, nofication.endMethodId);
}

static const JNINativeMethod gMethods[] = {
        {"beginTrace", "(Ljava/lang/String;)V", (void*)beginTrace}
};

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
    LOGD("jni load");
    JNIEnv *env;
    if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_4) != JNI_OK){
        return -1;
    }

    jclass kClass = (*env)->FindClass(env, "java/org/techgeorge/tracehost/Tracepath");
    (*env)->RegisterNatives(env, kClass, gMethods, sizeof(gMethods) / sizeof(gMethods[0]));
    return JNI_VERSION_1_4;
}

JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved){
    LOGD("jni unload");
}
</code>```

答: It should be FindClass(env, "org/techgeorge/tracehost/Tracepath"). This java in your screenshot is the sourceroot, not part of the package name.

Body:
I have a native C file in android studio, which I'm using to generate the library with JNI. but when I run the app I get error of file not finding the java file. So the C file has a pointer to the java file using the path to that file. and this is what I'm having problem finding. I guess, I'm not providing the right path. This is in a windows machine. here's the error.

A/zygote: java_vm_ext.cc:504] JNI DETECTED ERROR IN APPLICATION: JNI RegisterNatives called with pending exception java.lang.ClassNotFoundException: Didn't find class "java.org.techgeorge.tracehost.Tracepath" on path: DexPathList[[zip file "/data/app/org.techgeorge.tracehost-W_AzDnbsP-K7alPTKabP6Q==/base.apk", zip  file "/data/app/org.tech

I think this is the part of the code that is failing

jclass kClass = (*env)->FindClass(env, "java/org/techgeorge/tracehost/Tracepath");

here's the file

#include "org_techgeorge_tracehost_Tracepath.h"
#include <jni.h>
#include <unistd.h>
#include "tracepath.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>

typedef struct {
    jobject gObject;

    JNIEnv * g_Env;

    jclass kClass;

    jmethodID  updateMethodId;

    jmethodID  endMethodId;

} Nofication;

Nofication nofication;

JNIEXPORT void JNICALL beginTrace(JNIEnv *env, jobject object, jstring path){
    nofication.gObject = object;
    nofication.g_Env = env;

    nofication.kClass = (*env)->FindClass(env, "java/org/techgeorge/tracehost/Tracepath");
    nofication.updateMethodId = (*env)->GetMethodID(env, nofication.kClass, "callback", "(Ljava/lang/String;)V");
    nofication.endMethodId = (*env)->GetMethodID(env, nofication.kClass, "end", "()V");

    jboolean tmp = 1;
    const char * domin = (*env)->GetStringUTFChars(env, path, &tmp);

    struct hostent* host = gethostbyname(domin);
    if(host){
        notifyUpdateToJava("To %s ",  host->h_name);

        for (;;){
            if (*host->h_aliases){
                notifyUpdateToJava("(%s )",  *host->h_aliases);
                host->h_aliases++;
            } else {
                break;
            }
        }

        for (;;){
           if (*host->h_addr_list){
               notifyUpdateToJava("(%s )",  inet_ntoa(*(struct in_addr*)(*host->h_addr_list)));
               host->h_addr_list++;
           } else {
               break;
           }
        }

//        notifyUpdateToJava(" %s ",  inet_ntoa(*(struct in_addr*)(host->h_addr_list[1])));
        notifyUpdateToJava("\n");
    } else {
        notifyUpdateToJava("Net error! %s\n", strerror(errno));
        notifyEnd();
    }

    LOGD(domin);
    char * ret[] = {"tracepath", domin};
    traceroute(2, ret);
    LOGD(strerror(errno));
//
}

char line[1000];
int notifyUpdateToJava(const char* logs, ...){
    int ret = 0;
    char value[200];
    va_list arg;
    va_start(arg, logs);
    ret = vsprintf(value, logs, arg);
    va_end(arg);

    strcat(line, value);
    if(value[strlen(value) - 1] == '\n'){
        LOGD(line);
        if (line){
            jstring value = (*nofication.g_Env)->NewStringUTF(nofication.g_Env, line);
            (*nofication.g_Env)->CallVoidMethod(nofication.g_Env, nofication.gObject, nofication.updateMethodId, value);
        }
        memset(line, 0, sizeof(line));
    }

    return ret;
}

void notifyEnd(){
    (*nofication.g_Env)->CallVoidMethod(nofication.g_Env, nofication.gObject, nofication.endMethodId);
}

static const JNINativeMethod gMethods[] = {
        {"beginTrace", "(Ljava/lang/String;)V", (void*)beginTrace}
};

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
    LOGD("jni load");
    JNIEnv *env;
    if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_4) != JNI_OK){
        return -1;
    }

    jclass kClass = (*env)->FindClass(env, "java/org/techgeorge/tracehost/Tracepath");
    (*env)->RegisterNatives(env, kClass, gMethods, sizeof(gMethods) / sizeof(gMethods[0]));
    return JNI_VERSION_1_4;
}

JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved){
    LOGD("jni unload");
}


问:
Python get least significant digits from a float (without using string operations)
Assuming I have the float 12345.6789 and I want to get the six least significant digits (i.e. 45.6789) as an int (i.e. 456789) using bit operations in python (v. 2.6).

How do I do that?

Thanks

PS I do not want to use string operations even if it would be rather easy to: for any float f:

```<code>int(str(int(f * 1000))[-10:])
</code>```

EDIT:  This original question is pointless, as shown by comments within.  Many apologies... instead methods on getting the least significant digits without using strings are shown below (using ints and modulus)

Body:
Assuming I have the float 12345.6789 and I want to get the six least significant digits (i.e. 45.6789) as an int (i.e. 456789) using bit operations in python (v. 2.6).

How do I do that?

Thanks

PS I do not want to use string operations even if it would be rather easy to: for any float f:

int(str(int(f * 1000))[-10:])

EDIT:  This original question is pointless, as shown by comments within.  Many apologies... instead methods on getting the least significant digits without using strings are shown below (using ints and modulus)

Body:
>>> a = 12345.6789
>>> b = int(a*10000)
>>> b
123456789
>>> c = b % 1000000
>>> c
456789

But - WHY??


问:
How can I access JavaScript object in array?
My question is how can I Access the object in the array. As an example how can I access the property country?

```<code>var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}]
</code>```

答:
The correct syntax to acces an array of objects property is:

```<code>array[index].objectProperty
</code>```

So, with this said to access the country value of the first index you should use:

```<code>arr1[0].country  // Schweiz
</code>```

So, for example, lets print out every country on your array:

var arr1 = [{
    country: "Schweiz",
    code: 'ch'
  },
  {
    country: "Deutschland",
    code: 'de'
  },
  {
    country: "Oesterreich",
    code: 'at'
  }
];

arr1.forEach((item)=>{
  document.write(item.country+"
");
})```
</div>
</div>
</p>

<blockquote>
  <p><strong><em>Note:</strong> In the array structure you provided exists a syntax error. You are missing a comma, which is used to separate elements on your array.</em></p>
</blockquote>

<p>Arrays are structures separated with commas, like this:</p>

```myArray = [1,2,3,4,5];
```

<p>So, to separate each index, you need to use a comma. You have:</p>

```var arr1 = [{
        country: "Schweiz",
        code: 'ch'
    }, // First separator comma
    {
        country: "Deutschland",
        code: 'de'
    } { // MISSING COMMA HERE
        country: "Oesterreich",
        code: 'at'
    }

]
```

<p>So, just separate the new element with a comma:</p>

```var arr1 = [{
        country: "Schweiz",
        code: 'ch'
    },
    {
        country: "Deutschland",
        code: 'de'
    }, // ADDED COMMA
    {
        country: "Oesterreich",
        code: 'at'
    }

]
```

Hope this helps with your question. Welcome to Stackoverflow.

Body:
My question is how can I Access the object in the array. As an example how can I access the property country?

var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}]

Body:
The correct syntax to acces an array of objects property is:

array[index].objectProperty

So, with this said to access the country value of the first index you should use:

arr1[0].country  // Schweiz

So, for example, lets print out every country on your array:

var arr1 = [{
    country: "Schweiz",
    code: 'ch'
  },
  {
    country: "Deutschland",
    code: 'de'
  },
  {
    country: "Oesterreich",
    code: 'at'
  }
];

arr1.forEach((item)=>{
  document.write(item.country+"<br>");
})

Note: In the array structure you provided exists a syntax error. You are missing a comma, which is used to separate elements on your array.

Arrays are structures separated with commas, like this:

myArray = [1,2,3,4,5];

So, to separate each index, you need to use a comma. You have:

var arr1 = [{
        country: "Schweiz",
        code: 'ch'
    }, // First separator comma
    {
        country: "Deutschland",
        code: 'de'
    } { // MISSING COMMA HERE
        country: "Oesterreich",
        code: 'at'
    }

]

So, just separate the new element with a comma:

var arr1 = [{
        country: "Schweiz",
        code: 'ch'
    },
    {
        country: "Deutschland",
        code: 'de'
    }, // ADDED COMMA
    {
        country: "Oesterreich",
        code: 'at'
    }

]

Hope this helps with your question. Welcome to Stackoverflow.


问:
Is there a way to select an array without specifying it
I want to get a number from an array, without having to do a lot of if statements.</p>

```<code>double[] PVC_A1_Cu = new double[]{14.5d, 19.5d, 26.0d, 34.0d, 46.0d, 61.0d, 80.0d, 99.0d, 119.0d, 151.0d, 182.0d, 210.0d, 240.0d, 273.0d, 321.0d, 367.0d};
double[] PVC_A2_Cu = new double[]{14.0d, 18.5d, 25.0d, 32.0d, 43.0d, 57.0d, 75.0d, 92.0d, 110.0d, 139.0d, 167.0d, 192.0d, 219.0d, 148.0d, 291.0d, 334.0d};
double[] PVC_B1_Cu = new double[]{17.5d, 24.0d, 32.0d, 41.0d, 57.0d, 76.0d, 101.0d, 125.0d, 151.0d, 192.0d, 232.0d, 269.0d, 300.0d, 341.0d, 400.0d, 458.0d};
double[] PVC_B2_Cu = new double[]{16.5d, 23.0d, 30.0d, 38.0d, 52.0d, 69.0d, 90.0d, 111.0d, 133.0d, 168.0d, 201.0d, 232.0d, 258.0d, 294.0d, 344.0d, 394.0d};

String Kappe = SpinLederKapp.getSelectedItem().toString();   // This would return "PVC"
String LederMat = SpinLederMat.getSelectedItem().toString(); // This would return "A1"
String InsMet = SpinInsMet.getSelectedItem().toString();     //This would return  "Cu"

Integer Tverrsnitt = SpinTverrsnitt.getSelectedItemPosition();  //This would return in this case   "2"

String Codetest = Kappe + "_" + InsMet + "_"+LederMat;  //this would put it together like "PVC_A1_Cu"

Double Test3 = Codetest[Tverrsnitt];  //And here is were my knowledge ends...
//This does not work ^

//What i want it to do:
Double Test1 = PVC_A1_Cu[2];
</code>```

答:
This will help you understand what's going wrong here.

First you are creating a double array,

```<code>double[] PVC_A1_Cu = ..... //This means create a variable of type double array whose name is PVC_A1_Cu.
</code>```

Later you are creating a string variable,

```<code>String Codetest = ... //This means create a variable of type String whose name is codetest
</code>```

At last you are assigning a value "PVC_A1_Cu" (which happens to be your double array variable name) to your string variable Codetest. This is no way means that you are referring to the content of the double array, it just means that your string variable has a content "PVC_A1_Cu" and cannot be referred like an array. So the compiler will complain when your code does this,

```<code>Codetest[Tverrsnitt]; //codeTest is not an array
</code>```

The simplest way you could handle this is,

```<code>if("PVC_A1_Cu".equals(Codetest)) {
    test3 = PVC_A1_Cu[Tverrsnitt];
} else ("PVC_A2_Cu".equals(Codetest)) {
    test3 = PVC_A2_Cu[Tverrsnitt];
} else ("PVC_B1_Cu".equals(Codetest)) {
    test3 = PVC_B1_Cu[Tverrsnitt];
} else {
    test3 = PVC_B2_Cu[Tverrsnitt];
}
</code>```

Body:
I want to get a number from an array, without having to do a lot of if statements.

double[] PVC_A1_Cu = new double[]{14.5d, 19.5d, 26.0d, 34.0d, 46.0d, 61.0d, 80.0d, 99.0d, 119.0d, 151.0d, 182.0d, 210.0d, 240.0d, 273.0d, 321.0d, 367.0d};
double[] PVC_A2_Cu = new double[]{14.0d, 18.5d, 25.0d, 32.0d, 43.0d, 57.0d, 75.0d, 92.0d, 110.0d, 139.0d, 167.0d, 192.0d, 219.0d, 148.0d, 291.0d, 334.0d};
double[] PVC_B1_Cu = new double[]{17.5d, 24.0d, 32.0d, 41.0d, 57.0d, 76.0d, 101.0d, 125.0d, 151.0d, 192.0d, 232.0d, 269.0d, 300.0d, 341.0d, 400.0d, 458.0d};
double[] PVC_B2_Cu = new double[]{16.5d, 23.0d, 30.0d, 38.0d, 52.0d, 69.0d, 90.0d, 111.0d, 133.0d, 168.0d, 201.0d, 232.0d, 258.0d, 294.0d, 344.0d, 394.0d};

String Kappe = SpinLederKapp.getSelectedItem().toString();   // This would return "PVC"
String LederMat = SpinLederMat.getSelectedItem().toString(); // This would return "A1"
String InsMet = SpinInsMet.getSelectedItem().toString();     //This would return  "Cu"

Integer Tverrsnitt = SpinTverrsnitt.getSelectedItemPosition();  //This would return in this case   "2"

String Codetest = Kappe + "_" + InsMet + "_"+LederMat;  //this would put it together like "PVC_A1_Cu"

Double Test3 = Codetest[Tverrsnitt];  //And here is were my knowledge ends...
//This does not work ^

//What i want it to do:
Double Test1 = PVC_A1_Cu[2];

Body:
This will help you understand what's going wrong here.

First you are creating a double array,

double[] PVC_A1_Cu = ..... //This means create a variable of type double array whose name is PVC_A1_Cu.

Later you are creating a string variable,

String Codetest = ... //This means create a variable of type String whose name is codetest

At last you are assigning a value "PVC_A1_Cu" (which happens to be your double array variable name) to your string variable Codetest. This is no way means that you are referring to the content of the double array, it just means that your string variable has a content "PVC_A1_Cu" and cannot be referred like an array. So the compiler will complain when your code does this,

Codetest[Tverrsnitt]; //codeTest is not an array

The simplest way you could handle this is,

if("PVC_A1_Cu".equals(Codetest)) {
    test3 = PVC_A1_Cu[Tverrsnitt];
} else ("PVC_A2_Cu".equals(Codetest)) {
    test3 = PVC_A2_Cu[Tverrsnitt];
} else ("PVC_B1_Cu".equals(Codetest)) {
    test3 = PVC_B1_Cu[Tverrsnitt];
} else {
    test3 = PVC_B2_Cu[Tverrsnitt];
}


问:
TypeError for leetcode Python coding question
Hi guys I ma practicing a Python coding question on leetcode:

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

Here is my code:

class Solution:
    def removeDuplicates(self,nums):
          result = []
          result.append(nums[0])
          for n in range(len(nums)):
            result_ref = False
            for x in range(n):
              if nums[x] == nums[n]:
                result_ref = False
              else:
                result_ref = True
            if result_ref:
              result.append(nums[n])
            else:
              continue

          return result
```

<p>The function works fine in my computer, but I kept get this error in my leetcode console. Anyone knows how to fix it? Thank you very much!</p>

```TypeError: slice indices must be integers or None or have an __index__ method
Line 25 in integerListToString (Solution.py)
Line 42 in main (Solution.py)
Line 48 in <module> (Solution.py)
```

答:
please take a look at default code @ https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

```<code>class Solution(object):

    def removeDuplicates(self, nums):

        """
        :type nums: List[int]
        :rtype: int
        """
</code>```

rtype should be int, but you return boolean

as soon as you will change 'result' to int - this will disappear:

```<code>TypeError: slice indices must be integers or None or have an __index__ method
</code>```

btw afaik Python 2 is too old - imo Python 3.x is much more interesting to learn ;)

Body:
Hi guys I ma practicing a Python coding question on leetcode:

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

Here is my code:

class Solution:
    def removeDuplicates(self,nums):
          result = []
          result.append(nums[0])
          for n in range(len(nums)):
            result_ref = False
            for x in range(n):
              if nums[x] == nums[n]:
                result_ref = False
              else:
                result_ref = True
            if result_ref:
              result.append(nums[n])
            else:
              continue

          return result

The function works fine in my computer, but I kept get this error in my leetcode console. Anyone knows how to fix it? Thank you very much!

TypeError: slice indices must be integers or None or have an __index__ method
Line 25 in integerListToString (Solution.py)
Line 42 in main (Solution.py)
Line 48 in <module> (Solution.py)

Body:
please take a look at default code @ https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

class Solution(object):

    def removeDuplicates(self, nums):

        """
        :type nums: List[int]
        :rtype: int
        """

rtype should be int, but you return boolean

as soon as you will change 'result' to int - this will disappear:

TypeError: slice indices must be integers or None or have an __index__ method

btw afaik Python 2 is too old - imo Python 3.x is much more interesting to learn ;)


问:
No database provider .Net Core Angular app
I'm trying to build my database using .NET Core 2.2 and Angular and have run across this error:

```<code>No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
</code>```

I have a default constructor in my ApplicationDbContext class.

```<code>public class ApplicationDbContext : DbContext
{
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base()
        {
        }
}
</code>```

My program cs looks okay to me:

```<code>public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(SetUpConfiguration)
                .UseStartup<Startup>();

        private static void SetUpConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder builder)
        {
            builder.Sources.Clear();
            builder.AddJsonFile("appsettings.json", false, true)
                    .AddEnvironmentVariables();
        }
    }
</code>```

And my startup registers the db:

```<code>private readonly IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<ApplicationDbContext>(cfg => {
                cfg.UseSqlServer(_config.GetConnectionString("LevanaConnectionString"));
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
</code>```

答:
As we can see at the first message:
"If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext."

You're using "AddDbContext" at "ConfigureServices" class, but don't pass the "DbContextOptions" for the base constructor of "DbContext" at "ApplicationDbContext".

You can try this:

```<code>public class ApplicationDbContext : DbContext
{
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base(opts)
        {
        }
}
</code>```

Body:
I'm trying to build my database using .NET Core 2.2 and Angular and have run across this error:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

I have a default constructor in my ApplicationDbContext class.

public class ApplicationDbContext : DbContext
{
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base()
        {
        }
}

My program cs looks okay to me:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(SetUpConfiguration)
                .UseStartup<Startup>();

        private static void SetUpConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder builder)
        {
            builder.Sources.Clear();
            builder.AddJsonFile("appsettings.json", false, true)
                    .AddEnvironmentVariables();
        }
    }

And my startup registers the db:

private readonly IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<ApplicationDbContext>(cfg => {
                cfg.UseSqlServer(_config.GetConnectionString("LevanaConnectionString"));
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

Body:
As we can see at the first message:
"If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext."

You're using "AddDbContext" at "ConfigureServices" class, but don't pass the "DbContextOptions" for the base constructor of "DbContext" at "ApplicationDbContext".

You can try this:

public class ApplicationDbContext : DbContext
{
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base(opts)
        {
        }
}


问:
Python will not write to a CSV file and there are no errors; the print function works
I have 3 lists of integers. They are then converted into strings. When trying to write them to the CSV file, the file itself is generated, but completely empty. This has stumped all Python users in my lab.

I have tried isolating the different lists and writing them to CSVs. They all return blank.

The print function works.

```<code>LP = [25,26,27,28,30,67,71,9,17,18,3,4,46,47,48,49, 55, 56, 65, 66] #(190)

RP = [92,93,98,107,114,115,116,156,117,160,119,144,145,135,136,137,138,155,106,
      154] #(190)
RF = [90,94,95,96,97,101,102,103,104,105,106,113,118,120,121,129,128,134,141,
      142,143,157,158,151,152,153,159,136,137,138,155,92,93,107] #(561)

LP = list(map(str, LP))
RP = list(map(str, RP))
RF = list(map(str, RF))

f = open("All Connections Between Nodes.csv", "w")

def run(lobe):
    seperator = ","
    for num in lobe:
        for num2 in lobe:
            if lobe.index(num2) <= lobe.index(num):
                pass
            elif lobe.index(num) == lobe.index(num2):
                pass

            elif lobe == LP:
                f.write("" + (num) + seperator + (num2) + "")
                f.write("\n")
                print(num, num2)
            elif lobe == RP:
                f.write("" + (num) + seperator + (num2) + "")
                f.write("\n")
                print("" + (num) + seperator + (num2) + "")
            elif lobe == RF:
                f.write("" + (num) + seperator + (num2) + "")
                f.write("\n")
                print("" + (num) + seperator + (num2) + "")

if __name__ == "__main__":

    run(LP)
    run(RP)
    run(RF)
</code>```

The CSV file should look like this:

```<code>25 26
25 27
25 28
</code>```

And so on. Each pair should only exist once. (e.g., if 25-26 exists, there should not be a 26-25)

Body:
I have 3 lists of integers. They are then converted into strings. When trying to write them to the CSV file, the file itself is generated, but completely empty. This has stumped all Python users in my lab.

I have tried isolating the different lists and writing them to CSVs. They all return blank.

The print function works.

LP = [25,26,27,28,30,67,71,9,17,18,3,4,46,47,48,49, 55, 56, 65, 66] #(190)

RP = [92,93,98,107,114,115,116,156,117,160,119,144,145,135,136,137,138,155,106,
      154] #(190)
RF = [90,94,95,96,97,101,102,103,104,105,106,113,118,120,121,129,128,134,141,
      142,143,157,158,151,152,153,159,136,137,138,155,92,93,107] #(561)

LP = list(map(str, LP))
RP = list(map(str, RP))
RF = list(map(str, RF))

f = open("All Connections Between Nodes.csv", "w")

def run(lobe):
    seperator = ","
    for num in lobe:
        for num2 in lobe:
            if lobe.index(num2) <= lobe.index(num):
                pass
            elif lobe.index(num) == lobe.index(num2):
                pass

            elif lobe == LP:
                f.write("" + (num) + seperator + (num2) + "")
                f.write("\n")
                print(num, num2)
            elif lobe == RP:
                f.write("" + (num) + seperator + (num2) + "")
                f.write("\n")
                print("" + (num) + seperator + (num2) + "")
            elif lobe == RF:
                f.write("" + (num) + seperator + (num2) + "")
                f.write("\n")
                print("" + (num) + seperator + (num2) + "")

if __name__ == "__main__":

    run(LP)
    run(RP)
    run(RF)

The CSV file should look like this:

25 26
25 27
25 28

And so on. Each pair should only exist once. (e.g., if 25-26 exists, there should not be a 26-25)

Body:
I think the scope is not correct with open the file:

LP = [25,26,27,28,30,67,71,9,17,18,3,4,46,47,48,49, 55, 56, 65, 66] #(190)

RP = [92,93,98,107,114,115,116,156,117,160,119,144,145,135,136,137,138,155,106,
      154] #(190)
RF = [90,94,95,96,97,101,102,103,104,105,106,113,118,120,121,129,128,134,141,
      142,143,157,158,151,152,153,159,136,137,138,155,92,93,107] #(561)

LP = list(map(str, LP))
RP = list(map(str, RP))
RF = list(map(str, RF))

seperator = ','

def run(lobe):
    with open("All Connections Between Nodes.csv", 'w') as f:
        for num in lobe:
            for num2 in lobe:
                if lobe.index(num2) <= lobe.index(num):
                    pass
                elif lobe.index(num) == lobe.index(num2):
                    pass

                elif lobe == LP:
                    f.write(''+(num)+seperator+(num2)+'')
                    f.write('\n')
                    print(num,num2)
                elif lobe == RP:
                    f.write(''+(num)+seperator+(num2)+'')
                    f.write('\n')
                    print(''+(num)+seperator+(num2)+'')
                elif lobe == RF:
                    f.write(''+(num)+seperator+(num2)+'')
                    f.write('\n')
                    print(''+(num)+seperator+(num2)+'')

if __name__ == '__main__':

    run(LP)
    run(RP)
    run(RF)


问:
Error defining an input shape in keras for (60000, 28, 28) array
I am setting up my first neural network with keras and tensorflow. I got my input into an array of shape (60000, 28, 28), but when I try and feed it to the model I get an error that the input shape is wrong.

I have tried multiple different input shapes including (60000, 28, 28) (1, 28, 28) (28, 28) (28, 28, 1) but none of them seem to work.

model = kr.Sequential()

model.add(InputLayer(input_shape=(60000, 28, 28)))
model.add(Dense(units=784, activation='relu'))
model.add(Dense(units=392, activation='relu'))
model.add(Dense(units=196, activation='relu'))
model.add(Dense(units=10, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])

training = model.fit(x=images_array, y=labels_array, epochs=10, batch_size=256)
```

<p>I would expect it to work with input shape (60000, 28, 28) but I always get this error:</p>

<blockquote>
  <p>ValueError: Error when checking input: expected input_1 to have 4
  dimensions, but got array with shape (60000, 28, 28)</p>
</blockquote>

<p><strong>Edit:</strong></p>

<p>Thanks to everyone who answerd. cho_uc answer indeed worked, which is why I accepted it.
What I shold have mentioned in the post was, that I was trying to build a model consisting only of Dense layers, so I can use it as a benchmark for future models.</p>

<p>I solved the input layer problem with:</p>

<pre class="lang-py prettyprint-override"><code>images_array = images_array.reshape(-1, 28 * 28)

model.add(InputLayer(input_shape=(784, )))
</code>```

答:
Keras Conv2D layer performs the convolution operation. It requires its input to be a 4-dimensional array.
We have to reshape the input to ( , 1, 28, 28) or possibly to ( , 28, 28, 1), depending on your setup and backend (theano or tensorlow image layout convention).

```<code>from keras import backend as K
if K.image_data_format() == 'channels_first' :
   input_shape = (1, 28, 28)
   X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
   X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
else:
   input_shape = (28, 28, 1)
   X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
   X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
</code>```

So, you should reshape your data to (60000, 28, 28, 1) or (60000, 1, 28, 28)

Body:
I am setting up my first neural network with keras and tensorflow. I got my input into an array of shape (60000, 28, 28), but when I try and feed it to the model I get an error that the input shape is wrong.

I have tried multiple different input shapes including (60000, 28, 28) (1, 28, 28) (28, 28) (28, 28, 1) but none of them seem to work.

model = kr.Sequential()

model.add(InputLayer(input_shape=(60000, 28, 28)))
model.add(Dense(units=784, activation='relu'))
model.add(Dense(units=392, activation='relu'))
model.add(Dense(units=196, activation='relu'))
model.add(Dense(units=10, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])

training = model.fit(x=images_array, y=labels_array, epochs=10, batch_size=256)

I would expect it to work with input shape (60000, 28, 28) but I always get this error:

ValueError: Error when checking input: expected input_1 to have 4
  dimensions, but got array with shape (60000, 28, 28)

Edit:

Thanks to everyone who answerd. cho_uc answer indeed worked, which is why I accepted it.
What I shold have mentioned in the post was, that I was trying to build a model consisting only of Dense layers, so I can use it as a benchmark for future models.

I solved the input layer problem with:

images_array = images_array.reshape(-1, 28 * 28)

model.add(InputLayer(input_shape=(784, )))

Body:
Keras Conv2D layer performs the convolution operation. It requires its input to be a 4-dimensional array.
We have to reshape the input to ( , 1, 28, 28) or possibly to ( , 28, 28, 1), depending on your setup and backend (theano or tensorlow image layout convention).

from keras import backend as K
if K.image_data_format() == 'channels_first' :
   input_shape = (1, 28, 28)
   X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
   X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
else:
   input_shape = (28, 28, 1)
   X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
   X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)

So, you should reshape your data to (60000, 28, 28, 1) or (60000, 1, 28, 28)


问:
Conditional Forcasting with VAR model in python
I am using VAR model to forecast multivariate time series with lag 2. I have three features, and would like to forcast several timestamps forward. Instead of forcasting all the three features, I actually know the values of two of the features, and would like to forcast only one feature.

If I wanted to forcast all the three features 5 timestamps a head, I could have done that as follows (this is a toy example):

```<code>import pandas as pd
from statsmodels.tsa.api import VAR
data=pd.DataFrame({'Date':['1959-06-01','1959-06-02','1959-06-03','1959-06-04']\
                   ,'a':[1,2,3,5],'b':[2,3,5,8],'c':[3,4,7,11]})
data.set_index('Date', inplace=True)
model = VAR(data)
results = model.fit(2)
results.forecast(data.values[-2:], 5)
</code>```

Note that data is

```<code>            a  b   c
Date
1959-06-01  1  2   3
1959-06-02  2  3   4
1959-06-03  3  5   7
1959-06-04  5  8  11
</code>```

And the forecast gives me

```<code>array([[   8.01388889,   12.90277778,   17.79166667],
       [  12.93113426,   20.67650463,   28.421875  ],
       [  20.73343461,   33.12405961,   45.51468461],
       [  33.22366195,   52.98948789,   72.75531383],
       [  53.15895736,   84.72805652,  116.29715569]])
</code>```

Let's say I knew that the next 5 values for a should have actually been 8,13,21,34,55 and the next 5 values for b should have been 13,21,34,55,89. Is there a way to incorporate that into the model in statsmodels.tsa (or any other python package) to forecast only the 5 values of c? I know that R has such an option, by incorporating "hard" conditions into cpredict.VAR, but I was wondering if this can be done in python as well.

The above is a toy example. In reality I have several dozens of features, but I still know all of them and would like predict only one of them using VAR model.

答:
I have a similar issue when solving this problem. This is a makeshift method to accomplish what you are asking.</p>

```<code>prediction = model_fit.forecast(model_fit.y, steps=len(test))
predictions = prediction[:,0]
</code>```

<p>`
Where 0 in the prediction[:,0] refers to the column that contains the desired forecasting value. </p>

Body:
I am using VAR model to forecast multivariate time series with lag 2. I have three features, and would like to forcast several timestamps forward. Instead of forcasting all the three features, I actually know the values of two of the features, and would like to forcast only one feature.

If I wanted to forcast all the three features 5 timestamps a head, I could have done that as follows (this is a toy example):

import pandas as pd
from statsmodels.tsa.api import VAR
data=pd.DataFrame({'Date':['1959-06-01','1959-06-02','1959-06-03','1959-06-04']\
                   ,'a':[1,2,3,5],'b':[2,3,5,8],'c':[3,4,7,11]})
data.set_index('Date', inplace=True)
model = VAR(data)
results = model.fit(2)
results.forecast(data.values[-2:], 5)

Note that data is

            a  b   c
Date
1959-06-01  1  2   3
1959-06-02  2  3   4
1959-06-03  3  5   7
1959-06-04  5  8  11

And the forecast gives me

array([[   8.01388889,   12.90277778,   17.79166667],
       [  12.93113426,   20.67650463,   28.421875  ],
       [  20.73343461,   33.12405961,   45.51468461],
       [  33.22366195,   52.98948789,   72.75531383],
       [  53.15895736,   84.72805652,  116.29715569]])

Let's say I knew that the next 5 values for a should have actually been 8,13,21,34,55 and the next 5 values for b should have been 13,21,34,55,89. Is there a way to incorporate that into the model in statsmodels.tsa (or any other python package) to forecast only the 5 values of c? I know that R has such an option, by incorporating "hard" conditions into cpredict.VAR, but I was wondering if this can be done in python as well.

The above is a toy example. In reality I have several dozens of features, but I still know all of them and would like predict only one of them using VAR model.

Body:
I have a similar issue when solving this problem. This is a makeshift method to accomplish what you are asking.

prediction = model_fit.forecast(model_fit.y, steps=len(test))
predictions = prediction[:,0]

`
Where 0 in the prediction[:,0] refers to the column that contains the desired forecasting value.


问:
ob_get_contents + ob_end_clean vs ob_get_clean
Is there any difference between these two pieces of PHP?

```<code>ob_start();
//code...
$pageContent = ob_get_contents();
ob_end_clean();
someFunction($pageContent);
</code>```

vs

```<code>ob_start();
//code...
$pageContent=ob_get_clean();
someFunction($pageContent);
</code>```

I am currently using the first block, but I would like to use the second instead if it is functionally equivalent, since it is a bit more concise.

答:
Based on the documentation,

ob_get_contents() + ob_end_clean()

is supposed to work the same as:

ob_get_clean()

However, because of a bug in PHP, it doesn't. Roland from nextendweb filed a bug report:

https://bugs.php.net/bug.php?id=76563

If you use ob_start with callback, the callback does not run, if you use ob_get_clean() on the same output buffer. The callback get skipped, which gives unexpected results. I think it is a bug.

So, if you're passing a callback to ob_start(), you'll need to use

```<code>$content = ob_get_contents();
ob_clean();
</code>```

instead of:

```<code>$content = ob_get_clean();
</code>```

Testing on sandbox, you will notice that it affects all PHP versions.

Body:
Is there any difference between these two pieces of PHP?

ob_start();
//code...
$pageContent = ob_get_contents();
ob_end_clean();
someFunction($pageContent);

vs

ob_start();
//code...
$pageContent=ob_get_clean();
someFunction($pageContent);

I am currently using the first block, but I would like to use the second instead if it is functionally equivalent, since it is a bit more concise.

Body:
Based on the documentation,

ob_get_contents() + ob_end_clean()

is supposed to work the same as:

ob_get_clean()

However, because of a bug in PHP, it doesn't. Roland from nextendweb filed a bug report:

https://bugs.php.net/bug.php?id=76563

If you use ob_start with callback, the callback does not run, if you use ob_get_clean() on the same output buffer. The callback get skipped, which gives unexpected results. I think it is a bug.

So, if you're passing a callback to ob_start(), you'll need to use

$content = ob_get_contents();
ob_clean();

instead of:

$content = ob_get_clean();

Testing on sandbox, you will notice that it affects all PHP versions.


问:
How to stop console window from closing immediately | GNAT - GPS
I have Ada program that runs and compile perfectly using GNAT - GPS. When I run its exe file and provide user input then instead of saying "Press any key to continue", the exe closes immediately.

I have searched for it online alot but i only found info related to c/c++/visual studio console window using system('pause'); OR Console.Readline().

Is there any way around for this in Ada lanaguage?

答:
The same way you could use Console.Readline(), you can use Get_Line from the package Ada.Text_IO.
In this case, you will have to put the result into a String that you won't use.


问:
I need help to create an algorithm to return a list of possible groups of numbers from a list of numbers
One of the parts of a search algorithm I need to develop consists of a function that receives a list of integers and returns a list of list of integers based on some rules, here are the specifications.

The input list can have any amount of numbers varying from a min and max pre-determined values. The function needs to return all possible combinations of the input numbers that are sequencial and has a size that is 3 or greater.

The order of the ouput groups is not important.

As an example:

```<code>min = 1;
max = 10;

input = [1, 2, 3, 4, 6, 7, 8]

output = [ [1, 2, 3], [2, 3, 4], [1, 2, 3, 4], [6, 7, 8] ]
</code>```

The trick part is that the input list can receive any number of joker characters. Theses jokers can assume any value within the min and max values.

An example using jokers:

```<code>min = 1;
max = 10;

input = [1, 2, 3, 4, 6, 7, 8, J]

output = [
    [1, 2, 3],
    [2, 3, 4],
    [1, 2, 3, 4],
    [6, 7, 8],
    [1, 2, 3, 4, J, 6, 7, 8],
    [2, 3, 4, J, 6, 7, 8],
    [3, 4, J, 6, 7, 8],
    [4, J, 6, 7, 8],
    [J, 6, 7, 8],
    [6, 7, 8, J],
    [7, 8, J],
    [1, 2, 3, 4, J, 6, 7],
    [1, 2, 3, 4, J, 6],
    [1, 2, 3, 4, J, 6],
    [1, 2, 3, 4, J]
]
</code>```

When working with any possible number of jokers in the input I cannot come up with any algorithm that can solve this problem.

Are there any suggestions or pseudo code you could share to help me with this problem?

答:
Here's a recursion that may need tweaking depending on your needs. The idea is to enumerate to each possible ending point from each possible starting point. Jokers are only used for numbers not in the list. Since the list can be sparse, one way is to treat each number as a node in a graph, performing a search on still unseen starting points.

JavaScript code:

function f(A, jokerMin, jokerMax, globalMin, globalMax, minSeqLen){
  // Record available elements
  let sansJokers = A.filter(x => x != 'J');
  let numbers = new Set(sansJokers);
  let numJokers = A.length - sansJokers.length;
  let seen = new Set();

  // Given a starting point,
  // go as far as possible
  function g(js, n, comb){
    let result = comb.length >= minSeqLen ? [comb] : [];

    if (globalMin <= n && n <= globalMax){
      if (numbers.has(n)){
        return result.concat(
          g(js, n + 1, comb.slice().concat(n)));

      } else if (js && jokerMin <= n && n <= jokerMax){
        return result.concat(
          g(js - 1, n + 1, comb.slice().concat('J')));

      } else {
        return result;
      }

    } else {
      return result;
    }
  }

  let result = [];

  // Find starting points

  // If there are at least minSeqLen
  // jokers, we can start anywhere.
  // Otherwise, look only below
  // existing numbers since a pure
  // joker sequence will have to
  // connect to a number to be valid
  if (numJokers >= minSeqLen){
    return ['Enough jokers to start anywhere'];

  } else {
    for (let n of numbers){
      // search lower
      let tempN = n - 1;

      while (!seen.has(tempN) &&
        !numbers.has(tempN) &&
        tempN >= globalMin &&
        tempN >= jokerMin){

        seen.add(tempN);
        result = result.concat(
          g(numJokers, tempN, []));
        tempN--;
      }

      seen.add(n);
      result = result.concat(
        g(numJokers, n, []));
    }
  }

  return result;
}

var jokerMin = 1;
var jokerMax = 10;
var globalMin = 1;
var globalMax = 15;
var minSeqLen = 3;

var input = [1, 2, 3, 4, 7, 8, 'J', 'J']

let str = '';

for (let comb of f(input, jokerMin, jokerMax, globalMin, globalMax, minSeqLen))
  str += JSON.stringify(comb) + '\n';

console.log(str);```

Body:
One of the parts of a search algorithm I need to develop consists of a function that receives a list of integers and returns a list of list of integers based on some rules, here are the specifications.

The input list can have any amount of numbers varying from a min and max pre-determined values. The function needs to return all possible combinations of the input numbers that are sequencial and has a size that is 3 or greater.

The order of the ouput groups is not important.

As an example:

min = 1;
max = 10;

input = [1, 2, 3, 4, 6, 7, 8]

output = [ [1, 2, 3], [2, 3, 4], [1, 2, 3, 4], [6, 7, 8] ]

The trick part is that the input list can receive any number of joker characters. Theses jokers can assume any value within the min and max values.

An example using jokers:

min = 1;
max = 10;

input = [1, 2, 3, 4, 6, 7, 8, J]

output = [
    [1, 2, 3],
    [2, 3, 4],
    [1, 2, 3, 4],
    [6, 7, 8],
    [1, 2, 3, 4, J, 6, 7, 8],
    [2, 3, 4, J, 6, 7, 8],
    [3, 4, J, 6, 7, 8],
    [4, J, 6, 7, 8],
    [J, 6, 7, 8],
    [6, 7, 8, J],
    [7, 8, J],
    [1, 2, 3, 4, J, 6, 7],
    [1, 2, 3, 4, J, 6],
    [1, 2, 3, 4, J, 6],
    [1, 2, 3, 4, J]
]

When working with any possible number of jokers in the input I cannot come up with any algorithm that can solve this problem.

Are there any suggestions or pseudo code you could share to help me with this problem?


问:
Is it a good practice to manually create indexes for the primary keys?
I am recently working with Entity Framework Core and I have some issue about the relation between the primary key and the indexes.

To be more concrete, I found out that in a table containing composite primary keys an index is created for the second property of the key.

You can see an example here

Can you explain me if I should manually create another index for the first one? Or is a clustered index created for that first property?

答:
Generally an index on a set of columns can be used even if a query is only searching some of the columns, with the restriction that the query must ask for columns from the index left to right, no gaps

Thus if a set of columns A,B,C,D are indexed, this index can still be used to answer queries that are filtering on A, A and B, A and B and C.

Thus you don't need to index NoteID separately, because the index that aids the primary key (NoteID, CategoryID) can be used by queries calling for just NoteID. It cannot, however, be used to answer queries calling for just CategoryID, hence the separate index being created

As an aside, you might find, in some cases, that you can supply values in a where clause that have no purpose other than to encourage use of an index that covers them. Suppose, for example, that a table has an index on Name, Gender, Age, and you want all 20 year old people named Steven. If you can reasonably assert that Steven is always male, you can WHERE Name = 'Steven' AND Gender = 'M' AND Age = 20 - even though the Gender of M is redundant, specifying it will let the DB engine use that index. Omitting it means the DB will have a much harder job of figuring out whether to use the index or not

You can also re-arrange index ordering to help your application perform, and give the DB fewer indexes to maintain.. If all your queries will only ever ask for A, A+C or A+B+C, it would be better to specify the index for the columns in the order A,C,B then a single index can cover all queries, rather than having to maintain an index of A+B+C and another of A+C


问:
switch statement reverting to default regardless of user input?
What I want the program to do is ask for user input, take a number 1-7, and spit out the correct WriteLine statement. Everything compiles fine but I get the default WriteLine option no matter what number I enter. Where am I going wrong?

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

namespace week4discussion
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a number: ");
            int userInput = Console.Read();

            switch (userInput) {
                case 1:
                    Console.WriteLine("Your selected course is IT 145");
                    break;
                case 2:
                    Console.WriteLine("Your selected course is IT 200");
                    break;
                case 3:
                    Console.WriteLine("Your selected course is IT 201");
                    break;
                case 4:
                    Console.WriteLine("Your selected course is IT 270");
                    break;
                case 5:
                    Console.WriteLine("Your selected course is IT 315");
                    break;
                case 6:
                    Console.WriteLine("Your selected course is IT 328");
                    break;
                case 7:
                    Console.WriteLine("Your selected course is IT 330");
                    break;
                default:
                    Console.WriteLine("Please enter a number 1-7");
                    break;

            }
        }
    }
}
```

答:
You need this: </p>

```<code> int userInput = Convert.ToInt32(Console.ReadLine());
</code>```

Body:
You need this:

 int userInput = Convert.ToInt32(Console.ReadLine());


问:
Boost Random Number Not Change
I have some problem when generating random number with boost library in CPP. When I try printout random number, the value return same value. Here is my code.

for(int i = 0; i < TOTAL_PARTICLES; i++) {
            boost::random::mt19937 engine(static_cast<unsigned int>(std::time(0)));
            randn = boost::bind(boost::random::uniform_real_distribution<>(-2.5, 2.5), engine);
            cout << "Random : " << randn() << endl;
        }
```

答:
You're using the same engine seed every time, and therefore you'll receive the same set of random numbers each and every time. Therefore simply seed the engine outside of the for loop like so:</p>

```<code>boost::random::mt19937 engine(static_cast<unsigned int>(std::time(0)));
for(int i = 0; i < TOTAL_PARTICLES; i++)
{
    randn = boost::bind(boost::random::uniform_real_distribution<>(-2.5, 2.5), engine);
    cout << "Random : " << randn() << endl;
}
</code>```

Title: Boost Random Number Not Change

Body:
You're using the same engine seed every time, and therefore you'll receive the same set of random numbers each and every time. Therefore simply seed the engine outside of the for loop like so:

boost::random::mt19937 engine(static_cast<unsigned int>(std::time(0)));
for(int i = 0; i < TOTAL_PARTICLES; i++)
{
    randn = boost::bind(boost::random::uniform_real_distribution<>(-2.5, 2.5), engine);
    cout << "Random : " << randn() << endl;
}


问:
How can I solve "ReferenceError: expect is not defined" error message?
I am trying to test Javascript with mocha. I've this snippet of code:

```<code>describe('Array', function() {
    describe('indexOf()', function() {
        it("dovrebbe tornare -1 quando l'elemento non è presente", function() {
            expect([1,2,3].indexOf(4)).to.equal(-1)
        })
    })
})
</code>```

and a test/array.js file. Mocha was installed with

```<code>$ npm install -g mocha
</code>```

When I run

```<code>$ mocha
</code>```

I get this error:

```<code>$ mocha
․

0 passing (5ms)
1 failing

1) Array indexOf() dovrebbe tornare -1 quando l'elemento non è presente:
 ReferenceError: expect is not defined
  at Context.<anonymous> (/Users/simonegentili/Desktop/Javascipt Best Practice/test/array.js:4:4)
  at Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:211:32)
  at Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:358:10)
  at /usr/local/lib/node_modules/mocha/lib/runner.js:404:12
  at next (/usr/local/lib/node_modules/mocha/lib/runner.js:284:14)
  at /usr/local/lib/node_modules/mocha/lib/runner.js:293:7
  at next (/usr/local/lib/node_modules/mocha/lib/runner.js:237:23)
  at Object._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:261:5)
  at processImmediate [as _immediateCallback] (timers.js:317:15)
</code>```

答:
Either add this script tag in html file

```<code><script src="https://unpkg.com/expect@%3C21/umd/expect.min.js"></script>
</code>```

or install package

```<code>npm install chai or expect
</code>```

Body:
I am trying to test Javascript with mocha. I've this snippet of code:

describe('Array', function() {
    describe('indexOf()', function() {
        it("dovrebbe tornare -1 quando l'elemento non è presente", function() {
            expect([1,2,3].indexOf(4)).to.equal(-1)
        })
    })
})

and a test/array.js file. Mocha was installed with

$ npm install -g mocha

When I run

$ mocha

I get this error:

$ mocha
․

0 passing (5ms)
1 failing

1) Array indexOf() dovrebbe tornare -1 quando l'elemento non è presente:
 ReferenceError: expect is not defined
  at Context.<anonymous> (/Users/simonegentili/Desktop/Javascipt Best Practice/test/array.js:4:4)
  at Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:211:32)
  at Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:358:10)
  at /usr/local/lib/node_modules/mocha/lib/runner.js:404:12
  at next (/usr/local/lib/node_modules/mocha/lib/runner.js:284:14)
  at /usr/local/lib/node_modules/mocha/lib/runner.js:293:7
  at next (/usr/local/lib/node_modules/mocha/lib/runner.js:237:23)
  at Object._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:261:5)
  at processImmediate [as _immediateCallback] (timers.js:317:15)

Body:
Either add this script tag in html file

<script src="https://unpkg.com/expect@%3C21/umd/expect.min.js"></script>

or install package

npm install chai or expect


问:
Why is dask returning none on a CUDA function?
I'm trying to layer dask on top of my cuda functions, but when dask returns I get a  NoneType object.

from numba import cuda
import numpy as np
from dask.distributed import Client, LocalCluster

@cuda.jit()
def addingNumbersCUDA (big_array, big_array2, save_array):
    i = cuda.grid(1)
    if i < big_array.shape[0]:
        for j in range (big_array.shape[1]):
            save_array[i][j] = big_array[i][j] * big_array2[i][j]

if __name__ == "__main__":
    cluster = LocalCluster()
    client = Client(cluster)

    big_array = np.random.random_sample((100, 3000))
    big_array2  = np.random.random_sample((100, 3000))
    save_array = np.zeros(shape=(100, 3000))

    arraysize = 100
    threadsperblock = 64
    blockspergrid = (arraysize + (threadsperblock - 1))

    x = client.submit(addingNumbersCUDA[blockspergrid, threadsperblock], big_array, big_array2, save_array)

    y = client.gather(x)
    print(y)
```

I understand that you don't actually return in a cuda function and that the results are pushed back to the array you called in. Is this why I'm getting a noneType, or is it because I'm using dask wrong for cuda?

答:
As pointed out in this question: How to use Dask to run python code on the GPU? by Matthew Rocklin, dask can't handle in-place operations. In order to account for this it would be better to add an additional function that handles the gpu code.

from numba import cuda
import numpy as np
from dask.distributed import Client, LocalCluster

@cuda.jit()
def addingNumbersCUDA (big_array, big_array2, save_array):
    i = cuda.grid(1)
    if i < big_array.shape[0]:
        for j in range (big_array.shape[1]):
            save_array[i][j] = big_array[i][j] * big_array2[i][j]

def toCUDA (big_array, big_array2, save_array):
    arraysize = 100
    threadsperblock = 64
    blockspergrid = (arraysize + (threadsperblock - 1))

    d_big_array = cuda.to_device(big_array)
    d_big_array2 = cuda.to_device(big_array2)
    d_save_array = cuda.to_device(save_array)

    addingNumbersCUDA[blockspergrid, threadsperblock](d_big_array, d_big_array2, d_save_array)

    save_array = d_save_array.copy_to_host()
    return save_array

if __name__ == "__main__":
    cluster = LocalCluster()
    client = Client(cluster)

    big_array = np.random.random_sample((100, 3000))
    big_array2  = np.random.random_sample((100, 3000))
    save_array = np.zeros(shape=(100, 3000))

    x = client.submit(toCUDA, big_array, big_array2, save_array)

    y = client.gather(x)
    print(y)
```

Body:
I'm trying to layer dask on top of my cuda functions, but when dask returns I get a  NoneType object.

from numba import cuda
import numpy as np
from dask.distributed import Client, LocalCluster

@cuda.jit()
def addingNumbersCUDA (big_array, big_array2, save_array):
    i = cuda.grid(1)
    if i < big_array.shape[0]:
        for j in range (big_array.shape[1]):
            save_array[i][j] = big_array[i][j] * big_array2[i][j]

if __name__ == "__main__":
    cluster = LocalCluster()
    client = Client(cluster)

    big_array = np.random.random_sample((100, 3000))
    big_array2  = np.random.random_sample((100, 3000))
    save_array = np.zeros(shape=(100, 3000))

    arraysize = 100
    threadsperblock = 64
    blockspergrid = (arraysize + (threadsperblock - 1))

    x = client.submit(addingNumbersCUDA[blockspergrid, threadsperblock], big_array, big_array2, save_array)

    y = client.gather(x)
    print(y)

I understand that you don't actually return in a cuda function and that the results are pushed back to the array you called in. Is this why I'm getting a noneType, or is it because I'm using dask wrong for cuda?


问:
How to fix duplicate values while writing json in python
I have two files, after reading both files I am writing it to a json file in python. Problem is in the final json file I am getting duplicate json object (last json object appended).

I am able to read files and generate json file.

```<code>import json

data2 = {}
data1 = []
i = 1

with open('abc3') as json_file:
    f=open("abc2", "r")
    data = json.load(json_file)
    lines =f.readlines()
    for p,x in zip(data['Url'],lines):
        print(p['Urls'])
        print(x)
        print(i)
        print('')
        data2['videoId'] = i
        data2['videoUrl'] = p['Urls']
        data2['videName'] = x
        i = i + 1
        data1.extend(data2)

with open('data1.json', 'w') as outfile:
    json.dump(data1, outfile)
</code>```

答:
reusing the same reference of data2 is the main issue. Create a dictionary at each iteration.

And if you do data1.extend(data2), extend iterates on the keys of the dictionary, when you want to create a list of dictionaries.

Quickfix:

```<code>for p,x in zip(data['Url'],lines):
    print(p['Urls'])
    print(x)
    print(i)
    print('')
    data2 = {}
    data2['videoId'] = i
    data2['videoUrl'] = p['Urls']
    data2['videName'] = x
    i = i + 1
    data1.append(data2)
</code>```

but a list comprehension would be clearer and more pythonic (note: don't read the lines, use f directly, it will avoid a useless file read):

```<code>data1 = [{"videoId":i,"videoUrl":p['Urls'],'videoName':x.rstrip()}
          for i,(p,x) in enumerate(zip(data['Url'],f),1)]
</code>```

this creates a dictionary per iteration. i side-effect is replaced by the use of enumerate (starting at 1). Note the rstrip() operation needed to remove the end of line character when reading a file line by line.

To sum it up, here's how I'd rewrite the full code:

```<code>import json

with open('abc3') as json_file:
    data = json.load(json_file)

with open("abc2") as f:
    data1 = [{"videoId":i,"videoUrl":p['Urls'],'videoName':x.rstrip()}
              for i,(p,x) in enumerate(zip(data['Url'],f),1)]

with open('data1.json', 'w') as outfile:
    json.dump(data1, outfile)
</code>```

Body:
I have two files, after reading both files I am writing it to a json file in python. Problem is in the final json file I am getting duplicate json object (last json object appended).

I am able to read files and generate json file.

import json

data2 = {}
data1 = []
i = 1

with open('abc3') as json_file:
    f=open("abc2", "r")
    data = json.load(json_file)
    lines =f.readlines()
    for p,x in zip(data['Url'],lines):
        print(p['Urls'])
        print(x)
        print(i)
        print('')
        data2['videoId'] = i
        data2['videoUrl'] = p['Urls']
        data2['videName'] = x
        i = i + 1
        data1.extend(data2)

with open('data1.json', 'w') as outfile:
    json.dump(data1, outfile)

Body:
reusing the same reference of data2 is the main issue. Create a dictionary at each iteration.

And if you do data1.extend(data2), extend iterates on the keys of the dictionary, when you want to create a list of dictionaries.

Quickfix:

for p,x in zip(data['Url'],lines):
    print(p['Urls'])
    print(x)
    print(i)
    print('')
    data2 = {}
    data2['videoId'] = i
    data2['videoUrl'] = p['Urls']
    data2['videName'] = x
    i = i + 1
    data1.append(data2)

but a list comprehension would be clearer and more pythonic (note: don't read the lines, use f directly, it will avoid a useless file read):

data1 = [{"videoId":i,"videoUrl":p['Urls'],'videoName':x.rstrip()}
          for i,(p,x) in enumerate(zip(data['Url'],f),1)]

this creates a dictionary per iteration. i side-effect is replaced by the use of enumerate (starting at 1). Note the rstrip() operation needed to remove the end of line character when reading a file line by line.

To sum it up, here's how I'd rewrite the full code:

import json

with open('abc3') as json_file:
    data = json.load(json_file)

with open("abc2") as f:
    data1 = [{"videoId":i,"videoUrl":p['Urls'],'videoName':x.rstrip()}
              for i,(p,x) in enumerate(zip(data['Url'],f),1)]

with open('data1.json', 'w') as outfile:
    json.dump(data1, outfile)


问:
findIndex method gives undefined in ExpressJS server update method
I want to update the user object in an express js server from an HTTP request. A put request is sent to the server with the user id. I want to extract the user object from the user array using findIndex method but it returns undefined

here is there ExpressJS server

```<code>const express = require('express');
const BodyParser = require('body-parser');
const cors =require('cors');
const User = require('./user');
const PORT = 4000;
const app =express();
const appRoute = express.Router();
const  userarray = [];

app.use(cors());
app.use(BodyParser.json());

app.use('/api/user',appRoute);

app.listen(PORT ,function () {
    console.log("Sever is running on : " + PORT);
});

appRoute.route('/update/:id').put(function (req,res){
    try{

        const index = userarray.findIndex(instance => instance.id === req.param.id);
        userarray[index].firstName = req.body.fname;
        userarray[index].lastName = req.body.lname;
        userarray[index].BirtDay = req.body.date;

        res.status(200).send({message:"User updated"})

    }catch (e) {
        res.status(400).send({message:"Unable to get the users.ERROR:" +e})
    }
});

</code>```

Her is the user model

```<code>const  User = function(fname,lname,bday,id){

    this.firstname =  fname;
    this.lastname = lname;
    this.Birthday = bday;
    this.ID =id;
}

module.exports = User;`
</code>```

The ID is there in the array list. So the codes work before but I tried it again and it didn't work. I want to know why.

答:
Yes, Error can be recreated successfully. By replacing this code

const index = userarray.findIndex(instance => instance.id === req.param.id);```
</div>
</div>
</p>

<p>By using this code,</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const index = userarray.findIndex(instance => instance.id == req.params.id);</code>```

User can be updated successfully!!

The reason that I found first was, "==" sign can be used to compare strings and numbers but not "===". Second one was, it should be params but not param because it is now deprecated and also, by using params, it will directly look into route parameters. I hope my answer and the explanation is clear to you  !

Body:
I want to update the user object in an express js server from an HTTP request. A put request is sent to the server with the user id. I want to extract the user object from the user array using findIndex method but it returns undefined

here is there ExpressJS server

const express = require('express');
const BodyParser = require('body-parser');
const cors =require('cors');
const User = require('./user');
const PORT = 4000;
const app =express();
const appRoute = express.Router();
const  userarray = [];

app.use(cors());
app.use(BodyParser.json());

app.use('/api/user',appRoute);

app.listen(PORT ,function () {
    console.log("Sever is running on : " + PORT);
});

appRoute.route('/update/:id').put(function (req,res){
    try{

        const index = userarray.findIndex(instance => instance.id === req.param.id);
        userarray[index].firstName = req.body.fname;
        userarray[index].lastName = req.body.lname;
        userarray[index].BirtDay = req.body.date;

        res.status(200).send({message:"User updated"})

    }catch (e) {
        res.status(400).send({message:"Unable to get the users.ERROR:" +e})
    }
});

Her is the user model

const  User = function(fname,lname,bday,id){

    this.firstname =  fname;
    this.lastname = lname;
    this.Birthday = bday;
    this.ID =id;
}

module.exports = User;`

The ID is there in the array list. So the codes work before but I tried it again and it didn't work. I want to know why.

Body:
Yes, Error can be recreated successfully. By replacing this code

const index = userarray.findIndex(instance => instance.id === req.param.id);

By using this code,

const index = userarray.findIndex(instance => instance.id == req.params.id);

User can be updated successfully!!

The reason that I found first was, "==" sign can be used to compare strings and numbers but not "===". Second one was, it should be params but not param because it is now deprecated and also, by using params, it will directly look into route parameters. I hope my answer and the explanation is clear to you  !


问:
Use type to access properties instead of concrete instance
I'm having trouble figuring out how to ask this question (the title is not worded well), so let me start with an example using the NameOf() method, because it does something similar to what I'm trying to accomplish.

If I have a class like this:

Public Class MyClass
    Public Property Foo As Bar
End Class
```

<p>and then I declare an instance of it <code>Dim instance As New MyClass</code>, I can then use the <code>NameOf()</code> method in one of two ways:</p>

<pre class="lang-vb prettyprint-override"><code>' Both of these lines will print "Foo"
Console.WriteLine(NameOf(instance.Foo))
Console.WriteLine(NameOf(MyClass.Foo))
</code>```

I would like to implement a method that can accept similar types of parameters, but I cannot figure out how.
Here is the (extension) method I wrote:

<Extension()>
Public Function GetPathOfProperty(Of T As Class, TProp)(myObj As T, prop As Expression(Of Func(Of TProp))) As String
    Dim result As String = String.Empty
    Dim foundName As String = String.Empty
    Dim className As String = myObj.GetType().Name
    Dim p As MemberExpression = TryCast(prop.Body, MemberExpression)

    While p IsNot Nothing
        If className = p.Member.DeclaringType.Name Then
            foundName = className + "."
        End If

        result = foundName + p.Member.Name + "." + result
        If Not String.IsNullOrEmpty(foundName) Then
            Exit While
        End If
        p = TryCast(p.Expression, MemberExpression)
    End While

    Return IIf(String.IsNullOrEmpty(foundName), "", result.Substring(0, result.Length - 1))
End Function
```

<p>Using my above example, I can use it like this:</p>

<pre class="lang-vb prettyprint-override"><code>' Prints "MyClass.Foo"
Console.WriteLine(instance.GetPathOfProperty(Function() instance.Foo))
' Prints "MyClass.Foo.SomeBarProperty"
Console.WriteLine(instance.GetPathOfProperty(Function() instance.Foo.SomeBarProperty))
</code>```

I would like to create another version of this method that is not an extension method, but rather a static method that can be called like (or similar to) this:

Console.WriteLine(GetPathOfProperty(Function() MyClass.Foo) ' Prints "MyClass.Foo"
```

This way I'd be able to use the function without actually creating an instance of MyClass first. And this is where I need help. Since MyClass is not a static class, I'm not able to put MyClass.Foo in the function call. My first thought was to use Reflection, but I can't figure out how. Is there a parameter type I could use to allow me to do this (and if so, how would that look)? Or is this just a pipe-dream and not possible?

答:
You can't pass in a direct reference to a property on a type, but you can cheat using lambda expressions (Function delegates) by typing the parameter to the delegate (essentially a static open instance delegate).

Here is my module to return a path reference from an instance or from a type:

```<code>Public Module PropertyExt
    <Extension()>
    Public Function TrimStart(Byval src As String, starter As String) As String
        Return If(src.StartsWith(starter), src.Substring(starter.Length), src)
    End Function

    Public Function GetPathOfInstanceProperty(Of TRes)(e As Expression(Of Func(Of TRes))) As String
        Dim b = TryCast(e.Body, MemberExpression)
        Dim ans = ""
        Do
            ans = b.Member.Name.TrimStart("$VB$Local_") & "." & ans
            b = TryCast(b.Expression, MemberExpression)
        Loop While (b IsNot Nothing)
        Return ans.TrimEnd(".")
    End Function

    Public Function GetPathOfTypeProperty(Of T,TRes)(e As Expression(Of Func(Of T,TRes))) As String
        Dim b = TryCast(e.Body, MemberExpression)
        Dim ans = ""
        Do
            ans = b.Member.Name.TrimStart("$VB$Local_") & "." & ans
            Dim tryB = TryCast(b.Expression, MemberExpression)
            If tryB Is Nothing Then
                Dim tryParm = TryCast(b.Expression, ParameterExpression)
                If tryParm IsNot Nothing Then
                    ans = tryParm.Type.Name & "." & ans
                End If
            End If
            b = tryB
        Loop While (b IsNot Nothing)
        Return ans.TrimEnd(".")
    End Function
End Module
</code>```

Which you can use like so:

```<code>Dim cf = New CInstance()
Dim ipe = PropertyExt.GetPathOfInstanceProperty(Function() cf.Foo.SomeBarProperty)
Dim tpe = PropertyExt.GetPathOfTypeProperty(Function(i As CInstance) i.Foo.SomeBarProperty)
</code>```

NOTE: VB also seems to rename local variables so I added some code to drop the $VB$Local_ prefix from names - this can be removed if not needed.

PS This seems a lot cleaner/simpler in C# ;)

Body:
I'm having trouble figuring out how to ask this question (the title is not worded well), so let me start with an example using the NameOf() method, because it does something similar to what I'm trying to accomplish.

If I have a class like this:

Public Class MyClass
    Public Property Foo As Bar
End Class

and then I declare an instance of it Dim instance As New MyClass, I can then use the NameOf() method in one of two ways:

' Both of these lines will print "Foo"
Console.WriteLine(NameOf(instance.Foo))
Console.WriteLine(NameOf(MyClass.Foo))

I would like to implement a method that can accept similar types of parameters, but I cannot figure out how.
Here is the (extension) method I wrote:

<Extension()>
Public Function GetPathOfProperty(Of T As Class, TProp)(myObj As T, prop As Expression(Of Func(Of TProp))) As String
    Dim result As String = String.Empty
    Dim foundName As String = String.Empty
    Dim className As String = myObj.GetType().Name
    Dim p As MemberExpression = TryCast(prop.Body, MemberExpression)

    While p IsNot Nothing
        If className = p.Member.DeclaringType.Name Then
            foundName = className + "."
        End If

        result = foundName + p.Member.Name + "." + result
        If Not String.IsNullOrEmpty(foundName) Then
            Exit While
        End If
        p = TryCast(p.Expression, MemberExpression)
    End While

    Return IIf(String.IsNullOrEmpty(foundName), "", result.Substring(0, result.Length - 1))
End Function

Using my above example, I can use it like this:

' Prints "MyClass.Foo"
Console.WriteLine(instance.GetPathOfProperty(Function() instance.Foo))
' Prints "MyClass.Foo.SomeBarProperty"
Console.WriteLine(instance.GetPathOfProperty(Function() instance.Foo.SomeBarProperty))

I would like to create another version of this method that is not an extension method, but rather a static method that can be called like (or similar to) this:

Console.WriteLine(GetPathOfProperty(Function() MyClass.Foo) ' Prints "MyClass.Foo"

This way I'd be able to use the function without actually creating an instance of MyClass first. And this is where I need help. Since MyClass is not a static class, I'm not able to put MyClass.Foo in the function call. My first thought was to use Reflection, but I can't figure out how. Is there a parameter type I could use to allow me to do this (and if so, how would that look)? Or is this just a pipe-dream and not possible?

Body:
You can't pass in a direct reference to a property on a type, but you can cheat using lambda expressions (Function delegates) by typing the parameter to the delegate (essentially a static open instance delegate).

Here is my module to return a path reference from an instance or from a type:

Public Module PropertyExt
    <Extension()>
    Public Function TrimStart(Byval src As String, starter As String) As String
        Return If(src.StartsWith(starter), src.Substring(starter.Length), src)
    End Function

    Public Function GetPathOfInstanceProperty(Of TRes)(e As Expression(Of Func(Of TRes))) As String
        Dim b = TryCast(e.Body, MemberExpression)
        Dim ans = ""
        Do
            ans = b.Member.Name.TrimStart("$VB$Local_") & "." & ans
            b = TryCast(b.Expression, MemberExpression)
        Loop While (b IsNot Nothing)
        Return ans.TrimEnd(".")
    End Function

    Public Function GetPathOfTypeProperty(Of T,TRes)(e As Expression(Of Func(Of T,TRes))) As String
        Dim b = TryCast(e.Body, MemberExpression)
        Dim ans = ""
        Do
            ans = b.Member.Name.TrimStart("$VB$Local_") & "." & ans
            Dim tryB = TryCast(b.Expression, MemberExpression)
            If tryB Is Nothing Then
                Dim tryParm = TryCast(b.Expression, ParameterExpression)
                If tryParm IsNot Nothing Then
                    ans = tryParm.Type.Name & "." & ans
                End If
            End If
            b = tryB
        Loop While (b IsNot Nothing)
        Return ans.TrimEnd(".")
    End Function
End Module

Which you can use like so:

Dim cf = New CInstance()
Dim ipe = PropertyExt.GetPathOfInstanceProperty(Function() cf.Foo.SomeBarProperty)
Dim tpe = PropertyExt.GetPathOfTypeProperty(Function(i As CInstance) i.Foo.SomeBarProperty)

NOTE: VB also seems to rename local variables so I added some code to drop the $VB$Local_ prefix from names - this can be removed if not needed.

PS This seems a lot cleaner/simpler in C# ;)


问:
How to decode bytes object that contains invalid bytes, Python3
In python2, I can produce these hex bytes represented in a string format all day
'\x00\xaa\xff'

>>>’00'.decode('hex') + 'aa'.decode('hex') + 'ff'.decode('hex')
>>>'\x00\xaa\xff'
```

<p>Similarily, I can do this in python3</p>

<pre class="lang-py prettyprint-override"><code>>>> bytes.fromhex(’00’) + bytes.fromhex(‘aa’) + bytes.fromhex(‘ff’)
>>>b'\x00\xaa\xff'
</code>```

According to py2->py3 changes here

Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings.
  All text is Unicode; however encoded Unicode is represented as binary data.

So with the Py2 version the output is a string while the Py3 version’s is binary data of type bytes

But I really need a string version!

According to the aforementioned doc:

As the str and bytes types cannot be mixed, you must always explicitly convert between them. Use str.encode() to go from str to bytes, and bytes.decode() to go from bytes to str. You can also use bytes(s, encoding=...) and str(b, encoding=...), respectively.

Ok, so now I have to decode this binary data of type bytes…

>>> b'\x00\xaa\xff'.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xaa in position 1: invalid start byte
```

<p>Oops! I don’t care about UTF-8 encodings here.</p>

<p>Can I just get a dummy pass-through codec?</p>

<p>PS</p>

<p>Why do I need <code>'\x00\xaa\xff'</code> instead of <code>b'\x00\xaa\xff'</code> ?</p>

<p>Because I am taking this string and passing it into </p>

<p>a crc function written in pure python</p>

<pre class="lang-py prettyprint-override"><code>crc16pure.crc16xmodem('\x00\xaa\xff')
</code>```

This function expects to iterate through a string composed of bytes.
If I give the function b'\x00\xaa\xff' then that is just a number which cannot be iterated with.

答:
The question: Can I just get a dummy pass-through codec?

The answer: Yes, use iso-8859-1

In python3, the following doesn't work

```<code>b'\x00\xaa\xff'.decode()
</code>```

The default codec 'utf-8' can't decode byte 0xaa

As long you don't care about the character sets (as in, what char you see when you print()) and just want a string of 8bit chars like what you would get in python2, then use an 8bit codec iso-8859-1

```<code>b'\x00\xaa\xff'.decode('iso-8859-1')
</code>```

Body:
In python2, I can produce these hex bytes represented in a string format all day
'\x00\xaa\xff'

>>>’00'.decode('hex') + 'aa'.decode('hex') + 'ff'.decode('hex')
>>>'\x00\xaa\xff'

Similarily, I can do this in python3

>>> bytes.fromhex(’00’) + bytes.fromhex(‘aa’) + bytes.fromhex(‘ff’)
>>>b'\x00\xaa\xff'

According to py2->py3 changes here

Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings.
  All text is Unicode; however encoded Unicode is represented as binary data.

So with the Py2 version the output is a string while the Py3 version’s is binary data of type bytes

But I really need a string version!

According to the aforementioned doc:

As the str and bytes types cannot be mixed, you must always explicitly convert between them. Use str.encode() to go from str to bytes, and bytes.decode() to go from bytes to str. You can also use bytes(s, encoding=...) and str(b, encoding=...), respectively.

Ok, so now I have to decode this binary data of type bytes…

>>> b'\x00\xaa\xff'.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xaa in position 1: invalid start byte

Oops! I don’t care about UTF-8 encodings here.

Can I just get a dummy pass-through codec?

PS

Why do I need '\x00\xaa\xff' instead of b'\x00\xaa\xff' ?

Because I am taking this string and passing it into

a crc function written in pure python

crc16pure.crc16xmodem('\x00\xaa\xff')

This function expects to iterate through a string composed of bytes.
If I give the function b'\x00\xaa\xff' then that is just a number which cannot be iterated with.

Body:
The question: Can I just get a dummy pass-through codec?

The answer: Yes, use iso-8859-1

In python3, the following doesn't work

b'\x00\xaa\xff'.decode()

The default codec 'utf-8' can't decode byte 0xaa

As long you don't care about the character sets (as in, what char you see when you print()) and just want a string of 8bit chars like what you would get in python2, then use an 8bit codec iso-8859-1

b'\x00\xaa\xff'.decode('iso-8859-1')


答:
Add f.flush() as in:

```<code>if __name__ == "__main__":
    run(LP)
    run(RP)
    run(RF)
    f.flush()
</code>```

or, set the file to be unbuffered when you create the object:

```<code>f = open("All Connections Between Nodes.csv", "w", 0)
</code>```

Title: Python will not write to a CSV file and there are no errors; the print function works

Body:
I have 3 lists of integers. They are then converted into strings. When trying to write them to the CSV file, the file itself is generated, but completely empty. This has stumped all Python users in my lab.

I have tried isolating the different lists and writing them to CSVs. They all return blank.

The print function works.

LP = [25,26,27,28,30,67,71,9,17,18,3,4,46,47,48,49, 55, 56, 65, 66] #(190)

RP = [92,93,98,107,114,115,116,156,117,160,119,144,145,135,136,137,138,155,106,
      154] #(190)
RF = [90,94,95,96,97,101,102,103,104,105,106,113,118,120,121,129,128,134,141,
      142,143,157,158,151,152,153,159,136,137,138,155,92,93,107] #(561)

LP = list(map(str, LP))
RP = list(map(str, RP))
RF = list(map(str, RF))

f = open("All Connections Between Nodes.csv", "w")

def run(lobe):
    seperator = ","
    for num in lobe:
        for num2 in lobe:
            if lobe.index(num2) <= lobe.index(num):
                pass
            elif lobe.index(num) == lobe.index(num2):
                pass

            elif lobe == LP:
                f.write("" + (num) + seperator + (num2) + "")
                f.write("\n")
                print(num, num2)
            elif lobe == RP:
                f.write("" + (num) + seperator + (num2) + "")
                f.write("\n")
                print("" + (num) + seperator + (num2) + "")
            elif lobe == RF:
                f.write("" + (num) + seperator + (num2) + "")
                f.write("\n")
                print("" + (num) + seperator + (num2) + "")

if __name__ == "__main__":

    run(LP)
    run(RP)
    run(RF)

The CSV file should look like this:

25 26
25 27
25 28

And so on. Each pair should only exist once. (e.g., if 25-26 exists, there should not be a 26-25)

Body:
Add f.flush() as in:

if __name__ == "__main__":
    run(LP)
    run(RP)
    run(RF)
    f.flush()

or, set the file to be unbuffered when you create the object:

f = open("All Connections Between Nodes.csv", "w", 0)


问:
Is that we cannot set some styles attributes that we can set in XML?
```<code><GridView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="90px"
    android:gravity="center"
    android:numColumns="5"
    android:verticalSpacing="30dp"
    android:stretchMode="columnWidth"
/>
</code>```

For Example, the XML above defined a GridView's style,

and now I want to make a number of GridView instances using this Style.
So I have to generate those in code.(Is there another way?)

I can only know:

```<code>mGridView = new GridView(this);
mGridView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
</code>```

and then how to set the other attributes in code?

And if this question has an answer, the problem above will be solved:

Can we get a lot of instances defined by the same XML?

thought can include styles in XML, I need 100 instances I have to include in 100 <GridView ... />?

答:
Can we get a lot of instances defined
  by the same XML? thought can include
  styles in XML, I need 100 instances I
  have to include in 100 < GridView ... />

No, you can use LayoutInflater to add the same XML layout over and over again.
Using xml is preferable because of the separation of UI and logic.

Body:
<GridView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="90px"
    android:gravity="center"
    android:numColumns="5"
    android:verticalSpacing="30dp"
    android:stretchMode="columnWidth"
/>

For Example, the XML above defined a GridView's style,

and now I want to make a number of GridView instances using this Style.
So I have to generate those in code.(Is there another way?)

I can only know:

mGridView = new GridView(this);
mGridView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

and then how to set the other attributes in code?

And if this question has an answer, the problem above will be solved:

Can we get a lot of instances defined by the same XML?

thought can include styles in XML, I need 100 instances I have to include in 100 <GridView ... />?


问:
Share JavaScript files among different servers
I have a few Node apps, each hosted in a different container (Heroku dyno). All the apps use the same mongo models, so when I change a model, I have to change it for each app. I was wondering if there is a way to share the model files among all my apps.

I thought about hosting the model files in a different container, and then making them available to the apps, but I'm not sure how to do it.

A little more generally speaking, how can I share JavaScript files among different containers / servers? Is that the best approach to solve this problem?

Thanks!

答: First put your common model code into a local npm module as in Installing a local module using npm? then build and deploy your images as normal.