问:
How to Update UI slider in unity
I am building a top down shooter in unity, In the game the players health is represented by a UI slider.While moving between scenes I save the health value of the player using the down given code, and use GetFloat to set in next level.The problem i am facing is that when the players is spawned in the next level the UI slider moves to 0 instead of the saved value until some health damage is done to the player after which it is set to the saved value.

Saving Player health

```<code>public void yesTeleport(string levelname)
{
    healthNumber = healthSlider.value;
    SceneManager.LoadScene (levelname);
    PlayerPrefs.SetFloat ("HealthValue", healthNumber);
    PlayerPrefs.Save ();
}
</code>```

Setting Player health in next level

```<code>public Slider healthSlider;

void Start () {

    Time.timeScale = 1.0f;
    healthSlider.value = PlayerPrefs.GetInt ("HealthValue");
}
</code>```

答:
There are two problems in your code:

1.You are saving with SetFloat and loading with GetInt. You should be saving and loading with SetFloat and GetFloat.

2.You are loading new scene before saving the healthNumber value. It should be the other way around. The SceneManager.LoadScene (levelname); code should be put after PlayerPrefs.SetFloat ("HealthValue", healthNumber); and  PlayerPrefs.Save ();

Your code should look like this:

```<code>public void yesTeleport(string levelname)
{
    healthNumber = healthSlider.value;
    PlayerPrefs.SetFloat ("HealthValue", healthNumber);
    PlayerPrefs.Save ();
    SceneManager.LoadScene (levelname);
}

public Slider healthSlider;
void Start () {

    Time.timeScale = 1.0f;
    healthSlider.value = PlayerPrefs.GetFloat ("HealthValue");
}
</code>```

Also make sure to call the yesTeleport function from one of the Unity's callback functions that get's called when scene is unloading. One of them  is the OnDisable function...

```<code>void OnDisable()
{
    yesTeleport (...);
}
</code>```

Please rename the yesTeleport function to something that actually make sense. Maybe that function should be named "saveAndReload" ?

Title: How to Update UI slider in unity

Body:
I am building a top down shooter in unity, In the game the players health is represented by a UI slider.While moving between scenes I save the health value of the player using the down given code, and use GetFloat to set in next level.The problem i am facing is that when the players is spawned in the next level the UI slider moves to 0 instead of the saved value until some health damage is done to the player after which it is set to the saved value.

Saving Player health

public void yesTeleport(string levelname)
{
    healthNumber = healthSlider.value;
    SceneManager.LoadScene (levelname);
    PlayerPrefs.SetFloat ("HealthValue", healthNumber);
    PlayerPrefs.Save ();
}

Setting Player health in next level

public Slider healthSlider;

void Start () {

    Time.timeScale = 1.0f;
    healthSlider.value = PlayerPrefs.GetInt ("HealthValue");
}

Body:
There are two problems in your code:

1.You are saving with SetFloat and loading with GetInt. You should be saving and loading with SetFloat and GetFloat.

2.You are loading new scene before saving the healthNumber value. It should be the other way around. The SceneManager.LoadScene (levelname); code should be put after PlayerPrefs.SetFloat ("HealthValue", healthNumber); and  PlayerPrefs.Save ();

Your code should look like this:

public void yesTeleport(string levelname)
{
    healthNumber = healthSlider.value;
    PlayerPrefs.SetFloat ("HealthValue", healthNumber);
    PlayerPrefs.Save ();
    SceneManager.LoadScene (levelname);
}

public Slider healthSlider;
void Start () {

    Time.timeScale = 1.0f;
    healthSlider.value = PlayerPrefs.GetFloat ("HealthValue");
}

Also make sure to call the yesTeleport function from one of the Unity's callback functions that get's called when scene is unloading. One of them  is the OnDisable function...

void OnDisable()
{
    yesTeleport (...);
}

Please rename the yesTeleport function to something that actually make sense. Maybe that function should be named "saveAndReload" ?


来源: stackexchange

问:
Centered DIV with extra content on one side
I have an inner div centered horizontally within a container div, and I need to add another div within that container, to the right of the centered div? How can I do so without disturbing the position of the centered div (i.e. it should still be centered in the container, not between the left edge of the container and the left edge of the other div?

```<code><div id="container">
    <div id="inner"></div>
    <div id="right"></div>
</div>

div#container {
    width: 960px;
}
div#inner {
    width: 400px;
    margin: 0 auto;
}
div#right {
    width: 100px;
    float: right;
    /* what else? */
}
</code>```

Ideally, I would even want to specify the position of div#right as a distance from the right edge of div#inner, rather than using float:right.

(The only solution I've thought of so far is to add another div on the left with the same width as div#right and set visible:none. Is there a better way?)

答:
Add an extra wrapper for both of them and use that for relative positioning.

```<code><div id="container">
  <div id="center">
    <div id="inner">Some</div>
    <div id="right">content</div>
  </div>
</div>
</code>```

Then use the new centered as relative positioning and "hang" the right one on that. Use a negative margin-right to get it outside.

```<code>div#container {
    width: 960px;
    background: red;
}
div#center {
    width: 400px;
    margin: 0 auto;
    position: relative;
}
div#inner {
    background: blue;
}
div#right {
    width: 100px;
    background: pink;
    position: absolute;
    right: 0;
    top: 0;
    margin-right: -100px;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an inner div centered horizontally within a container div, and I need to add another div within that container, to the right of the centered div? How can I do so without disturbing the position of the centered div (i.e. it should still be centered in the container, not between the left edge of the container and the left edge of the other div?

div#container {
    width: 960px;
}
div#inner {
    width: 400px;
    margin: 0 auto;
}
div#right {
    width: 100px;
    float: right;
    /* what else? */
}

Ideally, I would even want to specify the position of div#right as a distance from the right edge of div#inner, rather than using float:right.

(The only solution I've thought of so far is to add another div on the left with the same width as div#right and set visible:none. Is there a better way?)

Body:
Add an extra wrapper for both of them and use that for relative positioning.

<div id="container">
  <div id="center">
    <div id="inner">Some</div>
    <div id="right">content</div>
  </div>
</div>

Then use the new centered as relative positioning and "hang" the right one on that. Use a negative margin-right to get it outside.

div#container {
    width: 960px;
    background: red;
}
div#center {
    width: 400px;
    margin: 0 auto;
    position: relative;
}
div#inner {
    background: blue;
}
div#right {
    width: 100px;
    background: pink;
    position: absolute;
    right: 0;
    top: 0;
    margin-right: -100px;
}


问:
How to get one week older tweets using tweepy?
I am getting tweets from the user using twitter search api i.e. tweepy. I get tweets of one day but now i want to get one week older tweets. I have tried to get older tweets by this code but i am unable to get old tweets. Any help will be highly appreciated</p>

```<code>for tweet in tweepy.Cursor(api.search,q="#afridi",count=100,\
                       lang="en",\
                       since_id=2016-05-25).items():
print tweet.created_at, tweet.text
</code>```

答:
No other way if you do not know the since_id of the tweet of just one week older tweet. To get older tweets you can let the code run for a while and check the dates of the tweets you are getting. Process those tweets as you want which are 1 week older or so.
Else if you know since_id then put the since_id.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am getting tweets from the user using twitter search api i.e. tweepy. I get tweets of one day but now i want to get one week older tweets. I have tried to get older tweets by this code but i am unable to get old tweets. Any help will be highly appreciated

for tweet in tweepy.Cursor(api.search,q="#afridi",count=100,\
                       lang="en",\
                       since_id=2016-05-25).items():
print tweet.created_at, tweet.text


问:
How to implement the Java comparable interface?
I am not sure how to implement a comparable interface into my abstract class. I have the following example code that I am using to try and get my head around it:

```<code>public class Animal{
    public String name;
    public int yearDiscovered;
    public String population;

    public Animal(String name, int yearDiscovered, String population){
        this.name = name;
        this.yearDiscovered = yearDiscovered;
        this.population = population; }

    public String toString(){
        String s = "Animal name: "+ name+"\nYear Discovered: "+yearDiscovered+"\nPopulation: "+population;
        return s;
    }
}
</code>```

I have a test class that will create objects of type Animal however I want to have a comparable interface inside this class so that older years of discovery rank higher than low. I have no idea on how to go about this though.

答:
Possible alternative from the source code of Integer.compare method which requires API Version 19 is :

public int compareTo(Animal other) {
    return Integer.valueOf(this.year_discovered).compareTo(other.year_discovered);
}

This alternative does not require you to use API version 19.

Body:
I am not sure how to implement a comparable interface into my abstract class. I have the following example code that I am using to try and get my head around it:

public class Animal{
    public String name;
    public int yearDiscovered;
    public String population;

    public Animal(String name, int yearDiscovered, String population){
        this.name = name;
        this.yearDiscovered = yearDiscovered;
        this.population = population; }

    public String toString(){
        String s = "Animal name: "+ name+"\nYear Discovered: "+yearDiscovered+"\nPopulation: "+population;
        return s;
    }
}

I have a test class that will create objects of type Animal however I want to have a comparable interface inside this class so that older years of discovery rank higher than low. I have no idea on how to go about this though.


问:
How to autostart windows service after install by sc?
I created a batch file for installing service because I need to install my service on PC don't have Visual Studio.

Content of batch file:

```<code>@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
echo Installing service complete
pause
</code>```

And I need to autostart MyService after install, so I make this code:

```<code>private void svInstaller_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceController sc = new ServiceController(svInstaller.ServiceName);
    sc.Start();
}
</code>```

Don't any problem if I installing my service by Visual Studio Command Prompt with InstallUtil.
When I install service by batch file, my service didn't autostart.

How to possible to auto start my service after install by batch file?

Update: Thanks Sam Denty's answer, I problem is resolved.

But I have another question: When I install my service by sc, my code in AfterInstall function do not work?

答:
This is possible by using either the net start service or sc start command (see previous question on that).

To start a service  using sc start, the syntax is:

```<code>sc [<ServerName>] start <ServiceName> [<ServiceArguments>]

<ServerName>
    Specifies the name of the remote server on which the service is located. The name must use the Universal Naming Convention (UNC) format (for example, \\myserver). To run SC.exe locally, omit this parameter.
<ServiceName>
    Specifies the service name returned by the getkeyname operation.
<ServiceArguments>
    Specifies the service arguments to pass to the service to be started.
</code>```

Example:

```<code>sc start MyService
</code>```

Updated script:

```<code>@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
sc start MyService
echo Installing service complete
pause
</code>```

Body:
I created a batch file for installing service because I need to install my service on PC don't have Visual Studio.

Content of batch file:

@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
echo Installing service complete
pause

And I need to autostart MyService after install, so I make this code:

private void svInstaller_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceController sc = new ServiceController(svInstaller.ServiceName);
    sc.Start();
}

Don't any problem if I installing my service by Visual Studio Command Prompt with InstallUtil.
When I install service by batch file, my service didn't autostart.

How to possible to auto start my service after install by batch file?

Update: Thanks Sam Denty's answer, I problem is resolved.

But I have another question: When I install my service by sc, my code in AfterInstall function do not work?

Body:
This is possible by using either the net start service or sc start command (see previous question on that).

To start a service  using sc start, the syntax is:

sc [<ServerName>] start <ServiceName> [<ServiceArguments>]

<ServerName>
    Specifies the name of the remote server on which the service is located. The name must use the Universal Naming Convention (UNC) format (for example, \\myserver). To run SC.exe locally, omit this parameter.
<ServiceName>
    Specifies the service name returned by the getkeyname operation.
<ServiceArguments>
    Specifies the service arguments to pass to the service to be started.

Example:

sc start MyService

Updated script:

@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
sc start MyService
echo Installing service complete
pause


问:
Layout animation not working on first run
I have an Activity with a list of items and when you click on an item, I want playback controls for that item to slide up from the bottom of the screen and become visible.  I've defined an animation set for the slide in and the slide out and they work.  I've setup my animationListener in my activity and started my slide in animation onClick of an item.  My problem is, the first time I run the app, when I click on an item, the onClick callback is executed, but the animation doesn't happen.  Second time I click, the slide in animation happens, but not the slide out.  Third and subsequent times, it works as expected.  Here are my animation sets.

vm_slide_in.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
           android:fillAfter="true">
    <translate
        android:fromYDelta="800"
        android:toYDelta="0"
        android:duration="600" />
</set>
</code>```

vm_slide_out.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
           android:fillAfter="true">
    <translate
        android:fromYDelta="0"
        android:toYDelta="800"
        android:duration="600" />
</set>
</code>```

Here is my activity layout

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/AppBG">
    <RelativeLayout
        style="@style/LogoBar"
        android:id="@+id/logo_bar"
        android:layout_alignParentTop="true">
        <include layout="@layout/logobar"></include>
    </RelativeLayout>
    <RelativeLayout
        style="@style/TitleBar"
        android:id="@+id/title_bar"
        android:layout_below="@+id/logo_bar">
        <include layout="@layout/titlebar"></include>"
        <Button style="@style/TitleBarButton"
            android:id="@+id/vm_speaker_btn"
            android:text="@string/vm_speaker_btn_label"
            android:layout_alignParentLeft="true"
            android:layout_margin="4dp">
        </Button>
        <Button style="@style/TitleBarButton"
            android:id="@+id/vm_edit_btn"
            android:text="@string/vm_edit_btn_label"
            android:layout_alignParentRight="true"
            android:layout_margin="4dp">
        </Button>
    </RelativeLayout>
    <ListView
        android:id="@+id/@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title_bar"/>
    <RelativeLayout
        android:id="@+id/vm_control_panel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/footer"
        android:visibility="gone">
        <include layout="@layout/vm_control"/>
    </RelativeLayout>
    <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true">
        <include layout="@layout/taskbar"/>
    </RelativeLayout>
</RelativeLayout>
</code>```

Here is the layout for the included control

```<code>    <?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout
        android:id="@+id/vm_control"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/dark_grey">
        <TextView
            android:id="@+id/vm_ctl_branding"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dp"
            android:text="@string/branding"
            android:textColor="@color/white">
        </TextView>
        <TextView style="@style/TimeMark"
            android:id="@+id/vm_timestamp"
            android:layout_toLeftOf="@+id/vm_progress"
            android:layout_below="@+id/vm_ctl_branding"
            android:layout_marginRight="3dp"
            android:text="0:00">
        </TextView>
        <SeekBar
            android:id="@+id/vm_progress"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/vm_ctl_branding"
            android:layout_centerHorizontal="true">
        </SeekBar>
        <TextView style="@style/TimeMark"
            android:id="@+id/vm_timeleft"
            android:layout_toRightOf="@+id/vm_progress"
            android:layout_below="@+id/vm_ctl_branding"
            android:layout_marginLeft="3dp"
            android:text="-0:00">
        </TextView>
        <LinearLayout
            android:id="@+id/vm_action_button_layout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/vm_timestamp"
            android:layout_alignRight="@+id/vm_timeleft"
            android:orientation="horizontal"
            android:layout_below="@+id/vm_progress">
            <TextView style="@style/Vm_Action_Button"
                android:background="@drawable/vm_action_btn_call"
                android:id="@+id/vm_callback_btn"
                android:layout_marginRight="5dp"
                android:text="@string/vm_action_btn_callback">
            </TextView>
            <TextView style="@style/Vm_Action_Button"
                android:background="@drawable/vm_action_btn_delete"
                android:id="@+id/vm_delete_btn"
                android:layout_marginLeft="5dp"
                android:text="@string/vm_action_btn_delete">
            </TextView>
        </LinearLayout>
    </RelativeLayout>
</merge>
</code>```

From my onCreate method...

```<code>// Handle list item selections
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final Voicemail vmItem = (Voicemail) vmla.getItem(position);
        Toast.makeText(ctx, "Name: " + vmItem.getCallerName() + " Position: " + position, Toast.LENGTH_SHORT)
                .show();
        vVm_controls.startAnimation(mSlideIn);
    }
});
</code>```

And my animation callbacks...

```<code>@Override
public void onAnimationStart(Animation animation) {
    vm_controls_in = !vm_controls_in;
    if (vm_controls_in) {
        vVm_controls.setVisibility(View.GONE);
    } else {
        vVm_controls.setVisibility(View.VISIBLE);
        // vVm_controls.bringToFront();
    }
}

@Override
public void onAnimationEnd(Animation animation) {
    if (!vm_controls_in) {
        try {
            Thread.sleep(1000);
            vVm_controls.startAnimation(mSlideOut);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

@Override
public void onAnimationRepeat(Animation animation) {
    // TODO Auto-generated method stub

}
</code>```

答:
Had the exact same problem even though I was setting the view to visible in animation start. I followed brockoli's advice and set it to visible before starting the animation and it worked like a charm.

BEFORE:

```<code>Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.slide_left);
animation.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {
        view.setVisibility(View.VISIBLE);
    }

    @Override
    public void onAnimationEnd(Animation animation) { }

    @Override
    public void onAnimationRepeat(Animation animation) {       }
);
view.startAnimation(animation);
</code>```

AFTER:

```<code>Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.slide_left);
view.setVisibility(View.VISIBLE);
view.startAnimation(animation);
</code>```

Body:
I have an Activity with a list of items and when you click on an item, I want playback controls for that item to slide up from the bottom of the screen and become visible.  I've defined an animation set for the slide in and the slide out and they work.  I've setup my animationListener in my activity and started my slide in animation onClick of an item.  My problem is, the first time I run the app, when I click on an item, the onClick callback is executed, but the animation doesn't happen.  Second time I click, the slide in animation happens, but not the slide out.  Third and subsequent times, it works as expected.  Here are my animation sets.

vm_slide_in.xml

    <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
           android:fillAfter="true">
    <translate
        android:fromYDelta="800"
        android:toYDelta="0"
        android:duration="600" />
</set>

vm_slide_out.xml

    <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
           android:fillAfter="true">
    <translate
        android:fromYDelta="0"
        android:toYDelta="800"
        android:duration="600" />
</set>

Here is my activity layout

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/AppBG">
    <RelativeLayout
        style="@style/LogoBar"
        android:id="@+id/logo_bar"
        android:layout_alignParentTop="true">
        <include layout="@layout/logobar"></include>
    </RelativeLayout>
    <RelativeLayout
        style="@style/TitleBar"
        android:id="@+id/title_bar"
        android:layout_below="@+id/logo_bar">
        <include layout="@layout/titlebar"></include>"
        <Button style="@style/TitleBarButton"
            android:id="@+id/vm_speaker_btn"
            android:text="@string/vm_speaker_btn_label"
            android:layout_alignParentLeft="true"
            android:layout_margin="4dp">
        </Button>
        <Button style="@style/TitleBarButton"
            android:id="@+id/vm_edit_btn"
            android:text="@string/vm_edit_btn_label"
            android:layout_alignParentRight="true"
            android:layout_margin="4dp">
        </Button>
    </RelativeLayout>
    <ListView
        android:id="@+id/@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title_bar"/>
    <RelativeLayout
        android:id="@+id/vm_control_panel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/footer"
        android:visibility="gone">
        <include layout="@layout/vm_control"/>
    </RelativeLayout>
    <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true">
        <include layout="@layout/taskbar"/>
    </RelativeLayout>
</RelativeLayout>

Here is the layout for the included control

    <?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout
        android:id="@+id/vm_control"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/dark_grey">
        <TextView
            android:id="@+id/vm_ctl_branding"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dp"
            android:text="@string/branding"
            android:textColor="@color/white">
        </TextView>
        <TextView style="@style/TimeMark"
            android:id="@+id/vm_timestamp"
            android:layout_toLeftOf="@+id/vm_progress"
            android:layout_below="@+id/vm_ctl_branding"
            android:layout_marginRight="3dp"
            android:text="0:00">
        </TextView>
        <SeekBar
            android:id="@+id/vm_progress"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/vm_ctl_branding"
            android:layout_centerHorizontal="true">
        </SeekBar>
        <TextView style="@style/TimeMark"
            android:id="@+id/vm_timeleft"
            android:layout_toRightOf="@+id/vm_progress"
            android:layout_below="@+id/vm_ctl_branding"
            android:layout_marginLeft="3dp"
            android:text="-0:00">
        </TextView>
        <LinearLayout
            android:id="@+id/vm_action_button_layout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/vm_timestamp"
            android:layout_alignRight="@+id/vm_timeleft"
            android:orientation="horizontal"
            android:layout_below="@+id/vm_progress">
            <TextView style="@style/Vm_Action_Button"
                android:background="@drawable/vm_action_btn_call"
                android:id="@+id/vm_callback_btn"
                android:layout_marginRight="5dp"
                android:text="@string/vm_action_btn_callback">
            </TextView>
            <TextView style="@style/Vm_Action_Button"
                android:background="@drawable/vm_action_btn_delete"
                android:id="@+id/vm_delete_btn"
                android:layout_marginLeft="5dp"
                android:text="@string/vm_action_btn_delete">
            </TextView>
        </LinearLayout>
    </RelativeLayout>
</merge>

From my onCreate method...

// Handle list item selections
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final Voicemail vmItem = (Voicemail) vmla.getItem(position);
        Toast.makeText(ctx, "Name: " + vmItem.getCallerName() + " Position: " + position, Toast.LENGTH_SHORT)
                .show();
        vVm_controls.startAnimation(mSlideIn);
    }
});

And my animation callbacks...

@Override
public void onAnimationStart(Animation animation) {
    vm_controls_in = !vm_controls_in;
    if (vm_controls_in) {
        vVm_controls.setVisibility(View.GONE);
    } else {
        vVm_controls.setVisibility(View.VISIBLE);
        // vVm_controls.bringToFront();
    }
}

@Override
public void onAnimationEnd(Animation animation) {
    if (!vm_controls_in) {
        try {
            Thread.sleep(1000);
            vVm_controls.startAnimation(mSlideOut);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

@Override
public void onAnimationRepeat(Animation animation) {
    // TODO Auto-generated method stub

}

Body:
Had the exact same problem even though I was setting the view to visible in animation start. I followed brockoli's advice and set it to visible before starting the animation and it worked like a charm.

BEFORE:

Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.slide_left);
animation.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {
        view.setVisibility(View.VISIBLE);
    }

    @Override
    public void onAnimationEnd(Animation animation) { }

    @Override
    public void onAnimationRepeat(Animation animation) {       }
);
view.startAnimation(animation);

AFTER:

Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.slide_left);
view.setVisibility(View.VISIBLE);
view.startAnimation(animation);


问:
Square Connect v1 Item ID Changing Across Locations
I have been writing an Square Connect integration that rests on the fact that an item has one and only one ID, even when it is present in multiple locations. After testing with a subset of products on a separate Square account/App, things were working smoothly. I have now pointed the integration at the "real" Square account/App, using that account's credentials, which contains the same subset of products in addition to many others, and the integration is failing. It seems I have many items that now have a unique ID for each location. This means that a single item has multiple IDs. The item only displays once in the Square dashboard, but there are two unique IDs associated with it. In fact, I have one item that has two IDs, yet those IDs share a single variation ID.

I have also noticed two different formats of IDs, which from my research sounds like a variation due to information created pre- and post- a certain date.

Format 1: XXxXxXXX-xxXX-XxXx-XXX-XXXxxxxxxxXX

Format 2: XXXXXXXXXXXXXXXXXXXXXXXX

I suppose the first question is, is this normal behavior? And if not, any thoughts on what might be causing it and is there a way out of it?

答:
There are some nuances to items with older accounts. Items were originally scoped to a location, which doesn't quite make sense with larger multi-location businesses. Internally we are migrating to a location independent item catalog, which should be invisible to you as an end user (save for the change in formats, like you mentioned) and depending on the date of your account it might have a mix of "old" and "new" item ids. It seems like you have basically a "new" location and an older one. </p>

<p>Basically in our current model you are only guaranteed that items will have unique ids within a location. We are working on new APIs that will allow you to manipulate items across locations more easily.   </p>

Body:
There are some nuances to items with older accounts. Items were originally scoped to a location, which doesn't quite make sense with larger multi-location businesses. Internally we are migrating to a location independent item catalog, which should be invisible to you as an end user (save for the change in formats, like you mentioned) and depending on the date of your account it might have a mix of "old" and "new" item ids. It seems like you have basically a "new" location and an older one.

Basically in our current model you are only guaranteed that items will have unique ids within a location. We are working on new APIs that will allow you to manipulate items across locations more easily.


问:
Script works in IE, not working in FF?
```<code>function AddRow(){
var rowCount = $("td.RowClass").length;
var currentIndex = 0;
if (rowCount > 0)
{
    currentIndex = rowCount--;
}

var markup = '<tr>';
markup += '<td class="RowClass" style="width:250px"><input type="text" id="TomId' + currentIndex + '" maxlength="78" size="70" /></td>';
markup += '<td><input style="width:245px" type="text" id="SerialNumber' + currentIndex + '" maxlength="30" size="25" />&nbsp&nbsp';

if (currentIndex >= 1)
{
    markup += '<a id="removeTom' + currentIndex + '" href="#" onclick="RemoveTomControls(' + currentIndex + ')">Remove</a>';
}

markup += '</td></tr>';
$('#dataTable > tbody').append(markup);
}
</code>```

here's the the html I'm appending to:

```<code><div style="height:340px; overflow:auto;">
            <table id="dataTable" style="margin:0px 1px 10px 5px; margin: width:800px;">
            </table>
       </div>
</code>```

答:
Firefox, unlike IE, won't infer a tbody element unless there is at least one tr in your table.

So $('#dataTable > tbody') matches nothing and your append has no effect.

Title: Script works in IE, not working in FF?

Body:
function AddRow(){
var rowCount = $("td.RowClass").length;
var currentIndex = 0;
if (rowCount > 0)
{
    currentIndex = rowCount--;
}

var markup = '
';
markup += '<input type="text" id="TomId' + currentIndex + '" maxlength="78" size="70" />	';
markup += '<input style="width:245px" type="text" id="SerialNumber' + currentIndex + '" maxlength="30" size="25" />&nbsp&nbsp';

if (currentIndex >= 1)
{
    markup += 'Remove';
}

markup += '
';
$('#dataTable > tbody').append(markup);
}

here's the the html I'm appending to:


问:
phpseclib rsa decryption return false
I'm trying to implement public-private key encryption/decryption for c# server and website. If I encrypt with the public key on PHP I can easily decrypt it using the private key, but when I encrypt the data in C# with the public key I cannot decrypt it with the private key on PHP. Basically, return nothing (or false from var_dump).

C#

var pkey = $"<RSAKeyValue>\r\n\t<Modulus>MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsaxzQmdhvuM+yjJJgpVHUr0DW 3XbAr/sWbSdceanVX7IhccU8XCGurrM7rNYWhyIBzD8/RGGnqupfdt3rsNYvMKMO rU6thBEDBUVYJO58olDgW7ACbd/u95/0uRPzwGeqDQUn565iDfMyU6+jjaoGn7+D 5D0Bt8x6mLiu43y0zQIDAQAB</Modulus>\r\n\t<Exponent>AQAB</Exponent>\r\n</RSAKeyValue>";

//Encrypting the text using the public key
cipher = new RSACryptoServiceProvider();
cipher.FromXmlString(pkey);
byte[] data = Encoding.UTF8.GetBytes(message);
byte[] cipherText = cipher.Encrypt(data, false);
var encrypted = Convert.ToBase64String(cipherText);
Console.WriteLine(encrypted);
```

<p>C# code image</p>

<p>From PHP</p>

<pre class="lang-php prettyprint-override"><code>$rsa = new RSA();
$rsa->loadKey('MIICXQIBAAKBgQCsaxzQmdhvuM+yjJJgpVHUr0DW3XbAr/sWbSdceanVX7IhccU8/nXCGurrM7rNYWhyIBzD8/RGGnqupfdt3rsNYvMKMOrU6thBEDBUVYJO58olDgW7AC/nbd/u95/0uRPzwGeqDQUn565iDfMyU6+jjaoGn7+D5D0Bt8x6mLiu43y0zQIDAQAB/nAoGAXLIRgczUYew4LcQJhlAbGH9IGrxh9eIm2b3BZaQ7PG4AdJ6X7YWSzjk6PyEC/n0IXCMLlAX6FB50SqULy1PtuJql6HAGP5E1YLUxbgct/+JTC3Txy7jLlBRENyf4Nz/nj0oVvR+//vLLNc/MRl4g8gsCOvtTv4QWDkhvPYq0nLNkGHkCQQDkdiGs103RC5pf/n9/SUMq95bIpAS3jDOrjNKrHjTCYPzchExh1Q3qcyJWWCDgUVP4rUwk5NBYyJ/Glb/nRUDeXuQbAkEAwTOag7BbRguTjjcZeyHrbCPEaimpEClzdEWp6CPxGwHYcTWes74K/ncJrhesgy3ZTqVi4lILdNbpUvq1JjvwpJNwJAVplYxnWOb7EgQURyF0LnNPWpqhlx/nmz9FEbAfYfNZciAky7z1G9RqOB3ozlWWI6nEbEWC/LsfvKZLIWes4R3DBQJBAJq3/nOmtu1Qj4yEdA9JTYivDki6wAhLS+nQhlqTSPY8se5Tdzmw2RiEa4oQx0OdecIzS0/na2MRp16A9dWaeupH0G0CQQDii6l2MeVK4ImBqeEjycRQYRhRxLsiEA7ad0ptGvfC/nir/AowGmQ6jTmkMxp+zSFFCHS8ZHAAcBnZ3Ef5kA8SFY');
$convert = base64_decode("CkR7GLQZFUHLcFnhMGxsLYX/4rbrOM+NaXFLyTED3H+xbTChLsXRBQTGo7Xme44b4+/1c7SWahah/FI4gqFx5aDJ1olUmvUR/cto2X7QjBbIBJiFmXRAokbyyBBZ14v8iFqHwunv6Yc+5k/kO/fMK41mJn8xQms+K79CERkCASB7W3dxAFqh06Ksq/Mi9HwW0RakIsbHsdhu3hGQQy4d4h5J");
var_dump($rsa->decrypt($convert));
</code>```

Note: Those keys are not real and they are generated for development purpose

Link to testing environment code

答:
Wrong padding scheme

You have to use the exact same padding scheme for this to work.

The false in cipher.Encrypt(data, false) disables OAEP. So, PKCS#1 v1.5 padding will be used for encryption.

You have to set the following to use the same padding scheme:

```<code>$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
</code>```

Broken keys

Keep in mind that you need to use proper keys for that. You seem to be using keys from here for testing purposes.

If we decode the public key, we get this in Hex:

```<code>modulus = 94 FB 56 CB 7C F9 9C 63 BA AB 17  F7 53 6C 0B 6E 26 5B F8 47 F1 55 73 55 84 1F D1  CA 53 48 D0 8D 7F E7 FD D6 FD BF 3F F1 D2 2D ED  7B F6 CA 2C D1 1C C1 48 41 BB E3 D6 3E 73 AD FE  A5 54 44 6F 41 51 3E 91 B0 24 45 52 7D 02 C8 68  94 2A 8C B8 E6 8F 4A FE 62 40 1E 66 EB 36 DA D4  07 A7 24 AD 82 C5 EF 96 39 D2 75 0D B0 15 47 50  3C 3C C9 0C A6 9A 23 81 4F 58 1C FC A3 39 B3 5C  53 CF 8E 0B 33
exponent = 01 00 01
</code>```

We can use this tool to convert this Hex representation to a Base64 representation. Remember, do not transmit your private key if you want to transform it. Your public key for C# would look like this:

<RSAKeyValue><Modulus>lPtWy3z5nGO6qxf3U2wLbiZb+EfxVXNVhB/RylNI0I1/5/3W/b8/8dIt7Xv2yizRHMFIQbvj1j5zrf6lVERvQVE+kbAkRVJ9AsholCqMuOaPSv5iQB5m6zba1AenJK2Cxe+WOdJ1DbAVR1A8PMkMppojgU9YHPyjObNcU8+OCzM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
```

<p>Now to your private key. PHP supports multiline strings. Use them! You tried to reduce your private key to a single line and because of that, you made a mistake. Newline characters are <code>\n</code> not <code>/n</code>.</p>

<h2>Solution</h2>

<p>C# example:</p>

```var pkey = "<RSAKeyValue><Modulus>lPtWy3z5nGO6qxf3U2wLbiZb+EfxVXNVhB/RylNI0I1/5/3W/b8/8dIt7Xv2yizRHMFIQbvj1j5zrf6lVERvQVE+kbAkRVJ9AsholCqMuOaPSv5iQB5m6zba1AenJK2Cxe+WOdJ1DbAVR1A8PMkMppojgU9YHPyjObNcU8+OCzM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

var cipher = new RSACryptoServiceProvider();
cipher.FromXmlString(pkey);
byte[] data = Encoding.UTF8.GetBytes("some message");
byte[] cipherText = cipher.Encrypt(data, false);
var encrypted = Convert.ToBase64String(cipherText);
Console.WriteLine(encrypted);
```

<p>C# output:</p>

```kRyQsT55mQWmjQ0n1GbXOpaoMvng/BDNWk/0S2G4cqsKD1Fm7ktFdQIvnGlY6kbPXY0unwzGHbBpUGrALOITeyPHCRdsGIGVUc2O0lqI74QROloyoShXwX7TyAwzLJB6yiVSM7SDpy/6wJ5XkHLZRJu9KxmFrIBgOB9+b2x6C4A=```

<p>PHP example:</p>

```use \phpseclib\Crypt\RSA;

$private_key = "-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCU+1bLfPmcY7qrF/dTbAtuJlv4R/FVc1WEH9HKU0jQjX/n/db9vz/x0i3te/bK
LNEcwUhBu+PWPnOt/qVURG9BUT6RsCRFUn0CyGiUKoy45o9K/mJAHmbrNtrUB6ckrYLF75Y50nUN
sBVHUDw8yQymmiOBT1gc/KM5s1xTz44LMwIDAQABAoGAGsiMtAyFu23ac0PdvOuhqm3O/vXAF0Ki
zxwBVURfxM6LfiOOcRPe5RSKGTW+Cl7AQVEmMlsa/LtBhLhQ9LNQ5L/4oTmRhCGiZZEmccAdjKsx
yMeaxkp+ZHvMxMKQNDgYg1CXqrCrpwwUuMUlA26tfxZ3xSFtFyDTaV9mgDQ1IGECQQCkX9Tum7D1
vQTwbhbYnu7eC4eUOaZeGWSEs2csK7U6vfZ3BzUZW/0tPqcSpQqcNxMtY9TiUsNRj1uM6jX3byp7
AkEA6Ab+wvOTNRtES77OAYG9gHGZZ+iXjQJ/6Z7JehN4p41UbDIf9nNUOLUPL9z5V1uOYnl1CWoo
Cw95cdhKXxEAqQJBAIU5Or6tp250ZdVslM27ewSyuY9UblfkIsk/EscFIdzbbDAqwkmsefW6yvTc
mU3lgYCPYlKRG8c19tCuX1ENY5MCQAz37x9YW975Ai01ofAFn2DheJCNOINCI4IcROiU1AaRaKmP
d6fftFJjFFE5iZovXNr2LOt0yn4rxD7vtuBvY9kCQGyty6YCB6qaD7qXPMhLrLbGajAIWd6ETgxv
frK/BJu+buPfDky/g1FhI5R9iMtL1xH0JYLJlaVocU+xSeA9DkY=
-----END RSA PRIVATE KEY-----";

$rsa = new RSA();
var_dump($rsa->loadKey($private_key));
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
$convert = base64_decode("kRyQsT55mQWmjQ0n1GbXOpaoMvng/BDNWk/0S2G4cqsKD1Fm7ktFdQIvnGlY6kbPXY0unwzGHbBpUGrALOITeyPHCRdsGIGVUc2O0lqI74QROloyoShXwX7TyAwzLJB6yiVSM7SDpy/6wJ5XkHLZRJu9KxmFrIBgOB9+b2x6C4A=");
var_dump($rsa->decrypt($convert));
```

<p>PHP output:</p>

```bool(true)
string(12) "some message"```

Title: phpseclib rsa decryption return false

Body:
I'm trying to implement public-private key encryption/decryption for c# server and website. If I encrypt with the public key on PHP I can easily decrypt it using the private key, but when I encrypt the data in C# with the public key I cannot decrypt it with the private key on PHP. Basically, return nothing (or false from var_dump).

C#

var pkey = $"<RSAKeyValue>\r\n\t<Modulus>MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsaxzQmdhvuM+yjJJgpVHUr0DW 3XbAr/sWbSdceanVX7IhccU8XCGurrM7rNYWhyIBzD8/RGGnqupfdt3rsNYvMKMO rU6thBEDBUVYJO58olDgW7ACbd/u95/0uRPzwGeqDQUn565iDfMyU6+jjaoGn7+D 5D0Bt8x6mLiu43y0zQIDAQAB</Modulus>\r\n\t<Exponent>AQAB</Exponent>\r\n</RSAKeyValue>";

//Encrypting the text using the public key
cipher = new RSACryptoServiceProvider();
cipher.FromXmlString(pkey);
byte[] data = Encoding.UTF8.GetBytes(message);
byte[] cipherText = cipher.Encrypt(data, false);
var encrypted = Convert.ToBase64String(cipherText);
Console.WriteLine(encrypted);

C# code image

From PHP

$rsa = new RSA();
$rsa->loadKey('MIICXQIBAAKBgQCsaxzQmdhvuM+yjJJgpVHUr0DW3XbAr/sWbSdceanVX7IhccU8/nXCGurrM7rNYWhyIBzD8/RGGnqupfdt3rsNYvMKMOrU6thBEDBUVYJO58olDgW7AC/nbd/u95/0uRPzwGeqDQUn565iDfMyU6+jjaoGn7+D5D0Bt8x6mLiu43y0zQIDAQAB/nAoGAXLIRgczUYew4LcQJhlAbGH9IGrxh9eIm2b3BZaQ7PG4AdJ6X7YWSzjk6PyEC/n0IXCMLlAX6FB50SqULy1PtuJql6HAGP5E1YLUxbgct/+JTC3Txy7jLlBRENyf4Nz/nj0oVvR+//vLLNc/MRl4g8gsCOvtTv4QWDkhvPYq0nLNkGHkCQQDkdiGs103RC5pf/n9/SUMq95bIpAS3jDOrjNKrHjTCYPzchExh1Q3qcyJWWCDgUVP4rUwk5NBYyJ/Glb/nRUDeXuQbAkEAwTOag7BbRguTjjcZeyHrbCPEaimpEClzdEWp6CPxGwHYcTWes74K/ncJrhesgy3ZTqVi4lILdNbpUvq1JjvwpJNwJAVplYxnWOb7EgQURyF0LnNPWpqhlx/nmz9FEbAfYfNZciAky7z1G9RqOB3ozlWWI6nEbEWC/LsfvKZLIWes4R3DBQJBAJq3/nOmtu1Qj4yEdA9JTYivDki6wAhLS+nQhlqTSPY8se5Tdzmw2RiEa4oQx0OdecIzS0/na2MRp16A9dWaeupH0G0CQQDii6l2MeVK4ImBqeEjycRQYRhRxLsiEA7ad0ptGvfC/nir/AowGmQ6jTmkMxp+zSFFCHS8ZHAAcBnZ3Ef5kA8SFY');
$convert = base64_decode("CkR7GLQZFUHLcFnhMGxsLYX/4rbrOM+NaXFLyTED3H+xbTChLsXRBQTGo7Xme44b4+/1c7SWahah/FI4gqFx5aDJ1olUmvUR/cto2X7QjBbIBJiFmXRAokbyyBBZ14v8iFqHwunv6Yc+5k/kO/fMK41mJn8xQms+K79CERkCASB7W3dxAFqh06Ksq/Mi9HwW0RakIsbHsdhu3hGQQy4d4h5J");
var_dump($rsa->decrypt($convert));

Note: Those keys are not real and they are generated for development purpose

Link to testing environment code

Body:
Wrong padding scheme

You have to use the exact same padding scheme for this to work.

The false in cipher.Encrypt(data, false) disables OAEP. So, PKCS#1 v1.5 padding will be used for encryption.

You have to set the following to use the same padding scheme:

$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);

Broken keys

Keep in mind that you need to use proper keys for that. You seem to be using keys from here for testing purposes.

If we decode the public key, we get this in Hex:

modulus = 94 FB 56 CB 7C F9 9C 63 BA AB 17  F7 53 6C 0B 6E 26 5B F8 47 F1 55 73 55 84 1F D1  CA 53 48 D0 8D 7F E7 FD D6 FD BF 3F F1 D2 2D ED  7B F6 CA 2C D1 1C C1 48 41 BB E3 D6 3E 73 AD FE  A5 54 44 6F 41 51 3E 91 B0 24 45 52 7D 02 C8 68  94 2A 8C B8 E6 8F 4A FE 62 40 1E 66 EB 36 DA D4  07 A7 24 AD 82 C5 EF 96 39 D2 75 0D B0 15 47 50  3C 3C C9 0C A6 9A 23 81 4F 58 1C FC A3 39 B3 5C  53 CF 8E 0B 33
exponent = 01 00 01

We can use this tool to convert this Hex representation to a Base64 representation. Remember, do not transmit your private key if you want to transform it. Your public key for C# would look like this:

<RSAKeyValue><Modulus>lPtWy3z5nGO6qxf3U2wLbiZb+EfxVXNVhB/RylNI0I1/5/3W/b8/8dIt7Xv2yizRHMFIQbvj1j5zrf6lVERvQVE+kbAkRVJ9AsholCqMuOaPSv5iQB5m6zba1AenJK2Cxe+WOdJ1DbAVR1A8PMkMppojgU9YHPyjObNcU8+OCzM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>

Now to your private key. PHP supports multiline strings. Use them! You tried to reduce your private key to a single line and because of that, you made a mistake. Newline characters are \n not /n.

Solution

C# example:

var pkey = "<RSAKeyValue><Modulus>lPtWy3z5nGO6qxf3U2wLbiZb+EfxVXNVhB/RylNI0I1/5/3W/b8/8dIt7Xv2yizRHMFIQbvj1j5zrf6lVERvQVE+kbAkRVJ9AsholCqMuOaPSv5iQB5m6zba1AenJK2Cxe+WOdJ1DbAVR1A8PMkMppojgU9YHPyjObNcU8+OCzM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

var cipher = new RSACryptoServiceProvider();
cipher.FromXmlString(pkey);
byte[] data = Encoding.UTF8.GetBytes("some message");
byte[] cipherText = cipher.Encrypt(data, false);
var encrypted = Convert.ToBase64String(cipherText);
Console.WriteLine(encrypted);

C# output:

kRyQsT55mQWmjQ0n1GbXOpaoMvng/BDNWk/0S2G4cqsKD1Fm7ktFdQIvnGlY6kbPXY0unwzGHbBpUGrALOITeyPHCRdsGIGVUc2O0lqI74QROloyoShXwX7TyAwzLJB6yiVSM7SDpy/6wJ5XkHLZRJu9KxmFrIBgOB9+b2x6C4A=

PHP example:

use \phpseclib\Crypt\RSA;

$private_key = "-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCU+1bLfPmcY7qrF/dTbAtuJlv4R/FVc1WEH9HKU0jQjX/n/db9vz/x0i3te/bK
LNEcwUhBu+PWPnOt/qVURG9BUT6RsCRFUn0CyGiUKoy45o9K/mJAHmbrNtrUB6ckrYLF75Y50nUN
sBVHUDw8yQymmiOBT1gc/KM5s1xTz44LMwIDAQABAoGAGsiMtAyFu23ac0PdvOuhqm3O/vXAF0Ki
zxwBVURfxM6LfiOOcRPe5RSKGTW+Cl7AQVEmMlsa/LtBhLhQ9LNQ5L/4oTmRhCGiZZEmccAdjKsx
yMeaxkp+ZHvMxMKQNDgYg1CXqrCrpwwUuMUlA26tfxZ3xSFtFyDTaV9mgDQ1IGECQQCkX9Tum7D1
vQTwbhbYnu7eC4eUOaZeGWSEs2csK7U6vfZ3BzUZW/0tPqcSpQqcNxMtY9TiUsNRj1uM6jX3byp7
AkEA6Ab+wvOTNRtES77OAYG9gHGZZ+iXjQJ/6Z7JehN4p41UbDIf9nNUOLUPL9z5V1uOYnl1CWoo
Cw95cdhKXxEAqQJBAIU5Or6tp250ZdVslM27ewSyuY9UblfkIsk/EscFIdzbbDAqwkmsefW6yvTc
mU3lgYCPYlKRG8c19tCuX1ENY5MCQAz37x9YW975Ai01ofAFn2DheJCNOINCI4IcROiU1AaRaKmP
d6fftFJjFFE5iZovXNr2LOt0yn4rxD7vtuBvY9kCQGyty6YCB6qaD7qXPMhLrLbGajAIWd6ETgxv
frK/BJu+buPfDky/g1FhI5R9iMtL1xH0JYLJlaVocU+xSeA9DkY=
-----END RSA PRIVATE KEY-----";

$rsa = new RSA();
var_dump($rsa->loadKey($private_key));
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
$convert = base64_decode("kRyQsT55mQWmjQ0n1GbXOpaoMvng/BDNWk/0S2G4cqsKD1Fm7ktFdQIvnGlY6kbPXY0unwzGHbBpUGrALOITeyPHCRdsGIGVUc2O0lqI74QROloyoShXwX7TyAwzLJB6yiVSM7SDpy/6wJ5XkHLZRJu9KxmFrIBgOB9+b2x6C4A=");
var_dump($rsa->decrypt($convert));

PHP output:

bool(true)
string(12) "some message"


问:
dynamycally created element click event inside jquery plugin?
I'm trying to make an autocomplete plugin with jQuery. Currently I did this:     http://jsfiddle.net/2rpn5L29/1/

HTML:

```<code><div class="form-group"><input type="text" class="input" value=""></div>
</code>```

JS:

```<code>(function ( $ ) {
  $.fn.searchPlugin = function( options ) {
    return this.each(function() {
      var $this = $(this), data = options.data, search = $this.val().toLowerCase(), result = [];

      function get(arg) {
        result = [];
        for(var i=0; i<data.length; i++) {
          if(data[i]['name'].toLowerCase().indexOf(arg)!=-1) {
            result.push(data[i]);
          }
          /*
            for(key in data[i]) {
                if(data[i][key].indexOf(search)!=-1) {
                results.push(data[i]);
              }
            }
         */
        }
      }

      function getById(id) {
        return result[id].name;
      }

      function set() {
        if(!$this.next('.autocomplete').length) {
          $this.after('<div class="autocomplete"></div>');
        }else {
          $this.next('.autocomplete').html('');
        }
        for(var i = 0; i < result.length; i++) {
          $this.next('.autocomplete').append('<div class="autocomplete__item" data-id="' + i + '">' + result[i].name + '</div>');
        }
      }

      $this.on('change keyup', function(){
        get( $this.val().toLowerCase() );
        set( result );
      });

      $this.on('blur', function(){
        //$this.next('.autocomplete').html('');
      });

      $('.form-group').on('click', '.autocomplete__item', function(e){
        alert( getById( $(this).data('id') ) );
        $this.val( getById( $(this).data('id') ) );
        $this.next('.autocomplete').html('');
      });
    });
  };
}( jQuery ));
$(function(){
  var data = [{'id': 1,'name': 'USA'},{'id': 2,'name': 'France'},{'id': 3,'name': 'Italy'}];

  $('.input').searchPlugin({
    data: data
  });
});
</code>```

When you type USA inside the input field and than you click on the text which appeared, it should alert the selected text. But it only work on the second click, not on the first. How can I fire the click event on the first click?

This is the code section which sould alert the selected text:

```<code>$('.form-group').on('click', '.autocomplete__item', function(e){
    alert( getById( $(this).data('id') ) );
    $this.val( getById( $(this).data('id') ) );
    $this.next('.autocomplete').html('');
 });
</code>```

答:
Remove change from $this.on('change keyup', function(){.

Since you update the suggestions on keyup, the change isn't really usefull anyway.

When user leaves the input to click on a suggestion, this change handler triggers first and changes the suggested elements (for the same thing, yes...)

Still the click event, which happens after the change event, but before new elements are created by the change... was triggered on the old not present anymore elements, not on the new ones.

;)

Body:
I'm trying to make an autocomplete plugin with jQuery. Currently I did this:     http://jsfiddle.net/2rpn5L29/1/

HTML:

<input type="text" class="input" value="">

JS:

(function ( $ ) {
  $.fn.searchPlugin = function( options ) {
    return this.each(function() {
      var $this = $(this), data = options.data, search = $this.val().toLowerCase(), result = [];

      function get(arg) {
        result = [];
        for(var i=0; i<data.length; i++) {
          if(data[i]['name'].toLowerCase().indexOf(arg)!=-1) {
            result.push(data[i]);
          }
          /*
            for(key in data[i]) {
                if(data[i][key].indexOf(search)!=-1) {
                results.push(data[i]);
              }
            }
         */
        }
      }

      function getById(id) {
        return result[id].name;
      }

      function set() {
        if(!$this.next('.autocomplete').length) {
          $this.after('

');
        }else {
          $this.next('.autocomplete').html('');
        }
        for(var i = 0; i < result.length; i++) {
          $this.next('.autocomplete').append('
' + result[i].name + '
');
        }
      }

      $this.on('change keyup', function(){
        get( $this.val().toLowerCase() );
        set( result );
      });

      $this.on('blur', function(){
        //$this.next('.autocomplete').html('');
      });

      $('.form-group').on('click', '.autocomplete__item', function(e){
        alert( getById( $(this).data('id') ) );
        $this.val( getById( $(this).data('id') ) );
        $this.next('.autocomplete').html('');
      });
    });
  };
}( jQuery ));
$(function(){
  var data = [{'id': 1,'name': 'USA'},{'id': 2,'name': 'France'},{'id': 3,'name': 'Italy'}];

  $('.input').searchPlugin({
    data: data
  });
});

When you type USA inside the input field and than you click on the text which appeared, it should alert the selected text. But it only work on the second click, not on the first. How can I fire the click event on the first click?

This is the code section which sould alert the selected text:

$('.form-group').on('click', '.autocomplete__item', function(e){
    alert( getById( $(this).data('id') ) );
    $this.val( getById( $(this).data('id') ) );
    $this.next('.autocomplete').html('');
 });


问:
SQL server Import and Export Wizard conversion VS Alter Command
Just attempted to import a .xls file into database by using SQL server Import and Export Wizard, for some of the fields in .xls file, there exists whitespace value. Those fields should be either DATE or MONEY type in the target table.

I tried to Edit Mapping for those columns, and it gave the error message saying cannot convert those field value for me because of potential data loss.

Here comes my confusing part, I ignore the data type on Import and Export Wizard level, just leave them as original nvarchar, and try to ALTER COLUMN such as Alter table.. Alter column col1 DATE, and it succeeded.
Why those fields would be converted without any issue (actually those blank values were converted either to 1900/01/01 for DATE column and 0.00 for MONEY column, even the Import and Export Wizard gives me these result, I can accept.) To be precisely of what I am confused is why the ALTER command did not throw the error for potential data loss and could convert blank value to the initial value of other types?

答: Well, I believe nvarchar will accept pretty much anything.  IT is definitely more forgiving than most data types.  Yeah, for sure, excel will take whatever you give it, and let you get away with all kinds of sloppiness.  As you've discovered, when you go from the Excel world into the database world, you need to be much more disciplined in what kinds of data types you use.


问:
JSON adding backslash automatically
I am trying to convert a java object to json using Gson. But when i tried printing it out.I got this JSON

{"user":"{\"email\":\"abc@gmail.com\",\"lastName\":\"Las\",\"name\":\"amy\",\"password\":\"qwe123\",\"phone\":\"8901245244\"}"}

I tried

s.replace("\\"", "\"")
  but neither it helps nor its a good approach.

Further I have gone through various links but answers are ambiguous.

This is my User class toString method

```<code> public class User implements Serializable
{ ...
@Override
public String toString()
{   return "User{" +
            "first_name:" + name+
            ", last_name:" + lastName+
            ", mobile:" + phone+
            ", email:" + email+
            ", password:" + password+
            "}";
}
</code>```

I guess its not even calling this toString method.

and here is how am I converting to JSON

```<code>        User u=new User(name,lastName,email,phone,password);
        Gson userGson=new GsonBuilder().create();
        String jo=userGson.toJson(u);

        JSONObject params=new JSONObject();
        params.put("user",jo);
        Log.e("in register",params.toString());
</code>```

Any help is appreciated.

答:
You've already converted it to a JSON string, then you stick that into a JSON object which automatically escapes the JSON string. Try something like this:</p>

```<code>User u=new User(name,lastName,email,phone,password);
Gson userGson=new GsonBuilder().create();
JSONObject params = new JSONObject();
params.put("user",user);
Log.e("in register", userGson.toJson(params));
</code>```

Title: JSON adding backslash automatically

Body:
I am trying to convert a java object to json using Gson. But when i tried printing it out.I got this JSON

{"user":"{\"email\":\"abc@gmail.com\",\"lastName\":\"Las\",\"name\":\"amy\",\"password\":\"qwe123\",\"phone\":\"8901245244\"}"}

I tried

s.replace("\\"", "\"")
  but neither it helps nor its a good approach.

Further I have gone through various links but answers are ambiguous.

This is my User class toString method

 public class User implements Serializable
{ ...
@Override
public String toString()
{   return "User{" +
            "first_name:" + name+
            ", last_name:" + lastName+
            ", mobile:" + phone+
            ", email:" + email+
            ", password:" + password+
            "}";
}

I guess its not even calling this toString method.

and here is how am I converting to JSON

        User u=new User(name,lastName,email,phone,password);
        Gson userGson=new GsonBuilder().create();
        String jo=userGson.toJson(u);

        JSONObject params=new JSONObject();
        params.put("user",jo);
        Log.e("in register",params.toString());

Any help is appreciated.

Body:
You've already converted it to a JSON string, then you stick that into a JSON object which automatically escapes the JSON string. Try something like this:

User u=new User(name,lastName,email,phone,password);
Gson userGson=new GsonBuilder().create();
JSONObject params = new JSONObject();
params.put("user",user);
Log.e("in register", userGson.toJson(params));


问:
Logic error while creating sentence from position
I created this program that asks to enter a list of position into a file than saves it as a list and also into another file the the user has to enter the list of words every position has. For example if i enter:

```<code>1 2 3 4 5 1 2 3 4 5
</code>```

and

```<code> this is a repeated sentence
</code>```

the outpur should be

```<code>this is a repeated sentence this is a repeated sentence
</code>```

However when i run my code i get the list of position instead

```<code>1 2 3 4 5 1 2 3 4 5
</code>```

here is my code:

```<code>import subprocess
process_position = subprocess.Popen(["notepad","list_of_numbers.txt"])
process_position.wait()
positions = []
with open("list_of_numbers.txt","r") as f:
    positions = f.read().split()

process_words = subprocess.Popen(["notepad","list_of_words.txt"])
process_words.wait()
sentence = ""
with open("list_of_numbers.txt","r") as s:
    sentence= s.read().split()

mapping = {}

for (position, word) in zip(positions, sentence):
    mapping[position] = word

output = [mapping[position] for position in positions]

print(' '.join(output))
</code>```

答:
I think you are confused. The position list, if I understand correctly, is a list of word-positions you want to print, in order. So you don't want to zip it together with the words from sentence.

Instead, simply look up the words in the sentence list using the integer value of the position numbers:

```<code>result = []
for p in map(int, position):
    result.append(sentence[p])

print(' '.join(result))
</code>```

Or, squeezing a little bit:

```<code>print(' '.join([sentence[p] for p in map(int, position)]))
</code>```

Body:
I created this program that asks to enter a list of position into a file than saves it as a list and also into another file the the user has to enter the list of words every position has. For example if i enter:

1 2 3 4 5 1 2 3 4 5

and

 this is a repeated sentence

the outpur should be

this is a repeated sentence this is a repeated sentence

However when i run my code i get the list of position instead

1 2 3 4 5 1 2 3 4 5

here is my code:

import subprocess
process_position = subprocess.Popen(["notepad","list_of_numbers.txt"])
process_position.wait()
positions = []
with open("list_of_numbers.txt","r") as f:
    positions = f.read().split()

process_words = subprocess.Popen(["notepad","list_of_words.txt"])
process_words.wait()
sentence = ""
with open("list_of_numbers.txt","r") as s:
    sentence= s.read().split()

mapping = {}

for (position, word) in zip(positions, sentence):
    mapping[position] = word

output = [mapping[position] for position in positions]

print(' '.join(output))

Body:
I think you are confused. The position list, if I understand correctly, is a list of word-positions you want to print, in order. So you don't want to zip it together with the words from sentence.

Instead, simply look up the words in the sentence list using the integer value of the position numbers:

result = []
for p in map(int, position):
    result.append(sentence[p])

print(' '.join(result))

Or, squeezing a little bit:

print(' '.join([sentence[p] for p in map(int, position)]))


问:
JavaMelody - Monitoring Free Disk Space in JSON or XML
I am using Tomcat and Javamelody and need the "Free Disk Space" of the machine. In the normal web view there is a table row for that, but in XML or JSON output (format=xml) this value is missing ?! Is this is bug?  How can i get the free disk space without modifying my java app ? </p>

答:
Si, the free disk space is in the xml/json.

You can find it in the response of the http requests:

.../monitoring?format=xml&part=jvm
or
.../monitoring?format=json&part=jvm

Or you can just get the last value in the free disk space graph, without other data:

.../monitoring?part=lastValue&graph=Free_disk_space

For reference:

https://github.com/javamelody/javamelody/wiki/ExternalAPI


问:
How to reset password that is generated with md5() and crypt()
I was working on my project and I forget Admin users password. Here is users table:

```<code>CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `password` varchar(32) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

INSERT INTO `users` (`id`, `email`, `password`, `name`) VALUES
(7, 'ikhlassons@gmail.com', '078bbb4bf0f7117fb131ec45f15b5b87', 'Ikhlas Sons'),
(10, 'wali_essa@hotmail.com', '078bbb4bf0f7117fb131ec45f15b5b87', 'essa');
</code>```

Can anyone tell me how reset password in php that is generated with md5() and cryp()

Here's how the password is generated:

```<code>$hash = crypt($entered_password,"");
$hash = md5($hash);
</code>```

答:
This should work:

```<code>$hash = crypt("passpass","");
$hash = md5("passpass");
echo $hash;
</code>```

Or this:

```<code>$hash = crypt("passpass","");
echo $hash;
</code>```

Remember your password is passpass. Copy the code into users.password field in mysql database. And use passpass as password when login.

Body:
I was working on my project and I forget Admin users password. Here is users table:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `password` varchar(32) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

INSERT INTO `users` (`id`, `email`, `password`, `name`) VALUES
(7, 'ikhlassons@gmail.com', '078bbb4bf0f7117fb131ec45f15b5b87', 'Ikhlas Sons'),
(10, 'wali_essa@hotmail.com', '078bbb4bf0f7117fb131ec45f15b5b87', 'essa');

Can anyone tell me how reset password in php that is generated with md5() and cryp()

Here's how the password is generated:

$hash = crypt($entered_password,"");
$hash = md5($hash);

Body:
This should work:

$hash = crypt("passpass","");
$hash = md5("passpass");
echo $hash;

Or this:

$hash = crypt("passpass","");
echo $hash;

Remember your password is passpass. Copy the code into users.password field in mysql database. And use passpass as password when login.


问:
Why does the command, alert($(this).attr("id")); return "undefined"?
Why does the command

```<code>alert($(this).attr("id"));
</code>```

return "undefined"? I'm using it in ASP NET and Internet Explorer 8.

答:
http://api.jquery.com/attr/

If we try to get the value of an attribute that has not been set, the .attr() method returns undefined.

Maybe some informations are missing? ^^

Body:
Why does the command

alert($(this).attr("id"));

return "undefined"? I'm using it in ASP NET and Internet Explorer 8.


问:
dynamically create element with onclick
I'm obviously missing something, but I haven't been able to find what I am doing wrong and I have been staring at this for entirely too long

```<code>function message(options) {
  ...
  options.onclose = options.onclose || null;
  ...
  this.gui = document.createElement('div');
  this.msg = document.createElement('div');
  ...
  if (options.onclose != null) {
    var close = document.createElement('i');
    close.innerHTML = 'close';
    close.className = 'material-icons close';
    close.onclick = options.onclose;
    console.log(close.onclick);
    this.msg.append(close);
  }

  this.msg.innerHTML += options.msg;
  this.gui.append(this.msg);
  ...
  return this.gui;
}

msgContainer.append(new message({
    class: 'update',
    sticky: true,
    icon: 'mic',
    msg: 'You are in a call',
    onclose: () => { console.log('click'); }
  }));
</code>```

from the developer console document.querySelector('.close').onclick is null, but if I add an on click document.querySelector('.close').onclick = () => { console.log('click'); }; it works?

答:
Why it wont work is because on click is a function:

```<code>document.querySelector('.close').onclick
</code>```

doesn't do anything so why call it.

```<code>document.querySelector('.close').onclick = () {
     alert("did something");
}
</code>```

so the real question is what do you want to do when clicked? create a new link or div.. look below. I would start using jQuery.

jQuery answer:

```<code>$(document).ready(function(){
     $(".myclass").click(function(){
          $(".container_div").append("<a href='test.php'>test link</a>");
          // also .prepend, .html are good too
     });

});
</code>```

Title: dynamically create element with onclick

Body:
I'm obviously missing something, but I haven't been able to find what I am doing wrong and I have been staring at this for entirely too long

function message(options) {
  ...
  options.onclose = options.onclose || null;
  ...
  this.gui = document.createElement('div');
  this.msg = document.createElement('div');
  ...
  if (options.onclose != null) {
    var close = document.createElement('i');
    close.innerHTML = 'close';
    close.className = 'material-icons close';
    close.onclick = options.onclose;
    console.log(close.onclick);
    this.msg.append(close);
  }

  this.msg.innerHTML += options.msg;
  this.gui.append(this.msg);
  ...
  return this.gui;
}

msgContainer.append(new message({
    class: 'update',
    sticky: true,
    icon: 'mic',
    msg: 'You are in a call',
    onclose: () => { console.log('click'); }
  }));

from the developer console document.querySelector('.close').onclick is null, but if I add an on click document.querySelector('.close').onclick = () => { console.log('click'); }; it works?

Body:
Why it wont work is because on click is a function:

document.querySelector('.close').onclick

doesn't do anything so why call it.

document.querySelector('.close').onclick = () {
     alert("did something");
}

so the real question is what do you want to do when clicked? create a new link or div.. look below. I would start using jQuery.

jQuery answer:

$(document).ready(function(){
     $(".myclass").click(function(){
          $(".container_div").append("<a href='test.php'>test link</a>");
          // also .prepend, .html are good too
     });

});


问:
C# WPF MVVM TabItem HeaderTemplate won't work?
I am currently working on an application with a TabControl, and every tab has a ViewModel which inherits from ITabViewModel, which has two properties: HeaderText and HeaderImage. I would like these to be set from each ViewModel. Thus, I attempted to use a HeaderTemplate style, but this did not work. Could anyone tell me how I could get this to work?

```<code><TabControl>
    <TabControl.Resources>
        <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding HeaderImage}" Height="20" Margin="5, 0"/>
                            <TextBlock Text="{Binding HeaderText}"/>
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.Resources>

    <TabItem DataContext="{Binding ViewModelStart}">

    </TabItem>

    <TabItem DataContext="{Binding ViewModelStartupManager}">

    </TabItem>
</TabControl>
</code>```

答:
I think there are at least two options for you.

first(I assume that ViewModelStart and ViewModelStartupManager are properties):

```<code> <TabItem Header="{Binding ViewModelStart}">
 <TabItem Header="{Binding ViewModelStartupManager}">
</code>```

second, use ItemsSource and define your tabs in some collection in ViewModel.

ViewModel:

```<code>public ObservableCollection<ITabViewModel> Tabs{ get; set; }
</code>```

XAML, remove yourTabItem's and add them to property above. Also add following attribute to TabControl:

```<code>ItemsSource="{Binding Tabs}"
</code>```

Body:
I am currently working on an application with a TabControl, and every tab has a ViewModel which inherits from ITabViewModel, which has two properties: HeaderText and HeaderImage. I would like these to be set from each ViewModel. Thus, I attempted to use a HeaderTemplate style, but this did not work. Could anyone tell me how I could get this to work?

<TabControl>
    <TabControl.Resources>

    </TabControl.Resources>

    <TabItem DataContext="{Binding ViewModelStart}">

    </TabItem>

    <TabItem DataContext="{Binding ViewModelStartupManager}">

    </TabItem>
</TabControl>

Body:
I think there are at least two options for you.

first(I assume that ViewModelStart and ViewModelStartupManager are properties):

 <TabItem Header="{Binding ViewModelStart}">
 <TabItem Header="{Binding ViewModelStartupManager}">

second, use ItemsSource and define your tabs in some collection in ViewModel.

ViewModel:

public ObservableCollection<ITabViewModel> Tabs{ get; set; }

XAML, remove yourTabItem's and add them to property above. Also add following attribute to TabControl:

ItemsSource="{Binding Tabs}"


问:
How to save a video to a URL in Swift Playgrounds
I'm trying to instantiate a PHLivePhoto but whenever I try to save the video that constitutes the live photo I can't get it to work.

Here's a little code snippet I wrote that handles exporting the video:

```<code>public func exportFilteredVideo(to outputURL: URL, completion: @escaping (Void) -> Void) {
    if FileManager.default.fileExists(atPath: outputURL.path) {
        try? FileManager.default.removeItem(at: outputURL)
    }

    let export = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality)!
    export.outputFileType = AVFileTypeQuickTimeMovie
    export.outputURL = outputURL
    export.videoComposition = generateComposition()
    export.exportAsynchronously(completionHandler: completion)
}
</code>```

This is when I try to retrieve the video:

```<code>let destURL = url.deletingLastPathComponent().appendingPathComponent("Test.mov")
pixellationFilter.exportFilteredVideo(to: destURL) {
     print(try! destURL.checkResourceIsReachable()) //An error is thrown! Why though, isn't the export completed?
}
</code>```

Currently, my suspicions are you might not be able to write to the URL specified. However, my understanding is that whenever I want to create a PHLivePhoto object I need to specify the resources as URL instead of Data. If this is possible, I would be able to instead use the data instead of exporting it to a URL. I could be wrong, but I'm not really finding a way to create a PHLivePhoto with Data. There is a PHAssetResource class but that only helps to get the data files of the PHLivePhoto not to create a PHLivePhoto.

So my possible solutions I believe at this moment are:

Figure out how I can save the video as a URL.

Try and create a live photo through Data instead of URL.

答: The fileURL it is just where the data is located. Just write the data to a temporary folder and pass that file url to the method.  </p>

Body:
I'm trying to instantiate a PHLivePhoto but whenever I try to save the video that constitutes the live photo I can't get it to work.

Here's a little code snippet I wrote that handles exporting the video:

public func exportFilteredVideo(to outputURL: URL, completion: @escaping (Void) -> Void) {
    if FileManager.default.fileExists(atPath: outputURL.path) {
        try? FileManager.default.removeItem(at: outputURL)
    }

    let export = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality)!
    export.outputFileType = AVFileTypeQuickTimeMovie
    export.outputURL = outputURL
    export.videoComposition = generateComposition()
    export.exportAsynchronously(completionHandler: completion)
}

This is when I try to retrieve the video:

let destURL = url.deletingLastPathComponent().appendingPathComponent("Test.mov")
pixellationFilter.exportFilteredVideo(to: destURL) {
     print(try! destURL.checkResourceIsReachable()) //An error is thrown! Why though, isn't the export completed?
}

Currently, my suspicions are you might not be able to write to the URL specified. However, my understanding is that whenever I want to create a PHLivePhoto object I need to specify the resources as URL instead of Data. If this is possible, I would be able to instead use the data instead of exporting it to a URL. I could be wrong, but I'm not really finding a way to create a PHLivePhoto with Data. There is a PHAssetResource class but that only helps to get the data files of the PHLivePhoto not to create a PHLivePhoto.

So my possible solutions I believe at this moment are:

Figure out how I can save the video as a URL.

Try and create a live photo through Data instead of URL.


问:
What to do with ENUM values in Mongoose?

Background

I have a Mongoose schema that defines a set of possible values a given object can have.

```<code>const mongoose = require("mongoose");

const COUNTRIES = ["ES", "PT", "US", "FR", "UK"];
const GENDERS = ["M", "F"];

const surveySchema = {
    subject: { type: String, required: true },
    country: { type: String, enum: COUNTRIES },
    target: {
        gender: { type: String, enum: GENDERS }
    }
};

module.exports = new mongoose.Schema(surveySchema);;
module.exports.modSchema = surveySchema;
</code>```

Why I don't like ENUM

I don't personally like ENUM values because if I add another value to the ENUM, I have to recompile the entire application again and deploy.

I guess that with an ENUM such as gender, that will never change, this is not a problem.

However, with countries, my SQL side tells me I should store them because if you have a growing business, you are likely to expand to other countries.

Problem

My problem here is that I don't know how to tell Mongoose, at a schema level, that the only allowed values for the countries have to be ["ES", "PT", "US", "FR", "UK"].

I guess I could create a collection countries, but then I lack the knowledge on how I would connect them. Would I have to use async validators?

How would you deal with an ENUM that can change?

答:
You can use admin panel to add more country to the country collection. As you are saying that COUNTRIES array can grow, you can use another collection to add more countries on demand from admin panel.

And when you are going to add/save a new record into the survey you can trigger a pre-save hook to mongo for validation.

suppose we have another schema for countries like this.

```<code>{
 countries: [String]
}
</code>```

Here is a sample code for the scenario.

```<code>const mongoose = require("mongoose");

const GENDERS = ["M", "F"];

const surveySchema = {
    subject: { type: String, required: true },
    country: { type: String},
    target: {
        gender: { type: String, enum: GENDERS }
    }
};

var Survey = new mongoose.Schema(surveySchema);

Survey.pre('save',function(next){
  var me = this;
  CountryModel.find({},(err,docs)=>{
    (docs.countries.indexOf(me.country) >=0) ? next() : next(new Error('validation failed'));
  });
});
</code>```

This way you can handle dynamic country add without changing the country array and redeploying your whole server.

USING CUSTOM VALIDATOR

```<code>const mongoose = require("mongoose");

const GENDERS = ["M", "F"];

const surveySchema = {
        subject: {
            type: String,
            required: true
        },
        country: {
            type: String,
            validate: {
                isAsync: true,
                validator: function(arg, cb) {
                    CountryModel.find({}, (err, docs) => {
                                if (err) {
                                    cb(err);
                                } else {
                                    cb(docs.countries.indexOf(arg) >= 0);
                                }
                            }
                        },
                        message: '{VALUE} is not a valid country'
                }
            },
            target: {
                gender: { type: String, enum: GENDERS }
            }
        };
</code>```

you will get an error while saving the survey data in the callback ..

```<code>ServeyModel.save((err,doc)=>{
if(err){
console.log(err.errors.country.message);
//Error handle
}else {
//TODO
}
});
</code>```

Body:
Background

I have a Mongoose schema that defines a set of possible values a given object can have.

const mongoose = require("mongoose");

const COUNTRIES = ["ES", "PT", "US", "FR", "UK"];
const GENDERS = ["M", "F"];

const surveySchema = {
    subject: { type: String, required: true },
    country: { type: String, enum: COUNTRIES },
    target: {
        gender: { type: String, enum: GENDERS }
    }
};

module.exports = new mongoose.Schema(surveySchema);;
module.exports.modSchema = surveySchema;

Why I don't like ENUM

I don't personally like ENUM values because if I add another value to the ENUM, I have to recompile the entire application again and deploy.

I guess that with an ENUM such as gender, that will never change, this is not a problem.

However, with countries, my SQL side tells me I should store them because if you have a growing business, you are likely to expand to other countries.

Problem

My problem here is that I don't know how to tell Mongoose, at a schema level, that the only allowed values for the countries have to be ["ES", "PT", "US", "FR", "UK"].

I guess I could create a collection countries, but then I lack the knowledge on how I would connect them. Would I have to use async validators?

How would you deal with an ENUM that can change?

Body:
You can use admin panel to add more country to the country collection. As you are saying that COUNTRIES array can grow, you can use another collection to add more countries on demand from admin panel.

And when you are going to add/save a new record into the survey you can trigger a pre-save hook to mongo for validation.

suppose we have another schema for countries like this.

{
 countries: [String]
}

Here is a sample code for the scenario.

const mongoose = require("mongoose");

const GENDERS = ["M", "F"];

const surveySchema = {
    subject: { type: String, required: true },
    country: { type: String},
    target: {
        gender: { type: String, enum: GENDERS }
    }
};

var Survey = new mongoose.Schema(surveySchema);

Survey.pre('save',function(next){
  var me = this;
  CountryModel.find({},(err,docs)=>{
    (docs.countries.indexOf(me.country) >=0) ? next() : next(new Error('validation failed'));
  });
});

This way you can handle dynamic country add without changing the country array and redeploying your whole server.

USING CUSTOM VALIDATOR

const mongoose = require("mongoose");

const GENDERS = ["M", "F"];

const surveySchema = {
        subject: {
            type: String,
            required: true
        },
        country: {
            type: String,
            validate: {
                isAsync: true,
                validator: function(arg, cb) {
                    CountryModel.find({}, (err, docs) => {
                                if (err) {
                                    cb(err);
                                } else {
                                    cb(docs.countries.indexOf(arg) >= 0);
                                }
                            }
                        },
                        message: '{VALUE} is not a valid country'
                }
            },
            target: {
                gender: { type: String, enum: GENDERS }
            }
        };

you will get an error while saving the survey data in the callback ..

ServeyModel.save((err,doc)=>{
if(err){
console.log(err.errors.country.message);
//Error handle
}else {
//TODO
}
});


问:
Efficient way to check if individual arrays inside a 2-d array have equal lengths
Let's say we have a 2D array

int[][] arr = new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7 }, { 8, 9 } };

Here, arr[1] has a length of 3.

Is there any efficient way to check if all the 1-d arrays present within the 2-d array have equal lengths?

Say, without looping through the array or may be through using any data structure which can be preferred instead of a int[][]?

答:
Given you do not do some bookkeeping at construction time, etc. you cannot avoid turning this into an O(n) algorithm with n the number of rows. For instance:

```<code>public static boolean sameLengths(int[][] matrix) {
    if(matrix == null) {
        return false;
    }
    if(matrix.length > 0) {
        if(matrix[0] == null) {
            return false;
        }
        int n = matrix[0].length;
        for(int[] row : matrix) {
            if(row == null || row.length != n) {
                return false;
            }
        }
    }
    return true;
}
</code>```

The edge-cases are what to do with null values and what with a matrix with no rows. Here I decided that:

a null matrix returns false;

a matrix with a row equal to null returns false as well; and

a matrix with no rows, returns true (since in that case all rows have the same length).

It is easy to alter the implementation if you to handle these edge-cases differently.

Body:
Given you do not do some bookkeeping at construction time, etc. you cannot avoid turning this into an O(n) algorithm with n the number of rows. For instance:

public static boolean sameLengths(int[][] matrix) {
    if(matrix == null) {
        return false;
    }
    if(matrix.length > 0) {
        if(matrix[0] == null) {
            return false;
        }
        int n = matrix[0].length;
        for(int[] row : matrix) {
            if(row == null || row.length != n) {
                return false;
            }
        }
    }
    return true;
}

The edge-cases are what to do with null values and what with a matrix with no rows. Here I decided that:

a null matrix returns false;

a matrix with a row equal to null returns false as well; and

a matrix with no rows, returns true (since in that case all rows have the same length).

It is easy to alter the implementation if you to handle these edge-cases differently.


问:
React Photoswipe using removed babel 5 option
I am just starting to dabble in react and one of the first components I want is something to use photoswipe.js. (react photoswipe)  It looks like there is a pretty decent one on npm, but I am running into a problem.  When I run my storybook to start testing and building my component, I get an error from babel.  It says:

```<code>in ./~/react-photoswipe/lib/index.js
Module build failed: ReferenceError: [BABEL] C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\lib\index.js: Using removed Babel 5 option: C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\.babelrc.stage - Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets
    at Logger.error (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\logger.js:41:11)
    at OptionManager.mergeOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:220:20)
    at OptionManager.init (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
    at File.initOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:212:65)
    at new File (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:135:24)
    at Pipeline.transform (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
    at transpile (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\index.js:46:20)
    at C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:79:18
    at ReadFileContext.callback (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:15:14)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13)
</code>```

So I did a bit of poking around and noticed that the babel rc file appears to be set to stage:0 which from my understanding seems like a really bad idea if you are producing a component that is supposed to be durable as the javascript spec updates and evolves.

I am still pretty new to using babel though so I am kind of having a hard time tracking down what I would need to update for this component to get it working in my environment with the newer babel.  Has anyone encountered this problem with this component before?  Does anyone have any advice or tips on how to troubleshoot the bable transpile and track down what I need to update?

答:
The .babelrc from react-photoswipe does not work with babel 6. But it doesn't need to, because main entry point of the module is lib/index.js, which contains the already transpiled code. You're trying to transpile it again, and it automatically applies the .babelrc closest to it.

You should exclude node_modules in your webpack config, for example:

```<code>{
  test: /\.js$/,
  loader: 'babel-loader',
  exclude: /node_modules/
}
</code>```

It will not only fix your issue, but also reduce the build time.

Body:
I am just starting to dabble in react and one of the first components I want is something to use photoswipe.js. (react photoswipe)  It looks like there is a pretty decent one on npm, but I am running into a problem.  When I run my storybook to start testing and building my component, I get an error from babel.  It says:

in ./~/react-photoswipe/lib/index.js
Module build failed: ReferenceError: [BABEL] C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\lib\index.js: Using removed Babel 5 option: C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\.babelrc.stage - Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets
    at Logger.error (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\logger.js:41:11)
    at OptionManager.mergeOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:220:20)
    at OptionManager.init (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
    at File.initOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:212:65)
    at new File (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:135:24)
    at Pipeline.transform (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
    at transpile (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\index.js:46:20)
    at C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:79:18
    at ReadFileContext.callback (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:15:14)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13)

So I did a bit of poking around and noticed that the babel rc file appears to be set to stage:0 which from my understanding seems like a really bad idea if you are producing a component that is supposed to be durable as the javascript spec updates and evolves.

I am still pretty new to using babel though so I am kind of having a hard time tracking down what I would need to update for this component to get it working in my environment with the newer babel.  Has anyone encountered this problem with this component before?  Does anyone have any advice or tips on how to troubleshoot the bable transpile and track down what I need to update?

Body:
The .babelrc from react-photoswipe does not work with babel 6. But it doesn't need to, because main entry point of the module is lib/index.js, which contains the already transpiled code. You're trying to transpile it again, and it automatically applies the .babelrc closest to it.

You should exclude node_modules in your webpack config, for example:

{
  test: /\.js$/,
  loader: 'babel-loader',
  exclude: /node_modules/
}

It will not only fix your issue, but also reduce the build time.


问:
Moving laravel 5.4 from localhost to server issue: uses localhost paths
I moved files and folders frm public directory to the root of my laravel project, uploaded to a sub directory on my hosting so it looks like this www.example.com/social. In .env file

```<code>APP_ENV=local
APP_URL=http://www.example.com/social/
</code>```

In index.php

```<code>require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
</code>```

When I try th view the project I get this error

```<code>InvalidArgumentException in FileViewFinder.php line 137:
View [welcome] not found.
in FileViewFinder.php line 137
at FileViewFinder->findInPaths('welcome', array('D:\\xampp\\htdocs\\social\\resources\\views')) in FileViewFinder.php line 79
</code>```

So hot to fix this issue to make it work as it should? It's first time Moving a laravel project to the server so no experience.

答:
Try to run this commands on the server laravel directory:</p>

```<code>php artisan cache:clear
php artisan config:clear
php artisan view:clear
</code>```

Body:
I moved files and folders frm public directory to the root of my laravel project, uploaded to a sub directory on my hosting so it looks like this www.example.com/social. In .env file

APP_ENV=local
APP_URL=http://www.example.com/social/

In index.php

require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';

When I try th view the project I get this error

InvalidArgumentException in FileViewFinder.php line 137:
View [welcome] not found.
in FileViewFinder.php line 137
at FileViewFinder->findInPaths('welcome', array('D:\\xampp\\htdocs\\social\\resources\\views')) in FileViewFinder.php line 79

So hot to fix this issue to make it work as it should? It's first time Moving a laravel project to the server so no experience.

Body:
Try to run this commands on the server laravel directory:

php artisan cache:clear
php artisan config:clear
php artisan view:clear


答:
params.toString() is a string representation of the JSON, not a User object.

I tried  s.replace("\"", "\"")

You didn't need to do that... Java is showing the string with escape characters. If you see the escape characters, then you've converted an existing JSON string into another JSON object, and string-ed it again.

```<code>String jo=userGson.toJson(u);
</code>```

Why are you not logging this instead?

I guess its not even calling this toString method

Well, you never printed a User object

Title: JSON adding backslash automatically

Body:
I am trying to convert a java object to json using Gson. But when i tried printing it out.I got this JSON

{"user":"{\"email\":\"abc@gmail.com\",\"lastName\":\"Las\",\"name\":\"amy\",\"password\":\"qwe123\",\"phone\":\"8901245244\"}"}

I tried

s.replace("\\"", "\"")
  but neither it helps nor its a good approach.

Further I have gone through various links but answers are ambiguous.

This is my User class toString method

 public class User implements Serializable
{ ...
@Override
public String toString()
{   return "User{" +
            "first_name:" + name+
            ", last_name:" + lastName+
            ", mobile:" + phone+
            ", email:" + email+
            ", password:" + password+
            "}";
}

I guess its not even calling this toString method.

and here is how am I converting to JSON

        User u=new User(name,lastName,email,phone,password);
        Gson userGson=new GsonBuilder().create();
        String jo=userGson.toJson(u);

        JSONObject params=new JSONObject();
        params.put("user",jo);
        Log.e("in register",params.toString());

Any help is appreciated.

Body:
params.toString() is a string representation of the JSON, not a User object.

I tried  s.replace("\"", "\"")

You didn't need to do that... Java is showing the string with escape characters. If you see the escape characters, then you've converted an existing JSON string into another JSON object, and string-ed it again.

String jo=userGson.toJson(u);

Why are you not logging this instead?

I guess its not even calling this toString method

Well, you never printed a User object


答:
You need an extra column named, for example, password_reset_token. When a user wants to recover his password, your app must generate a (long enough) random string and store it in than password_reset_token field.

Then you create a script that receives that token by $_GET (i.e.: example.com/password-reset/?token=982dh89h2w9h92hd), check if it exists in the Users table and, if correct, promtps a form to reset the password for that user.

You have to email that link (example.com/password-reset/?token=982dh89h2w9h92hd) to the user, telling him to click on it to reset his password.

Title: How to reset password that is generated with md5() and crypt()

Body:
I was working on my project and I forget Admin users password. Here is users table:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `password` varchar(32) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

INSERT INTO `users` (`id`, `email`, `password`, `name`) VALUES
(7, 'ikhlassons@gmail.com', '078bbb4bf0f7117fb131ec45f15b5b87', 'Ikhlas Sons'),
(10, 'wali_essa@hotmail.com', '078bbb4bf0f7117fb131ec45f15b5b87', 'essa');

Can anyone tell me how reset password in php that is generated with md5() and cryp()

Here's how the password is generated:

$hash = crypt($entered_password,"");
$hash = md5($hash);


问:
Java QueryDSL 3.6.0 Projection.bean(Person.class, person.firstName, person.count())
I am using QueryDSL in my project to return a list of Person groupBy LastName and no of persons with that lastName. Below is the Person.java

```<code>@Entity
class Person {
     private String firstName;
     private String lastName;
     private boolean isCitizen;
     private int age;
     private int groupByCount; //Property to return groupByCount - could use Group tuple for this, but doing a research trying to set it as an object field.

     //Constructors to support n! ways of object creation - where n is no of fields in the object
     public Person(String lastName, int groupByCount){
       this.lastName = lastName;
       this.groupByCount = groupByCount;
     }

     public Person(int age, int groupByCount){
       this.age = age;
       this.groupByCount = groupByCount;
     }

     public Person(boolean isCitizen, int groupByCount){
       this.isCitizen = isCitizen;
       this.groupByCount = groupByCount;
     }

     // keeps going to cover all possible constructors - i want to avoid this for maintainability reasons - want to be able to build objects dynamically with different parameters

     //Below is code for Getter and setters for above fields
}
</code>```

The QueryDSL query which uses these Constructors are below.

```<code>personRepo.getQueryDSL().createQuery(person).groupBy(person.lastName)
.list(Projections.constructor(Alarm.class, person.lastName, person.count());

personRepo.getQueryDSL().createQuery(person).groupBy(person.age)
.list(Projections.constructor(Alarm.class, person.age, person.count());

personRepo.getQueryDSL().createQuery(person).groupBy(person.isCitizen)
.list(Projections.constructor(Alarm.class, person.isCitizen, person.count());
</code>```

How to avoid writing those n! constructors for a class with n fields using QueryDSL ?? I tried Projections.bean like below, after removing the constructors in the Person class

```<code>personRepo.getQueryDSL().createQuery(person).groupBy(person.isCitizen)
.list(Projections.bean(Alarm.class, person.isCitizen, person.count());
</code>```

It complains .count() is not a valid expression. It is notable to assign the value of count to groupByCount field in person object. How to set groupByCount of the person object with person.count() value using Projections.bean method ??

Thanks in Advance. Really appreciate your help.

答: I believe that Projections.fields is what you're looking for. Have the setter names in the POJO mirror the column names in the query - it looks like you already have this in place.

Body:
I am using QueryDSL in my project to return a list of Person groupBy LastName and no of persons with that lastName. Below is the Person.java

@Entity
class Person {
     private String firstName;
     private String lastName;
     private boolean isCitizen;
     private int age;
     private int groupByCount; //Property to return groupByCount - could use Group tuple for this, but doing a research trying to set it as an object field.

     //Constructors to support n! ways of object creation - where n is no of fields in the object
     public Person(String lastName, int groupByCount){
       this.lastName = lastName;
       this.groupByCount = groupByCount;
     }

     public Person(int age, int groupByCount){
       this.age = age;
       this.groupByCount = groupByCount;
     }

     public Person(boolean isCitizen, int groupByCount){
       this.isCitizen = isCitizen;
       this.groupByCount = groupByCount;
     }

     // keeps going to cover all possible constructors - i want to avoid this for maintainability reasons - want to be able to build objects dynamically with different parameters

     //Below is code for Getter and setters for above fields
}

The QueryDSL query which uses these Constructors are below.

personRepo.getQueryDSL().createQuery(person).groupBy(person.lastName)
.list(Projections.constructor(Alarm.class, person.lastName, person.count());

personRepo.getQueryDSL().createQuery(person).groupBy(person.age)
.list(Projections.constructor(Alarm.class, person.age, person.count());

personRepo.getQueryDSL().createQuery(person).groupBy(person.isCitizen)
.list(Projections.constructor(Alarm.class, person.isCitizen, person.count());

How to avoid writing those n! constructors for a class with n fields using QueryDSL ?? I tried Projections.bean like below, after removing the constructors in the Person class

personRepo.getQueryDSL().createQuery(person).groupBy(person.isCitizen)
.list(Projections.bean(Alarm.class, person.isCitizen, person.count());

It complains .count() is not a valid expression. It is notable to assign the value of count to groupByCount field in person object. How to set groupByCount of the person object with person.count() value using Projections.bean method ??

Thanks in Advance. Really appreciate your help.