答:
Assuming you're attempting to break the string in your code, not the output, you can use a template literal by delimiting the string with `:

```<code>$('.ContText-1').text(`
  For a business to thrive, it needs a team of people who are dedicated to its
  success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of
  that team for each of their clients.
`);
</code>```

Note that this is completely unsupported in any version of IE, although works in every other modern browser - even Edge.

Alternatively you can append each line separately:

```<code>$('.ContText-1').text(
  'For a business to thrive, it needs a team of people who are dedicated to its ' +
  'success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of ' +
  'that team for each of their clients.'
);
</code>```

Title: JQuery .text() Multi-Line

Body:
Assuming you're attempting to break the string in your code, not the output, you can use a template literal by delimiting the string with `:

$('.ContText-1').text(`
  For a business to thrive, it needs a team of people who are dedicated to its
  success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of
  that team for each of their clients.
`);

Note that this is completely unsupported in any version of IE, although works in every other modern browser - even Edge.

Alternatively you can append each line separately:

$('.ContText-1').text(
  'For a business to thrive, it needs a team of people who are dedicated to its ' +
  'success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of ' +
  'that team for each of their clients.'
);


来源: stackexchange

问:
Adding selected Items to collection
I am trying to write selected values in a listbox inside a collection.

I get an error in this line - SelectedEnt.Add ItemReq, Key

Here is my complete code,

```<code>Sub YesFormDataSubmit()
    Dim SelectedEnt As Collection
    Dim Key As Variant

    Set SelectedEnt = New Collection
    Key = 0

    For lItem = 0 To Sheets("Main").Ent_ListBox.ListCount - 1
        If Sheets("Main").Ent_ListBox.Selected(lItem) = True Then
            ItemReq = Sheets("Main").Ent_ListBox.List(lItem)
            If ItemReq <> "" Then
                Key= Key + 1
                SelectedEnt.Add ItemReq, Key
            End If
        End If
    Next

End Sub
</code>```

答:
Your error because of that Key must be String.</p>

```<code>Sub YesFormDataSubmit()
    Dim SelectedEnt As Collection
    Dim Key As Variant

    Set SelectedEnt = New Collection
    Key = 0

    For lItem = 0 To Sheets("Main").Ent_ListBox.ListCount - 1
        If Sheets("Main").Ent_ListBox.Selected(lItem) = True Then
            ItemReq = Sheets("Main").Ent_ListBox.list(lItem)
            If ItemReq <> "" Then
                Key = Key + 1
               'key must be string
                SelectedEnt.Add ItemReq, CStr(Key)
            End If
        End If
    Next

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: Adding selected Items to collection

Body:
I am trying to write selected values in a listbox inside a collection.

I get an error in this line - SelectedEnt.Add ItemReq, Key

Here is my complete code,

Sub YesFormDataSubmit()
    Dim SelectedEnt As Collection
    Dim Key As Variant

    Set SelectedEnt = New Collection
    Key = 0

    For lItem = 0 To Sheets("Main").Ent_ListBox.ListCount - 1
        If Sheets("Main").Ent_ListBox.Selected(lItem) = True Then
            ItemReq = Sheets("Main").Ent_ListBox.List(lItem)
            If ItemReq <> "" Then
                Key= Key + 1
                SelectedEnt.Add ItemReq, Key
            End If
        End If
    Next

End Sub

Body:
Your error because of that Key must be String.

Sub YesFormDataSubmit()
    Dim SelectedEnt As Collection
    Dim Key As Variant

    Set SelectedEnt = New Collection
    Key = 0

    For lItem = 0 To Sheets("Main").Ent_ListBox.ListCount - 1
        If Sheets("Main").Ent_ListBox.Selected(lItem) = True Then
            ItemReq = Sheets("Main").Ent_ListBox.list(lItem)
            If ItemReq <> "" Then
                Key = Key + 1
               'key must be string
                SelectedEnt.Add ItemReq, CStr(Key)
            End If
        End If
    Next

End Sub


问:
how to add confirmation fields to mysql table creation
I am following a tutorial on how to make table with mysql for android studio app
this is the code to create table

```<code>create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
</code>```

but the form in this tutorial only has:

```<code>name
email
password
</code>```

while my form has:

```<code>email
confirm email
name
password
confirm password
referral code
</code>```

how do i add the confirmation fields,e.g confirm password fields to mysql create table

答:
On Account creation:

Validate the fields

Comapre the password and confirmation fields

Run the password through a password derivation function such as password_hash/password_verify, PBKDF2 or Bcrypt depending on the language you are using.

Put the password derivation in the password field of the DB

On login:

Retrive the account information from the DB using the userID, (name?)

if using password_hash/password_verify

Call password_verify withthe presented password and the password value from the DB

else

Run the password through the password derivation function used above

Compare the derived password to the value in the DB

Note: Do not add a confirm password or confirm email field to the DB, just use them to verify the submission.

ContentLicense: CC BY-SA 3.0

Body:
I am following a tutorial on how to make table with mysql for android studio app
this is the code to create table

create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);

but the form in this tutorial only has:

name
email
password

while my form has:

email
confirm email
name
password
confirm password
referral code

how do i add the confirmation fields,e.g confirm password fields to mysql create table


问:
How to implement type declaration with generics?
How can I define a function which is an implementation of a type declaration that includes generics?

Here's what I mean:

```<code>abstract class Base {}
class Sub extends Base {}

declare type BaseFactory = <T extends Base>() => T;
let subFactory: BaseFactory = <Sub>():Sub => new Sub();

console.debug(subFactory()); // expect instance of Sub
</code>```

Unfortunately, this produces the following error:

Sub is not assignable to parameter of type Base

Can this be done?

/edit nevermind, it actually works in Playground. Guess it's a compiler version issue

答:
This works:

```<code>declare type BaseFactory = <T extends Base>() => T;
let subFactory: BaseFactory = (): Sub => new Sub();

let a = subFactory<Sub>(); // type of a is Sub
</code>```

(code in playground)

But I'd do it like this:

```<code>declare type BaseFactory<T extends Base> = () => T;
let subFactory: BaseFactory<Sub> = (): Sub => new Sub();

let a = subFactory(); // type of a is Sub
</code>```

(code in playground)

Edit

If you're using typescript >= 2.3 then you can use default generics:

```<code>declare type BaseFactory<T extends Base = Base> = () => T;
</code>```

And then you don't need to specify T everywhere.

Body:
How can I define a function which is an implementation of a type declaration that includes generics?

Here's what I mean:

abstract class Base {}
class Sub extends Base {}

declare type BaseFactory = <T extends Base>() => T;
let subFactory: BaseFactory = ():Sub => new Sub();

console.debug(subFactory()); // expect instance of Sub

Unfortunately, this produces the following error:

Sub is not assignable to parameter of type Base

Can this be done?

/edit nevermind, it actually works in Playground. Guess it's a compiler version issue

Body:
This works:

declare type BaseFactory = <T extends Base>() => T;
let subFactory: BaseFactory = (): Sub => new Sub();

let a = subFactory<Sub>(); // type of a is Sub

(code in playground)

But I'd do it like this:

declare type BaseFactory<T extends Base> = () => T;
let subFactory: BaseFactory<Sub> = (): Sub => new Sub();

let a = subFactory(); // type of a is Sub

(code in playground)

Edit

If you're using typescript >= 2.3 then you can use default generics:

declare type BaseFactory<T extends Base = Base> = () => T;

And then you don't need to specify T everywhere.


问:
Using RecyclerView with DataBase
```<code>public class Contact {

// id
int mNumber;

String  mMonth,mDate, mDay, mTime , mTitle , mContent;
int mMood,mWeather;

public Contact(){}

public Contact(int number, String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mNumber=number; mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}

public Contact(String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}
public Contact(String month, String date, String day, String time, String title, String content) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content;
}

public int getmNumber() {
    return mNumber;
}

public void setmNumber(int mNumber) {
    this.mNumber = mNumber;
}

public String getmMonth() {
    return mMonth;
}

public void setmMonth(String mMonth) {
    this.mMonth = mMonth;
}

public String getmDate() {
    return mDate;
}

public void setmDate(String mDate) {
    this.mDate = mDate;
}

public String getmDay() {
    return mDay;
}

public void setmDay(String mDay) {
    this.mDay = mDay;
}

public String getmTime() {
    return mTime;
}

public void setmTime(String mTime) {
    this.mTime = mTime;
}

public String getmTitle() {
    return mTitle;
}

public void setmTitle(String mTitle) {
    this.mTitle = mTitle;
}

public String getmContent() {
    return mContent;
}

public void setmContent(String mContent) {
    this.mContent = mContent;
}

public int getmMood() {
    return mMood;
}

public void setmMood(int mMood) {
    this.mMood = mMood;
}

public int getmWeather() {
    return mWeather;
}

public void setmWeather(int mWeather) {
    this.mWeather = mWeather;
}
}
</code>```

Contact class is use to save value

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

public static final String DATABASE_NAME = "Calendar.db";

//Table Name
public static final String D_TABLE_NAME = "Diary";

public static final String D_COL_1 = "m_Number";  //id
public static final String D_COL_2 = "m_Title";
public static final String D_COL_3 = "m_Content";
public static final String D_COL_4 = "m_Month";
public static final String D_COL_5 = "m_Date";
public static final String D_COL_6 = "m_Day";
public static final String D_COL_7 = "m_Time";
public static final String D_COL_8 = "m_Mood";    //image
public static final String D_COL_9 = "m_Weather"; //image

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE "+D_TABLE_NAME+"("+D_COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT, "+D_COL_2+" TEXT, "+D_COL_3+" TEXT, "+D_COL_4+" TEXT, "
                +D_COL_5+" TEXT, "+D_COL_6+" TEXT, "+D_COL_7+ " TEXT, "+D_COL_8+" INTEGER, "+D_COL_9+" INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists"+TABLE_NAME);
    onCreate(db);
}

//Insert new Data
public void addContact(Contact contact){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(D_COL_2,contact.getmTitle());
    contentValues.put(D_COL_3,contact.getmContent());
    contentValues.put(D_COL_4,contact.getmMonth());
    contentValues.put(D_COL_5,contact.getmDate());
    contentValues.put(D_COL_6,contact.getmDay());
    contentValues.put(D_COL_7,contact.getmTime());
    contentValues.put(D_COL_8,contact.getmMood());
    contentValues.put(D_COL_9,contact.getmWeather());

    db.insert(D_TABLE_NAME,null,contentValues);
    db.close();

}   //

// mNumber to get Contact
public Contact getContact(int mNumber) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(D_TABLE_NAME, new String[] { D_COL_1,D_COL_2,D_COL_3,D_COL_4,D_COL_5,
                    D_COL_6,D_COL_7,D_COL_8,D_COL_9 }, D_COL_1 + "=?",
            new String[] { String.valueOf(mNumber) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),cursor.getString(6),
            Integer.parseInt(cursor.getString(7)),Integer.parseInt(cursor.getString(8)));
    return contact;
}

// All Contact information get
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + D_TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setmNumber(Integer.parseInt(cursor.getString(0)));
            contact.setmTitle(cursor.getString(1));
            contact.setmContent(cursor.getString(2));
            contact.setmMonth(cursor.getString(3));
            contact.setmDate(cursor.getString(4));
            contact.setmDay(cursor.getString(5));
            contact.setmTime(cursor.getString(6));
            contact.setmMood(Integer.parseInt(cursor.getString(7)));
            contact.setmWeather(Integer.parseInt(cursor.getString(8)));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    // return contact list
    Log.d("agent99", contactList.get(0).getmTitle().toString());

    return contactList;
}

public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(D_COL_2,contact.getmTitle());
    values.put(D_COL_3,contact.getmContent());
    values.put(D_COL_4,contact.getmMonth());
    values.put(D_COL_5,contact.getmDate());
    values.put(D_COL_6,contact.getmDay());
    values.put(D_COL_7,contact.getmTime());
    values.put(D_COL_8,contact.getmMood());
    values.put(D_COL_9,contact.getmWeather());

    // updating row
    return db.update(D_TABLE_NAME, values, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
}

// Contact information delete
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(D_TABLE_NAME, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
    db.close();
}

// Contact information number
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + D_TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();
    // return count
    return cursor.getCount();
}
}
</code>```

Recycler Adapter class DataManager

```<code>import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.codbking.calendar.Contact;
import com.codbking.calendar.DBHelper;
import com.codbking.calendar.exaple.R;
import java.util.List;

public class DataManager extends RecyclerView.Adapter<DataManager.RecyclerViewHolder> {
DBHelper dbHelper;
CursorAdapter mCursorAdapter;

List<Contact> contacts = dbHelper.getAllContacts();

public static class RecyclerViewHolder extends RecyclerView.ViewHolder {

    TextView mDate, mDay, mMonth, mTime, mTitle, mContent;
    ImageView mMood, mWeather;
    private Context context;

    RecyclerViewHolder(final View itemView) {
        super(itemView);
        context = itemView.getContext();
        mDate = (TextView) itemView.findViewById(R.id.TV_entries_item_date);
        mDay = (TextView) itemView.findViewById(R.id.TV_entries_item_day);
        mMonth = (TextView) itemView.findViewById(R.id.TV_entries_item_header);
        mTime = (TextView) itemView.findViewById(R.id.TV_entries_item_time);
        mTitle = (TextView) itemView.findViewById(R.id.TV_entries_item_title);
        mContent = (TextView) itemView.findViewById(R.id.TV_entries_item_summary);
        mMood = (ImageView) itemView.findViewById(R.id.IV_entries_item_weather);
        mWeather = (ImageView) itemView.findViewById(R.id.IV_entries_item_mood);

        itemView.setClickable(true);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(v.getContext(), MainActivity.class);
                context.startActivity(myIntent);
            }
        });
    }
}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.entries, viewGroup, false);
    return new RecyclerViewHolder(v);
}

@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
    // get the single element from the main array

    for (Contact cn : contacts) {
        viewHolder.mDate.setText(cn.getmDate());
        viewHolder.mDay.setText(cn.getmDay());
        viewHolder.mMonth.setText(cn.getmMonth());
        viewHolder.mTime.setText(cn.getmTime());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mMood.setImageResource(cn.getmMood());
        viewHolder.mWeather.setImageResource(cn.getmWeather());

    }

}
@Override
public int getItemCount(){
   return contacts.size();
}
}
</code>```

I don't know how to use RecyclerView with DataBase.
Error occur in DataManager Class (confidence)

Maybe Error occur in onBindViewHolder() Method or getItemCount() Method.
Previously I use RecyclerView without DataBase App run well... But when I use DataBase, App is just die so I surely die  onBindViewHolder() Method or getItemCount() Method in this code

答:
You are setting all data in a loop. That is not correct for recycler view. You can use the below code :</p>

```<code>@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
    Contact cn = contact.get(i);
    if (cn != null){
    viewHolder.mDate.setText(cn.getmDate());
    viewHolder.mDay.setText(cn.getmDay());
    viewHolder.mMonth.setText(cn.getmMonth());
    viewHolder.mTime.setText(cn.getmTime());
    viewHolder.mTitle.setText(cn.getmTitle());
    viewHolder.mContent.setText(cn.getmContent());
    viewHolder.mTitle.setText(cn.getmTitle());
    viewHolder.mContent.setText(cn.getmContent());
    viewHolder.mMood.setImageResource(cn.getmMood());
    viewHolder.mWeather.setImageResource(cn.getmWeather());
    }
  }
</code>```

Title: Using RecyclerView with DataBase

Body:
public class Contact {

// id
int mNumber;

String  mMonth,mDate, mDay, mTime , mTitle , mContent;
int mMood,mWeather;

public Contact(){}

public Contact(int number, String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mNumber=number; mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}

public Contact(String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}
public Contact(String month, String date, String day, String time, String title, String content) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content;
}

public int getmNumber() {
    return mNumber;
}

public void setmNumber(int mNumber) {
    this.mNumber = mNumber;
}

public String getmMonth() {
    return mMonth;
}

public void setmMonth(String mMonth) {
    this.mMonth = mMonth;
}

public String getmDate() {
    return mDate;
}

public void setmDate(String mDate) {
    this.mDate = mDate;
}

public String getmDay() {
    return mDay;
}

public void setmDay(String mDay) {
    this.mDay = mDay;
}

public String getmTime() {
    return mTime;
}

public void setmTime(String mTime) {
    this.mTime = mTime;
}

public String getmTitle() {
    return mTitle;
}

public void setmTitle(String mTitle) {
    this.mTitle = mTitle;
}

public String getmContent() {
    return mContent;
}

public void setmContent(String mContent) {
    this.mContent = mContent;
}

public int getmMood() {
    return mMood;
}

public void setmMood(int mMood) {
    this.mMood = mMood;
}

public int getmWeather() {
    return mWeather;
}

public void setmWeather(int mWeather) {
    this.mWeather = mWeather;
}
}

Contact class is use to save value

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "Calendar.db";

//Table Name
public static final String D_TABLE_NAME = "Diary";

public static final String D_COL_1 = "m_Number";  //id
public static final String D_COL_2 = "m_Title";
public static final String D_COL_3 = "m_Content";
public static final String D_COL_4 = "m_Month";
public static final String D_COL_5 = "m_Date";
public static final String D_COL_6 = "m_Day";
public static final String D_COL_7 = "m_Time";
public static final String D_COL_8 = "m_Mood";    //image
public static final String D_COL_9 = "m_Weather"; //image

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE "+D_TABLE_NAME+"("+D_COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT, "+D_COL_2+" TEXT, "+D_COL_3+" TEXT, "+D_COL_4+" TEXT, "
                +D_COL_5+" TEXT, "+D_COL_6+" TEXT, "+D_COL_7+ " TEXT, "+D_COL_8+" INTEGER, "+D_COL_9+" INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists"+TABLE_NAME);
    onCreate(db);
}

//Insert new Data
public void addContact(Contact contact){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(D_COL_2,contact.getmTitle());
    contentValues.put(D_COL_3,contact.getmContent());
    contentValues.put(D_COL_4,contact.getmMonth());
    contentValues.put(D_COL_5,contact.getmDate());
    contentValues.put(D_COL_6,contact.getmDay());
    contentValues.put(D_COL_7,contact.getmTime());
    contentValues.put(D_COL_8,contact.getmMood());
    contentValues.put(D_COL_9,contact.getmWeather());

    db.insert(D_TABLE_NAME,null,contentValues);
    db.close();

}   //

// mNumber to get Contact
public Contact getContact(int mNumber) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(D_TABLE_NAME, new String[] { D_COL_1,D_COL_2,D_COL_3,D_COL_4,D_COL_5,
                    D_COL_6,D_COL_7,D_COL_8,D_COL_9 }, D_COL_1 + "=?",
            new String[] { String.valueOf(mNumber) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),cursor.getString(6),
            Integer.parseInt(cursor.getString(7)),Integer.parseInt(cursor.getString(8)));
    return contact;
}

// All Contact information get
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + D_TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setmNumber(Integer.parseInt(cursor.getString(0)));
            contact.setmTitle(cursor.getString(1));
            contact.setmContent(cursor.getString(2));
            contact.setmMonth(cursor.getString(3));
            contact.setmDate(cursor.getString(4));
            contact.setmDay(cursor.getString(5));
            contact.setmTime(cursor.getString(6));
            contact.setmMood(Integer.parseInt(cursor.getString(7)));
            contact.setmWeather(Integer.parseInt(cursor.getString(8)));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    // return contact list
    Log.d("agent99", contactList.get(0).getmTitle().toString());

    return contactList;
}

public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(D_COL_2,contact.getmTitle());
    values.put(D_COL_3,contact.getmContent());
    values.put(D_COL_4,contact.getmMonth());
    values.put(D_COL_5,contact.getmDate());
    values.put(D_COL_6,contact.getmDay());
    values.put(D_COL_7,contact.getmTime());
    values.put(D_COL_8,contact.getmMood());
    values.put(D_COL_9,contact.getmWeather());

    // updating row
    return db.update(D_TABLE_NAME, values, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
}

// Contact information delete
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(D_TABLE_NAME, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
    db.close();
}

// Contact information number
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + D_TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();
    // return count
    return cursor.getCount();
}
}

Recycler Adapter class DataManager

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.codbking.calendar.Contact;
import com.codbking.calendar.DBHelper;
import com.codbking.calendar.exaple.R;
import java.util.List;

public class DataManager extends RecyclerView.Adapter<DataManager.RecyclerViewHolder> {
DBHelper dbHelper;
CursorAdapter mCursorAdapter;

List<Contact> contacts = dbHelper.getAllContacts();

public static class RecyclerViewHolder extends RecyclerView.ViewHolder {

    TextView mDate, mDay, mMonth, mTime, mTitle, mContent;
    ImageView mMood, mWeather;
    private Context context;

    RecyclerViewHolder(final View itemView) {
        super(itemView);
        context = itemView.getContext();
        mDate = (TextView) itemView.findViewById(R.id.TV_entries_item_date);
        mDay = (TextView) itemView.findViewById(R.id.TV_entries_item_day);
        mMonth = (TextView) itemView.findViewById(R.id.TV_entries_item_header);
        mTime = (TextView) itemView.findViewById(R.id.TV_entries_item_time);
        mTitle = (TextView) itemView.findViewById(R.id.TV_entries_item_title);
        mContent = (TextView) itemView.findViewById(R.id.TV_entries_item_summary);
        mMood = (ImageView) itemView.findViewById(R.id.IV_entries_item_weather);
        mWeather = (ImageView) itemView.findViewById(R.id.IV_entries_item_mood);

        itemView.setClickable(true);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(v.getContext(), MainActivity.class);
                context.startActivity(myIntent);
            }
        });
    }
}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.entries, viewGroup, false);
    return new RecyclerViewHolder(v);
}

@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
    // get the single element from the main array

    for (Contact cn : contacts) {
        viewHolder.mDate.setText(cn.getmDate());
        viewHolder.mDay.setText(cn.getmDay());
        viewHolder.mMonth.setText(cn.getmMonth());
        viewHolder.mTime.setText(cn.getmTime());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mMood.setImageResource(cn.getmMood());
        viewHolder.mWeather.setImageResource(cn.getmWeather());

    }

}
@Override
public int getItemCount(){
   return contacts.size();
}
}

I don't know how to use RecyclerView with DataBase.
Error occur in DataManager Class (confidence)

Maybe Error occur in onBindViewHolder() Method or getItemCount() Method.
Previously I use RecyclerView without DataBase App run well... But when I use DataBase, App is just die so I surely die  onBindViewHolder() Method or getItemCount() Method in this code

Body:
You are setting all data in a loop. That is not correct for recycler view. You can use the below code :

@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
    Contact cn = contact.get(i);
    if (cn != null){
    viewHolder.mDate.setText(cn.getmDate());
    viewHolder.mDay.setText(cn.getmDay());
    viewHolder.mMonth.setText(cn.getmMonth());
    viewHolder.mTime.setText(cn.getmTime());
    viewHolder.mTitle.setText(cn.getmTitle());
    viewHolder.mContent.setText(cn.getmContent());
    viewHolder.mTitle.setText(cn.getmTitle());
    viewHolder.mContent.setText(cn.getmContent());
    viewHolder.mMood.setImageResource(cn.getmMood());
    viewHolder.mWeather.setImageResource(cn.getmWeather());
    }
  }


答:
The key is not the index of a collection, consider:

```<code>Dim c as New Collection, i as Long
c.Add "David", "999"
c.Add "George", "14"

For i = 1 to c.Count
    Debug.Print c(i)
Next
</code>```

The key must also be a string type, which is why you're getting a mismatch error, passing a long/integer instead of a string.

Unless you are using that key value for something else, you can omit it entirely.You can call them by index without using the key at all.

Just do SelectedEnt.Add ItemReq.

The items will be added to the collection in order, and will be accessible by index e.g., SelectedEnt.Item(1), etc.

If you do need key for some other reason, then you must explicitly cast it to string:

SelectedEnt.Add ItemReq, CStr(Key)

Title: Adding selected Items to collection

Body:
The key is not the index of a collection, consider:

Dim c as New Collection, i as Long
c.Add "David", "999"
c.Add "George", "14"

For i = 1 to c.Count
    Debug.Print c(i)
Next

The key must also be a string type, which is why you're getting a mismatch error, passing a long/integer instead of a string.

Unless you are using that key value for something else, you can omit it entirely.You can call them by index without using the key at all.

Just do SelectedEnt.Add ItemReq.

The items will be added to the collection in order, and will be accessible by index e.g., SelectedEnt.Item(1), etc.

If you do need key for some other reason, then you must explicitly cast it to string:

SelectedEnt.Add ItemReq, CStr(Key)


问:
How to switch between hide and view password
Is there a clever way to let the user switch between hide and view password in an android EditText?
A number of PC based apps let the user do this.</p>

答:
```<code>if (inputPassword.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
 //password is visible
                inputPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
else if(inputPassword.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
 //password is hidden
                inputPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
</code>```


问:
Return Object of Class to Main Program
I am not so familiar with C++ and currently trying to code a class 'fraction'. I want to code a method 'Input' where a user gives values to a fraction. These values should be available throughout the program. This is what I have so far:

Call:

```<code>BRUCH t1;
   t1.Eingabe();
</code>```

Method:

```<code>    BRUCH BRUCH::Eingabe()
{
    int _z, _n;
    BRUCH bruch;
    cout << "Bitte einen Zaehlerwert eingeben: " << endl;
    cin >> _z;
    cout << "Bitte einen Nennerwert eingeben: " << endl;
    cin >> _n;
    while(_n==0)
    {
        cout << "Bitte einen gültigen Wert eingeben!" << endl;
        cin >> _n;
    }
    bruch.z = _z;
    bruch.n = _n;
    return bruch;
}
</code>```

When I return the object the values vanish and the constructor creates a new object with default values.

What must I do to get the correct return?

Bruch - Fraction (math.) | Eingabe - Input

答:
I solved the problem.

I changed the return bruch; to return *this; and removed the 'bruch' obj. from the code. The assignment is now z = _z, n = _n;. This returns the current object I am working with.

Sorry for any inconvenience.

Title: Return Object of Class to Main Program

Body:
I am not so familiar with C++ and currently trying to code a class 'fraction'. I want to code a method 'Input' where a user gives values to a fraction. These values should be available throughout the program. This is what I have so far:

Call:

BRUCH t1;
   t1.Eingabe();

Method:

    BRUCH BRUCH::Eingabe()
{
    int _z, _n;
    BRUCH bruch;
    cout << "Bitte einen Zaehlerwert eingeben: " << endl;
    cin >> _z;
    cout << "Bitte einen Nennerwert eingeben: " << endl;
    cin >> _n;
    while(_n==0)
    {
        cout << "Bitte einen gültigen Wert eingeben!" << endl;
        cin >> _n;
    }
    bruch.z = _z;
    bruch.n = _n;
    return bruch;
}

When I return the object the values vanish and the constructor creates a new object with default values.

What must I do to get the correct return?

Bruch - Fraction (math.) | Eingabe - Input


问:
Matplotlib with varying x span and lower size markers
I created a plot, but as you can see the x-axis has overlapping entries, I want the span between different x-axis markers to be apparent to see the numbers 1,5, 10 distinct.

Also, the markers for the plotted values are bit heavier. How can I reduce the size ?

```<code>import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;

filename = 'plot.pdf';

fig, ax1 = plt.subplots(frameon=False);
rc('mathtext', default='regular');
rc('lines',lw=2);
rc('lines',mew=2);
rc('text', usetex=True);

x = np.array([1,5,10,50,100,250,500]);

t_err = np.array([106.50, 99.53, 94.70, 94.65, 93.40, 93.38, 92.81]);
c_err  = np.array([ 66.48, 65.11, 62.08, 60.09, 59.36, 60.32, 61.17]);
lns1 = ax1.plot(x,t_err,'bs:', label="T");
lns2 = ax1.plot(x,c_err,'bs-',label="C");

ax1.set_ylabel('Error',color='b',size=12);
ax1.set_ylim([50,100]);
ax1.set_xlim([1,500]);
ax1.set_xticks(x);
ax1.tick_params(axis='y', which=u'both', length=0, labelsize=10, colors='b');
ax1.tick_params(axis='x', which=u'both', length=0, labelsize=10);

lns = lns1 + lns2;
labs = [l.get_label() for l in lns];

ax1.set_xlabel('# of Iterations',size=14);
ax1.legend(lns, labs, bbox_to_anchor=(1.02,1.0), loc=2, borderaxespad=2.5, ncol = 1);
fig.savefig(filename,format='pdf',transparent=True, bbox_inches='tight');
</code>```

答:
You can manually plot one thing and add another as label. For example (I pointed out as comment the parts I've changed):

```<code>import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;

filename = 'plot.pdf';

fig, ax1 = plt.subplots(frameon=False);
rc('mathtext', default='regular');
rc('lines',lw=2);
rc('lines',mew=2);
rc('text', usetex=False); # Change to False because I don't have Latex

x = np.array([1,5,10,50,100,250,500]);
xo = np.array([10,20,30,40,70,110,160]); # changed here

t_err = np.array([106.50, 99.53, 94.70, 94.65, 93.40, 93.38, 92.81]);
c_err  = np.array([ 66.48, 65.11, 62.08, 60.09, 59.36, 60.32, 61.17]);
lns1 = ax1.plot(xo ,t_err,'bs:', label="T"); # changed here
lns2 = ax1.plot(xo ,c_err,'bs-',label="C"); # changed here

ax1.set_ylabel('Error',color='b',size=12);
ax1.set_ylim([50,100]);
ax1.set_xlim([1,xo.max()]); #changed here
ax1.set_xticks(xo) # changed here
ax1.set_xticklabels([str(i) for i in x]); # Changed here
ax1.tick_params(axis='y', which=u'both', length=0, labelsize=10, colors='b');
ax1.tick_params(axis='x', which=u'both', length=0, labelsize=10);

lns = lns1 + lns2;
labs = [l.get_label() for l in lns];

ax1.set_xlabel('# of Iterations',size=14);
ax1.legend(lns, labs, bbox_to_anchor=(1.02,1.0), loc=2, borderaxespad=2.5, ncol = 1);
plt.show()
</code>```

Which results in this:

But obviously this goes a long way from something automatic. You can either build your own "deforming Axis function" to make a plot using this method or perhaps explore a bit the matplotlib transformations. I don't know how to use the latter so I rather not comment (I'm not even sure it can achieve this effect). Hopefully you'll get an answer with a better approach. In the mean time hope this helps.

Body:
I created a plot, but as you can see the x-axis has overlapping entries, I want the span between different x-axis markers to be apparent to see the numbers 1,5, 10 distinct.

Also, the markers for the plotted values are bit heavier. How can I reduce the size ?

import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;

filename = 'plot.pdf';

fig, ax1 = plt.subplots(frameon=False);
rc('mathtext', default='regular');
rc('lines',lw=2);
rc('lines',mew=2);
rc('text', usetex=True);

x = np.array([1,5,10,50,100,250,500]);

t_err = np.array([106.50, 99.53, 94.70, 94.65, 93.40, 93.38, 92.81]);
c_err  = np.array([ 66.48, 65.11, 62.08, 60.09, 59.36, 60.32, 61.17]);
lns1 = ax1.plot(x,t_err,'bs:', label="T");
lns2 = ax1.plot(x,c_err,'bs-',label="C");

ax1.set_ylabel('Error',color='b',size=12);
ax1.set_ylim([50,100]);
ax1.set_xlim([1,500]);
ax1.set_xticks(x);
ax1.tick_params(axis='y', which=u'both', length=0, labelsize=10, colors='b');
ax1.tick_params(axis='x', which=u'both', length=0, labelsize=10);

lns = lns1 + lns2;
labs = [l.get_label() for l in lns];

ax1.set_xlabel('# of Iterations',size=14);
ax1.legend(lns, labs, bbox_to_anchor=(1.02,1.0), loc=2, borderaxespad=2.5, ncol = 1);
fig.savefig(filename,format='pdf',transparent=True, bbox_inches='tight');

Body:
You can manually plot one thing and add another as label. For example (I pointed out as comment the parts I've changed):

import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;

filename = 'plot.pdf';

fig, ax1 = plt.subplots(frameon=False);
rc('mathtext', default='regular');
rc('lines',lw=2);
rc('lines',mew=2);
rc('text', usetex=False); # Change to False because I don't have Latex

x = np.array([1,5,10,50,100,250,500]);
xo = np.array([10,20,30,40,70,110,160]); # changed here

t_err = np.array([106.50, 99.53, 94.70, 94.65, 93.40, 93.38, 92.81]);
c_err  = np.array([ 66.48, 65.11, 62.08, 60.09, 59.36, 60.32, 61.17]);
lns1 = ax1.plot(xo ,t_err,'bs:', label="T"); # changed here
lns2 = ax1.plot(xo ,c_err,'bs-',label="C"); # changed here

ax1.set_ylabel('Error',color='b',size=12);
ax1.set_ylim([50,100]);
ax1.set_xlim([1,xo.max()]); #changed here
ax1.set_xticks(xo) # changed here
ax1.set_xticklabels([str(i) for i in x]); # Changed here
ax1.tick_params(axis='y', which=u'both', length=0, labelsize=10, colors='b');
ax1.tick_params(axis='x', which=u'both', length=0, labelsize=10);

lns = lns1 + lns2;
labs = [l.get_label() for l in lns];

ax1.set_xlabel('# of Iterations',size=14);
ax1.legend(lns, labs, bbox_to_anchor=(1.02,1.0), loc=2, borderaxespad=2.5, ncol = 1);
plt.show()

Which results in this:

But obviously this goes a long way from something automatic. You can either build your own "deforming Axis function" to make a plot using this method or perhaps explore a bit the matplotlib transformations. I don't know how to use the latter so I rather not comment (I'm not even sure it can achieve this effect). Hopefully you'll get an answer with a better approach. In the mean time hope this helps.


问:
How to use docker deploy in docker-compose 3?
When I make command sudo docker stack deploy -c docker-compose.yml test

```<code>Ignoring unsupported options: build, external_links, links, restart

Updating service test_cache (id: me2vh1lffrl4ppzomphin167la)
Updating service test_lb (id: ycnne1ifpt517wdbfdg1g5tlup)
Updating service test_media (id: rr3ural9hjz0mw6hjx7n2vywm)
Creating service test_web

Error response from daemon: rpc error: code = 3 desc = ContainerSpec: image reference must be provided
</code>```

And I get this error - Error response from daemon: rpc error: code = 3 desc = ContainerSpec: image reference must be provided

But I create image for this container.

答: Your compose.yml file does not include an image section which is required by docker stack deploy.  You should also be pushing these images to a registry server if you are deploying them to a swarm since docker uses pinning to the sha256 of the image in the registry to ensure all nodes run the same image. And since swarm does not build the images, any node without the image included locally will not be able to run this image unless it's pulled from a registry.

Body:
When I make command sudo docker stack deploy -c docker-compose.yml test

Ignoring unsupported options: build, external_links, links, restart

Updating service test_cache (id: me2vh1lffrl4ppzomphin167la)
Updating service test_lb (id: ycnne1ifpt517wdbfdg1g5tlup)
Updating service test_media (id: rr3ural9hjz0mw6hjx7n2vywm)
Creating service test_web

Error response from daemon: rpc error: code = 3 desc = ContainerSpec: image reference must be provided

And I get this error - Error response from daemon: rpc error: code = 3 desc = ContainerSpec: image reference must be provided

But I create image for this container.


问:
send enter key on python Paramiko ssh
I'm trying to create a function that connects to a machine from another machine via minicom. After connecting to minicom enter should be pressed in order to send commands to the machine connected by minicom. My python code is as follows:

```<code>ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.serialHost, username=self.username, password=self.password)
shell = ssh.invoke_shell()
shell.send('minicom free -o')
shell.send('\u000d')
ssh.close()
</code>```

Can someone tell me how can I send the enter key correctly?

答:
you can try '\r\n' for the return key, but I think there is also an exec_command method call that would not require for the return key. Something like.

```<code>shell.exec_command('minicom free -o')
</code>```

source

Title: send enter key on python Paramiko ssh

Body:
I'm trying to create a function that connects to a machine from another machine via minicom. After connecting to minicom enter should be pressed in order to send commands to the machine connected by minicom. My python code is as follows:

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.serialHost, username=self.username, password=self.password)
shell = ssh.invoke_shell()
shell.send('minicom free -o')
shell.send('\u000d')
ssh.close()

Can someone tell me how can I send the enter key correctly?

Body:
you can try '\r\n' for the return key, but I think there is also an exec_command method call that would not require for the return key. Something like.

shell.exec_command('minicom free -o')

source


答:
Typically, when trying to execute commands in paramiko you don't have to invoke a shell and can just call ssh.exec_command(...).  If the command you want to execute depends on the environment that starting a shell would give you, then you have to explicitly call the invoke_shell() method.

When you use invoke_shell() in paramiko, you'll have to send the line termination character(s) that the particular shell expects.  If the machine you're ssh'ing to has bash as it's default shell, you have to send a newline (i.e. '\n') character after each command.  For example:

```<code>shell.send('ls\n')
</code>```

instead of

```<code>shell.send('ls')
</code>```

If you're connecting to an older Windows machine, you need to send both a carriage return and a newline (i.e. '\r\n') for the command to be processed.

Title: send enter key on python Paramiko ssh

Body:
Typically, when trying to execute commands in paramiko you don't have to invoke a shell and can just call ssh.exec_command(...).  If the command you want to execute depends on the environment that starting a shell would give you, then you have to explicitly call the invoke_shell() method.

When you use invoke_shell() in paramiko, you'll have to send the line termination character(s) that the particular shell expects.  If the machine you're ssh'ing to has bash as it's default shell, you have to send a newline (i.e. '\n') character after each command.  For example:

shell.send('ls\n')

instead of

shell.send('ls')

If you're connecting to an older Windows machine, you need to send both a carriage return and a newline (i.e. '\r\n') for the command to be processed.


问:
Functions with returns 'table' has no begin...end?
If I ever add 'Begin' after 'As' It says incorrect syntax. It works just fine If I'm trying to return one value though.

Instead I should add 'return' after 'as' and open brackets ()

Why is that?

With one value as returns, I can do it fine:

```<code> CREATE FUNCTION MATHEE(@A int,@B int)
 returns int
 as
 begin
    DECLARE @C int

    SET @C = @A + @B

 return @C
 end
</code>```

With table as returns, I cant:

```<code>   CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
BEGIN

RETURN SELECT agent from Agents where agent = @bob and prime > @number
END
</code>```

It says :

Incorrect syntax near 'BEGIN'.

It works fine using brackets and without begin..end though:

```<code>CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
RETURN
(
 SELECT agent from Agents where agent = @bob and prime > @number
)
</code>```

答:
You can declare fields of Return table as following code:</p>

```<code>CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS @Result TABLE ( Agent varchar(20) )
AS
BEGIN
    Insert into @Result
    SELECT agent from Agents where agent = @bob and prime > @number

    RETURN
END
</code>```

Body:
If I ever add 'Begin' after 'As' It says incorrect syntax. It works just fine If I'm trying to return one value though.

Instead I should add 'return' after 'as' and open brackets ()

Why is that?

With one value as returns, I can do it fine:

 CREATE FUNCTION MATHEE(@A int,@B int)
 returns int
 as
 begin
    DECLARE @C int

    SET @C = @A + @B

 return @C
 end

With table as returns, I cant:

   CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
BEGIN

RETURN SELECT agent from Agents where agent = @bob and prime > @number
END

It says :

Incorrect syntax near 'BEGIN'.

It works fine using brackets and without begin..end though:

CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS TABLE
AS
RETURN
(
 SELECT agent from Agents where agent = @bob and prime > @number
)

Body:
You can declare fields of Return table as following code:

CREATE FUNCTION TOP_USERSs(@number int,@bob varchar(20))
RETURNS @Result TABLE ( Agent varchar(20) )
AS
BEGIN
    Insert into @Result
    SELECT agent from Agents where agent = @bob and prime > @number

    RETURN
END


问:
How to change spinner text color
I saw many topics about how to change spinner's text color,but i couldnt understand how to use

spinner_item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="top"
    android:singleLine="true"
    android:textColor="@color/iphone_text" />
</code>```

What shall i really do in java code:?
Any responses will be aprecieted
Please answer clearly with as more  details as you can

答:
Building on noobProgrammer answer, as singleLine has been deprecated, a quick updated version of the spinner_item.xml for anyone who is looking for a answer for this.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1">
</TextView>
</code>```

Title: How to change spinner text color

Body:
I saw many topics about how to change spinner's text color,but i couldnt understand how to use

spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="top"
    android:singleLine="true"
    android:textColor="@color/iphone_text" />

What shall i really do in java code:?
Any responses will be aprecieted
Please answer clearly with as more  details as you can

Body:
Building on noobProgrammer answer, as singleLine has been deprecated, a quick updated version of the spinner_item.xml for anyone who is looking for a answer for this.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1">
</TextView>


问:
a function for bigglm model selection like dredge working for glm
I was using glm with dredge in MuMIn package. But now since my data is large I am using bigglm from biglm package. Now how do I do model selection now since dredge does not work with bigglm? Is there another package I can use to achieve this?

On applying the dredge on bigglm I am receiving the following error:

Error in nobs.default(global.model) : no 'nobs' method is available

答:
dredge relies on availability of logLik method for the the given model class. big[g]lm object does not provide such value, and there seems to be a long known bug in the AIC method for big[g]lm-class that makes it impossible to calculate LL from it (it uses deviance rather than LL to calculate AIC, so AIC-values are not comparable to other model types, see here: AIC different between biglm and lm).

You could try adding the missing methods (using deviance instead of LL, which may be slippery):

```<code># incorrect if any prior weights are 0
nobs.biglm <- function (object, ...) object$n

logLik.bigglm <- function(object, ...) {
    dev <- deviance(object, ...)
    df <- object$n - object$df.resid
    structure(dev, df = df, nobs = object$n)
}

coefTable.biglm <- function (model, data, ...) {
    ct <- summary(model)$mat[, c(1L,4L,5L), drop = FALSE]
    .makeCoefTable(ct[, 1L], se = ct[, 2L], df = model$df.resid, coefNames = rownames(ct))
}
environment(coefTable.biglm) <- asNamespace("MuMIn")

#from example(bigglm)

fm <- bigglm(log(Volume)~log(Girth)+log(Height),data=trees, chunksize=10, sandwich=TRUE)
dredge(fm, rank = AIC)
</code>```

Body:
dredge relies on availability of logLik method for the the given model class. big[g]lm object does not provide such value, and there seems to be a long known bug in the AIC method for big[g]lm-class that makes it impossible to calculate LL from it (it uses deviance rather than LL to calculate AIC, so AIC-values are not comparable to other model types, see here: AIC different between biglm and lm).

You could try adding the missing methods (using deviance instead of LL, which may be slippery):

# incorrect if any prior weights are 0
nobs.biglm <- function (object, ...) object$n

logLik.bigglm <- function(object, ...) {
    dev <- deviance(object, ...)
    df <- object$n - object$df.resid
    structure(dev, df = df, nobs = object$n)
}

coefTable.biglm <- function (model, data, ...) {
    ct <- summary(model)$mat[, c(1L,4L,5L), drop = FALSE]
    .makeCoefTable(ct[, 1L], se = ct[, 2L], df = model$df.resid, coefNames = rownames(ct))
}
environment(coefTable.biglm) <- asNamespace("MuMIn")

#from example(bigglm)

fm <- bigglm(log(Volume)~log(Girth)+log(Height),data=trees, chunksize=10, sandwich=TRUE)
dredge(fm, rank = AIC)


问:
Create a new div class row every 3 items fetch from SQL with PHP
I am trying to create a gallery.. Every 3 images I need to create a new div and start again.(trying to turn this html to php-sql)

I am trying that with this php code

```<code><?php
  //get images from database
  $query = $con->query("SELECT * FROM images ORDER BY id");

   if($query->num_rows > 0){
    while($row = $query->fetch_assoc()){
    $imagethumb = 'images/thumb/'.$row["file_name"];
    $imagefront = 'images/'.$row["file_name"];

    $i = 0;

    if($i++ % 3 == 0){
    ?>
    <div class=" bd-layoutcontainer bd-columns bd-no-margins">
       <div class="bd-container-inner">
          <div class="container-fluid">
              <div class="row">
                   <div class="bd-columnwrapper-136 <?php
                       list($width, $height) = getimagesize($imagethumb);
                       if($width > 298){
                          echo 'col-sm-6';
                       }else{
                          echo 'col-sm-3';
                     }
                   ?>">
                   <?php echo '<div class="bd-layoutcolumn-136 bd-column">
                               <div class="bd-vertical-align-wrapper">
                               <div class="bd-hoverbox-6 bd-effect-fade">
                               <div class="bd-slidesWrapper">' ?>
                        <a href="<?php echo $imagethumb; ?>" data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
                         <img src="<?php echo $imagefront; ?>" alt="" />
                        </a>
                  <?php echo '
                              </div>
                              </div>
                              </div>
                              </div>'
                  ?>
                  </div>
            </div>
      </div>
     </div>
   <?php
      }
      }
      }
?>
</code>```

I am using the if statement $i % 3 == 0 to create a new div but i get every image one down of other and not three images in row like the pic..
 This is what i get

What else should i do?

I need every 3 imgs to create the

```<code>     <div class=" bd-layoutcontainer bd-columns bd-no-margins">
       ..............
     </div>
</code>```

And div never multiplied by 3 i just got one div back

答:
```<code></div>
<div class=" bd-layoutcontainer bd-columns bd-no-margins">
</code>```

i think  if statement $i % 3 == 0 you should add close tag and create a new div.Hope to solve your issue.

Body:
I am trying to create a gallery.. Every 3 images I need to create a new div and start again.(trying to turn this html to php-sql)

I am trying that with this php code

<?php
  //get images from database
  $query = $con->query("SELECT * FROM images ORDER BY id");

   if($query->num_rows > 0){
    while($row = $query->fetch_assoc()){
    $imagethumb = 'images/thumb/'.$row["file_name"];
    $imagefront = 'images/'.$row["file_name"];

    $i = 0;

    if($i++ % 3 == 0){
    ?>

                   <div class="bd-columnwrapper-136 <?php
                       list($width, $height) = getimagesize($imagethumb);
                       if($width > 298){
                          echo 'col-sm-6';
                       }else{
                          echo 'col-sm-3';
                     }
                   ?>">
                   <?php echo '

' ?>
                        <a href="<?php echo $imagethumb; ?>" data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
                         <img src="<?php echo $imagefront; ?>" alt="" />

                  <?php echo '

'
                  ?>

   <?php
      }
      }
      }
?>

I am using the if statement $i % 3 == 0 to create a new div but i get every image one down of other and not three images in row like the pic..
 This is what i get

What else should i do?

I need every 3 imgs to create the

       ..............

And div never multiplied by 3 i just got one div back

Body:
</div>
<div class=" bd-layoutcontainer bd-columns bd-no-margins">

i think  if statement $i % 3 == 0 you should add close tag and create a new div.Hope to solve your issue.


问:
Spring @PreDestroy method
I found out that @PreDestroy only work with singleton scoped bean. I was thinking what could go wrong if we use it with prototype scoped bean. Anything at all??? I dont think so. I think this is just not implemented in spring as they would have to keep the references to all the beans created. Tell me if i am wrong

答:
For "prototype" scoped beans, Spring does not call the @PreDestroy method.

Here is the answer from the Spring reference manual. Section 7.5.2

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes-prototype

In contrast to the other scopes, Spring does not manage the complete lifecycle of a
prototype bean: the container instantiates, configures, and otherwise assembles a
prototype object, and hands it to the client, with no further record of that prototype
instance.

Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.

To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.

Title: Spring @PreDestroy method


问:
Explicitly stop late binding
If we create an object pointer to base class class which points to its child class object  then we use virtual key word for  late binding
So.,in case of late binding,, our code goes like this :-

```<code>#include<iostream>
using namespace std;
struct A{
    virtual void print() {
        cout<<"function1";
    }
};

struct B : public A{
    void print(){
        cout<<"function2";
    }
};

struct C : public B{
    void print(){
        cout<<"function3";
    }
};

int main(){
    A* a = new C();
    A* p = new B();
    a->print();
    p->print();
}
</code>```

Now my question is : when we use virtual keyword in base class, all the functions of derived classes created in base class will become virtual.
      In multilevel inheritance, is there any way so that we can stop the function of class c from being virtual??
   Any way to break this chain of virtual functions ?
  Sorry for any mistakes in question  but i tried my best.. ☺☺

答:
It is not possible to make a function that is already virtual be not virtual in a child class.

Virtuality is a property of the top-level base class, not the child classes. Once a method has been marked as virtual, and pointer to that class must use dynamic dispatch for that function when calling because the pointer could be pointing to a child class that has overridden the behaviour.

Consider this code:

```<code>A a;
B b;
C c;

A * ap = &a;
A * bp = &b;
A * cp = &c;

ap->print(); // 'function1'
bp->print(); // 'function2'
cp->print(); // 'function3'
</code>```

Here, the calls to print cannot tell which function to call at compile time, they absolutely must use dynamic dispatch.

However, you can make C::print behave like A::print

```<code>struct C : public B {
    void print() {
        A::print();
    }
};
</code>```

Which results in:

```<code>ap->print(); // 'function1'
bp->print(); // 'function2'
cp->print(); // 'function1'
</code>```

And if the behaviour of A::print() changes, C::print() mirrors those changes.

This will still be overridable though, unless you use the final keyword as outlined below.

Original answer:

I believe you are looking for the final specifier.
It's only available as of C++11 though.

To quote en.cppreference's page about the final specifier:

When used in a virtual function declaration or definition, final
  ensures that the function is virtual and specifies that it may not be
  overridden by derived classes. The program is ill-formed (a
  compile-time error is generated) otherwise.

And a variation of the example they give, demonstrating the solution to your problem:

```<code>struct A
{
    virtual void foo();
};

struct B : A
{
    void foo() final; // B::foo is overridden and it is the final override
};

struct C : B
{
    void foo() override; // Error: foo cannot be overridden as it's final in B
};
</code>```

Title: Explicitly stop late binding

Body:
If we create an object pointer to base class class which points to its child class object  then we use virtual key word for  late binding
So.,in case of late binding,, our code goes like this :-

#include<iostream>
using namespace std;
struct A{
    virtual void print() {
        cout<<"function1";
    }
};

struct B : public A{
    void print(){
        cout<<"function2";
    }
};

struct C : public B{
    void print(){
        cout<<"function3";
    }
};

int main(){
    A* a = new C();
    A* p = new B();
    a->print();
    p->print();
}

Now my question is : when we use virtual keyword in base class, all the functions of derived classes created in base class will become virtual.
      In multilevel inheritance, is there any way so that we can stop the function of class c from being virtual??
   Any way to break this chain of virtual functions ?
  Sorry for any mistakes in question  but i tried my best.. ☺☺

Body:
It is not possible to make a function that is already virtual be not virtual in a child class.

Virtuality is a property of the top-level base class, not the child classes. Once a method has been marked as virtual, and pointer to that class must use dynamic dispatch for that function when calling because the pointer could be pointing to a child class that has overridden the behaviour.

Consider this code:

A a;
B b;
C c;

A * ap = &a;
A * bp = &b;
A * cp = &c;

ap->print(); // 'function1'
bp->print(); // 'function2'
cp->print(); // 'function3'

Here, the calls to print cannot tell which function to call at compile time, they absolutely must use dynamic dispatch.

However, you can make C::print behave like A::print

struct C : public B {
    void print() {
        A::print();
    }
};

Which results in:

ap->print(); // 'function1'
bp->print(); // 'function2'
cp->print(); // 'function1'

And if the behaviour of A::print() changes, C::print() mirrors those changes.

This will still be overridable though, unless you use the final keyword as outlined below.

Original answer:

I believe you are looking for the final specifier.
It's only available as of C++11 though.

To quote en.cppreference's page about the final specifier:

When used in a virtual function declaration or definition, final
  ensures that the function is virtual and specifies that it may not be
  overridden by derived classes. The program is ill-formed (a
  compile-time error is generated) otherwise.

And a variation of the example they give, demonstrating the solution to your problem:

struct A
{
    virtual void foo();
};

struct B : A
{
    void foo() final; // B::foo is overridden and it is the final override
};

struct C : B
{
    void foo() override; // Error: foo cannot be overridden as it's final in B
};


问:
CSV string handling
Typical way of creating a CSV string (pseudocode):

Create a CSV container object (like a StringBuilder in C#).

Loop through the strings you want to add appending a comma after each one.

After the loop, remove that last superfluous comma.

Code sample:

```<code>public string ReturnAsCSV(ContactList contactList)
{
    StringBuilder sb = new StringBuilder();
    foreach (Contact c in contactList)
    {
        sb.Append(c.Name + ",");
    }

    sb.Remove(sb.Length - 1, 1);
    //sb.Replace(",", "", sb.Length - 1, 1)

    return sb.ToString();
}
</code>```

I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence?

I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?

答:
You could instead add the comma as the first thing inside your foreach.

if (sb.Length > 0) sb.Append(",");

Title: CSV string handling

Body:
Typical way of creating a CSV string (pseudocode):

Create a CSV container object (like a StringBuilder in C#).

Loop through the strings you want to add appending a comma after each one.

After the loop, remove that last superfluous comma.

Code sample:

public string ReturnAsCSV(ContactList contactList)
{
    StringBuilder sb = new StringBuilder();
    foreach (Contact c in contactList)
    {
        sb.Append(c.Name + ",");
    }

    sb.Remove(sb.Length - 1, 1);
    //sb.Replace(",", "", sb.Length - 1, 1)

    return sb.ToString();
}

I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence?

I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?

LastEditorDisplayName: aussieviking


问:
How do you test a message expectation within a block in Rspec?
I'm trying to test message expectation within a block in Rspec:

```<code>def a_method
  ALibrary.execute do |batch|
    batch.execute if a == 1
  end
end
</code>```

If I am stubbing out the execute method in ALibrary, how do I test that a message was sent to the inner execute?

```<code>allow(ALibrary).to receive(:execute).and_return(a_library_execute)
let(:a_library_execute) {double(execute:true)}
</code>```

Thanks!

答:
If you want the ALibrary.execute to return your own test double you can the and_yield response.

```<code>allow(ALibrary).to receive(:execute).and_yield(a_library_execute)
</code>```

Body:
I'm trying to test message expectation within a block in Rspec:

def a_method
  ALibrary.execute do |batch|
    batch.execute if a == 1
  end
end

If I am stubbing out the execute method in ALibrary, how do I test that a message was sent to the inner execute?

allow(ALibrary).to receive(:execute).and_return(a_library_execute)
let(:a_library_execute) {double(execute:true)}

Thanks!

Body:
If you want the ALibrary.execute to return your own test double you can the and_yield response.

allow(ALibrary).to receive(:execute).and_yield(a_library_execute)


问:
Error - argument "inputId" is missing, with no default
Trying to get a numeric input and apply 2 formulas on the input and use them to plot histograms.

UI Side

```<code>library(shiny)

shinyUI(fluidPage(
  actionButton (InputId = "USD", label = "US Bond Return"),
  actionButton (InputId = "INR", label = "Indian Bond Return"),
  numericInput(InputId = "num", label = "USD given by Investor", value = 0,
min = 1, max = 1000, step = NA, width = NULL), plotOutput("hist")))
</code>```

Server Side

```<code>library(shiny)

shinyServer(function(input, output) {

rv = reactiveValues(data = input$num)
observeEvent(input$USD, { rv$data <- (input$num * 0.0225) })
observeEvent(input$INR, { rv$data <- (input$num*0.1) })

output$curve <- renderPlot({
hist(rv$data)
})
}
)
</code>```

答:
There is a problem in your ui. Its not InputId, its inputId(notice the small i).

Therefore your ui code will be as follows:

```<code>shinyUI(fluidPage(
    actionButton (inputId = "USD", label = "US Bond Return"),
    actionButton (inputId = "INR", label = "Indian Bond Return"),
    numericInput(inputId = "num", label = "USD given by Investor", value = 0,
                 min = 1, max = 1000, step = NA, width = NULL), plotOutput("hist")))
</code>```

Body:
Trying to get a numeric input and apply 2 formulas on the input and use them to plot histograms.

UI Side

library(shiny)

shinyUI(fluidPage(
  actionButton (InputId = "USD", label = "US Bond Return"),
  actionButton (InputId = "INR", label = "Indian Bond Return"),
  numericInput(InputId = "num", label = "USD given by Investor", value = 0,
min = 1, max = 1000, step = NA, width = NULL), plotOutput("hist")))

Server Side

library(shiny)

shinyServer(function(input, output) {

rv = reactiveValues(data = input$num)
observeEvent(input$USD, { rv$data <- (input$num * 0.0225) })
observeEvent(input$INR, { rv$data <- (input$num*0.1) })

output$curve <- renderPlot({
hist(rv$data)
})
}
)

Body:
There is a problem in your ui. Its not InputId, its inputId(notice the small i).

Therefore your ui code will be as follows:

shinyUI(fluidPage(
    actionButton (inputId = "USD", label = "US Bond Return"),
    actionButton (inputId = "INR", label = "Indian Bond Return"),
    numericInput(inputId = "num", label = "USD given by Investor", value = 0,
                 min = 1, max = 1000, step = NA, width = NULL), plotOutput("hist")))