问:
How to pass data to child fragment while using dagger 2
I want to pass some data from fragment parent to dialog fragment child. The trouble is I cannot pass the data through bundle since dagger instantiates fragment dialog, so the bundle is always null. I am using dagger 2.12..

I'm new to Dagger 2, so this might be something trivial. I am still trying to wrap my head around it.

I followed this tutorial, and adopted it to suit my application. To keep it simple here is my MainFragment:

```<code>public class MainFragment extends BaseFragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        this.setHasOptionsMenu(true);
        return inflater.inflate(R.layout.my_fragment, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.my_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_delete:
                Bundle args = new Bundle();
                args.putString("BUNDLE_TITLE_KEY", getResources().getString(R.string.dialog_delete_name));
                args.putString("BUNDLE_MESSAGE_KEY", getResources().getString(R.string.delete_message));
                addDialogFragment(new ConformationFragmentDialog(), args);
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }
}
</code>```

Here is BaseFragment (extended by MainFragment):

```<code>public class BaseFragment extends Fragment implements HasFragmentInjector {

    @Inject
    @Named(BaseFragmentModule.CHILD_FRAGMENT_MANAGER)
    FragmentManager childFragmentManager;

    @Inject
    DispatchingAndroidInjector<Fragment> childFragmentInjector;

    @Override
    public void onAttach(Context context) {
        AndroidInjection.inject(this);
        super.onAttach(context);
    }

    @Override
    public AndroidInjector<Fragment> fragmentInjector() {
        return childFragmentInjector;
    }

    protected final void addDialogFragment(DialogFragment dialogFragment, Bundle bundle) {
        dialogFragment.setArguments(bundle);
        childFragmentManager.beginTransaction().add(dialogFragment, "Hello").commit();
    }
}
</code>```

And here is ConformationFragmentDialog:

```<code>public class ConformationFragmentDialog extends DialogFragment {

    @Override
    public void onAttach(Context context) {
        AndroidInjection.inject(this);
        super.onAttach(context);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
        dialogBuilder.setNegativeButton(R.string.common_odustani, new DialogInterface.OnClickListener() {
            //TODO: set title and message dynamically, bundle is null
        }).setTitle("TITLE").setMessage("MESSAGE");
        return dialogBuilder.create();
    }
}
</code>```

Here are BaseFragmentModule and MainFragmentModule:

```<code>@Module
public abstract class BaseFragmentModule {
    public static final String FRAGMENT = "BaseFragmentModule.fragment";
    public static final String CHILD_FRAGMENT_MANAGER = "BaseFragmentModule.ChildFragmentManager";

    @Provides
    @Named(CHILD_FRAGMENT_MANAGER)
    static FragmentManager childFragmentManager(@Named(FRAGMENT) Fragment fragment) {
        return fragment.getChildFragmentManager();
    }
}

@Module(includes = BaseFragmentModule.class, subcomponents = ConformationFragmentDialogSubcomponent.class)
public abstract class MainFragmentModule {

    @Binds
    @IntoMap
    @FragmentKey(ConformationFragmentDialog.class)
    abstract AndroidInjector.Factory<? extends Fragment> conformationFragmentDialog(ConformationFragmentDialogSubcomponent.Builder builder);

    @Binds
    @Named(BaseFragmentModule.FRAGMENT)
    abstract Fragment fragment(UvjetListFragment uvjetListFragment);

}
</code>```

At this moment, ConformationFragmentDialogModule is empty and Subcomponents are basic subcomponents.

I want ConformationFragmentDialog to be reusable in different fragments. How can I set different title and message for every fragment from which I am calling ConformationFragmentDialog, while still doing things in dagger appropriate manner?

答:
Create a fragment using static newInstance in your ConfirmationFragmentDialog class like this

```<code>public class ConformationFragmentDialog extends DialogFragment {
    public static ConformationFragmentDialog newInstance(String title,String msg) {
        ConformationFragmentDialog fragment = new ConformationFragmentDialog();

        // Supply string input as an argument.
        Bundle args = new Bundle();
        args.putString("BUNDLE_TITLE_KEY", title);
        args.putString("BUNDLE_MESSAGE_KEY", msg);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        String title = getArguments.getStrings("BUNDLE_TITLE_KEY");
        String message = getArguments.getStrings("");
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
        dialogBuilder.setNegativeButton(
            R.string.common_odustani,
            new DialogInterface.OnClickListener() {
                //TODO: set title and message dynamically, bundle is null
            }
        ).setTitle("TITLE").setMessage("MESSAGE");
        return dialogBuilder.create();
    }
}
</code>```

Also for your MainFragment return fragment by calling newInstance method.

Body:
I want to pass some data from fragment parent to dialog fragment child. The trouble is I cannot pass the data through bundle since dagger instantiates fragment dialog, so the bundle is always null. I am using dagger 2.12..

I'm new to Dagger 2, so this might be something trivial. I am still trying to wrap my head around it.

I followed this tutorial, and adopted it to suit my application. To keep it simple here is my MainFragment:

public class MainFragment extends BaseFragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        this.setHasOptionsMenu(true);
        return inflater.inflate(R.layout.my_fragment, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.my_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_delete:
                Bundle args = new Bundle();
                args.putString("BUNDLE_TITLE_KEY", getResources().getString(R.string.dialog_delete_name));
                args.putString("BUNDLE_MESSAGE_KEY", getResources().getString(R.string.delete_message));
                addDialogFragment(new ConformationFragmentDialog(), args);
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }
}

Here is BaseFragment (extended by MainFragment):

public class BaseFragment extends Fragment implements HasFragmentInjector {

    @Inject
    @Named(BaseFragmentModule.CHILD_FRAGMENT_MANAGER)
    FragmentManager childFragmentManager;

    @Inject
    DispatchingAndroidInjector<Fragment> childFragmentInjector;

    @Override
    public void onAttach(Context context) {
        AndroidInjection.inject(this);
        super.onAttach(context);
    }

    @Override
    public AndroidInjector<Fragment> fragmentInjector() {
        return childFragmentInjector;
    }

    protected final void addDialogFragment(DialogFragment dialogFragment, Bundle bundle) {
        dialogFragment.setArguments(bundle);
        childFragmentManager.beginTransaction().add(dialogFragment, "Hello").commit();
    }
}

And here is ConformationFragmentDialog:

public class ConformationFragmentDialog extends DialogFragment {

    @Override
    public void onAttach(Context context) {
        AndroidInjection.inject(this);
        super.onAttach(context);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
        dialogBuilder.setNegativeButton(R.string.common_odustani, new DialogInterface.OnClickListener() {
            //TODO: set title and message dynamically, bundle is null
        }).setTitle("TITLE").setMessage("MESSAGE");
        return dialogBuilder.create();
    }
}

Here are BaseFragmentModule and MainFragmentModule:

@Module
public abstract class BaseFragmentModule {
    public static final String FRAGMENT = "BaseFragmentModule.fragment";
    public static final String CHILD_FRAGMENT_MANAGER = "BaseFragmentModule.ChildFragmentManager";

    @Provides
    @Named(CHILD_FRAGMENT_MANAGER)
    static FragmentManager childFragmentManager(@Named(FRAGMENT) Fragment fragment) {
        return fragment.getChildFragmentManager();
    }
}

@Module(includes = BaseFragmentModule.class, subcomponents = ConformationFragmentDialogSubcomponent.class)
public abstract class MainFragmentModule {

    @Binds
    @IntoMap
    @FragmentKey(ConformationFragmentDialog.class)
    abstract AndroidInjector.Factory<? extends Fragment> conformationFragmentDialog(ConformationFragmentDialogSubcomponent.Builder builder);

    @Binds
    @Named(BaseFragmentModule.FRAGMENT)
    abstract Fragment fragment(UvjetListFragment uvjetListFragment);

}

At this moment, ConformationFragmentDialogModule is empty and Subcomponents are basic subcomponents.

I want ConformationFragmentDialog to be reusable in different fragments. How can I set different title and message for every fragment from which I am calling ConformationFragmentDialog, while still doing things in dagger appropriate manner?

Body:
Create a fragment using static newInstance in your ConfirmationFragmentDialog class like this

public class ConformationFragmentDialog extends DialogFragment {
    public static ConformationFragmentDialog newInstance(String title,String msg) {
        ConformationFragmentDialog fragment = new ConformationFragmentDialog();

        // Supply string input as an argument.
        Bundle args = new Bundle();
        args.putString("BUNDLE_TITLE_KEY", title);
        args.putString("BUNDLE_MESSAGE_KEY", msg);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        String title = getArguments.getStrings("BUNDLE_TITLE_KEY");
        String message = getArguments.getStrings("");
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
        dialogBuilder.setNegativeButton(
            R.string.common_odustani,
            new DialogInterface.OnClickListener() {
                //TODO: set title and message dynamically, bundle is null
            }
        ).setTitle("TITLE").setMessage("MESSAGE");
        return dialogBuilder.create();
    }
}

Also for your MainFragment return fragment by calling newInstance method.


来源: stackexchange

问:
How to prevent "0" as the first character and limit number of characters allowed in UITextField using Swift?
I want to achieve following:

Have a decimal keypad. Which means user will be able to enter Double
values. (Needless to say "." will be limited one)

Prevent "0" characters as the first characters. (i.e.: There should
not be values like "003" "01" "000012" etc.)

Limit the character count to 10.

Only allow numbers. No Copy-Paste text values.

I am using decimal keypad. Below code handles first and third item above:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentString: NSString = (textField.text ?? "") as NSString
    let newString = currentString.replacingCharacters(in: range, with: string)
    return newString.count <= 10
}
</code>```

Thank you for your time.

答:
You can Create this method to prevent from copy paste

```<code>override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        if action == "paste:" {
            return false
        }
        return super.canPerformAction(action, withSender: sender)
    }
</code>```

and also you can add the following code to shouldChangeCharactersInRange Delegate method of textfield

```<code>  let searchString = (txtMobilePhone.text as NSString?)?.replacingCharacters(in: range, with: string)

        if (searchString?.length)! > 1 {

            let inverseSet = CharacterSet(charactersIn: ".0123456789").inverted

            return ((string as NSString).rangeOfCharacter(from: inverseSet).location == NSNotFound)

        } else {

            let inverseSet = CharacterSet(charactersIn: ".123456789").inverted

            return ((string as NSString).rangeOfCharacter(from: inverseSet).location == NSNotFound)
        }
</code>```

this above will only allow the user to enter the "0" after the second character I mean restricts the user to type "0" at the starting of numbers

ContentLicense: CC BY-SA 3.0

Body:
I want to achieve following:

Have a decimal keypad. Which means user will be able to enter Double
values. (Needless to say "." will be limited one)

Prevent "0" characters as the first characters. (i.e.: There should
not be values like "003" "01" "000012" etc.)

Limit the character count to 10.

Only allow numbers. No Copy-Paste text values.

I am using decimal keypad. Below code handles first and third item above:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentString: NSString = (textField.text ?? "") as NSString
    let newString = currentString.replacingCharacters(in: range, with: string)
    return newString.count <= 10
}

Thank you for your time.

Body:
You can Create this method to prevent from copy paste

override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        if action == "paste:" {
            return false
        }
        return super.canPerformAction(action, withSender: sender)
    }

and also you can add the following code to shouldChangeCharactersInRange Delegate method of textfield

  let searchString = (txtMobilePhone.text as NSString?)?.replacingCharacters(in: range, with: string)

        if (searchString?.length)! > 1 {

            let inverseSet = CharacterSet(charactersIn: ".0123456789").inverted

            return ((string as NSString).rangeOfCharacter(from: inverseSet).location == NSNotFound)

        } else {

            let inverseSet = CharacterSet(charactersIn: ".123456789").inverted

            return ((string as NSString).rangeOfCharacter(from: inverseSet).location == NSNotFound)
        }

this above will only allow the user to enter the "0" after the second character I mean restricts the user to type "0" at the starting of numbers

ContentLicense: CC BY-SA 4.0


问:
jquery validate and error styles

how do i get rid of the borders in ul > li ?

i have :

```<code>    errorLabelContainer: $("ul", $('div.error')), wrapper: 'li',

errorContainer: $('div.error'),
</code>```

i tried :

```<code> div.message{
background: transparent url(images\ad_next.png) no-repeat scroll left center;
padding-left: 17px; border:0px;
}
div.message ul, li { border:0px; }
div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid solid;
    border-width: 2px;
    padding: 5px;
}
</code>```

答:
```<code>div.message li { border:0px; }
</code>```

should be enough

ContentLicense: CC BY-SA 2.5

Title: jquery validate and error styles

Body:
how do i get rid of the borders in ul > li ?

i have :

    errorLabelContainer: $("ul", $('div.error')), wrapper: 'li',

errorContainer: $('div.error'),

i tried :

 div.message{
background: transparent url(images\ad_next.png) no-repeat scroll left center;
padding-left: 17px; border:0px;
}
div.message ul, li { border:0px; }
div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid solid;
    border-width: 2px;
    padding: 5px;
}

Body:
div.message li { border:0px; }

should be enough


问:
Add lines to plot in pyplot
I want to plot a sin-function and show it, then add a cos-function and plot again, so that the output is two plots, the first with only sin and the second with sin AND cos. But show() flushes the plot, how do I prevent the flushing? </p>

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

f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)

plt.plot(x,y1)
plt.show() #can I avoid flushing here?

plt.plot(x,y2)
plt.show()
</code>```

<p>I need it in a jupyter notebook. </p>

答:
Would recommend doing it in the Object Oriented way.

```<code>%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import time
f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)

f,ax = plt.subplots() # creating the plot and saving the reference in f and ax

ax.plot(x,y1)
f.canvas.draw()
time.sleep(1) # delay for when to add the second line
ax.plot(x,y2)
f.canvas.draw()
</code>```

Edit:
Noticed you need it in jupyter notebook and the first solution i posted didn't work there, but the one posted now does. Use f.canvas.draw() instead of plt.show().

Title: Add lines to plot in pyplot

Body:
I want to plot a sin-function and show it, then add a cos-function and plot again, so that the output is two plots, the first with only sin and the second with sin AND cos. But show() flushes the plot, how do I prevent the flushing?

import numpy as np
import matplotlib.pyplot as plt

f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)

plt.plot(x,y1)
plt.show() #can I avoid flushing here?

plt.plot(x,y2)
plt.show()

I need it in a jupyter notebook.

Body:
Would recommend doing it in the Object Oriented way.

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import time
f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)

f,ax = plt.subplots() # creating the plot and saving the reference in f and ax

ax.plot(x,y1)
f.canvas.draw()
time.sleep(1) # delay for when to add the second line
ax.plot(x,y2)
f.canvas.draw()

Edit:
Noticed you need it in jupyter notebook and the first solution i posted didn't work there, but the one posted now does. Use f.canvas.draw() instead of plt.show().


问:
How to highlight multiple elements under the overlap page
I want to highlight multiple elements under the overlap page, the expected result will be like this:

I have tried to increase the z-index of this element (I have tried this, but I met some issues to cause z-index not to work), can we use canvas to do it?
Are there any detailed steps about it?

答:
Try to switch off the pointer-events of your overlapping element: https://developer.mozilla.org/ru/docs/Web/CSS/pointer-events

(also you may switch it off when the cursor is over the circle)


问:
Call function from activity to close the soft keyboard android
I'm new to mobile automation and I've been trying to find a way to close the soft keyboard on Android (using Java). The best solution I've come across so far was from this post:

Close/hide the Android Soft Keyboard

The function that I'm trying to use from there is:

```<code>public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
</code>```

I want to be able to call this function when the keyboard pops up, but what I don't understand is how to pass through the Activity when I call this function?

Before calling the function to close the keyboard I have the following:

```<code>    // Create object of  DesiredCapabilities class and specify android platform
    DesiredCapabilities capabilities = DesiredCapabilities.android();

    // set the capability to execute test in android app
    capabilities.setCapability(MobileCapabilityType.PLATFORM, Platform.ANDROID);
    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Emulator_1");
    capabilities.setCapability(MobileCapabilityType.VERSION, "8.0");
    capabilities.setCapability("appPackage", "com.spreeza.shop.stag.debug");
    capabilities.setCapability("appActivity", "com.spreeza.shop.ui.features.splash.EntryPointActivity");

    driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

// click on the login button
driver.findElement(By.id(identifierName)).click();

// close the keyboard
hideKeyboard();
</code>```

答:
```<code>    /**
     * Hide the keyboard
     */
    private void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                    hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
</code>```

Body:
I'm new to mobile automation and I've been trying to find a way to close the soft keyboard on Android (using Java). The best solution I've come across so far was from this post:

Close/hide the Android Soft Keyboard

The function that I'm trying to use from there is:

public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

I want to be able to call this function when the keyboard pops up, but what I don't understand is how to pass through the Activity when I call this function?

Before calling the function to close the keyboard I have the following:

    // Create object of  DesiredCapabilities class and specify android platform
    DesiredCapabilities capabilities = DesiredCapabilities.android();

    // set the capability to execute test in android app
    capabilities.setCapability(MobileCapabilityType.PLATFORM, Platform.ANDROID);
    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Emulator_1");
    capabilities.setCapability(MobileCapabilityType.VERSION, "8.0");
    capabilities.setCapability("appPackage", "com.spreeza.shop.stag.debug");
    capabilities.setCapability("appActivity", "com.spreeza.shop.ui.features.splash.EntryPointActivity");

    driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

// click on the login button
driver.findElement(By.id(identifierName)).click();

// close the keyboard
hideKeyboard();


问:
JMeter read the second sheet of CSV
How can I make JMeter read the second sheet of my CSV?

I want to use CSV Data Set Config.

Normally, it reads the first line of the first sheet but is there any way to be a bit more flexible?

答:
Currently you can use CSV Data Set Config for that, you should add external code for example using Apache Commons CSV,

Download the jar file and place it in JMETER_HOME lib folder, and then write the code in JSR223 Element.

Examples exists, code for get second record:

```<code>Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
// go to next record
records.next();
CSVRecord secondRecord = records.next();
//columnOne = secondRecord.get(0);
</code>```

Title: JMeter read the second sheet of CSV

Body:
Currently you can use CSV Data Set Config for that, you should add external code for example using Apache Commons CSV,

Download the jar file and place it in JMETER_HOME lib folder, and then write the code in JSR223 Element.

Examples exists, code for get second record:

Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
// go to next record
records.next();
CSVRecord secondRecord = records.next();
//columnOne = secondRecord.get(0);


问:
Android: How to reset FirstRun SharedPreferences when my app is updated?
My app copies files over from res/raw to the sdcard on first run. I want it to update those files on every subsequent app update. How can i have it reset the firstrun preference to true on every app update?

Here is the relevant code:

```<code>/**
     * get if this is the first run
     *
     * @return returns true, if this is the first run
     */
        public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }

     /**
     * store the first run
     */
     public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }

     SharedPreferences mPrefs;

     /**
     * setting up preferences storage
     */
     public void firstRunPreferences() {
        Context mContext = this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); //0 = mode private. only this app can read these preferences
     }

     public void setStatus(String statustext) {
         SharedPreferences.Editor edit = mPrefs.edit();
         edit.putString("status", statustext);
         edit.commit();
      }

}
</code>```

答: You could mimic what's done on the database side, with version numbers. Instead of having just a firstRun variable, have a couple with firstRun and versionNumber, and put a static version number field in your app, that you increment at each release. This way, you'll be able to check if the app has been updated, and do your operation on each update.

Body:
My app copies files over from res/raw to the sdcard on first run. I want it to update those files on every subsequent app update. How can i have it reset the firstrun preference to true on every app update?

Here is the relevant code:

/**
     * get if this is the first run
     *
     * @return returns true, if this is the first run
     */
        public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }

     /**
     * store the first run
     */
     public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }

     SharedPreferences mPrefs;

     /**
     * setting up preferences storage
     */
     public void firstRunPreferences() {
        Context mContext = this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); //0 = mode private. only this app can read these preferences
     }

     public void setStatus(String statustext) {
         SharedPreferences.Editor edit = mPrefs.edit();
         edit.putString("status", statustext);
         edit.commit();
      }

}


问:
Rspec check if a method has been called without calling the method
I am pretty new with RSpec an althought I have been reading a lot about how to check if a method has been called I cannot find a proper solution for the case I need. Sorry if this is a duplicate but couldn't find anything :S

I have an object which implements this function

```<code>def link
  paths.each do |old,new|
    FileUtils.ln_s old, new
  end
end
</code>```

Several links are done based on paths (which is a hash pairing old and new files). My test for this looks like this:

```<code>context "linking files to new ones" do
  it "links a sample to the propper file" do
    @comb.link
    expect(FileUtils).to have_received(:ln_s).with("/example/path/files/old.root",
                                             "example/path/nornmfiles/new.root")
  end
end
</code>```

Since I want to test that at least on of them has been called  have to use the have_received method since the receive ones will fail as soon as the ln_s method gets called with different arguments. The issue is that the test fails because this is a test and I an mot going to actually create the links because the files don't exists so it fails raising an exception because the files don't exists.

How can I test this without actually having to call the method?

This call also fail as soon as a different call is made

```<code>  it "links a sample with a region subpath to the propper file" do
    expect(FileUtils).to receive(:ln_s).with("/example/path/files/pathsuff/old.root",
                                             "/example/path/normfiles/pathsuff/new.root").at_least(:once)
    @comb.link
  end
</code>```

It gives this error:

```<code>RSpec::Mocks::MockExpectationError: FileUtils received :ln_s with unexpected
arguments
   expected: ("/example/path/files/pathsuff/old.root",
 "/example/path/normfiles/pathsuff/new.root")
   got: ("/example/path/files/old.root",
 "/example/path/normfiles/new.root")
</code>```

which is on of the other calls with different methods that can happen that can be called

答:
```<code>context "linking files to new ones" do
  it "links a sample to the propper file" do
    allow(FileUtils).to receive(:ln_s)

    @comb.link

    expect(FileUtils).to have_received(:ln_s).with(
      "/example/path/files/old.root",
      "example/path/nornmfiles/new.root",
    ).at_least(:once)
  end
end
</code>```

Body:
I am pretty new with RSpec an althought I have been reading a lot about how to check if a method has been called I cannot find a proper solution for the case I need. Sorry if this is a duplicate but couldn't find anything :S

I have an object which implements this function

def link
  paths.each do |old,new|
    FileUtils.ln_s old, new
  end
end

Several links are done based on paths (which is a hash pairing old and new files). My test for this looks like this:

context "linking files to new ones" do
  it "links a sample to the propper file" do
    @comb.link
    expect(FileUtils).to have_received(:ln_s).with("/example/path/files/old.root",
                                             "example/path/nornmfiles/new.root")
  end
end

Since I want to test that at least on of them has been called  have to use the have_received method since the receive ones will fail as soon as the ln_s method gets called with different arguments. The issue is that the test fails because this is a test and I an mot going to actually create the links because the files don't exists so it fails raising an exception because the files don't exists.

How can I test this without actually having to call the method?

This call also fail as soon as a different call is made

  it "links a sample with a region subpath to the propper file" do
    expect(FileUtils).to receive(:ln_s).with("/example/path/files/pathsuff/old.root",
                                             "/example/path/normfiles/pathsuff/new.root").at_least(:once)
    @comb.link
  end

It gives this error:

RSpec::Mocks::MockExpectationError: FileUtils received :ln_s with unexpected
arguments
   expected: ("/example/path/files/pathsuff/old.root",
 "/example/path/normfiles/pathsuff/new.root")
   got: ("/example/path/files/old.root",
 "/example/path/normfiles/new.root")

which is on of the other calls with different methods that can happen that can be called


问:
Replacing missing quarter and missing data per quarter

Background

I've a quarterly data set where certain quarters and corresponding values are missing. The characteristics of the data set are:

Each group should have the same number of quarters but in practe quarters are missing

For missing quarter values are unknown

This is to be resolved by sourcing imputing next available value; for instance, as available via na.locf function

Example data

```<code># Packages
Vectorize(require)(package = c("tidyverse", "zoo", "magrittr"),
                   character.only = TRUE)

# Seed
set.seed(123)

# Dummy data
dta <- data.frame(group = rep(LETTERS[1:5], 10)) %>%
    group_by(group) %>%
    mutate(qrtr = seq(
        from = as.Date("01/01/2012", "%d/%m/%Y"),
        to = as.Date("31/5/2014", "%d/%m/%Y"),
        by = "quarter"
    )) %>%
    ungroup() %>%
    mutate(qrtr = as.yearqtr(qrtr)) %>%
    arrange(group, qrtr) %>%
    mutate(value = sample(1:10, 50, replace = TRUE))

# Remove random rows
dta[sample(1:dim(dta)[1], 10), c(2, 3)] <- NA
dta %<>% na.omit()
</code>```

Preview

```<code># A tibble: 40 x 3
   group          qrtr value
   <chr> <S3: yearqtr> <int>
 1     A       2012 Q1     3
 2     A       2012 Q2     8
 3     A       2012 Q4     9
 4     A       2013 Q1    10
 5     A       2013 Q3     6
 6     A       2013 Q4     9
 7     A       2014 Q1     6
 8     B       2012 Q1    10
 9     B       2012 Q2     5
10     B       2012 Q3     7
# ... with 30 more rows
</code>```

Problem

Create add rows within each group where quarter are missing. Total number of quarter is derived from sequence min(qrtr) to max(qrtr), in the context of existing code:

```<code>seq(from = as.Date("01/01/2012", "%d/%m/%Y"),
    to = as.Date("31/5/2014", "%d/%m/%Y"),
    by = "quarter")
</code>```

First non-missing value should be carried forward for the missing value.

Desired results:

```<code>>> dta
# A tibble: 50 x 3
   group          qrtr value
   <chr> <S3: yearqtr> <int>
 1     A       2012 Q1     3
 2     A       2012 Q2     8
 3     A       2012 Q3     8
 4     A       2012 Q4     9
 5     A       2013 Q1    10
 6     A       2013 Q2    10
 7     A       2013 Q3     6
 8     A       2013 Q4     9
 9     A       2014 Q1     6
10     A       2015 Q1     6
# ... with 40 more rows
</code>```

Proposed approaches

One approach would rely on making use of the expand, in order to convert implicitly missing values to explicitly missing values. This so far creates missing quarters but there is no clear way of creating missing observations for value column for where given quarter is missing.

```<code>dta %>%
    # Append mixing quarters
    expand(group, qrtr) %>%
    left_join(data.frame(qrtr = as.yearqtr(
        seq(
            from = as.Date("01/01/2012", "%d/%m/%Y"),
            to = as.Date("31/5/2014", "%d/%m/%Y"),
            by = "quarter"
        )
    )), by = "qrtr") %>%
    # TODO
    # mutate(value = na.locf(value)) %>%
    arrange(group, qrtr) -> dta_fixed
</code>```

答:
You seems to be interested in padr

```<code>library(padr)
library(zoo)

#convert to POSIXct as pad() expect it to be like this
dta$qrtr <- as.POSIXct(dta$qrtr,format="%Y %q")
dta %>%
  pad(group="group") %>%
  arrange(group, qrtr) %>%
  mutate(qrtr = as.yearqtr(qrtr)) %>%
  na.locf()
</code>```

output is:

```<code># A tibble: 49 x 3
   group    qrtr value
   <chr>   <chr> <chr>
 1     A 2012 Q1     3
 2     A 2012 Q2     8
 3     A 2012 Q3     8
 4     A 2012 Q4     9
 5     A 2013 Q1    10
 6     A 2013 Q2    10
 7     A 2013 Q3     6
 8     A 2013 Q4     9
 9     A 2014 Q1     6
10     B 2012 Q1    10
# ... with 39 more rows
</code>```

Body:
Background

I've a quarterly data set where certain quarters and corresponding values are missing. The characteristics of the data set are:

Each group should have the same number of quarters but in practe quarters are missing

For missing quarter values are unknown

This is to be resolved by sourcing imputing next available value; for instance, as available via na.locf function

Example data

# Packages
Vectorize(require)(package = c("tidyverse", "zoo", "magrittr"),
                   character.only = TRUE)

# Seed
set.seed(123)

# Dummy data
dta <- data.frame(group = rep(LETTERS[1:5], 10)) %>%
    group_by(group) %>%
    mutate(qrtr = seq(
        from = as.Date("01/01/2012", "%d/%m/%Y"),
        to = as.Date("31/5/2014", "%d/%m/%Y"),
        by = "quarter"
    )) %>%
    ungroup() %>%
    mutate(qrtr = as.yearqtr(qrtr)) %>%
    arrange(group, qrtr) %>%
    mutate(value = sample(1:10, 50, replace = TRUE))

# Remove random rows
dta[sample(1:dim(dta)[1], 10), c(2, 3)] <- NA
dta %<>% na.omit()

Preview

# A tibble: 40 x 3
   group          qrtr value
   <chr> <S3: yearqtr> <int>
 1     A       2012 Q1     3
 2     A       2012 Q2     8
 3     A       2012 Q4     9
 4     A       2013 Q1    10
 5     A       2013 Q3     6
 6     A       2013 Q4     9
 7     A       2014 Q1     6
 8     B       2012 Q1    10
 9     B       2012 Q2     5
10     B       2012 Q3     7
# ... with 30 more rows

Problem

Create add rows within each group where quarter are missing. Total number of quarter is derived from sequence min(qrtr) to max(qrtr), in the context of existing code:

seq(from = as.Date("01/01/2012", "%d/%m/%Y"),
    to = as.Date("31/5/2014", "%d/%m/%Y"),
    by = "quarter")

First non-missing value should be carried forward for the missing value.

Desired results:

>> dta
# A tibble: 50 x 3
   group          qrtr value
   <chr> <S3: yearqtr> <int>
 1     A       2012 Q1     3
 2     A       2012 Q2     8
 3     A       2012 Q3     8
 4     A       2012 Q4     9
 5     A       2013 Q1    10
 6     A       2013 Q2    10
 7     A       2013 Q3     6
 8     A       2013 Q4     9
 9     A       2014 Q1     6
10     A       2015 Q1     6
# ... with 40 more rows

Proposed approaches

One approach would rely on making use of the expand, in order to convert implicitly missing values to explicitly missing values. This so far creates missing quarters but there is no clear way of creating missing observations for value column for where given quarter is missing.

dta %>%
    # Append mixing quarters
    expand(group, qrtr) %>%
    left_join(data.frame(qrtr = as.yearqtr(
        seq(
            from = as.Date("01/01/2012", "%d/%m/%Y"),
            to = as.Date("31/5/2014", "%d/%m/%Y"),
            by = "quarter"
        )
    )), by = "qrtr") %>%
    # TODO
    # mutate(value = na.locf(value)) %>%
    arrange(group, qrtr) -> dta_fixed

Body:
You seems to be interested in padr

library(padr)
library(zoo)

#convert to POSIXct as pad() expect it to be like this
dta$qrtr <- as.POSIXct(dta$qrtr,format="%Y %q")
dta %>%
  pad(group="group") %>%
  arrange(group, qrtr) %>%
  mutate(qrtr = as.yearqtr(qrtr)) %>%
  na.locf()

output is:

# A tibble: 49 x 3
   group    qrtr value
   <chr>   <chr> <chr>
 1     A 2012 Q1     3
 2     A 2012 Q2     8
 3     A 2012 Q3     8
 4     A 2012 Q4     9
 5     A 2013 Q1    10
 6     A 2013 Q2    10
 7     A 2013 Q3     6
 8     A 2013 Q4     9
 9     A 2014 Q1     6
10     B 2012 Q1    10
# ... with 39 more rows


问:
How to call search term variable in functions.php?
I am trying to call a variable in functions.php file but it does not work for some reason. From what I have read, the default method to call search word in Wordpress is done using the following method. It is working fine in search.php but not in functions.php

```<code><?php $search_query = get_search_query(); ?>
<div align="center">
<?php echo $search_query ?>
</div>
</code>```

I am making use of the same in an array as follows in functions.php file but it is not being called.

This does not work:

```<code><?php
function load_posts_by_ajax_callback_search() {
    check_ajax_referer('load_more_posts_search', 'security');
    $paged_search = $_POST['page'];
    $args_search = array(
        'posts_per_page' => '20',
        's' => $search_query,
        'paged' => $paged_search,
    );
    $my_posts_search = new WP_Query( $args_search );
    if ( $my_posts_search->have_posts() ) :
        ?>
        <?php while ( $my_posts_search->have_posts() ) : $my_posts_search->the_post() ?>
</code>```

But when I hard code the search term "Bangalore" in the code, it is working

```<code><?php
function load_posts_by_ajax_callback_search() {
    check_ajax_referer('load_more_posts_search', 'security');
    $paged_search = $_POST['page'];
    $args_search = array(
        'posts_per_page' => '20',
        's' => 'Bangalore',
        'paged' => $paged_search,
    );
    $my_posts_search = new WP_Query( $args_search );
    if ( $my_posts_search->have_posts() ) :
        ?>
        <?php while ( $my_posts_search->have_posts() ) : $my_posts_search->the_post() ?>
</code>```

How do I make it work for all keywords?

This is the script that calls this post
This script runs in search.php to call more posts

```<code><script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore', function() {

    var data = {
        'action': 'load_posts_by_ajax_search',
        'page': page,
        'security': '<?php echo wp_create_nonce("load_more_posts_search"); ?>'
    };

    $.post(ajaxurl, data, function(response) {
        $('.my-posts').append(response);
        page++;
    });
});
});

</script>
</code>```

The Search Term Comes From This Search From

```<code><form method="get" id="searchform" action="<?php bloginfo('url'); ?>" target="_self">
<div>
<input style="text-align:center;width:100%;margin:0 0 12px; 0;border-color:#4a235a;color:#000000;" placeholder='Eg:Location,Skill,Company' class="text" type="text" value="" name="s" id="s" />
</div>
<div>
<input type="submit" style="text-align:center;margin:0 0 0 0;width:100%;border:1.5px solid;border-color:grey;background-color:#4a235a;color:#f4511e;" class="submit button" name="submit" value="<?php _e('Search');?>" />
</div>
</form>
</code>```

Please Let Me Know If You Need The Complete Code From search.php and functions.php file . Thanks for any input and help.

答:
Process:

The visitor writes the search term and clicks the search button

Using jQuery we will access the search term and send it with our request to the PHP script

In the PHP function we will get the search term and use the "s" parameter in our args array for WP_Query.

Access the search term with jQuery

```<code>$('body').on('click', '.loadmore', function() {

    var data = {
        'action': 'load_posts_by_ajax_search',
        'page': page,
        'searchTerm': $('#s').val(), //Get the search term.
        'security': '<?php echo wp_create_nonce("load_more_posts_search"); ?>'
    }
</code>```

Update your PHP code:

```<code>$paged_search = $_POST['page'];
$search_term = esc_attr($_POST['searchTerm']);
$args_search = array(
    'posts_per_page' => '20',
    's' => $search_term,
    'paged' => $paged_search,
);
</code>```

Body:
I am trying to call a variable in functions.php file but it does not work for some reason. From what I have read, the default method to call search word in Wordpress is done using the following method. It is working fine in search.php but not in functions.php

<?php $search_query = get_search_query(); ?>

<?php echo $search_query ?>

I am making use of the same in an array as follows in functions.php file but it is not being called.

This does not work:

<?php
function load_posts_by_ajax_callback_search() {
    check_ajax_referer('load_more_posts_search', 'security');
    $paged_search = $_POST['page'];
    $args_search = array(
        'posts_per_page' => '20',
        's' => $search_query,
        'paged' => $paged_search,
    );
    $my_posts_search = new WP_Query( $args_search );
    if ( $my_posts_search->have_posts() ) :
        ?>
        <?php while ( $my_posts_search->have_posts() ) : $my_posts_search->the_post() ?>

But when I hard code the search term "Bangalore" in the code, it is working

<?php
function load_posts_by_ajax_callback_search() {
    check_ajax_referer('load_more_posts_search', 'security');
    $paged_search = $_POST['page'];
    $args_search = array(
        'posts_per_page' => '20',
        's' => 'Bangalore',
        'paged' => $paged_search,
    );
    $my_posts_search = new WP_Query( $args_search );
    if ( $my_posts_search->have_posts() ) :
        ?>
        <?php while ( $my_posts_search->have_posts() ) : $my_posts_search->the_post() ?>

How do I make it work for all keywords?

This is the script that calls this post
This script runs in search.php to call more posts

The Search Term Comes From This Search From

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>" target="_self">

<input style="text-align:center;width:100%;margin:0 0 12px; 0;border-color:#4a235a;color:#000000;" placeholder='Eg:Location,Skill,Company' class="text" type="text" value="" name="s" id="s" />

<input type="submit" style="text-align:center;margin:0 0 0 0;width:100%;border:1.5px solid;border-color:grey;background-color:#4a235a;color:#f4511e;" class="submit button" name="submit" value="<?php _e('Search');?>" />

</form>

Please Let Me Know If You Need The Complete Code From search.php and functions.php file . Thanks for any input and help.

Body:
Process:

The visitor writes the search term and clicks the search button

Using jQuery we will access the search term and send it with our request to the PHP script

In the PHP function we will get the search term and use the "s" parameter in our args array for WP_Query.

Access the search term with jQuery

$('body').on('click', '.loadmore', function() {

    var data = {
        'action': 'load_posts_by_ajax_search',
        'page': page,
        'searchTerm': $('#s').val(), //Get the search term.
        'security': '<?php echo wp_create_nonce("load_more_posts_search"); ?>'
    }

Update your PHP code:

$paged_search = $_POST['page'];
$search_term = esc_attr($_POST['searchTerm']);
$args_search = array(
    'posts_per_page' => '20',
    's' => $search_term,
    'paged' => $paged_search,
);


问:
Iphone MPMoviePlayerController "the server is not correctly configured"?
On the iphone, when trying to play a broken url using MPMoviePlayerController the user gets an alertbox with the message "the server is not correctly configured".

Is there any way to change this to something more user-friendly? Alternatively, is there any way to get an error status from the player instead of getting this message?

Thanks in advance..

答: Once I've got this error when trying to play urlencoded url string. I removed urlencoding method call before ask MPMoviePlayerController to play url and everything ok.</p>


问:
Why I get error when I try to generate ActionLink?
I have this HtmlHelper:

```<code>@foreach (var item in Model)
{
<tr>
    <td>
        @Html.ActionLink(modelItem => item.LayoutID, "someAction");
    </td>
</tr>
}
</code>```

On this row,

```<code>@Html.ActionLink(modelItem => item.LayoutID, "someAction");
</code>```

i get this error:

```<code>CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type
</code>```

Why do I get the above error ?
The LayoutID is of string type.

EDIT
Improved Formatting

答:
you can not use modelitem as parameter in actionlink.actionlink must have string value as parameter
try below code:

```<code>   @Html.ActionLink(item.LayoutID, "someAction")
</code>```

or i will suggest you to direct write down string

```<code> @Html.ActionLink("View Report", "someAction")
</code>```

Body:
I have this HtmlHelper:

@foreach (var item in Model)
{

        @Html.ActionLink(modelItem => item.LayoutID, "someAction");

}

On this row,

@Html.ActionLink(modelItem => item.LayoutID, "someAction");

i get this error:

CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type

Why do I get the above error ?
The LayoutID is of string type.

EDIT
Improved Formatting

Body:
you can not use modelitem as parameter in actionlink.actionlink must have string value as parameter
try below code:

   @Html.ActionLink(item.LayoutID, "someAction")

or i will suggest you to direct write down string

 @Html.ActionLink("View Report", "someAction")


问:
tensorflow: self.stack[-1] is not default (list index out of range)
I got error message such this:

IndexErrorTraceback (most recent call last)

```<code>/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.pyc in get_controller(self, default)
3813     finally:
3814       if self._enforce_nesting:
-> 3815         if self.stack[-1] is not default:
3816           raise AssertionError(
3817               "Nesting violated for default stack of %s objects"
</code>```

IndexError: list index out of range

My code like this:

```<code>with tf.Graph().as_default():
    tf.reset_default_graph()
    session_conf = tf.ConfigProto(
      allow_soft_placement=True,
      log_device_placement=False)
    sess = tf.Session(config=session_conf)
    with sess.as_default():
        cnn = TextCNN(
            sequence_length=708,
            num_classes=9,
            embedding_size=embedding_size,
            filter_sizes=filter_sizes,
            num_filters=num_filters,
            l2_reg_lambda=l2_reg_lambda)

        ...

        step = 0
        while step < num_epochs:
            x_batch, y_batch = next_batch(training_x, training_y, training_prot_num)
            v_x_batch, v_y_batch = next_batch(validation_x, validation_y, validation_prot_num)
            train_step(x_batch, y_batch)
            currenct_step = tf.train.global_step(sess, gloabl_step)
            if currect_step % evaluate_every == 0:
                print("\nEvaluation:")
                dev_step(v_x_batch,v_y_batch)
                print("")
</code>```

How should I modify this code for fixing errors?

答:
Your problem seems similar to this StackOverflow question.

Try removing tf.reset_default_graph() and see if that fixes your issue.

Body:
I got error message such this:

IndexErrorTraceback (most recent call last)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.pyc in get_controller(self, default)
3813     finally:
3814       if self._enforce_nesting:
-> 3815         if self.stack[-1] is not default:
3816           raise AssertionError(
3817               "Nesting violated for default stack of %s objects"

IndexError: list index out of range

My code like this:

with tf.Graph().as_default():
    tf.reset_default_graph()
    session_conf = tf.ConfigProto(
      allow_soft_placement=True,
      log_device_placement=False)
    sess = tf.Session(config=session_conf)
    with sess.as_default():
        cnn = TextCNN(
            sequence_length=708,
            num_classes=9,
            embedding_size=embedding_size,
            filter_sizes=filter_sizes,
            num_filters=num_filters,
            l2_reg_lambda=l2_reg_lambda)

        ...

        step = 0
        while step < num_epochs:
            x_batch, y_batch = next_batch(training_x, training_y, training_prot_num)
            v_x_batch, v_y_batch = next_batch(validation_x, validation_y, validation_prot_num)
            train_step(x_batch, y_batch)
            currenct_step = tf.train.global_step(sess, gloabl_step)
            if currect_step % evaluate_every == 0:
                print("\nEvaluation:")
                dev_step(v_x_batch,v_y_batch)
                print("")

How should I modify this code for fixing errors?


答:
You will need to pass the variable into your function for it to be available in that function.

```<code>function load_posts_by_ajax_callback_search($searchInput) {
    check_ajax_referer('load_more_posts_search', 'security');
    $paged_search = $_POST['page'];
    $args_search = array(
        'posts_per_page' => '20',
        's' => $searchInput,
        'paged' => $paged_search,
</code>```

And when you call the function, you put in your $search_query variable.

```<code>load_posts_by_ajax_search($search_query)
</code>```

Title: How to call search term variable in functions.php?

Body:
You will need to pass the variable into your function for it to be available in that function.

function load_posts_by_ajax_callback_search($searchInput) {
    check_ajax_referer('load_more_posts_search', 'security');
    $paged_search = $_POST['page'];
    $args_search = array(
        'posts_per_page' => '20',
        's' => $searchInput,
        'paged' => $paged_search,

And when you call the function, you put in your $search_query variable.

load_posts_by_ajax_search($search_query)


问:
How to deserialize XML document with inner tags and inner elements?
This is my XML file.

```<code><getMetadata>
 <Project Name="Doors_Demo">
  <Module FullPath="/Doors_Demo/Test_Module2">
   <Attributes>
    <Attribute name="TableType" type="TableType" />
    <Attribute name="TableTopBorder" type="TableEdgeType" />
   </Attributes>
  </Module>
 </Project>
</getMetadata>
</code>```

I want to deserialize the above XML

Below is my code:

```<code>[XmlRoot("getMetadata")]
public class RootClass
{
    public Project element_Project;

    [XmlElement("Project")]
    public Project Project
    {
        get { return element_Project; }
        set { element_Project = value; }
    }
}

public class Project
{
    public string name;

    [XmlAttribute("Name")]
    public string Id
    {
        get { return name; }
        set { name = value; }
    }
}

public static void Main(string[] args)
{
    RootClass obj = new RootClass();

    XmlSerializer serializer = new XmlSerializer(typeof(RootClass));
    using (FileStream stream = new FileStream(@"E:\getMetadata(4).xml", FileMode.Open))
    {
        RootClass myxml = (RootClass)serializer.Deserialize(stream);

        Console.WriteLine(myxml.Project.name);
    }
}
</code>```

I want to deserialize my XML into a list, I am not able to access all inner elements and attributes inside the root element.

I want details of module element and its inner elements and tags into list which can be accessed.

答:
Here is a little trick to generate classes from your XML automatically.

First, create a new empty class, name it for example TempXml.

Copy your XML to the clipboard and open the new empty class you just created.

Go to Visual Studio Edit menu then Paste Special and Paste XML as Classes:

This will generate the following code:

```<code>/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class getMetadata
{

    private getMetadataProject projectField;

    /// <remarks/>
    public getMetadataProject Project
    {
        get
        {
            return this.projectField;
        }
        set
        {
            this.projectField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProject
{

    private getMetadataProjectModule moduleField;

    private string nameField;

    /// <remarks/>
    public getMetadataProjectModule Module
    {
        get
        {
            return this.moduleField;
        }
        set
        {
            this.moduleField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModule
{

    private getMetadataProjectModuleAttribute[] attributesField;

    private string fullPathField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Attribute", IsNullable = false)]
    public getMetadataProjectModuleAttribute[] Attributes
    {
        get
        {
            return this.attributesField;
        }
        set
        {
            this.attributesField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string FullPath
    {
        get
        {
            return this.fullPathField;
        }
        set
        {
            this.fullPathField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModuleAttribute
{

    private string nameField;

    private string typeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string type
    {
        get
        {
            return this.typeField;
        }
        set
        {
            this.typeField = value;
        }
    }
}
</code>```

Which should work fine with the XmlSerializer class.

You can clean up a little bit the generated output by removing the empty remarks, changing the name of the classes to use camel case (in this case you need to specify the real element name in the attribute as you were doing in your question) or move the classes to different files.

Hope it helps.

Body:
This is my XML file.

<getMetadata>
 <Project Name="Doors_Demo">
  <Module FullPath="/Doors_Demo/Test_Module2">
   <Attributes>
    <Attribute name="TableType" type="TableType" />
    <Attribute name="TableTopBorder" type="TableEdgeType" />
   </Attributes>
  </Module>
 </Project>
</getMetadata>

I want to deserialize the above XML

Below is my code:

[XmlRoot("getMetadata")]
public class RootClass
{
    public Project element_Project;

    [XmlElement("Project")]
    public Project Project
    {
        get { return element_Project; }
        set { element_Project = value; }
    }
}

public class Project
{
    public string name;

    [XmlAttribute("Name")]
    public string Id
    {
        get { return name; }
        set { name = value; }
    }
}

public static void Main(string[] args)
{
    RootClass obj = new RootClass();

    XmlSerializer serializer = new XmlSerializer(typeof(RootClass));
    using (FileStream stream = new FileStream(@"E:\getMetadata(4).xml", FileMode.Open))
    {
        RootClass myxml = (RootClass)serializer.Deserialize(stream);

        Console.WriteLine(myxml.Project.name);
    }
}

I want to deserialize my XML into a list, I am not able to access all inner elements and attributes inside the root element.

I want details of module element and its inner elements and tags into list which can be accessed.

Body:
Here is a little trick to generate classes from your XML automatically.

First, create a new empty class, name it for example TempXml.

Copy your XML to the clipboard and open the new empty class you just created.

Go to Visual Studio Edit menu then Paste Special and Paste XML as Classes:

This will generate the following code:

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class getMetadata
{

    private getMetadataProject projectField;

    /// <remarks/>
    public getMetadataProject Project
    {
        get
        {
            return this.projectField;
        }
        set
        {
            this.projectField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProject
{

    private getMetadataProjectModule moduleField;

    private string nameField;

    /// <remarks/>
    public getMetadataProjectModule Module
    {
        get
        {
            return this.moduleField;
        }
        set
        {
            this.moduleField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModule
{

    private getMetadataProjectModuleAttribute[] attributesField;

    private string fullPathField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Attribute", IsNullable = false)]
    public getMetadataProjectModuleAttribute[] Attributes
    {
        get
        {
            return this.attributesField;
        }
        set
        {
            this.attributesField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string FullPath
    {
        get
        {
            return this.fullPathField;
        }
        set
        {
            this.fullPathField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class getMetadataProjectModuleAttribute
{

    private string nameField;

    private string typeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string type
    {
        get
        {
            return this.typeField;
        }
        set
        {
            this.typeField = value;
        }
    }
}

Which should work fine with the XmlSerializer class.

You can clean up a little bit the generated output by removing the empty remarks, changing the name of the classes to use camel case (in this case you need to specify the real element name in the attribute as you were doing in your question) or move the classes to different files.

Hope it helps.


问:
Drupal: sync users accounts between 2 different Drupal websites
I've a Drupal A website with users accounts running on server A and with domain A.

Now, I need to build a Drupal B website on server B and domain B, and when someone register on Drupal B, he is automatically registered on Drupal A.

In other terms, I need so sync the users accounts.
Can i easily make it ?

thanks

答:
You'll have to write something to export the users from Site A.  Then use Feeds to import.  You may be able to use Rules or some custom scripts to export from Site A to go into Site B (probably by running drupal cron on both in sequence).

Another idea would be to use the same database table for both.  This is accomplished easily.

For Site B's settings file:

```<code>$db_prefix = array(
  'users' => 'siteAdb.',
);
</code>```

where siteAdb is the database that contains Site A's drupal installation so long as both databases use the same account.  Of course you would have to apply any appropriate prefixes.

Body:
You'll have to write something to export the users from Site A.  Then use Feeds to import.  You may be able to use Rules or some custom scripts to export from Site A to go into Site B (probably by running drupal cron on both in sequence).

Another idea would be to use the same database table for both.  This is accomplished easily.

For Site B's settings file:

$db_prefix = array(
  'users' => 'siteAdb.',
);

where siteAdb is the database that contains Site A's drupal installation so long as both databases use the same account.  Of course you would have to apply any appropriate prefixes.


问:
Validate that exposed primary/foreign keys in a form are intact
I have a Survey form. Every question has 3-4 pre-defined answers as radio buttons. The value of a radio button is the primary key of the answer in the database.

As all answers to all questions are stored in one table, if a user increments the value, the ID may still be a valid foreign key, but it does not belong to that question.

What's the best practice to be sure the value of the radio button is not manipulated?

答:
In your controller, you can do something like this:</p>

```<code># Get the ids of the answers that are valid for that question
$validAnswerIds = $Question->answers->pluck('id')->toArray();

# Validate that the answer given is in there
$rules = ['answer' => Rule::in( $validAnswerIds ) ];
$request->validate( $rules );
</code>```

Body:
In your controller, you can do something like this:

# Get the ids of the answers that are valid for that question
$validAnswerIds = $Question->answers->pluck('id')->toArray();

# Validate that the answer given is in there
$rules = ['answer' => Rule::in( $validAnswerIds ) ];
$request->validate( $rules );


问:
How to store the dropdown, other option text input data in database using ruby on rails?
I do have a select dropdown and in that few options also and in that OTHERS option also

```<code><div class="form-group clearfix">
    <div class="col-sm-2" id="mainone">
        <%#= form.text_field :city, placeholder: "CITY", class: 'form-control required' %>
        <%= form.select :city, options_for_select([['DELHI'],['GURGAON'],['FARIDABAD'],['GHAZIABAD'],['NOIDA'],['MUMBAI'],['THANE'], ['BANGALORE'],['OTHERS']]), {include_blank: 'CITY*'}, class: 'form-control required', name: 'city', :onchange => 'Checkselectedone(this.value);' %>
            <% if @ezetab.errors[:city].present? %>
                <span class="error_msg"><%= @ezetab.errors[:city][0]%></span>
            <% end %>
    </div>
</div>
<div class="form-group clearfix">
    <div class="col-sm-2">
        <%= form.text_field :city, name: 'city', id: 'newtext', label: "Others",style: 'display:none;' %>
    </div>
</div>
</code>```

when i select the others option one more text box should come and i
  can type which is my city.

but the thing is here that entered city data also should be store in
  the same filed. but i dont no how to save that one in the same field.

these are the my fields

```<code>def ezetab_params
        params.require(:ezetab).permit(:name, :email, :phonenumber, :organization, :city)
    end
</code>```

this is javascript code

```<code><script type="text/javascript">
function Checkselectedone(val){
    alert("one more text box is coming");
 var element=document.getElementById('newtext');
 if(val=='OTHERS')
   element.style.display='block';
 else
   element.style.display='none';
}

</script>

can any one tell me how to store that other option data also in the same city filed and i have give required also for that it should not be shown any validation msg. please let me know.
thanks in advance
</code>```

答:
```<code><div class="form-group clearfix">
    <div class="col-sm-2" id="mainone">
        <%#= form.text_field :city, placeholder: "CITY", class: 'form-control required' %>
        <%= form.select :city, options_for_select([['DELHI'],['GURGAON'],['FARIDABAD'],['GHAZIABAD'],['NOIDA'],['MUMBAI'],['THANE'], ['BANGALORE'],['OTHERS']]), {include_blank: 'CITY*'}, class: 'form-control required', :onchange => 'Checkselectedone(this.value);' %>
            <% if @ezetab.errors[:city].present? %>
                <span class="error_msg"><%= @ezetab.errors[:city][0]%></span>
            <% end %>
    </div>
</div>
<div class="form-group clearfix">
    <div class="col-sm-2">
        <%= text_field_tag :others, "", class: 'form-control', id: 'newtext', style: 'display:none;' %>
    </div>
</div>
</code>```

Controller: -

```<code>def ezetab_params
   ep = params.require(:ezetab).permit(:name, :email, :phonenumber, :organization, :city)
   ep[:city] = params[:others] if params[:others].present?
   ep
end
</code>```

Body:
I do have a select dropdown and in that few options also and in that OTHERS option also

        <%#= form.text_field :city, placeholder: "CITY", class: 'form-control required' %>
        <%= form.select :city, options_for_select([['DELHI'],['GURGAON'],['FARIDABAD'],['GHAZIABAD'],['NOIDA'],['MUMBAI'],['THANE'], ['BANGALORE'],['OTHERS']]), {include_blank: 'CITY*'}, class: 'form-control required', name: 'city', :onchange => 'Checkselectedone(this.value);' %>
            <% if @ezetab.errors[:city].present? %>
                <%= @ezetab.errors[:city][0]%>
            <% end %>

        <%= form.text_field :city, name: 'city', id: 'newtext', label: "Others",style: 'display:none;' %>

when i select the others option one more text box should come and i
  can type which is my city.

but the thing is here that entered city data also should be store in
  the same filed. but i dont no how to save that one in the same field.

these are the my fields

def ezetab_params
        params.require(:ezetab).permit(:name, :email, :phonenumber, :organization, :city)
    end

this is javascript code

can any one tell me how to store that other option data also in the same city filed and i have give required also for that it should not be shown any validation msg. please let me know.
thanks in advance

Body:
<div class="form-group clearfix">
    <div class="col-sm-2" id="mainone">
        <%#= form.text_field :city, placeholder: "CITY", class: 'form-control required' %>
        <%= form.select :city, options_for_select([['DELHI'],['GURGAON'],['FARIDABAD'],['GHAZIABAD'],['NOIDA'],['MUMBAI'],['THANE'], ['BANGALORE'],['OTHERS']]), {include_blank: 'CITY*'}, class: 'form-control required', :onchange => 'Checkselectedone(this.value);' %>
            <% if @ezetab.errors[:city].present? %>
                <span class="error_msg"><%= @ezetab.errors[:city][0]%></span>
            <% end %>
    </div>
</div>
<div class="form-group clearfix">
    <div class="col-sm-2">
        <%= text_field_tag :others, "", class: 'form-control', id: 'newtext', style: 'display:none;' %>
    </div>
</div>

Controller: -

def ezetab_params
   ep = params.require(:ezetab).permit(:name, :email, :phonenumber, :organization, :city)
   ep[:city] = params[:others] if params[:others].present?
   ep
end


问:
Rerurn null if subquery hasn't value sql
If this query hasn't B values, but has A values, can I have null where there are no values?

```<code>SELECT A, B
FROM
(SELECT title as A
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'),

(SELECT title as B
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B')
</code>```

For example, this table must be show

```<code>  A        B
---------------
Computer  null
</code>```

But now it show the values only if Id has Type A and Type B

答:
There is no such thing as a LEFT CROSS JOIN, but you can implement it using a LEFT JOIN:

```<code>SELECT a.A, b.B
FROM (SELECT title as A
      FROM TABLE JOIN
           TABLE2
           ON TABLE_TABLE2_ID = TABLE2_ID JOIN
           TABLE3
           ON TABLE_TABLE3_ID = TABLE3_ID
      WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'
     ) a, LEFT JOIN
     (SELECT title as B
      FROM TABLE JOIN
           TABLE2
           ON TABLE_TABLE2_ID = TABLE2_ID JOIN
           TABLE3
           ON TABLE_TABLE3_ID = TABLE3_ID
      WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B'
     ) b
     ON 1 = 1;
</code>```

Body:
If this query hasn't B values, but has A values, can I have null where there are no values?

SELECT A, B
FROM
(SELECT title as A
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'),

(SELECT title as B
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B')

For example, this table must be show

  A        B
---------------
Computer  null

But now it show the values only if Id has Type A and Type B

Body:
There is no such thing as a LEFT CROSS JOIN, but you can implement it using a LEFT JOIN:

SELECT a.A, b.B
FROM (SELECT title as A
      FROM TABLE JOIN
           TABLE2
           ON TABLE_TABLE2_ID = TABLE2_ID JOIN
           TABLE3
           ON TABLE_TABLE3_ID = TABLE3_ID
      WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'
     ) a, LEFT JOIN
     (SELECT title as B
      FROM TABLE JOIN
           TABLE2
           ON TABLE_TABLE2_ID = TABLE2_ID JOIN
           TABLE3
           ON TABLE_TABLE3_ID = TABLE3_ID
      WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B'
     ) b
     ON 1 = 1;


问:
Changing Port on HUG
Is it possible to change the port number on HUG for python?
I have the following sample of what I'm trying to do.
The API defaults to port 8000 but I want to be able to set it manually. </p>

```<code>@hug.post()
def receive_json(request):
    request=str(request)
    print("Hello! Glad you're here!")
    print(request)
    process=os.system("echo "+'"'+request+'"')
</code>```

答:
add at the end of your app.py (or whatever it's name is) file:

```<code>hug.API(__name__).http.serve(port=8005)
</code>```

for serving on port 8005

Title: Changing Port on HUG

Body:
Is it possible to change the port number on HUG for python?
I have the following sample of what I'm trying to do.
The API defaults to port 8000 but I want to be able to set it manually.

@hug.post()
def receive_json(request):
    request=str(request)
    print("Hello! Glad you're here!")
    print(request)
    process=os.system("echo "+'"'+request+'"')

Body:
add at the end of your app.py (or whatever it's name is) file:

hug.API(__name__).http.serve(port=8005)

for serving on port 8005


问:
Right & Left Img Borders Being Cut Off on Mobile - Force Mobile to Display Images + Borders?
I have a series 8.5" x 11" @ 72ppi magazine pages exported from InDesign as jpegs that I wish to display within Blogger posts. I want to display a 1 pixel border around each of these images so the edges of the pages are more easily discerned. I am testing the mobile version of the Blogger site in Chrome's emulator.

The images are correctly be resized to fit the mobile device; however the right and left borders are being cut off. Sometimes the page will load with one border showing, but the opposing border is then 2 pixels off screen. Sometimes when I reload the blog, or change devices, the borders might appear correctly, but then start not appearing once again. How do I make sure the images are correctly resized with the border on each side

```<code>.post-body-container img {
border:1px solid #000000;
padding:0px;
width: 612px;
height:100%;
display: block;
}
</code>```

答:
It's better to not have a fixed width if you want responsiveness to work.

```<code>.post-body-container {
max-width: 100%;
}

.post-body-container img {
border:1px solid #000000;
padding:0px;
width: 100%;
height: auto;
display: block;
}
</code>```

Example (try resizing the page to see the image size changing): https://codepen.io/felipefreitag/pen/EbXxjx

Further reading:
https://www.w3schools.com/css/css_rwd_images.asp

Body:
I have a series 8.5" x 11" @ 72ppi magazine pages exported from InDesign as jpegs that I wish to display within Blogger posts. I want to display a 1 pixel border around each of these images so the edges of the pages are more easily discerned. I am testing the mobile version of the Blogger site in Chrome's emulator.

The images are correctly be resized to fit the mobile device; however the right and left borders are being cut off. Sometimes the page will load with one border showing, but the opposing border is then 2 pixels off screen. Sometimes when I reload the blog, or change devices, the borders might appear correctly, but then start not appearing once again. How do I make sure the images are correctly resized with the border on each side

.post-body-container img {
border:1px solid #000000;
padding:0px;
width: 612px;
height:100%;
display: block;
}

Body:
It's better to not have a fixed width if you want responsiveness to work.

.post-body-container {
max-width: 100%;
}

.post-body-container img {
border:1px solid #000000;
padding:0px;
width: 100%;
height: auto;
display: block;
}

Example (try resizing the page to see the image size changing): https://codepen.io/felipefreitag/pen/EbXxjx

Further reading:
https://www.w3schools.com/css/css_rwd_images.asp


问:
C++ vector debug implementation
While learning c++ I went through the pains of learning what iterators were, and exactly how to use them.  Then, I went through the pain of learning what function calls invalidate iterators, and spotting them quickly.  I've been following questions lately and have noticed that a very common theme is people not realizing that calling vector::erase() invalidates iterators.  This made me wonder if there were a debug implementation of vector that does runtime checking against vector valid-ness?

My initial thoughts were that it would have to be a wrapper around vector that basically tracked all existing iterators, and set an isValid boolean when an action was performed that invalidated them.  Then, when dereferencing or incrementing, isValid could be checked.

This would help diagnose more obscure errors where the erase() call is nested (accidentally, or unknowingly) deep within a function call, while that same vector is being iterator over.

Does anyone know of such an implementation, or any reasons why one should not be used?

EDIT: I am using linux and g++.

答:
Microsoft's implementation does some debug checking (ref, and ref).  It checks specifically for range, so I'm not sure if the erase() scenario fits or not.

Edit for jalf's contribution:

It appears that GCC (and g++) has similar functionality:

stackoverflow.com/questions/2567997/ and

gcc.gnu.org/onlinedocs/libstdc++/manual/debug_mode.html

Title: C++ vector debug implementation


问:
Sending a request and receiving a response in Node JS
Hi I am new to Node JS and trying to understand the working of client server communication.

File on Server- (express.js)

```<code>  app.post('/action', (req, res) => {
    const status = action.doAction(req);
  });
</code>```

AJax Call on Client :

```<code>$.ajax({
  type: 'POST',
  url: '/action',
  data: foo.getJSON(),
  success: () => {
    console.log('Action done');
  }
});
</code>```

My ajax call send a JSON data and server side implements some function which does further action and returns true or false.

But on success on client side console there is nothing printed. Also, I want to understand that how can I send data i.e. status back to client from Server by response object and how can I receive it and print on client side. Also, I want to print which is in success after completing all the action in my doAction function which takes about 2-4 seconds.
 Can somebody explain how to achieve all this?

答:
In order to get your code running try this

app.post('/action', (req, res) => {
    res.send('request done');
  });

NodeJS is non-blocking. So you need promises or async/await to process data in doAction()

Body:
Hi I am new to Node JS and trying to understand the working of client server communication.

File on Server- (express.js)

  app.post('/action', (req, res) => {
    const status = action.doAction(req);
  });

AJax Call on Client :

$.ajax({
  type: 'POST',
  url: '/action',
  data: foo.getJSON(),
  success: () => {
    console.log('Action done');
  }
});

My ajax call send a JSON data and server side implements some function which does further action and returns true or false.

But on success on client side console there is nothing printed. Also, I want to understand that how can I send data i.e. status back to client from Server by response object and how can I receive it and print on client side. Also, I want to print which is in success after completing all the action in my doAction function which takes about 2-4 seconds.
 Can somebody explain how to achieve all this?


问:
How can I retrieve unique values from a column with Knex.js?
I use Knex.js to communicate to Postgres database.

I have rows in a table with a column named 'state' which represents a US state.

How can I retrieve all unique values from this column?

答:
You are probably looking for knex.distinct + knex.pluck combo.</p>
```<code>knex
    .distinct()
    .from('tablename')
    .pluck('state')
    .then(states => {
        console.log(states)
    })
</code>```

Body:
You are probably looking for knex.distinct + knex.pluck combo.

knex
    .distinct()
    .from('tablename')
    .pluck('state')
    .then(states => {
        console.log(states)
    })


答:
I found a solution.

You have to transform data to as_xts and define date column:

```<code>newdata <- as_xts(thedata, date_col = `Date Time`)
newdata <- newdata[endpoints(newdata, "minutes", 10)]
</code>```

Title: must be either xts-coercible or timebased

Body:
I have this kind of data:

Date Time           Value
02-09-17 14:17:20   92
02-09-17 14:17:20   91
02-09-17 14:17:20   38.62391
02-09-17 14:17:20   120.3348
02-09-17 14:17:20   18.1
02-09-17 14:17:20   11.2
02-09-17 14:26:40   97
02-09-17 14:26:40   102
02-09-17 14:26:40   38.62254
02-09-17 14:26:40   120.3719
02-09-17 14:26:40   18.1
02-09-17 14:26:40   11.2
02-09-17 14:30:09   103
02-09-17 14:30:09   103
02-09-17 14:30:09   38.62012
02-09-17 14:30:09   120.3853
02-09-17 14:30:09   18.1
02-09-17 14:30:09   11.3
02-09-17 14:37:00   102
02-09-17 14:37:00   103
02-09-17 14:37:00   38.61536
02-09-17 14:37:00   120.4119
02-09-17 14:37:00   18.1
02-09-17 14:37:00   11.3
02-09-17 14:41:30   101
02-09-17 14:41:30   101
02-09-17 14:41:30   38.61232
02-09-17 14:41:30   120.4295
02-09-17 14:41:30   18.1
02-09-17 14:41:30   11.3
02-09-17 14:46:59   99
02-09-17 14:46:59   98
02-09-17 14:46:59   38.60936
02-09-17 14:46:59   120451
02-09-17 14:46:59   18.1
02-09-17 14:46:59   11.3
02-09-17 14:51:20   97
02-09-17 14:51:20   96

and I want to resample every 10 minutes.

mydata <- read_csv('~/dd.csv')
mydata$`Date Time` <- as.POSIXct(mydata$`Date Time`, "%d-%m-%y %H:%M:%S")

mydata <- mydata[endpoints(mydata, "minutes", 10)]

and I am receiving:

Error in try.xts(x, error = "must be either xts-coercible or
  timeBased") : must be either xts-coercible or timeBased

Body:
I found a solution.

You have to transform data to as_xts and define date column:

newdata <- as_xts(thedata, date_col = `Date Time`)
newdata <- newdata[endpoints(newdata, "minutes", 10)]


问:
PHP snippet for translated content. Is it a good practice? Can it get better/simpler?
I am currently developing a website that will have translated content served by different gTLD. (example.com, example.fr, example.de)

The idea is to have them all redirect to the same content on the same server, and based on the gTLD, have a simple php routine that serves the correct language.

Here is the code I am using to detect the domain/language:

```<code><?php

$url_tld = explode("." , $_SERVER['HTTP_HOST'] , 3);
if ($url_tld[2] == "fr") { $language = "FR"; $lang_id = 1;}
elseif ($url_tld[2] == "de") { $language = "DE"; $lang_id = 2;}
elseif ($url_tld[2] == "nl") { $language = "NL"; $lang_id = 3;}
else { $language = "EN"; $lang_id = 0;}

function txt($x) {
    global $lang_id;
    echo $x[$lang_id];
};
</code>```

In the html code I run txt function whenever I need different language content; example:

```<code><h1><?=txt(['Hello World','Bonjour France','Hallo Deutschland','Hallo Nederland'])?></h1>
</code>```

I am trying to avoid using any database as the website will be mostly static.

Can this approach get simpler? Or more eye friendly (for those updating code manually)?

Best regards and thanks in advance.

答:
I don't like the 3 in your explode() and the 2's in your indexes. What is it based on? What if the domain is example.co.uk or www.example.fr? Better use:

```<code>$domainExtension = end(explode(".",$_SERVER['HTTP_HOST']));
</code>```

Then you can do:

```<code>switch ($domainExtension) {
  case 'fr' : $language = 'FRE'; break;
  case 'de' : $language = 'GER'; break;
  case 'nl' : $language = 'DUT'; break;
  default   : $language = 'ENG'; break;
}
</code>```

As you can see the switch () makes the code more readable. I don't abbreviate unnecessarily, for better readability. I also used the official three-letter abbreviation for languages. It's a bit more versatile, but two letters will do, see:

https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes

Personally I don't like numbers for languages, that's why I left them out, although I understand why you used them. You can do:

```<code>$texts = ['hello','Bonjour','Guten Tag','Hallo'];
</code>```

but in that case you cannot leave out any languages. I would forget the numbers and do:

```<code>$texts = ['ENG' => 'hello',
          'FRE' => 'Bonjour',
          'GER' => 'Guten Tag',
          'DUT' => 'Hallo'];
</code>```

Then, when a language is missing, you can replace it by another:

```<code>function getText($language,$texts) {
  if (isset($texts[$language]) return $texts[$language];  // it is there
                          else return reset($texts);      // take the first
};
</code>```

You can then also sort the languages from most commonly used to rarely used. Note that I don't use a global, which is on purpose. Again, you can choose to use one.

Finally, to get back to the simpler list of texts you could use another function:

```<code>function setTexts($english,$french,$german,$dutch)
{
  return ['ENG' => $english,
          'FRE' => $french,
          'GER' => $german,
          'DUT' => $dutch];
}

$helloTexts = setTexts('hello','Bonjour','Guten Tag','Hallo');
</code>```

and then used like this:

```<code>echo getText($language,$helloTexts);
</code>```

But I have to stress that there are many other ways of doing this. You could, for instance, have separate include files for the various languages. That way you don't process any texts that aren't used. It might save a bit of time, but it will be minimal, and it is nice to keep the different translations of the same piece of text together.

One last tip: The broswer can tell you the preferred language of the visitor. See: $_SERVER['HTTP_ACCEPT_LANGUAGE'].

Body:
I am currently developing a website that will have translated content served by different gTLD. (example.com, example.fr, example.de)

The idea is to have them all redirect to the same content on the same server, and based on the gTLD, have a simple php routine that serves the correct language.

Here is the code I am using to detect the domain/language:

<?php

$url_tld = explode("." , $_SERVER['HTTP_HOST'] , 3);
if ($url_tld[2] == "fr") { $language = "FR"; $lang_id = 1;}
elseif ($url_tld[2] == "de") { $language = "DE"; $lang_id = 2;}
elseif ($url_tld[2] == "nl") { $language = "NL"; $lang_id = 3;}
else { $language = "EN"; $lang_id = 0;}

function txt($x) {
    global $lang_id;
    echo $x[$lang_id];
};

In the html code I run txt function whenever I need different language content; example:

<?=txt(['Hello World','Bonjour France','Hallo Deutschland','Hallo Nederland'])?>

I am trying to avoid using any database as the website will be mostly static.

Can this approach get simpler? Or more eye friendly (for those updating code manually)?

Best regards and thanks in advance.

Body:
I don't like the 3 in your explode() and the 2's in your indexes. What is it based on? What if the domain is example.co.uk or www.example.fr? Better use:

$domainExtension = end(explode(".",$_SERVER['HTTP_HOST']));

Then you can do:

switch ($domainExtension) {
  case 'fr' : $language = 'FRE'; break;
  case 'de' : $language = 'GER'; break;
  case 'nl' : $language = 'DUT'; break;
  default   : $language = 'ENG'; break;
}

As you can see the switch () makes the code more readable. I don't abbreviate unnecessarily, for better readability. I also used the official three-letter abbreviation for languages. It's a bit more versatile, but two letters will do, see:

https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes

Personally I don't like numbers for languages, that's why I left them out, although I understand why you used them. You can do:

$texts = ['hello','Bonjour','Guten Tag','Hallo'];

but in that case you cannot leave out any languages. I would forget the numbers and do:

$texts = ['ENG' => 'hello',
          'FRE' => 'Bonjour',
          'GER' => 'Guten Tag',
          'DUT' => 'Hallo'];

Then, when a language is missing, you can replace it by another:

function getText($language,$texts) {
  if (isset($texts[$language]) return $texts[$language];  // it is there
                          else return reset($texts);      // take the first
};

You can then also sort the languages from most commonly used to rarely used. Note that I don't use a global, which is on purpose. Again, you can choose to use one.

Finally, to get back to the simpler list of texts you could use another function:

function setTexts($english,$french,$german,$dutch)
{
  return ['ENG' => $english,
          'FRE' => $french,
          'GER' => $german,
          'DUT' => $dutch];
}

$helloTexts = setTexts('hello','Bonjour','Guten Tag','Hallo');

and then used like this:

echo getText($language,$helloTexts);

But I have to stress that there are many other ways of doing this. You could, for instance, have separate include files for the various languages. That way you don't process any texts that aren't used. It might save a bit of time, but it will be minimal, and it is nice to keep the different translations of the same piece of text together.

One last tip: The broswer can tell you the preferred language of the visitor. See: $_SERVER['HTTP_ACCEPT_LANGUAGE'].


问:
Html Navigation bar item only last item clickable and the rest cannot
My navigation bar cannot click any item except the last item. I have checked and follow the tutorial from youtube but unfortunately I checked code is same but not working at all please anyone got solution please share to me.

Here's My html

```<code><html>
</code>```

```<code><title>UIA | Homepage</title>
<link href="Homepage.css" rel="stylesheet" type="text/css">
</code>```

```<code><header>
<div class="row">
    <div class="logo">
    <img src = "Logo.png">
    </div>

    <ul class="main-nav">
        <li class = "active"><a href="Homepage.html"> Home </a></li>
        <li><a href="Promotion.html"> Promotion </a></li>
        <li><a href=""> Booking </a></li>
        <li><a href=""> SignIn </a></li>
        <li><a href=""> About </a></li>

    </ul>

</div>

<div class="title">
<h1>Ready for another adventure?</h1>
</div>

</header>
</code>```

And here's my CSS.

```<code>*{
margin: 0;
padding: 0;

}

header{
background-image:
linear-gradient(rgba(0,0,0,0.8),rgba(0,0,0,0.8)), url(Homepage.jpg);
height:100vh;
background-position:center;
background-size: cover;

}

.main-nav{
float: right;
list-style: None;
margin-top: 30px;
}

 .main-nav li{

display: inline-block;
}

 .main-nav li a{

color: white;
text-decoration: none;
padding: 5px 20px;
font-family: "Roboto", Sans-serif;
font-size: 15px;
}

 .main-nav li.active a{
border: 1px solid white;
}

.main-nav li a:hover {

border: 1px solid white;
}

.logo img{
width: 150px;
height: auto;
margin-top:10px;
float: left;
}

.row{
max-width: 1200px;
margin: auto;
}

.title{
position:absolute;
width: 1200px;
margin-left: 0;
margin-top: 0;
 }

h1{
color: white;
font-size: 60px;
text-align: center;
margin-top: 255px;

}
</code>```

So did I miss out something please advice me Thank you.

答:
It is because you do not use clearfix on your floated element parent(similar issues will occur on all floated stuff if you don't use clearfix).
Add this to your css file:

```<code>.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
</code>```

And add clearfix to parent of floated element, in this case to:

```<code><div class="row clearfix">
</code>```

I recommend reading these two(will come in handy in the future):
https://css-tricks.com/all-about-floats/
https://css-tricks.com/snippets/css/clear-fix/

Just in case, here is a link to jsfiddle with solution to your issue: https://jsfiddle.net/mwgjycv4/1/

Body:
My navigation bar cannot click any item except the last item. I have checked and follow the tutorial from youtube but unfortunately I checked code is same but not working at all please anyone got solution please share to me.

Here's My html

<title>UIA | Homepage</title>
<link href="Homepage.css" rel="stylesheet" type="text/css">

 Home

 Promotion

 Booking

 SignIn

 About

Ready for another adventure?

And here's my CSS.

*{
margin: 0;
padding: 0;

}

header{
background-image:
linear-gradient(rgba(0,0,0,0.8),rgba(0,0,0,0.8)), url(Homepage.jpg);
height:100vh;
background-position:center;
background-size: cover;

}

.main-nav{
float: right;
list-style: None;
margin-top: 30px;
}

 .main-nav li{

display: inline-block;
}

 .main-nav li a{

color: white;
text-decoration: none;
padding: 5px 20px;
font-family: "Roboto", Sans-serif;
font-size: 15px;
}

 .main-nav li.active a{
border: 1px solid white;
}

.main-nav li a:hover {

border: 1px solid white;
}

.logo img{
width: 150px;
height: auto;
margin-top:10px;
float: left;
}

.row{
max-width: 1200px;
margin: auto;
}

.title{
position:absolute;
width: 1200px;
margin-left: 0;
margin-top: 0;
 }

h1{
color: white;
font-size: 60px;
text-align: center;
margin-top: 255px;

}

So did I miss out something please advice me Thank you.

Body:
It is because you do not use clearfix on your floated element parent(similar issues will occur on all floated stuff if you don't use clearfix).
Add this to your css file:

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

And add clearfix to parent of floated element, in this case to:

<div class="row clearfix">

I recommend reading these two(will come in handy in the future):
https://css-tricks.com/all-about-floats/
https://css-tricks.com/snippets/css/clear-fix/

Just in case, here is a link to jsfiddle with solution to your issue: https://jsfiddle.net/mwgjycv4/1/


问:
explanation of INameOfInterface nameOfVariable = new ExampleClass();
I will appreciate if someone could explain the following C# code

```<code>INameOfInterface nameOfVariable = new ExampleClass();
</code>```

ExampleClass is implementing interface INameOfInterface.
What is this line doing? Thank you all in advance.

答: The line is creating an instance of ExampleClass and assigning it to a variable of type INameOfInterface. </p>

Body:
I will appreciate if someone could explain the following C# code

INameOfInterface nameOfVariable = new ExampleClass();

ExampleClass is implementing interface INameOfInterface.
What is this line doing? Thank you all in advance.


问:
Spark 1.5.2: org.apache.spark.sql.AnalysisException: unresolved operator 'Union;
I have two dataframes df1 and df2. Both of them have the following schema:

```<code> |-- ts: long (nullable = true)
 |-- id: integer (nullable = true)
 |-- managers: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- projects: array (nullable = true)
 |    |-- element: string (containsNull = true)
</code>```

df1 is created from an avro file while df2 from an equivalent parquet file. However, If I execute, df1.unionAll(df2).show(), I get the following error:

```<code>    org.apache.spark.sql.AnalysisException: unresolved operator 'Union;
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$class.failAnalysis(CheckAnalysis.scala:37)
    at org.apache.spark.sql.catalyst.analysis.Analyzer.failAnalysis(Analyzer.scala:44)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:174)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:49)
    at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:103)
</code>```

答:
This is old and there are already some answers lying around but I just faced this problem while trying to make a union of two dataframes like in...

```<code>//Join 2 dataframes
val df = left.unionAll(right)
</code>```

As others have mentioned, order matters. So just select right columns in the same order than left dataframe columns

```<code>//Join 2 dataframes, but take columns in the same order
val df = left.unionAll(right.select(left.columns.map(col):_*))
</code>```

Body:
I have two dataframes df1 and df2. Both of them have the following schema:

 |-- ts: long (nullable = true)
 |-- id: integer (nullable = true)
 |-- managers: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- projects: array (nullable = true)
 |    |-- element: string (containsNull = true)

df1 is created from an avro file while df2 from an equivalent parquet file. However, If I execute, df1.unionAll(df2).show(), I get the following error:

    org.apache.spark.sql.AnalysisException: unresolved operator 'Union;
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$class.failAnalysis(CheckAnalysis.scala:37)
    at org.apache.spark.sql.catalyst.analysis.Analyzer.failAnalysis(Analyzer.scala:44)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:174)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:49)
    at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:103)

Body:
This is old and there are already some answers lying around but I just faced this problem while trying to make a union of two dataframes like in...

//Join 2 dataframes
val df = left.unionAll(right)

As others have mentioned, order matters. So just select right columns in the same order than left dataframe columns

//Join 2 dataframes, but take columns in the same order
val df = left.unionAll(right.select(left.columns.map(col):_*))


Title: Center of each side of a polygon

Body:
Hi I have a polygon with coordintes

[
    [-73.9280684530257, 40.8099975343718],
    [-73.9282820374729, 40.8100875554645],
    [-73.9280124002104, 40.8103130893677],
    [-73.927875543761, 40.8102554080229],
    [-73.9280684530257, 40.8099975343718]
]

How I can find out the center of each side of this polygon using javascript?

Body:
Another solution can be of this form

var vertexArray = [[-73.9280684530257, 40.8099975343718], [-73.9282820374729, 40.8100875554645], [-73.9280124002104, 40.8103130893677], [-73.927875543761, 40.8102554080229], [-73.9280684530257, 40.8099975343718]];

var centerArray = [];
for(i=0;i<vertexArray .length;i++){
   nextIndex = (i+1)%vertexArray.length;
   centerArray[i] = [] ;
   centerArray[i][0] = (vertexArray [i][0] + vertexArray[nextIndex][0])/2;
    centerArray[i][1] = (vertexArray[i][1] + vertexArray[nextIndex][1])/2

}
console.log(centerArray);