问:
Replace multiple
's with only one

How do I use JavaScript to detect

```<code><br>
<br>
<br>
</code>```

to become one

```<code><br>
</code>```

?

I tried with:

```<code>jQuery('body').html().replace(/(\<br\>\r\n){3, }/g,"\n");
</code>```

but this is not working for me.

答:
This solution is jQuery + DOM only, does not manipulate HTML as string, works with text nodes, ignores whitespace only text nodes:

```<code>$('br').each(function () {
  const {nodeName} = this;

  let node = this;

  while (node = node.previousSibling) {
    if (node.nodeType !== Node.TEXT_NODE || node.nodeValue.trim() !== '') {
      break;
    };
  }

  if (node && node !== this && node.nodeName === nodeName) {
    $(node).remove();
  }
});
</code>```

See: https://jsfiddle.net/kov35jct/

Title:
Replace multiple
's with only one

Body:
How do I use JavaScript to detect

to become one

?

I tried with:

jQuery('body').html().replace(/(\
\r\n){3, }/g,"\n");

but this is not working for me.

Body:
This solution is jQuery + DOM only, does not manipulate HTML as string, works with text nodes, ignores whitespace only text nodes:

$('br').each(function () {
  const {nodeName} = this;

  let node = this;

  while (node = node.previousSibling) {
    if (node.nodeType !== Node.TEXT_NODE || node.nodeValue.trim() !== '') {
      break;
    };
  }

  if (node && node !== this && node.nodeName === nodeName) {
    $(node).remove();
  }
});

See: https://jsfiddle.net/kov35jct/


来源: stackexchange

问:
How to change angular port from 4200 to any other
I want to use 5000 instead of 4200.

I have tried to create a file on root name ember-cli and put JSON according to the code below:

```<code>{
   "port": 5000
}
</code>```

But my app still runs on 4200 instead of 5000

答: you can also write this command: ng serve -p 5000

ContentLicense: CC BY-SA 4.0

Body:
I want to use 5000 instead of 4200.

I have tried to create a file on root name ember-cli and put JSON according to the code below:

{
   "port": 5000
}

But my app still runs on 4200 instead of 5000

ContentLicense: CC BY-SA 3.0


问:
UPDATE prepared statement with Object
I have an Object that maps column names to values. The columns to be updated are not known beforehand and are decided at run-time.

e.g. map = {col1: "value1", col2: "value2"}.

I want to execute an UPDATE query, updating a table with those columns to the corresponding values. Can I do the following? If not, is there an elegant way of doing it without building the query manually?

```<code>db.none('UPDATE mytable SET $1 WHERE id = 99', map)
</code>```

答:
is there an elegant way of doing it without building the query manually?

Yes, there is, by using the helpers for SQL generation.

You can pre-declare a static object like this:

```<code>const cs = new pgp.helpers.ColumnSet(['col1', 'col2'], {table: 'mytable'});
</code>```

And then use it like this, via helpers.update:

```<code>const sql = pgp.helpers.update(data, cs) + /* WHERE clause with the condition */;
// and then execute it:
db.none(sql).then(data => {}).catch(error => {})
</code>```

This approach will work with both a single object and an array of objects, and you will just append the update condition accordingly.

See also: PostgreSQL multi-row updates in Node.js

What if the column names are not known beforehand?

For that see: Dynamic named parameters in pg-promise, and note that a proper answer would depend on how you intend to cast types of such columns.

Title: UPDATE prepared statement with Object

Body:
I have an Object that maps column names to values. The columns to be updated are not known beforehand and are decided at run-time.

e.g. map = {col1: "value1", col2: "value2"}.

I want to execute an UPDATE query, updating a table with those columns to the corresponding values. Can I do the following? If not, is there an elegant way of doing it without building the query manually?

db.none('UPDATE mytable SET $1 WHERE id = 99', map)

Body:
is there an elegant way of doing it without building the query manually?

Yes, there is, by using the helpers for SQL generation.

You can pre-declare a static object like this:

const cs = new pgp.helpers.ColumnSet(['col1', 'col2'], {table: 'mytable'});

And then use it like this, via helpers.update:

const sql = pgp.helpers.update(data, cs) + /* WHERE clause with the condition */;
// and then execute it:
db.none(sql).then(data => {}).catch(error => {})

This approach will work with both a single object and an array of objects, and you will just append the update condition accordingly.

See also: PostgreSQL multi-row updates in Node.js

What if the column names are not known beforehand?

For that see: Dynamic named parameters in pg-promise, and note that a proper answer would depend on how you intend to cast types of such columns.


问:
filter two dropdown list with jQuery
I have two lists who looks like this.

```<code><select class="form-control" id="arrondissement" required="required" aria-invalid="false" name="arrondissement">
  <option value="1">1er arrondissement</option>
  <option value="2"><span>2ème arrondissement</span></option>
  <option value="3"><span>3ème arrondissement</span></option>
  <option value="4"><span>4ème arrondissement</span></option>
  <option value="5"><span>5ème arrondissement</span></option>
</select>

<select class="form-control classeNomIgh" id="nomIGH" required="required" aria-invalid="false" name="nomIGH">
  <!-- remplacer les valeurs "précodées" ('eiffel', 'montparnasse', 'tgi') par la liste des valeurs renvoyées par l'appel au WebService -->
  <option value="" label="---">---</option>
  <option data-arrondissement="1" value="IGH1">IGH1</option>
  <option data-arrondissement="2" value="IGH2">IGH2</option>
  <option data-arrondissement="3" value="IGH3">IGH3</option>
  <option data-arrondissement="4" value="IGH4">IGH4</option>
  <option data-arrondissement="5" value="IGH5">IGH5</option>
</select>
</code>```

How can i do so that when i select an 'arrondissement' in the first drowdown list, the second will display only those with data-arrondissement with the same value.

答:
Here you go with a solution

$('#arrondissement').change(function(){
  $('#nomIGH').find('option[data-arrondissement=' + $(this).find('option:selected').val() +']').attr('selected', 'selected');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="arrondissement" required="required" aria-invalid="false" name="arrondissement">
  <option value="1">1er arrondissement</option>
  <option value="2"><span>2ème arrondissement</span></option>
  <option value="3"><span>3ème arrondissement</span></option>
  <option value="4"><span>4ème arrondissement</span></option>
  <option value="5"><span>5ème arrondissement</span></option>
</select>

<select class="form-control classeNomIgh" id="nomIGH" required="required" aria-invalid="false" name="nomIGH">
  <!-- remplacer les valeurs "précodées" ('eiffel', 'montparnasse', 'tgi') par la liste des valeurs renvoyées par l'appel au WebService -->
  <option value="" label="---">---</option>
  <option data-arrondissement="1" value="IGH1">IGH1</option>
  <option data-arrondissement="2" value="IGH2">IGH2</option>
  <option data-arrondissement="3" value="IGH3">IGH3</option>
  <option data-arrondissement="4" value="IGH4">IGH4</option>
  <option data-arrondissement="5" value="IGH5">IGH5</option>
</select></code>```

Hope this will help you.

Title: filter two dropdown list with jQuery

Body:
I have two lists who looks like this.

<select class="form-control" id="arrondissement" required="required" aria-invalid="false" name="arrondissement">
  <option value="1">1er arrondissement</option>
  <option value="2">2ème arrondissement</option>
  <option value="3">3ème arrondissement</option>
  <option value="4">4ème arrondissement</option>
  <option value="5">5ème arrondissement</option>
</select>

<select class="form-control classeNomIgh" id="nomIGH" required="required" aria-invalid="false" name="nomIGH">

  <option value="" label="---">---</option>
  <option data-arrondissement="1" value="IGH1">IGH1</option>
  <option data-arrondissement="2" value="IGH2">IGH2</option>
  <option data-arrondissement="3" value="IGH3">IGH3</option>
  <option data-arrondissement="4" value="IGH4">IGH4</option>
  <option data-arrondissement="5" value="IGH5">IGH5</option>
</select>

How can i do so that when i select an 'arrondissement' in the first drowdown list, the second will display only those with data-arrondissement with the same value.

Body:
Here you go with a solution

$('#arrondissement').change(function(){
  $('#nomIGH').find('option[data-arrondissement=' + $(this).find('option:selected').val() +']').attr('selected', 'selected');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="arrondissement" required="required" aria-invalid="false" name="arrondissement">
  <option value="1">1er arrondissement</option>
  <option value="2"><span>2ème arrondissement</span></option>
  <option value="3"><span>3ème arrondissement</span></option>
  <option value="4"><span>4ème arrondissement</span></option>
  <option value="5"><span>5ème arrondissement</span></option>
</select>

<select class="form-control classeNomIgh" id="nomIGH" required="required" aria-invalid="false" name="nomIGH">
  <!-- remplacer les valeurs "précodées" ('eiffel', 'montparnasse', 'tgi') par la liste des valeurs renvoyées par l'appel au WebService -->
  <option value="" label="---">---</option>
  <option data-arrondissement="1" value="IGH1">IGH1</option>
  <option data-arrondissement="2" value="IGH2">IGH2</option>
  <option data-arrondissement="3" value="IGH3">IGH3</option>
  <option data-arrondissement="4" value="IGH4">IGH4</option>
  <option data-arrondissement="5" value="IGH5">IGH5</option>
</select>

Hope this will help you.


问:
Error Showing a specific column is not present in my sqlite Database Table
I am trying to enter user details into sqlite database but data is not getting entered.Though i have created a column with name user_mobile but still error shows table has no column with this name.Please help me with this error i am not able to understand where i am missing things.

Logcat Error :-

```<code>E/SQLiteLog: (1) table user has no column named user_mobile
E/SQLiteDatabase: Error inserting user_password=1234 user_email=him@gmail.com user_name=Himanshu user_mobile=9899235121
android.database.sqlite.SQLiteException: table user has no column named user_mobile (code 1): , while compiling: INSERT INTO user(user_password,user_email,user_name,user_mobile) VALUES (?,?,?,?)
</code>```

My SqliteHelper Class :

```<code>public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "UserManager.db";

    // User table name
    private static final String TABLE_USER = "user";

    // User Table Columns names
    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_USER_NAME = "user_name";
    private static final String COLUMN_USER_MOBILE = "user_mobile";
    private static final String COLUMN_USER_EMAIL = "user_email";
    private static final String COLUMN_USER_PASSWORD = "user_password";

    // create table sql query
    private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " TEXT," + COLUMN_USER_MOBILE + "TEXT,"
            + COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";

    // drop table sql query
    private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;

    /**
     * Constructor
     *
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        //Drop User Table if exist
        db.execSQL(DROP_USER_TABLE);

        // Create tables again
        onCreate(db);

    }

    /**
     * This method is to create user record
     *
     * @param user
     */
    public void addUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_MOBILE, user.getMobile());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        // Inserting Row
        db.insert(TABLE_USER, null, values);
        db.close();
    }

    /**
     * This method is to fetch all user and return the list of user records
     *
     * @return list
     */
    public List<User> getAllUser() {
        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID,
                COLUMN_USER_EMAIL,
                COLUMN_USER_MOBILE,
                COLUMN_USER_NAME,
                COLUMN_USER_PASSWORD
        };
        // sorting orders
        String sortOrder =
                COLUMN_USER_NAME + " ASC";
        List<User> userList = new ArrayList<User>();

        SQLiteDatabase db = this.getReadableDatabase();

        // query the user table
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,    //columns to return
                null,        //columns for the WHERE clause
                null,        //The values for the WHERE clause
                null,       //group the rows
                null,       //filter by row groups
                sortOrder); //The sort order

        // Traversing through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                User user = new User();
                user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
                user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
                user.setMobile(cursor.getString(cursor.getColumnIndex(COLUMN_USER_MOBILE)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
                // Adding user record to list
                userList.add(user);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        // return user list
        return userList;
    }

    /**
     * This method to update user record
     *
     * @param user
     */
    public void updateUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_MOBILE, user.getMobile());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        // updating row
        db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?",
                new String[]{String.valueOf(user.getId())});
        db.close();
    }

    /**
     * This method is to delete user record
     *
     * @param user
     */
    public void deleteUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();
        // delete user record by id
        db.delete(TABLE_USER, COLUMN_USER_ID + " = ?",
                new String[]{String.valueOf(user.getId())});
        db.close();
    }

    /**
     * This method to check user exist or not
     *
     * @param email
     * @return true/false
     */
    public boolean checkUser(String email) {

        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID
        };
        SQLiteDatabase db = this.getReadableDatabase();

        // selection criteria
        String selection = COLUMN_USER_EMAIL + " = ?";

        // selection argument
        String[] selectionArgs = {email};

        // query user table with condition
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                      //filter by row groups
                null);                      //The sort order
        int cursorCount = cursor.getCount();
        cursor.close();
        db.close();

        if (cursorCount > 0) {
            return true;
        }

        return false;
    }

    /**
     * This method to check user exist or not
     *
     * @param email
     * @param password
     * @return true/false
     */
    public boolean checkUser(String email, String password) {

        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID
        };
        SQLiteDatabase db = this.getReadableDatabase();
        // selection criteria
        String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";

        // selection arguments
        String[] selectionArgs = {email, password};

        // query user table with conditions
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                       //filter by row groups
                null);                      //The sort order

        int cursorCount = cursor.getCount();

        cursor.close();
        db.close();
        if (cursorCount > 0) {
            return true;
        }

        return false;
    }
}
</code>```

答:
You are missing a space before TEXT:
COLUMN_USER_MOBILE + "TEXT,"

Body:
I am trying to enter user details into sqlite database but data is not getting entered.Though i have created a column with name user_mobile but still error shows table has no column with this name.Please help me with this error i am not able to understand where i am missing things.

Logcat Error :-

E/SQLiteLog: (1) table user has no column named user_mobile
E/SQLiteDatabase: Error inserting user_password=1234 user_email=him@gmail.com user_name=Himanshu user_mobile=9899235121
android.database.sqlite.SQLiteException: table user has no column named user_mobile (code 1): , while compiling: INSERT INTO user(user_password,user_email,user_name,user_mobile) VALUES (?,?,?,?)

My SqliteHelper Class :

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "UserManager.db";

    // User table name
    private static final String TABLE_USER = "user";

    // User Table Columns names
    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_USER_NAME = "user_name";
    private static final String COLUMN_USER_MOBILE = "user_mobile";
    private static final String COLUMN_USER_EMAIL = "user_email";
    private static final String COLUMN_USER_PASSWORD = "user_password";

    // create table sql query
    private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " TEXT," + COLUMN_USER_MOBILE + "TEXT,"
            + COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";

    // drop table sql query
    private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;

    /**
     * Constructor
     *
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        //Drop User Table if exist
        db.execSQL(DROP_USER_TABLE);

        // Create tables again
        onCreate(db);

    }

    /**
     * This method is to create user record
     *
     * @param user
     */
    public void addUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_MOBILE, user.getMobile());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        // Inserting Row
        db.insert(TABLE_USER, null, values);
        db.close();
    }

    /**
     * This method is to fetch all user and return the list of user records
     *
     * @return list
     */
    public List<User> getAllUser() {
        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID,
                COLUMN_USER_EMAIL,
                COLUMN_USER_MOBILE,
                COLUMN_USER_NAME,
                COLUMN_USER_PASSWORD
        };
        // sorting orders
        String sortOrder =
                COLUMN_USER_NAME + " ASC";
        List<User> userList = new ArrayList<User>();

        SQLiteDatabase db = this.getReadableDatabase();

        // query the user table
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,    //columns to return
                null,        //columns for the WHERE clause
                null,        //The values for the WHERE clause
                null,       //group the rows
                null,       //filter by row groups
                sortOrder); //The sort order

        // Traversing through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                User user = new User();
                user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
                user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
                user.setMobile(cursor.getString(cursor.getColumnIndex(COLUMN_USER_MOBILE)));
                user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
                user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
                // Adding user record to list
                userList.add(user);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        // return user list
        return userList;
    }

    /**
     * This method to update user record
     *
     * @param user
     */
    public void updateUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_MOBILE, user.getMobile());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        // updating row
        db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?",
                new String[]{String.valueOf(user.getId())});
        db.close();
    }

    /**
     * This method is to delete user record
     *
     * @param user
     */
    public void deleteUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();
        // delete user record by id
        db.delete(TABLE_USER, COLUMN_USER_ID + " = ?",
                new String[]{String.valueOf(user.getId())});
        db.close();
    }

    /**
     * This method to check user exist or not
     *
     * @param email
     * @return true/false
     */
    public boolean checkUser(String email) {

        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID
        };
        SQLiteDatabase db = this.getReadableDatabase();

        // selection criteria
        String selection = COLUMN_USER_EMAIL + " = ?";

        // selection argument
        String[] selectionArgs = {email};

        // query user table with condition
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                      //filter by row groups
                null);                      //The sort order
        int cursorCount = cursor.getCount();
        cursor.close();
        db.close();

        if (cursorCount > 0) {
            return true;
        }

        return false;
    }

    /**
     * This method to check user exist or not
     *
     * @param email
     * @param password
     * @return true/false
     */
    public boolean checkUser(String email, String password) {

        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID
        };
        SQLiteDatabase db = this.getReadableDatabase();
        // selection criteria
        String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";

        // selection arguments
        String[] selectionArgs = {email, password};

        // query user table with conditions
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty';
         */
        Cursor cursor = db.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                       //filter by row groups
                null);                      //The sort order

        int cursorCount = cursor.getCount();

        cursor.close();
        db.close();
        if (cursorCount > 0) {
            return true;
        }

        return false;
    }
}


问:
Laravel post request not works
I have Form in Laravel and when i submit the form to redirect another page("action = panel") with inputs's value. but problem is that when i enter in another's link it displays error. what is wrong?

This is form

this is another page when submit form

this is error when i enter in link again

this is form code:

```<code><form action="{{route('adminPanel')}}" class="form" method="POST">
    <p>Name:</p>
    <input type="text" name="name"><br>
    <p>Password:</p>
    <input type="password" name="password"><br>
    <input type="submit" name="submit" value="Enter As Admin" class="submit">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</code>```

this is routes:

```<code>Route::get('/', [

    'uses' => 'AdminController@getAdminIndex',

    'as' => 'index.admin'
]);
Route::post('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);
</code>```

this is controller:

```<code>class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
        return view('admin/admin', ['name' => $request->name]);
    }
}
</code>```

答:
Sometimes routes may create you an issue. Try below snippet.

```<code><form action="{{route('adminPanel')}}" class="form" method="POST">
  <p>Name:</p>
  <input type="text" name="name"><br>

  <p>Password:</p>
  <input type="password" name="password"><br>

  <input type="submit" name="submit" value="Enter As Admin" class="submit">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</code>```

Correct your Routes as below and try.

```<code>Route::post('/adminPanel', ['uses' => 'AdminController@getAdminPanel', 'as' => 'adminPanel' ]);
</code>```

Title: Laravel post request not works

Body:
I have Form in Laravel and when i submit the form to redirect another page("action = panel") with inputs's value. but problem is that when i enter in another's link it displays error. what is wrong?

This is form

this is another page when submit form

this is error when i enter in link again

this is form code:

<form action="{{route('adminPanel')}}" class="form" method="POST">

Name:

    <input type="text" name="name">

Password:

    <input type="password" name="password">

    <input type="submit" name="submit" value="Enter As Admin" class="submit">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

this is routes:

Route::get('/', [

    'uses' => 'AdminController@getAdminIndex',

    'as' => 'index.admin'
]);
Route::post('/panel', [
    'uses' => 'AdminController@getAdminPanel',
    'as' => 'adminPanel'

]);

this is controller:

class AdminController extends Controller
{
    public function getAdminIndex(){
        return view('admin/index');
    }
    public function getAdminPanel(Request $request){
        return view('admin/admin', ['name' => $request->name]);
    }
}

Body:
Sometimes routes may create you an issue. Try below snippet.

<form action="{{route('adminPanel')}}" class="form" method="POST">
  <p>Name:</p>
  <input type="text" name="name"><br>

  <p>Password:</p>
  <input type="password" name="password"><br>

  <input type="submit" name="submit" value="Enter As Admin" class="submit">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Correct your Routes as below and try.

Route::post('/adminPanel', ['uses' => 'AdminController@getAdminPanel', 'as' => 'adminPanel' ]);


问:
Create a barplot with unique strings
```<code>#Data set
library(ggplot2)
library(dplyr)
data <- data_frame(ended= c("14/11/2016 13:37", "14/11/2016 13:37",
"14/11/2016 13:47", "14/11/2016 13:51", "14/11/2016 13:51"),
satisfactionLevel = c("Very dissatisfied", "Very satisfied",
"Satisfied", "Neither satisfied nor dissatisfied",
"Very satisfied"))
</code>```

I want to make a barplot where the x axis contains the different satisfaction levels and y axis counts their number.

I tried

```<code>ggplot(mydata, aes(x=unique(satisfactionLevel), y = n_distinct(satisfactionLevel))) + geom_bar()
</code>```

答:
I think the following one should work:

```<code>ggplot(data, aes(x = satisfactionLevel)) +
         geom_bar()
</code>```

That counts the number of each satisfactionLevel.

Title: Create a barplot with unique strings

Body:
#Data set
library(ggplot2)
library(dplyr)
data <- data_frame(ended= c("14/11/2016 13:37", "14/11/2016 13:37",
"14/11/2016 13:47", "14/11/2016 13:51", "14/11/2016 13:51"),
satisfactionLevel = c("Very dissatisfied", "Very satisfied",
"Satisfied", "Neither satisfied nor dissatisfied",
"Very satisfied"))

I want to make a barplot where the x axis contains the different satisfaction levels and y axis counts their number.

I tried

ggplot(mydata, aes(x=unique(satisfactionLevel), y = n_distinct(satisfactionLevel))) + geom_bar()

Body:
I think the following one should work:

ggplot(data, aes(x = satisfactionLevel)) +
         geom_bar()

That counts the number of each satisfactionLevel.


问:
upstart ubuntu apt-get install fails to configure
After installing upstart with

```<code>sudo apt-get install upstart
</code>```

the command

```<code>start jobname
</code>```

prints this:

start: Name "com.ubuntu.Upstart" does not exist

what am i missing?

答: All Upstart commands e.g. initctl, status, start, stop should to be executed as the root user or as sudo. Running your command with sudo or as root user should solve your problem.

Body:
After installing upstart with

sudo apt-get install upstart

the command

start jobname

prints this:

start: Name "com.ubuntu.Upstart" does not exist

what am i missing?


问:
Display a number from array in PHP
Hello I would like to have a code that displays randomly from an array a number and displays it.
For example this code

```<code><?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
</code>```

will return

```<code>Array
(
    [1] => January
    [2] => February
    [3] => March
)
</code>```

Instead of this, I would like to display on

答:
Use rand()

```<code>$iIndex = rand(1, count($firstquarter));
echo $firstquarter[$iIndex];
</code>```

This assumes you have an one indexed array with consecutive keys.

ContentLicense: CC BY-SA 2.5

Title: Display a number from array in PHP

Body:
Hello I would like to have a code that displays randomly from an array a number and displays it.
For example this code

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

will return

Array
(
    [1] => January
    [2] => February
    [3] => March
)

Instead of this, I would like to display on

Body:
Use rand()

$iIndex = rand(1, count($firstquarter));
echo $firstquarter[$iIndex];

This assumes you have an one indexed array with consecutive keys.


问:
How to use Angular Local storage
i'm very much new to angular and trying to access localStorage. Here is the code. Please help me figure that out if it is not the right way to define and use. Thank you.</p>

```<code>var app = angular.module("toggleApp", ['LocalStorageModule']).config(function (localStorageServiceProvider) {
        localStorageServiceProvider
            .setPrefix('test')
            .setStorageType('localStorage');
    });
    app.controller("toggleController", function ($scope, $timeout,
                                                 timerParsingService, localStorageService) {
        localStorageService.set('user' ,'yash');
</code>```

答:
you dont require to define any module or inject any other module in the application.

inject $window in your application and then you can access the localstorage module like this

```<code>angular.module('toggleApp', [])
     .controller('toggleController', ['$scope', '$window', function ($scope,  $window) {
    $window.localStorage.setItem('ls', 'test');
}]);
</code>```

and save the value like this

```<code>$window.localStorage.setItem('ls', 'test');
</code>```

and you can retrieve the localStorage value like this

```<code>$window.localStorage.getItem('ls');
</code>```

Title: How to use Angular Local storage

Body:
i'm very much new to angular and trying to access localStorage. Here is the code. Please help me figure that out if it is not the right way to define and use. Thank you.

var app = angular.module("toggleApp", ['LocalStorageModule']).config(function (localStorageServiceProvider) {
        localStorageServiceProvider
            .setPrefix('test')
            .setStorageType('localStorage');
    });
    app.controller("toggleController", function ($scope, $timeout,
                                                 timerParsingService, localStorageService) {
        localStorageService.set('user' ,'yash');

Body:
you dont require to define any module or inject any other module in the application.

inject $window in your application and then you can access the localstorage module like this

angular.module('toggleApp', [])
     .controller('toggleController', ['$scope', '$window', function ($scope,  $window) {
    $window.localStorage.setItem('ls', 'test');
}]);

and save the value like this

$window.localStorage.setItem('ls', 'test');

and you can retrieve the localStorage value like this

$window.localStorage.getItem('ls');


问:
Insert a Node at a Specific Position in a Linked List
I need to insert a note at position. I didn't get any error but my answer is wrong. Could you please help me to correct my code?
 Link to question</p>

```<code>Node InsertNth(Node head, int data, int position) {
    Node node = new Node();
    node.data = data;
 if (head == null){
        return node;
    } else {
    Node current = head;
    for (int i=0; i < position-1 ; i++){
        current = current.next;
    }

    node.next = current.next;
    current.next = node;
 return head;
}

}
</code>```

答:
```<code>Node insertAt(Node head, int data, int position) {
    Node node = new Node();
    node.data = data;
    if (position == 0) {
        node.next = head;
        return node;
    } else {
        head.next = insertAt(head.next, data, position - 1);
        return head;
    }
    /* Or iterative
    Node current = head;
    Node previous = null;
    for (int i = 0; i < position && current != null; i++) {
        previous = current;
        current = current.next;
    }
    node.next = current;
    if (previous == null) {
        head = node;
    } else {
        previous.next = node;
    }
    return head;
    */
}
</code>```

This does not do an IndexOutOfBoundsException.

Body:
I need to insert a note at position. I didn't get any error but my answer is wrong. Could you please help me to correct my code?
 Link to question

Node InsertNth(Node head, int data, int position) {
    Node node = new Node();
    node.data = data;
 if (head == null){
        return node;
    } else {
    Node current = head;
    for (int i=0; i < position-1 ; i++){
        current = current.next;
    }

    node.next = current.next;
    current.next = node;
 return head;
}

}

Body:
Node insertAt(Node head, int data, int position) {
    Node node = new Node();
    node.data = data;
    if (position == 0) {
        node.next = head;
        return node;
    } else {
        head.next = insertAt(head.next, data, position - 1);
        return head;
    }
    /* Or iterative
    Node current = head;
    Node previous = null;
    for (int i = 0; i < position && current != null; i++) {
        previous = current;
        current = current.next;
    }
    node.next = current;
    if (previous == null) {
        head = node;
    } else {
        previous.next = node;
    }
    return head;
    */
}

This does not do an IndexOutOfBoundsException.


问:
Update a nested state array based on selected value
I am trying to update which menu item was clicked and therefore change the class accordingly. I have tried different way suggested to do it but couldn't make it work.

Heres my code:

```<code>constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
        this.state = {
            menuState: [
                {
                    menuName: 'homeMenuStatus',
                    homeMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },
                {
                    menuName: 'accountMenuStatus',
                    accountMenuStatus: 'active',
                    ulSidenavClass: "nav child_menu block-display"
                },
                {
                    menuName: 'contactMenuStatus',
                    peopleMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },

            ]
        }
    }

handleClick(menuClicked) {
        this.state.menuState.map((name, index) => {
            let thisMenu = name.menuName;

            if(name.menuName == menuClicked) {
                if(this.state.menuClicked === 'active') {
                    this.setState({
                        ...this.state,
                        menuClicked: 'inactive',
                        ulSidenavClass: 'block-display height-adjust'
                    });
                } else {
                    this.setState({
                        ...this.state,
                        menuClicked: 'active',
                        ulSidenavClass: 'block-display'
                    });
                }
            } else {
                this.setState({
                    ...this.state,
                    thisMenu: 'inactive',
                    ulSidenavClass: 'block-display height-adjust'
                });
            }
        });
    }
</code>```

HTML:

```<code>    <div>
        <ul>
            <li className={this.state.menuState[0].homeMenuStatus}>
                <a onClick={() => this.handleClick('homeMenuStatus')}>Home </a>
                <ul className={this.state.menuState[0].ulSidenavClass}>
                    <li>
                        <a href="#">Dashboard</a>
                    </li>
                    <li>
                        <a href="#">Activities</a>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</code>```

My state object is not getting changed. Must be doing something wrong in setState(). Can anyone please guide me.

答:
You are setting your global state instead off the state of the specific object, what would help is mapping over the menu's setting them and just appending the new menu to the state.

You are setting on this.state instead off your this.state.desiredItem

Feel free to ask questions, good luck :)

Body:
I am trying to update which menu item was clicked and therefore change the class accordingly. I have tried different way suggested to do it but couldn't make it work.

Heres my code:

constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
        this.state = {
            menuState: [
                {
                    menuName: 'homeMenuStatus',
                    homeMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },
                {
                    menuName: 'accountMenuStatus',
                    accountMenuStatus: 'active',
                    ulSidenavClass: "nav child_menu block-display"
                },
                {
                    menuName: 'contactMenuStatus',
                    peopleMenuStatus: 'inactive',
                    ulSidenavClass: "nav child_menu no-display"
                },

            ]
        }
    }

handleClick(menuClicked) {
        this.state.menuState.map((name, index) => {
            let thisMenu = name.menuName;

            if(name.menuName == menuClicked) {
                if(this.state.menuClicked === 'active') {
                    this.setState({
                        ...this.state,
                        menuClicked: 'inactive',
                        ulSidenavClass: 'block-display height-adjust'
                    });
                } else {
                    this.setState({
                        ...this.state,
                        menuClicked: 'active',
                        ulSidenavClass: 'block-display'
                    });
                }
            } else {
                this.setState({
                    ...this.state,
                    thisMenu: 'inactive',
                    ulSidenavClass: 'block-display height-adjust'
                });
            }
        });
    }

HTML:

                 this.handleClick('homeMenuStatus')}>Home

                        Dashboard

                        Activities

My state object is not getting changed. Must be doing something wrong in setState(). Can anyone please guide me.


问:
Cannot debug error message for psycopg2 with django and postgreSQL
I am trying to create a postgreSQL database connected to a django web app using psycopg2. I am recieving the following error when I run python manage.py migrate

```<code>(temp-python) ❯ python manage.py migrate
Traceback (most recent call last):
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/backends/postgresql/base.py", line 20, in <module>
    import psycopg2 as Database
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: ~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/core/management/__init__.py", line 341, in execute
    django.setup()
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/apps/config.py", line 199, in import_models
    self.models_module = import_module(models_module_name)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "~/git-repos/MyApp/connecting/models.py", line 2, in <module>
    from django.contrib.auth.models import User
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/contrib/auth/models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/contrib/auth/base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/models/base.py", line 119, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/models/base.py", line 316, in add_to_class
    value.contribute_to_class(cls, name)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/models/options.py", line 214, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/utils.py", line 211, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/utils.py", line 115, in load_backend
    return import_module('%s.base' % backend_name)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/backends/postgresql/base.py", line 24, in <module>
    raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: ~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference
</code>```

I'm running arch linux and don't really know where to begin with debugging this error, thanks in advance for any help.

答:
There was a known bug on psycopg2 versions prior to 2.2.

That gives you the option of either restarting it, as it may be a runtime problem, or alternatively you can reinstall using the --no-binary psycopg2 command, which will prevent it using the wheel, per the last comment in that thread.

Body:
I am trying to create a postgreSQL database connected to a django web app using psycopg2. I am recieving the following error when I run python manage.py migrate

(temp-python) ❯ python manage.py migrate
Traceback (most recent call last):
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/backends/postgresql/base.py", line 20, in <module>
    import psycopg2 as Database
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import (                     # noqa
ImportError: ~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/core/management/__init__.py", line 341, in execute
    django.setup()
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/apps/config.py", line 199, in import_models
    self.models_module = import_module(models_module_name)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "~/git-repos/MyApp/connecting/models.py", line 2, in <module>
    from django.contrib.auth.models import User
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/contrib/auth/models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/contrib/auth/base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/models/base.py", line 119, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/models/base.py", line 316, in add_to_class
    value.contribute_to_class(cls, name)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/models/options.py", line 214, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/utils.py", line 211, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/utils.py", line 115, in load_backend
    return import_module('%s.base' % backend_name)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/django/db/backends/postgresql/base.py", line 24, in <module>
    raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: ~/git-repos/MyApp/temp-python/lib/python3.4/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference

I'm running arch linux and don't really know where to begin with debugging this error, thanks in advance for any help.


问:
Testing background color espresso Android
Is it possible to check if the background color matches a given color with espresso?

Update:

I made a custom matcher, similar to what @Irfan suggested, thanks!

```<code>public static Matcher<Object> backgroundShouldHaveColor(int expectedColor) {
    return buttondShouldHaveBackgroundColor(equalTo(expectedColor));
}
private static Matcher<Object> buttonShouldHaveBackgroundColor(final Matcher<Integer> expectedObject) {
    final int[] color = new int[1];
    return new BoundedMatcher<Object, Button>( Button.class) {
        @Override
        public boolean matchesSafely(final Button actualObject) {

            color[0] =((ColorDrawable) actualObject.getBackground()).getColor();

            if( expectedObject.matches(color[0])) {
                return true;
            } else {
                return false;
            }
        }
        @Override
        public void describeTo(final Description description) {
            // Should be improved!
            description.appendText("Color did not match "+color[0]);
        }
    };
}
</code>```

答:
Another approach to check TextView text's color could be via hasTextColor(int color) as it comes directly from Espresso.

```<code>import static android.support.test.espresso.matcher.ViewMatchers.hasTextColor;

onView(withId(R.id.anyTextView)).check(matches(hasTextColor(R.color.red)));
</code>```

Be aware that this method is currently in Beta for Espresso 3.0.1

Body:
Is it possible to check if the background color matches a given color with espresso?

Update:

I made a custom matcher, similar to what @Irfan suggested, thanks!

public static Matcher<Object> backgroundShouldHaveColor(int expectedColor) {
    return buttondShouldHaveBackgroundColor(equalTo(expectedColor));
}
private static Matcher<Object> buttonShouldHaveBackgroundColor(final Matcher<Integer> expectedObject) {
    final int[] color = new int[1];
    return new BoundedMatcher<Object, Button>( Button.class) {
        @Override
        public boolean matchesSafely(final Button actualObject) {

            color[0] =((ColorDrawable) actualObject.getBackground()).getColor();

            if( expectedObject.matches(color[0])) {
                return true;
            } else {
                return false;
            }
        }
        @Override
        public void describeTo(final Description description) {
            // Should be improved!
            description.appendText("Color did not match "+color[0]);
        }
    };
}

Body:
Another approach to check TextView text's color could be via hasTextColor(int color) as it comes directly from Espresso.

import static android.support.test.espresso.matcher.ViewMatchers.hasTextColor;

onView(withId(R.id.anyTextView)).check(matches(hasTextColor(R.color.red)));

Be aware that this method is currently in Beta for Espresso 3.0.1


问:
Find element with rel attribute and change text
I have a pagination for browsing older posts. I need to change it's text using jquery or js. (pagination generated in laravel package so can't edit text directly)

So I tried with finding rel and replace text. But no luck. This is my code.

$(".older-posts").find("li[rel='next']").html("Older posts");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="older-posts">
  <ul class="pagination">
    <li>
      « Previous
    </li>
    <li class="disabled"><span>Next »</span></li>
  </ul>
</div></code>```

Any idea?

答:
pure js solution:

Please Note: querySelectorAll returns an array, so position of li matters; if u change position of "prev" li , then this code might behave naughty.

Cheers

```<code>document.querySelectorAll('[rel="prev"]')[0].innerHTML = "Older posts";
</code>```

Approach 2:

If you feel that above code is incomplete for the reason I mentioned, use this approach instead

```<code>var lists = document.querySelectorAll("li")

var filteredList = Array.prototype.filter.call(lists,function(node) {   return node.innerHTML.includes("Previous"); });

filteredList[0].innerHTML = "Older posts";
</code>```

Body:
I have a pagination for browsing older posts. I need to change it's text using jquery or js. (pagination generated in laravel package so can't edit text directly)

So I tried with finding rel and replace text. But no luck. This is my code.

$(".older-posts").find("li[rel='next']").html("Older posts");

      « Previous

Next »

Any idea?

Body:
pure js solution:

Please Note: querySelectorAll returns an array, so position of li matters; if u change position of "prev" li , then this code might behave naughty.

Cheers

document.querySelectorAll('[rel="prev"]')[0].innerHTML = "Older posts";

Approach 2:

If you feel that above code is incomplete for the reason I mentioned, use this approach instead

var lists = document.querySelectorAll("li")

var filteredList = Array.prototype.filter.call(lists,function(node) {   return node.innerHTML.includes("Previous"); });

filteredList[0].innerHTML = "Older posts";


问:
SQL query to get min, max rows
I have following sample data, I want to get min and max time of every consecutive status.

```<code>cat     subcat  status  logtime
fruits  apple   0   30-10-2017 06:00
fruits  apple   0   30-10-2017 06:03
fruits  apple   0   30-10-2017 06:06
fruits  apple   0   30-10-2017 06:09
fruits  apple   0   30-10-2017 06:12
fruits  apple   0   30-10-2017 06:15
fruits  apple   0   30-10-2017 06:18
fruits  apple   0   30-10-2017 06:21
fruits  apple   0   30-10-2017 06:24
fruits  apple   0   30-10-2017 06:27
fruits  apple   0   30-10-2017 06:30
fruits  apple   0   30-10-2017 06:33
fruits  apple   0   30-10-2017 06:36
fruits  apple   0   30-10-2017 06:39
fruits  apple   0   30-10-2017 06:42
fruits  apple   0   30-10-2017 06:45
fruits  apple   0   30-10-2017 06:48
fruits  apple   0   30-10-2017 06:51
fruits  apple   0   30-10-2017 06:54
fruits  apple   0   30-10-2017 06:57
fruits  strawberry  1   30-10-2017 06:00
fruits  strawberry  1   30-10-2017 06:03
fruits  strawberry  1   30-10-2017 06:06
fruits  strawberry  2   30-10-2017 06:09
fruits  strawberry  1   30-10-2017 06:12
fruits  strawberry  1   30-10-2017 06:15
fruits  strawberry  1   30-10-2017 06:18
fruits  strawberry  1   30-10-2017 06:21
fruits  strawberry  1   30-10-2017 06:24
fruits  strawberry  1   30-10-2017 06:27
fruits  strawberry  1   30-10-2017 06:30
fruits  strawberry  1   30-10-2017 06:33
fruits  strawberry  1   30-10-2017 06:36
fruits  strawberry  1   30-10-2017 06:39
fruits  strawberry  2   30-10-2017 06:42
fruits  strawberry  1   30-10-2017 06:45
fruits  strawberry  1   30-10-2017 06:48
fruits  strawberry  1   30-10-2017 06:51
fruits  strawberry  1   30-10-2017 06:54
fruits  strawberry  1   30-10-2017 06:57
fruits  blueberry   0   30-10-2017 06:00
fruits  blueberry   0   30-10-2017 06:03
fruits  blueberry   0   30-10-2017 06:06
fruits  blueberry   2   30-10-2017 06:09
fruits  blueberry   0   30-10-2017 06:12
fruits  blueberry   0   30-10-2017 06:15
fruits  blueberry   0   30-10-2017 06:18
fruits  blueberry   0   30-10-2017 06:21
fruits  blueberry   0   30-10-2017 06:24
fruits  blueberry   0   30-10-2017 06:27
fruits  blueberry   0   30-10-2017 06:30
fruits  blueberry   0   30-10-2017 06:33
fruits  blueberry   0   30-10-2017 06:36
fruits  blueberry   0   30-10-2017 06:39
fruits  blueberry   2   30-10-2017 06:42
fruits  blueberry   0   30-10-2017 06:45
fruits  blueberry   0   30-10-2017 06:48
fruits  blueberry   0   30-10-2017 06:51
fruits  blueberry   0   30-10-2017 06:54
fruits  blueberry   0   30-10-2017 06:57
fruits  guaua   1   30-10-2017 06:00
fruits  guaua   1   30-10-2017 06:03
fruits  guaua   1   30-10-2017 06:06
fruits  guaua   2   30-10-2017 06:09
fruits  guaua   1   30-10-2017 06:12
fruits  guaua   1   30-10-2017 06:15
fruits  guaua   1   30-10-2017 06:18
fruits  guaua   1   30-10-2017 06:21
fruits  guaua   1   30-10-2017 06:24
fruits  guaua   1   30-10-2017 06:27
fruits  guaua   1   30-10-2017 06:30
fruits  guaua   1   30-10-2017 06:33
fruits  guaua   1   30-10-2017 06:36
fruits  guaua   1   30-10-2017 06:39
fruits  guaua   2   30-10-2017 06:42
fruits  guaua   1   30-10-2017 06:45
fruits  guaua   1   30-10-2017 06:48
fruits  guaua   1   30-10-2017 06:51
fruits  guaua   1   30-10-2017 06:54
fruits  guaua   1   30-10-2017 06:57
</code>```

I'm trying get min, max time of each status for cat and subcat status.

Output result should be following:

```<code>cat     subcat      status  mintime maxtime
fruits  apple       0   30-10-2017 06:00    30-10-2017 06:57
fruits  strawberry  1   30-10-2017 06:00    30-10-2017 06:06
fruits  strawberry  2   30-10-2017 06:09    30-10-2017 06:09
fruits  strawberry  1   30-10-2017 06:12    30-10-2017 06:39
fruits  strawberry  2   30-10-2017 06:42    30-10-2017 06:42
fruits  strawberry  1   30-10-2017 06:45    30-10-2017 06:57
fruits  blueberry   0   30-10-2017 06:00    30-10-2017 06:06
fruits  blueberry   2   30-10-2017 06:09    30-10-2017 06:09
fruits  blueberry   0   30-10-2017 06:12    30-10-2017 06:39
fruits  blueberry   2   30-10-2017 06:42    30-10-2017 06:42
fruits  blueberry   0   30-10-2017 06:45    30-10-2017 06:57
fruits  guaua       1   30-10-2017 06:00    30-10-2017 06:06
fruits  guaua       2   30-10-2017 06:09    30-10-2017 06:09
fruits  guaua       1   30-10-2017 06:12    30-10-2017 06:39
fruits  guaua       2   30-10-2017 06:42    30-10-2017 06:42
fruits  guaua       1   30-10-2017 06:45    30-10-2017 06:57
</code>```

tried with following sql query but unable to get above output instead its giving min, max total hour.

```<code>SELECT cat,
        subcat,
        status,
        min(logtime) as minlog,
        max(logtime) as maxlog
FROM fruits_log
WHERE
    cat = 'fruits'
    AND date_format(logtime,'%Y-%m-%d %H) = '2017-10-30 06'
    AND status IN ('0','1','2')
GROUP BY cat,subcat,date_format(logtime,'%Y-%m-%d %H),status
ORDER BY cat,subcat,minlog ;
</code>```

Please help what i'm missing in above query

答:
You may try something like this

```<code>select  t.cat, t.subcat, t.status, min(t.logdate), max(t.logdate)
from
(
    select t1.cat, t1.subcat, t1.status, t1.logdate, count(t2.cat) grpnum
    from data t1
    left join data t2 on t1.cat = t2.cat and t1.subcat = t2.subcat and
                         t1.status != t2.status and
                         t1.logdate < t2.logdate
    group by t1.cat, t1.subcat, t1.status, t1.logdate
) t
group by t.cat, t.subcat, t.status, t.grpnum
</code>```

I have tested on just very small sample of your data, but it seems to be ok. The inner query use a self-join to isolate consecutive rows with the same cat, subcat and status values. Once this is ready, you can simply do a group by for each group of rows in the data.

Title: SQL query to get min, max rows

Body:
I have following sample data, I want to get min and max time of every consecutive status.

cat     subcat  status  logtime
fruits  apple   0   30-10-2017 06:00
fruits  apple   0   30-10-2017 06:03
fruits  apple   0   30-10-2017 06:06
fruits  apple   0   30-10-2017 06:09
fruits  apple   0   30-10-2017 06:12
fruits  apple   0   30-10-2017 06:15
fruits  apple   0   30-10-2017 06:18
fruits  apple   0   30-10-2017 06:21
fruits  apple   0   30-10-2017 06:24
fruits  apple   0   30-10-2017 06:27
fruits  apple   0   30-10-2017 06:30
fruits  apple   0   30-10-2017 06:33
fruits  apple   0   30-10-2017 06:36
fruits  apple   0   30-10-2017 06:39
fruits  apple   0   30-10-2017 06:42
fruits  apple   0   30-10-2017 06:45
fruits  apple   0   30-10-2017 06:48
fruits  apple   0   30-10-2017 06:51
fruits  apple   0   30-10-2017 06:54
fruits  apple   0   30-10-2017 06:57
fruits  strawberry  1   30-10-2017 06:00
fruits  strawberry  1   30-10-2017 06:03
fruits  strawberry  1   30-10-2017 06:06
fruits  strawberry  2   30-10-2017 06:09
fruits  strawberry  1   30-10-2017 06:12
fruits  strawberry  1   30-10-2017 06:15
fruits  strawberry  1   30-10-2017 06:18
fruits  strawberry  1   30-10-2017 06:21
fruits  strawberry  1   30-10-2017 06:24
fruits  strawberry  1   30-10-2017 06:27
fruits  strawberry  1   30-10-2017 06:30
fruits  strawberry  1   30-10-2017 06:33
fruits  strawberry  1   30-10-2017 06:36
fruits  strawberry  1   30-10-2017 06:39
fruits  strawberry  2   30-10-2017 06:42
fruits  strawberry  1   30-10-2017 06:45
fruits  strawberry  1   30-10-2017 06:48
fruits  strawberry  1   30-10-2017 06:51
fruits  strawberry  1   30-10-2017 06:54
fruits  strawberry  1   30-10-2017 06:57
fruits  blueberry   0   30-10-2017 06:00
fruits  blueberry   0   30-10-2017 06:03
fruits  blueberry   0   30-10-2017 06:06
fruits  blueberry   2   30-10-2017 06:09
fruits  blueberry   0   30-10-2017 06:12
fruits  blueberry   0   30-10-2017 06:15
fruits  blueberry   0   30-10-2017 06:18
fruits  blueberry   0   30-10-2017 06:21
fruits  blueberry   0   30-10-2017 06:24
fruits  blueberry   0   30-10-2017 06:27
fruits  blueberry   0   30-10-2017 06:30
fruits  blueberry   0   30-10-2017 06:33
fruits  blueberry   0   30-10-2017 06:36
fruits  blueberry   0   30-10-2017 06:39
fruits  blueberry   2   30-10-2017 06:42
fruits  blueberry   0   30-10-2017 06:45
fruits  blueberry   0   30-10-2017 06:48
fruits  blueberry   0   30-10-2017 06:51
fruits  blueberry   0   30-10-2017 06:54
fruits  blueberry   0   30-10-2017 06:57
fruits  guaua   1   30-10-2017 06:00
fruits  guaua   1   30-10-2017 06:03
fruits  guaua   1   30-10-2017 06:06
fruits  guaua   2   30-10-2017 06:09
fruits  guaua   1   30-10-2017 06:12
fruits  guaua   1   30-10-2017 06:15
fruits  guaua   1   30-10-2017 06:18
fruits  guaua   1   30-10-2017 06:21
fruits  guaua   1   30-10-2017 06:24
fruits  guaua   1   30-10-2017 06:27
fruits  guaua   1   30-10-2017 06:30
fruits  guaua   1   30-10-2017 06:33
fruits  guaua   1   30-10-2017 06:36
fruits  guaua   1   30-10-2017 06:39
fruits  guaua   2   30-10-2017 06:42
fruits  guaua   1   30-10-2017 06:45
fruits  guaua   1   30-10-2017 06:48
fruits  guaua   1   30-10-2017 06:51
fruits  guaua   1   30-10-2017 06:54
fruits  guaua   1   30-10-2017 06:57

I'm trying get min, max time of each status for cat and subcat status.

Output result should be following:

cat     subcat      status  mintime maxtime
fruits  apple       0   30-10-2017 06:00    30-10-2017 06:57
fruits  strawberry  1   30-10-2017 06:00    30-10-2017 06:06
fruits  strawberry  2   30-10-2017 06:09    30-10-2017 06:09
fruits  strawberry  1   30-10-2017 06:12    30-10-2017 06:39
fruits  strawberry  2   30-10-2017 06:42    30-10-2017 06:42
fruits  strawberry  1   30-10-2017 06:45    30-10-2017 06:57
fruits  blueberry   0   30-10-2017 06:00    30-10-2017 06:06
fruits  blueberry   2   30-10-2017 06:09    30-10-2017 06:09
fruits  blueberry   0   30-10-2017 06:12    30-10-2017 06:39
fruits  blueberry   2   30-10-2017 06:42    30-10-2017 06:42
fruits  blueberry   0   30-10-2017 06:45    30-10-2017 06:57
fruits  guaua       1   30-10-2017 06:00    30-10-2017 06:06
fruits  guaua       2   30-10-2017 06:09    30-10-2017 06:09
fruits  guaua       1   30-10-2017 06:12    30-10-2017 06:39
fruits  guaua       2   30-10-2017 06:42    30-10-2017 06:42
fruits  guaua       1   30-10-2017 06:45    30-10-2017 06:57

tried with following sql query but unable to get above output instead its giving min, max total hour.

SELECT cat,
        subcat,
        status,
        min(logtime) as minlog,
        max(logtime) as maxlog
FROM fruits_log
WHERE
    cat = 'fruits'
    AND date_format(logtime,'%Y-%m-%d %H) = '2017-10-30 06'
    AND status IN ('0','1','2')
GROUP BY cat,subcat,date_format(logtime,'%Y-%m-%d %H),status
ORDER BY cat,subcat,minlog ;

Please help what i'm missing in above query

Body:
You may try something like this

select  t.cat, t.subcat, t.status, min(t.logdate), max(t.logdate)
from
(
    select t1.cat, t1.subcat, t1.status, t1.logdate, count(t2.cat) grpnum
    from data t1
    left join data t2 on t1.cat = t2.cat and t1.subcat = t2.subcat and
                         t1.status != t2.status and
                         t1.logdate < t2.logdate
    group by t1.cat, t1.subcat, t1.status, t1.logdate
) t
group by t.cat, t.subcat, t.status, t.grpnum

I have tested on just very small sample of your data, but it seems to be ok. The inner query use a self-join to isolate consecutive rows with the same cat, subcat and status values. Once this is ready, you can simply do a group by for each group of rows in the data.


问:
What is "metrics" in Keras?
It is not yet clear for me what metrics are (as given in the code below). What exactly are they evaluating? Why do we need to define them in the model? Why we can have multiple metrics in one model? And more importantly what is the mechanics behind all this?
Any scientific reference is also appreciated.

model.compile(loss='mean_squared_error',
              optimizer='sgd',
              metrics=['mae', 'acc'])
```

答:
So in order to understand what metrics are, it's good to start by understanding what a loss function is. Neural networks are mostly trained using gradient methods by an iterative process of decreasing a loss function.

A loss is designed to have two crucial properties - first, the smaller its value is, the better your model fits your data, and second, it should be differentiable. So, knowing this, we could fully define what a metric is: it's a function that, given predicted values and ground truth values from examples, provides you with a scalar measure of a "fitness" of your model, to the data you have. So, as you may see, a loss function is a metric, but the opposite doesn't always hold. To understand these differences, let's look at the most common examples of metrics usage:

Measure a performance of your network using non-differentiable functions: e.g. accuracy is not differentiable (not even continuous) so you cannot directly optimize your network w.r.t. to it. However, you could use it in order to choose the model with the best accuracy.

Obtain values of different loss functions when your final loss is a combination of a few of them: Let's assume that your loss has a regularization term which measures how your weights differ from 0, and a term which measures the fitness of your model. In this case, you could use metrics in order to have a separate track of how the fitness of your model changes across epochs.

Track a measure with respect to which you don't want to directly optimize your model: so - let's assume that you are solving a multidimensional regression problem where you are mostly concerned about mse, but at the same time you are interested in how a cosine-distance of your solution is changing in time. Then, it's the best to use metrics.

I hope that the explanation presented above made obvious what metrics are used for, and why you could use multiple metrics in one model. So now, let's say a few words about mechanics of their usage in keras. There are two ways of computing them while training:

Using metrics defined while compilation: this is what you directly asked. In this case, keras is defining a separate tensor for each metric you defined, to have it computed while training. This usually makes computation faster, but this comes at a cost of additional compilations, and the fact that metrics should be defined in terms of keras.backend functions.

Using keras.callback: It is nice that you can use Callbacks in order to compute your metrics. As each callback has a default attribute of model, you could compute a variety of metrics using model.predict or model parameters while training. Moreover, it makes it possible to compute it, not only epoch-wise, but also batch-wise, or training-wise. This comes at a cost of slower computations, and more complicated logic - as you need to define metrics on your own.

Here you can find a list of available metrics, as well as an example on how you could define your own.

Title: What is "metrics" in Keras?


问:
How to find the "href" of the last <tr> element?
ImageI am trying to get the "href" of a particular frame which you can find in the image , i tried as much as i can but i am not able to get the "href"  </p>

```<code>List<WebElement> list=d.findElements(By.xpath("html/body/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td/form/table/tbody/tr[52]/td"));

                   for(WebElement e : list){
                       String link = e.getAttribute("href");
                      System.out.println(link);
</code>```

<p>I tried the above code , i took the Xpath of that frame and tried to get the href of that frame . Link: "https://iaeme.com/ijciet/issues.asp?VType=8&IType=10&JType=IJCIET&PageNumber=1" </p>

答:
As per the xpath you shared to get all the "href" attributes you can use the following code block :

```<code>List<WebElement> list = d.findElements(By.xpath("//form[@name='form1']/table/tbody/tr[last()]/td/a"));
    for(WebElement e : list)
        System.out.println(e.getAttribute("href"));
</code>```

Body:
ImageI am trying to get the "href" of a particular frame which you can find in the image , i tried as much as i can but i am not able to get the "href"

List<WebElement> list=d.findElements(By.xpath("html/body/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td/form/table/tbody/tr[52]/td"));

                   for(WebElement e : list){
                       String link = e.getAttribute("href");
                      System.out.println(link);

I tried the above code , i took the Xpath of that frame and tried to get the href of that frame . Link: "https://iaeme.com/ijciet/issues.asp?VType=8&IType=10&JType=IJCIET&PageNumber=1"

Body:
As per the xpath you shared to get all the "href" attributes you can use the following code block :

List<WebElement> list = d.findElements(By.xpath("//form[@name='form1']/table/tbody/tr[last()]/td/a"));
    for(WebElement e : list)
        System.out.println(e.getAttribute("href"));


问:
How to disable/ prevent browser reload icon for a page using javascript?
Browser reload icon functionality should be disabled for a particular page.Even though if it reloads also,the page content should not change.</p>

答:
You can disable refresh by using the following code

```<code> $(document).on("keydown", function (e) {
        if (e.key == "F5" || e.key == "F11" ||
            (e.ctrlKey == true && (e.key == 'r' || e.key == 'R')) ||
            e.keyCode == 116 || e.keyCode == 82) {

                   e.preventDefault();
        }
    });
</code>```

Even after this the user can refresh using browser refresh button. If so we can just give a confirmation message using

```<code>window.onbeforeunload = function() {
        return "Leave this page ?";
    }
</code>```

Body:
You can disable refresh by using the following code

 $(document).on("keydown", function (e) {
        if (e.key == "F5" || e.key == "F11" ||
            (e.ctrlKey == true && (e.key == 'r' || e.key == 'R')) ||
            e.keyCode == 116 || e.keyCode == 82) {

                   e.preventDefault();
        }
    });

Even after this the user can refresh using browser refresh button. If so we can just give a confirmation message using

window.onbeforeunload = function() {
        return "Leave this page ?";
    }


问:
Excel VBA: Loop IF statement through two columns
I have a client list with various information. Column C shows inception date, Column Q shows Status.

I need to loop an IF statement through Column C that checks todays date() and if the clients corresponding status is 100%. Then adds 1 year to the date in column C if true.

```<code>Private Sub Workbook_Open()
    Dim ID As Date
    Dim Status As Long

    ID = Sheets("Kunder").Range("C" & Rows.Count).End(xlUp).Row

    If ID>= Date And Status = 1 Then
    ID.Value = ID.Value + 365
    End If

    End Sub
</code>```

Thank you very much :-)

答:
Date in excel is just number. So,

```<code>Dim ID as Double
</code>```

To loop through all cell in column C

```<code>Dim cl As Range

With Sheets("Kunder")
    For Each cl In Intersect(.Range("C:C"), .UsedRange)
        If cl.Value = ID And cl.Offset(, 14).Value = 1 Then
             cl.Value = cl.Value + 365
        End If
    Next cl
End With
</code>```

But, remember about leap years, they have 366 days.
 cl.Offset(, 14) is Q column, remember about it when inserting/deleting columns.

Body:
I have a client list with various information. Column C shows inception date, Column Q shows Status.

I need to loop an IF statement through Column C that checks todays date() and if the clients corresponding status is 100%. Then adds 1 year to the date in column C if true.

Private Sub Workbook_Open()
    Dim ID As Date
    Dim Status As Long

    ID = Sheets("Kunder").Range("C" & Rows.Count).End(xlUp).Row

    If ID>= Date And Status = 1 Then
    ID.Value = ID.Value + 365
    End If

    End Sub

Thank you very much :-)

Body:
Date in excel is just number. So,

Dim ID as Double

To loop through all cell in column C

Dim cl As Range

With Sheets("Kunder")
    For Each cl In Intersect(.Range("C:C"), .UsedRange)
        If cl.Value = ID And cl.Offset(, 14).Value = 1 Then
             cl.Value = cl.Value + 365
        End If
    Next cl
End With

But, remember about leap years, they have 366 days.
 cl.Offset(, 14) is Q column, remember about it when inserting/deleting columns.


问:
Fill listview with database table in C#
Im trying to fill listView1 with the first table of my database. But it is not working, can someone help me?

The function LoadList is not recognizing the DataTable DT

Here is the code I am using

```<code>namespace Project.Data_Layer
{
    class Leerling
    {
        public static DataTable ExecSelect(string Leerling)
        {
            DataSet DS = new DataSet();
            SqlDataAdapter DA;
            DA = new SqlDataAdapter(Leerling, SQLString.Conn);
            DS.Clear();
            DA.Fill(DS);
            // 1e tabel uit database
            DataTable DT = DS.Tables[0];
            return DT;
        }

        public static bool ExecOverig(string Leerling)
        {
            bool gelukt = true;
            SqlConnection Connect = new SqlConnection(SQLString.Conn);
            SqlCommand Cmd = new SqlCommand(Leerling, Connect);
            try
            {
                Cmd.Connection.Open();
                Cmd.ExecuteNonQuery();
                Connect.Close();
            }
            catch
            {
                gelukt = false;
            }
            return gelukt;
        }

        public void LoadList()
        {
            if(DT.tables.count > 0)
            {
                listView1.DataSource = DT;
                listView1.DataBind();
            }
            else
            {
                //
            }
        }
    }
}
</code>```

答:
Declare the DataTable variable DT outside of method 'ExecSelect'</p>

```<code>DataTable DT = new DataTable();
public static DataTable ExecSelect(string Leerling)
    {
        DataSet DS = new DataSet();
        SqlDataAdapter DA;
        DA = new SqlDataAdapter(Leerling, SQLString.Conn);
        DS.Clear();
        DA.Fill(DS);
        // 1e tabel uit database
        DT = DS.Tables[0];
        return DT;
    }
</code>```

Title: Fill listview with database table in C#

Body:
Im trying to fill listView1 with the first table of my database. But it is not working, can someone help me?

The function LoadList is not recognizing the DataTable DT

Here is the code I am using

namespace Project.Data_Layer
{
    class Leerling
    {
        public static DataTable ExecSelect(string Leerling)
        {
            DataSet DS = new DataSet();
            SqlDataAdapter DA;
            DA = new SqlDataAdapter(Leerling, SQLString.Conn);
            DS.Clear();
            DA.Fill(DS);
            // 1e tabel uit database
            DataTable DT = DS.Tables[0];
            return DT;
        }

        public static bool ExecOverig(string Leerling)
        {
            bool gelukt = true;
            SqlConnection Connect = new SqlConnection(SQLString.Conn);
            SqlCommand Cmd = new SqlCommand(Leerling, Connect);
            try
            {
                Cmd.Connection.Open();
                Cmd.ExecuteNonQuery();
                Connect.Close();
            }
            catch
            {
                gelukt = false;
            }
            return gelukt;
        }

        public void LoadList()
        {
            if(DT.tables.count > 0)
            {
                listView1.DataSource = DT;
                listView1.DataBind();
            }
            else
            {
                //
            }
        }
    }
}

Body:
Declare the DataTable variable DT outside of method 'ExecSelect'

DataTable DT = new DataTable();
public static DataTable ExecSelect(string Leerling)
    {
        DataSet DS = new DataSet();
        SqlDataAdapter DA;
        DA = new SqlDataAdapter(Leerling, SQLString.Conn);
        DS.Clear();
        DA.Fill(DS);
        // 1e tabel uit database
        DT = DS.Tables[0];
        return DT;
    }


问:
Why does <!DOCTYPE html> break height: 100%?
This code works:

```<code><html>
  <head>
    <style>#a { height: 100%; }</style>
  </head>
  <body>
   <form>
     <textarea id="a"></textarea>
   </form>
  </body>
</html>
</code>```

and produces a 100% height textarea.

If we add <!DOCTYPE html> on top, it doesn't work anymore (the height isn't 100% anymore).

Why? According to here, it seems that adding this DOCTYPE is making it HTML5. Why would HTML5 break the height: 100%;?

答:
When you use of <!DOCTYPE html>,you are in standard mode and html and body have height equal his inside content,so you must use this code:

```<code>html, body, form, #a {
   height:100%;
}
</code>```

but when you don't use of DOCTYPE you are in  quirks mode and , html and body have default height equal 100%,only use this code:

```<code>#a {
   height:100%;
}
</code>```

Body:
This code works:

   <form>
     <textarea id="a"></textarea>
   </form>

and produces a 100% height textarea.

If we add <!DOCTYPE html> on top, it doesn't work anymore (the height isn't 100% anymore).

Why? According to here, it seems that adding this DOCTYPE is making it HTML5. Why would HTML5 break the height: 100%;?

Body:
When you use of <!DOCTYPE html>,you are in standard mode and html and body have height equal his inside content,so you must use this code:

html, body, form, #a {
   height:100%;
}

but when you don't use of DOCTYPE you are in  quirks mode and , html and body have default height equal 100%,only use this code:

#a {
   height:100%;
}


问:
How can I convert array of bytes to a string in PHP?
I have an array of bytes that I'd like to map to their ASCII equivalents.

How can I do this?

答:
Ammending the answer by mario for using pack():
Since PHP 5.5, you can use Argument unpacking via ...

```<code>$str = pack('C*', ...$bytes);
</code>```

The other functions are fine to use, but it is preferred to have readable code.

Body:
Ammending the answer by mario for using pack():
Since PHP 5.5, you can use Argument unpacking via ...

$str = pack('C*', ...$bytes);

The other functions are fine to use, but it is preferred to have readable code.


问:
How to vertically center an  with CSS and NOT overlap a text?
I'm trying to put a logo in my forum, but neither the engine nor the template I use support this. So I decided to give it a try and put it. It seems so simple, but it's not.

I've tried at least 5 ways I found in the net (mostly from StackOverflow), but they either do not work at all (image not centered vertically) or solve the problem only partially as the image overlaps a text following it.

The only solution which worked in terms of vertical-centering is based on position: absolute and margin: auto

```<code><img src="/EL3232.png" width="32" height="32" style="
        float: left;
        position: absolute;
        top:0;
        bottom:0;
        margin:auto;
">
</code>```

It has however a side effect: the image overlaps the forum title text.

The HTML is quite complex I would say and its simplification for the post is not easy (a lot of CSS for each preceding element), so I think I will just pass the link to my website, so you knew what I mean:
http://www.forumextalife.pl/

It's basically a hierarchy like this:

 ->  ->
 ->
 -> . I want to put an  containig the logo inside this  tag.
To be exact - the  element in the website is: class="navbar-brand">

I hope you guys can solve it. I've never thought this is gonna be so complicated to have simply an image centered vertically and not overlapping text.

答:
The cleanest approach is probably to set the image as a background image of .navbar-brand, with a bit of padding and/or line height so that the title aligns appropriately alongside it. Something like this...

```<code>.navbar-brand {
   background:url(/EL3232.png) left center no-repeat;
   display:inline-block;
   padding-left:40px;
   height:32px;
   line-height:32px;
}
</code>```

Keep responsive design in mind, though - I see your title already is limited at mobile sizes.

Title: How to vertically center an <img> with CSS and NOT overlap a text?

Body:
I'm trying to put a logo in my forum, but neither the engine nor the template I use support this. So I decided to give it a try and put it. It seems so simple, but it's not.

I've tried at least 5 ways I found in the net (mostly from StackOverflow), but they either do not work at all (image not centered vertically) or solve the problem only partially as the image overlaps a text following it.

The only solution which worked in terms of vertical-centering is based on position: absolute and margin: auto

It has however a side effect: the image overlaps the forum title text.

The HTML is quite complex I would say and its simplification for the post is not easy (a lot of CSS for each preceding element), so I think I will just pass the link to my website, so you knew what I mean:
http://www.forumextalife.pl/

It's basically a hierarchy like this:

 ->  ->
 ->
 -> . I want to put an  containig the logo inside this  tag.
To be exact - the  element in the website is:

I hope you guys can solve it. I've never thought this is gonna be so complicated to have simply an image centered vertically and not overlapping text.

Body:
The cleanest approach is probably to set the image as a background image of .navbar-brand, with a bit of padding and/or line height so that the title aligns appropriately alongside it. Something like this...

.navbar-brand {
   background:url(/EL3232.png) left center no-repeat;
   display:inline-block;
   padding-left:40px;
   height:32px;
   line-height:32px;
}

Keep responsive design in mind, though - I see your title already is limited at mobile sizes.


问:
Pypark read CSV with 60516 columns taking longer time
The CSV file size is 130 MB but just reading and caching the file takes more than 5 minutes. I have set Inferschema as False and also it is taking much time. I tried with increasing cores, nodes , memory but no use. Any suggestions, please ?</p>

答:
Unfortunately, this is somewhat expected behavior or rather known weak side of Apache Spark. Structured API (Spark SQL / Dataset) scales poorly (depending on the context and version complexity might grow even exponentially) in terms of number of fields used for the query. Luckily this is constant overhead (doesn't depend on the number of rows).

If you work with very wide data, and require low latency, it might be wise to skip Spark SQL, and go back to RDD API.


问:
Remember me cookie is not showing after browser is closed and reopened?
I have trying to add a remember me function in my web application. This is the configurations I made with Spring.

```<code>..........
    .rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
                .tokenValiditySeconds(86400).and().csrf().and().exceptionHandling().accessDeniedPage("/access_denied");
............

@Bean
public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
    PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
            "remember-me", userDetailsService, tokenRepository);
    return tokenBasedservice;
}
</code>```

Once I logged into the application and checked for the cookies I see remember-me cookie as below which is to be expired tomorrow.

But once I closed the browser and opened again I'm logged out of the application and when checking for the cookie , remember-me cookie is not shown as well.

So I want to know

Is this the normal behavior of remember me functionality?

Am I able to keep logged until the remember-me cookie expires?

Why do the remember-me cookie disappears when the browser is reopened?

edit:
This is the browser settings for cookies

Firefox configuration:

答:
You have to turn off Keep local data only until you quit your browser to keep your cookies, see Google Chrome Help:

Delete cookies after you close Chrome

You can let sites remember information during your browsing session, but automatically delete the cookies when you quit Chrome.

On your computer, open Google Chrome.

At the top right, click More More and then Settings.

At the bottom, click Advanced.

Under "Privacy and security," click Content settings.

Click Cookies.

Turn on Keep local data only until you quit your browser.

Body:
I have trying to add a remember me function in my web application. This is the configurations I made with Spring.

..........
    .rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
                .tokenValiditySeconds(86400).and().csrf().and().exceptionHandling().accessDeniedPage("/access_denied");
............

@Bean
public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
    PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
            "remember-me", userDetailsService, tokenRepository);
    return tokenBasedservice;
}

Once I logged into the application and checked for the cookies I see remember-me cookie as below which is to be expired tomorrow.

But once I closed the browser and opened again I'm logged out of the application and when checking for the cookie , remember-me cookie is not shown as well.

So I want to know

Is this the normal behavior of remember me functionality?

Am I able to keep logged until the remember-me cookie expires?

Why do the remember-me cookie disappears when the browser is reopened?

edit:
This is the browser settings for cookies

Firefox configuration:


问:
ServiceLocatorImplBase.cs not found when using StructureMap
I get the following error when debugging (F5) my code in Visual Studio (2017):

ServiceLocatorImplBase.cs not found

Reading the detail, it seems to be looking for a file on my computer in the following place:

'c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs'

I don't have a directory 'c:\Home\Chris...' and I have no idea why it would be looking there.

How can I fix this?

答:
(Answering own question)

I spent days looking for an answer.

I noticed that I started getting the issue after I had installed StructureMap. I managed to solve it with the help of this explanation.

In short, I had to install CommonServiceLocator v2.0.1. using NuGet. Once I did that I then had to update this file:

StructureMapDependencyScope.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
//using Microsoft.Practices.ServiceLocation
using StructureMap;
using CommonServiceLocator;

namespace UI.DependencyResolution
{
    /// <summary>
    /// The structure map dependency scope.
    /// </summary>
    public class StructureMapDependencyScope : ServiceLocatorImplBase, IDependencyScope
    {
</code>```

I added a reference to CommonServiceLocator and removed the reference to Microsoft.Practices.ServiceLocation.

This removed the hard dependency on c:\Home\Chris....

Hope that helps others.

Body:
(Answering own question)

I spent days looking for an answer.

I noticed that I started getting the issue after I had installed StructureMap. I managed to solve it with the help of this explanation.

In short, I had to install CommonServiceLocator v2.0.1. using NuGet. Once I did that I then had to update this file:

StructureMapDependencyScope.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;
//using Microsoft.Practices.ServiceLocation
using StructureMap;
using CommonServiceLocator;

namespace UI.DependencyResolution
{
    /// <summary>
    /// The structure map dependency scope.
    /// </summary>
    public class StructureMapDependencyScope : ServiceLocatorImplBase, IDependencyScope
    {

I added a reference to CommonServiceLocator and removed the reference to Microsoft.Practices.ServiceLocation.

This removed the hard dependency on c:\Home\Chris....

Hope that helps others.


问:
AWS Lambda - Create Thumbnail
I am using AWS Lambda for creating resized thumbnails. The source is an S3 bucket and the destination is another S3 bucket. I was able to create the lambda function from Amazon CLI. The function is triggered whenever a new image is added to the source bucket. But, the resize/thumbnail creation is not working. I can see some issue in the CloudWatch Console.

The content of the uploaded ZIP package is:

CreateThumbnail.js, node_modules

```<code>Unable to import module 'CreateThumbnail': Error
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/task/CreateThumbnail.js:2:13)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
</code>```

Best regards,
BP

答:
Finally able to find the source of the bug. The command used to make the zip file was causing the issue.

The correct command is:
    zip -r CreateThumbnail.zip *

Title: AWS Lambda - Create Thumbnail

Body:
I am using AWS Lambda for creating resized thumbnails. The source is an S3 bucket and the destination is another S3 bucket. I was able to create the lambda function from Amazon CLI. The function is triggered whenever a new image is added to the source bucket. But, the resize/thumbnail creation is not working. I can see some issue in the CloudWatch Console.

The content of the uploaded ZIP package is:

CreateThumbnail.js, node_modules

Unable to import module 'CreateThumbnail': Error
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/task/CreateThumbnail.js:2:13)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)

Best regards,
BP


问:
What can be used instead of tooltip in iphone app?
What can be used instead of tooltip in iphone app?

Best alternative of tooltip in touch screen systems?

答:
Tooltips are generally reserved for operating systems that have a cursor. In touchscreen applications, tooltips should not be needed at all. When your application is in use, the user should always know where the menus are, what all of the buttons do, etc, simply because they have been labeled clearly with a text explanation or an image.

If you need the use of tooltips in your application, you need to rethink your design.

Be Succinct.