问:
Android emulator crashes due to Db (can't find the mistake - newbie)
Sorry for the question but I can't really find why my DB throws an exception. Here is the code please have a look at it. The whole idea is to make a hangman game as a school project, and I wanted to create a place where the user can see all current words and add more if he/she wants or remove existing (it is in the requirements). I think I have made a mistake in the populateListView method because I don't think I have worked with a cursor before but had a look at a few online materials so I tried to adjust accordingly. If there is a simpler way to do it -> I am all up for it. Thanks in advance !

This is the DBAdapter file:

```<code>public class DBAdapter {

private static final String TAG = "DBAdapter"; //used for logging database version changes

// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_WORD = "word";

public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_WORD};

// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_WORD = 1;

// DataBase info:
public static final String DATABASE_NAME = "dbToDo";
public static final String DATABASE_TABLE = "mainToDo";
public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.

//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
        "CREATE TABLE " + DATABASE_TABLE
                + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + KEY_WORD + " TEXT NOT NULL"
                + ");";

private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx) {
    this.context = ctx;
    myDBHelper = new DatabaseHelper(context);
}

// Open the database connection.
public DBAdapter open() {
    db = myDBHelper.getWritableDatabase();
    return this;
}

// Close the database connection.
public void close() {
    myDBHelper.close();
}

// Add a new set of values to be inserted into the database.
public long insertRow(String word) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_WORD, word);

    // Insert the data into the database.
    return db.insert(DATABASE_TABLE, null, initialValues);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));
        } while (c.moveToNext());
    }
    c.close();
}

// Return all data in the database.
public Cursor getAllRows() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
            where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String word) {
    String where = KEY_ROWID + "=" + rowId;
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_WORD, word);
    // Insert it into the database.
    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}

private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading application's database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data!");

        // Destroy old database:
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        // Recreate new database:
        onCreate(_db);
    }
}
</code>```

And here is the other place that crashes:

```<code>public class EditWords extends Activity {
ListView listViewWords;
EditText editTextNewWord;
Button buttonAddWord;
Button buttonDeleteWord;

DBAdapter myDb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_words);
    listViewWords = (ListView) findViewById(R.id.listViewWords);
    editTextNewWord = (EditText) findViewById(R.id.editTextNewWord);
    buttonAddWord = (Button) findViewById(R.id.buttonAddWord);
    buttonDeleteWord = (Button) findViewById(R.id.buttonDeleteWord);
    populateListView();
    openDB();

}
private void openDB(){
    myDb = new DBAdapter(this);
    myDb.open();
}

private void populateListView() {
    Cursor cursor = myDb.getAllRows();
    String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID,DBAdapter.KEY_WORD};
    int[] toViewIDs = new int[]{R.id.editTextNewWord};
    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.id.listViewWords,cursor,fromFieldNames,toViewIDs,0);
    listViewWords.setAdapter(myCursorAdapter);
}

    public void onClick_AddWord(View v) {
        if(!TextUtils.isEmpty(editTextNewWord.getText().toString())) {
            myDb.insertRow(editTextNewWord.getText().toString());
        }
        populateListView();

    }
</code>```

}

Stacktrace:

03-30 12:13:39.603 8800-9926/com.example.daniel.hangman I/OpenGLRenderer: Initialized EGL, version 1.4
03-30 12:13:39.603 8800-9926/com.example.daniel.hangman W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
03-30 12:13:42.570 8800-8800/com.example.daniel.hangman D/AndroidRuntime: Shutting down VM
03-30 12:13:42.571 8800-8800/com.example.daniel.hangman E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.daniel.hangman, PID: 8800
                                                                          android.content.res.Resources$NotFoundException: Resource ID #0x7f070009 type #0x12 is not valid
                                                                              at android.content.res.Resources.loadXmlResourceParser(Resources.java:2779)
                                                                              at android.content.res.Resources.getLayout(Resources.java:1165)
                                                                              at android.view.LayoutInflater.inflate(LayoutInflater.java:421)
                                                                              at android.widget.ResourceCursorAdapter.newView(ResourceCursorAdapter.java:135)
                                                                              at android.widget.CursorAdapter.getView(CursorAdapter.java:285)
                                                                              at android.widget.AbsListView.obtainView(AbsListView.java:2346)
                                                                              at android.widget.ListView.makeAndAddView(ListView.java:1875)
                                                                              at android.widget.ListView.fillDown(ListView.java:702)
                                                                              at android.widget.ListView.fillFromTop(ListView.java:763)
                                                                              at android.widget.ListView.layoutChildren(ListView.java:1684)
                                                                              at android.widget.AbsListView.onLayout(AbsListView.java:2148)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
                                                                              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
                                                                              at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                              at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:493)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                              at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                              at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2678)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171)
                                                                              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931)
                                                                              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                                              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                                              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                              at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                              at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                              at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)```

答:
You call:

```<code>populateListView();
</code>```

which uses 'myDb' before:

```<code>openDB();
</code>```

which initializes 'myDb'

Body:
Sorry for the question but I can't really find why my DB throws an exception. Here is the code please have a look at it. The whole idea is to make a hangman game as a school project, and I wanted to create a place where the user can see all current words and add more if he/she wants or remove existing (it is in the requirements). I think I have made a mistake in the populateListView method because I don't think I have worked with a cursor before but had a look at a few online materials so I tried to adjust accordingly. If there is a simpler way to do it -> I am all up for it. Thanks in advance !

This is the DBAdapter file:

public class DBAdapter {

private static final String TAG = "DBAdapter"; //used for logging database version changes

// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_WORD = "word";

public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_WORD};

// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_WORD = 1;

// DataBase info:
public static final String DATABASE_NAME = "dbToDo";
public static final String DATABASE_TABLE = "mainToDo";
public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.

//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
        "CREATE TABLE " + DATABASE_TABLE
                + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + KEY_WORD + " TEXT NOT NULL"
                + ");";

private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx) {
    this.context = ctx;
    myDBHelper = new DatabaseHelper(context);
}

// Open the database connection.
public DBAdapter open() {
    db = myDBHelper.getWritableDatabase();
    return this;
}

// Close the database connection.
public void close() {
    myDBHelper.close();
}

// Add a new set of values to be inserted into the database.
public long insertRow(String word) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_WORD, word);

    // Insert the data into the database.
    return db.insert(DATABASE_TABLE, null, initialValues);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));
        } while (c.moveToNext());
    }
    c.close();
}

// Return all data in the database.
public Cursor getAllRows() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
            where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String word) {
    String where = KEY_ROWID + "=" + rowId;
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_WORD, word);
    // Insert it into the database.
    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}

private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading application's database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data!");

        // Destroy old database:
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        // Recreate new database:
        onCreate(_db);
    }
}

And here is the other place that crashes:

public class EditWords extends Activity {
ListView listViewWords;
EditText editTextNewWord;
Button buttonAddWord;
Button buttonDeleteWord;

DBAdapter myDb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_words);
    listViewWords = (ListView) findViewById(R.id.listViewWords);
    editTextNewWord = (EditText) findViewById(R.id.editTextNewWord);
    buttonAddWord = (Button) findViewById(R.id.buttonAddWord);
    buttonDeleteWord = (Button) findViewById(R.id.buttonDeleteWord);
    populateListView();
    openDB();

}
private void openDB(){
    myDb = new DBAdapter(this);
    myDb.open();
}

private void populateListView() {
    Cursor cursor = myDb.getAllRows();
    String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID,DBAdapter.KEY_WORD};
    int[] toViewIDs = new int[]{R.id.editTextNewWord};
    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.id.listViewWords,cursor,fromFieldNames,toViewIDs,0);
    listViewWords.setAdapter(myCursorAdapter);
}

    public void onClick_AddWord(View v) {
        if(!TextUtils.isEmpty(editTextNewWord.getText().toString())) {
            myDb.insertRow(editTextNewWord.getText().toString());
        }
        populateListView();

    }

}

Stacktrace:

03-30 12:13:39.603 8800-9926/com.example.daniel.hangman I/OpenGLRenderer: Initialized EGL, version 1.4
03-30 12:13:39.603 8800-9926/com.example.daniel.hangman W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
03-30 12:13:42.570 8800-8800/com.example.daniel.hangman D/AndroidRuntime: Shutting down VM
03-30 12:13:42.571 8800-8800/com.example.daniel.hangman E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.daniel.hangman, PID: 8800
                                                                          android.content.res.Resources$NotFoundException: Resource ID #0x7f070009 type #0x12 is not valid
                                                                              at android.content.res.Resources.loadXmlResourceParser(Resources.java:2779)
                                                                              at android.content.res.Resources.getLayout(Resources.java:1165)
                                                                              at android.view.LayoutInflater.inflate(LayoutInflater.java:421)
                                                                              at android.widget.ResourceCursorAdapter.newView(ResourceCursorAdapter.java:135)
                                                                              at android.widget.CursorAdapter.getView(CursorAdapter.java:285)
                                                                              at android.widget.AbsListView.obtainView(AbsListView.java:2346)
                                                                              at android.widget.ListView.makeAndAddView(ListView.java:1875)
                                                                              at android.widget.ListView.fillDown(ListView.java:702)
                                                                              at android.widget.ListView.fillFromTop(ListView.java:763)
                                                                              at android.widget.ListView.layoutChildren(ListView.java:1684)
                                                                              at android.widget.AbsListView.onLayout(AbsListView.java:2148)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
                                                                              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
                                                                              at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                              at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:493)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                              at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                              at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2678)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171)
                                                                              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931)
                                                                              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                                              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                                              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                              at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                              at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                              at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
You call:

populateListView();

which uses 'myDb' before:

openDB();

which initializes 'myDb'


来源: stackexchange

问:
JAX-RS Access-Control-Allow-Origin header not present, but it was added in ResponseFilter
I'm trying to connect to my REST endpoint built using JAX-RS, but I get the response that the header 'Access-Control-Allow-Origin' is not present. Trying to GET a resource with Angular2.

What I've tried

I tried the solution presented in https://stackoverflow.com/a/30450944.

My response filter:

```<code>@Provider
@PreMatching
public class ResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}
</code>```

And my web.xml servlet mapping:

```<code>    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>com.api.ResponseFilter</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
</code>```

Update 1

Updated the

```<code>responseContext.getHeaders().add(...);
</code>```

to

```<code>responseContext.getHeaders.putSingle(...);
</code>```

but I'm still getting the same error.
While testing in postman, I am getting the correct headers back:

```<code>Access-Control-Allow-Credentials →true
Access-Control-Allow-Headers →origin, content-type, accept, authorization
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin →*
</code>```

Update 2

In my JAXRSConfig, which extends Application, I've manually added all resources possibly necessary:

```<code>@ApplicationPath("api")
public class JAXRSConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new HashSet<>();
        addRestResourceClasses(resources);
        return resources;
    }

    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(AdminResource.class);
        resources.add(RequestFilter.class);
        resources.add(ResponseFilter.class);
        resources.add(TweetResource.class);
        resources.add(UserResource.class);
    }
}
</code>```

Via the use of breakpoints I have noticed that my ResponseFilter does get invoked when I send a GET request via Postman, but it does not get invoked when I send a GET request via my angular application.

My angular code to send a request:

```<code>let headers = new Headers({'Authorization': authToken});
    headers.append('Content-Type', 'application/json');

    let options = new RequestOptions({ headers: headers});

    return this.http.get(http://localhost:8080/api/object/user)
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
</code>```

Update 3

I did realize I did not actually add the defined headers to the request; so I've updated my angular code to:

```<code>let authToken = "Basic " + btoa("henk:asdf");//temporary until I learn how to allow a user to log in, in angular
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', authToken);

    //let options = new RequestOptions({ headers: headers});

    return this.http.get(this.myUrl, {headers: headers})
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
</code>```

Update 4

I've since learned this could be due to the pre-flight check Chrome (and other browsers) perform, via a request-method called OPTIONS. I've added a request filter to my api as follows:

```<code>@Provider
@PreMatching
public class RequestFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        if (requestContext.getRequest().getMethod().equals("OPTIONS")) {
            requestContext.abortWith(Response.status(Response.Status.OK).header("Access-Control-Allow-Origin", "http://localhost:4200").build());
        }
    }
}
</code>```

But to no avail. With a break point on the if-statement I've seen that this method does not get called in a GET request from angular, but it does get called from a request from Postman.

I've also tried a different CORS filter according to https://stackoverflow.com/a/19902666/6795661.
But this did not work either.

Update 5

As per peeskillet I've tried creating a class that implements javax.servlet.Filter, to add the required header(s) to a response:

```<code>public class ContainerResponseFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
</code>```

With the corresponding mapping in my web.xml:

```<code>    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>com.api.ResponseFilter</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
</code>```0

And I've added ContainerResponseFilter as resource in my Application configuration.
Unfortunately I am still getting the error that the 'Access-Control-Allow-Origin' header is not present.

答: As it turns out, the problem was with the authentication. My application server was trying to authenticate the request, but since a CORS check is done before the authentication I just got an unauthorized response, which did not include the required header.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to connect to my REST endpoint built using JAX-RS, but I get the response that the header 'Access-Control-Allow-Origin' is not present. Trying to GET a resource with Angular2.

What I've tried

I tried the solution presented in https://stackoverflow.com/a/30450944.

My response filter:

@Provider
@PreMatching
public class ResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

And my web.xml servlet mapping:

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>com.api.ResponseFilter</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

Update 1

Updated the

responseContext.getHeaders().add(...);

to

responseContext.getHeaders.putSingle(...);

but I'm still getting the same error.
While testing in postman, I am getting the correct headers back:

Access-Control-Allow-Credentials →true
Access-Control-Allow-Headers →origin, content-type, accept, authorization
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin →*

Update 2

In my JAXRSConfig, which extends Application, I've manually added all resources possibly necessary:

@ApplicationPath("api")
public class JAXRSConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new HashSet<>();
        addRestResourceClasses(resources);
        return resources;
    }

    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(AdminResource.class);
        resources.add(RequestFilter.class);
        resources.add(ResponseFilter.class);
        resources.add(TweetResource.class);
        resources.add(UserResource.class);
    }
}

Via the use of breakpoints I have noticed that my ResponseFilter does get invoked when I send a GET request via Postman, but it does not get invoked when I send a GET request via my angular application.

My angular code to send a request:

let headers = new Headers({'Authorization': authToken});
    headers.append('Content-Type', 'application/json');

    let options = new RequestOptions({ headers: headers});

    return this.http.get(http://localhost:8080/api/object/user)
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

Update 3

I did realize I did not actually add the defined headers to the request; so I've updated my angular code to:

let authToken = "Basic " + btoa("henk:asdf");//temporary until I learn how to allow a user to log in, in angular
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', authToken);

    //let options = new RequestOptions({ headers: headers});

    return this.http.get(this.myUrl, {headers: headers})
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

Update 4

I've since learned this could be due to the pre-flight check Chrome (and other browsers) perform, via a request-method called OPTIONS. I've added a request filter to my api as follows:

@Provider
@PreMatching
public class RequestFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        if (requestContext.getRequest().getMethod().equals("OPTIONS")) {
            requestContext.abortWith(Response.status(Response.Status.OK).header("Access-Control-Allow-Origin", "http://localhost:4200").build());
        }
    }
}

But to no avail. With a break point on the if-statement I've seen that this method does not get called in a GET request from angular, but it does get called from a request from Postman.

I've also tried a different CORS filter according to https://stackoverflow.com/a/19902666/6795661.
But this did not work either.

Update 5

As per peeskillet I've tried creating a class that implements javax.servlet.Filter, to add the required header(s) to a response:

public class ContainerResponseFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

With the corresponding mapping in my web.xml:

    <filter>
        <filter-name>corsfilter</filter-name>
        <filter-class>com.api.ContainerResponseFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>corsfilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

And I've added ContainerResponseFilter as resource in my Application configuration.
Unfortunately I am still getting the error that the 'Access-Control-Allow-Origin' header is not present.


问:
In Hybris what the difference between ant deploy and ant all
Can anyone please tell the difference in hybris of ant deploy and ant all.
According to me ant deploy will deploy code without any re-compliation.
It is said it takes only changes in configurations.
I dont see this making any sense as property and .xml files dont need any ant all.
So does ant deploy build items.xml and beans files?</p>

答:
You call ant deploy when you use ant server. This command is used to update the configuration done for tomcat/tcserver in /hybris/config to /hybris/bin/platform. It restarts the server if it's already started.

ant all executes ant build and ant server. ant build is in charge of compilation of java code, hybris beans, and items.


问:
repmat vs simple matrix multiplication in MATLAB
Let v be a row vector of length n. The goal is to create a matrix A with m rows that are all equal to v.

MATLAB has a function for this that is called repmat. Possible code would be

A = repmat(v,[m 1])

There is an alternative equally concise way using simple matrix operations

A = ones(m,1)*v

Is any of the two methods preferable for large m and n?

答:
You should use repmat().

Matrix Multiplication is O(n ^ 3) operation which is much slower then replicating data in memory.

On top of that, the second option allocate more data in memory of the size of the output.

In the case above you create a vector which the outer multiplication is faster yet still not as memory operation.

MATLAB doesn't use the knowledge all vector elements are 1, hence you multiply each element of x by 1 m times.

Both operations will be mainly memory bounded, yet more efficient, fast and direct method would be going with repmat().

The question is, what you do afterwards?

Because you may not need repmat().


问:
Memory leak problem NSAutoreleaseNoPool()
I am trying to create an immutable string. I am not initializing it with init, alloc or new but still the memory is leaking and its saying "object 0x234b533 of Class NSCFString autoreleased with no pool in place - just leaking " here is what I am trying to do

```<code>NSMutableString *srn = [NSMutableString stringwithCString:devSID];

// devSID is *char
</code>```

this leaves a leak. I have tried this too

```<code>NSMutableString *srn = [NSMutableString stringwithCString:devSID length:sizeof(devSID)];
</code>```

but this too doesn't work, however if I try initialize it with a simple string like this

```<code>NSMutableString *srn = @"this is my string";
</code>```

it works, dont have any idea whats happening around. I am not using init or alloc but still there is a leak. I would be obliged if anyone could help me out to resolve this issue

Regards

Umair

答:
The leak is caused by your autoreleasing an object without having an autorelease pool in place to take care of it. That usually happens when you're doing things apart from the main thread, via creating your own threads or just using the -performSelectorInBackground:withObject: convenience method. If you want to use the autorelease functionality (implied by the use of the NSMutableString class method here), you need to create an autorelease pool at the beginning of the block of code where you'll be using it and drain it at the end. In other words, something along these lines:

```<code>- (void)myBackgroundThing:(id)whatever
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSMutableString *srn = [NSMutableString stringwithCString:devSID];

    // etc...

    [pool release];
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to create an immutable string. I am not initializing it with init, alloc or new but still the memory is leaking and its saying "object 0x234b533 of Class NSCFString autoreleased with no pool in place - just leaking " here is what I am trying to do

NSMutableString *srn = [NSMutableString stringwithCString:devSID];

// devSID is *char

this leaves a leak. I have tried this too

NSMutableString *srn = [NSMutableString stringwithCString:devSID length:sizeof(devSID)];

but this too doesn't work, however if I try initialize it with a simple string like this

NSMutableString *srn = @"this is my string";

it works, dont have any idea whats happening around. I am not using init or alloc but still there is a leak. I would be obliged if anyone could help me out to resolve this issue

Regards

Umair

Body:
The leak is caused by your autoreleasing an object without having an autorelease pool in place to take care of it. That usually happens when you're doing things apart from the main thread, via creating your own threads or just using the -performSelectorInBackground:withObject: convenience method. If you want to use the autorelease functionality (implied by the use of the NSMutableString class method here), you need to create an autorelease pool at the beginning of the block of code where you'll be using it and drain it at the end. In other words, something along these lines:

- (void)myBackgroundThing:(id)whatever
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSMutableString *srn = [NSMutableString stringwithCString:devSID];

    // etc...

    [pool release];
}


问:
Firebase querying data
```<code>{
  "random_key 1" : {
    "id": 0,
    "text": "This is text"
  },
  "random_key 2" : {
    "id": 1,
    "text": "This is text"
  }
}
</code>```

If I'm storing my data like this, and I want to get the node where id is equal to 0. How can I do that?

The above is the child of issue, which is a child of root.

答:
@Linxy's answer is correct but since you'll be reading a list of items from the database, it's better to use a child event listener instead of the value event listener.</p>

```<code>DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

Query query = reference.child("issue").orderByChild("id").equalTo(0);
query.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        //Do something with the individual node here`enter code here`
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }

});
</code>```

Title: Firebase querying data

Body:
{
  "random_key 1" : {
    "id": 0,
    "text": "This is text"
  },
  "random_key 2" : {
    "id": 1,
    "text": "This is text"
  }
}

If I'm storing my data like this, and I want to get the node where id is equal to 0. How can I do that?

The above is the child of issue, which is a child of root.

Body:
@Linxy's answer is correct but since you'll be reading a list of items from the database, it's better to use a child event listener instead of the value event listener.

DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

Query query = reference.child("issue").orderByChild("id").equalTo(0);
query.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        //Do something with the individual node here`enter code here`
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }

});


问:
Search in a json API using VB.net
hello guys i want to search in a json string and get a value of one of the attribute i have the following code

```<code>    Dim ser As JObject = JObject.Parse(reader.ReadToEnd())

    Dim data As List(Of JToken) = ser.Children().ToList

    Response.Write(ser)
</code>```

and this is my out put

{ "success": true, "result": { "access_token":
  "T1RLAQLTD+AB7uveLzir/oF8EKbu32EJIRDHKkx5O/W2+ri3cbWT8uOuAADAF7OJij6m20nPrYZzWRwNlDA99fzg/pnN7eL8XiWS9pkvapQtPDhiPHupNJOettLKPJRuekAO0zBgptPAkYt1G6etINlTjHLpW2kVOxeAqH7t3mSzXmScSQvgQwMC2d4FBdZu2jKgSf86ret2i0eHydFW91vJ1eWI9LkZFPrHBXPzlQJZ9GyvFpF2IEVo2D23y3xMYYEVI410ZRKLnTLvTcrH12s/8wYNc8jKLMWKcNNjiKnDm8i0WJS7eOU7iXKu",
  "token_type": "bearer", "expires_in": 604800 } }

i want to get the value of that  "access_token"   thank you

答:
You can get it without using ToList() first:

```<code>Dim myAccessToken as String = ser("result")("access_token").Value(Of String)()
</code>```

I haven't checked it, but I think this should work.

Title: Search in a json API using VB.net

Body:
hello guys i want to search in a json string and get a value of one of the attribute i have the following code

    Dim ser As JObject = JObject.Parse(reader.ReadToEnd())

    Dim data As List(Of JToken) = ser.Children().ToList

    Response.Write(ser)

and this is my out put

{ "success": true, "result": { "access_token":
  "T1RLAQLTD+AB7uveLzir/oF8EKbu32EJIRDHKkx5O/W2+ri3cbWT8uOuAADAF7OJij6m20nPrYZzWRwNlDA99fzg/pnN7eL8XiWS9pkvapQtPDhiPHupNJOettLKPJRuekAO0zBgptPAkYt1G6etINlTjHLpW2kVOxeAqH7t3mSzXmScSQvgQwMC2d4FBdZu2jKgSf86ret2i0eHydFW91vJ1eWI9LkZFPrHBXPzlQJZ9GyvFpF2IEVo2D23y3xMYYEVI410ZRKLnTLvTcrH12s/8wYNc8jKLMWKcNNjiKnDm8i0WJS7eOU7iXKu",
  "token_type": "bearer", "expires_in": 604800 } }

i want to get the value of that  "access_token"   thank you

Body:
You can get it without using ToList() first:

Dim myAccessToken as String = ser("result")("access_token").Value(Of String)()

I haven't checked it, but I think this should work.


问:
Call property from parent class like dictionary in c#
May I dont know how too look for it, but fact is I cant find anything that helps me.

Is there a way to call property from a parent class like an assoc array (dictionary) ?

Sample:

```<code>using System;

class Foobar
{
    public string bla;
    public Foobar()
    {
        this.bla = "hello world";
    }
}

public class Test
{
    public static void Main()
    {
        Foobar x = new Foobar();
        Console.WriteLine(x.bla); //this works (prints hello world)
        Console.WriteLine(x["bla"]); //this wont work but is my achivment
    }
}
</code>```

To clarify what I want is...

I want to create a class that has some propertys e.g

```<code>class SomeClass
{
    private string aaa {get;set;};
    private string bbb {get;set;};
    private string ccc {get;set;};
    private string ddd {get;set;};
    ....
}
</code>```

and than loop this in a other class by a dictionary

```<code>SomeClass x = new SomeClass();
IDictionary<string, string> dict = new Dictionary<string, string>();
dict["a"] = "aaa";
dict["b"] = "bbb";
dict["d"] = "ddd";

foreach( d in dict )
{
    someMethode(x[d]);
}
</code>```

答:
Modify your class this way

```<code>class Foobar
{
    public string bla { get; set; }
    public Foobar()
    {
        this.bla = "hello world";
    }

    public string this[string name]
    {
        get
        {
            return this.GetType().GetProperty(name).GetValue(this, null).ToString();
        }
    }
}
</code>```

Sample: https://dotnetfiddle.net/XboHOg

Body:
May I dont know how too look for it, but fact is I cant find anything that helps me.

Is there a way to call property from a parent class like an assoc array (dictionary) ?

Sample:

using System;

class Foobar
{
    public string bla;
    public Foobar()
    {
        this.bla = "hello world";
    }
}

public class Test
{
    public static void Main()
    {
        Foobar x = new Foobar();
        Console.WriteLine(x.bla); //this works (prints hello world)
        Console.WriteLine(x["bla"]); //this wont work but is my achivment
    }
}

To clarify what I want is...

I want to create a class that has some propertys e.g

class SomeClass
{
    private string aaa {get;set;};
    private string bbb {get;set;};
    private string ccc {get;set;};
    private string ddd {get;set;};
    ....
}

and than loop this in a other class by a dictionary

SomeClass x = new SomeClass();
IDictionary<string, string> dict = new Dictionary<string, string>();
dict["a"] = "aaa";
dict["b"] = "bbb";
dict["d"] = "ddd";

foreach( d in dict )
{
    someMethode(x[d]);
}

Body:
Modify your class this way

class Foobar
{
    public string bla { get; set; }
    public Foobar()
    {
        this.bla = "hello world";
    }

    public string this[string name]
    {
        get
        {
            return this.GetType().GetProperty(name).GetValue(this, null).ToString();
        }
    }
}

Sample: https://dotnetfiddle.net/XboHOg


问:
How do you get a widget's children in Qt?
I'm simulating keyPresses to an application through Qt's KeyPress function. All the KeyPresses work fine. However when I pass a QT::Key_Enter which is supposed to press the OK button of the currently active window, or QT::Key_Cancel for the cancel button, it does nothing.

I'm thinking maybe, because these buttons don't have the focus, and the parent window itself has it. How do you get the children of a window? or rather find the OK or Cancel button on it so you could set it as the activeWindow and then pass KeyPresses successfully?

I have:

```<code>QWidget *pWin = QApplication::activeWindow;
QObjectList *pList = pWin->children();
//how do you iterate through the list and find the OK or Cancel button?
</code>```

答: You might want to put a custom event filter on your widget to capture the key event and see what really happens to it.</p>

Body:
I'm simulating keyPresses to an application through Qt's KeyPress function. All the KeyPresses work fine. However when I pass a QT::Key_Enter which is supposed to press the OK button of the currently active window, or QT::Key_Cancel for the cancel button, it does nothing.

I'm thinking maybe, because these buttons don't have the focus, and the parent window itself has it. How do you get the children of a window? or rather find the OK or Cancel button on it so you could set it as the activeWindow and then pass KeyPresses successfully?

I have:

QWidget *pWin = QApplication::activeWindow;
QObjectList *pList = pWin->children();
//how do you iterate through the list and find the OK or Cancel button?


问:
Merging dropzone.js with my form
I'm creating a form that uses dropzone.js, I've managed to do it by having the drag and drop image by itself. The problem I'm having is that I'm struggling to merge dropzone with the form I'm having. If I add the dropzone class to my form then my whole form is the dropzone but I just want a section to be the dropzone.

Hope I explained it properly.

Here is my create.blade.php

```<code>{{ Form::open(array('route' => 'menus.store', 'class' => 'add-form')) }}
    <div class="form">
        <div class="parents_input">
                <div>
                    {{ Form::label('menu_id', 'Parent Menu')}}
                </div>

                <div>
                    {!! Form::select('menu_id', $menu_id->prepend('Please Select', '0'), null, array("class" => "form-control")) !!}
                </div>
            </div>

        <div class="title_input">
            <div>
                {{ Form::label('title', 'Title') }}
            </div>
            <div>
                {{ Form::text('title','', array('id' => 'title', "class" => "form-control")) }}
            </div>
        </div>

        <input type="file" name="file" class="dropzone" id="my-awesome-dropzone" />

        <div class="layout_type">
                <input id="home" type="radio" value="home" name="type">
                <label for="home">Home</label>

                <input id="stories" type="radio" value="stories" name="type">
                <label for="stories">Stories</label>
            </div>

        <div class="submit_button">
            <div>
                {{ Form::submit('Submit', array("class" => "btn btn-info submit", "role" => "button")) }}
            </div>
        </div>
    </div>
{{ Form::close() }}
</code>```

答:
you have to add dropzone in one separate div.

```<code>   <script src="../../assets/dropzone/js/dropzone.js"></script>
   <link type="text/css" rel="stylesheet"
     href="../../assets/dropzone/css/dropzone.css">

 <div class="">

  <div action="" id="dZUpload" class="dropzone" method="post"
  enctype="multipart/form-data">

 </div>
 </div>
</code>```

after that initialise dropzone.

Title: Merging dropzone.js with my form

Body:
I'm creating a form that uses dropzone.js, I've managed to do it by having the drag and drop image by itself. The problem I'm having is that I'm struggling to merge dropzone with the form I'm having. If I add the dropzone class to my form then my whole form is the dropzone but I just want a section to be the dropzone.

Hope I explained it properly.

Here is my create.blade.php

{{ Form::open(array('route' => 'menus.store', 'class' => 'add-form')) }}

                    {{ Form::label('menu_id', 'Parent Menu')}}

                    {!! Form::select('menu_id', $menu_id->prepend('Please Select', '0'), null, array("class" => "form-control")) !!}

                {{ Form::label('title', 'Title') }}

                {{ Form::text('title','', array('id' => 'title', "class" => "form-control")) }}

        <input type="file" name="file" class="dropzone" id="my-awesome-dropzone" />

                <input id="home" type="radio" value="home" name="type">
                Home

                <input id="stories" type="radio" value="stories" name="type">
                Stories

                {{ Form::submit('Submit', array("class" => "btn btn-info submit", "role" => "button")) }}

{{ Form::close() }}

Body:
you have to add dropzone in one separate div.

   <script src="../../assets/dropzone/js/dropzone.js"></script>
   <link type="text/css" rel="stylesheet"
     href="../../assets/dropzone/css/dropzone.css">

 <div class="">

  <div action="" id="dZUpload" class="dropzone" method="post"
  enctype="multipart/form-data">

 </div>
 </div>

after that initialise dropzone.


问:
Windows Authentication Impersonation - Second request gets wrong user identity
I have the following architecture:

```<code>Client1(Browser-App) -> Server1 (WebAPI/IIS) -> Server2 (WebAPI/IIS)
</code>```

I am using ASP.NET for my server-side applications/apis and the user should be authenticated via "windows integrated authentication".

As you can see there is a second hop from server1 to server2. NTML does not support the second hop if both WebAPIs are not on the same server.
So I configured an AD domain to support "kerberos".

It works now with the second hop.
My test-WebAPIs output the identity of the user like this:

```<code>server1: test.domain/user1
server2: test.domain/user1
</code>```

But if I change the logged-in user on Client1 and execute the same request as "otherUser2", only the first hop gets the correct identity:

```<code>server1: test.domain/otherUser2
server2: test.domain/user1
</code>```

On the second hop the old user of the first request is displayed.
I tested multiple scenarios: Same behaviour if the following requests come from another client with another windows user...

It looks like the windows identity of the first request is cached on the server2... This is a big problem for me and I think this should not be possible... It's a big security hole if a request is executed in the wrong user context!

Is this a known problem? Did I do something wrong?
Is there a solution or a better configuration?

On the first ASP.NET WebAPI I use impersonation like this:

```<code>WindowsIdentity identity = (WindowsIdentity)HttpContext.Current.User.Identity;

            using (var wic = identity.Impersonate())
            {
                try
                {
                    WebClient c = new WebClient
                    {
                        UseDefaultCredentials = true
                    };
</code>```

I use the WebClient class of .NET.

Both IIS server have "Windows Authentication" with "Negotiation" and "NTML" configured.

Server1 is the DomainController, DNS and DHCP-Server (+IIS)

Server2 is only a normal server with IIS installed.

All computers are in the same domain.

I cannot explain me this behavior... It makes no sense to me. Why should the first incoming request's identity should be cached on 'server2'?
If I restart the IIS and re-execute the requests with another windows identity, this is the "first working request" and the others get his identity on 'server2'.

答:
I found the solution/problem.

It was in fact a caching problem... The identity of the first user was cached.
You can change this behavior with this "IIS settings":

authPersistNonNTLM

authPersistSingleRequest

Or your HTTP-Client at API1 can disable TCP-Connection caching:

Connection: close

instead of

Connection: keep-alive

But the actual problem in my scenario was fiddler (a HTTP proxy tool).
I configured fiddler as proxy in the web.config at API1. This kept the connection open and the first identity was reused...

I hope I can help some others with this answer.

Body:
I have the following architecture:

Client1(Browser-App) -> Server1 (WebAPI/IIS) -> Server2 (WebAPI/IIS)

I am using ASP.NET for my server-side applications/apis and the user should be authenticated via "windows integrated authentication".

As you can see there is a second hop from server1 to server2. NTML does not support the second hop if both WebAPIs are not on the same server.
So I configured an AD domain to support "kerberos".

It works now with the second hop.
My test-WebAPIs output the identity of the user like this:

server1: test.domain/user1
server2: test.domain/user1

But if I change the logged-in user on Client1 and execute the same request as "otherUser2", only the first hop gets the correct identity:

server1: test.domain/otherUser2
server2: test.domain/user1

On the second hop the old user of the first request is displayed.
I tested multiple scenarios: Same behaviour if the following requests come from another client with another windows user...

It looks like the windows identity of the first request is cached on the server2... This is a big problem for me and I think this should not be possible... It's a big security hole if a request is executed in the wrong user context!

Is this a known problem? Did I do something wrong?
Is there a solution or a better configuration?

On the first ASP.NET WebAPI I use impersonation like this:

WindowsIdentity identity = (WindowsIdentity)HttpContext.Current.User.Identity;

            using (var wic = identity.Impersonate())
            {
                try
                {
                    WebClient c = new WebClient
                    {
                        UseDefaultCredentials = true
                    };

I use the WebClient class of .NET.

Both IIS server have "Windows Authentication" with "Negotiation" and "NTML" configured.

Server1 is the DomainController, DNS and DHCP-Server (+IIS)

Server2 is only a normal server with IIS installed.

All computers are in the same domain.

I cannot explain me this behavior... It makes no sense to me. Why should the first incoming request's identity should be cached on 'server2'?
If I restart the IIS and re-execute the requests with another windows identity, this is the "first working request" and the others get his identity on 'server2'.


问:
angular 2 export interface initialize inside component issue
i am having kind of a goofy problem. inside my component i export some interfaces and whe i try to use them inside my component if i dont initialize them i am geting issues about undifined which i totaly normal. Is these any other way to init them without writting all that code again?

```<code>export interface Data {
    Code: string;
    Date: Date;
    OccurredDate: Date;
    Person: Person;
    Vehicle: Vehicle;
    Policy: Policy;
    OccurredLocation: OccurredLocation;
    Phones: Phone[];
    Notes: string;
    Actions: Action[];
}

export interface RootObject {
    Data: Data[];
    IsSuccessful: boolean;
    Messages: any[];
}
</code>```

these are 2 of my interfaces and i init them like this:

```<code>export class SubscriberComponent {
        public myRootObject: RootObject = {
            Data: this.myData[0],
            IsSuccessful: true,
            Messages: null
        }
        public myData: Data ={
            Code: '',
            Date: new Date(),
            OccurredDate: new Date(),
            Person: null,
            Vehicle: null,
            Policy: null,
            OccurredLocation: null,
            Phones: null,
            Notes: '',
            Actions: null,
    }
}
</code>```

when i try to use myData.Code if i dont initialize it with '' i get and error. any other way to init my templates without all that much code?

答:
The short answer of how to initialize an object of type Data would be:

myData = {} as Data;
```

<p>But a bit more explanation... Interfaces are more of a "help" for the programmer himself, as well as the IDE, that can "warn" you with squiggly lines and errors that you are now assigning wrong type of values.</p>

<p>During runtime, this doesn't really matter though. Typescript is a superset of JavaScript, and TS will be compiled as JS during runtime, and in JS there are no interfaces.</p>

<p>To present this regarding interfaces, we could say we have an interface like so:</p>

<pre class="lang-ts prettyprint-override"><code>interface Foo {
  bar: number
  bas: string
}
</code>```

and a object initialized like so: foo = {} as Foo;

Since using an Interface your IDE is helpful and warns you of assigning wrong type of data to foo.bar. BUT this would still run and assign the object to foo.bar:

this.foo.bar = { id:1, name: "name" };
```

<p>So as mentioned on top of answer, if you do not <em>need</em> default values for your <code>Data</code> object, the proper way to initialize the object would be:</p>

<pre class="lang-ts prettyprint-override"><code>myData = {} as Data;
</code>```

this will solve your undefined issue, since the object is initialized as an empty object. So unless you need default values, you can see it's pretty useless to initialize the properties, as the even the type of the properties can be overwritten.

Here's a sample of how you can overwrite a string value with an object just to have some reference on what I explained above :)

Demo

Body:
i am having kind of a goofy problem. inside my component i export some interfaces and whe i try to use them inside my component if i dont initialize them i am geting issues about undifined which i totaly normal. Is these any other way to init them without writting all that code again?

export interface Data {
    Code: string;
    Date: Date;
    OccurredDate: Date;
    Person: Person;
    Vehicle: Vehicle;
    Policy: Policy;
    OccurredLocation: OccurredLocation;
    Phones: Phone[];
    Notes: string;
    Actions: Action[];
}

export interface RootObject {
    Data: Data[];
    IsSuccessful: boolean;
    Messages: any[];
}

these are 2 of my interfaces and i init them like this:

export class SubscriberComponent {
        public myRootObject: RootObject = {
            Data: this.myData[0],
            IsSuccessful: true,
            Messages: null
        }
        public myData: Data ={
            Code: '',
            Date: new Date(),
            OccurredDate: new Date(),
            Person: null,
            Vehicle: null,
            Policy: null,
            OccurredLocation: null,
            Phones: null,
            Notes: '',
            Actions: null,
    }
}

when i try to use myData.Code if i dont initialize it with '' i get and error. any other way to init my templates without all that much code?

Body:
The short answer of how to initialize an object of type Data would be:

myData = {} as Data;

But a bit more explanation... Interfaces are more of a "help" for the programmer himself, as well as the IDE, that can "warn" you with squiggly lines and errors that you are now assigning wrong type of values.

During runtime, this doesn't really matter though. Typescript is a superset of JavaScript, and TS will be compiled as JS during runtime, and in JS there are no interfaces.

To present this regarding interfaces, we could say we have an interface like so:

interface Foo {
  bar: number
  bas: string
}

and a object initialized like so: foo = {} as Foo;

Since using an Interface your IDE is helpful and warns you of assigning wrong type of data to foo.bar. BUT this would still run and assign the object to foo.bar:

this.foo.bar = { id:1, name: "name" };

So as mentioned on top of answer, if you do not need default values for your Data object, the proper way to initialize the object would be:

myData = {} as Data;

this will solve your undefined issue, since the object is initialized as an empty object. So unless you need default values, you can see it's pretty useless to initialize the properties, as the even the type of the properties can be overwritten.

Here's a sample of how you can overwrite a string value with an object just to have some reference on what I explained above :)

Demo


问:
Gulp build is not working since devDependencies are not installed when NODE_ENV=production
I have an application in which I am trying to do npm install && then gulp build. It works fine unless I give NODE_ENV=production since npm will not install modules listed in devDependencies.

Following are some snippets.

```<code>"devDependencies": {
    "aliasify": "^2.0.0",
    "babel": "^6.5.2",
    "babel-plugin-__coverage__": "^11.0.0",
    "babel-polyfill": "^6.16.0",
    "babel-preset-es2015": "^6.16.0",
    "babelify": "^7.3.0"
}
</code>```

Error

```<code>[13:10:13] Failed to load external module babel-register
[13:10:13] Failed to load external module babel-core/register
[13:10:13] Failed to load external module babel/register
/path/to/repository/gulpfile.babel.js:1
(function (exports, require, module, __filename, __dirname) { import gulp from 'gulp';
                                                              ^^^^^^
SyntaxError: Unexpected reserved word
</code>```

Since I am trying to build the application for production, babel & its dependencies are not installed. I am not even able to start the build.

Please suggest a solution.

答:
If you don't want to install dev dependencies, you can write gulpfile in es5 and es6 features already supported by nodejs.

Or you can set NODE_ENV after you run  gulp tasks.

Also npm install --only=dev will install dev dependencies regardless of NODE_ENV.

Body:
I have an application in which I am trying to do npm install && then gulp build. It works fine unless I give NODE_ENV=production since npm will not install modules listed in devDependencies.

Following are some snippets.

"devDependencies": {
    "aliasify": "^2.0.0",
    "babel": "^6.5.2",
    "babel-plugin-__coverage__": "^11.0.0",
    "babel-polyfill": "^6.16.0",
    "babel-preset-es2015": "^6.16.0",
    "babelify": "^7.3.0"
}

Error

[13:10:13] Failed to load external module babel-register
[13:10:13] Failed to load external module babel-core/register
[13:10:13] Failed to load external module babel/register
/path/to/repository/gulpfile.babel.js:1
(function (exports, require, module, __filename, __dirname) { import gulp from 'gulp';
                                                              ^^^^^^
SyntaxError: Unexpected reserved word

Since I am trying to build the application for production, babel & its dependencies are not installed. I am not even able to start the build.

Please suggest a solution.


问:
how to toggle expand row by click on button in table using bootstrap and jQuery
I have this example, I've successfully made table to be collapse but it is only click row in the table.

I wanna to change it , only if click on button the expand more datails

See this fiddle

Code Snippet

$('.flip').click(function() {
  $(this)
    .closest('tbody')
    .next('.section')
    .toggle('slow');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section {
  display: none;
}</code>```

      CASINO
      BONUS
      HIGHLIGHTS
      DEPOSIT
      RATING

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 111
      item 112
      item 113
      item 114

      item 121
      item 122
      item 123
      item 124

      item 131
      item 132
      item 133
      item 134

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 211
      item 212
      item 213
      item 214

      item 221
      item 222
      item 223
      item 224

      item 231
      item 232
      item 233
      item 234

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

```

if can get class flip from td to button read more

答:
$('.readmore').click(function () {
            $(this).closest('table').closest('tbody').next('.section').toggle('slow');
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section {
  display: none;
}</code>```

                CASINO
                BONUS
                HIGHLIGHTS
                DEPOSIT
                RATING

                                <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                <button class="readmore" id="acc1">READ MORE </button>

                item 111
                item 112
                item 113
                item 114

                item 121
                item 122
                item 123
                item 124

                item 131
                item 132
                item 133
                item 134

                                <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                <button class="readmore" id="acc1">READ MORE </button>

                item 211
                item 212
                item 213
                item 214

                item 221
                item 222
                item 223
                item 224

                item 231
                item 232
                item 233
                item 234

                                <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                <button class="readmore" id="acc1">READ MORE </button>

                item 311
                item 312
                item 313
                item 314

                item 321
                item 322
                item 323
                item 324

                item 331
                item 332
                item 333
                item 334

                                <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                <button class="readmore" id="acc1">READ MORE </button>

                item 311
                item 312
                item 313
                item 314

                item 321
                item 322
                item 323
                item 324

                item 331
                item 332
                item 333
                item 334

                                <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                         sfgfsjghsjghsjghjsghsjghsj

                                <button class="readmore" id="acc1">READ MORE </button>

                item 311
                item 312
                item 313
                item 314

                item 321
                item 322
                item 323
                item 324

                item 331
                item 332
                item 333
                item 334

```

Body:
I have this example, I've successfully made table to be collapse but it is only click row in the table.

I wanna to change it , only if click on button the expand more datails

See this fiddle

Code Snippet

$('.flip').click(function() {
  $(this)
    .closest('tbody')
    .next('.section')
    .toggle('slow');
});

.section {
  display: none;
}

      CASINO
      BONUS
      HIGHLIGHTS
      DEPOSIT
      RATING

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 111
      item 112
      item 113
      item 114

      item 121
      item 122
      item 123
      item 124

      item 131
      item 132
      item 133
      item 134

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 211
      item 212
      item 213
      item 214

      item 221
      item 222
      item 223
      item 224

      item 231
      item 232
      item 233
      item 234

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

if can get class flip from td to button read more

Body:
$('.readmore').click(function () {
            $(this).closest('table').closest('tbody').next('.section').toggle('slow');
        });

.section {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main_table">
        <thead>
            <tr class="firstline">
                <th>CASINO</th>
                <th>BONUS</th>
                <th>HIGHLIGHTS</th>
                <th>DEPOSIT</th>
                <th>RATING</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td colspan="6" class="flip">
                    <table>
                        <tr>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/logosquare-big.png" /><button>PLAY NOW!</button>
                            </td>
                            <td>
                                <div>200% UP TO</div>
                                <div>$1000</div>
                                <div>+250 FREE SPINS</div>
                            </td>
                            <td>
                                <ul>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                </ul>
                            </td>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-nodeposit.png" />
                            </td>
                            <td>
                                <i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i>
                            </td>
                            <td>
                                <button class="readmore" id="acc1">READ MORE <i class="fa fa-chevron-circle-right" aria-hidden="true"></i></button>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </tbody>
        <tbody class="section">
            <tr>
                <td>item 111</td>
                <td>item 112</td>
                <td>item 113</td>
                <td>item 114</td>
            </tr>
            <tr>
                <td>item 121</td>
                <td>item 122</td>
                <td>item 123</td>
                <td>item 124</td>
            </tr>
            <tr>
                <td>item 131</td>
                <td>item 132</td>
                <td>item 133</td>
                <td>item 134</td>
            </tr>
        </tbody>
        <tbody>
            <tr>
                <td colspan="6" class="flip">
                    <table>
                        <tr>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/logosquare-big.png" /><button>PLAY NOW!</button>
                            </td>
                            <td>
                                <div>200% UP TO</div>
                                <div>$1000</div>
                                <div>+250 FREE SPINS</div>
                            </td>
                            <td>
                                <ul>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                </ul>
                            </td>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-nodeposit.png" />
                            </td>
                            <td>
                                <i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star-half fa-2x"
                                                                                aria-hidden="true"></i>
                            </td>
                            <td>
                                <button class="readmore" id="acc1">READ MORE <i class="fa fa-chevron-circle-right" aria-hidden="true"></i></button>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </tbody>
        <tbody class="section">
            <tr>
                <td>item 211</td>
                <td>item 212</td>
                <td>item 213</td>
                <td>item 214</td>
            </tr>
            <tr>
                <td>item 221</td>
                <td>item 222</td>
                <td>item 223</td>
                <td>item 224</td>
            </tr>
            <tr>
                <td>item 231</td>
                <td>item 232</td>
                <td>item 233</td>
                <td>item 234</td>
            </tr>
        </tbody>
        <tbody>
            <tr>
                <td colspan="6" class="flip">
                    <table>
                        <tr>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/logosquare-big.png" /><button>PLAY NOW!</button>
                            </td>
                            <td>
                                <div>200% UP TO</div>
                                <div>$1000</div>
                                <div>+250 FREE SPINS</div>
                            </td>
                            <td>
                                <ul>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                </ul>
                            </td>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-nodeposit.png" />
                            </td>
                            <td>
                                <i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i>
                            </td>
                            <td>
                                <button class="readmore" id="acc1">READ MORE <i class="fa fa-chevron-circle-right" aria-hidden="true"></i></button>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </tbody>
        <tbody class="section">
            <tr>
                <td>item 311</td>
                <td>item 312</td>
                <td>item 313</td>
                <td>item 314</td>
            </tr>
            <tr>
                <td>item 321</td>
                <td>item 322</td>
                <td>item 323</td>
                <td>item 324</td>
            </tr>
            <tr>
                <td>item 331</td>
                <td>item 332</td>
                <td>item 333</td>
                <td>item 334</td>
            </tr>
        </tbody>
        <tbody>
            <tr>
                <td colspan="6" class="flip">
                    <table>
                        <tr>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/logosquare-big.png" /><button>PLAY NOW!</button>
                            </td>
                            <td>
                                <div>200% UP TO</div>
                                <div>$1000</div>
                                <div>+250 FREE SPINS</div>
                            </td>
                            <td>
                                <ul>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                </ul>
                            </td>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-deposit.png" />
                            </td>
                            <td>
                                <i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star-half fa-2x"
                                                                                aria-hidden="true"></i>
                            </td>
                            <td>
                                <button class="readmore" id="acc1">READ MORE <i class="fa fa-chevron-circle-right" aria-hidden="true"></i></button>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </tbody>
        <tbody class="section">
            <tr>
                <td>item 311</td>
                <td>item 312</td>
                <td>item 313</td>
                <td>item 314</td>
            </tr>
            <tr>
                <td>item 321</td>
                <td>item 322</td>
                <td>item 323</td>
                <td>item 324</td>
            </tr>
            <tr>
                <td>item 331</td>
                <td>item 332</td>
                <td>item 333</td>
                <td>item 334</td>
            </tr>
        </tbody>
        <tbody>
            <tr>
                <td colspan="6" class="flip">
                    <table>
                        <tr>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/logosquare-big.png" /><button>PLAY NOW!</button>
                            </td>
                            <td>
                                <div>200% UP TO</div>
                                <div>$1000</div>
                                <div>+250 FREE SPINS</div>
                            </td>
                            <td>
                                <ul>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                    <li>
                                        <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-check.png" /> sfgfsjghsjghsjghjsghsjghsj
                                    </li>
                                </ul>
                            </td>
                            <td>
                                <img src="http://freespins.dev.kim/wp-content/uploads/2017/03/icon-nodeposit.png" />
                            </td>
                            <td>
                                <i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i><i class="fa fa-star fa-2x" aria-hidden="true"></i>
                            </td>
                            <td>
                                <button class="readmore" id="acc1">READ MORE <i class="fa fa-chevron-circle-right" aria-hidden="true"></i></button>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </tbody>
        <tbody class="section">
            <tr>
                <td>item 311</td>
                <td>item 312</td>
                <td>item 313</td>
                <td>item 314</td>
            </tr>
            <tr>
                <td>item 321</td>
                <td>item 322</td>
                <td>item 323</td>
                <td>item 324</td>
            </tr>
            <tr>
                <td>item 331</td>
                <td>item 332</td>
                <td>item 333</td>
                <td>item 334</td>
            </tr>
        </tbody>
    </table>


问:
Converting DDMMMYYYY to date format in pandas
I have dates in a DataFrame's column like:

```<code>1    06AUG2010
2    07APR2011
</code>```

I want to convert them to a type, where i can count diffrences between dates in days.
I'm searching the internet for the answer, but cant find it. New to pandas.

答:
You can use to_datetime with custom format:

```<code>df = pd.DataFrame({'date':['06AUG2010','07APR2011']}, index=[1,2])
print (df)
        date
1  06AUG2010
2  07APR2011

df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')
print (df)
        date
1 2010-08-06
2 2011-04-07
</code>```

And then for differences add diff:

```<code>df['date'] = df['date'].diff()
print (df)
      date
1      NaT
2 244 days
</code>```

Body:
I have dates in a DataFrame's column like:

1    06AUG2010
2    07APR2011

I want to convert them to a type, where i can count diffrences between dates in days.
I'm searching the internet for the answer, but cant find it. New to pandas.

Body:
You can use to_datetime with custom format:

df = pd.DataFrame({'date':['06AUG2010','07APR2011']}, index=[1,2])
print (df)
        date
1  06AUG2010
2  07APR2011

df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')
print (df)
        date
1 2010-08-06
2 2011-04-07

And then for differences add diff:

df['date'] = df['date'].diff()
print (df)
      date
1      NaT
2 244 days


问:
Java: Method always returns same result
I'm supposed to write a program for my programming class in High School. The program asks the user to input a time in seconds, and calculates the falling distance using the common formula d = 1/2 * g * t ^ 2. D is the distance (result), g equals 9.8 and t is the time the user entered. We are supposed to call the method 10 times for some reason. Here's my problem: The method always returns the same result (4.9 in the first iteration), no matter what the user's input for time was. What am I doing wrong?</p>

```<code>import javax.swing.JOptionPane;
public class fallingDistance {

    public static void main(String[] args){

        String input;
        double time;

        input = JOptionPane.showInputDialog("Enter the time in seconds: ");
        time = Double.parseDouble(input);
        System.out.println(time);
        for(int x=1; x<=10; x++){
            JOptionPane.showMessageDialog(null, "The falling distance is: " + calculate(x) + "m.");
        }

    }

    public static double calculate(double time){
        double g = 9.8, a=0.5;
        double distance = (a*g) * (Math.pow(time, 2.0));
        JOptionPane.showMessageDialog(null, distance);
        return (distance);
    }
}
</code>```

答: Why do you say return (distance)? I think you have to remove the brackets. Let me know if that helps.</p>

Title: Java: Method always returns same result

Body:
I'm supposed to write a program for my programming class in High School. The program asks the user to input a time in seconds, and calculates the falling distance using the common formula d = 1/2 * g * t ^ 2. D is the distance (result), g equals 9.8 and t is the time the user entered. We are supposed to call the method 10 times for some reason. Here's my problem: The method always returns the same result (4.9 in the first iteration), no matter what the user's input for time was. What am I doing wrong?

import javax.swing.JOptionPane;
public class fallingDistance {

    public static void main(String[] args){

        String input;
        double time;

        input = JOptionPane.showInputDialog("Enter the time in seconds: ");
        time = Double.parseDouble(input);
        System.out.println(time);
        for(int x=1; x<=10; x++){
            JOptionPane.showMessageDialog(null, "The falling distance is: " + calculate(x) + "m.");
        }

    }

    public static double calculate(double time){
        double g = 9.8, a=0.5;
        double distance = (a*g) * (Math.pow(time, 2.0));
        JOptionPane.showMessageDialog(null, distance);
        return (distance);
    }
}


问:
How to change gradle metadata location in java builds
I have a java project where i am using gradle for build purpose.

I have set GRADLE_USER_HOME to a location where all the artifacts are downloaded and managed, this is working fine and cool.

Inside the project work space there is a .gradle folder generated after the build which has below directories.

1. taskArtifacts --> This has files(fileHashes.bin,fileSnapshots.bin,taskArtifacts.bin and taskArtifacts.lock)

2. tasks

I understand these .gradle folder stores some metadata regarding the project build history. is it possible to move the location of .gradle folder to a external location and use it from there???If so how can i do this?

答:
I found the way, by passing --project-cache-dir argument we can change the location of local caching.

https://docs.gradle.org/current/userguide/gradle_command_line.html


问:
Access control on Tags
Does git allow to have access control on tags for creation and deletion. Similar to what it has for branches.

I want contributors to be able to create tags, but not to delete remote tags.

答: Git has no access control. You can implement access control using Git hooks and this would work the same for branches and tags. If you use some Git hosting solution, then it is a question to the hosting solution which level of access control it allows.</p>

Title: Access control on Tags