问:
Android FCM sending message to the user
I use FCM to send message to client (android), but I will have many client android and I want to send message to only one device not to everyone. How can I do this? Now when I send a message I send to everyone</p>

答:
send message to one device no to every one

When you register FCM from client app, you will receive a token for that device. You can pass it into server and save it there. Later you can use that specific device token to send FCM message to that device.

The code snippet which returns the FCM token is given below

```<code>      import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(refreshedToken);
    }
    // [END refresh_token]

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }
}
</code>```

see the official doc

Title: Android FCM sending message to the user

Body:
send message to one device no to every one

When you register FCM from client app, you will receive a token for that device. You can pass it into server and save it there. Later you can use that specific device token to send FCM message to that device.

The code snippet which returns the FCM token is given below

      import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(refreshedToken);
    }
    // [END refresh_token]

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }
}

see the official doc


来源: stackexchange

问:
Commit specific lines of a file to git

Possible Duplicate:

  How can I commit only part of a file in git

How do I commit a few specific line ranges from a file to git? while ignoring some other line changes in the same file.

答: Use git add -i to stage the lines then commit as normal, or use git-cola until you get used to the command line.

ContentLicense: CC BY-SA 2.5

Title: Commit specific lines of a file to git

ContentLicense: CC BY-SA 3.0


问:
add data attributes to <options> rendered by django form library
I have django choice field

The HTML rendered by django looks like this:

```<code><select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 <option value="query-action-take">Take</option>
 <option value="query-action-forward">Forward</option>
</select>
</code>```

Before executing the action which was choosen by the user, a confirmation should happen. But not all actions need a confirmation. In this example "delete" needs, but "take" does not need a confirmation.

I would like to add html data attributes the options

The result should look like this:

```<code><select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 <option value="query-action-take"   data-need-confirm="False">Take</option>
 <option value="query-action-delete" data-need-confirm="True">Delete</option>
</select>
</code>```

Up to now I found no way to inject the data "need confirmation" into individual choices.

... or am I on the wrong track here?

This question is only about "how to get the data into the html". The evaluation of the data (confirmation popup) is not part of this question.

答: You need to create a custom Widget for this. If you check out the Django docs for the Select widget (django.forms.Select), you will find a render_option() method. So best to subclass the default Select class and override this method.

Body:
I have django choice field

The HTML rendered by django looks like this:

<select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 <option value="query-action-take">Take</option>
 <option value="query-action-forward">Forward</option>
</select>

Before executing the action which was choosen by the user, a confirmation should happen. But not all actions need a confirmation. In this example "delete" needs, but "take" does not need a confirmation.

I would like to add html data attributes the options

The result should look like this:

<select id="id_action" name="action">
 <option value="" selected="selected">---</option>
 <option value="query-action-take"   data-need-confirm="False">Take</option>
 <option value="query-action-delete" data-need-confirm="True">Delete</option>
</select>

Up to now I found no way to inject the data "need confirmation" into individual choices.

... or am I on the wrong track here?

This question is only about "how to get the data into the html". The evaluation of the data (confirmation popup) is not part of this question.


问:
Is it right to create am html5 game with Canvas or custom html structure
I am trying to find out the best way of convering flash games into html5.

I built one game with custom html, css, js and had some issues with having the game fullscreen always on any desktop/mobile screen, audio issues on apple devices etc.

As far as i checked all html5 games are created with canvas. I am trying to understand if that is possible to create any type of flash game with canvas and avoid issues i had like to have the game fullscreen without any issues or custom coding, avoid audio issues.

Will it be possible to create any type of structure from flash game with the canvas?

I am new to Canvas so i need to know all pros and cons and see if the canvas performance will be better than the custom html one.

Also the game will have an API for the game logic so how easy it will be to integrate the game API with the canvas?

Mostly games are Slot machine games so i will need winning combinations logic, lots of animations.
Any help is apprecited.
Thanks.

答:
Notice that this snippet wont work on stackoverflow because it's nested in an iframe

Fullscreen is a standard feature with a rather wide support: https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen#Browser_compatibility

var c = document.body.appendChild(document.createElement("canvas"));
var ctx = c.getContext("2d");
c.width = window.outerWidth;
c.height = window.outerHeight;
ctx.textAlign = "center";
ctx.font = "120px Arial";
setInterval(function () {
    c.width = window.outerWidth;
    c.height = window.outerHeight;
    ctx.fillStyle = "rgba(" +
        (Math.floor(Math.random() * 255)) + "," +
        (Math.floor(Math.random() * 255)) + "," +
        (Math.floor(Math.random() * 255)) +
        ",0.5)";
    ctx.fillRect(Math.floor(Math.random() * c.width), Math.floor(Math.random() * c.height), Math.floor(Math.random() * c.width), Math.floor(Math.random() * c.height));
    ctx.fillStyle = "white";
    ctx.fillText("Click for fullscreen", Math.floor(c.width / 2), Math.floor(c.height / 2));
    ctx.strokeText("Click for fullscreen", Math.floor(c.width / 2), Math.floor(c.height / 2));
}, 1000 / 60);
c.onclick = function goFullScreen(evt) {
    if (c.requestFullscreen) {
        c.requestFullscreen();
    }
    else if (c.webkitRequestFullScreen) {
        c.webkitRequestFullScreen();
    }
    else if (c.mozRequestFullScreen) {
        c.mozRequestFullScreen();
    }
};```


问:
Calling php artisan db:seed does not work without providing a class name
I have a seeder class in the database folder

```<code>class UsersTableSeeder extends Seeder
{
    public function run()
    {
        $user = new User();
        $user->name         = 'Name';
        $user->email        = 'email@gmail.com';
        $user->password        = bcrypt('secret');
        $user->save();

    }
}
</code>```

When I run php artisan db:seed nothing happens, the seeder is only called when I run php artisan db:seed --class=UsersTableSeeder

This means I have to call each seeder class separately, any idea why db:seed doesn't work by it self?

答:
You need to add it to the DatabaseSeeder class:

```<code>public function run()
{
    $this->call(UsersTableSeeder::class);
}
</code>```

Body:
I have a seeder class in the database folder

class UsersTableSeeder extends Seeder
{
    public function run()
    {
        $user = new User();
        $user->name         = 'Name';
        $user->email        = 'email@gmail.com';
        $user->password        = bcrypt('secret');
        $user->save();

    }
}

When I run php artisan db:seed nothing happens, the seeder is only called when I run php artisan db:seed --class=UsersTableSeeder

This means I have to call each seeder class separately, any idea why db:seed doesn't work by it self?

Body:
You need to add it to the DatabaseSeeder class:

public function run()
{
    $this->call(UsersTableSeeder::class);
}


问:
is it possible to make nant run a publish on web application project
is it possible to make nant run a publish on mvc project or a good old web application project

and after the publish make nant FTP the files to the web server

UPDATE: found the solution to the ftp problem

Nant ftp task thanks Paco

what i mean by publich

is there a command line application or nant task that can public like visual studio publish...

答:
There is a Ftp Task for nant.
Beside that, you have to create a script that copies the files and directories you need and the config files. I don't do it automatically, because I want to have control over database update scripts and changes in web.config.</p>

OwnerDisplayName: Subnus

LastEditorDisplayName: Subnus

OwnerDisplayName: Paco


问:
How to access Session value from Angularjs.?
i wants to access session value from angular js.or set it in a text field.But its not working.

```<code><input type="text" id="uname" value="<%=session.getAttribute("username")%>" ng-model="username" readonly="readonly">
</code>```

when i  set the value of normal text field its working, like

```<code><input type="text" id="uname" value="<%=session.getAttribute("username")%>"  readonly="readonly">
</code>```

but after adding ng-model its not working.
How i will do this?Please anybody help me.

答:
It's angular's normal behavior. Try to use

  ng-value="'<%=session.getAttribute("username")%>'" which is better

or

ng-init="username = '<%=session.getAttribute("username")%>'"

Body:
i wants to access session value from angular js.or set it in a text field.But its not working.

<input type="text" id="uname" value="<%=session.getAttribute("username")%>" ng-model="username" readonly="readonly">

when i  set the value of normal text field its working, like

<input type="text" id="uname" value="<%=session.getAttribute("username")%>"  readonly="readonly">

but after adding ng-model its not working.
How i will do this?Please anybody help me.


答:
You have to register the seed classes in DatabaseSeeder class in seeds folder.
All the classes in run method will be seed on php artisab db:seed command</p>

```<code>class DatabaseSeeder extends Seeder {

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() {
        $this->call(UsersTableSeeder::class);
        $this->call(AnotherSeeder::class);

    }

}
</code>```

Title: Calling php artisan db:seed does not work without providing a class name

Body:
You have to register the seed classes in DatabaseSeeder class in seeds folder.
All the classes in run method will be seed on php artisab db:seed command

class DatabaseSeeder extends Seeder {

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() {
        $this->call(UsersTableSeeder::class);
        $this->call(AnotherSeeder::class);

    }

}


问:
Error installing GitHub desktop "Application cannot be started, contact the application vendor."
I've recently upgraded from windows 7 to windows 10 and when installing GitHub desktop, I'm getting the following error:

```<code>"Application cannot be started, contact the application vendor."
</code>```

When I click on details, there is the following error:

```<code>"Unable to install this application because an application with the same identity is already installed."
</code>```

I tried several troubleshoots, such as:

running the .exe file as administrator;

deleting the 2.0 folder from Local/apps/

disabling windows defender

But none of them seems to work. I cant understand what the problem may be, since I had no trouble installing github desktop on windows 7.

答:
I fixed this problem by adding permissions to the UserName for the of the folder containing GitHub.exe:

Using the explorer paste "%UserProfile%\AppData\Local\Apps\2.0

In the search box write "github.exe"

In the result list right-click the file & select open file location.

Right click the folder -> Properties->Security

Click [Edit...] for "Group or user names:"

Add the account user name to the list giving it full permission.

Body:
I've recently upgraded from windows 7 to windows 10 and when installing GitHub desktop, I'm getting the following error:

"Application cannot be started, contact the application vendor."

When I click on details, there is the following error:

"Unable to install this application because an application with the same identity is already installed."

I tried several troubleshoots, such as:

running the .exe file as administrator;

deleting the 2.0 folder from Local/apps/

disabling windows defender

But none of them seems to work. I cant understand what the problem may be, since I had no trouble installing github desktop on windows 7.


问:
Enforce type safety in C++ without using extra classes
I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:

```<code>// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);

// Type safe version
enum SendImmediatelyPreference
{
    SEND_IMMEDIATELY,
    DO_NOT_SEND_IMMEDIATELY
};

enum PacketDivisionPreference
{
    DIVIDE_PACKET,
    DO_NOT_DIVIDE_PACKET
};

void sendPackage(
    SendImmediateltPreference immediatePref,
    PacketDivisionPreference divisionPref);
</code>```

So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).

The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.

I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.

Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.

答:
Not sure I understood you correctly, but maybe this can help:</p>

```<code>enum SendImmediatelyPreference : bool  // allows only 2 options:
{
  DO_NOT_SEND_IMMEDIATELY,  // false
  SEND_IMMEDIATELY          // true
}
</code>```

Body:
I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:

// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);

// Type safe version
enum SendImmediatelyPreference
{
    SEND_IMMEDIATELY,
    DO_NOT_SEND_IMMEDIATELY
};

enum PacketDivisionPreference
{
    DIVIDE_PACKET,
    DO_NOT_DIVIDE_PACKET
};

void sendPackage(
    SendImmediateltPreference immediatePref,
    PacketDivisionPreference divisionPref);

So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).

The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.

I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.

Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.

Body:
Not sure I understood you correctly, but maybe this can help:

enum SendImmediatelyPreference : bool  // allows only 2 options:
{
  DO_NOT_SEND_IMMEDIATELY,  // false
  SEND_IMMEDIATELY          // true
}


问:
Spark connects to database every time I perform a Transformation/Action?
I am running Spark 2.1.0 on Windows 10. I connected to a MySQL database to get data into spark using JDBC. As shown below, whenever I perform an action I get the following warning which makes me wonder that the data is being retrieved from database for every operation.

```<code>scala> val jdbcDF2 = spark.read.jdbc("jdbc:mysql:dbserver", "schema.tablename", connectionProperties)
Wed Mar 29 15:05:23 IST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
jdbcDF2: org.apache.spark.sql.DataFrame = [id: bigint, site: bigint ... 15 more fields]

scala> jdbcDF2.count
Wed Mar 29 15:09:09 IST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
</code>```

If this is the case, is there a way by which I can save the data in a spark local object like a DataFrame so that it doesn't have to connect to database all the time?

I tried to cache the table and it runs successfully but I am unable to use Spark-SQL on the table

```<code>scala> jdbcDF2.cache()
res6: jdbcDF2.type = [id: bigint, site: bigint ... 15 more fields]
scala> val unique = sql("SELECT DISTINCT site FROM jdbcDF2")
org.apache.spark.sql.AnalysisException: Table or view not found: jdbcDF2;
</code>```

答:
You were right to cache your DataFrame for later reuse and in order not to query your database at each Spark action (collect, count, first, ...)

But to use SQL to query your DataFrame, first you have to do :

```<code>jdbcDF2.createOrReplaceTempView("my_table")
</code>```

and then :

```<code>sql("SELECT DISTINCT site FROM my_table")
</code>```

Body:
I am running Spark 2.1.0 on Windows 10. I connected to a MySQL database to get data into spark using JDBC. As shown below, whenever I perform an action I get the following warning which makes me wonder that the data is being retrieved from database for every operation.

scala> val jdbcDF2 = spark.read.jdbc("jdbc:mysql:dbserver", "schema.tablename", connectionProperties)
Wed Mar 29 15:05:23 IST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
jdbcDF2: org.apache.spark.sql.DataFrame = [id: bigint, site: bigint ... 15 more fields]

scala> jdbcDF2.count
Wed Mar 29 15:09:09 IST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

If this is the case, is there a way by which I can save the data in a spark local object like a DataFrame so that it doesn't have to connect to database all the time?

I tried to cache the table and it runs successfully but I am unable to use Spark-SQL on the table

scala> jdbcDF2.cache()
res6: jdbcDF2.type = [id: bigint, site: bigint ... 15 more fields]
scala> val unique = sql("SELECT DISTINCT site FROM jdbcDF2")
org.apache.spark.sql.AnalysisException: Table or view not found: jdbcDF2;

Body:
You were right to cache your DataFrame for later reuse and in order not to query your database at each Spark action (collect, count, first, ...)

But to use SQL to query your DataFrame, first you have to do :

jdbcDF2.createOrReplaceTempView("my_table")

and then :

sql("SELECT DISTINCT site FROM my_table")


问:
Copy Numbers from end of string
Here's something I can't get my head around and I would appreciate some help :)

At the moment I have fields on an Excel spreadsheet that have customer's addresses and phone numbers. However the phone numbers are at the end of each string in the address field e.g

Name,Address,Landline,Mobile

Johnson,2 Oxton Road Moreton CH45 9JB 07854213658 721 2569,

I need it to go to

Johnson,2 Oxton Road Moreton CH45 9JB,07854213658,721 2569

Any ideas? The phone numbers are always at the end of the string

I can also write in c# but I can't figure out where to start

Thanks in advance guys

答:
Try regex here. It is hard to parse but it can be very useful for one time  parsing text data:

```<code>var userInfo = "Johnson,2 Oxton Road Moreton CH45 9JB 07854213658 721 2569,";
var regEx = new System.Text.RegularExpressions.Regex("(?<address>.+) (?<landline>\\d{11}) (?<mobile>(\\d{3} \\d{4})|(\\d{7})),$");
regEx.Replace(userInfo, "${address},${landline},${mobile}")
</code>```

The result would be:

"Johnson,2 Oxton Road Moreton CH45 9JB,07854213658,721 2569"

You might need to tweak regex for your data. But it must be much faster than manual editing.

You can find your functions regexlib.

Title: Copy Numbers from end of string

Body:
Try regex here. It is hard to parse but it can be very useful for one time  parsing text data:

var userInfo = "Johnson,2 Oxton Road Moreton CH45 9JB 07854213658 721 2569,";
var regEx = new System.Text.RegularExpressions.Regex("(?<address>.+) (?<landline>\\d{11}) (?<mobile>(\\d{3} \\d{4})|(\\d{7})),$");
regEx.Replace(userInfo, "${address},${landline},${mobile}")

The result would be:

"Johnson,2 Oxton Road Moreton CH45 9JB,07854213658,721 2569"

You might need to tweak regex for your data. But it must be much faster than manual editing.

You can find your functions regexlib.


问:
How to get names of enum entries?
I would like to iterate a TypeScript enum object and get each enumerated symbol name, for example:
enum myEnum { entry1, entry2 }</p>
```<code>for (var entry in myEnum) {
    // use entry's name here, e.g., "entry1"
}
</code>```

答:
If you only search for the names and iterate later use:</p>

```<code>Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get names of enum entries?

Body:
I would like to iterate a TypeScript enum object and get each enumerated symbol name, for example:
enum myEnum { entry1, entry2 }

for (var entry in myEnum) {
    // use entry's name here, e.g., "entry1"
}

Body:
If you only search for the names and iterate later use:

Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];


问:
How to move to next row in datatable if one row catches an error? C# 2.0
I am getting data from a mySql database and I am inserting it into another system. If a column has data in an incorrect format I log this and go to next row in the datatable. It works as expected but now if I have a search function in my method that gets some additional data and this function fails I want to immediately log this and go to next row. As it is now I just log it but it still gets inserted (without the value that didn't meet the search criteria).

My code:

```<code>    private void updateCustomer()
            {
                 MySqlConnection connection = new MySqlConnection("server=myServer;database=myDatabase;uid=myID;password=myPass");

                MySqlCommand command = new MySqlCommand(@"mySelectCommand", connection);
                DataTable customerTbl = new DataTable();
                MySqlDataReader reader;
                try
                {
                    connection.Open();
                    reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        customerTbl.Load(reader);
                    }
                    reader.Close();

                }
                catch (Exception ex)
                {
            _out.error("Could not connect to mySql database");
                }
                finally
                {
                    connection.Close();
                }

                foreach (DataRow row in customerTbl.Rows)
                {
                    // Declare the customer variables
                    string customerID = Encoding.ASCII.GetString((byte[])row["Customer ID"]);
                    string ChildOf = row["Child of"].ToString();

                    // Create the customer object
                    Customer customer = new Customer();

            customer.entityId = customerID;

                    if (ChildOf != "")
                    {
            RecordRef parentRef = new RecordRef();
                        try
                        {

                            parentRef.internalId = searchCustomer(ChildOf);

                        }
                        catch
                        {
// If it fails here I want to log the customerID and then go to the next row in the datatable (could not find the internalid for ChildOf
                            _out.error(customerID + " was not updated. Error: invalid format Parent string");
                        }
                finally
                {
                parentRef.typeSpecified = false;
                            customer.parent = parentRef;
                }
                    }

                    // Invoke update() operation
                    WriteResponse response = _service.update(customer);

                    // Process the response
                    if (response.status.isSuccess)
                    {

                    }
                    else
                    {
                        _out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
                    }
                }
            }
</code>```

答: Use the row.HasError property.

Body:
I am getting data from a mySql database and I am inserting it into another system. If a column has data in an incorrect format I log this and go to next row in the datatable. It works as expected but now if I have a search function in my method that gets some additional data and this function fails I want to immediately log this and go to next row. As it is now I just log it but it still gets inserted (without the value that didn't meet the search criteria).

My code:

    private void updateCustomer()
            {
                 MySqlConnection connection = new MySqlConnection("server=myServer;database=myDatabase;uid=myID;password=myPass");

                MySqlCommand command = new MySqlCommand(@"mySelectCommand", connection);
                DataTable customerTbl = new DataTable();
                MySqlDataReader reader;
                try
                {
                    connection.Open();
                    reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        customerTbl.Load(reader);
                    }
                    reader.Close();

                }
                catch (Exception ex)
                {
            _out.error("Could not connect to mySql database");
                }
                finally
                {
                    connection.Close();
                }

                foreach (DataRow row in customerTbl.Rows)
                {
                    // Declare the customer variables
                    string customerID = Encoding.ASCII.GetString((byte[])row["Customer ID"]);
                    string ChildOf = row["Child of"].ToString();

                    // Create the customer object
                    Customer customer = new Customer();

            customer.entityId = customerID;

                    if (ChildOf != "")
                    {
            RecordRef parentRef = new RecordRef();
                        try
                        {

                            parentRef.internalId = searchCustomer(ChildOf);

                        }
                        catch
                        {
// If it fails here I want to log the customerID and then go to the next row in the datatable (could not find the internalid for ChildOf
                            _out.error(customerID + " was not updated. Error: invalid format Parent string");
                        }
                finally
                {
                parentRef.typeSpecified = false;
                            customer.parent = parentRef;
                }
                    }

                    // Invoke update() operation
                    WriteResponse response = _service.update(customer);

                    // Process the response
                    if (response.status.isSuccess)
                    {

                    }
                    else
                    {
                        _out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
                    }
                }
            }

Body: Use the row.HasError property.


问:
ng2 translate and @Input()
I have the following problem. How Can I translate @Input() from angular2 in ng2-translate? Will be very grateful for any help. If you have any other question about my code, just ask.

I am getting

Your phone number: 123 {{ telephone }}

My code

```<code>import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'child',
    template: `
        <span> {{ 'Contact.Text' | translate:telNumber:telephone }}</span>
        <input type="text" placeholder="{{ 'Contact.Input' | translate }}">
    `
})

export class ChildComponent implements OnInit {
    @Input() telephone: number; // <- this one
    telNumber = { value: 123 };
    constructor() { }
    ngOnInit() { }
}
</code>```

en.json

```<code>{
"Navigation": {
    "First": "Main Page",
    "Second": "Menu",
    "Third": "Contact",
    "ChangeLanguage": "Change language"
},
"Mainpage": {
    "Title": "Welcome to the home page",
    "Content": "This home page is the most beautiful homepage you have ever seen"
},
"Menu": {
    "Title": "Animals",
    "FirstAnimal": "Dog",
    "SecondAnimal": "Cat",
    "ThirdAnimal": "Cow",
    "FourthAnimal": "Pig",
    "FifthAnimal": "Bird"
},
"Contact": {
    "Title": "Contact to us",
    "Text": "Your phone number:  {{ value }} {{ telephone }}",
    "Input": "Deutschland Name"
}
}
</code>```

答:
try this

```<code>import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'child',
    template: `
        <span> {{ 'Contact.Text' | translate:telParams }}</span>
        <input type="text" placeholder="{{ 'Contact.Input' | translate }}">
    `
})

export class ChildComponent implements OnInit {
    @Input() telephone: number; // <- this one
    get telParams() {
      return { value: 123, telephone: this.telephone };
    }
    constructor() { }
    ngOnInit() { }
}
</code>```

btw, using ngx-translate https://github.com/ngx-translate instead of ng2-translate.

Title: ng2 translate and @Input()

Body:
I have the following problem. How Can I translate @Input() from angular2 in ng2-translate? Will be very grateful for any help. If you have any other question about my code, just ask.

I am getting

Your phone number: 123 {{ telephone }}

My code

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'child',
    template: `
         {{ 'Contact.Text' | translate:telNumber:telephone }}
        <input type="text" placeholder="{{ 'Contact.Input' | translate }}">
    `
})

export class ChildComponent implements OnInit {
    @Input() telephone: number; // <- this one
    telNumber = { value: 123 };
    constructor() { }
    ngOnInit() { }
}

en.json

{
"Navigation": {
    "First": "Main Page",
    "Second": "Menu",
    "Third": "Contact",
    "ChangeLanguage": "Change language"
},
"Mainpage": {
    "Title": "Welcome to the home page",
    "Content": "This home page is the most beautiful homepage you have ever seen"
},
"Menu": {
    "Title": "Animals",
    "FirstAnimal": "Dog",
    "SecondAnimal": "Cat",
    "ThirdAnimal": "Cow",
    "FourthAnimal": "Pig",
    "FifthAnimal": "Bird"
},
"Contact": {
    "Title": "Contact to us",
    "Text": "Your phone number:  {{ value }} {{ telephone }}",
    "Input": "Deutschland Name"
}
}

Body:
try this

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'child',
    template: `
        <span> {{ 'Contact.Text' | translate:telParams }}</span>
        <input type="text" placeholder="{{ 'Contact.Input' | translate }}">
    `
})

export class ChildComponent implements OnInit {
    @Input() telephone: number; // <- this one
    get telParams() {
      return { value: 123, telephone: this.telephone };
    }
    constructor() { }
    ngOnInit() { }
}

btw, using ngx-translate https://github.com/ngx-translate instead of ng2-translate.


问:
How to insert new cell at first element in UICollectionView in Xamarin?
I want to make horizontal collection and add new cell at the first position.

I make custom UICollectionViewFlowLayout and override
LayoutAttributesForElementsInRect like this (to see reverse order of items):

```<code>    public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CGRect rect)
    {
        var attributes = new UICollectionViewLayoutAttributes[cellCount];

        NSIndexPath indexPath;

        // Setting first position
        int shift = 25, reverseXCenter;
        for (int i = 0; i < cellCount; i++)
        {
            indexPath = NSIndexPath.FromItemSection(i, 0);

            attributes[i] = LayoutAttributesForItem(indexPath);

            // We have to make opposite order
            reverseXCenter = (cellCount -1 - i) * 50;
            attributes[i].Center = new CGPoint(reverseXCenter + shift, attributes[i].Center.Y);
        }

        return attributes;
    }
</code>```

I think is bad solution, because when I have more than 5 cells, the displayed collection is filled and I can't scroll.
I had debugger in GetOrCreateCellFor in CollectionViewSource
and indexPath.Item's had value for example (10,9,8,7,6...), where 10 is the last I added.

Maybe is another way to do this, or just I miss something?

答:
Ok I am gonna help you out with a flow .

Suppose you are in a ViewController called "A" which will present a controller ViewController called "B"

Inside A use this function to push B

```<code>Public void PushNewHorizontalCollectionController(){
using (var vc =
                   new B(this.PageViewControllerLayout(), indexPath))
            {

                this.controller.PushViewController(pageViewController, true);
            }
}

public UICollectionViewFlowLayout PageViewControllerLayout()
        {

            var flowLayout = new UICollectionViewFlowLayout();
                var itemSize = this.controller.NavigationBarHidden ? new CGSize(Constants.ScreenWidth, Constants.ScreenHeight + 20) : new CGSize(Constants.ScreenWidth, Constants.ScreenHeight - Constants.NavigationHeaderAndStatusbarHeight);
                flowLayout.ItemSize = itemSize;
                flowLayout.MinimumLineSpacing = 0;
                flowLayout.MinimumInteritemSpacing = 0;
                flowLayout.ScrollDirection = UICollectionViewScrollDirection.Horizontal;
                return flowLayout;

        }
</code>```

Here itemSize is CGSize which u can assign what size you can ignore my constants which are self explainable .

Inside B your constructor should look like this .

```<code>public HorizontalViewController(UICollectionViewLayout layout, NSIndexPath indexpath) : base(layout)
        {

Do your initialisation like registering UICollectionViewCell class nibs for use with this Controller
        }
</code>```

Handling real requirement from comment .

You wanna add something always as 1st element in collectionView ,Go to this method which should look like below

```<code>public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
    Console.WriteLine("getcellHori");

    var isQuoteType = Photo.PhotoCollection[(int)indexPath.Item].Type;
    if (isQuoteType == 3 || isQuoteType == 4)
    {
        var item = Photo.PhotoCollection[(int)indexPath.Item];

        var cell = (HorizontalviewForQuoteType)collectionView.DequeueReusableCell("HorizontalviewForQuoteType", indexPath);
        cell.PopulateCell(item.Caption,item.TextLabel,item.Likes,item.TimeLabel,item.Id);

        HorizontalviewForQuoteType.pullAction = (offset) =>
        {
            this.pullOffset = offset;
            this.NavigationController.PopViewController(true);
        };
        cell.SetNeedsLayout();
        return cell;
    }
</code>```

Here you this line

var item = Photo.PhotoCollection[(int)indexPath.Item];

this is the data source , so whenever you adding something at index first and everything will be solved .

Body:
I want to make horizontal collection and add new cell at the first position.

I make custom UICollectionViewFlowLayout and override
LayoutAttributesForElementsInRect like this (to see reverse order of items):

    public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CGRect rect)
    {
        var attributes = new UICollectionViewLayoutAttributes[cellCount];

        NSIndexPath indexPath;

        // Setting first position
        int shift = 25, reverseXCenter;
        for (int i = 0; i < cellCount; i++)
        {
            indexPath = NSIndexPath.FromItemSection(i, 0);

            attributes[i] = LayoutAttributesForItem(indexPath);

            // We have to make opposite order
            reverseXCenter = (cellCount -1 - i) * 50;
            attributes[i].Center = new CGPoint(reverseXCenter + shift, attributes[i].Center.Y);
        }

        return attributes;
    }

I think is bad solution, because when I have more than 5 cells, the displayed collection is filled and I can't scroll.
I had debugger in GetOrCreateCellFor in CollectionViewSource
and indexPath.Item's had value for example (10,9,8,7,6...), where 10 is the last I added.

Maybe is another way to do this, or just I miss something?

Body:
Ok I am gonna help you out with a flow .

Suppose you are in a ViewController called "A" which will present a controller ViewController called "B"

Inside A use this function to push B

Public void PushNewHorizontalCollectionController(){
using (var vc =
                   new B(this.PageViewControllerLayout(), indexPath))
            {

                this.controller.PushViewController(pageViewController, true);
            }
}

public UICollectionViewFlowLayout PageViewControllerLayout()
        {

            var flowLayout = new UICollectionViewFlowLayout();
                var itemSize = this.controller.NavigationBarHidden ? new CGSize(Constants.ScreenWidth, Constants.ScreenHeight + 20) : new CGSize(Constants.ScreenWidth, Constants.ScreenHeight - Constants.NavigationHeaderAndStatusbarHeight);
                flowLayout.ItemSize = itemSize;
                flowLayout.MinimumLineSpacing = 0;
                flowLayout.MinimumInteritemSpacing = 0;
                flowLayout.ScrollDirection = UICollectionViewScrollDirection.Horizontal;
                return flowLayout;

        }

Here itemSize is CGSize which u can assign what size you can ignore my constants which are self explainable .

Inside B your constructor should look like this .

public HorizontalViewController(UICollectionViewLayout layout, NSIndexPath indexpath) : base(layout)
        {

Do your initialisation like registering UICollectionViewCell class nibs for use with this Controller
        }

Handling real requirement from comment .

You wanna add something always as 1st element in collectionView ,Go to this method which should look like below

public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
    Console.WriteLine("getcellHori");

    var isQuoteType = Photo.PhotoCollection[(int)indexPath.Item].Type;
    if (isQuoteType == 3 || isQuoteType == 4)
    {
        var item = Photo.PhotoCollection[(int)indexPath.Item];

        var cell = (HorizontalviewForQuoteType)collectionView.DequeueReusableCell("HorizontalviewForQuoteType", indexPath);
        cell.PopulateCell(item.Caption,item.TextLabel,item.Likes,item.TimeLabel,item.Id);

        HorizontalviewForQuoteType.pullAction = (offset) =>
        {
            this.pullOffset = offset;
            this.NavigationController.PopViewController(true);
        };
        cell.SetNeedsLayout();
        return cell;
    }

Here you this line

var item = Photo.PhotoCollection[(int)indexPath.Item];

this is the data source , so whenever you adding something at index first and everything will be solved .


问:
getElementByTagName(a) for autoscroll
What I have now is:

```<code>var a = document.getElementsByTagName('a');
</code>```

I use this to get all elements with an 'a' and when I scroll it autoscrolls to the next 'a' element.

The problem with that is that I also use links (that use an a href="") so sometimes it scrolls to a link instead of an . Is their anyway to fix this? Like:

```<code>var a = document.getElementsByTagName('a name=""');
</code>```

(this one doesnt work)

If full code is needed I will add it below, but its probably not needed.

```<code>(function () {
    var delay = false;

    $(document).on('mousewheel DOMMouseScroll', function (event) {
        event.preventDefault();
        if (delay) return;

        delay = true;
        setTimeout(function () {
            delay = false
        }, 800);

        var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;

        var a = document.getElementsByTagName('a');
        if (wd < 0) {
            for (var i = 0; i < a.length; i++) {
                var t = a[i].getClientRects()[0].top;
                if (t >= window.innerHeight * 0.95) break;
            }
        }
        else {
            for (var i = a.length - 1; i >= 0; i--) {
                var t = a[i].getClientRects()[0].top;
                if (t < -window.innerHeight * 0.5) break;
            }
        }
        $('html,body').animate({
            scrollTop: a[i].offsetTop
        }, 800);
    });
})();
</code>```

答:
You can use QuerySelector for HTML 5 supporting browsers .You can check its support from http://caniuse.com/#feat=queryselector

QuerySelectorAll

```<code>document.querySelectorAll("a[name='<setname>']");
</code>```

For older browsers use Jquery

```<code>$("a[name='<setname>']")
</code>```

If you don't want to set a specific name just leave it blank. The selector is same for both JQuery and HTML 5 querySelector

```<code>document.querySelectorAll("a[name]");
</code>```

or

```<code>$("a[name]")
</code>```

Title: getElementByTagName(a) for autoscroll

Body:
What I have now is:

var a = document.getElementsByTagName('a');

I use this to get all elements with an 'a' and when I scroll it autoscrolls to the next 'a' element.

The problem with that is that I also use links (that use an a href="") so sometimes it scrolls to a link instead of an . Is their anyway to fix this? Like:

var a = document.getElementsByTagName('a name=""');

(this one doesnt work)

If full code is needed I will add it below, but its probably not needed.

(function () {
    var delay = false;

    $(document).on('mousewheel DOMMouseScroll', function (event) {
        event.preventDefault();
        if (delay) return;

        delay = true;
        setTimeout(function () {
            delay = false
        }, 800);

        var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;

        var a = document.getElementsByTagName('a');
        if (wd < 0) {
            for (var i = 0; i = window.innerHeight * 0.95) break;
            }
        }
        else {
            for (var i = a.length - 1; i >= 0; i--) {
                var t = a[i].getClientRects()[0].top;
                if (t < -window.innerHeight * 0.5) break;
            }
        }
        $('html,body').animate({
            scrollTop: a[i].offsetTop
        }, 800);
    });
})();

Body:
You can use QuerySelector for HTML 5 supporting browsers .You can check its support from http://caniuse.com/#feat=queryselector

QuerySelectorAll

document.querySelectorAll("a[name='<setname>']");

For older browsers use Jquery

$("a[name='<setname>']")

If you don't want to set a specific name just leave it blank. The selector is same for both JQuery and HTML 5 querySelector

document.querySelectorAll("a[name]");

or

$("a[name]")


问:
Echo PHP returned value with AJAX in span/div
Ok I have a following HTML, AJAX and PHP script below. I want to get the $deduct value to update
 field when the AJAX request is processed. How can I do so?

Example Form

```<code><form>
    <span id="mywallet">$<?php echo $wallet; ?></span>
</form>
</code>```

Example flip-process.php structure

```<code><?php
if($_POST){
    //process everything

    $deduct = (something calculated);

    if(success){
       $msg = "success";
    }else{
       $msg = "fail";
    }
}
echo $msg;
?>
</code>```

Ajax Script

```<code>$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#process-flipping").hide();
                $(".coin-flip").show();
      },
            success: function(html){
                setTimeout(function(){
                $(".message").html(html).fadeIn();
                    $("#process-flipping").show();
                    $(".coin-flip").hide();
                },3000);
            }
        });
        return false;
    });
});
</code>```

答:
Yes, json is the best solution:

```<code><?php
if($_POST){
    //process everything

    $deduct = (something calculated);

    if(success){
       $msg = "success";
    }else{
       $msg = "fail";
    }

    echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>
</code>```

and the ajax success:

```<code>success: function(json){
    setTimeout(function(){
    $(".message").html(json.status).fadeIn();
        $("#process-flipping").show();
        $(".coin-flip").hide();
    },3000);
    if(json.status == 'success')
        $('#mywallet').html('$' + json.deduct);
}
</code>```

Body:
Ok I have a following HTML, AJAX and PHP script below. I want to get the $deduct value to update
 field when the AJAX request is processed. How can I do so?

Example Form

<form>
    $<?php echo $wallet; ?>
</form>

Example flip-process.php structure

<?php
if($_POST){
    //process everything

    $deduct = (something calculated);

    if(success){
       $msg = "success";
    }else{
       $msg = "fail";
    }
}
echo $msg;
?>

Ajax Script

$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#process-flipping").hide();
                $(".coin-flip").show();
      },
            success: function(html){
                setTimeout(function(){
                $(".message").html(html).fadeIn();
                    $("#process-flipping").show();
                    $(".coin-flip").hide();
                },3000);
            }
        });
        return false;
    });
});

Body:
Yes, json is the best solution:

<?php
if($_POST){
    //process everything

    $deduct = (something calculated);

    if(success){
       $msg = "success";
    }else{
       $msg = "fail";
    }

    echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>

and the ajax success:

success: function(json){
    setTimeout(function(){
    $(".message").html(json.status).fadeIn();
        $("#process-flipping").show();
        $(".coin-flip").hide();
    },3000);
    if(json.status == 'success')
        $('#mywallet').html('$' + json.deduct);
}


问:
<h> tag different color in different page
I'm trying to make that a h1 tag as two colors, for example in the "main page" the h1 is red, and in the "secondary page" the h1 is blue.

I'm trying to achieve this without success, I been doing this with a span but I would like to know if there is another way to do this.

this is my code structure

```<code>h1, h2, h3, h4, h5, p, li, ul, ol, a, a:hover, button { color: red; }

h1 .h1cor{
   color: blue;
}
</code>```

答:
First get the page name you are currently in by using this

```<code>var url = window.location.href
 var getLink = url.split("/").pop();
</code>```

Then set the color according to the name of the page

```<code>if(getLink == 'mainPage'){
  $('h1').css("color","red");
}else if(getLink == 'secondary page'){
  $('h1').css("color","yellow");
}
</code>```

Body:
I'm trying to make that a h1 tag as two colors, for example in the "main page" the h1 is red, and in the "secondary page" the h1 is blue.

I'm trying to achieve this without success, I been doing this with a span but I would like to know if there is another way to do this.

this is my code structure

h1, h2, h3, h4, h5, p, li, ul, ol, a, a:hover, button { color: red; }

h1 .h1cor{
   color: blue;
}

Body:
First get the page name you are currently in by using this

var url = window.location.href
 var getLink = url.split("/").pop();

Then set the color according to the name of the page

if(getLink == 'mainPage'){
  $('h1').css("color","red");
}else if(getLink == 'secondary page'){
  $('h1').css("color","yellow");
}


答:
every page throws a unique class or id in the page,
take the class or id of the page as your reference to style h1 tag;
for example;

```<code>.page-class h1{
    color:blue;
 }
</code>```

Title: <h> tag different color in different page

Body:
every page throws a unique class or id in the page,
take the class or id of the page as your reference to style h1 tag;
for example;

<body class="page-class">

.page-class h1{
    color:blue;
 }


问:
Grep pattern from file (list) into same line
I have two files (see below) and want to grep the patterns in file 1 from file 2 (2 columns). I think it is really easy but I could not find any clue how to grep the matches to the same line

```<code>File1
ABC
DEF
GHI

File 2
ABC SeqX
ABC SeqY
ABC SeqP
DEF SeqW
DEF SeqO
GHI SeqR
GHI Seql
</code>```

The output should look like this:

```<code>    ABC SeqX SeqY SeqP
    DEF SeqW SeqO
    GHI SeqR Seql
</code>```

I know it has to be something like: grep -f file 1 file2 > output

答:
with awk yes, not as_is with grep</p>

```<code>awk 'FNR==NR { Ls[$1];next}
     ( $1 in Ls) { Ds[ $1] = Ds[ $1] " " $2 }
     END { for( L in Ls ) print L Ds[ L] }
     ' File1 File2
</code>```

Body:
I have two files (see below) and want to grep the patterns in file 1 from file 2 (2 columns). I think it is really easy but I could not find any clue how to grep the matches to the same line

File1
ABC
DEF
GHI

File 2
ABC SeqX
ABC SeqY
ABC SeqP
DEF SeqW
DEF SeqO
GHI SeqR
GHI Seql

The output should look like this:

    ABC SeqX SeqY SeqP
    DEF SeqW SeqO
    GHI SeqR Seql

I know it has to be something like: grep -f file 1 file2 > output

Body:
with awk yes, not as_is with grep

awk 'FNR==NR { Ls[$1];next}
     ( $1 in Ls) { Ds[ $1] = Ds[ $1] " " $2 }
     END { for( L in Ls ) print L Ds[ L] }
     ' File1 File2


问:
Serializing and deserializing a map with key as string
I am intending to serialize and deserialize a hashmap whose key is a string.

From Josh Bloch's Effective Java, I understand the following.
P.222

For example, consider the case of a hash table.  The physical
  representation is a sequence of hash buckets containing key-value
  entries.  Which bucket an entry is placed in is a function of the hash
  code of the key, which is not, in general guaranteed to be the same
  from JVM implementation to JVM implementation.  In fact, it isn't even
  guaranteed to be the same from run to run on the same JVM
  implementation.  Therefore accepting the default serialized form for a
  hash table would constitute a serious bug. Serializing and
  deserializing the hash table could yield an object whose invariants
  were seriously corrupt.

My questions are:
1) In general, would overriding equals and hashcode of the key class of the map resolve this issue and the map can be correctly restored?

2) If my key is a String and the String class is already overriding the hashCode() method, would I still have problem described above.
(I am seeing a bug which makes me think this is probably still a problem even though the key is String with overriding hashCode.)

3)Previously, I got around this issue by serializing an array of entries (key, value) and when deserializing I would reconstruct the map.  I am wondering if there is a better approach.

4) If the answers to question 1 and 2 are that it still can't be guaranteed, could someone explain why?  If the hashCodes are the same would they go to the same buckets across JVMs?

Thanks, Grace

答:
Add these methods to the class that contains the map. You have also to add serialisation/de-serialization of any other fields:</p>

```<code>private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.writeInt(map.size());
    for (Entry<String, String> entry : map.entrySet()) {
        stream.writeObject(entry.getKey());
        stream.writeObject(entry.getValue());
    }
}

private void readObject(ObjectInputStream stream) throws IOException,
        ClassNotFoundException {
    int mapSize = stream.readInt();
    for (int i = 0; i < mapSize; i++) {
        String key = (String) stream.readObject();
        String value = (String) stream.readObject();
        map.put(key, value);
    }
}
</code>```

Body:
Add these methods to the class that contains the map. You have also to add serialisation/de-serialization of any other fields:

private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.writeInt(map.size());
    for (Entry<String, String> entry : map.entrySet()) {
        stream.writeObject(entry.getKey());
        stream.writeObject(entry.getValue());
    }
}

private void readObject(ObjectInputStream stream) throws IOException,
        ClassNotFoundException {
    int mapSize = stream.readInt();
    for (int i = 0; i < mapSize; i++) {
        String key = (String) stream.readObject();
        String value = (String) stream.readObject();
        map.put(key, value);
    }
}


问:
Socialite laravel 5.4 Facebook Provider
i have a problem here maybe sameone can help me:  i install the Socialite pakcage  to my laravel project and in start it work perfect with facebook , google and linkedin provider. But now it get always this message when i try to connect with facebook , and other provider connect perfectly.

What's wrong ?

ClientException in RequestException.php line 111:
      Client error: GET https://graph.facebook.com/v2.8/me?access_token=&fields=name,email,gender,verified,link&appsecret_proof=5fbda0d218f94cb8024712269c053f0186d360efd82cd358b588eaf621e0c79c
  resulted in a 400 Bad Request response:
      {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthExce (truncated...)

答: composer update will fix it by updating the laravel/socialite version</p>

Title: Socialite laravel 5.4 Facebook Provider


问:
Return function pointing to local var in php
```<code>class Person{

     var $name = "Omer";

     function get_name(){
         return $this->name;//Why not $this->$name ?
     }
}
</code>```

Thanks

答:
To illustrate what @Aaron has so eloquently answered, the following would compile:</p>

```<code>class Person{
     var $name = "Omer";
     function get_name(){
         $varname = 'name';
         return $this->$varname;
     }
}
$Person = new Person;
echo $Person->get_name(); // output = Omer
</code>```

Body:
class Person{

     var $name = "Omer";

     function get_name(){
         return $this->name;//Why not $this->$name ?
     }
}

Thanks

Body:
To illustrate what @Aaron has so eloquently answered, the following would compile:

class Person{
     var $name = "Omer";
     function get_name(){
         $varname = 'name';
         return $this->$varname;
     }
}
$Person = new Person;
echo $Person->get_name(); // output = Omer


问:
Calling php artisan db:seed does not work without providing a class name
I have a seeder class in the database folder

```<code>class UsersTableSeeder extends Seeder
{
    public function run()
    {
        $user = new User();
        $user->name         = 'Name';
        $user->email        = 'email@gmail.com';
        $user->password        = bcrypt('secret');
        $user->save();

    }
}
</code>```

When I run php artisan db:seed nothing happens, the seeder is only called when I run php artisan db:seed --class=UsersTableSeeder

This means I have to call each seeder class separately, any idea why db:seed doesn't work by it self?

答:
Take a look at database/seeds/DatabaseSeeder.php

You will need to add the calls to your other seeders in there.

Then db:seed will function as expected

Example:

```<code><?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UsersTableSeeder::class);
        $this->call(SecondSeedClass::class);
        $this->call(ThirdSeedClass::class);

    }
}
</code>```

Body:
I have a seeder class in the database folder

class UsersTableSeeder extends Seeder
{
    public function run()
    {
        $user = new User();
        $user->name         = 'Name';
        $user->email        = 'email@gmail.com';
        $user->password        = bcrypt('secret');
        $user->save();

    }
}

When I run php artisan db:seed nothing happens, the seeder is only called when I run php artisan db:seed --class=UsersTableSeeder

This means I have to call each seeder class separately, any idea why db:seed doesn't work by it self?

Body:
Take a look at database/seeds/DatabaseSeeder.php

You will need to add the calls to your other seeders in there.

Then db:seed will function as expected

Example:

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UsersTableSeeder::class);
        $this->call(SecondSeedClass::class);
        $this->call(ThirdSeedClass::class);

    }
}


问:
Check if string is in array or not including wildcards with Excel VBA
I found this function to identify whether a string is in a given array, however it does not seem to be able to handle wildcards (or atleast not the way i do it).

```<code>Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
</code>```

My use of the function:

```<code>Dim BannedWildcards() As Variant

BannedWildcards = Array("", "-", "?", 0, "na", "n/a", _
"*account*", "*hse*", "*defined*", "*applicable*", "*operation*", "*action*", "*manager*")

            Select Case True
            Case IsInArray(LCase(Sht_Tracker.Cells(RowCounter_CRCT, 17)), BannedWildcards) = True
                Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = "#N/A"
            Case Else: Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = Sht_Tracker.Cells(RowCounter_CRCT, 17)
            End Select
</code>```

答:
Or something like:</p>

```<code>Function IsInArray2(StringToBeFound As String, MyArray As Variant) As Boolean
IsInArray2 = False
wildCard = "*"
If InStr(StringToBeFound, wildCard) > 0 Then
    For i = LBound(MyArray) To UBound(MyArray)
        If "*" & MyArray(i) & "*" Like StringToBeFound Then IsInArray2 =    True 'will match MyArray to any substring of StringToBeFound
    Next
Else
    For i = LBound(MyArray) To UBound(MyArray)
            If MyArray(i) == StringToBeFound Then IsInArray2 =  True 'will exactly match MyArray to StringToBeFound
    Next
End If
End Function
</code>```

Body:
I found this function to identify whether a string is in a given array, however it does not seem to be able to handle wildcards (or atleast not the way i do it).

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

My use of the function:

Dim BannedWildcards() As Variant

BannedWildcards = Array("", "-", "?", 0, "na", "n/a", _
"*account*", "*hse*", "*defined*", "*applicable*", "*operation*", "*action*", "*manager*")

            Select Case True
            Case IsInArray(LCase(Sht_Tracker.Cells(RowCounter_CRCT, 17)), BannedWildcards) = True
                Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = "#N/A"
            Case Else: Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = Sht_Tracker.Cells(RowCounter_CRCT, 17)
            End Select

Body:
Or something like:

Function IsInArray2(StringToBeFound As String, MyArray As Variant) As Boolean
IsInArray2 = False
wildCard = "*"
If InStr(StringToBeFound, wildCard) > 0 Then
    For i = LBound(MyArray) To UBound(MyArray)
        If "*" & MyArray(i) & "*" Like StringToBeFound Then IsInArray2 =    True 'will match MyArray to any substring of StringToBeFound
    Next
Else
    For i = LBound(MyArray) To UBound(MyArray)
            If MyArray(i) == StringToBeFound Then IsInArray2 =  True 'will exactly match MyArray to StringToBeFound
    Next
End If
End Function


问:
Whoops, looks like something went wrong. Laravel 5.0
I installed Laravel 5.0 properly by cloning in git, and composer install, when I ran it to browser http://localhost/laravel/public/, it says

"Whoops, looks like something went wrong."

I did not make any changes after composer install.

Update after copy the env.example to .env this is result

RuntimeException in compiled.php line 5599: OpenSSL extension is required.

答: make sure app/storage dir permission is set to 755 and owner is set to admin. and also check permission and owner of files and dir in app/storage too


问:
Update User Using Laravel 5.4
need your help at my laravel user update...

here's my coding:

```<code><form class="form-horizontal" role="form" method="POST" action="{{ route('editregister.post') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                            <label for="name" class="col-md-4 control-label">Name</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control" name="name" value="{{ $users->name }}" required autofocus>
                                @if ($errors->has('name'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('username') ? ' has-error' : '' }}">
                            <label for="username" class="col-md-4 control-label">Username</label>
                            <div class="col-md-6">
                                <input id="username" type="username" class="form-control" name="username" value="{{ $users->username }}" required>
                                @if ($errors->has('username'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('username') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        @if ($users->position == "Super Admin")

                        @else
                            <div class="form-group{{ $errors->has('position') ? ' has-error' : '' }}">
                                <label for="user-position" class="col-md-4 control-label">Position</label>
                                <div class="col-md-6">
                                    <select id="position" class="form-control" name="position" required autofocus>
                                        <option value=""> -- Select Position -- </option>
                                        <option value="Admin" {{ $users->position == 'Admin' ? 'selected' : '' }}>Admin</option>
                                        <option value="User" {{ $users->position == 'User' ? 'selected' : '' }}>User</option>
                                    </select>
                                    @if ($errors->has('position'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('position') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>
                        @endif
                        @if(session()->has('message'))
                            <div class="alert alert-success">
                                {{ session()->get('message') }}
                            </div>
                        @endif
                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>
                                <a href='{{ url('/userlist') }}' class="btn btn-primary">
                                    Cancel
                                </a>
                            </div>
                        </div>
                    </form>
</code>```

and here's my controller:

```<code>public function editregister(Request $request, $iduser)
{

    $this->validate(request(), [
        'name' => 'required|max:255',
        'username' => 'required|max:255|unique:users',
        'position' => 'required',
        ]
    );

    $name = $request->input('name');
    $username = $request->input('username');
    $position = $request->input('position');
    $updated_at = date("Y-m-d H:i:s");

    DB::table('users')->where('id', $iduser)->update([
        ['name' => $name, 'username' => $username, 'position' => $position, 'updated_at' => $updated_at, ]
    ]);

    return redirect()->back()->with('message', 'User is successfully Updated!');
}
</code>```

and here my web routes coding:

```<code>Route::get('edituser/{iduser}',['as' => 'edituser', 'uses' => 'UserRegController@editregisterform']);
Route::post('editregister', ['as' => 'editregister.post', 'uses' => 'UserRegController@editregister']);
</code>```

I don't know how to it works when updating a data... Im a new user of laravel 5.4...

please help me about this one thanks..

答:
Use post when updating.

```<code>Route::post('edituser/{iduser}',['as' => 'edituser', 'uses' => 'UserRegController@editregisterform']);
</code>```

Just grab the user object using its id $user = User::find($id)
and then set the properties $user->name = 'updated name' and then $user->save(). Hope this will help you.

Title: Update User Using Laravel 5.4

Body:
need your help at my laravel user update...

here's my coding:

<form class="form-horizontal" role="form" method="POST" action="{{ route('editregister.post') }}">
                        {{ csrf_field() }}

has('name') ? ' has-error' : '' }}">
                            Name

                                <input id="name" type="text" class="form-control" name="name" value="{{ $users->name }}" required autofocus>
                                @if ($errors->has('name'))

                                        {{ $errors->first('name') }}

                                @endif

has('username') ? ' has-error' : '' }}">
                            Username

                                <input id="username" type="username" class="form-control" name="username" value="{{ $users->username }}" required>
                                @if ($errors->has('username'))

                                        {{ $errors->first('username') }}

                                @endif

                        @if ($users->position == "Super Admin")

                        @else

has('position') ? ' has-error' : '' }}">
                                Position

                                    <select id="position" class="form-control" name="position" required autofocus>
                                        <option value=""> -- Select Position -- </option>
                                        <option value="Admin" {{ $users->position == 'Admin' ? 'selected' : '' }}>Admin</option>
                                        <option value="User" {{ $users->position == 'User' ? 'selected' : '' }}>User</option>
                                    </select>
                                    @if ($errors->has('position'))

                                            {{ $errors->first('position') }}

                                    @endif

                        @endif
                        @if(session()->has('message'))

                                {{ session()->get('message') }}

                        @endif

                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>

                                    Cancel

                    </form>

and here's my controller:

public function editregister(Request $request, $iduser)
{

    $this->validate(request(), [
        'name' => 'required|max:255',
        'username' => 'required|max:255|unique:users',
        'position' => 'required',
        ]
    );

    $name = $request->input('name');
    $username = $request->input('username');
    $position = $request->input('position');
    $updated_at = date("Y-m-d H:i:s");

    DB::table('users')->where('id', $iduser)->update([
        ['name' => $name, 'username' => $username, 'position' => $position, 'updated_at' => $updated_at, ]
    ]);

    return redirect()->back()->with('message', 'User is successfully Updated!');
}

and here my web routes coding:

Route::get('edituser/{iduser}',['as' => 'edituser', 'uses' => 'UserRegController@editregisterform']);
Route::post('editregister', ['as' => 'editregister.post', 'uses' => 'UserRegController@editregister']);

I don't know how to it works when updating a data... Im a new user of laravel 5.4...

please help me about this one thanks..

Body:
Use post when updating.

Route::post('edituser/{iduser}',['as' => 'edituser', 'uses' => 'UserRegController@editregisterform']);

Just grab the user object using its id $user = User::find($id)
and then set the properties $user->name = 'updated name' and then $user->save(). Hope this will help you.


问:
Commit specific lines of a file to git

Possible Duplicate:

  How can I commit only part of a file in git

How do I commit a few specific line ranges from a file to git? while ignoring some other line changes in the same file.

答: Try git add -p -- it will interactively let you add, skip, or split diff hunks.

Title: Commit specific lines of a file to git


问:
How to refresh an ng-repeat list when $scope is not used?
$scope.$apply() is mostly used when $scope is defined.
But this kind of definition does not seem to refresh the list.

HTML :

```<code><div ng-repeat="feed in feedCtrl.feeds"></div>
</code>```

Controller :

```<code>this.feeds = response.data;
</code>```

答:
This may help you

```<code><body ng-app="myApp" ng-controller="appCtrl as ctrl">
<h1 ng-repeat="x in ctrl.records">{{x}}</h1>
<button ng-click="ctrl.records=['Bananna','Grapes'];">update records</button>
</code>```

in controller

```<code>var app = angular.module("myApp", []);
app.controller("appCtrl", function() {  this.records = ["Mango","Apple","Orange"];    });
</code>```

Body:
$scope.$apply() is mostly used when $scope is defined.
But this kind of definition does not seem to refresh the list.

HTML :

Controller :

this.feeds = response.data;

Body:
This may help you

<body ng-app="myApp" ng-controller="appCtrl as ctrl">
<h1 ng-repeat="x in ctrl.records">{{x}}</h1>
<button ng-click="ctrl.records=['Bananna','Grapes'];">update records</button>

in controller

var app = angular.module("myApp", []);
app.controller("appCtrl", function() {  this.records = ["Mango","Apple","Orange"];    });


问:
How to invoke a function and pass parameter when you have function name as string?
How to invoke a function when you have function name as string? e.g.</p>

```<code>$scope.ExecuteFunction = function (func,val) {
  // here func="GetActivityInfo" and val="ERF000000000A6543"
  // How to Invoke function named in variable func and pass val as parameter ?
  // GetActivityInfo(val) to be invoked.
}

var GetActivityInfo = function (elementId) {
  // some code
};
</code>```

答:
please ensure you don't have parenthesis in parameter, try below in browser console :</p>

```<code>function addUser(id, callback) {
    callback(id);
}

function callback(id) {
    alert(id);
}

addUser(1, callback);
</code>```

Body:
How to invoke a function when you have function name as string? e.g.

$scope.ExecuteFunction = function (func,val) {
  // here func="GetActivityInfo" and val="ERF000000000A6543"
  // How to Invoke function named in variable func and pass val as parameter ?
  // GetActivityInfo(val) to be invoked.
}

var GetActivityInfo = function (elementId) {
  // some code
};

Body:
please ensure you don't have parenthesis in parameter, try below in browser console :

function addUser(id, callback) {
    callback(id);
}

function callback(id) {
    alert(id);
}

addUser(1, callback);


问:
Re indexing array-object in jquery
I have an array with object like this

```<code>var arr = [
  {'key1':'A','key2':1,'key3':0.04,'key4':10},
  {'key1':'B','key2':1,'key3':0.03,'key4':20},
  {'key1':'B','key2':2,'key3':0.05,'key4':30},
  {'key1':'A','key2':1,'key3':0.03,'key4':40},
  ...
];
</code>```

Inside array there can be unlimited objects. I need to create new array where every key1 and key2 must save unique and if same key1 and key2,then key3 must be added. My result for above array look like this

```<code>//Can be array or object
var a = [
  ['A'][1] => {'key3':0.07,'key4':50},
  ['B'][1] => {'key3':0.07,'key4':20},
  ['B'][2] => {'key3':0.05,'key4':30}
];
</code>```

My result can be array or object. What I have tried is

```<code>var a = {};
arr.forEach(function(obj){
  if(a[obj.key1]){
    if(a[obj.key1][obj.key2]){
      a[obj.key1][obj.key2] += obj.key3;
    }else{
      a[obj.key1][obj.key2] = obj.key3;
    }
  }else{
    a[obj.key1] = obj.key1;
  }
});
console.log(a);
</code>```

And I am getting only depth of result. Please suggest me how can I get my result output from given array object.
Thanks in advance.

答:
```<code>var arr = [
    {'key1':'A','key2':1,'key3':0.04},
    {'key1':'B','key2':1,'key3':0.03},
    {'key1':'B','key2':2,'key3':0.05},
    {'key1':'A','key2':1,'key3':0.03}
];
var tempArr = $.extend(true, [], arr);
var newArray = new Array();
var len = arr.length;
for(var i=0;i<len;i++){
    var totalk3 = arr[i].key3;

    for(var j=i+1;j<tempArr.length;j++){

        if(arr[i].key1 == tempArr[j].key1 && arr[i].key2 == tempArr[j].key2){
            totalk3 = totalk3 + tempArr[j].key3;
            arr.splice(j,1);
        }
    }

    var json1 = {};
    var json2 = {};
    json2[arr[i].key2] = totalk3;
    json1[arr[i].key1]=json2;
    newArray[i] = json1;

    len = arr.length;
}
console.log(newArray);
</code>```

Title: Re indexing array-object in jquery

Body:
I have an array with object like this

var arr = [
  {'key1':'A','key2':1,'key3':0.04,'key4':10},
  {'key1':'B','key2':1,'key3':0.03,'key4':20},
  {'key1':'B','key2':2,'key3':0.05,'key4':30},
  {'key1':'A','key2':1,'key3':0.03,'key4':40},
  ...
];

Inside array there can be unlimited objects. I need to create new array where every key1 and key2 must save unique and if same key1 and key2,then key3 must be added. My result for above array look like this

//Can be array or object
var a = [
  ['A'][1] => {'key3':0.07,'key4':50},
  ['B'][1] => {'key3':0.07,'key4':20},
  ['B'][2] => {'key3':0.05,'key4':30}
];

My result can be array or object. What I have tried is

var a = {};
arr.forEach(function(obj){
  if(a[obj.key1]){
    if(a[obj.key1][obj.key2]){
      a[obj.key1][obj.key2] += obj.key3;
    }else{
      a[obj.key1][obj.key2] = obj.key3;
    }
  }else{
    a[obj.key1] = obj.key1;
  }
});
console.log(a);

And I am getting only depth of result. Please suggest me how can I get my result output from given array object.
Thanks in advance.


问:
How to pass data from an activity to a fragment in TabHost?
I have a page divided like this: there is the "Main" layout which holds a fragment

```<code><fragment
    android:name="com.x.x.FirstFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/firstFragment"
    tools:layout="@layout/first_fragment" />
</code>```

Inside that fragment in an external layout I've created a TabHost like this:

```<code><TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tabHost">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <fragment
                android:id="@+id/first"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.First"
                tools:layout="@layout/first" />

            <fragment
                android:id="@+id/second"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.Second"
                tools:layout="@layout/second" />

        </FrameLayout>
    </LinearLayout>
</TabHost>
</code>```

The problem is that I need to run a method inside the "First" class when a button inside the "Main" class has been clicked.

I've been struggling with this problem since yesterday, is there any solution?

Thank you.

答:
You can call the method of First.class from the Main.class by simply using this code.
Inside your Main.class</p>

```<code>new First.method();
</code>```

Body:
I have a page divided like this: there is the "Main" layout which holds a fragment

<fragment
    android:name="com.x.x.FirstFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/firstFragment"
    tools:layout="@layout/first_fragment" />

Inside that fragment in an external layout I've created a TabHost like this:

<TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tabHost">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <fragment
                android:id="@+id/first"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.First"
                tools:layout="@layout/first" />

            <fragment
                android:id="@+id/second"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.Second"
                tools:layout="@layout/second" />

        </FrameLayout>
    </LinearLayout>
</TabHost>

The problem is that I need to run a method inside the "First" class when a button inside the "Main" class has been clicked.

I've been struggling with this problem since yesterday, is there any solution?

Thank you.

Body:
You can call the method of First.class from the Main.class by simply using this code.
Inside your Main.class

new First.method();


问:
How to enable filtering on an ObjectDataSource with FilterExpression when bound to a List<object>.
Does anyone know how to use FilterExpression with an ObjectDataSource when it is bound using a select method that returns a list of entity objects?

I get the following error when I attempt it:

"The data source 'testODS' only supports filtering when the SelectMethod returns a DataSet or a DataTable"

答:
Why not just do what the error says and use a DataTable or DataSet?

Convert generic list to dataset in C#


问:
Get object from parent class object
I have class

```<code>public class IPTable : SerializableDictionary<string, string>
{
...
}
</code>```

trying to deserialize IPTable:

```<code>XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, string>));
StreamReader textReader = new StreamReader(xmlFileName);
SerializableDictionary<string, string> ip =( SerializableDictionary < string, string>) serializer.Deserialize(textReader);
return (IPTable)ip;
</code>```

Got exception below while casting SerializableDictionary<string, string> to IPTable.

```<code>Message = "Unable to cast object of type 'SerializableDictionary`2[System.String,System.String]' to type 'IPTable'."
</code>```

How to deserialize to IPTable?

答:
Create your XmlSerializer with IPTable

```<code>XmlSerializer serializer = new XmlSerializer(typeof(IPTable));
StreamReader textReader = new StreamReader(xmlFileName);
return (IPTable)serializer.Deserialize(textReader);
</code>```

Title: Get object from parent class object

Body:
I have class

public class IPTable : SerializableDictionary<string, string>
{
...
}

trying to deserialize IPTable:

XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, string>));
StreamReader textReader = new StreamReader(xmlFileName);
SerializableDictionary<string, string> ip =( SerializableDictionary < string, string>) serializer.Deserialize(textReader);
return (IPTable)ip;

Got exception below while casting SerializableDictionary<string, string> to IPTable.

Message = "Unable to cast object of type 'SerializableDictionary`2[System.String,System.String]' to type 'IPTable'."

How to deserialize to IPTable?

Body:
Create your XmlSerializer with IPTable

XmlSerializer serializer = new XmlSerializer(typeof(IPTable));
StreamReader textReader = new StreamReader(xmlFileName);
return (IPTable)serializer.Deserialize(textReader);


问:
How to root Genymotion Android Emulator?
I have downloaded Genymotion Android Emulator for personal use. I searched over internet to root this device, forums says that via adb shell its already rooted -"agreed".

```<code>Sumits-MacBook-Pro:sdk eSumit$ adb -s 192.168.57.102:5555 shell
root@vbox86p:/ #
root@vbox86p:/ # whoami
root
</code>```

Found Genymotion configure apk, it will help to root access, if checkbox  get clicked - "always allow su access", I did that as well, and then it get stuck like here. (see below)

If I restart by myself, it shows that no root access ?

May I know what I am missing here ?

Here are the pictures sequence :

I have also followed various tutorials e.g. Youtube - how to root genymotion emulator Android 7.0  but no solution yet

答: Maybe it uses Iso file mounting system like Bluestacks that's why I guess it can't be rooted and also if it says its rooted then you can use UltraISO to modify root files only if it uses ISO file system.</p>

Body:
I have downloaded Genymotion Android Emulator for personal use. I searched over internet to root this device, forums says that via adb shell its already rooted -"agreed".

Sumits-MacBook-Pro:sdk eSumit$ adb -s 192.168.57.102:5555 shell
root@vbox86p:/ #
root@vbox86p:/ # whoami
root

Found Genymotion configure apk, it will help to root access, if checkbox  get clicked - "always allow su access", I did that as well, and then it get stuck like here. (see below)

If I restart by myself, it shows that no root access ?

May I know what I am missing here ?

Here are the pictures sequence :

I have also followed various tutorials e.g. Youtube - how to root genymotion emulator Android 7.0  but no solution yet


问:
Confused by relation between DOM and HTML (APIs)
How are DOM and HTML related? Is one subset of another, is one a more abstract concept than the another? Is HTML an extension of DOM? Or do they describe rather unrelated concepts (related only in that you can transform from HTML into DOM)? How would you draw these 2 in one picture if you had to?

For example, what is the purpose of these difference specs. Both first and last links contain information about HTMLElement..

http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/

http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/

http://www.w3.org/TR/html5/

I found a possible answer to this question here: http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html#ID-1176245063-h2, which is

The goals of the HTML-specific DOM API are:

to specialize and add functionality that relates specifically to HTML documents and elements

...

to provide convenience mechanisms, where appropriate, for common and frequent operations on HTML documents.

Does this mean that the 3rd link in the list above extends the DOM Core, which is described in the 1st link?

Or if you implement DOM Core, that allows you to manipulate simple documents, but if you implement HTML, that gives you like a super-DOM that allows you to manipulate more complicated objects?

Finally, say you want to implement your own browser that is able to open only HTML5 websites (render, as well as support JavaScript). Is it enough to read the specification found in the 3rd link, or do you first need to implement everything provided in DOM and then implement HTML5 specific things?

UPDATE

I guess I'm wondering about DOM API vs HTML API vs DOM HTML API vs HTML DOM API.

答:
In short:

The HTML standards define the HTML language - which tags / attributes exist and what they mean.

The DOM standards define interfaces that are implemented by the objects from the DOM object tree in the browser. (The web-browser parses the HTML source code and creates an object tree based on it. The objects in that tree have properties which are defined by DOM (and other) standards.)

The HTML5 standard also defines interfaces for stuff that wasn't defined before - like the window object, the navigator and history object, global functions like alert and prompt, timeout functions, etc.

The different standards are not subsets of each other - they are just distinct standards that define a piece of the whole picture.