问:
no such table found in SQLite
im having a problem trying to establish a database in android, everytime i log in, the log cat says that no such table.

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

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "name";

private static final String TABLE_LOGIN = "online";

private static final String KEY_ID = "Registration_id";
private static final String KEY_NAME = "Name";
private static final String KEY_PASSWORD = "Password";
private static final String KEY_UNIQUEID = "unique_id";

public DatabaseOnline(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
            + KEY_NAME + " VARCHAR (255), " + KEY_PASSWORD
            + " VARCHAR (255), " + KEY_ID + " VARCHAR(255), "
            + KEY_UNIQUEID + " VARCHAR (255)" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);
}

public void addUser(String name, String password, String regId,
        String unique_id) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, name); // Name
    values.put(KEY_PASSWORD, password); // Email
    values.put(KEY_ID, regId);
    values.put(KEY_UNIQUEID, unique_id);
    // Inserting Row
    db.insert(TABLE_LOGIN, null, values);
    db.close(); // Closing database connection
}

public int getRowCount() {
    String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int rowCount = cursor.getCount();
    db.close();
    cursor.close();

    // return row count
    return rowCount;
}

/**
 * Re crate database Delete all tables and create them again
 * */
public void resetTables() {
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_LOGIN, null, null);
    db.close();
}

}
</code>```

the problem is when i log in:

```<code>    DatabaseOnline db = new DatabaseOnline(getApplicationContext());
db.getWritableDatabase();
JSONObject json_user = json.getJSONObject("user");

System.out.println("unique id " + json_user.getString("unique_id"));
System.out.println("password " + json_user.getString("password"));
  db.addUser(json_user.getString("name"),json_user.getString("password"),json_user.getString("regId"),json_user.getString("unique_id"));

Intent dashboard = new Intent(getApplicationContext(),Main.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
</code>```

what appears is that android didnt create the database.
and here is the log cat:

```<code>11-20 21:42:15.162: E/SQLiteLog(1176): (1) no such table: online
11-20 21:42:15.282: E/SQLiteDatabase(1176): Error inserting unique_id=50a939dc9fa8a4.09780382 Name=v Registration_id=APA91bHnScWAF0xjtMjyHTvHx3ON6Eu_8on6kZUL5EvDmtAK8WDxwBVpNyMoapaTl0-ProAnY0m9VZbS-0OPeMshQkeU7ZOHlfI8tUAVJbeIgoe9sdL061ntJ8MnyglrLHK2BOWH2K1n Password=9e3669d19b675bd57058fd4664205d2a
11-20 21:42:15.282: E/SQLiteDatabase(1176): android.database.sqlite.SQLiteException: no such table: online (code 1): , while compiling: INSERT INTO online(unique_id,Name,Registration_id,Password) VALUES (?,?,?,?)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at guc.edu.i.DatabaseOnline.addUser(DatabaseOnline.java:66)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at guc.edu.i.Login.login(Login.java:199)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at guc.edu.i.Login$7.run(Login.java:146)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at java.lang.Thread.run(Thread.java:856)
</code>```

答:
If you make changes to your database then clearing the cache & clearing the data from your device (settings->Apps->your App) will also solve this problem.
I have tried it & its working.</p>

Title: no such table found in SQLite

Body:
im having a problem trying to establish a database in android, everytime i log in, the log cat says that no such table.

public class DatabaseOnline extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "name";

private static final String TABLE_LOGIN = "online";

private static final String KEY_ID = "Registration_id";
private static final String KEY_NAME = "Name";
private static final String KEY_PASSWORD = "Password";
private static final String KEY_UNIQUEID = "unique_id";

public DatabaseOnline(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
            + KEY_NAME + " VARCHAR (255), " + KEY_PASSWORD
            + " VARCHAR (255), " + KEY_ID + " VARCHAR(255), "
            + KEY_UNIQUEID + " VARCHAR (255)" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);
}

public void addUser(String name, String password, String regId,
        String unique_id) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, name); // Name
    values.put(KEY_PASSWORD, password); // Email
    values.put(KEY_ID, regId);
    values.put(KEY_UNIQUEID, unique_id);
    // Inserting Row
    db.insert(TABLE_LOGIN, null, values);
    db.close(); // Closing database connection
}

public int getRowCount() {
    String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int rowCount = cursor.getCount();
    db.close();
    cursor.close();

    // return row count
    return rowCount;
}

/**
 * Re crate database Delete all tables and create them again
 * */
public void resetTables() {
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_LOGIN, null, null);
    db.close();
}

}

the problem is when i log in:

    DatabaseOnline db = new DatabaseOnline(getApplicationContext());
db.getWritableDatabase();
JSONObject json_user = json.getJSONObject("user");

System.out.println("unique id " + json_user.getString("unique_id"));
System.out.println("password " + json_user.getString("password"));
  db.addUser(json_user.getString("name"),json_user.getString("password"),json_user.getString("regId"),json_user.getString("unique_id"));

Intent dashboard = new Intent(getApplicationContext(),Main.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();

what appears is that android didnt create the database.
and here is the log cat:

11-20 21:42:15.162: E/SQLiteLog(1176): (1) no such table: online
11-20 21:42:15.282: E/SQLiteDatabase(1176): Error inserting unique_id=50a939dc9fa8a4.09780382 Name=v Registration_id=APA91bHnScWAF0xjtMjyHTvHx3ON6Eu_8on6kZUL5EvDmtAK8WDxwBVpNyMoapaTl0-ProAnY0m9VZbS-0OPeMshQkeU7ZOHlfI8tUAVJbeIgoe9sdL061ntJ8MnyglrLHK2BOWH2K1n Password=9e3669d19b675bd57058fd4664205d2a
11-20 21:42:15.282: E/SQLiteDatabase(1176): android.database.sqlite.SQLiteException: no such table: online (code 1): , while compiling: INSERT INTO online(unique_id,Name,Registration_id,Password) VALUES (?,?,?,?)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at guc.edu.i.DatabaseOnline.addUser(DatabaseOnline.java:66)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at guc.edu.i.Login.login(Login.java:199)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at guc.edu.i.Login$7.run(Login.java:146)
11-20 21:42:15.282: E/SQLiteDatabase(1176):     at java.lang.Thread.run(Thread.java:856)


来源: stackexchange

问:
Error: select command denied to user '<userid>'@'<ip-address>' for table '
'
In my website, I am using MySQL database. I am using a webservice where in I do all my database related manipulations.

Now In one of the methods of that webservice, I get the following Error.

select command denied to user '<userid>'@'<ip-address>' for table '
'

What could be wrong?

Below is the code where I get that error. I tried debugging and found that it fails at the line

MySqlDataReader result1 = command1.ExecuteReader();

Here is my code:

```<code>        String addSQL = "Select Max(`TradeID`) from `jsontest`.`tbl_Positions";
        MySqlConnection objMyCon = new MySqlConnection(strProvider);
        objMyCon.Open();
        MySqlCommand command = objMyCon.CreateCommand();

        command.CommandText = addSQL;
         MySqlDataReader result = command.ExecuteReader();
        //int j = command.ExecuteNonQuery();
         while (result.Read())
         {
             MaxTradeID = Convert.ToInt32(result[0]);
         }
        objMyCon.Close();
        for (i = 1; i <= MaxTradeID; i++)
        {
            String newSQL = "Select `Strike`,`LongShort`,`Current`,`TPLevel`,`SLLevel` from `json`.`tbl_Position` where `TradeID` = '" + i + "'";
            MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
            objMyCon1.Open();
            MySqlCommand command1 = objMyCon1.CreateCommand();

            command1.CommandText = newSQL;
            MySqlDataReader result1 = command1.ExecuteReader();
           objMyCon2.Close();
</code>```

答:
database user does not have the permission to do select query.

you can grant the permission to the user if you have root access to mysql

http://dev.mysql.com/doc/refman/5.1/en/grant.html

Your second query is on different database on different table.

```<code> String newSQL = "Select `Strike`,`LongShort`,`Current`,`TPLevel`,`SLLevel` from `json`.`tbl_Position` where `TradeID` = '" + i + "'";
</code>```

And the user you are connecting with does not have permission to access data from this database or this particular table.

Have you consider this thing?

ContentLicense: CC BY-SA 4.0

Title: Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

Body:
In my website, I am using MySQL database. I am using a webservice where in I do all my database related manipulations.

Now In one of the methods of that webservice, I get the following Error.

select command denied to user '<userid>'@'<ip-address>' for table '
'

What could be wrong?

Below is the code where I get that error. I tried debugging and found that it fails at the line

MySqlDataReader result1 = command1.ExecuteReader();

Here is my code:

        String addSQL = "Select Max(`TradeID`) from `jsontest`.`tbl_Positions";
        MySqlConnection objMyCon = new MySqlConnection(strProvider);
        objMyCon.Open();
        MySqlCommand command = objMyCon.CreateCommand();

        command.CommandText = addSQL;
         MySqlDataReader result = command.ExecuteReader();
        //int j = command.ExecuteNonQuery();
         while (result.Read())
         {
             MaxTradeID = Convert.ToInt32(result[0]);
         }
        objMyCon.Close();
        for (i = 1; i <= MaxTradeID; i++)
        {
            String newSQL = "Select `Strike`,`LongShort`,`Current`,`TPLevel`,`SLLevel` from `json`.`tbl_Position` where `TradeID` = '" + i + "'";
            MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
            objMyCon1.Open();
            MySqlCommand command1 = objMyCon1.CreateCommand();

            command1.CommandText = newSQL;
            MySqlDataReader result1 = command1.ExecuteReader();
           objMyCon2.Close();

Body:
database user does not have the permission to do select query.

you can grant the permission to the user if you have root access to mysql

http://dev.mysql.com/doc/refman/5.1/en/grant.html

Your second query is on different database on different table.

 String newSQL = "Select `Strike`,`LongShort`,`Current`,`TPLevel`,`SLLevel` from `json`.`tbl_Position` where `TradeID` = '" + i + "'";

And the user you are connecting with does not have permission to access data from this database or this particular table.

Have you consider this thing?

ContentLicense: CC BY-SA 2.5


问:
ConstraintException does not raise in rspec
I want to write a test that handles FOREIGN KEY constraint error when deleting a record, but ConstraintException is not raised.

the table's schema like below

```<code>class CreateCountries < ActiveRecord::Migration[5.1]
  def change
    create_table :countries do |t|
      t.string :name
      t.integer :sequence
    end
  end
end

class CreateStates < ActiveRecord::Migration[5.1]
  def change
    create_table :states do |t|
      t.string :name
      t.integer :sequence
      t.references :country, foreign_key: true
    end
  end
end
</code>```

I confirmed to raise ConstraintException on delete it in rails console.

```<code>c = Country.create!(name: 'country')
State.create!(name: 'state', country: c)
c.destroy
</code>```

(0.1ms)  begin transaction
    SQL (0.8ms)  DELETE FROM "countries" WHERE "countries"."id" = ?  [["id", 10]]
     (6.1ms)  rollback transaction
  ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "countries" WHERE "countries"."id" = ?
  from /Users/masamoto/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:108:in `step'

However, no error occurred in the rspec, and it seemed to me that it was deleted normally.

```<code>describe 'Error' do
  it 'Destroy' do
    country = Country.create!(name: 'hohooho')
    State.create!(name: 'oooooo', country: country)
    country.destroy
  end
end
</code>```

Error
        Destroy

Finished in 0.0339 seconds (files took 3.27 seconds to load)
  1 example, 0 failures

I thought that the transaction was not committed, I tried setting config.use_transactional_fixtures = false, but it did not change.

And I tried explicit commit, but the result is the same.

```<code>describe 'Error' do
  it 'Destroy' do
    country = nil
    ActiveRecord::Base.transaction do
      country = Country.create!(name: 'hohooho')
      State.create!(name: 'oooooo', country: country)
    end

    ActiveRecord::Base.transaction do
      country.destroy
    end
  end
end
</code>```

Does anyone have an idea?

答:
That is because your foreign key constraints are not in the test database.

Add following to application.rb file

```<code>config.active_record.schema_format = :sql
</code>```

and run

```<code>rake db:test:prepare
</code>```

should fix the problem

more information can be found here missing foreign key in test database

ContentLicense: CC BY-SA 3.0

Body:
I want to write a test that handles FOREIGN KEY constraint error when deleting a record, but ConstraintException is not raised.

the table's schema like below

class CreateCountries < ActiveRecord::Migration[5.1]
  def change
    create_table :countries do |t|
      t.string :name
      t.integer :sequence
    end
  end
end

class CreateStates < ActiveRecord::Migration[5.1]
  def change
    create_table :states do |t|
      t.string :name
      t.integer :sequence
      t.references :country, foreign_key: true
    end
  end
end

I confirmed to raise ConstraintException on delete it in rails console.

c = Country.create!(name: 'country')
State.create!(name: 'state', country: c)
c.destroy

(0.1ms)  begin transaction
    SQL (0.8ms)  DELETE FROM "countries" WHERE "countries"."id" = ?  [["id", 10]]
     (6.1ms)  rollback transaction
  ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "countries" WHERE "countries"."id" = ?
  from /Users/masamoto/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:108:in `step'

However, no error occurred in the rspec, and it seemed to me that it was deleted normally.

describe 'Error' do
  it 'Destroy' do
    country = Country.create!(name: 'hohooho')
    State.create!(name: 'oooooo', country: country)
    country.destroy
  end
end

Error
        Destroy

Finished in 0.0339 seconds (files took 3.27 seconds to load)
  1 example, 0 failures

I thought that the transaction was not committed, I tried setting config.use_transactional_fixtures = false, but it did not change.

And I tried explicit commit, but the result is the same.

describe 'Error' do
  it 'Destroy' do
    country = nil
    ActiveRecord::Base.transaction do
      country = Country.create!(name: 'hohooho')
      State.create!(name: 'oooooo', country: country)
    end

    ActiveRecord::Base.transaction do
      country.destroy
    end
  end
end

Does anyone have an idea?

Body:
That is because your foreign key constraints are not in the test database.

Add following to application.rb file

config.active_record.schema_format = :sql

and run

rake db:test:prepare

should fix the problem

more information can be found here missing foreign key in test database


问:
What does NHibernate Session.Evict do?
What does the following code snippet do? Why the use of Evict?

```<code>private void DoEvict(customer cust)
{
    AddressRepository.Evict(cust.Address);
    cust.Address = AddressRepository.Get(cust.Address.Id);
}
</code>```

答: Session.evict() is used to remove a particular object from Persistent state to Detached state.</p>

Title: What does NHibernate Session.Evict do?

Body:
What does the following code snippet do? Why the use of Evict?

private void DoEvict(customer cust)
{
    AddressRepository.Evict(cust.Address);
    cust.Address = AddressRepository.Get(cust.Address.Id);
}


问:
Persisting a @OneToOne child entity with @MapsId throws "error:detached entity passed to persist" in Hibernate
I read https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/.
I tried suggestion config like(using spring data JPA,hibernate 5.0 as vendor ):

```<code>public class PaperSubjectType{
    @Id
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private PaperSetting paperSetting;
..
}

class PaperSetting{
  @Id
  @GeneratedValue
  private Long id;
..
}
</code>```

first I tried the example:

```<code>PaperSetting paperSettingInDb = paperSettingRepository.findOne(1);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setSubjectCode("91");
paperSubjectType.setPaperSetting(paperSettingInDb);

paperSubjectTypeRepository.save(paperSubjectType);
</code>```

error:detached entity passed to persist:PaperSetting.
it seems hibernate take PaperSetting as detached when cascade

2 if I want to create both PaperSubjectType and PaperSetting together,do I need to do this:

```<code>PaperSetting paperSetting = new PaperSetting();
paperSetting.setxx;
PaperSetting  paperSettingInDbNew = paperSettingRepository.save(paperSetting);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setPaperSetting(paperSettingInDbNew);
paperSubjectTypeRepository.save(paperSubjectType);
</code>```

or I should use bidirectional in this situation?
thank you！

答:
I think you may have forgotten to wrap the logic in a @Transactional block

```<code>@Transactional
PaperSetting paperSettingInDb = paperSettingRepository.findOne(1);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setSubjectCode("91");
paperSubjectType.setPaperSetting(paperSettingInDb);

paperSubjectTypeRepository.save(paperSubjectType);
</code>```

without that crudRepository.findOne() will open it's own short lived transaction so when you get the return of findOne() the entity is already detached, hence the error

Body:
I read https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/.
I tried suggestion config like(using spring data JPA,hibernate 5.0 as vendor ):

public class PaperSubjectType{
    @Id
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private PaperSetting paperSetting;
..
}

class PaperSetting{
  @Id
  @GeneratedValue
  private Long id;
..
}

first I tried the example:

PaperSetting paperSettingInDb = paperSettingRepository.findOne(1);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setSubjectCode("91");
paperSubjectType.setPaperSetting(paperSettingInDb);

paperSubjectTypeRepository.save(paperSubjectType);

error:detached entity passed to persist:PaperSetting.
it seems hibernate take PaperSetting as detached when cascade

2 if I want to create both PaperSubjectType and PaperSetting together,do I need to do this:

PaperSetting paperSetting = new PaperSetting();
paperSetting.setxx;
PaperSetting  paperSettingInDbNew = paperSettingRepository.save(paperSetting);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setPaperSetting(paperSettingInDbNew);
paperSubjectTypeRepository.save(paperSubjectType);

or I should use bidirectional in this situation?
thank you！

Body:
I think you may have forgotten to wrap the logic in a @Transactional block

@Transactional
PaperSetting paperSettingInDb = paperSettingRepository.findOne(1);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setSubjectCode("91");
paperSubjectType.setPaperSetting(paperSettingInDb);

paperSubjectTypeRepository.save(paperSubjectType);

without that crudRepository.findOne() will open it's own short lived transaction so when you get the return of findOne() the entity is already detached, hence the error


问:
Hard link cells in script editor for Google Spreadsheet
When in Google Spreadsheet, you have formula's referencing cells to make for example a simple sum, Spreadsheets will automatically update the references, should the cells be moved. For example if the cells where cut and pasted to a different location, or rows/columns where added somewhere.

I've got this Spreadsheet where I refresh some data in using REST API's in the Spreadsheet script editor. This one runs every 5 minutes or so. However if the cells in which the data needs to be inserted, move around, my script breaks. So I have a list of constants with all kinds of cell names, for example:

```<code>/* --- EXCHANGE RATES --- */
var CELL_BTC_EUR = "B3";
var CELL_ETH_EUR = "B4";
var CELL_BNK_EUR = "B5";
</code>```

But I need to update these every time I move something to optimize the spreadsheet. Is there a way to hard link it to a specific cell so that they automatically update similar to in cell formula's? Maybe not with these constant but with lines like:

```<code>sheet.getRange(CELL_BTC_EUR).setValue(btceur.last);
</code>```

答:
Potential solution

I make a seperate sheet with all my "dynamic" data which is refreshed via Spreadsheet script. In my main sheet, I can reference those cells. Thus if in my mainsheet things start moving, the reference to my other sheet stay the same. I can then hide/protect the Script Sheet.

I'm still gonna make a small table in my mainsheet with my currency exchange rates, just to get an overview of everything. But my references would not break anymore everytime I insert a new coin or something.

(better solutions are welcome. :) )

Body:
When in Google Spreadsheet, you have formula's referencing cells to make for example a simple sum, Spreadsheets will automatically update the references, should the cells be moved. For example if the cells where cut and pasted to a different location, or rows/columns where added somewhere.

I've got this Spreadsheet where I refresh some data in using REST API's in the Spreadsheet script editor. This one runs every 5 minutes or so. However if the cells in which the data needs to be inserted, move around, my script breaks. So I have a list of constants with all kinds of cell names, for example:

/* --- EXCHANGE RATES --- */
var CELL_BTC_EUR = "B3";
var CELL_ETH_EUR = "B4";
var CELL_BNK_EUR = "B5";

But I need to update these every time I move something to optimize the spreadsheet. Is there a way to hard link it to a specific cell so that they automatically update similar to in cell formula's? Maybe not with these constant but with lines like:

sheet.getRange(CELL_BTC_EUR).setValue(btceur.last);


问:
Permissions for ServiceStack Slack Logging
I'm currently trying out ServiceStack Logging with Slack, and altough it seems to work, I can't change the channels and name of the bot. I think it might have something to do with my Slack configuration, but since I didn't really use Slack before, I'm not sure how to set it up.

My logging config looks like this:

```<code>public override void Configure(Funq.Container container)
{
    LogManager.LogFactory = new SlackLogFactory("https://hooks.slack.com/services/[...]", debugEnabled: true)
    {
        DefaultChannel = "logs",
        ErrorChannel = "errorlogs",
        BotUsername = "ServiceStack Logger"
    };

    SetConfig(new HostConfig
    {
        DefaultContentType = MimeTypes.Json
    });
}
</code>```

So, the logging works, but the username is not set correctly (instead, it's the apps name) and it only posts to the channel I specified when creating the WebHook. What do I need to adjust?

Edit: I access the logger like this:

```<code>public static ILog Log = LogManager.GetLogger(typeof(BroadcastService));

public object Get(ConnectionTest request) {
    Log.Info(String.Format("Info Logged: {0}", DateTime.Now.ToShortTimeString()));
    // ...
}
</code>```

答:
When using the ServiceStack Slack logger, to enable channel overrides, it needs to be used with an Incoming Web Hook.

https://api.slack.com/incoming-webhooks

As Slack API docs state, if the integration is trying to work with a Slack App, these overrides will be ignored.

Body:
I'm currently trying out ServiceStack Logging with Slack, and altough it seems to work, I can't change the channels and name of the bot. I think it might have something to do with my Slack configuration, but since I didn't really use Slack before, I'm not sure how to set it up.

My logging config looks like this:

public override void Configure(Funq.Container container)
{
    LogManager.LogFactory = new SlackLogFactory("https://hooks.slack.com/services/[...]", debugEnabled: true)
    {
        DefaultChannel = "logs",
        ErrorChannel = "errorlogs",
        BotUsername = "ServiceStack Logger"
    };

    SetConfig(new HostConfig
    {
        DefaultContentType = MimeTypes.Json
    });
}

So, the logging works, but the username is not set correctly (instead, it's the apps name) and it only posts to the channel I specified when creating the WebHook. What do I need to adjust?

Edit: I access the logger like this:

public static ILog Log = LogManager.GetLogger(typeof(BroadcastService));

public object Get(ConnectionTest request) {
    Log.Info(String.Format("Info Logged: {0}", DateTime.Now.ToShortTimeString()));
    // ...
}


问:
Bash Script (awk-sed-grep) to check whether numbers in every next line are 1 more than previous line
I have a file:

```<code>Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
...
...
Time= 12:40:41, value = 123456, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123457, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123458, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123459, data=2, data2=4,timeEnter=12:34:34
</code>```

I want to read this file using Cat | grep awk.
And want to be able to run a command using combination of these to check if every number in the 'value' section increased by 1 in every next line.
if this was not followed in any case I want to be able to see that point.

Till now: I am stuck at:
$ Cat FileName | awk -F "= " '{print $4}'

Thanks

答:
Perl solution:

```<code>perl -ne 'next unless /value = ([0-9]+)/;
          print "$.: $_" if 1 + $value != $1;
          $value = $1' -- file.name
</code>```

-n reads the input line by line

next skips processing the line if there's no value to check.

$value keeps the value from the previous line. If the captured value isn't equal to the old one plus one, the line number ($.) and the line ($_) are printed.

Body:
I have a file:

Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
...
...
Time= 12:40:41, value = 123456, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123457, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123458, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123459, data=2, data2=4,timeEnter=12:34:34

I want to read this file using Cat | grep awk.
And want to be able to run a command using combination of these to check if every number in the 'value' section increased by 1 in every next line.
if this was not followed in any case I want to be able to see that point.

Till now: I am stuck at:
$ Cat FileName | awk -F "= " '{print $4}'

Thanks

Body:
Perl solution:

perl -ne 'next unless /value = ([0-9]+)/;
          print "$.: $_" if 1 + $value != $1;
          $value = $1' -- file.name

-n reads the input line by line

next skips processing the line if there's no value to check.

$value keeps the value from the previous line. If the captured value isn't equal to the old one plus one, the line number ($.) and the line ($_) are printed.


答:
Have a look at this, see if its any good. This is the ms sql server approach, but hopefully similar enough to help.

```<code>DECLARE @Tbl AS TABLE (item CHAR(3)
                      ,count INT
                      ,date DATE
                      )
INSERT  INTO @Tbl
        (item, count, date)
VALUES  ('000', 10, '2017-11-01'),
        ('001', 15, '2017-11-01'),
        ('002', 2, '2017-11-01'),
        ('003', 100, '2017-11-01'),
        ('000', 20, '2017-11-02'),
        ('001', 20, '2017-11-02'),
        ('002', 22, '2017-11-02'),
        ('003', 101, '2017-11-02'),
        ('000', 30, '2017-11-03'),
        ('001', 25, '2017-11-03'),
        ('002', 42, '2017-11-03'),
        ('003', 102, '2017-11-03'),
        ('000', 40, '2017-11-04'),
        ('001', 30, '2017-11-04'),
        ('002', 62, '2017-11-04'),
        ('003', 103, '2017-11-04');
WITH    cte
          AS (SELECT    *
              ,         ROW_NUMBER() OVER (PARTITION BY item ORDER BY date) RN
              FROM      @Tbl
             )
    SELECT  A.item
     ,      A.count
     ,      A.date
     ,      C.Cume
    FROM    cte A
    CROSS APPLY (SELECT SUM(count) Cume
                 FROM   cte B
                 WHERE  A.item = B.item
                        AND A.RN >= B.RN
                ) C
</code>```

This is a generic example of how to get cume totals against your data.  Adding date ranges in should be simple enough. Using the row number technique you can replace the sum of previous to be difference from previous.

If your still stuck after looking through this, then let me know and I can code that up too, but better if you can understand whats been done here and apply your own solution.

Title: MySQL: Any good way to get cumulative counts and diff counts?

Body:
Suppose I have the following dataset.

+--------------------+
| item_id count date |
+--------------------+
| 000 10 2017-11-01  |
| 001 15 2017-11-01  |
| 002 2 2017-11-01   |
| 003 100 2017-11-01 |
| 000 20 2017-11-02  |
| 001 20 2017-11-02  |
| 002 22 2017-11-02  |
| 003 101 2017-11-02 |
| 000 30 2017-11-03  |
| 001 25 2017-11-03  |
| 002 42 2017-11-03  |
| 003 102 2017-11-03 |
| 000 40 2017-11-04  |
| 001 30 2017-11-04  |
| 002 62 2017-11-04  |
| 003 103 2017-11-04 |
+--------------------+

Is there any way to get cumulative counts and diff counts for each day between two arbitrary dates?

(As for the diff counts, if the selected dates are 2017-11-01 and 2017-11-04, the first diff count(2017-11-01) does not have to be included in the final SQL result as there is no data available before that date)

The following two tables are the expected SQL result.

Cumulative Counts

+--------------------+
| item_id count date |
+--------------------+
| 000 10 2017-11-01  |
| 000 30 2017-11-02  |
| 000 60 2017-11-03  |
| 000 100 2017-11-03 |
| 001 15 2017-11-01  |
| 001 35 2017-11-02  |
| 001 60 2017-11-03  |
| 001 90 2017-11-04  |
| 002 2 2017-11-01   |
| 002 24 2017-11-02  |
| 002 66 2017-11-03  |
| 002 128 2017-11-04 |
| 003 100 2017-11-01 |
| 003 201 2017-11-02 |
| 003 303 2017-11-03 |
| 003 406 2017-11-04 |
+--------------------+

Diff Counts

+--------------------+
| item_id count date |
+--------------------+
| 000 10 2017-11-02  |
| 000 10 2017-11-03  |
| 000 10 2017-11-04  |
| 001 5 2017-11-02   |
| 001 5 2017-11-03   |
| 001 5 2017-11-04   |
| 002 20 2017-11-02  |
| 002 20 2017-11-03  |
| 002 20 2017-11-04  |
| 003 1 2017-11-02   |
| 003 1 2017-11-03   |
| 003 1 2017-11-04   |
+--------------------+

Body:
Have a look at this, see if its any good. This is the ms sql server approach, but hopefully similar enough to help.

DECLARE @Tbl AS TABLE (item CHAR(3)
                      ,count INT
                      ,date DATE
                      )
INSERT  INTO @Tbl
        (item, count, date)
VALUES  ('000', 10, '2017-11-01'),
        ('001', 15, '2017-11-01'),
        ('002', 2, '2017-11-01'),
        ('003', 100, '2017-11-01'),
        ('000', 20, '2017-11-02'),
        ('001', 20, '2017-11-02'),
        ('002', 22, '2017-11-02'),
        ('003', 101, '2017-11-02'),
        ('000', 30, '2017-11-03'),
        ('001', 25, '2017-11-03'),
        ('002', 42, '2017-11-03'),
        ('003', 102, '2017-11-03'),
        ('000', 40, '2017-11-04'),
        ('001', 30, '2017-11-04'),
        ('002', 62, '2017-11-04'),
        ('003', 103, '2017-11-04');
WITH    cte
          AS (SELECT    *
              ,         ROW_NUMBER() OVER (PARTITION BY item ORDER BY date) RN
              FROM      @Tbl
             )
    SELECT  A.item
     ,      A.count
     ,      A.date
     ,      C.Cume
    FROM    cte A
    CROSS APPLY (SELECT SUM(count) Cume
                 FROM   cte B
                 WHERE  A.item = B.item
                        AND A.RN >= B.RN
                ) C

This is a generic example of how to get cume totals against your data.  Adding date ranges in should be simple enough. Using the row number technique you can replace the sum of previous to be difference from previous.

If your still stuck after looking through this, then let me know and I can code that up too, but better if you can understand whats been done here and apply your own solution.


问:
PHP set value to php variable if variable store in database table
This is my Code

```<code>table_query
id query
1  SELECT * FROM TABLE WHERE date = "$loc_date"

 <?php
$q1 = 'SELECT query FROM table_query WHERE 1 LIMIT 1';
$result = execute q1;
$query = $result['query'];
    $loc_date = '2017-12-06';
    $loc_query = $query; //This query fetch from table. Not directly write on file
    execute query here
    ?>
</code>```

But I don't get any result after executing query.

答:
You can try this one :)

```<code>//creates database connection
$connection=mysql_connect("localhost","root","");
//selects database connection
$database_select=mysql_select_db("your_database_name",$connection);

//put the entered date to loc_date variable
$loc_date='2017-12-06';

//select * date with 2017-12-06 on table_query but would display only 1   since theres a LIMIT
$query1=mysql_query("select * from table_query WHERE date='$loc_date' LIMIT 1");
while($loc_query=mysql_fetch_array($query1)){
echo $loc_query['date']; //prints the date - 2017-12-06 if present
}
</code>```

I think you want to display the date which is '2017-12-06' on your table_query. But since you want to limit the record to be displayed to 1, so only one(1) date which is 2017-12-06 would be displayed on that code. If theres more than 1 record(date:2017-12-06) saved on that table, you can remove the "LIMIT 1" on mysql query so that it will display all.

Body:
This is my Code

table_query
id query
1  SELECT * FROM TABLE WHERE date = "$loc_date"

 <?php
$q1 = 'SELECT query FROM table_query WHERE 1 LIMIT 1';
$result = execute q1;
$query = $result['query'];
    $loc_date = '2017-12-06';
    $loc_query = $query; //This query fetch from table. Not directly write on file
    execute query here
    ?>

But I don't get any result after executing query.

Body:
You can try this one :)

//creates database connection
$connection=mysql_connect("localhost","root","");
//selects database connection
$database_select=mysql_select_db("your_database_name",$connection);

//put the entered date to loc_date variable
$loc_date='2017-12-06';

//select * date with 2017-12-06 on table_query but would display only 1   since theres a LIMIT
$query1=mysql_query("select * from table_query WHERE date='$loc_date' LIMIT 1");
while($loc_query=mysql_fetch_array($query1)){
echo $loc_query['date']; //prints the date - 2017-12-06 if present
}

I think you want to display the date which is '2017-12-06' on your table_query. But since you want to limit the record to be displayed to 1, so only one(1) date which is 2017-12-06 would be displayed on that code. If theres more than 1 record(date:2017-12-06) saved on that table, you can remove the "LIMIT 1" on mysql query so that it will display all.


问:
C++ method overloading: base and derived parameters
After searching around the web I did not manage to find an answer to this question:

I have this overloaded method:

```<code>foo(Base* base);
foo(Derived* derived);
</code>```

In this case "Derived" is a subclass of "Base".

When I call:

```<code>foo(new Derived());
</code>```

I notice that always the first overloaded method is called, while I would like to achieve the opposite result (call the method which takes a "Derived*" object as a parameter).

How to solve this? Thank you.

EDIT:

Ok, this is my actual situation:

I have an UIWidget and a UIScoreLabel class. UIScoreLabel derives from UIWidget. I also have a GameEvent class (Base) and a P1ScoreGameEvent class (Derived).

UIWidget:

```<code>virtual void handleGameEvent(GameEvent* e) { printf("ui_widget"); }
</code>```

UIScoreLabel:

```<code>virtual void handleGameEvent(P1ScoreGameEvent* e) { printf("ui_score_label"); }
</code>```

This is the call:

```<code>UIWidget* scoreLabel = new UIScoreLabel();
scoreLabel.handleGameEvent(new P1ScoreGameEvent());
</code>```

Output:

```<code>ui_widget
</code>```

I don't understand what I'm doing wrong.

答:
This is because C++ does not support double dispatch. If you declare your variable as Base, it will be treated so. Once you changed its type to Derived, the compiler was able to get its real type and then call the correct method.

To solve this problem you may want to use a Visitor Pattern.

There's a nice discussion about this in this answer.

Body:
After searching around the web I did not manage to find an answer to this question:

I have this overloaded method:

foo(Base* base);
foo(Derived* derived);

In this case "Derived" is a subclass of "Base".

When I call:

foo(new Derived());

I notice that always the first overloaded method is called, while I would like to achieve the opposite result (call the method which takes a "Derived*" object as a parameter).

How to solve this? Thank you.

EDIT:

Ok, this is my actual situation:

I have an UIWidget and a UIScoreLabel class. UIScoreLabel derives from UIWidget. I also have a GameEvent class (Base) and a P1ScoreGameEvent class (Derived).

UIWidget:

virtual void handleGameEvent(GameEvent* e) { printf("ui_widget"); }

UIScoreLabel:

virtual void handleGameEvent(P1ScoreGameEvent* e) { printf("ui_score_label"); }

This is the call:

UIWidget* scoreLabel = new UIScoreLabel();
scoreLabel.handleGameEvent(new P1ScoreGameEvent());

Output:

ui_widget

I don't understand what I'm doing wrong.


问:
AngularJS: Escape HTML in input fields
What is the best way to escape HTML in the input field? For example, I've search input field

```<code><input id="search" type="text" ng-model="search" placeholder="search...">
</code>```

And I want to escape if somebody types something like this:

```<code><script>alert("test123");</script>
</code>```

答:
You could use lodash  <code>_.escape([string=''])</code>. This is a easy and simple solution. </p>

```<code>_.escape($scope.search);
</code>```

Title: AngularJS: Escape HTML in input fields

Body:
What is the best way to escape HTML in the input field? For example, I've search input field

<input id="search" type="text" ng-model="search" placeholder="search...">

And I want to escape if somebody types something like this:

Body:
You could use lodash  _.escape([string='']). This is a easy and simple solution.

_.escape($scope.search);


问:
Wordpress Sort Posts By Category
I'm outputting all posts in date order and want to add a few buttons that'll allow the user sort them via category.

The two categories I have are "Events" and "News". I'd like the user to be able to click an "Events" button, and have all post disappear other than Events posts, as well as one for "News" and one for "All".

Looking for a code solution over a plugin. Cheers.

答:
```<code>    <div class="filter-dropdown">
      <?php $args = array('type' => 'CUSTOM_POST_TYPE','orderby' => 'name','order' => 'ASC','taxonomy' => 'TAXONOMY_NAME' ); ?>
      <?php $terms = get_terms( array( 'taxonomy' => 'TAXONOMY_NAME', 'parent'   => 0 ) );
      $allcats = array();
      ?>
<!-- Nav Tabs -->
    <ul class="nav nav-tabs" role="tablist">
              <li class="active" role="presentation">
                <a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab" aria-expanded="true">ALL</a>
              </li>
      <?php  $i=1;
        $class='';
          foreach ($terms as $category) {
            if ($category->category_parent == 0 && $category->slug != 'all') {
              $i++;
                array_push($allcats,$category->slug);
                  echo '<li role="presentation" class=""><a href="#tab'.$i.'" aria-controls="tab'.$i.'" role="tab" data-toggle="tab">'.$category->name.'</a></li>';
            }
          }
      ?>
    </ul>
<!-- -->
    </div>

    <div class="tab-content">
      <?php $post_type = 'CUSTOM_POST_TYPE'; $taxonomy = 'TAXONOMY_NAME'; ?>
<!-- Code to Display All Posts -->
        <div id="tab1" class="tab-pane fade active in" role="tabpanel">
          <div class="row">
            <?php $args = array( 'post_type' => $post_type, 'posts_per_page' => -1, 'tax_query' => array(array('taxonomy' => $taxonomy, 'field'    => 'slug', 'terms'    => $allcats, 'include_children' => false, ),),);
              $posts = new WP_Query($args);
              $j = 0;
                if( $posts->have_posts() ){
                  while( $posts->have_posts() ) {
                    $posts->the_post();
                      $image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' ); ?>
                      <div class="col-sm-6 col-xs-6">
                        <div class="tab_pic">
                          <img src="<?php echo $image[0]; ?>" alt="" />
                          <a href="<?php the_permalink(); ?>" class="tab_hover">
                            <span class="inner_txt"><?php the_title(); ?></span>
                          </a>
                        </div>
                      </div>
                  <?php }
                }
            wp_reset_query(); ?>
          </div>
        </div>
<!-- -->
        <?php $i=1; $class='';
          foreach( $allcats as $cats ) {
            $postcat= $category->cat_ID; $i++; ?>
              <div role="tabpanel" class="tab-pane fade" id="tab<?php echo $i; ?>">
                <div class="row">
                  <?php $args = array( 'post_type' => $post_type, 'posts_per_page' => -1, 'tax_query' => array(array('taxonomy' => $taxonomy,'field' => 'slug', 'terms' => $cats, 'include_children' => false,) ) );
                    $posts = new WP_Query($args); if( $posts->have_posts() ){ while( $posts->have_posts() ) { $posts->the_post();
                    $image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' ); ?>
                      <div class="col-sm-6 col-xs-6">
                        <div class="tab_pic">
                          <img src="<?php echo $image[0]; ?>" alt="" />
                          <a href="<?php the_permalink(); ?>" class="tab_hover">
                            <span class="inner_txt"><?php the_title(); ?></span>
                          </a>
                        </div>
                      </div>
                  <?php } } wp_reset_query(); ?>
                </div>
              </div>
              <?php } ?>
            </div>
</code>```

Title: Wordpress Sort Posts By Category


问:
JavaScript Object vs minimongo efficiency
My Meteor client receives data from the server and stores it in minimongo. This data is guaranteed not to change during their session, so I don't need Meteor's reactivity. The static data just happens to arrive by that route; let's just take that as a given.

The data looks like this:

```<code>{_id: 'abc...', val: {...}}
</code>```

On the client, is it more efficient for me to look up values using:

```<code>val_I_need = Collection.findOne({id})
</code>```

or to create a JavaScript object:

```<code>data = {}
Collection.find().fetch().map((x) => {data[x._id] = x.val})
</code>```

and use it for look ups:

```<code>val_I_need = data[id]
</code>```

Is there a tipping point, either in terms of the size of the data or the number of look ups, where the more efficient method changes, or outweighs the initial cost of building the object?

答:
FindOne may be more efficient on larger datasets because it looks up using cursors where _id is an indexed key while your find().fetch() approach requires to get all docs and then iterate manually by mapping.

Note, that findOne could also be replaced by .find({_id:desiredId}).fetch()[0](assuming it returns the desired doc).

More on this in the mongo documentation on query performance.

However, if it concerns only one object that is afterwards not reactively tracked, I would rather load it via a "findOne"-returning method from the server:

export const getOne = new ValidatedMethod({
    name: "getOne",
    validate(query) {
        // validate query schema
        // ...
    },
    run(query) {

        // CHECK PERMISSIONS
        // ...

        return MyCollection.findOne(query);
});
```

This avoids using publications / subscriptions and thus minimongo for this collection on the current client template. Think about that pub/sub has already some reactivity initialized to observe the collection and thus eats up some computation somewhere.

Body:
My Meteor client receives data from the server and stores it in minimongo. This data is guaranteed not to change during their session, so I don't need Meteor's reactivity. The static data just happens to arrive by that route; let's just take that as a given.

The data looks like this:

{_id: 'abc...', val: {...}}

On the client, is it more efficient for me to look up values using:

val_I_need = Collection.findOne({id})

or to create a JavaScript object:

data = {}
Collection.find().fetch().map((x) => {data[x._id] = x.val})

and use it for look ups:

val_I_need = data[id]

Is there a tipping point, either in terms of the size of the data or the number of look ups, where the more efficient method changes, or outweighs the initial cost of building the object?

Body:
FindOne may be more efficient on larger datasets because it looks up using cursors where _id is an indexed key while your find().fetch() approach requires to get all docs and then iterate manually by mapping.

Note, that findOne could also be replaced by .find({_id:desiredId}).fetch()[0](assuming it returns the desired doc).

More on this in the mongo documentation on query performance.

However, if it concerns only one object that is afterwards not reactively tracked, I would rather load it via a "findOne"-returning method from the server:

export const getOne = new ValidatedMethod({
    name: "getOne",
    validate(query) {
        // validate query schema
        // ...
    },
    run(query) {

        // CHECK PERMISSIONS
        // ...

        return MyCollection.findOne(query);
});

This avoids using publications / subscriptions and thus minimongo for this collection on the current client template. Think about that pub/sub has already some reactivity initialized to observe the collection and thus eats up some computation somewhere.


问:
Not able to install @angular/cli using npm
I am new to "@angular/cli", I have tried every thing but could not install.
I am tired now please some one can help me to install angular 4 "@angular/cli" in my system.

node and npm Version

and when I am installing "npm install -g @angular/cli" then getting

after installing node -v 6 I am getting below erorr

please suggest me where actually I am wrong.

答:
It could be issue with your node version. I will suggest you to reinstall node and try it again.

Or you can also try to clean node cache of using npm cache clean --force


问:
how to call a method from one controller to another controller in Objective-C

Hello everyone, I am a beginner in Mac OS Developer. I have a problem when calling a method in a controller named Controller1.

Here is my code for Controller1:

Controller1.h

```<code>#import <Cocoa/Cocoa.h>

@interface Controller1 : NSViewController

- (void)LoadViewActiveCall;

@end
</code>```

Controller1.m

```<code>#import "Controller1.h"
@implementation Controller1

- (void)showCallViewController:(NSViewController*)target_viewcontroller2{
    NSLog(@"Run method showCallViewController");
    NSLog(@"Parameter targe view controller 2 : %@",target_viewcontroller2);
    if(current_controller2!=nil){
        [current_controller2.view removeFromSuperview];
        [current_controller2 removeFromParentViewController];
    }
    [self addChildViewController:target_viewcontroller2];
    target_viewcontroller2.view.frame=container_Call.frame;
    [container_Call addSubview:target_viewcontroller2.view];
    current_controller2=target_viewcontroller2;
}

- (void)LoadViewActiveCall {
    [self showCallViewController:vCall];
    NSLog(@"keluar active call berhasil");
}

@end
</code>```

I want call LoadViewActiveCall method on button IBAction of Controller2

Controller2.h

```<code>#import <Cocoa/Cocoa.h>
#import "Controller1.h"

@interface Controller2 : NSViewController

- (IBAction)audioCall:(id)sender;

@end
</code>```

Controller2.m

```<code>#import "Controller1.h"
#import "Controller2.h"

@implementation Controller2

- (IBAction)audioCall:(id)sender {
    Controller1 *co1 = [[Controller1 alloc] init];
    [co1 LoadViewActiveCall];
}

@end
</code>```

My problem is when I press audioCall button, but LoadViewActiveCall method is not being called.

I am sorry for my bad english

答:
Add NSNotificationCenter to call a method.

```<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioCall:) name:@"notificationName" object:nil];

-(void) audioCall:(NSNotification*)notification
{
}
</code>```

post the notification from the second view controller as below.

```<code>[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:obj];
</code>```

Body:
Hello everyone, I am a beginner in Mac OS Developer. I have a problem when calling a method in a controller named Controller1.

Here is my code for Controller1:

Controller1.h

#import <Cocoa/Cocoa.h>

@interface Controller1 : NSViewController

- (void)LoadViewActiveCall;

@end

Controller1.m

#import "Controller1.h"
@implementation Controller1

- (void)showCallViewController:(NSViewController*)target_viewcontroller2{
    NSLog(@"Run method showCallViewController");
    NSLog(@"Parameter targe view controller 2 : %@",target_viewcontroller2);
    if(current_controller2!=nil){
        [current_controller2.view removeFromSuperview];
        [current_controller2 removeFromParentViewController];
    }
    [self addChildViewController:target_viewcontroller2];
    target_viewcontroller2.view.frame=container_Call.frame;
    [container_Call addSubview:target_viewcontroller2.view];
    current_controller2=target_viewcontroller2;
}

- (void)LoadViewActiveCall {
    [self showCallViewController:vCall];
    NSLog(@"keluar active call berhasil");
}

@end

I want call LoadViewActiveCall method on button IBAction of Controller2

Controller2.h

#import <Cocoa/Cocoa.h>
#import "Controller1.h"

@interface Controller2 : NSViewController

- (IBAction)audioCall:(id)sender;

@end

Controller2.m

#import "Controller1.h"
#import "Controller2.h"

@implementation Controller2

- (IBAction)audioCall:(id)sender {
    Controller1 *co1 = [[Controller1 alloc] init];
    [co1 LoadViewActiveCall];
}

@end

My problem is when I press audioCall button, but LoadViewActiveCall method is not being called.

I am sorry for my bad english

Body:
Add NSNotificationCenter to call a method.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioCall:) name:@"notificationName" object:nil];

-(void) audioCall:(NSNotification*)notification
{
}

post the notification from the second view controller as below.

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:obj];


问:
How to pass data from asp.NET MVC to Angular2
What is the best way to pass data from an ASP.NET MVC controller to an Angular 2.0 component? For example, we use the ASP.NET MVC Model and would like to send a JSON version of it to Angular to use it in Angular.

When the controller is serving the view, we can already push some data to Angular2 (the model). So additional AJAX call to fetch that data is not required.

However, I am struggling to "inject" it into the Angular component. How do you do this? Any good references for this? As you may have noticed, I'm quite new to Angular2.

My index.cshtml looks like this.

```<code><div class="container">
<div>
    <h1>Welcome to the Angular 2 components!</h1>
</div>
<div class="row">
    <MyAngular2Component>
        <div class="alert alert-info" role="alert">
            <h3>Loading...</h3>
        </div>
    </MyAngular2Component>
</div>
</div>
</code>```

Kind regards,

Rob

答:
I found a much simpler solution. Don't attempt to get the attribute from in the constructor! Use the ngOnInit() hook instead. The property will be accessible as long as it has been decorated with @Input(). It just appears that it is not available by the time the constructor is called.

Component HTML:

```<code><MyComponent [CustomAttribute]="hello"></MyComponent>
</code>```

Component TS:

```<code>export class MyComponentComponent {
    @Input()
    public CustomAttribute: string;

    constructor() {}

    ngOnInit() {
        console.log("Got it! " + this.CustomAttribute);
    }
}
</code>```

Body:
What is the best way to pass data from an ASP.NET MVC controller to an Angular 2.0 component? For example, we use the ASP.NET MVC Model and would like to send a JSON version of it to Angular to use it in Angular.

When the controller is serving the view, we can already push some data to Angular2 (the model). So additional AJAX call to fetch that data is not required.

However, I am struggling to "inject" it into the Angular component. How do you do this? Any good references for this? As you may have noticed, I'm quite new to Angular2.

My index.cshtml looks like this.

Welcome to the Angular 2 components!

    <MyAngular2Component>

Loading...

    </MyAngular2Component>

Kind regards,

Rob

Body:
I found a much simpler solution. Don't attempt to get the attribute from in the constructor! Use the ngOnInit() hook instead. The property will be accessible as long as it has been decorated with @Input(). It just appears that it is not available by the time the constructor is called.

Component HTML:

<MyComponent [CustomAttribute]="hello"></MyComponent>

Component TS:

export class MyComponentComponent {
    @Input()
    public CustomAttribute: string;

    constructor() {}

    ngOnInit() {
        console.log("Got it! " + this.CustomAttribute);
    }
}


问:
How do i add a Jackson custom deserialiser of a list to a module?
I have a custom deserializer

```<code>class MyListDeserialiser extends JsonDeserializer<List<MyObject>>{

@Override
public List< MyObject > deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {

 ....
    return myListOfObjects; }
</code>```

}

then i need to add this to a Jackson mapper module

I tried

```<code>public class MyModule extends SimpleModule {

public MyModule() {
    super(new Version(1, 0, 0, "", null, null));
    addDeserializer(TypeFactory.defaultInstance().constructCollectionType(List.class, MyObject.class).getClass(),
            new MyListDeserialiser());
}
</code>```

But that did not work.

Is TypeFactory the right way or is the problem with the deserialiser definition ?

I don't want to use annotations so this is the only other method i know. I don't want to add the functionality directly to the object mapper since i will have a lot of custom deserialisations and i want to keep all that code hidden away in a module.

Thanks in advance

答: You need to add your module to a mapper, otherwise it won't be used for (de)serialization.</p>

Body:
I have a custom deserializer

class MyListDeserialiser extends JsonDeserializer<List<MyObject>>{

@Override
public List< MyObject > deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {

 ....
    return myListOfObjects; }

}

then i need to add this to a Jackson mapper module

I tried

public class MyModule extends SimpleModule {

public MyModule() {
    super(new Version(1, 0, 0, "", null, null));
    addDeserializer(TypeFactory.defaultInstance().constructCollectionType(List.class, MyObject.class).getClass(),
            new MyListDeserialiser());
}

But that did not work.

Is TypeFactory the right way or is the problem with the deserialiser definition ?

I don't want to use annotations so this is the only other method i know. I don't want to add the functionality directly to the object mapper since i will have a lot of custom deserialisations and i want to keep all that code hidden away in a module.

Thanks in advance


问:
Check boxes bottom border is not visible in internet explorer

Check boxes are working fine in chrome but not in internet explorer.

Here is my HTML code:

```<code><div class="patient-div-w" style="width: 9.5vw;">
  <input type="checkbox" id="edema" class="input-checkbox-l">
  <label class="label-n" for="edema" style="line-height: 8vh;">Edema</label>
  <br>
</div>
</code>```

Here is my CSS code:

```<code>input[type="checkbox"] {
    opacity: 0;
    margin: 0px 3px 0px 0px;
}

.input-checkbox-l[type="checkbox"] + label {
    background-image: url(../images/unchk.png);
    background-size: 1.2vw;
    background-repeat: no-repeat;
    padding-left: 1.7vw;
    background-position: 0vh 0vw;
    width: 8vw;
    margin: 0vw;
    position: relative;
    top: -.1vh;
    left: -1.6vw;
    white-space: nowrap;
    font-family: "Roboto Regular";
}

.label-n {
    font-size: 1vw;
    color: #000;
}
</code>```

The same is the problem with radio buttons.
Any kind of help is highly appreciated.

答:
Try this
In your code

Edema Just remove inline style="line-height:8vh;. it will work.

you can use below code as a reference and it will work IE, FF, Chrome

```<code>.input-checkbox-l[type="checkbox"] + label {
  box-sizing:border-box;
  padding:0px 20px 0px 55px;
  background:url(https://i.stack.imgur.com/EAkMC.png) no-repeat center left 5px;
  background-size: 30px;
  font-size:22px;
  margin-right:5px;
  display:inline-block;
}
</code>```

You can try without image

```<code>input[type="checkbox"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  width: 20px;
  height: 20px;
  background-color: #fff;
  border: 1px solid #ccc;
  cursor: pointer;
  outline: none;
}

input[type="checkbox"]:checked {
 border:1px solid blue;
  outline: none;

}

div{
  display: inline-block;
}

div span{
vertical-align: super;
}
</code>```

HTML

```<code><div>
<input  type="checkbox" name="" value="1"><span>Label name</span>
</div>
</code>```

Body:
Check boxes are working fine in chrome but not in internet explorer.

Here is my HTML code:

  <input type="checkbox" id="edema" class="input-checkbox-l">
  Edema

Here is my CSS code:

input[type="checkbox"] {
    opacity: 0;
    margin: 0px 3px 0px 0px;
}

.input-checkbox-l[type="checkbox"] + label {
    background-image: url(../images/unchk.png);
    background-size: 1.2vw;
    background-repeat: no-repeat;
    padding-left: 1.7vw;
    background-position: 0vh 0vw;
    width: 8vw;
    margin: 0vw;
    position: relative;
    top: -.1vh;
    left: -1.6vw;
    white-space: nowrap;
    font-family: "Roboto Regular";
}

.label-n {
    font-size: 1vw;
    color: #000;
}

The same is the problem with radio buttons.
Any kind of help is highly appreciated.

Body:
Try this
In your code

<label class="label-n" for="edema" style="line-height: 8vh;">Edema</label> Just remove inline style="line-height:8vh;. it will work.

you can use below code as a reference and it will work IE, FF, Chrome

.input-checkbox-l[type="checkbox"] + label {
  box-sizing:border-box;
  padding:0px 20px 0px 55px;
  background:url(https://i.stack.imgur.com/EAkMC.png) no-repeat center left 5px;
  background-size: 30px;
  font-size:22px;
  margin-right:5px;
  display:inline-block;
}

You can try without image

input[type="checkbox"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  width: 20px;
  height: 20px;
  background-color: #fff;
  border: 1px solid #ccc;
  cursor: pointer;
  outline: none;
}

input[type="checkbox"]:checked {
 border:1px solid blue;
  outline: none;

}

div{
  display: inline-block;
}

div span{
vertical-align: super;
}

HTML

<div>
<input  type="checkbox" name="" value="1"><span>Label name</span>
</div>


问:
Docker Notary doesn't find Yubikey
I'm running Ubuntu 16 LTS with docker, Notary 0.4.3 and yubico-piv-tool 1.5.0
The piv tool works with the yubokey, can create certificates and also import them to the yubikey. Notary works okay as well, but it doesn't seem to notice the yubikey.

When downgrading to yubikey-piv-tools 1.4.0 I get the following panic report:
when installing yubico-piv-tool 1.4.0 I think NOtary fnds the key but panics out with the following report

```<code>fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x0]

runtime stack:
runtime.throw(0x99e364, 0x2a)
    /usr/local/go/src/runtime/panic.go:566 +0x95
runtime.sigpanic()
    /usr/local/go/src/runtime/sigpanic_unix.go:12 +0x2cc

goroutine 1 [syscall, locked to thread]:
runtime.cgocall(0x8012b0, 0xc420049e88, 0xc400000000)
    /usr/local/go/src/runtime/cgocall.go:131 +0x110 fp=0xc420049e58 sp=0xc420049e18
github.com/docker/notary/vendor/github.com/miekg/pkcs11._Cfunc_New(0x1cccfa0, 0x0)
    ??:0 +0x4a fp=0xc420049e88 sp=0xc420049e58
github.com/docker/notary/vendor/github.com/miekg/pkcs11.New(0x994909, 0x1b, 0x0)
    /go/src/github.com/docker/notary/vendor/github.com/miekg/pkcs11/pkcs11.go:755 +0xa1 fp=0xc420049ec8 sp=0xc420049e88
github.com/docker/notary/trustmanager/yubikey.init.1()
    /go/src/github.com/docker/notary/trustmanager/yubikey/yubikeystore.go:98 +0xb6 fp=0xc420049f30 sp=0xc420049ec8
github.com/docker/notary/trustmanager/yubikey.init()
    /go/src/github.com/docker/notary/trustmanager/yubikey/yubikeystore.go:915 +0x91 fp=0xc420049f38 sp=0xc420049f30
github.com/docker/notary/client.init()
    /go/src/github.com/docker/notary/client/witness.go:70 +0x9b fp=0xc420049f40 sp=0xc420049f38
main.init()
    /go/src/github.com/docker/notary/cmd/notary/util.go:55 +0x4b fp=0xc420049f48 sp=0xc420049f40
runtime.main()
    /usr/local/go/src/runtime/proc.go:172 +0x1bf fp=0xc420049fa0 sp=0xc420049f48
runtime.goexit()
    /usr/local/go/src/runtime/asm_amd64.s:2086 +0x1 fp=0xc420049fa8 sp=0xc420049fa0

goroutine 17 [syscall, locked to thread]:
runtime.goexit()
    /usr/local/go/src/runtime/asm_amd64.s:2086 +0x1
</code>```

答:
Build notary from Source fixes the issue.
go build -tags pkcs11

Title: Docker Notary doesn't find Yubikey

Body:
I'm running Ubuntu 16 LTS with docker, Notary 0.4.3 and yubico-piv-tool 1.5.0
The piv tool works with the yubokey, can create certificates and also import them to the yubikey. Notary works okay as well, but it doesn't seem to notice the yubikey.

When downgrading to yubikey-piv-tools 1.4.0 I get the following panic report:
when installing yubico-piv-tool 1.4.0 I think NOtary fnds the key but panics out with the following report

fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x0]

runtime stack:
runtime.throw(0x99e364, 0x2a)
    /usr/local/go/src/runtime/panic.go:566 +0x95
runtime.sigpanic()
    /usr/local/go/src/runtime/sigpanic_unix.go:12 +0x2cc

goroutine 1 [syscall, locked to thread]:
runtime.cgocall(0x8012b0, 0xc420049e88, 0xc400000000)
    /usr/local/go/src/runtime/cgocall.go:131 +0x110 fp=0xc420049e58 sp=0xc420049e18
github.com/docker/notary/vendor/github.com/miekg/pkcs11._Cfunc_New(0x1cccfa0, 0x0)
    ??:0 +0x4a fp=0xc420049e88 sp=0xc420049e58
github.com/docker/notary/vendor/github.com/miekg/pkcs11.New(0x994909, 0x1b, 0x0)
    /go/src/github.com/docker/notary/vendor/github.com/miekg/pkcs11/pkcs11.go:755 +0xa1 fp=0xc420049ec8 sp=0xc420049e88
github.com/docker/notary/trustmanager/yubikey.init.1()
    /go/src/github.com/docker/notary/trustmanager/yubikey/yubikeystore.go:98 +0xb6 fp=0xc420049f30 sp=0xc420049ec8
github.com/docker/notary/trustmanager/yubikey.init()
    /go/src/github.com/docker/notary/trustmanager/yubikey/yubikeystore.go:915 +0x91 fp=0xc420049f38 sp=0xc420049f30
github.com/docker/notary/client.init()
    /go/src/github.com/docker/notary/client/witness.go:70 +0x9b fp=0xc420049f40 sp=0xc420049f38
main.init()
    /go/src/github.com/docker/notary/cmd/notary/util.go:55 +0x4b fp=0xc420049f48 sp=0xc420049f40
runtime.main()
    /usr/local/go/src/runtime/proc.go:172 +0x1bf fp=0xc420049fa0 sp=0xc420049f48
runtime.goexit()
    /usr/local/go/src/runtime/asm_amd64.s:2086 +0x1 fp=0xc420049fa8 sp=0xc420049fa0

goroutine 17 [syscall, locked to thread]:
runtime.goexit()
    /usr/local/go/src/runtime/asm_amd64.s:2086 +0x1


问:
Guava cache not taking values from cache and refreshing for every call
I have created cache in my spark application, to refresh few values after every 6 hours.

The code looks as below.

```<code>val cachedList: Cache[String, String] = CacheBuilder.newBuilder()
    .maximumSize(10)
    .expireAfterWrite(refreshTimeInSeconds.toLong, TimeUnit.SECONDS)
    .build()
</code>```

This method gets the items and caches for me.

```<code>  def prepareUnfilteredAccountList(): Array[String] = {
    logger.info("Refreshing the UNFILTERED Accounts List from API")
    val unfilteredAccounts = apiService.getElementsToCache().get.map(_.accountNumber).toArray
    logger.trace("cached list has been refreshed New List is " +

    unfilteredAccounts
  }
</code>```

This method is used to get the cached values into list.

```<code>def getUnfilteredList(): Array[String] = {
    unfilteredAccounts.get("cached_list", new Callable[String]() {
      override def call(): String = {
        prepareUnfilteredAccountList().mkString(",")
      }
    }).split(",")
  }
</code>```

However, i observed that the cache is getting refreshed for every call, instead of getting refreshed after specified time period.

答:
First off, if you want to store a list or an array in a Cache you can do so, there's no need to convert it into a string and then split it back into an array.

Second, maximumSize() configures how many entries are in your cache - by the looks of it your cache only ever has one entry (your list), so specifying a maximum size is meaningless.

Third, if you're only trying to cache one value you might prefer the Suppliers.memoizeWithExperiation() API, which is simpler and less expensive than a Cache.

Fourth, in prepareUnfilteredAccountList() unfilteredAccounts appears to be an array, but in getUnfilteredList() the same variable appears to be a cache. At best this is going to be confusing for you to work with. Use distinct variable names for distinct purposes. It's possible this is the cause of your problems.

All that said calling Cache.get(K, Runnable) should work as you expect - it will invoke the Runnable only if the given key does not already exist in the the cache and has not expired. If that isn't the behavior you're seeing the bug is likely elsewhere in your code. Perhaps your refreshTimeInSeconds is not what you expect, or you're not actually reading the value you're caching, or the cache is actually working as intended and you're misdiagnosing its behavior as erroneous.

Body:
I have created cache in my spark application, to refresh few values after every 6 hours.

The code looks as below.

val cachedList: Cache[String, String] = CacheBuilder.newBuilder()
    .maximumSize(10)
    .expireAfterWrite(refreshTimeInSeconds.toLong, TimeUnit.SECONDS)
    .build()

This method gets the items and caches for me.

  def prepareUnfilteredAccountList(): Array[String] = {
    logger.info("Refreshing the UNFILTERED Accounts List from API")
    val unfilteredAccounts = apiService.getElementsToCache().get.map(_.accountNumber).toArray
    logger.trace("cached list has been refreshed New List is " +

    unfilteredAccounts
  }

This method is used to get the cached values into list.

def getUnfilteredList(): Array[String] = {
    unfilteredAccounts.get("cached_list", new Callable[String]() {
      override def call(): String = {
        prepareUnfilteredAccountList().mkString(",")
      }
    }).split(",")
  }

However, i observed that the cache is getting refreshed for every call, instead of getting refreshed after specified time period.


问:
Inject service into angular 1.5 component
I'm trying to initialize a test.service.js from an angular1.5 component and I don't really know how to that. I have used this structure for angular components:

```<code>var testComponent =  {
    templateUrl: "app/components/test.component.html",
    controllerAs: "mvm",
    bindings:{
        bindingInput: "=",
},
controller: function(){
      var mvm = this;

    }
};
angular.module('myApp').component('testComponent', testComponent);
</code>```

答:
You can inject the service right into the controller like this:

```<code>....
    controller: function(testService) {
      var mvm = this;
    }
};
</code>```

To prevent testService getting obfuscated by a minification plugin, let the injector service know about the dependencies as well.

```<code>var Controller = function(testService) {
   // Your controller code here
};

Controller.$inject = ['testService'];

var testComponent = {
  ...
  controller: Controller, // Assign controller in component
  ...
};
</code>```

Body:
I'm trying to initialize a test.service.js from an angular1.5 component and I don't really know how to that. I have used this structure for angular components:

var testComponent =  {
    templateUrl: "app/components/test.component.html",
    controllerAs: "mvm",
    bindings:{
        bindingInput: "=",
},
controller: function(){
      var mvm = this;

    }
};
angular.module('myApp').component('testComponent', testComponent);

Body:
You can inject the service right into the controller like this:

....
    controller: function(testService) {
      var mvm = this;
    }
};

To prevent testService getting obfuscated by a minification plugin, let the injector service know about the dependencies as well.

var Controller = function(testService) {
   // Your controller code here
};

Controller.$inject = ['testService'];

var testComponent = {
  ...
  controller: Controller, // Assign controller in component
  ...
};


问:
How to check divisibility of a number not in base 10 without converting?
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?

Update

The original problem is from TopCoder

The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.

Notes

-  When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.

Constraints

-  base is between 3 and 30, inclusive.

This is my solution:

```<code>class InterestingDigits {
public:
    vector<int> digits( int base ) {
        vector<int> temp;
        for( int i = 2; i <= base; ++i )
            if( base % i == 1 )
                temp.push_back( i );
        return temp;
    }
};
</code>```

The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit

Thanks,

Chan

答:
You can always build a finite automaton for any base and any divisor:

Normally to compute the value n of a string of digits in base b
you iterate over the digits and do

```<code>n = (n * b) + d
</code>```

for each digit d.

Now if you are interested in divisibility you do this modulo m instead:

```<code>n = ((n * b) + d) % m
</code>```

Here n can take at most m different values. Take these as states of a finite automaton, and compute the transitions depending on the digit d according to that formula.  The accepting state is the one where the remainder is 0.

For your specific case we have

```<code>n == 0, d == 0: n = ((0 * 3) + 0) % 2 = 0
n == 0, d == 1: n = ((0 * 3) + 1) % 2 = 1
n == 0, d == 2: n = ((0 * 3) + 2) % 2 = 0
n == 1, d == 0: n = ((1 * 3) + 0) % 2 = 1
n == 1, d == 1: n = ((1 * 3) + 1) % 2 = 0
n == 1, d == 2: n = ((1 * 3) + 2) % 2 = 1
</code>```

which shows that you can just sum the digits 1 modulo 2 and ignore any digits 0 or 2.

Body:
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?

Update

The original problem is from TopCoder

The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.

Notes

-  When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.

Constraints

-  base is between 3 and 30, inclusive.

This is my solution:

class InterestingDigits {
public:
    vector<int> digits( int base ) {
        vector<int> temp;
        for( int i = 2; i <= base; ++i )
            if( base % i == 1 )
                temp.push_back( i );
        return temp;
    }
};

The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit

Thanks,

Chan

Body:
You can always build a finite automaton for any base and any divisor:

Normally to compute the value n of a string of digits in base b
you iterate over the digits and do

n = (n * b) + d

for each digit d.

Now if you are interested in divisibility you do this modulo m instead:

n = ((n * b) + d) % m

Here n can take at most m different values. Take these as states of a finite automaton, and compute the transitions depending on the digit d according to that formula.  The accepting state is the one where the remainder is 0.

For your specific case we have

n == 0, d == 0: n = ((0 * 3) + 0) % 2 = 0
n == 0, d == 1: n = ((0 * 3) + 1) % 2 = 1
n == 0, d == 2: n = ((0 * 3) + 2) % 2 = 0
n == 1, d == 0: n = ((1 * 3) + 0) % 2 = 1
n == 1, d == 1: n = ((1 * 3) + 1) % 2 = 0
n == 1, d == 2: n = ((1 * 3) + 2) % 2 = 1

which shows that you can just sum the digits 1 modulo 2 and ignore any digits 0 or 2.


问:
Cross Client google oauth2.0 for android app with a backend server for offline access
I am developing an android app that fetches data from user's youtube account and needs to do so in offline mode also. For this i am supposed to implement google's oauth2.0 crossclient authentication (https://developers.google.com/+/mobile/android/sign-in#server-side_access_for_your_app) mechanism.
I am able to fetch the IdToken but for the one time exchange token (https://developers.google.com/accounts/docs/CrossClientAuth) it returns null.
Please help me out in this problem.
Thanks in advance...
Here is my code

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

import java.util.Arrays;
import java.util.List;

import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.accounts.AccountManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

final private String CLIENT_ID = "12345----.apps.googleusercontent.com";
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
private String mEmail;
//private static final String SCOPE =
  //      "oauth2:https://www.googleapis.com/auth/userinfo.profile";

final private List<String> SCOPES = Arrays.asList(new String[]{
          "https://www.googleapis.com/auth/plus.login",
          "https://www.googleapis.com/auth/youtube"});

 private EditText mExchangeCodeEditText;
  private EditText mIdTokenEditText;

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

     mExchangeCodeEditText = (EditText) findViewById(R.id.editTextExchangeCode);
        mIdTokenEditText = (EditText) findViewById(R.id.editTextIdToken);

Button b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

//      static final int REQUEST_CODE_PICK_ACCOUNT = 1000;

        String[] accountTypes = new String[]{"com.google"};
        Intent intent = AccountPicker.newChooseAccountIntent(null, null,
                accountTypes, false, null, null, null, null);
        startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
    }
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override   public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
        // Receiving a result from the AccountPicker
        if (resultCode == RESULT_OK) {
            mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            // With the account name acquired, go get the auth token
      //      getUsername();
            Log.v("MY_UNAME",mEmail);
            new RetrieveJwtAsyncTask().execute();
            new RetrieveExchangeCodeAsyncTask().execute();
        } else if (resultCode == RESULT_CANCELED) {
            // The account picker dialog closed without selecting an account.
            // Notify users that they must pick an account to proceed.
            Toast.makeText(this, R.string.pick_account, Toast.LENGTH_SHORT).show();
        }
    }
    // Later, more code will go here to handle the result from some exceptions...
}

 public class RetrieveJwtAsyncTask
 extends AsyncTask<Void, Boolean, String> {

   @Override
  protected String doInBackground(Void... params) {
  String scope = "audience:server:client_id:" + CLIENT_ID;
  try {
   return GoogleAuthUtil.getToken(
       MainActivity.this, mEmail, scope);
  } catch (Exception e) {
   e.printStackTrace(); // TODO: handle the exception
  }
  return null;
 }

  @Override
  protected void onPostExecute(String idToken) {
  // exchange encrypted idToken with server-side to identify the user
   mIdTokenEditText.setText(idToken);
  Log.v("Second One","  "+ idToken);

  }
 }

 public class RetrieveExchangeCodeAsyncTask
 extends AsyncTask<Void, Boolean, String> {

 @Override
 protected String doInBackground(Void... params) {
 String scope = String.format("oauth2:server:client_id:%s:api_scope:%s",
     CLIENT_ID, TextUtils.join(" ", SCOPES));
 try {
   return GoogleAuthUtil.getToken(
       MainActivity.this, mEmail, scope);

 } catch (Exception e) {
   e.printStackTrace(); // TODO: handle the exception
  }
 return null;
 }

 @Override
 protected void onPostExecute(String code) {
 // exchange code with server-side to retrieve an additional
 // access token on the server-side.
 Log.v("first One","1"+ code);
 mExchangeCodeEditText.setText(code);
  }
 }

}
</code>```

class RetrieveJwtAsyncTask runs fine but class RetrieveExchangeCodeAsyncTask returns null instead of one-time access code reffered to as "code" in the above snippet.

答: I had not registered my app properly in the developer console. After fixing it my problem was solved and the above code worked.</p>

Body:
I am developing an android app that fetches data from user's youtube account and needs to do so in offline mode also. For this i am supposed to implement google's oauth2.0 crossclient authentication (https://developers.google.com/+/mobile/android/sign-in#server-side_access_for_your_app) mechanism.
I am able to fetch the IdToken but for the one time exchange token (https://developers.google.com/accounts/docs/CrossClientAuth) it returns null.
Please help me out in this problem.
Thanks in advance...
Here is my code

package com.example.sampleapp;

import java.util.Arrays;
import java.util.List;

import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.accounts.AccountManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

final private String CLIENT_ID = "12345----.apps.googleusercontent.com";
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
private String mEmail;
//private static final String SCOPE =
  //      "oauth2:https://www.googleapis.com/auth/userinfo.profile";

final private List<String> SCOPES = Arrays.asList(new String[]{
          "https://www.googleapis.com/auth/plus.login",
          "https://www.googleapis.com/auth/youtube"});

 private EditText mExchangeCodeEditText;
  private EditText mIdTokenEditText;

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

     mExchangeCodeEditText = (EditText) findViewById(R.id.editTextExchangeCode);
        mIdTokenEditText = (EditText) findViewById(R.id.editTextIdToken);

Button b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

//      static final int REQUEST_CODE_PICK_ACCOUNT = 1000;

        String[] accountTypes = new String[]{"com.google"};
        Intent intent = AccountPicker.newChooseAccountIntent(null, null,
                accountTypes, false, null, null, null, null);
        startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
    }
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override   public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
        // Receiving a result from the AccountPicker
        if (resultCode == RESULT_OK) {
            mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            // With the account name acquired, go get the auth token
      //      getUsername();
            Log.v("MY_UNAME",mEmail);
            new RetrieveJwtAsyncTask().execute();
            new RetrieveExchangeCodeAsyncTask().execute();
        } else if (resultCode == RESULT_CANCELED) {
            // The account picker dialog closed without selecting an account.
            // Notify users that they must pick an account to proceed.
            Toast.makeText(this, R.string.pick_account, Toast.LENGTH_SHORT).show();
        }
    }
    // Later, more code will go here to handle the result from some exceptions...
}

 public class RetrieveJwtAsyncTask
 extends AsyncTask<Void, Boolean, String> {

   @Override
  protected String doInBackground(Void... params) {
  String scope = "audience:server:client_id:" + CLIENT_ID;
  try {
   return GoogleAuthUtil.getToken(
       MainActivity.this, mEmail, scope);
  } catch (Exception e) {
   e.printStackTrace(); // TODO: handle the exception
  }
  return null;
 }

  @Override
  protected void onPostExecute(String idToken) {
  // exchange encrypted idToken with server-side to identify the user
   mIdTokenEditText.setText(idToken);
  Log.v("Second One","  "+ idToken);

  }
 }

 public class RetrieveExchangeCodeAsyncTask
 extends AsyncTask<Void, Boolean, String> {

 @Override
 protected String doInBackground(Void... params) {
 String scope = String.format("oauth2:server:client_id:%s:api_scope:%s",
     CLIENT_ID, TextUtils.join(" ", SCOPES));
 try {
   return GoogleAuthUtil.getToken(
       MainActivity.this, mEmail, scope);

 } catch (Exception e) {
   e.printStackTrace(); // TODO: handle the exception
  }
 return null;
 }

 @Override
 protected void onPostExecute(String code) {
 // exchange code with server-side to retrieve an additional
 // access token on the server-side.
 Log.v("first One","1"+ code);
 mExchangeCodeEditText.setText(code);
  }
 }

}

class RetrieveJwtAsyncTask runs fine but class RetrieveExchangeCodeAsyncTask returns null instead of one-time access code reffered to as "code" in the above snippet.


问:
Which benefits Smarty gives when using with PHP or better to use pure PHP?
I am deciding if to use some template engine in php code or no.
Now I take close look to Smarty.

To be honest, it is not clear for me its benefits.

My impressions are not very good from the very beginning.
I tried to go through the demo application: http://www.smarty.net/sampleapp1. And from the very beginning I obtained notices . I fixed this by passing values to forms.
I changes the code from

```<code>// adding a guestbook entry
$guestbook->displayForm();
</code>```

to

```<code>// adding a guestbook entry
$guestbook->displayForm(array('Name' => '', 'Comment' => ''));
</code>```

While guessing this I understand that it complicates debugging the code.
And this also makes me to learn one more language - it is easy, but most easy is not to learn something new at all if there is no needed.
Alternative is to use PHP itself.

Syntax comparison  http://www.smarty.net/syntax_comparison is most funny for me: calculate number of symbols.... But I am familiar with PHP and this is easy for me to write on it, and Smarty is new for me. And I don't think that for Web Designers are so difficult to learn some simple php constructs, and Smarty is so simpler in this respect. If I am wrong it would be good to hear web designer here.

Smarty parses the code and this is in fact time overhead.

But at the same time many people use it. And that is why I would like to understand the reasons for this?
Where are the benefits? Am I missing something?

If you know good alternative to Smarty, it would be good to know about.
Thanks!

UPDATE:

I have found also the question on subject: How to use Smarty better with PHP?. In general it is also about not to use Smarty. But this is 1.5 years old. Possibly something changed?

答:
We extensively use Smarty.

I would say it is dis-advantageous
    in terms:

```<code>1. Parsing of smarty templates to PHP which make things slow
2. Your learning ablity to cope-up with smarty syntax.
</code>```

It is advantageous in the sense:

Separation of Business logic from the Presentational logic.

If you need display helpers, it would be helpful towards DRY principle. (Just like helpers in erb - ROR)

Unless your product is going to be a large and ongoing product and if things are possible with PHP, avoid using Smarty.

Body:
I am deciding if to use some template engine in php code or no.
Now I take close look to Smarty.

To be honest, it is not clear for me its benefits.

My impressions are not very good from the very beginning.
I tried to go through the demo application: http://www.smarty.net/sampleapp1. And from the very beginning I obtained notices . I fixed this by passing values to forms.
I changes the code from

// adding a guestbook entry
$guestbook->displayForm();

to

// adding a guestbook entry
$guestbook->displayForm(array('Name' => '', 'Comment' => ''));

While guessing this I understand that it complicates debugging the code.
And this also makes me to learn one more language - it is easy, but most easy is not to learn something new at all if there is no needed.
Alternative is to use PHP itself.

Syntax comparison  http://www.smarty.net/syntax_comparison is most funny for me: calculate number of symbols.... But I am familiar with PHP and this is easy for me to write on it, and Smarty is new for me. And I don't think that for Web Designers are so difficult to learn some simple php constructs, and Smarty is so simpler in this respect. If I am wrong it would be good to hear web designer here.

Smarty parses the code and this is in fact time overhead.

But at the same time many people use it. And that is why I would like to understand the reasons for this?
Where are the benefits? Am I missing something?

If you know good alternative to Smarty, it would be good to know about.
Thanks!

UPDATE:

I have found also the question on subject: How to use Smarty better with PHP?. In general it is also about not to use Smarty. But this is 1.5 years old. Possibly something changed?

Body:
We extensively use Smarty.

I would say it is dis-advantageous
    in terms:

1. Parsing of smarty templates to PHP which make things slow
2. Your learning ablity to cope-up with smarty syntax.

It is advantageous in the sense:

Separation of Business logic from the Presentational logic.

If you need display helpers, it would be helpful towards DRY principle. (Just like helpers in erb - ROR)

Unless your product is going to be a large and ongoing product and if things are possible with PHP, avoid using Smarty.


问:
Bash Script (awk-sed-grep) to check whether numbers in every next line are 1 more than previous line
I have a file:

```<code>Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
...
...
Time= 12:40:41, value = 123456, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123457, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123458, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123459, data=2, data2=4,timeEnter=12:34:34
</code>```

I want to read this file using Cat | grep awk.
And want to be able to run a command using combination of these to check if every number in the 'value' section increased by 1 in every next line.
if this was not followed in any case I want to be able to see that point.

Till now: I am stuck at:
$ Cat FileName | awk -F "= " '{print $4}'

Thanks

答:
Awk solution:

Sample input.txt:

```<code>Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 5, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 6, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 7, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 9, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 10, data=2, data2=4,timeEnter=12:34:34
</code>```

```<code>awk 'v && ($5-1)!=v{ printf "value %d is not followed by %d\n",v,v+1 }{ v=$5+0 }' input.txt
</code>```

v=$5+0 - capturing the current value (as a number)

v && ($5-1)!=v - if the current value number $5 is not next (increased by 1) relatively to the previous one v (the equivalent condition is v && $5+0!=v+1)

The output:

```<code>value 3 is not followed by 4
value 7 is not followed by 8
</code>```

Body:
I have a file:

Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
...
...
Time= 12:40:41, value = 123456, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123457, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123458, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123459, data=2, data2=4,timeEnter=12:34:34

I want to read this file using Cat | grep awk.
And want to be able to run a command using combination of these to check if every number in the 'value' section increased by 1 in every next line.
if this was not followed in any case I want to be able to see that point.

Till now: I am stuck at:
$ Cat FileName | awk -F "= " '{print $4}'

Thanks

Body:
Awk solution:

Sample input.txt:

Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 5, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 6, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 7, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 9, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 10, data=2, data2=4,timeEnter=12:34:34

awk 'v && ($5-1)!=v{ printf "value %d is not followed by %d\n",v,v+1 }{ v=$5+0 }' input.txt

v=$5+0 - capturing the current value (as a number)

v && ($5-1)!=v - if the current value number $5 is not next (increased by 1) relatively to the previous one v (the equivalent condition is v && $5+0!=v+1)

The output:

value 3 is not followed by 4
value 7 is not followed by 8