问:
Adding a new Field to FDMemTable when loading an existing data
I'm using TFDMemTable, i have created a dataset and populated my table with data and then used FDMemTable.saveToFile to save my data.

Now here is the question, how can i add a new Field to this already saved data and fill all records with a default value ?

I tried adding the new Field to the FDMemTable and then loading the information hoping it would automatically fill each Field using it's FieldName and the new field with an empty space, but i got an error saying  :
`---------------------------

Debugger Exception Notification

Project Project1.exe raised exception class EDatabaseError with message 'Field 'Episode' not found'.

Break   Continue   Help

`

How can i fix this ? is there a work around for adding a new field with default value to an already existing data ?

Here is a testcase:

```<code>// here is a simple example, i have a few fields
FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

FDMemTable1.CreateDataSet;

// i fill the the table with some value
FDMemTable1.Open;
FDMemTable1.AppendRecord([1, 'Movie1', 1]);
FDMemTable1.AppendRecord([2, 'Movie2', 2]);
FDMemTable1.AppendRecord([3, 'Movie3', 1]);

// after seeing the value on the grid, i push a button and save the table as XML
FDMemTable1.saveToFile('Data.xml');

// now after closing the program and running it again, i want to load the data with a new FieldDef Called Episode with a default value 0
// the table is connected to cxGrid, and the moment i try to load, i get the error i mentioned.

FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
// this line is NEW
FDMemTable1.FieldDefs.Add('Episode', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

FDMemTable1.CreateDataSet;

// i try to load but i get an error
FDMemTable1.loadFromFile('Data.xml');
</code>```

Update 1 (based on Victoria's answer) :

```<code>//All the codes below are executed after the code at the top, after the loadFromFile.
  FDMemTable1.ResourceOptions.StoreItems := FDMemTable1.ResourceOptions.StoreItems + [siMeta];
  FDMemTable1.Close;

  //i tried putting FDMemTable1 as the owner but when i try the line "FDMemTable1.Fields.add" i get an Duplicate error!
  // and when i try putting nil, i get access violation ! so i tried putting the owner someother random table and it fixed the problem
  fieldDefs := TFieldDefs.Create(someRandomFDMemTable);
  fieldDefs.Add('Episodes', ftString, 30, false);

  FDMemTable1.Fields.Add(fieldDefs.Items[0].CreateField(FDMemTable1));
  FDMemTable1.Open;
</code>```

As you can see i have two problem,

1- I have a problem with adding a new field! where i get an error, i first tried using TFieldDef instead of TFieldDefs but i couldn't get it to work.

2- Is the fact that all the columns are empty and there is no data on the grid.

Problem 2 occurs when i try solving the problem 1 forcefully.

答:
The code below works fine for me in Delphi Seattle.  It's closely based on yours but with a few minor changes (see comments) and one important addition.

The thing is, if you closely observe FDMemTable1.loadFromFile, it actually clears the FieldDefs/Fields, so there's not a lot of point setting them up again in the first place, so your added Episode field is just going to get omitted from the loaded dataset.

To avoid that, the addition I've made is to use a temporary TFDMemTable, loaded the XML file into that, then copied its contents to FDMemTable1 using CopyDataSet.  FDMemTable1 retains the added Episode field in the process, and you can of course add code to set the Episode field data once CopyDataSet has been called.

```<code>procedure TForm1.AddFieldTest;
var
  DataFN : String;
  TempMemTable : TFDMemTable;
begin
  // Added, to avoid relative path for data file name
  DataFN := ExtractFilePath(Application.ExeName) + 'Data.Xml';

  FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
  FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
  FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

  FDMemTable1.CreateDataSet;

  // i fill the the table with some value
  FDMemTable1.Open;
  FDMemTable1.AppendRecord([1, 'Movie1', 1]);
  FDMemTable1.AppendRecord([2, 'Movie2', 2]);
  FDMemTable1.AppendRecord([3, 'Movie3', 1]);

  // after seeing the value on the grid, i push a button and save the table as XML
  FDMemTable1.saveToFile(DataFN);

  // Added, close the dataset and clear the FieldDefs
  // Without the FieldDefs.Clear call, your code produces a "Duplicate field ID" error
  FDMemTable1.Close;
  FDMemTable1.FieldDefs.Clear;

  // now after closing the program and running it again, i want to load the data with a new FieldDef Called Episode with a default value 0
  // the table is connected to cxGrid, and the moment i try to load, i get the error i mentioned.

  FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
  FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
  // this line is NEW
  FDMemTable1.FieldDefs.Add('Episode', ftInteger, 0, false);
  FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

  FDMemTable1.CreateDataSet;

  // check the FieldCount and existence of the Episode field
  Caption := IntToStr(FDMemTable1.FieldCount);
  Assert(FDMemTable1.FindField('Episode') <> Nil);

  //  Create a temporary TFDMemTable
  TempMemTable := TFDMemTable.Create(Nil);
  try
    //  load the data into the temporary TFDMemTable
    TempMemTable.loadFromFile(DataFN);
    //  copy the data from the temporary TFDMemTable into FDMemTable1
    FDMemTable1.CopyDataSet(TempMemTable, [coAppend]);

  // check the FieldCount and existence of the Episode field
    Caption := IntToStr(FDMemTable1.FieldCount);
    Assert(FDMemTable1.FindField('Episode') <> Nil);
  finally
    TempMemTable.Free;
  end;
end;
</code>```

Body:
I'm using TFDMemTable, i have created a dataset and populated my table with data and then used FDMemTable.saveToFile to save my data.

Now here is the question, how can i add a new Field to this already saved data and fill all records with a default value ?

I tried adding the new Field to the FDMemTable and then loading the information hoping it would automatically fill each Field using it's FieldName and the new field with an empty space, but i got an error saying  :
`---------------------------

Debugger Exception Notification

Project Project1.exe raised exception class EDatabaseError with message 'Field 'Episode' not found'.

Break   Continue   Help

`

How can i fix this ? is there a work around for adding a new field with default value to an already existing data ?

Here is a testcase:

// here is a simple example, i have a few fields
FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

FDMemTable1.CreateDataSet;

// i fill the the table with some value
FDMemTable1.Open;
FDMemTable1.AppendRecord([1, 'Movie1', 1]);
FDMemTable1.AppendRecord([2, 'Movie2', 2]);
FDMemTable1.AppendRecord([3, 'Movie3', 1]);

// after seeing the value on the grid, i push a button and save the table as XML
FDMemTable1.saveToFile('Data.xml');

// now after closing the program and running it again, i want to load the data with a new FieldDef Called Episode with a default value 0
// the table is connected to cxGrid, and the moment i try to load, i get the error i mentioned.

FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
// this line is NEW
FDMemTable1.FieldDefs.Add('Episode', ftInteger, 0, false);
FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

FDMemTable1.CreateDataSet;

// i try to load but i get an error
FDMemTable1.loadFromFile('Data.xml');

Update 1 (based on Victoria's answer) :

//All the codes below are executed after the code at the top, after the loadFromFile.
  FDMemTable1.ResourceOptions.StoreItems := FDMemTable1.ResourceOptions.StoreItems + [siMeta];
  FDMemTable1.Close;

  //i tried putting FDMemTable1 as the owner but when i try the line "FDMemTable1.Fields.add" i get an Duplicate error!
  // and when i try putting nil, i get access violation ! so i tried putting the owner someother random table and it fixed the problem
  fieldDefs := TFieldDefs.Create(someRandomFDMemTable);
  fieldDefs.Add('Episodes', ftString, 30, false);

  FDMemTable1.Fields.Add(fieldDefs.Items[0].CreateField(FDMemTable1));
  FDMemTable1.Open;

As you can see i have two problem,

1- I have a problem with adding a new field! where i get an error, i first tried using TFieldDef instead of TFieldDefs but i couldn't get it to work.

2- Is the fact that all the columns are empty and there is no data on the grid.

Problem 2 occurs when i try solving the problem 1 forcefully.

Body:
The code below works fine for me in Delphi Seattle.  It's closely based on yours but with a few minor changes (see comments) and one important addition.

The thing is, if you closely observe FDMemTable1.loadFromFile, it actually clears the FieldDefs/Fields, so there's not a lot of point setting them up again in the first place, so your added Episode field is just going to get omitted from the loaded dataset.

To avoid that, the addition I've made is to use a temporary TFDMemTable, loaded the XML file into that, then copied its contents to FDMemTable1 using CopyDataSet.  FDMemTable1 retains the added Episode field in the process, and you can of course add code to set the Episode field data once CopyDataSet has been called.

procedure TForm1.AddFieldTest;
var
  DataFN : String;
  TempMemTable : TFDMemTable;
begin
  // Added, to avoid relative path for data file name
  DataFN := ExtractFilePath(Application.ExeName) + 'Data.Xml';

  FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
  FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
  FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

  FDMemTable1.CreateDataSet;

  // i fill the the table with some value
  FDMemTable1.Open;
  FDMemTable1.AppendRecord([1, 'Movie1', 1]);
  FDMemTable1.AppendRecord([2, 'Movie2', 2]);
  FDMemTable1.AppendRecord([3, 'Movie3', 1]);

  // after seeing the value on the grid, i push a button and save the table as XML
  FDMemTable1.saveToFile(DataFN);

  // Added, close the dataset and clear the FieldDefs
  // Without the FieldDefs.Clear call, your code produces a "Duplicate field ID" error
  FDMemTable1.Close;
  FDMemTable1.FieldDefs.Clear;

  // now after closing the program and running it again, i want to load the data with a new FieldDef Called Episode with a default value 0
  // the table is connected to cxGrid, and the moment i try to load, i get the error i mentioned.

  FDMemTable1.FieldDefs.Add('ID', ftInteger, 0, false);
  FDMemTable1.FieldDefs.Add('name', ftString, 30, false);
  // this line is NEW
  FDMemTable1.FieldDefs.Add('Episode', ftInteger, 0, false);
  FDMemTable1.FieldDefs.Add('QualityID', ftInteger, 0, false);

  FDMemTable1.CreateDataSet;

  // check the FieldCount and existence of the Episode field
  Caption := IntToStr(FDMemTable1.FieldCount);
  Assert(FDMemTable1.FindField('Episode') <> Nil);

  //  Create a temporary TFDMemTable
  TempMemTable := TFDMemTable.Create(Nil);
  try
    //  load the data into the temporary TFDMemTable
    TempMemTable.loadFromFile(DataFN);
    //  copy the data from the temporary TFDMemTable into FDMemTable1
    FDMemTable1.CopyDataSet(TempMemTable, [coAppend]);

  // check the FieldCount and existence of the Episode field
    Caption := IntToStr(FDMemTable1.FieldCount);
    Assert(FDMemTable1.FindField('Episode') <> Nil);
  finally
    TempMemTable.Free;
  end;
end;


来源: stackexchange

问:
Can I edit the file app\Http\Controllers\Controller.php in laravel?
I'm a beginner, and I have a stupid question, I really want to edit this file. Can I do this?

And when I update new Laravel version, is this file be replace by default?

Thank You!

答: Yes, you can edit app/Http/Controllers/Controller.php. In fact, you are free to edit any files in the app directory. The app directory is never touched when you upgrade your Laravel version. You have to do any required upgrade-related changes manually.

ContentLicense: CC BY-SA 3.0


问:
SQL: Efficiently Calculate Time Spent
Given a list of event timestamps, how do you calculate the "time spent"? The "time spent" is the sum of the time intervals between each timestamp, ignoring intervals above a certain threshold, e.g. 1 minute, during which the user was probably inactive.

I tried something like this:

```<code>select sum(finish - start)
from (select start.time as start,
             finish.time as finish
      from events start, events finish
      where start.time < finish.time and
            finish.time - start.time < interval '1 minute'
      group by start.time) as intervals;
</code>```

But this proved vastly inefficient and never terminated.

答:
Use:

```<code>SELECT SUM ( time_interval_up_to_1_min )
FROM (
  SELECT
        CASE WHEN time - lag( time ) over (ORDER BY time)
                <= interval '1' minute
             THEN time - lag( time ) over (ORDER BY time)
        END As time_interval_up_to_1_min
  FROM events
) x
</code>```

Demo: http://sqlfiddle.com/#!17/6f814/7

Title: SQL: Efficiently Calculate Time Spent

Body:
Given a list of event timestamps, how do you calculate the "time spent"? The "time spent" is the sum of the time intervals between each timestamp, ignoring intervals above a certain threshold, e.g. 1 minute, during which the user was probably inactive.

I tried something like this:

select sum(finish - start)
from (select start.time as start,
             finish.time as finish
      from events start, events finish
      where start.time < finish.time and
            finish.time - start.time < interval '1 minute'
      group by start.time) as intervals;

But this proved vastly inefficient and never terminated.

Body:
Use:

SELECT SUM ( time_interval_up_to_1_min )
FROM (
  SELECT
        CASE WHEN time - lag( time ) over (ORDER BY time)
                <= interval '1' minute
             THEN time - lag( time ) over (ORDER BY time)
        END As time_interval_up_to_1_min
  FROM events
) x

Demo: http://sqlfiddle.com/#!17/6f814/7


问:
C# Elegant way to handle checking for an item in a collection
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

```<code>TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }
</code>```

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

答:
IEnumerable.Any(...) should work for your case:   </p>

```<code>termsStore.Groups.Any()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

Body:
IEnumerable.Any(...) should work for your case:

termsStore.Groups.Any()


问:
Display text with icon in Xamarin forms
How to display text with icon in button? I am using font awesome icons and displaying them using their uni code. Like this:

Now if i add unicode with text the icon doesnt show although text still shows.

This only shows text and Cross instead of icon.

答: Font awsome is a font, so it can't be in the same block as other text. We need 2 blocks so you can control the font for each of them. </p>

Title: Display text with icon in Xamarin forms


问:
How to choose starting Activity based on condition
I have 4 radio buttons like below and i want to select only 1 out of any 4 choices and also one time after that user can't go back to change the choices he filled.......and when the app opens user should be directed to the activity filled by his choice. How should i do that?
Thank you.</p>

```<code>RadioButton FourthGrade = (RadioButton) findViewById(R.id.grade_4th);

            FourthGrade.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(CourseSelectionActivity.this, Home.class);
                    startActivity(intent);
                }
            });
</code>```

答:
You could create a "navigator" Activity as an entry point to your app, something like this:

```<code>public class NavigatorActivity extends AppCompatActivity {

    public static final String KEY_CHOICE = "choice";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // fetch the choice of the user, or return -1 if there is no choice yet
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        int choice = prefs.getInt(KEY_CHOICE, -1);
        Intent intent = createIntentBasedOnChoice(this, choice);

        startActivity(intent);
        finish();
    }

    // this method returns an Intent based on the passed choice parameter
    public static Intent createIntentBasedOnChoice(Context context, int choice) {
        Intent intent;

        switch (choice) {
            case 1: {
                intent = new Intent(context, FirstActivity.class);
                break;
            }
            case 2: {
                intent = new Intent(context, SecondActivity.class);
                break;
            }
            case 3: {
                intent = new Intent(context, ThirdActivity.class);
                break;
            }
            case 4: {
                intent = new Intent(context, FourthActivity.class);
                break;
            }
            default: {
                // if there is no choice yet, start the ChoiceActivity
                intent = new Intent(context, ChoiceActivity.class);
                break;
            }
        }
        return intent;
    }
}
</code>```

This would navigate to one of the four activities depending on the user's preceding choice. If the user has not chosen yet, it will navigate to ChoiceActivity.

A basic layout for ChoiceActivity:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RadioGroup
        android:id="@+id/group_choices"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/button_choice1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Choice 1" />

        <RadioButton
            android:id="@+id/button_choice2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Choice 2" />

        <RadioButton
            android:id="@+id/button_choice3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Choice 3" />

        <RadioButton
            android:id="@+id/button_choice4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Choice 4" />

    </RadioGroup>

    <Button
        android:id="@+id/button_submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is my choice!" />
</LinearLayout>
</code>```

And its code would look something like this:

```<code>public class ChoiceActivity extends AppCompatActivity {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choice);

        final RadioGroup choiceGroup = (RadioGroup) findViewById(
            R.id.group_choices);
        Button submitButton = (Button) findViewById(R.id.button_submit);

        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int choice;

                switch (choiceGroup.getCheckedRadioButtonId()) {
                    case R.id.button_choice1: {
                        choice = 1;
                        break;
                    }
                    case R.id.button_choice2: {
                        choice = 2;
                        break;
                    }
                    case R.id.button_choice3: {
                        choice = 3;
                        break;
                    }
                    case R.id.button_choice4: {
                        choice = 4;
                        break;
                    }
                    default: {
                        choice = 1;
                        break;
                    }
                }

                // saving the choice of the user
                PreferenceManager
                    .getDefaultSharedPreferences(ChoiceActivity.this)
                    .edit()
                    .putInt(NavigatorActivity.KEY_CHOICE, choice)
                    .apply();

                Intent intent = NavigatorActivity
                    .createIntentBasedOnChoice(ChoiceActivity.this, choice);

                startActivity(intent);
                finish();
            }
        });
    }
}
</code>```

This will save the user's choice in SharedPreferences and navigate forward to the appropriate Activity.

This is just a very basic example to get you going, tailor it according to your needs.

Body:
I have 4 radio buttons like below and i want to select only 1 out of any 4 choices and also one time after that user can't go back to change the choices he filled.......and when the app opens user should be directed to the activity filled by his choice. How should i do that?
Thank you.

RadioButton FourthGrade = (RadioButton) findViewById(R.id.grade_4th);

            FourthGrade.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(CourseSelectionActivity.this, Home.class);
                    startActivity(intent);
                }
            });

Body:
You could create a "navigator" Activity as an entry point to your app, something like this:

public class NavigatorActivity extends AppCompatActivity {

    public static final String KEY_CHOICE = "choice";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // fetch the choice of the user, or return -1 if there is no choice yet
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        int choice = prefs.getInt(KEY_CHOICE, -1);
        Intent intent = createIntentBasedOnChoice(this, choice);

        startActivity(intent);
        finish();
    }

    // this method returns an Intent based on the passed choice parameter
    public static Intent createIntentBasedOnChoice(Context context, int choice) {
        Intent intent;

        switch (choice) {
            case 1: {
                intent = new Intent(context, FirstActivity.class);
                break;
            }
            case 2: {
                intent = new Intent(context, SecondActivity.class);
                break;
            }
            case 3: {
                intent = new Intent(context, ThirdActivity.class);
                break;
            }
            case 4: {
                intent = new Intent(context, FourthActivity.class);
                break;
            }
            default: {
                // if there is no choice yet, start the ChoiceActivity
                intent = new Intent(context, ChoiceActivity.class);
                break;
            }
        }
        return intent;
    }
}

This would navigate to one of the four activities depending on the user's preceding choice. If the user has not chosen yet, it will navigate to ChoiceActivity.

A basic layout for ChoiceActivity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RadioGroup
        android:id="@+id/group_choices"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/button_choice1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Choice 1" />

        <RadioButton
            android:id="@+id/button_choice2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Choice 2" />

        <RadioButton
            android:id="@+id/button_choice3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Choice 3" />

        <RadioButton
            android:id="@+id/button_choice4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Choice 4" />

    </RadioGroup>

    <Button
        android:id="@+id/button_submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is my choice!" />
</LinearLayout>

And its code would look something like this:

public class ChoiceActivity extends AppCompatActivity {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choice);

        final RadioGroup choiceGroup = (RadioGroup) findViewById(
            R.id.group_choices);
        Button submitButton = (Button) findViewById(R.id.button_submit);

        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int choice;

                switch (choiceGroup.getCheckedRadioButtonId()) {
                    case R.id.button_choice1: {
                        choice = 1;
                        break;
                    }
                    case R.id.button_choice2: {
                        choice = 2;
                        break;
                    }
                    case R.id.button_choice3: {
                        choice = 3;
                        break;
                    }
                    case R.id.button_choice4: {
                        choice = 4;
                        break;
                    }
                    default: {
                        choice = 1;
                        break;
                    }
                }

                // saving the choice of the user
                PreferenceManager
                    .getDefaultSharedPreferences(ChoiceActivity.this)
                    .edit()
                    .putInt(NavigatorActivity.KEY_CHOICE, choice)
                    .apply();

                Intent intent = NavigatorActivity
                    .createIntentBasedOnChoice(ChoiceActivity.this, choice);

                startActivity(intent);
                finish();
            }
        });
    }
}

This will save the user's choice in SharedPreferences and navigate forward to the appropriate Activity.

This is just a very basic example to get you going, tailor it according to your needs.


问:
Access impersonated account's private keys
I'm working on a program that is intended to impersonate another account and then decrypt a file using a private key from the impersonated account's keystore.

The problem is that although I'm able to open the impersonated account's certificate store and instantiate an X509Certificate2 object with the appropriate cert, when the program attempts to access the private key, I receive an exception:

System.Security.Cryptography.CryptographicException: The system cannot find the file specified...at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()

I was able to locate the impersonated user's private key in the file system using the FindPrivateKey.exe utility & found it located in C:\Users\TESTUSR\AppData\Roaming\Microsoft\Crypto\RSA...  I used this article as a guide to ensure that my own account has access to the private key file.  I definitely have access to the key file from an NTFS perspective as I can load it in notepad (although it's jiberish, obviously).

Quite by accident, I discovered that the program does work if I pre-load the impersonated account's local profile by using runas to, for instance, open a command prompt as that user.

Any advice would be greatly appreciated!

```<code>class Program
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
    int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    static void Main(string[] args)
    {
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;

        SafeTokenHandle safeTokenHandle;

        try
        {
            string username = "TESTUSR";
            string domain = "CONTOSO";
            string password = "P@ssw0rd";

            // Call LogonUser to obtain a handle to an access token.
            if (!LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle))
                return;

            if (safeTokenHandle == null)
            {
                int ret = Marshal.GetLastWin32Error();
                throw new System.ComponentModel.Win32Exception(ret);
            }
            using (safeTokenHandle)
            {
                using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                {
                    using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                    {
                        string neededCertSN = "17396B080000000000A5";
                        X509Store my = new X509Store(StoreLocation.CurrentUser);
                        my.Open(OpenFlags.ReadOnly);

                        string result;
                        foreach (X509Certificate2 cert in my.Certificates)
                        {
                            if (Regex.IsMatch(neededCertSN, cert.SerialNumber))
                            {
                                result = DecryptFile(args[0], ".txt", (RSACryptoServiceProvider)cert.PrivateKey);
                                Console.WriteLine("Result:\r\n" + result);
                                return;
                            }
                        }

                        Console.WriteLine("Encryption certificate not found.");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An exception occurred:\r\n" + ex.ToString());
        }
    }

    static string DecryptFile(string cypherTextFile, string plainTextFileExtension, RSACryptoServiceProvider rsaPrivateKey)
    {
        string plainTextFile = string.Empty;
        try
        {
            if (!File.Exists(cypherTextFile))
                return "Cyphertext file not found";

            // Create instance of AesManaged for
            // symetric decryption of the data.
            using (AesManaged aesManaged = new AesManaged())
            {
                aesManaged.KeySize = 256;
                aesManaged.BlockSize = 128;
                aesManaged.Mode = CipherMode.CBC;

                // Create byte arrays to get the length of
                // the encrypted key and IV.
                // These values were stored as 4 bytes each
                // at the beginning of the encrypted package.
                byte[] LenK = new byte[4];
                byte[] LenIV = new byte[4];

                // Consruct the file name for the decrypted file.
                if (plainTextFileExtension[0] != '.')
                    plainTextFileExtension = "." + plainTextFileExtension;
                string[] parts = cypherTextFile.Split('.');
                for (int x = 0; x < parts.Length - 1; x++)
                    plainTextFile = plainTextFile + parts[x];
                plainTextFile = plainTextFile + plainTextFileExtension;

                // Use FileStream objects to read the encrypted
                // file (inFs) and save the decrypted file (outFs).
                using (FileStream inFs = new FileStream(cypherTextFile, FileMode.Open))
                {

                    inFs.Seek(0, SeekOrigin.Begin);
                    inFs.Seek(0, SeekOrigin.Begin);
                    inFs.Read(LenK, 0, 3);
                    inFs.Seek(4, SeekOrigin.Begin);
                    inFs.Read(LenIV, 0, 3);

                    // Convert the lengths to integer values.
                    int lenK = BitConverter.ToInt32(LenK, 0);
                    int lenIV = BitConverter.ToInt32(LenIV, 0);

                    // Determine the start postition of
                    // the ciphter text (startC)
                    // and its length(lenC).
                    int startC = lenK + lenIV + 8;
                    int lenC = (int)inFs.Length - startC;

                    // Create the byte arrays for
                    // the encrypted AesManaged key,
                    // the IV, and the cipher text.
                    byte[] KeyEncrypted = new byte[lenK];
                    byte[] IV = new byte[lenIV];

                    // Extract the key and IV
                    // starting from index 8
                    // after the length values.
                    inFs.Seek(8, SeekOrigin.Begin);
                    inFs.Read(KeyEncrypted, 0, lenK);
                    inFs.Seek(8 + lenK, SeekOrigin.Begin);
                    inFs.Read(IV, 0, lenIV);

                    // Use RSACryptoServiceProvider
                    // to decrypt the AesManaged key.
                    byte[] KeyDecrypted = rsaPrivateKey.Decrypt(KeyEncrypted, false);

                    // Decrypt the key.
                    using (ICryptoTransform transform = aesManaged.CreateDecryptor(KeyDecrypted, IV))
                    {

                        // Decrypt the cipher text from
                        // from the FileSteam of the encrypted
                        // file (inFs) into the FileStream
                        // for the decrypted file (outFs).
                        using (FileStream outFs = new FileStream(plainTextFile, FileMode.Create))
                        {

                            int count = 0;
                            int offset = 0;

                            int blockSizeBytes = aesManaged.BlockSize / 8;
                            byte[] data = new byte[blockSizeBytes];

                            // By decrypting a chunk a time,
                            // you can save memory and
                            // accommodate large files.

                            // Start at the beginning
                            // of the cipher text.
                            inFs.Seek(startC, SeekOrigin.Begin);
                            using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                            {
                                do
                                {
                                    count = inFs.Read(data, 0, blockSizeBytes);
                                    offset += count;
                                    outStreamDecrypted.Write(data, 0, count);

                                }
                                while (count > 0);

                                outStreamDecrypted.FlushFinalBlock();
                                outStreamDecrypted.Close();
                            }
                            outFs.Close();
                        }
                        inFs.Close();
                    }
                }
            }

            return plainTextFile;
        }
        catch (Exception e)
        {
            return "An exception occurred:\r\n" + e.ToString();
        }
    }

}

public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private SafeTokenHandle()
        : base(true)
    {
    }

    [DllImport("kernel32.dll")]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    [SuppressUnmanagedCodeSecurity]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr handle);

    protected override bool ReleaseHandle()
    {
        return CloseHandle(handle);
    }
}
</code>```

The problem I'm having is that although I'm able to open the impersonated account's certificate store & grab the correct cert in a X509Certificate2 object, when the program tries to use the private key, it's

答:
You need to manually load the users registry according to the CreateProcessAsUser documentation:

CreateProcessAsUser does not load the specified user's profile into the HKEY_USERS registry key. Therefore, to access the information in the HKEY_CURRENT_USER registry key, you must load the user's profile information into HKEY_USERS with the LoadUserProfile function before calling CreateProcessAsUser.

RunAs would not change HKEY_CURRENT_USER in your process but it will cause the hive to be loaded under HKEY_USERS.

You could try calling LoadUserProfile after LogonUser...

Body:
I'm working on a program that is intended to impersonate another account and then decrypt a file using a private key from the impersonated account's keystore.

The problem is that although I'm able to open the impersonated account's certificate store and instantiate an X509Certificate2 object with the appropriate cert, when the program attempts to access the private key, I receive an exception:

System.Security.Cryptography.CryptographicException: The system cannot find the file specified...at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()

I was able to locate the impersonated user's private key in the file system using the FindPrivateKey.exe utility & found it located in C:\Users\TESTUSR\AppData\Roaming\Microsoft\Crypto\RSA...  I used this article as a guide to ensure that my own account has access to the private key file.  I definitely have access to the key file from an NTFS perspective as I can load it in notepad (although it's jiberish, obviously).

Quite by accident, I discovered that the program does work if I pre-load the impersonated account's local profile by using runas to, for instance, open a command prompt as that user.

Any advice would be greatly appreciated!

class Program
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
    int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    static void Main(string[] args)
    {
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;

        SafeTokenHandle safeTokenHandle;

        try
        {
            string username = "TESTUSR";
            string domain = "CONTOSO";
            string password = "P@ssw0rd";

            // Call LogonUser to obtain a handle to an access token.
            if (!LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle))
                return;

            if (safeTokenHandle == null)
            {
                int ret = Marshal.GetLastWin32Error();
                throw new System.ComponentModel.Win32Exception(ret);
            }
            using (safeTokenHandle)
            {
                using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                {
                    using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                    {
                        string neededCertSN = "17396B080000000000A5";
                        X509Store my = new X509Store(StoreLocation.CurrentUser);
                        my.Open(OpenFlags.ReadOnly);

                        string result;
                        foreach (X509Certificate2 cert in my.Certificates)
                        {
                            if (Regex.IsMatch(neededCertSN, cert.SerialNumber))
                            {
                                result = DecryptFile(args[0], ".txt", (RSACryptoServiceProvider)cert.PrivateKey);
                                Console.WriteLine("Result:\r\n" + result);
                                return;
                            }
                        }

                        Console.WriteLine("Encryption certificate not found.");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An exception occurred:\r\n" + ex.ToString());
        }
    }

    static string DecryptFile(string cypherTextFile, string plainTextFileExtension, RSACryptoServiceProvider rsaPrivateKey)
    {
        string plainTextFile = string.Empty;
        try
        {
            if (!File.Exists(cypherTextFile))
                return "Cyphertext file not found";

            // Create instance of AesManaged for
            // symetric decryption of the data.
            using (AesManaged aesManaged = new AesManaged())
            {
                aesManaged.KeySize = 256;
                aesManaged.BlockSize = 128;
                aesManaged.Mode = CipherMode.CBC;

                // Create byte arrays to get the length of
                // the encrypted key and IV.
                // These values were stored as 4 bytes each
                // at the beginning of the encrypted package.
                byte[] LenK = new byte[4];
                byte[] LenIV = new byte[4];

                // Consruct the file name for the decrypted file.
                if (plainTextFileExtension[0] != '.')
                    plainTextFileExtension = "." + plainTextFileExtension;
                string[] parts = cypherTextFile.Split('.');
                for (int x = 0; x < parts.Length - 1; x++)
                    plainTextFile = plainTextFile + parts[x];
                plainTextFile = plainTextFile + plainTextFileExtension;

                // Use FileStream objects to read the encrypted
                // file (inFs) and save the decrypted file (outFs).
                using (FileStream inFs = new FileStream(cypherTextFile, FileMode.Open))
                {

                    inFs.Seek(0, SeekOrigin.Begin);
                    inFs.Seek(0, SeekOrigin.Begin);
                    inFs.Read(LenK, 0, 3);
                    inFs.Seek(4, SeekOrigin.Begin);
                    inFs.Read(LenIV, 0, 3);

                    // Convert the lengths to integer values.
                    int lenK = BitConverter.ToInt32(LenK, 0);
                    int lenIV = BitConverter.ToInt32(LenIV, 0);

                    // Determine the start postition of
                    // the ciphter text (startC)
                    // and its length(lenC).
                    int startC = lenK + lenIV + 8;
                    int lenC = (int)inFs.Length - startC;

                    // Create the byte arrays for
                    // the encrypted AesManaged key,
                    // the IV, and the cipher text.
                    byte[] KeyEncrypted = new byte[lenK];
                    byte[] IV = new byte[lenIV];

                    // Extract the key and IV
                    // starting from index 8
                    // after the length values.
                    inFs.Seek(8, SeekOrigin.Begin);
                    inFs.Read(KeyEncrypted, 0, lenK);
                    inFs.Seek(8 + lenK, SeekOrigin.Begin);
                    inFs.Read(IV, 0, lenIV);

                    // Use RSACryptoServiceProvider
                    // to decrypt the AesManaged key.
                    byte[] KeyDecrypted = rsaPrivateKey.Decrypt(KeyEncrypted, false);

                    // Decrypt the key.
                    using (ICryptoTransform transform = aesManaged.CreateDecryptor(KeyDecrypted, IV))
                    {

                        // Decrypt the cipher text from
                        // from the FileSteam of the encrypted
                        // file (inFs) into the FileStream
                        // for the decrypted file (outFs).
                        using (FileStream outFs = new FileStream(plainTextFile, FileMode.Create))
                        {

                            int count = 0;
                            int offset = 0;

                            int blockSizeBytes = aesManaged.BlockSize / 8;
                            byte[] data = new byte[blockSizeBytes];

                            // By decrypting a chunk a time,
                            // you can save memory and
                            // accommodate large files.

                            // Start at the beginning
                            // of the cipher text.
                            inFs.Seek(startC, SeekOrigin.Begin);
                            using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                            {
                                do
                                {
                                    count = inFs.Read(data, 0, blockSizeBytes);
                                    offset += count;
                                    outStreamDecrypted.Write(data, 0, count);

                                }
                                while (count > 0);

                                outStreamDecrypted.FlushFinalBlock();
                                outStreamDecrypted.Close();
                            }
                            outFs.Close();
                        }
                        inFs.Close();
                    }
                }
            }

            return plainTextFile;
        }
        catch (Exception e)
        {
            return "An exception occurred:\r\n" + e.ToString();
        }
    }

}

public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private SafeTokenHandle()
        : base(true)
    {
    }

    [DllImport("kernel32.dll")]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    [SuppressUnmanagedCodeSecurity]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr handle);

    protected override bool ReleaseHandle()
    {
        return CloseHandle(handle);
    }
}

The problem I'm having is that although I'm able to open the impersonated account's certificate store & grab the correct cert in a X509Certificate2 object, when the program tries to use the private key, it's


答: You can't edit only one folder - vendor</p>

Title: Can I edit the file app\Http\Controllers\Controller.php in laravel?

Body:
I'm a beginner, and I have a stupid question, I really want to edit this file. Can I do this?

And when I update new Laravel version, is this file be replace by default?

Thank You!

Body: You can't edit only one folder - vendor


问:
I want to send multiple product on stock.picking.form form mrp.bomline in odoo10

I create a button on a purchase order for material out which open stock.picking form and i want multiple products here.

def action_workorder_out(self):
    x = 0
    """ This opens the xml view specified in xml_id for the current Work Order in Manufacturing """
    self.ensure_one()
    xml_id = self.env.context.get('xml_id')
    if self.env.context.get('source_location_id'):

    defaults['location_id'] = self.env.context['source_location_id']
        # new_move = self.copy(defaults)
        res = self.env['ir.actions.act_window'].for_xml_id('stock', xml_id)

  purchase = self.env['purchase.order.line'].search([('order_id','=',self.product_id.id)])
        for record in purchase:
            x = record.product_id.id

        production = self.env['mrp.production'].search([('product_id','=',x)])

        for item in production:

            x = item.bom_id.id

        bomline = self.env['mrp.bom.line'].search([('bom_id','=',x)])

        for record in bomline:
         res.update(
                context={'default_states':'draft','default_origin':self.name,'default_partner_id': self.partner_id.id, 'default_incoterm_id': 0, 'default_picking_type_id':4    ,'default_move_lines': [(0,0, {'address_in_id':self.partner_id.id,'product_id':record.product_id.id,'product_uom': record.product_uom_id.id,'product_uom_qty':record.product_qty,'scrapped':False,'state':'draft','picking_id':False,'name': 'test','no_open': True,'no_create':True,'availability':1,'location_id':15,'location_dest_id':9,'picking_type_id':4,'date_expected':str(datetime.now()),})]}
            )
return res
return False
```

答:
```<code>@api.multi
def stock_move_line(self,picking_id):
    # stock_pick = self.env['stock.picking'].browse(picking_id)
    stock_move = self.env['stock.move']
    purchase = self.env['purchase.order.line'].search([('order_id','=',self.product_id.id)])
    for record in purchase:
        x = record.product_id.id

    production = self.env['mrp.production'].search([('product_id','=',x)])

    for item in production:

        x = item.bom_id.id

    bomline = self.env['mrp.bom.line'].search([('bom_id','=',x)])

    for record in bomline:
        data = {

                'product_id':record.product_id.id,
                'product_uom':record.product_uom_id.id,
                'product_uom_qty':record.product_qty,
                'company_id': self.env.user.company_id.id,
                'name': self.name,
                'picking_id': picking_id,
                'address_in_id':self.partner_id.id,
                'scrapped': False,
                'location_id':15,
                'location_dest_id':9,
                'picking_type_id':4,
                'procure_method':'make_to_stock',
                }

        move_line=stock_move.create(data)
</code>```

This is for material out for BOM

@api.multi
def action_workorder_out(self):
    x = 0
    update_qty = []
    res_obj = self.env['stock.picking']
    # """ This opens the xml view specified in xml_id for the current Work Order in Manufacturing """

    res=res_obj.create(
                {
                'work_center':self.work_center.id,
                'work_order':self.work_order ,
                'manfacturing_order':self.manfacturing_order.id,
                'origin':self.name,
                'partner_id': self.partner_id.id,
                'move_type':'direct',
                'company_id': self.env.user.company_id.id,
                'location_id':15,
                # 'default_location_id':15,
                'picking_type_id':4,
                'location_dest_id':9,

                }
            )

    self.stock_move_line(res.id)

    if self.env.context.get('source_location_id'):

        defaults['location_id'] = self.env.context['source_location_id']

    action = self.env.ref('stock.action_picking_tree_all').read()[0]
    # res = self.env['ir.actions.act_window'].for_xml_id('stock', xml_id)
    action['views'] = [(self.env.ref('stock.view_picking_form').id, 'form')]
    action['res_id'] = res.id
    purchase_order = self.env['purchase.order.line'].search([])
    for rec in purchase_order:
        print rec.product_qty,"##############################"
        update_qty.append(rec.product_qty)
        update_qty[-1]
    return action
```

Blockquote
  Here is we need to create another function and create data in both for stock,picking and move_lines.

ContentLicense: CC BY-SA 4.0

Body:
@api.multi
def stock_move_line(self,picking_id):
    # stock_pick = self.env['stock.picking'].browse(picking_id)
    stock_move = self.env['stock.move']
    purchase = self.env['purchase.order.line'].search([('order_id','=',self.product_id.id)])
    for record in purchase:
        x = record.product_id.id

    production = self.env['mrp.production'].search([('product_id','=',x)])

    for item in production:

        x = item.bom_id.id

    bomline = self.env['mrp.bom.line'].search([('bom_id','=',x)])

    for record in bomline:
        data = {

                'product_id':record.product_id.id,
                'product_uom':record.product_uom_id.id,
                'product_uom_qty':record.product_qty,
                'company_id': self.env.user.company_id.id,
                'name': self.name,
                'picking_id': picking_id,
                'address_in_id':self.partner_id.id,
                'scrapped': False,
                'location_id':15,
                'location_dest_id':9,
                'picking_type_id':4,
                'procure_method':'make_to_stock',
                }

        move_line=stock_move.create(data)

This is for material out for BOM

@api.multi
def action_workorder_out(self):
    x = 0
    update_qty = []
    res_obj = self.env['stock.picking']
    # """ This opens the xml view specified in xml_id for the current Work Order in Manufacturing """

    res=res_obj.create(
                {
                'work_center':self.work_center.id,
                'work_order':self.work_order ,
                'manfacturing_order':self.manfacturing_order.id,
                'origin':self.name,
                'partner_id': self.partner_id.id,
                'move_type':'direct',
                'company_id': self.env.user.company_id.id,
                'location_id':15,
                # 'default_location_id':15,
                'picking_type_id':4,
                'location_dest_id':9,

                }
            )

    self.stock_move_line(res.id)

    if self.env.context.get('source_location_id'):

        defaults['location_id'] = self.env.context['source_location_id']

    action = self.env.ref('stock.action_picking_tree_all').read()[0]
    # res = self.env['ir.actions.act_window'].for_xml_id('stock', xml_id)
    action['views'] = [(self.env.ref('stock.view_picking_form').id, 'form')]
    action['res_id'] = res.id
    purchase_order = self.env['purchase.order.line'].search([])
    for rec in purchase_order:
        print rec.product_qty,"##############################"
        update_qty.append(rec.product_qty)
        update_qty[-1]
    return action

Blockquote
  Here is we need to create another function and create data in both for stock,picking and move_lines.


问:
convert array_chunk from php to java
my php code is:</p>

```<code>$splitArray = array_chunk($theArray,ceil(count($theArray) / 2),true);
</code>```

答:
Java only supports numeric arrays, so you this will only work for a numeric array which  has no gaps. If u need a solution to deal with non-numeric values (i.e. Maps) post back, and I'll look into it.</p>

```<code>public void testMethod() {
    Object[] array={"one","two","three","four","five"};

    Object[][] chunkedArray = array_chunk(array,2);

    System.out.println(Arrays.deepToString(chunkedArray));

}

public Object[][] array_chunk(Object[] array,int size/*,FALSE Arrays are always numeric in java*/){
    Object[][] target= new Object[(array.length + size -1) / size][];

    for (int i = 0; i < target.length; i++) {
        int innerArraySize=array.length-i*size>=size?size:array.length-i*size;
        Object[] inner=new Object[innerArraySize];
        System.arraycopy(array, i*size, inner, 0, innerArraySize);
        target[i]=inner;
    }

    return target;
}
</code>```

Title: convert array_chunk from php to java

Body:
my php code is:

$splitArray = array_chunk($theArray,ceil(count($theArray) / 2),true);

Body:
Java only supports numeric arrays, so you this will only work for a numeric array which  has no gaps. If u need a solution to deal with non-numeric values (i.e. Maps) post back, and I'll look into it.

public void testMethod() {
    Object[] array={"one","two","three","four","five"};

    Object[][] chunkedArray = array_chunk(array,2);

    System.out.println(Arrays.deepToString(chunkedArray));

}

public Object[][] array_chunk(Object[] array,int size/*,FALSE Arrays are always numeric in java*/){
    Object[][] target= new Object[(array.length + size -1) / size][];

    for (int i = 0; i < target.length; i++) {
        int innerArraySize=array.length-i*size>=size?size:array.length-i*size;
        Object[] inner=new Object[innerArraySize];
        System.arraycopy(array, i*size, inner, 0, innerArraySize);
        target[i]=inner;
    }

    return target;
}


问:
TensorFlow wasn't compiled to use SSE (etc.) instructions, but these are available
I am running TensorFlow for the first time using some example code. I got the following warnings when running my code. Does anybody know why this happened, and how to fix it?</p>
```<code>2017-03-31 02:12:59.346109: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346968: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346975: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow libbrary wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346979: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346983: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346987: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346991: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346995: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
</code>```

答:
To hide those warnings, you could do this before your actual code.

```<code>import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
</code>```

for detailed discussion, please refer here https://github.com/tensorflow/tensorflow/issues/7778

I hope, it can be a help for the other. :)

Body:
I am running TensorFlow for the first time using some example code. I got the following warnings when running my code. Does anybody know why this happened, and how to fix it?

2017-03-31 02:12:59.346109: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346968: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346975: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow libbrary wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346979: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346983: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346987: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346991: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-03-31 02:12:59.346995: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.

Body:
To hide those warnings, you could do this before your actual code.

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf

for detailed discussion, please refer here https://github.com/tensorflow/tensorflow/issues/7778

I hope, it can be a help for the other. :)


问:
Using spinner font with rotation
I'm using a spinner icon from a font set and rotating it. I must set the transform-origin to define the centre of rotation of the icon to avoid wobbling (as suggested here). However, if I change the font size, the wobbling effect comes again. The same happens if I change the browser resolution.

HTML:

```<code><div>
  <p>First icon</p>
  <i id="first" class="fa fa-spinner rotation-animation"></i>
</div>
<div>
  <p>Second icon</p>
  <span id="second" class="fa fa-spinner rotation-animation"></span>
</div>
<div>
  <p>Third icon</p>
  <span id="third" class="fa fa-spinner rotation-animation"></span>
</div>
<div>
  <p>Fourth icon</p>
  <span id="fourth" class="fa fa-spinner rotation-animation"></span>
</div>
</code>```

CSS:

```<code>.rotation-animation {
    animation: div-rotate 0.7s infinite steps(8);
    transform: translateZ(0);
    -webkit-transform: translateZ(0);
    transform-origin: 50% 51%;
    -webkit-transform-origin: 50% 51%;
}

@keyframes div-rotate {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
@-webkit-keyframes div-rotate {
    0% {
        -webkit-transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(360deg);
    }
}

#first {
  font-size: 20px;
}
#second {
  font-size: 30px;
}
#third {
  font-size: 40px;
}
#fourth {
  font-size: 50px;
}
</code>```

https://jsfiddle.net/r944z1a6/

As you can see in the above link, the second icon is the only one which does not wobble. If you change the browser resolution, the second one will wobble too.

Why is it happening? The x and y percent offsets to the centre of rotation shouldn't change when changing the font size. Isn't it?
Is there any way to fix this and make the spinner not to wobble for any size/resolution?

Note: I've used font awesome for the example, but I'm actually using a custom font, which has the same effect.

EDIT:

Regardless of @vals answer, the only way that I've found which doesn't seem to wobble is using linear rotation:

```<code>animation: div-rotate 0.7s infinite linear;
</code>```

It's not so cool, but works.

答:
There is nothing wrong with the font-awesome icon, and spinning it.

Try setting it to 200px and you will see that it spins perfectly.

The wobbling that you see, and that you are trying to correct, arises from rounding px from the browser at small font sizes.
It's impossible to predict what will be the size rounding for any font size and browser zoom.

So, the only way to get a perfect solution is to make your effect at a larger scale, and then scale it

.rotation-animation {
    animation: div-rotate 0.7s infinite steps(8);
    transform: translateZ(0);
    transform-origin: 50% 50%;
}

@keyframes div-rotate {
      0% { transform: rotate(  0deg) scale(0.1);}
    100% { transform: rotate(360deg) scale(0.1);}
}

#first {
  font-size: 200px;
  margin: -90px;
}
#second {
  font-size: 300px;
  margin: -140px;
}
#third {
  font-size: 400px;
  margin: -180px;
}
#fourth {
  font-size: 500px;
  margin: -230px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div>
  <p>First icon</p>
  <i id="first" class="fa fa-spinner rotation-animation"></i>
</div>
<div>
  <p>Second icon</p>
  <span id="second" class="fa fa-spinner rotation-animation"></span>
</div>
<div>
  <p>Third icon</p>
  <span id="third" class="fa fa-spinner rotation-animation"></span>
</div>
<div>
  <p>Fourth icon</p>
  <span id="fourth" class="fa fa-spinner rotation-animation"></span>
</div></code>```

Title: Using spinner font with rotation

Body:
I'm using a spinner icon from a font set and rotating it. I must set the transform-origin to define the centre of rotation of the icon to avoid wobbling (as suggested here). However, if I change the font size, the wobbling effect comes again. The same happens if I change the browser resolution.

HTML:

First icon

Second icon

Third icon

Fourth icon

CSS:

.rotation-animation {
    animation: div-rotate 0.7s infinite steps(8);
    transform: translateZ(0);
    -webkit-transform: translateZ(0);
    transform-origin: 50% 51%;
    -webkit-transform-origin: 50% 51%;
}

@keyframes div-rotate {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
@-webkit-keyframes div-rotate {
    0% {
        -webkit-transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(360deg);
    }
}

#first {
  font-size: 20px;
}
#second {
  font-size: 30px;
}
#third {
  font-size: 40px;
}
#fourth {
  font-size: 50px;
}

https://jsfiddle.net/r944z1a6/

As you can see in the above link, the second icon is the only one which does not wobble. If you change the browser resolution, the second one will wobble too.

Why is it happening? The x and y percent offsets to the centre of rotation shouldn't change when changing the font size. Isn't it?
Is there any way to fix this and make the spinner not to wobble for any size/resolution?

Note: I've used font awesome for the example, but I'm actually using a custom font, which has the same effect.

EDIT:

Regardless of @vals answer, the only way that I've found which doesn't seem to wobble is using linear rotation:

animation: div-rotate 0.7s infinite linear;

It's not so cool, but works.

Body:
There is nothing wrong with the font-awesome icon, and spinning it.

Try setting it to 200px and you will see that it spins perfectly.

The wobbling that you see, and that you are trying to correct, arises from rounding px from the browser at small font sizes.
It's impossible to predict what will be the size rounding for any font size and browser zoom.

So, the only way to get a perfect solution is to make your effect at a larger scale, and then scale it

.rotation-animation {
    animation: div-rotate 0.7s infinite steps(8);
    transform: translateZ(0);
    transform-origin: 50% 50%;
}

@keyframes div-rotate {
      0% { transform: rotate(  0deg) scale(0.1);}
    100% { transform: rotate(360deg) scale(0.1);}
}

#first {
  font-size: 200px;
  margin: -90px;
}
#second {
  font-size: 300px;
  margin: -140px;
}
#third {
  font-size: 400px;
  margin: -180px;
}
#fourth {
  font-size: 500px;
  margin: -230px;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div>
  <p>First icon</p>
  <i id="first" class="fa fa-spinner rotation-animation"></i>
</div>
<div>
  <p>Second icon</p>
  <span id="second" class="fa fa-spinner rotation-animation"></span>
</div>
<div>
  <p>Third icon</p>
  <span id="third" class="fa fa-spinner rotation-animation"></span>
</div>
<div>
  <p>Fourth icon</p>
  <span id="fourth" class="fa fa-spinner rotation-animation"></span>
</div>


答:
yes u can edit, then make all the update changes manually. And
 just make sure not to touch vendor folder.</p>


问:
Possibly advanced SQL query UNION of 3 Tables
Goal. To make a query that displays Product Name(Products), Product Type(ProductTypes), and total number of sales of each product(Sales)

Here are my tables:

I am having real difficulty figuring out how I am meant to do this. I am trying to do a UNION and a few other things but cannot get it to work.
I can get the total number of sales by using this SELECT ProductID, count(*) as NumSales from Sales group by ProductID but really struggling to do the rest and format it correctly. Any help would be appreciated.

EDIT:

Select Products.ProductName, ProductTypes.ProductType
From Products
INNER JOIN ProductTypes ON Products.ProductTypeID=ProductTypes.ProductTypeID

I have this to display this right now, just need to join the sales count somehow.

答:
try:</p>

```<code>select prod.ProductName, ptyp.ProductType, count(SaleID) count_sale
from Products prod
join ProductTypes ptyp on ( ptyp.ProductTypeID= prod.ProductTypeID)
join Sales sal on ( sal.ProductID = prod.ProductID)

group by prod.ProductName, ptyp.ProductType
</code>```

Body:
try:

select prod.ProductName, ptyp.ProductType, count(SaleID) count_sale
from Products prod
join ProductTypes ptyp on ( ptyp.ProductTypeID= prod.ProductTypeID)
join Sales sal on ( sal.ProductID = prod.ProductID)

group by prod.ProductName, ptyp.ProductType


问:
Error dynamic link library in Firefox /bin/sh: symbol lookup error
I'm trying to load a library to Firefox, and I get the following error in the terminal:

http://pastebin.com/ZLryd20D,

```<code>gcc -Wall -fPIC -c 11.cpp ,

gcc -shared  -o libshared.so 11.o -ldl ,

LD_PRELOAD=$PWD/libshared.so firefox ,
</code>```

/bin/sh: symbol lookup error: /home/enigma/Desktop/compilacionproceso/libshared.so: undefined symbol: __gxx_personality_v0

答:
Answer from the OP himself, taken from a revision of the question:

I solved the problem adding a flag  -lstdc++ for create the library
  thanks to this post
  What is __gxx_personality_v0 for?

```<code>cd  /directory

gcc -Wall -fPIC -c 11.cpp

gcc -shared  -o libshared.so 11.o -ldl -lstdc++

LD_PRELOAD=$PWD/libshared.so program
</code>```

Body:
I'm trying to load a library to Firefox, and I get the following error in the terminal:

http://pastebin.com/ZLryd20D,

gcc -Wall -fPIC -c 11.cpp ,

gcc -shared  -o libshared.so 11.o -ldl ,

LD_PRELOAD=$PWD/libshared.so firefox ,

/bin/sh: symbol lookup error: /home/enigma/Desktop/compilacionproceso/libshared.so: undefined symbol: __gxx_personality_v0

Body:
Answer from the OP himself, taken from a revision of the question:

I solved the problem adding a flag  -lstdc++ for create the library
  thanks to this post
  What is __gxx_personality_v0 for?

cd  /directory

gcc -Wall -fPIC -c 11.cpp

gcc -shared  -o libshared.so 11.o -ldl -lstdc++

LD_PRELOAD=$PWD/libshared.so program


问:
"Inspect" a hover element?
Note: I've read similar threads, but none quite my issue - I can right click on it fine, it just then disappears.

I find 'Inspect Element' an invaluable tool in Chrome, however I'm having trouble using it for sub-menu for an element on my nav bar, which pops up below on hover of its parent item.

The popup (or down) isn't quite styled how I'd like, so I right-click > inspect element to see what's coming from where exactly, and get a better idea of how to achieve my desired effect.

However, as soon as I move my mouse away from the menu, it's gone; thus I can't select different elements in the inspection pane, and see which area is highlighted at the same time.

Is there a way around this, without changing the menu, so that it stays 'popped up' once activated?

答:
Excellent stuff!

Thank you to gmo for that advice. I did not know about those attribute settings massively helpful.

As a small revision to the wording I would explain that process as follows:

Right Click on the element you would like to style

Open 'Inspect' tool

On right hand side, navigate to the small Styles tab

Found above CSS stylesheet contents

Select the .hov option - This will give you all the settings
available for the selected HTML  element

Click and Change all options to be inactive

Now Select the state that you would like to tweak - On activation of any of these, your Stylesheet will jump you directly to those settings:

Styles - Tweaking Filters - Interactive elements

This information was a lifesaver for me, cannot believe I have just heard about it!

Title: "Inspect" a hover element?


答:
You need to normalize your data before you apply neuralnet(). So before splitting train1 into train/ test, use below code

```<code>maximum <- apply(train1, 2, max)
minimum <- apply(train1, 2, min)
train1_scaled <- as.data.frame(scale(train1, center=minimum, scale = maximum- minimum))
</code>```

Then use your code to split data and use below function

```<code>#linear.output should be TRUE as you are predicting continuos dependent variable
n <- neuralnet(Weekly_Sales~Temperature+Fuel_Price+MarkDown1+MarkDown2+MarkDown3+MarkDown4+MarkDown5+CPI+Unemployment+IsHoliday+Rank,data= train,hidden=c(4,3),err.fct="sse",linear.output=TRUE)
</code>```

Below code will also need slight modification after this

```<code>#basically to convert it back to non-scaled version, you need to do it using non-scaled original data not 'test' dataset
output1 <- output$net.result*(max(train1$Weekly_Sales)-min(train1$Weekly_Sales))+min(train1$Weekly_Sales)

#also the dependent variable in test dataset will need conversion
test$Weekly_Sales_nonScaled <- test$Weekly_Sales*(max(train1$Weekly_Sales)-min(train1$Weekly_Sales))+min(train1$Weekly_Sales)

#After this you can compare original data (test$Weekly_Sales_nonScaled) with predicted data (output1)
</code>```

Kindly don't forget to let us know if it helped :)

Title: Using package ' neuralnet ' in R to predict Weekly_Sales

Body:
I am completely new to R and I'm trying to predict the Weekly_Sales for a test dataset by training a neural network using neuralnet package in R.

The data I have looked (train1):

  Store Dep  Date     Temperature  Fuel_Price MarkDown1 MarkDown2 MarkDown3  MarkDown4  MarkDown5   CPI         Unemployment   IsHoliday    Rank Weekly_Sales
   1    1   5/2/2010       42.31      2.572     -2000      -500      -100        -500      -700 211.0963582        8.106         0         13     24924.50
   1    1  12/2/2010       38.51      2.548     -2000      -500      -100        -500      -700 211.2421698        8.106         1         13     46039.49
   1    1 19/02/2010       39.93      2.514     -2000      -500      -100        -500      -700 211.2891429        8.106         0         13     41595.55
   1    1 26/02/2010       46.63      2.561     -2000      -500      -100        -500      -700 211.3196429        8.106         0         13     19403.54
   1    1   5/3/2010       46.50      2.625     -2000      -500      -100        -500      -700 211.3501429        8.106         0         13     21827.90
   1    1  12/3/2010       57.79      2.667     -2000      -500      -100        -500      -700 211.3501429        8.106         0         13     21827.90

separation of data

>ind<- sample(2,nrow(train1),replace= TRUE,prob=c(0.7,0.3))
>train <- train1[ind==1,]
>test <- train1 [ind==2,]

for train

>head(train)
Store Dept  Date    Temperature   Fuel_Price MarkDown1 MarkDown2 MarkDown3  MarkDown4 MarkDown5      CPI    Unemployment      IsHoliday    Rank  Weekly_Sales
 1    1   5/2/2010       42.31      2.572     -2000      -500      -100     -500      -700       211.0963582     8.106         0          13     24924.50
 1    1 26-02-2010       46.63      2.561     -2000      -500      -100     -500      -700       211.3196429     8.106         0          13     19403.54
 1    1   5/3/2010       46.50      2.625     -2000      -500      -100     -500      -700       211.3501429     8.106         0          13     21827.90
 1    1 19-03-2010       54.58      2.720     -2000      -500      -100     -500      -700       211.2156350     8.106         0          13     22136.64
 1    1 26-03-2010       51.45      2.732     -2000      -500      -100     -500      -700       211.0180424     8.106         0          13     26229.21
 1    1   2/4/2010       62.27      2.719     -2000      -500      -100     -500      -700       210.8204499     7.808         0          13     57258.43

for test

>head(test)
Store Dept  Date   Temperature Fuel_Price MarkDown1 MarkDown2 MarkDown3  MarkDown4 MarkDown5  CPI     Unemployment   IsHoliday Rank Weekly_Sales
1    1  12/2/2010       38.51      2.548     -2000      -500      -100       -500      -700   211.2421698    8.106       1     13     46039.49
1    1 19-02-2010       39.93      2.514     -2000      -500      -100       -500      -700   211.2891429    8.106       0     13     41595.55
1    1  12/3/2010       57.79      2.667     -2000      -500      -100       -500      -700   211.3806429    8.106       0     13     21043.39
1    1   7/5/2010       72.55      2.835     -2000      -500      -100       -500      -700   210.3399684    7.808       0     13     17413.94
1    1 21-05-2010       76.44      2.826     -2000      -500      -100       -500      -700   210.6170934    7.808       0     13     14773.04
1    1 28-05-2010       80.44      2.759     -2000      -500      -100       -500      -700   210.8967606    7.808       0     13     15580.43

The code I use looks as follows:

>library(neuralnet)

>n <-neuralnet(Weekly_Sales~Temperature+Fuel_Price+MarkDown1+MarkDown2+MarkDown3+MarkDown4+MarkDown5+CPI+Unemployment+IsHoliday+Rank,data= train,hidden=c(4,3),err.fct="sse",linear.output=FALSE)
>plot(n)
>output <- compute(n,test[,4:14])
>output1 <- output$net.result*(max(test$Weekly_Sales)-min(test$Weekly_Sales))+min(test$Weekly_Sales)

The neural network is trained and it is showing an error in the range of 10^13. Also I'm getting the same output every time, I am running the code and these predictions are not even close to the actual Weekly_Sales in test data. I have used datasets of another department but still getting the same predictions.

output

>head(output$net.result)
      [,1]
2  0.9999999998
3  0.9999999998
6  0.9999999998
14 0.9999999998
16 0.9999999998
17 0.9999999998

> head(output1)
    [,1]
2  149743.97
3  149743.97
6  149743.97
14 149743.97
16 149743.97
17 149743.97

Body:
You need to normalize your data before you apply neuralnet(). So before splitting train1 into train/ test, use below code

maximum <- apply(train1, 2, max)
minimum <- apply(train1, 2, min)
train1_scaled <- as.data.frame(scale(train1, center=minimum, scale = maximum- minimum))

Then use your code to split data and use below function

#linear.output should be TRUE as you are predicting continuos dependent variable
n <- neuralnet(Weekly_Sales~Temperature+Fuel_Price+MarkDown1+MarkDown2+MarkDown3+MarkDown4+MarkDown5+CPI+Unemployment+IsHoliday+Rank,data= train,hidden=c(4,3),err.fct="sse",linear.output=TRUE)

Below code will also need slight modification after this

#basically to convert it back to non-scaled version, you need to do it using non-scaled original data not 'test' dataset
output1 <- output$net.result*(max(train1$Weekly_Sales)-min(train1$Weekly_Sales))+min(train1$Weekly_Sales)

#also the dependent variable in test dataset will need conversion
test$Weekly_Sales_nonScaled <- test$Weekly_Sales*(max(train1$Weekly_Sales)-min(train1$Weekly_Sales))+min(train1$Weekly_Sales)

#After this you can compare original data (test$Weekly_Sales_nonScaled) with predicted data (output1)

Kindly don't forget to let us know if it helped :)


问:
Form button -Save & clear,Save& next
I am using laravel5.4. I am working on form. I have to add three buttons like Clear All, Save & Clear, Save & Next button.For Clear All, I have added

```<code><button type="reset" value="reset" class="btn btn-primary">
    Clear All
</button>
</code>```

For Save & clear,my requirement is to save the input data entered by user and clear all input fields to make the user enter another data in form.

For Save & Next, my requirement is to save all the input data entered by user and make student name input field, subject input field,Teacher Input field selected by user remain same and clear rest input fields in form.

A user can select student name, subject name, teacher name from the dropdown list and can enter multiple inputs for the same student, subject, teacher. So I need to keep all these three unchanged and clear rest input fields to enter new data.

Please suggest on how to implement this.

答:
Name all 3 buttons differently, then in your controller just handle each in which ever way you require.

So for save and reset you'd listen for the save-reset button and return the form for another entry, whereas if it's save-next return the next form.

Eg:

```<code>Public function handleFormAction(Request $request){
    If(isset($request->input('save-next')){
        // Do something
    }else if(isset($request->input('save-next')){
        // Do something else
    }
}
</code>```

Or instead of names you could use button values

```<code>If($request->input('save-button') == 'save-reset')){}
</code>```

As previously mentioned you can let the browser handle the simple reset action.

Title: Form button -Save & clear,Save& next

Body:
I am using laravel5.4. I am working on form. I have to add three buttons like Clear All, Save & Clear, Save & Next button.For Clear All, I have added

<button type="reset" value="reset" class="btn btn-primary">
    Clear All
</button>

For Save & clear,my requirement is to save the input data entered by user and clear all input fields to make the user enter another data in form.

For Save & Next, my requirement is to save all the input data entered by user and make student name input field, subject input field,Teacher Input field selected by user remain same and clear rest input fields in form.

A user can select student name, subject name, teacher name from the dropdown list and can enter multiple inputs for the same student, subject, teacher. So I need to keep all these three unchanged and clear rest input fields to enter new data.

Please suggest on how to implement this.

Body:
Name all 3 buttons differently, then in your controller just handle each in which ever way you require.

So for save and reset you'd listen for the save-reset button and return the form for another entry, whereas if it's save-next return the next form.

Eg:

Public function handleFormAction(Request $request){
    If(isset($request->input('save-next')){
        // Do something
    }else if(isset($request->input('save-next')){
        // Do something else
    }
}

Or instead of names you could use button values

If($request->input('save-button') == 'save-reset')){}

As previously mentioned you can let the browser handle the simple reset action.


问:
How do I install babel.messages module in Ubuntu?
I am trying to install using

```<code>sudo apt-get install babel.messages
</code>```

but getting error:

ImportError: No module named babel.messages

Please let me know how to install in Ubuntu 16.04

答:
For Ubuntu versions older than 17.04, you can install python-babel from the Ubuntu repositories by running the following command in terminal:

```<code>sudo apt-get install python-babel
</code>```

For Ubuntu versions from 17.04 and also on older versions you can install it via pip, the Python package manager as:

```<code>pip install babel
</code>```

If you don't have pip installed yet, you can install it as:

```<code>sudo apt install python-pip
</code>```

Body:
I am trying to install using

sudo apt-get install babel.messages

but getting error:

ImportError: No module named babel.messages

Please let me know how to install in Ubuntu 16.04

Body:
For Ubuntu versions older than 17.04, you can install python-babel from the Ubuntu repositories by running the following command in terminal:

sudo apt-get install python-babel

For Ubuntu versions from 17.04 and also on older versions you can install it via pip, the Python package manager as:

pip install babel

If you don't have pip installed yet, you can install it as:

sudo apt install python-pip


问:
How i get client side input html value to the server side in MVC 5
I am trying to solve this error but after execution variable stored null values. Please tell me how I get client side html input value to the server side

Below is the HTML Code :

```<code><input type="text" id="firstname" class="form-control" name="firstname"/>
</code>```

and below is the Server Code :

```<code>string firstname=Convert.ToString(Request.Form["firstname"]);
</code>```

答:
your code is so tiny incomplete ...if you want to pass some value from html  to your server side variables...you have multiple options...one of them is is usingrequest.Form[]....but for this option you have to pass your input value to a controller by this parameter : ActionName(FormCollection frm) so check to see does your action have any FormCollection parameter or not...then you can use Request.Form["firstname"]

you can see a complete example here: This

pay: your input most to be inside a form! like Html.BeginForm("ActionName","ControllerName")...

```<code>       public void savedata(FormCollection fomr)
    {
        string name = Request.Form["name"];
        string surname = Request.Form["surname"];
        string age = Request.Form["age"];
        string gender = Request.Form["gender"];
    }
</code>```

Body:
I am trying to solve this error but after execution variable stored null values. Please tell me how I get client side html input value to the server side

Below is the HTML Code :

<input type="text" id="firstname" class="form-control" name="firstname"/>

and below is the Server Code :

string firstname=Convert.ToString(Request.Form["firstname"]);

Body:
your code is so tiny incomplete ...if you want to pass some value from html  to your server side variables...you have multiple options...one of them is is usingrequest.Form[]....but for this option you have to pass your input value to a controller by this parameter : ActionName(FormCollection frm) so check to see does your action have any FormCollection parameter or not...then you can use Request.Form["firstname"]

you can see a complete example here: This

pay: your input most to be inside a form! like Html.BeginForm("ActionName","ControllerName")...

       public void savedata(FormCollection fomr)
    {
        string name = Request.Form["name"];
        string surname = Request.Form["surname"];
        string age = Request.Form["age"];
        string gender = Request.Form["gender"];
    }


问:
Get tapped word from UITextView in Swift
I know that this problem has been solved in Objective-C, but I haven't seen any solution to it in Swift. I have tried to convert the solution code from this post, but I'm getting errors:

```<code>func textTapped(recognizer: UITapGestureRecognizer){

    var textView: UITextView = recognizer.view as UITextView
    var layoutManager: NSLayoutManager = textView.layoutManager
    var location: CGPoint = recognizer.locationInView(textView)
    location.x -= textView.textContainerInset.left
    location.y -= textView.textContainerInset.top

    var charIndex: Int
    charIndex = layoutManager.characterIndexForPoint(location, inTextContainer: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

    if charIndex < textView.textStorage.length {
        // do the stuff
        println(charIndex)
    }
}
</code>```

I think the problem is in this line (see error here):

```<code> var textView: UITextView = recognizer.view as UITextView
</code>```

... which I have converted from Objective-C based on this line:

```<code> UITextView *textView = (UITextView *)recognizer.view;
</code>```

Finally, I am also in doubt about how this function should be called. As I understand it, the function should be passed to a Selector in viewDidLoad(), like this:

```<code> let aSelector: Selector = "textTapped:"

 let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)
 tapGesture.numberOfTapsRequired = 1
 view.addGestureRecognizer(tapGesture)
</code>```

Because I'm getting the before mentioned error, I'm not sure if it would work. But I'm thinking that I would need to pass the parameter in the textTapped function (recognizer) into the Selector as well. However, I've read that you can only pass the function and not any parameters.

答:
For Swift 3.0 OR Above

add Tap gesture to UITextView

```<code>let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapOnTextView(_:)))
textView.addGestureRecognizer(tapGesture)
</code>```

add tap handler method

```<code>@objc private final func tapOnTextView(_ tapGesture: UITapGestureRecognizer){

  let point = tapGesture.location(in: textView)
  if let detectedWord = getWordAtPosition(point)
  {

  }
}
</code>```

get word from point

```<code>private final func getWordAtPosition(_ point: CGPoint) -> String?{
if let textPosition = textView.closestPosition(to: point)
{
  if let range = textView.tokenizer.rangeEnclosingPosition(textPosition, with: .word, inDirection: 1)
  {
    return textView.text(in: range)
  }
}
return nil}
</code>```

Body:
I know that this problem has been solved in Objective-C, but I haven't seen any solution to it in Swift. I have tried to convert the solution code from this post, but I'm getting errors:

func textTapped(recognizer: UITapGestureRecognizer){

    var textView: UITextView = recognizer.view as UITextView
    var layoutManager: NSLayoutManager = textView.layoutManager
    var location: CGPoint = recognizer.locationInView(textView)
    location.x -= textView.textContainerInset.left
    location.y -= textView.textContainerInset.top

    var charIndex: Int
    charIndex = layoutManager.characterIndexForPoint(location, inTextContainer: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

    if charIndex < textView.textStorage.length {
        // do the stuff
        println(charIndex)
    }
}

I think the problem is in this line (see error here):

 var textView: UITextView = recognizer.view as UITextView

... which I have converted from Objective-C based on this line:

 UITextView *textView = (UITextView *)recognizer.view;

Finally, I am also in doubt about how this function should be called. As I understand it, the function should be passed to a Selector in viewDidLoad(), like this:

 let aSelector: Selector = "textTapped:"

 let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)
 tapGesture.numberOfTapsRequired = 1
 view.addGestureRecognizer(tapGesture)

Because I'm getting the before mentioned error, I'm not sure if it would work. But I'm thinking that I would need to pass the parameter in the textTapped function (recognizer) into the Selector as well. However, I've read that you can only pass the function and not any parameters.

Body:
For Swift 3.0 OR Above

add Tap gesture to UITextView

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapOnTextView(_:)))
textView.addGestureRecognizer(tapGesture)

add tap handler method

@objc private final func tapOnTextView(_ tapGesture: UITapGestureRecognizer){

  let point = tapGesture.location(in: textView)
  if let detectedWord = getWordAtPosition(point)
  {

  }
}

get word from point

private final func getWordAtPosition(_ point: CGPoint) -> String?{
if let textPosition = textView.closestPosition(to: point)
{
  if let range = textView.tokenizer.rangeEnclosingPosition(textPosition, with: .word, inDirection: 1)
  {
    return textView.text(in: range)
  }
}
return nil}


问:
Replacing a sequence in a string with its match index
In PHP, If I am replacing "a" in a string "a b a b a b c", how do I get it to replace with the index of the match (i.e. "1 b 2 b 3 b c")?</p>

答:
Are you sure you need preg_*?

Here is how I would do it:

```<code>$numerals = range(1, 10);
$str = str_replace('a', $numerals, $str);
</code>```

The sadly neglected and often ignored str_replace() function can accept arrays as arguments. In case an array is passed as the second argument, it changes every occurrence of the search string with the corresponding array's element.

Body:
Are you sure you need preg_*?

Here is how I would do it:

$numerals = range(1, 10);
$str = str_replace('a', $numerals, $str);

The sadly neglected and often ignored str_replace() function can accept arrays as arguments. In case an array is passed as the second argument, it changes every occurrence of the search string with the corresponding array's element.


问:
python statement: (k,v) for k,v
I use pycharm with python 2.7

For a dictionary param, I try to use the following two statements:

```<code>   *print "%s=%s" %(k,v) for k,v in param.items()
    print ["%s=%s" %(k,v) for k,v in param.items()]*
</code>```

The first line has a syntax error because the k,v can't be resolved, but the second line could be executed normally. How should I understand that, and how can the IDE find k,v for the second line?

I know the second line belongs to list comprehension, but it makes me confused because parts of a valid statement is invalid, so this kind of statement can be used only within a list?

答: The first line has a syntax error because it's invalid syntax. The second line is a list comprehension.</p>

Title: python statement: (k,v) for k,v

Body:
I use pycharm with python 2.7

For a dictionary param, I try to use the following two statements:

   *print "%s=%s" %(k,v) for k,v in param.items()
    print ["%s=%s" %(k,v) for k,v in param.items()]*

The first line has a syntax error because the k,v can't be resolved, but the second line could be executed normally. How should I understand that, and how can the IDE find k,v for the second line?

I know the second line belongs to list comprehension, but it makes me confused because parts of a valid statement is invalid, so this kind of statement can be used only within a list?


问:
Connecting Samsung S7 to AndroidStudio
I like to start my app directly on Samsung S7 with AndroidStudio.

I have already enabled debugging mode in the developer option by tapping 7 times on build number, but still I don't see the device when starting the app and getting the "Select Deployment Target" Dialog.

What else do I have to do ?

答:
If you are using windows, i have sometimes needed to "reconnect" the device. Particularly when switching between the device and emulator.

To do that, find the folder in the sdk that you have downloaded for adb.exe
In that folder, start up a command prompt and try "adb reconnect". This usually works for me. Sometimes, I have also had to revoke the debugging permissions and then reenable them from the developer settings on the phone...

Note that this S7 Is the most problematic phone I have with this issue. I have about 6 other development phones, and this is the worst for connection issues. Otherwise, I think the phone is great.

Title: Connecting Samsung S7 to AndroidStudio