问:
Android studio registration button isnt responsing a volley request
i m trying to make registration script in android studio with volley library and PHP page. PHP pages are working fine, it has been tested. I have it on WEBSERVER like MySQL and connection is good and everything in there tested. Today i m trying to make some app but i want to have registration and login there. Could u tell me why nothing happens when i click on Registration button? Where do i have error in my code? I would really appreciate every help.

```<code>import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toolbar;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class Register extends AppCompatActivity {
    Button reg_bn;
    EditText Name,Email,UserName,Password,ConPassword;
    String name,email,username,password,conpass;
    AlertDialog.Builder builder;
    String reg_url = "https://prchy.ic.cz/register.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        reg_bn = (Button)findViewById(R.id.bn_reg);
        Name = (EditText)findViewById(R.id.reg_name);
        Email = (EditText)findViewById(R.id.reg_email);
        UserName = (EditText)findViewById(R.id.reg_user_name);
        Password = (EditText)findViewById(R.id.reg_password);
        ConPassword = (EditText)findViewById(R.id.reg_con_password);
        builder = new AlertDialog.Builder(Register.this);
        reg_bn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
               name = Name.getText().toString();
               email = Email.getText().toString();
               username = UserName.getText().toString();
               password = Password.getText().toString();
               conpass = ConPassword.getText().toString();
               if(name.equals("")||email.equals("")||username.equals("")||password.equals("")||conpass.equals(""))
               {
                   builder.setTitle("Něco se pokazilo...");
                   builder.setMessage("Prosím vyplňte všechny pole.");
                   displayAlert("input_error");
               }
               else {
                   if(!(password.equals(conpass)))
                   {
                       builder.setTitle("Něco se pokazilo...");
                       builder.setMessage("Vaše hesla se neshodují.");
                       displayAlert("input_error");
                   }
                   else {
                       StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url,
                               new Response.Listener<String>() {
                                   @Override
                                   public void onResponse(String response) {
                                       try {
                                           JSONArray jsonArray = new JSONArray(response);
                                           JSONObject jsonObject = jsonArray.getJSONObject(0);
                                           String code = jsonObject.getString("code");
                                           String message = jsonObject.getString("message");
                                           builder.setTitle("Odpověď serveru...");
                                           builder.setMessage(message);
                                           displayAlert(code);
                                       } catch (JSONException e) {
                                           e.printStackTrace();
                                       }
                                   }
                               }, new Response.ErrorListener() {
                           @Override
                           public void onErrorResponse(VolleyError error) {

                           }
                       }){
                           @Override
                           protected Map<String, String> getParams() throws AuthFailureError {
                               Map<String, String> params = new HashMap<String,String>();
                               params.put("name",name);
                               params.put("email",email);
                               params.put("user_name",username);
                               params.put("password",password);
                               return params;
                           }
                       };
                       MySingleton.getInstance(Register.this).addToRequestque(stringRequest);

                   }
                   }
               }
            });

    }
    public void displayAlert(final String code)
    {
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if(code.equals("input_error"))
            {
                Password.setText("");
                ConPassword.setText("");
            }
            else if(code.equals("reg_success")){
                finish();
            }
            else if(code.equals("reg_failed")){
                Name.setText("");
                UserName.setText("");
                Password.setText("");
                ConPassword.setText("");
            }
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
    }
}
</code>```

And in my xml file is

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_light"
    tools:background="@android:color/holo_blue_light"
    tools:context="com.example.admin.bongfinalapp.Register">

    <EditText
        android:id="@+id/reg_name"
        android:layout_width="368dp"
        android:layout_height="42dp"
        android:ems="10"
        android:hint="Vaše jméno"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/reg_email"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/imageView2"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:layout_constraintVertical_bias="0.333" />

    <EditText
        android:id="@+id/reg_email"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="E-Mail"
        android:inputType="textEmailAddress"
        app:layout_constraintBottom_toTopOf="@+id/reg_user_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_name" />

    <EditText
        android:id="@+id/reg_user_name"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Přihlašovací jméno"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/reg_password"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_email"
        app:layout_constraintVertical_bias="0.045" />

    <EditText
        android:id="@+id/reg_password"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Heslo"
        android:inputType="textPassword"
        app:layout_constraintBottom_toTopOf="@+id/reg_con_password"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_user_name"
        app:layout_constraintVertical_bias="0.074" />

    <Button
        android:id="@+id/bn_reg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Registruj"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_con_password" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="144dp"
        app:layout_constraintBottom_toTopOf="@+id/reg_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/bong" />

    <EditText
        android:id="@+id/reg_con_password"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Potvrď heslo"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/bn_reg"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_password" />
</android.support.constraint.ConstraintLayout>
</code>```

答: Show MySingelton class. add log for onError to check if you not receive error

Body:
i m trying to make registration script in android studio with volley library and PHP page. PHP pages are working fine, it has been tested. I have it on WEBSERVER like MySQL and connection is good and everything in there tested. Today i m trying to make some app but i want to have registration and login there. Could u tell me why nothing happens when i click on Registration button? Where do i have error in my code? I would really appreciate every help.

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toolbar;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class Register extends AppCompatActivity {
    Button reg_bn;
    EditText Name,Email,UserName,Password,ConPassword;
    String name,email,username,password,conpass;
    AlertDialog.Builder builder;
    String reg_url = "https://prchy.ic.cz/register.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        reg_bn = (Button)findViewById(R.id.bn_reg);
        Name = (EditText)findViewById(R.id.reg_name);
        Email = (EditText)findViewById(R.id.reg_email);
        UserName = (EditText)findViewById(R.id.reg_user_name);
        Password = (EditText)findViewById(R.id.reg_password);
        ConPassword = (EditText)findViewById(R.id.reg_con_password);
        builder = new AlertDialog.Builder(Register.this);
        reg_bn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
               name = Name.getText().toString();
               email = Email.getText().toString();
               username = UserName.getText().toString();
               password = Password.getText().toString();
               conpass = ConPassword.getText().toString();
               if(name.equals("")||email.equals("")||username.equals("")||password.equals("")||conpass.equals(""))
               {
                   builder.setTitle("Něco se pokazilo...");
                   builder.setMessage("Prosím vyplňte všechny pole.");
                   displayAlert("input_error");
               }
               else {
                   if(!(password.equals(conpass)))
                   {
                       builder.setTitle("Něco se pokazilo...");
                       builder.setMessage("Vaše hesla se neshodují.");
                       displayAlert("input_error");
                   }
                   else {
                       StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url,
                               new Response.Listener<String>() {
                                   @Override
                                   public void onResponse(String response) {
                                       try {
                                           JSONArray jsonArray = new JSONArray(response);
                                           JSONObject jsonObject = jsonArray.getJSONObject(0);
                                           String code = jsonObject.getString("code");
                                           String message = jsonObject.getString("message");
                                           builder.setTitle("Odpověď serveru...");
                                           builder.setMessage(message);
                                           displayAlert(code);
                                       } catch (JSONException e) {
                                           e.printStackTrace();
                                       }
                                   }
                               }, new Response.ErrorListener() {
                           @Override
                           public void onErrorResponse(VolleyError error) {

                           }
                       }){
                           @Override
                           protected Map<String, String> getParams() throws AuthFailureError {
                               Map<String, String> params = new HashMap<String,String>();
                               params.put("name",name);
                               params.put("email",email);
                               params.put("user_name",username);
                               params.put("password",password);
                               return params;
                           }
                       };
                       MySingleton.getInstance(Register.this).addToRequestque(stringRequest);

                   }
                   }
               }
            });

    }
    public void displayAlert(final String code)
    {
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if(code.equals("input_error"))
            {
                Password.setText("");
                ConPassword.setText("");
            }
            else if(code.equals("reg_success")){
                finish();
            }
            else if(code.equals("reg_failed")){
                Name.setText("");
                UserName.setText("");
                Password.setText("");
                ConPassword.setText("");
            }
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
    }
}

And in my xml file is

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_light"
    tools:background="@android:color/holo_blue_light"
    tools:context="com.example.admin.bongfinalapp.Register">

    <EditText
        android:id="@+id/reg_name"
        android:layout_width="368dp"
        android:layout_height="42dp"
        android:ems="10"
        android:hint="Vaše jméno"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/reg_email"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/imageView2"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:layout_constraintVertical_bias="0.333" />

    <EditText
        android:id="@+id/reg_email"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="E-Mail"
        android:inputType="textEmailAddress"
        app:layout_constraintBottom_toTopOf="@+id/reg_user_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_name" />

    <EditText
        android:id="@+id/reg_user_name"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Přihlašovací jméno"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/reg_password"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_email"
        app:layout_constraintVertical_bias="0.045" />

    <EditText
        android:id="@+id/reg_password"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Heslo"
        android:inputType="textPassword"
        app:layout_constraintBottom_toTopOf="@+id/reg_con_password"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_user_name"
        app:layout_constraintVertical_bias="0.074" />

    <Button
        android:id="@+id/bn_reg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Registruj"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_con_password" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="144dp"
        app:layout_constraintBottom_toTopOf="@+id/reg_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/bong" />

    <EditText
        android:id="@+id/reg_con_password"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Potvrď heslo"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/bn_reg"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/reg_password" />
</android.support.constraint.ConstraintLayout>


来源: stackexchange

问:
Python - What is a simple way to update elements in a list?
Here is an example to illustrate what I am trying to do:

```<code>class bar:
    pass

list1 = []
for i in range(10):
    bar1 = bar()
    bar1.foo = 0
    list1.append(bar1)

# update list1

for i in range(10):
    print(list1[i].foo)
</code>```

I want the output of the code above to be

```<code>10
10
10
10
10
10
10
10
10
10
</code>```

At the # update list1 part, if I were doing this in C#, I could do

```<code>list1.ForEach(x=>x.foo = 10)
</code>```

And I know in Python I can do

```<code>for x in list1:
    x.foo = 10
</code>```

But how can I do it in Python in a way similar to the way in C#?

答:
Add the parameter to the initialization; use that in a comprehension.

```<code>class bar:
    def __init__(self, foo):
        self.foo = foo

list1 = [bar(10) for i in range(10)]
</code>```

Example for further updating:

```<code>print([x for x in map(lambda obj:obj.foo + 3, list1)])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is an example to illustrate what I am trying to do:

class bar:
    pass

list1 = []
for i in range(10):
    bar1 = bar()
    bar1.foo = 0
    list1.append(bar1)

# update list1

for i in range(10):
    print(list1[i].foo)

I want the output of the code above to be

10
10
10
10
10
10
10
10
10
10

At the # update list1 part, if I were doing this in C#, I could do

list1.ForEach(x=>x.foo = 10)

And I know in Python I can do

for x in list1:
    x.foo = 10

But how can I do it in Python in a way similar to the way in C#?

Body:
Add the parameter to the initialization; use that in a comprehension.

class bar:
    def __init__(self, foo):
        self.foo = foo

list1 = [bar(10) for i in range(10)]

Example for further updating:

print([x for x in map(lambda obj:obj.foo + 3, list1)])


问:
View with editable textviews (onClick)
I have a view with several textView. I want them to be editable on Click.
Following code seems not to do what is supposed to do:

```<code>    textView1 = (TextView) findViewById(R.id.tv1);
    textView1.setText(tv1);
    runEditListener(textView1);

    textView2 = (TextView) findViewById(R.id.tv2);
    textView2.setText(tv2);
    runEditListener(textView1);
</code>```

.......

```<code>    private void runEditListener(TextView textView) {

    dialog = new AlertDialog.Builder(this).create();
    editText = new EditText(this);
    dialog.setTitle("Edit");
    dialog.setView(editText);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) { textView.setText(editText.getText());

        }
    });

    textView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            editText.setText(textView.getText());
            dialog.show();
        }
    });

}
</code>```

I probably should only run once the runEditListener() method and get on which TextView the user clicked but I don't really find how to do that.

答:
You call the dialog in a public void. Shouldn't the dialog be final then?
The same for textView, that is also called inside a public void. </p>

Title: View with editable textviews (onClick)

Body:
I have a view with several textView. I want them to be editable on Click.
Following code seems not to do what is supposed to do:

    textView1 = (TextView) findViewById(R.id.tv1);
    textView1.setText(tv1);
    runEditListener(textView1);

    textView2 = (TextView) findViewById(R.id.tv2);
    textView2.setText(tv2);
    runEditListener(textView1);

.......

    private void runEditListener(TextView textView) {

    dialog = new AlertDialog.Builder(this).create();
    editText = new EditText(this);
    dialog.setTitle("Edit");
    dialog.setView(editText);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) { textView.setText(editText.getText());

        }
    });

    textView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            editText.setText(textView.getText());
            dialog.show();
        }
    });

}

I probably should only run once the runEditListener() method and get on which TextView the user clicked but I don't really find how to do that.


问:
Image exceeding parent size
I want to center and restrict an image

I have an outer container and an image-container which has display: inline-block; to have the same size as the image (required, will contain draggable items)

But the image keeps exceeding the height: 100%;

Is there a workaround to get the desired result (as in the screenshot)

.container {
  width: 300px;
  height: 100px;
  background: red;
  text-align: center;
}

.image-container {
  display: inline-block;
  background: #0f0;
  outline: 5px solid #00f;
  max-width: 100%;
  max-height: 100%;

}

.main-image {
  max-width: 100%;
  max-height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="image-container">
    <img class="main-image" src="http://via.placeholder.com/400x400" />
  </div>
</div></code>```

fiddle

答:
You can do it like this:

.container {
  width: 300px;
  height: 100px;
  background: red;
  display: flex;
}

.image-container {
  display: flex;
  justify-content: center; /* horizontal centering */
  background: #0f0;
  outline: 5px solid #00f;
}

img { /* responsiveness */
  display: block;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="image-container">
    <img class="main-image" src="http://via.placeholder.com/400x400">
  </div>
</div></code>```

Title: Image exceeding parent size

Body:
I want to center and restrict an image

I have an outer container and an image-container which has display: inline-block; to have the same size as the image (required, will contain draggable items)

But the image keeps exceeding the height: 100%;

Is there a workaround to get the desired result (as in the screenshot)

.container {
  width: 300px;
  height: 100px;
  background: red;
  text-align: center;
}

.image-container {
  display: inline-block;
  background: #0f0;
  outline: 5px solid #00f;
  max-width: 100%;
  max-height: 100%;

}

.main-image {
  max-width: 100%;
  max-height: 100%;
}

fiddle

Body:
You can do it like this:

.container {
  width: 300px;
  height: 100px;
  background: red;
  display: flex;
}

.image-container {
  display: flex;
  justify-content: center; /* horizontal centering */
  background: #0f0;
  outline: 5px solid #00f;
}

img { /* responsiveness */
  display: block;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}

<div class="container">
  <div class="image-container">
    <img class="main-image" src="http://via.placeholder.com/400x400">
  </div>
</div>


问:
Spring Batch Step does not execute
I'm trying to fix a problem in Spring Batch that has been plaguing our system recently. We have a job that, for the most part works just fine. It's a multi-step job that downloads and processes data.

The problem is that sometimes the job will bomb out. Maybe the server we're trying to connect to throws an error or we shut down the server in the middle of the job. At this point the next time our quartz scheduler tries to run the job it doesn't seem to do anything. Below is an abridged version of this job definition:

```<code><batch:job id="job.download-stuff" restartable="true">
<batch:validator ref="downloadValidator"/>
<batch:step id="job.download-stuff.download">
    <batch:tasklet ref="salesChannelOrderDownloader" transaction-manager="transactionManager">
        <batch:transaction-attributes isolation="READ_UNCOMMITTED" propagation="NOT_SUPPORTED"/>
        <batch:listeners>
            <batch:listener ref="downloadListener"/>
            <batch:listener ref="loggingContextStepListener" />
        </batch:listeners>
    </batch:tasklet>
    <batch:next on="CONTINUE" to="job.download-stuff.process-stuff.step" />
    <batch:end on="*" />
</batch:step>
<batch:step id="job.download-stuff.process-stuff.step">
    ...
</batch:step>
<batch:listeners>
    <batch:listener ref="loggingContextJobListener"/>
</batch:listeners>
</code>```

Once it gets into this state, the downloadValidator runs, but it never makes it into the first step download-stuff.download. I set a breakpoint in the tasklet and it never makes it inside.

If I clear out all of the spring batch tables, which are stored in our mysql database, and restart the server it will begin working again, but I'd rather understand what prevents it from operating correctly at this point rather than employ scorched earth tactics to get the job running.

I'm a novice at Spring Batch, to put it mildly, so forgive me if I am omitting important details. I've set breakpoints and turned on logging to learn what I can.

What I have observed so far from going through the database is that entries appear to no longer be written to the BATCH_STEP_EXECUTION and BATCH_JOB_EXECUTION tables.

There are no BATCH_JOB_EXECUTION entries for the job that are not in COMPLETED status and no BATCH_STEP_EXECUTION entries that are not in COMPLETED

You'll see that there is a batch:validator defined, I've confirmed that spring batch calls that validator and that it makes it through successfully (set a breakpoint and stepped through). The first step does not get executed.

Neither the loggingContextJobListener nor the loggingContextStepListener seem to fire either. What could be causing this?

UPDATE
I took a closer look at the downloadListener added as a batch:listener. Here's the source code of afterStep:

```<code>@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public ExitStatus afterStep(StepExecution stepExecution) {
    long runSeconds = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - nanoStart);

    // If Success - we're good
    if (stepExecution.getStatus() == BatchStatus.COMPLETED) {
        Long endTs = stepExecution.getExecutionContext().getLong("toTime");
        Date toTime = new Date(endTs);
        handleSuccess(toTime, stepExecution.getWriteCount());
        return null;
    }

    // Otherwise - record errors
    List<Throwable> failures = stepExecution.getFailureExceptions();
    handleError(failures);
    return ExitStatus.FAILED;
}
</code>```

I confirmed that the return ExitStatus.FAILED line executes and that the exception that was thrown is logged in the failureExceptions. It seems like once that happens the BATCH_JOB_EXECUTION entry is in COMPLETED status (and exit_code) and the STEP_EXECUTION is failed.

At this point, the entries in the BATCH_JOB_EXECUTION_PARAMS table remain. I actually tried modifying the values of their KEY_NAME and value columns, but this still didn't allow the job to run. As long as there are parameters tied to a JOB_EXECUTION_ID, another job belonging to the same BATCH_JOB_INSTANCE cannot run.

Once I remove the entries in BATCH_JOB_EXECUTION_PARAMS for that specific JOB_EXECUTION_ID, another BATCH_JOB_EXECUTION can run, even though all the BATCH_JOB_EXECUTION entries are in a completed state.

So I guess I have two questions- is that the correct behavior? And if so, what is preventing the BATCH_JOB_EXECUTION_PARAMS from being removed and how do I remove them?

答: Had the same issue, during test/debug process I kept job name and parameters same, make sure you are changing job name or job parameters to get different JobExecution</p>

Title: Spring Batch Step does not execute

Body:
I'm trying to fix a problem in Spring Batch that has been plaguing our system recently. We have a job that, for the most part works just fine. It's a multi-step job that downloads and processes data.

The problem is that sometimes the job will bomb out. Maybe the server we're trying to connect to throws an error or we shut down the server in the middle of the job. At this point the next time our quartz scheduler tries to run the job it doesn't seem to do anything. Below is an abridged version of this job definition:

<batch:job id="job.download-stuff" restartable="true">
<batch:validator ref="downloadValidator"/>
<batch:step id="job.download-stuff.download">
    <batch:tasklet ref="salesChannelOrderDownloader" transaction-manager="transactionManager">
        <batch:transaction-attributes isolation="READ_UNCOMMITTED" propagation="NOT_SUPPORTED"/>
        <batch:listeners>
            <batch:listener ref="downloadListener"/>
            <batch:listener ref="loggingContextStepListener" />
        </batch:listeners>
    </batch:tasklet>
    <batch:next on="CONTINUE" to="job.download-stuff.process-stuff.step" />
    <batch:end on="*" />
</batch:step>
<batch:step id="job.download-stuff.process-stuff.step">
    ...
</batch:step>
<batch:listeners>
    <batch:listener ref="loggingContextJobListener"/>
</batch:listeners>

Once it gets into this state, the downloadValidator runs, but it never makes it into the first step download-stuff.download. I set a breakpoint in the tasklet and it never makes it inside.

If I clear out all of the spring batch tables, which are stored in our mysql database, and restart the server it will begin working again, but I'd rather understand what prevents it from operating correctly at this point rather than employ scorched earth tactics to get the job running.

I'm a novice at Spring Batch, to put it mildly, so forgive me if I am omitting important details. I've set breakpoints and turned on logging to learn what I can.

What I have observed so far from going through the database is that entries appear to no longer be written to the BATCH_STEP_EXECUTION and BATCH_JOB_EXECUTION tables.

There are no BATCH_JOB_EXECUTION entries for the job that are not in COMPLETED status and no BATCH_STEP_EXECUTION entries that are not in COMPLETED

You'll see that there is a batch:validator defined, I've confirmed that spring batch calls that validator and that it makes it through successfully (set a breakpoint and stepped through). The first step does not get executed.

Neither the loggingContextJobListener nor the loggingContextStepListener seem to fire either. What could be causing this?

UPDATE
I took a closer look at the downloadListener added as a batch:listener. Here's the source code of afterStep:

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public ExitStatus afterStep(StepExecution stepExecution) {
    long runSeconds = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - nanoStart);

    // If Success - we're good
    if (stepExecution.getStatus() == BatchStatus.COMPLETED) {
        Long endTs = stepExecution.getExecutionContext().getLong("toTime");
        Date toTime = new Date(endTs);
        handleSuccess(toTime, stepExecution.getWriteCount());
        return null;
    }

    // Otherwise - record errors
    List<Throwable> failures = stepExecution.getFailureExceptions();
    handleError(failures);
    return ExitStatus.FAILED;
}

I confirmed that the return ExitStatus.FAILED line executes and that the exception that was thrown is logged in the failureExceptions. It seems like once that happens the BATCH_JOB_EXECUTION entry is in COMPLETED status (and exit_code) and the STEP_EXECUTION is failed.

At this point, the entries in the BATCH_JOB_EXECUTION_PARAMS table remain. I actually tried modifying the values of their KEY_NAME and value columns, but this still didn't allow the job to run. As long as there are parameters tied to a JOB_EXECUTION_ID, another job belonging to the same BATCH_JOB_INSTANCE cannot run.

Once I remove the entries in BATCH_JOB_EXECUTION_PARAMS for that specific JOB_EXECUTION_ID, another BATCH_JOB_EXECUTION can run, even though all the BATCH_JOB_EXECUTION entries are in a completed state.

So I guess I have two questions- is that the correct behavior? And if so, what is preventing the BATCH_JOB_EXECUTION_PARAMS from being removed and how do I remove them?


问:
Mongoose/MongoDB: Get second to last document
How would I be able to get the 2nd to latest or previous day's document collection using Mongoose?

my code to get the latest data goes as follows:

```<code>data.findOne()
        .sort({"_id": -1})
        .exec(function(err, data) {
            if (err) {
                console.log('Error getting data..');
            }
            if (data) {
                res.json(data);
            }
            else {
                console.log('No data found!');
            }
        });
</code>```

This only returns the LATEST document in the collection. I instead need the one prior to the latest one, so one from a day before this one, how would I be able to do this?

答:
you could do like this:

```<code>data
.find()
.limit(2)
.sort({ "_id": -1 })
.exec(function(err, data) {
    if (err) return res.json(err);
    return res.json(data);
});
</code>```

this will find on all documents sorted by id: -1, and then limit the result to two, this should give you the result that you want.

Body:
How would I be able to get the 2nd to latest or previous day's document collection using Mongoose?

my code to get the latest data goes as follows:

data.findOne()
        .sort({"_id": -1})
        .exec(function(err, data) {
            if (err) {
                console.log('Error getting data..');
            }
            if (data) {
                res.json(data);
            }
            else {
                console.log('No data found!');
            }
        });

This only returns the LATEST document in the collection. I instead need the one prior to the latest one, so one from a day before this one, how would I be able to do this?

Body:
you could do like this:

data
.find()
.limit(2)
.sort({ "_id": -1 })
.exec(function(err, data) {
    if (err) return res.json(err);
    return res.json(data);
});

this will find on all documents sorted by id: -1, and then limit the result to two, this should give you the result that you want.


问:
How to check if a view controller is presented modally or pushed on a navigation stack?
How can I, in my view controller code, differentiate between:

presented modally

pushed on navigation stack

Both presentingViewController and isMovingToParentViewController are YES in both cases, so are not very helpful.

What complicates things is that my parent view controller is sometimes modal, on which the to be checked view controller is pushed.

It turns out my issue is that I embed my HtmlViewController in a UINavigationController which is then presented. That's why my own attempts and the good answers below were not working.

```<code>HtmlViewController*     termsViewController = [[HtmlViewController alloc] initWithDictionary:dictionary];
UINavigationController* modalViewController;

modalViewController = [[UINavigationController alloc] initWithRootViewController:termsViewController];
modalViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:modalViewController
                   animated:YES
                 completion:nil];
</code>```

I guess I'd better tell my view controller when it's modal, instead of trying to determine.

答:
Swift 4

```<code>var isModal: Bool {
    return presentingViewController != nil ||
           navigationController?.presentingViewController?.presentedViewController === navigationController ||
           tabBarController?.presentingViewController is UITabBarController
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I, in my view controller code, differentiate between:

presented modally

pushed on navigation stack

Both presentingViewController and isMovingToParentViewController are YES in both cases, so are not very helpful.

What complicates things is that my parent view controller is sometimes modal, on which the to be checked view controller is pushed.

It turns out my issue is that I embed my HtmlViewController in a UINavigationController which is then presented. That's why my own attempts and the good answers below were not working.

HtmlViewController*     termsViewController = [[HtmlViewController alloc] initWithDictionary:dictionary];
UINavigationController* modalViewController;

modalViewController = [[UINavigationController alloc] initWithRootViewController:termsViewController];
modalViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:modalViewController
                   animated:YES
                 completion:nil];

I guess I'd better tell my view controller when it's modal, instead of trying to determine.

Body:
Swift 4

var isModal: Bool {
    return presentingViewController != nil ||
           navigationController?.presentingViewController?.presentedViewController === navigationController ||
           tabBarController?.presentingViewController is UITabBarController
}


问:
How to export MongoDB database from cloud9 to mlab?
So I created a web app on cloud9 using Node.js, mongoDB, express. I set up MongoDB in cloud 9 as per the instructions.

When I completed the app, I deployed it to Heroku, and created a new db in mlab (mongolab). This works fine.

However, I inserted a lot of dummy data into the db hosted on cloud9. I want to copy this dummy data from the db in cloud9 to the db in mlab. How do i do that?

I did some research.

According to mongodb docs, I should use db.copyDatabase():

db.copydatabase(fromdb,todb,fromhost,username,password,mechanism)

It says I should run this command  in the destination instance, i.e. the instance receiving the copied data.

I'm assuming this means that I should connect to the db hosted on mlab through:
mongo dsblahblah.mlab.com:59220/blahblah -u  -p

and then run the db.copyDatabase command, correct?

But what should I use for the fromdb parameter? This is the db that is hosted in cloud9. But what is this db's url?

Help. And ELI5.

答:
Nathan Loyer has the correct answer, though it's of course more complicated than that. If you're like me and don't really know what you're doing, here's a detailed explanation that worked for me, with resources for where I got this information at bottom in case anything gets updated and makes you out of date.

Note that you need to do this for each collection you want to migrate. Chances are you only have one or a few collections, so that's not much hassle. If you want to move a full db, it's possible these instructions can be adapted, but that's up to you.

Figure out which collection you want to move. To do that, in Cloud9, at the appropriate directory, in your command line, run the following commands, and remember or write down the db and collection you identify. (If you're not sure on the collections, you can do db.(collection).find() to output a list of data it has)

mongo
show dbs
use (the name of the appropriate db, not in parentheses though)
show collections
```

<ol start="2">
<li>Export the data from your database. That's relatively easy. Simply exit mongo with ctrl+c, and use the following code in your command line, with data filled in and no parentheses:</li>
</ol>

<pre class="lang-html prettyprint-override"><code>mongoexport --db (your db name) --collection (your collection name) --outs (a filename: mongodb.org recommends "traffic.json", no quotes)
</code>```

Now you need to import your data into mLabs. Go to mLabs, select your database, and pick the "tools" menu. You should see a pre-fab code under "JSON" for importing. Fill in the blanks again, using your database user credentials from mLab, but don't run it yet. It should look something like:

mongoimport -h ds12345.mlab.com:12121 -d databasename -c <collection> -u <user> -p <password> --file <input file, possibly traffic.json?>
```

In order to pass the import successfully, you should check that your Cloud9 and mLabs instances are running on the same (or at least very similar versions). In cloud9, just type "mongo" into the console and see what it says. You're probably on 2.6 or 3.2. On mLab, it's on almost every page. Just look for "mongod version: xxxxx." You're probably on 3.4.7. I ran it as Cloud9 3.2 with mLab 3.4, and it worked fine. (If your Cloud9 is on less than version 3, backup anything important (use git?) and update per the instructions at https://community.c9.io/t/updating-mongodb/3914 )

The other thing you need to do is stop all processes in Cloud9, including Mongod, which operates from the root directory. This is where you need to run mongoimport from (NOT from your command line inside some directory in your workspace, which is where I told you to run mongoexport from). To be clear: Your command line should show "username: ~$", not "username:~/workspace/filedirectories/maybeafewofthem (possibly master) $".

Since you're running from the root, you also need to make sure the filename you're passing is referenced correctly. It won't be as simple as "traffic.json." It should look something like "workspace/directoryName/traffic.json." (If your export was successful, you should see the traffic.json file floating around your files somewhere.)

And that's it. Run the code from Step 3, and check in mLabs that it processed correctly. Good to go.

Resources:

http://docs.mlab.com/connecting/

http://docs.mlab.com/migrating/

https://docs.mongodb.com/manual/reference/program/mongoexport/

https://docs.mongodb.com/manual/reference/program/mongoimport/

Body:
Nathan Loyer has the correct answer, though it's of course more complicated than that. If you're like me and don't really know what you're doing, here's a detailed explanation that worked for me, with resources for where I got this information at bottom in case anything gets updated and makes you out of date.

Note that you need to do this for each collection you want to migrate. Chances are you only have one or a few collections, so that's not much hassle. If you want to move a full db, it's possible these instructions can be adapted, but that's up to you.

Figure out which collection you want to move. To do that, in Cloud9, at the appropriate directory, in your command line, run the following commands, and remember or write down the db and collection you identify. (If you're not sure on the collections, you can do db.(collection).find() to output a list of data it has)

mongo
show dbs
use (the name of the appropriate db, not in parentheses though)
show collections

Export the data from your database. That's relatively easy. Simply exit mongo with ctrl+c, and use the following code in your command line, with data filled in and no parentheses:

mongoexport --db (your db name) --collection (your collection name) --outs (a filename: mongodb.org recommends "traffic.json", no quotes)

Now you need to import your data into mLabs. Go to mLabs, select your database, and pick the "tools" menu. You should see a pre-fab code under "JSON" for importing. Fill in the blanks again, using your database user credentials from mLab, but don't run it yet. It should look something like:

mongoimport -h ds12345.mlab.com:12121 -d databasename -c <collection> -u <user> -p <password> --file <input file, possibly traffic.json?>

In order to pass the import successfully, you should check that your Cloud9 and mLabs instances are running on the same (or at least very similar versions). In cloud9, just type "mongo" into the console and see what it says. You're probably on 2.6 or 3.2. On mLab, it's on almost every page. Just look for "mongod version: xxxxx." You're probably on 3.4.7. I ran it as Cloud9 3.2 with mLab 3.4, and it worked fine. (If your Cloud9 is on less than version 3, backup anything important (use git?) and update per the instructions at https://community.c9.io/t/updating-mongodb/3914 )

The other thing you need to do is stop all processes in Cloud9, including Mongod, which operates from the root directory. This is where you need to run mongoimport from (NOT from your command line inside some directory in your workspace, which is where I told you to run mongoexport from). To be clear: Your command line should show "username: ~$", not "username:~/workspace/filedirectories/maybeafewofthem (possibly master) $".

Since you're running from the root, you also need to make sure the filename you're passing is referenced correctly. It won't be as simple as "traffic.json." It should look something like "workspace/directoryName/traffic.json." (If your export was successful, you should see the traffic.json file floating around your files somewhere.)

And that's it. Run the code from Step 3, and check in mLabs that it processed correctly. Good to go.

Resources:

http://docs.mlab.com/connecting/

http://docs.mlab.com/migrating/

https://docs.mongodb.com/manual/reference/program/mongoexport/

https://docs.mongodb.com/manual/reference/program/mongoimport/


问:
Javac can't infer type unless lambda expression is inlined
I have the following snippet of Java code using Vavr. Type-checking fails unless I inline a parameter.

Why can the code below not be accepted by the compiler?

```<code>import io.vavr.Function1;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.List;
import io.vavr.Option;

import static io.vavr.collection.List.unfoldRight;

class A {}
class B {}
class Main {
    Function1<A, Option<Tuple2<B, A>>> f = (a) -> Option.of(Tuple.of(new B(), new A()));
    List<B> L0 = unfoldRight(new A(), f); // *
    List<B> L1 = unfoldRight(new A(), (a) -> Option.of(Tuple.of(new B(), new A()));

    Option<Tuple2<B, A>> g(A a) { return Option.of(Tuple.of(new B(), new A())); }
    List<B> L2 = unfoldRight(new A(), (a) -> g(a)); // **
}

// *  Compilation fails with: "Incompatible equality constraint: ? extends T and A"

// ** Compilation fails with: "Incompatible equality constraint: ? extends A and A"
</code>```

Here's the method signature for unfoldRight from the Vavr library:

```<code>static <T, U> List<U> unfoldRight(T seed, Function<? super T, Option<Tuple2<? extends U, ? extends T>>> f)
</code>```

and here's a link to the Github documentation for same:

https://github.com/vavr-io/vavr/blob/master/vavr/src/main/java/io/vavr/collection/List.java#L644-L671

答:
The key is that Option<Tuple> isn't an instance of Option<Tuple<? extends A, ? extends B>> (although it is a Option<? extends Tuple<? extends A, ? extends B>>).

Consider the case of a List<Map> and List<Map<? extends A, ? extends B>> (which is the same from a type safety perspective as your code). If you could write:

```<code>List<Map<A, B>> list = new ArrayList<>();

// Compiler error! Pretend it's OK, though.
List<Map<? extends A, ? extends B>> list2 = list;

Map<SubclassOfA, SubclassOfB> map = new HashMap<>();
list2.add(map);

list.get(0).put(new A(), new B());
</code>```

This is now a problem, because map contains a key/value pair of type A,B, not SubclassOfA,SubclassOfB. As such, you'd get a ClassCastException if you tried to get things from map.

```<code>// ClassCastException!
SubclassOfA soa = map.keySet().iterator().next();
</code>```

Ideone demo

Hence, it's disallowed by the compiler.

If list2 were declared as List<? extends Map<? extends A, ? extends B>>, you couldn't call list2.add(map), so you couldn't get the same problem. Hence, that assignment would be allowed.

Add wildcard upper bounds to your types:

```<code>Function1<A, Option<Tuple2<? extends B, ? extends A>>> f = ...
Option<Tuple2<? extends B, ? extends A>> g(A a) { ... }
</code>```

Body:
I have the following snippet of Java code using Vavr. Type-checking fails unless I inline a parameter.

Why can the code below not be accepted by the compiler?

import io.vavr.Function1;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.List;
import io.vavr.Option;

import static io.vavr.collection.List.unfoldRight;

class A {}
class B {}
class Main {
    Function1<A, Option<Tuple2>> f = (a) -> Option.of(Tuple.of(new B(), new A()));
    List L0 = unfoldRight(new A(), f); // *
    List L1 = unfoldRight(new A(), (a) -> Option.of(Tuple.of(new B(), new A()));

    Option<Tuple2> g(A a) { return Option.of(Tuple.of(new B(), new A())); }
    List L2 = unfoldRight(new A(), (a) -> g(a)); // **
}

// *  Compilation fails with: "Incompatible equality constraint: ? extends T and A"

// ** Compilation fails with: "Incompatible equality constraint: ? extends A and A"

Here's the method signature for unfoldRight from the Vavr library:

static <T, U> List unfoldRight(T seed, Function<? super T, Option<Tuple2<? extends U, ? extends T>>> f)

and here's a link to the Github documentation for same:

https://github.com/vavr-io/vavr/blob/master/vavr/src/main/java/io/vavr/collection/List.java#L644-L671

Body:
The key is that Option<Tuple<A, B>> isn't an instance of Option<Tuple<? extends A, ? extends B>> (although it is a Option<? extends Tuple<? extends A, ? extends B>>).

Consider the case of a List<Map<A, B>> and List<Map<? extends A, ? extends B>> (which is the same from a type safety perspective as your code). If you could write:

List<Map<A, B>> list = new ArrayList<>();

// Compiler error! Pretend it's OK, though.
List<Map<? extends A, ? extends B>> list2 = list;

Map<SubclassOfA, SubclassOfB> map = new HashMap<>();
list2.add(map);

list.get(0).put(new A(), new B());

This is now a problem, because map contains a key/value pair of type A,B, not SubclassOfA,SubclassOfB. As such, you'd get a ClassCastException if you tried to get things from map.

// ClassCastException!
SubclassOfA soa = map.keySet().iterator().next();

Ideone demo

Hence, it's disallowed by the compiler.

If list2 were declared as List<? extends Map<? extends A, ? extends B>>, you couldn't call list2.add(map), so you couldn't get the same problem. Hence, that assignment would be allowed.

Add wildcard upper bounds to your types:

Function1<A, Option<Tuple2<? extends B, ? extends A>>> f = ...
Option<Tuple2<? extends B, ? extends A>> g(A a) { ... }


问:
Hover effect on only one element and not affect the others
How to animate only one element (div) each time, having class .box and not affect the other elements with same class. Something like this :

```<code>$(.box).hover(function() {
        $(.box).animate({ fontSize : '2rem' });
        $(.box).removeClass("main");
        // other things...
</code>```

html:

```<code><div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</code>```

I tried with .next() and .find() but I did not succeed because of my basic level in jQuery.

答:
```<code>//use 'this' inside an event handler to reference the element being processed for the event
$('.box').hover(function(){
    $(this).animate(...);
    $(this).removeClass(...);
    $(this).whatever...
});
</code>```

Ref. http://learn.jquery.com/events/event-basics/

Body:
How to animate only one element (div) each time, having class .box and not affect the other elements with same class. Something like this :

$(.box).hover(function() {
        $(.box).animate({ fontSize : '2rem' });
        $(.box).removeClass("main");
        // other things...

html:

I tried with .next() and .find() but I did not succeed because of my basic level in jQuery.

Body:
//use 'this' inside an event handler to reference the element being processed for the event
$('.box').hover(function(){
    $(this).animate(...);
    $(this).removeClass(...);
    $(this).whatever...
});

Ref. http://learn.jquery.com/events/event-basics/


问:
Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES) in C:\Users\xampp\htdocs\PHP_Login_Script\config.php on line 6

I'm getting this error above on localhost even if my config file is like this:

```<code><?php

    define("DB_HOST", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "");
    define("DB_DATABASE", "databasename");

    $db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
</code>```

This used to work, but now it doesn't anymore. Is there any problem with this code or is it not working now?

答:
The same issue faced me with XAMPP 7 and opencart Arabic 3.
Replacing  localhost by the actual machine name reslove the issue.</p>

Body:
Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES) in C:\Users\xampp\htdocs\PHP_Login_Script\config.php on line 6

I'm getting this error above on localhost even if my config file is like this:

<?php

    define("DB_HOST", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "");
    define("DB_DATABASE", "databasename");

    $db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

This used to work, but now it doesn't anymore. Is there any problem with this code or is it not working now?


问:
Pull Only One Unique Item from Column of Dupes Based on Another Cell
I have a sheet that looks like this:

I have VBA code that launches an email and takes data from the sheet and puts it in the email body based on an inputbox value that is searched for in the sheet.  Values are grabbed from the row based on finding that value.  What I am having trouble with now is we have many dupes and I want to pull a name only once, and then getting it to loop, creating a new email when it hits a new approver name, then grabbing all of that approver's customers, and so on.

Example from above sheet:
Email says 'Dear Chris,
Your customers Thomas, Mark, and Jared all need to be reviewed."

So I need code that gets all customers (column C) assigned to one approver (column E), but only grabs one instance of each customer name.

Then, it creates a new separate email when it finds the next approver, in this case John. So the approver name becomes a delimiter.

I am unsure how to do this, or what is even the best approach.  Can anyone offer up any ideas?  I am learning, but this part is giving me trouble.
Here is the code I have so far:

```<code>Sub Test()
Dim aOutlook As Object
Dim aEmail As Object
Dim rngeAddresses As Range, rngeCell As Range, strRecipients As String
Dim strbox As String
Dim stritem As String
Dim x As Long
Dim r As Long
Dim lr, lookRng As Range
Dim findStr As String
Dim foundCell As Variant
Dim foundcell1 As Variant
Dim foundcell2 As Variant
Dim strbody As String
Dim sigstring As String
Dim signature As String
Dim findstr1 As String
Dim foundrng As Range
Dim valuefound As Boolean
Dim strFilename As String

Set aOutlook = CreateObject("Outlook.Application")
Set aEmail = aOutlook.CreateItem(0)

'Input box(es)

findStr = InputBox("Enter approver name to find")

'Greeting based on time of day

Select Case Time
       Case 0.25 To 0.5
            GreetTime = "Good morning"
       Case 0.5 To 0.71
            GreetTime = "Good afternoon"
       Case Else
            GreetTime = "Good evening"
 End Select

'Search for input box values and set fields to be pulled

lr = Cells(Rows.Count, "c").End(xlUp).Row
Set lookRng = Range("d1:d" & lr)
 valuefound = False
 For x = 1 To lr
   If Range("c" & x).Value = findStr Then
    Set foundCell = Range("B" & x).Offset(0, 4)
    Set foundcell1 = Range("e" & x).Offset(0, 1)
    Set foundcell2 = Range("B" & x).Offset(0, 5)
    valuefound = True
   End If
 Next x

'Ends the macro if input values to not match the sheet exactly

   If Not valuefound Then
    MsgBox "Is case-sensitive, Must be exact name", vbExclamation, "No
 Match!"
    Exit Sub
    End If
</code>```

答:
The way I would approach this is to query your table using SQL to exclude any duplicates (I adapted this example), then iterate over the returned recordset using a dictionary to store your approvers and their customers.

To get the below example to work I've added the Microsoft ActiveX Data Objects 6.1 Library (for the SQL), and the Microsoft Scripting Runtime (for the dictionary), I believe it does what you need:

```<code>Sub GetApproversAndCustomers()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset

strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

'only retrieve unique combinations of approvers and customers
strSQL = "SELECT DISTINCT [Approver Name],[Customer Name] FROM [Sheet1$B1:E11]"

rs.Open strSQL, cn

Dim approvers As Dictionary
Set approvers = New Dictionary

Do Until rs.EOF
    'only add the approver to the collection if they do not already exist
    If approvers.Exists(rs.Fields("Approver Name").Value) = False Then
        'if they dont exist, add both the approver and customer to the dictionary
        approvers.Add rs.Fields("Approver Name").Value, rs.Fields("Customer Name").Value
    Else
        'if they do exist, find the approver and add the customer to the existing list
        approvers.Item(rs.Fields("Approver Name").Value) = approvers.Item(rs.Fields("Approver Name").Value) & ", " & rs.Fields("Customer Name").Value
    End If
    rs.MoveNext
Loop

'iterate over the dictionary, outputting our values
Dim strKey As Variant
For Each strKey In approvers.Keys()
    Debug.Print "Dear " & strKey & ", Your customer(s) " & approvers(strKey) & " all need to be reviewed."
Next
End Sub
</code>```

Body:
I have a sheet that looks like this:

I have VBA code that launches an email and takes data from the sheet and puts it in the email body based on an inputbox value that is searched for in the sheet.  Values are grabbed from the row based on finding that value.  What I am having trouble with now is we have many dupes and I want to pull a name only once, and then getting it to loop, creating a new email when it hits a new approver name, then grabbing all of that approver's customers, and so on.

Example from above sheet:
Email says 'Dear Chris,
Your customers Thomas, Mark, and Jared all need to be reviewed."

So I need code that gets all customers (column C) assigned to one approver (column E), but only grabs one instance of each customer name.

Then, it creates a new separate email when it finds the next approver, in this case John. So the approver name becomes a delimiter.

I am unsure how to do this, or what is even the best approach.  Can anyone offer up any ideas?  I am learning, but this part is giving me trouble.
Here is the code I have so far:

Sub Test()
Dim aOutlook As Object
Dim aEmail As Object
Dim rngeAddresses As Range, rngeCell As Range, strRecipients As String
Dim strbox As String
Dim stritem As String
Dim x As Long
Dim r As Long
Dim lr, lookRng As Range
Dim findStr As String
Dim foundCell As Variant
Dim foundcell1 As Variant
Dim foundcell2 As Variant
Dim strbody As String
Dim sigstring As String
Dim signature As String
Dim findstr1 As String
Dim foundrng As Range
Dim valuefound As Boolean
Dim strFilename As String

Set aOutlook = CreateObject("Outlook.Application")
Set aEmail = aOutlook.CreateItem(0)

'Input box(es)

findStr = InputBox("Enter approver name to find")

'Greeting based on time of day

Select Case Time
       Case 0.25 To 0.5
            GreetTime = "Good morning"
       Case 0.5 To 0.71
            GreetTime = "Good afternoon"
       Case Else
            GreetTime = "Good evening"
 End Select

'Search for input box values and set fields to be pulled

lr = Cells(Rows.Count, "c").End(xlUp).Row
Set lookRng = Range("d1:d" & lr)
 valuefound = False
 For x = 1 To lr
   If Range("c" & x).Value = findStr Then
    Set foundCell = Range("B" & x).Offset(0, 4)
    Set foundcell1 = Range("e" & x).Offset(0, 1)
    Set foundcell2 = Range("B" & x).Offset(0, 5)
    valuefound = True
   End If
 Next x

'Ends the macro if input values to not match the sheet exactly

   If Not valuefound Then
    MsgBox "Is case-sensitive, Must be exact name", vbExclamation, "No
 Match!"
    Exit Sub
    End If

Body:
The way I would approach this is to query your table using SQL to exclude any duplicates (I adapted this example), then iterate over the returned recordset using a dictionary to store your approvers and their customers.

To get the below example to work I've added the Microsoft ActiveX Data Objects 6.1 Library (for the SQL), and the Microsoft Scripting Runtime (for the dictionary), I believe it does what you need:

Sub GetApproversAndCustomers()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset

strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

'only retrieve unique combinations of approvers and customers
strSQL = "SELECT DISTINCT [Approver Name],[Customer Name] FROM [Sheet1$B1:E11]"

rs.Open strSQL, cn

Dim approvers As Dictionary
Set approvers = New Dictionary

Do Until rs.EOF
    'only add the approver to the collection if they do not already exist
    If approvers.Exists(rs.Fields("Approver Name").Value) = False Then
        'if they dont exist, add both the approver and customer to the dictionary
        approvers.Add rs.Fields("Approver Name").Value, rs.Fields("Customer Name").Value
    Else
        'if they do exist, find the approver and add the customer to the existing list
        approvers.Item(rs.Fields("Approver Name").Value) = approvers.Item(rs.Fields("Approver Name").Value) & ", " & rs.Fields("Customer Name").Value
    End If
    rs.MoveNext
Loop

'iterate over the dictionary, outputting our values
Dim strKey As Variant
For Each strKey In approvers.Keys()
    Debug.Print "Dear " & strKey & ", Your customer(s) " & approvers(strKey) & " all need to be reviewed."
Next
End Sub


问:
Import several existing resources in Terraform state takes very long time
I'm trying to import several resources by creating a scripts which read AWS resources and then import in Terraform state file using terraform import. The fact is that it takes ages because the import command upload at every call the changes to the remote state in S3. Do you have any idea how to approach in a different way the problem?

答:
You could try to disable the remote state (delete the S3 state and keep a copy just in case), then import to the local path the state and once you finish all the imports you can configure the backend again and run  terraform init -reconfigure then terraform will ask you to upload the local state to S3.

```<code>/Users/koe/.terraform-versions/terraform-0.9.11/terraform init -reconfigure
Initializing the backend...
Do you want to copy state from "local" to "s3"?
  Pre-existing state was found in "local" while migrating to "s3". No existing
  state was found in "s3". Do you want to copy the state from "local" to
  "s3"? Enter "yes" to copy and "no" to start with an empty state.

  Enter a value:
</code>```

Body:
You could try to disable the remote state (delete the S3 state and keep a copy just in case), then import to the local path the state and once you finish all the imports you can configure the backend again and run  terraform init -reconfigure then terraform will ask you to upload the local state to S3.

/Users/koe/.terraform-versions/terraform-0.9.11/terraform init -reconfigure
Initializing the backend...
Do you want to copy state from "local" to "s3"?
  Pre-existing state was found in "local" while migrating to "s3". No existing
  state was found in "s3". Do you want to copy the state from "local" to
  "s3"? Enter "yes" to copy and "no" to start with an empty state.

  Enter a value:


问:
Compiling Executable with dask or joblib multiprocessing with cython results in errors
I'm converting some serial processed python jobs to multiprocessing with dask or joblib. Sadly I need to work on windows.

When running from within IPython or from command line invoking the py-file with python everything is running fine.

When compiling an executable with cython, it is no longer running fine: Step by step more and more processes (unlimited and bigger than the number of requested processes) get startet and block my system.

It somehow feels like Multiprocessing Bomb - but of course I used if __name__=="__main__:" for having the control block - approved by fine running from python call at the command line.

My cython call is cython --embed --verbose --annotate THECODE.PY and I'm compiling with gcc -time -municode -DMS_WIN64 -mthreads -Wall -O -I"PATH_TO_\include" -L"PATH_TO_\libs"  THECODE.c -lpython36 -o THECODE resulting in a windows executable THECODE.exe.

With other (single processing) code that is running fine.

The problem seems to be the same for dask and joblib (what might mean, that dask works like or is based on joblib).

Any suggestions?

For those interested in a mcve: Just taking the first code from Multiprocessing Bomb and compiling it with my cython commands above will result in an executable blowing your system. (I just tried :-) )

I just found something interesting by adding one line to the code sample for showing the __name__:

```<code>import multiprocessing

def worker():
    """worker function"""
    print('Worker')
    return

print("-->" + __name__ + "<--")
if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()
</code>```

When running that piece of code with python it shows

```<code>__main__
__mp_main__
__mp_main__
__mp_main__
__mp_main__
__mp_main__
</code>```

(other output supressed). Explaining that the if decision works.
When running the executable after cython and compilation is shows

```<code>__main__
__main__
__main__
__main__
__main__
__main__
</code>```

and more and more. Thus the workers call to the module are no longer masqueraded like an import and thus each workers tries to start five new ones in a recursive manner.

答:
When starting a new python-process multiprocessing-module uses spawn-method on Windows (this behavior can be also triggered on Linux by using mp.set_start_method('spawn').

Command-line arguments are passed to the interpreter in the new process, so the communication with the parent process can be established, for example:

```<code> python -c "from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=11)" --multiprocessing-fork
</code>```

The problem with embeded cython modules (or with frozen (i.e. created with cx_Freeze, py2exe and similar) modules in general), that passing command line arguments to them corresponds more to

```<code>python my_script.py <arguments>
</code>```

i.e. the command line aren't automatically processed by the interpeter, but needs to be handled in the script.

multiprocessing provides a function called multiprocessing.freeze_support(), which handles the command line arguments correctly and which can be used as shown in Bastian's answer:

```<code>if __name__ == '__main__':
    # needed for Cython, as it doesn't set `frozen`-attribute
    setattr(sys, 'frozen', True)
    # parse command line options and execute it if needed
    multiprocessing.freeze_support()
</code>```

This solution works however only for Windows, as can be seen in the code:

```<code>def freeze_support(self):
    '''Check whether this is a fake forked process in a frozen executable.
    If so then run code specified by commandline and exit.
    '''
    if sys.platform == 'win32' and getattr(sys, 'frozen', False):
        from .spawn import freeze_support
        freeze_support()
</code>```

There is a bug-report: multiprocessing freeze_support needed outside win32 which might/might not be fixed soon.

As explained in the above bug-report, it is not enough to set frozen attribute to True and to call freeze_support directly from the multiprocessing.spawn because than the semaphore tracker isn't handled correctly.

There are two options I see: either to patch your installation with a yet unreleased patch from the above bug report or to use the do-it-yourself approach presented bellow.

Here are an earlier version of this answer which is more "experimental" but offers more insights/details and proposes a solution in a somewhat Do-It-Yourself-style.

I'm on linux, so I use mp.set_start_method('spawn') to simulate the behavior of windows.

What happens in the spawn-mode? Let's add some sleeps, so we can investigate the processes:

```<code>#bomb.py
import multiprocessing as mp
import sys
import time

def worker():
    time.sleep(50)
    print('Worker')
    return

if __name__ == '__main__':
        print("Starting...")
        time.sleep(20)
        mp.set_start_method('spawn') ## use spawn!
        jobs = []
        for i in range(5):
            p = mp.Process(target=worker)
            jobs.append(p)
            p.start()
</code>```

By using pgrep python we can see that at first there is only one-python process, then 7(!) different pids. We can see the command-line arguments via cat /proc/<pid>/cmdline. 5 of the new processes have command line

```<code>-c "from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=11)" --multiprocessing-fork
</code>```

and one:

```<code>-c "from multiprocessing.semaphore_tracker import main;main(4)"
</code>```

That means, the parent process starts 6 new python interpreter instances and every newly started interpreter executes a code sent from the parent via the command line options, the information is shared via pipes. One of these 6 python-instances is a tracker, which observes the whole thing.

Ok, what happens if cythonized+embeded? The same as with the normal python, the only difference is that the bomb-executable is started instead of python. But differently as the python-interpreter, it doesn't execute/isn't aware of the command line arguments, so the main function runs over and over and over again.

There is an easy fix: let the bomb-exe to start the python interpreter

```<code> ...
 if __name__ == '__main__':
    mp.set_executable(<PATH TO PYTHON>)
 ....
</code>```

Now the bomb is no longer a multiprocessing bomb!

However, the goal is probably not to have a python-interpreter around, so we need to make our program aware of possible command lines:

```<code>import re
......
if __name__ == '__main__':
    if len(sys.argv)==3:  # should start in semaphore_tracker mode
        nr=list(map(int, re.findall(r'\d+',sys.argv[2])))
        sys.argv[1]='--multiprocessing-fork'   # this canary is needed for multiprocessing module to work
        from multiprocessing.semaphore_tracker import main;main(nr[0])

    elif len(sys.argv)>3: # should start in slave mode
        fd, pipe=map(int, re.findall(r'\d+',sys.argv[2]))
        print("I'm a slave!, fd=%d, pipe=%d"%(fd,pipe))
        sys.argv[1]='--multiprocessing-fork'   # this canary is needed for multiprocessing module to work
        from multiprocessing.spawn import spawn_main;
        spawn_main(tracker_fd=fd, pipe_handle=pipe)

    else: #main mode
        print("Starting...")
        mp.set_start_method('spawn')
        jobs = []
        for i in range(5):
            p = mp.Process(target=worker)
            jobs.append(p)
            p.start()
</code>```

Now, our bomb doesn't need a stand-alone python-interpreter and stops after the workers are done. Please note the following:

The way it is decide, in which mode bomb should be started is not very error-safe, but I hope you get the gist

--multiprocessing-fork is just a canary, it doesn't do anything it only must be there, see here.

NB: The changed code can be also used with python, because after executing "from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=11)" --multiprocessing-fork python changes the sys.argv so the code no longer sees the original command line and len(sys.argv) is 1.

Body:
I'm converting some serial processed python jobs to multiprocessing with dask or joblib. Sadly I need to work on windows.

When running from within IPython or from command line invoking the py-file with python everything is running fine.

When compiling an executable with cython, it is no longer running fine: Step by step more and more processes (unlimited and bigger than the number of requested processes) get startet and block my system.

It somehow feels like Multiprocessing Bomb - but of course I used if __name__=="__main__:" for having the control block - approved by fine running from python call at the command line.

My cython call is cython --embed --verbose --annotate THECODE.PY and I'm compiling with gcc -time -municode -DMS_WIN64 -mthreads -Wall -O -I"PATH_TO_\include" -L"PATH_TO_\libs"  THECODE.c -lpython36 -o THECODE resulting in a windows executable THECODE.exe.

With other (single processing) code that is running fine.

The problem seems to be the same for dask and joblib (what might mean, that dask works like or is based on joblib).

Any suggestions?

For those interested in a mcve: Just taking the first code from Multiprocessing Bomb and compiling it with my cython commands above will result in an executable blowing your system. (I just tried :-) )

I just found something interesting by adding one line to the code sample for showing the __name__:

import multiprocessing

def worker():
    """worker function"""
    print('Worker')
    return

print("-->" + __name__ + "<--")
if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()

When running that piece of code with python it shows

__main__
__mp_main__
__mp_main__
__mp_main__
__mp_main__
__mp_main__

(other output supressed). Explaining that the if decision works.
When running the executable after cython and compilation is shows

__main__
__main__
__main__
__main__
__main__
__main__

and more and more. Thus the workers call to the module are no longer masqueraded like an import and thus each workers tries to start five new ones in a recursive manner.

Body:
When starting a new python-process multiprocessing-module uses spawn-method on Windows (this behavior can be also triggered on Linux by using mp.set_start_method('spawn').

Command-line arguments are passed to the interpreter in the new process, so the communication with the parent process can be established, for example:

 python -c "from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=11)" --multiprocessing-fork

The problem with embeded cython modules (or with frozen (i.e. created with cx_Freeze, py2exe and similar) modules in general), that passing command line arguments to them corresponds more to

python my_script.py <arguments>

i.e. the command line aren't automatically processed by the interpeter, but needs to be handled in the script.

multiprocessing provides a function called multiprocessing.freeze_support(), which handles the command line arguments correctly and which can be used as shown in Bastian's answer:

if __name__ == '__main__':
    # needed for Cython, as it doesn't set `frozen`-attribute
    setattr(sys, 'frozen', True)
    # parse command line options and execute it if needed
    multiprocessing.freeze_support()

This solution works however only for Windows, as can be seen in the code:

def freeze_support(self):
    '''Check whether this is a fake forked process in a frozen executable.
    If so then run code specified by commandline and exit.
    '''
    if sys.platform == 'win32' and getattr(sys, 'frozen', False):
        from .spawn import freeze_support
        freeze_support()

There is a bug-report: multiprocessing freeze_support needed outside win32 which might/might not be fixed soon.

As explained in the above bug-report, it is not enough to set frozen attribute to True and to call freeze_support directly from the multiprocessing.spawn because than the semaphore tracker isn't handled correctly.

There are two options I see: either to patch your installation with a yet unreleased patch from the above bug report or to use the do-it-yourself approach presented bellow.

Here are an earlier version of this answer which is more "experimental" but offers more insights/details and proposes a solution in a somewhat Do-It-Yourself-style.

I'm on linux, so I use mp.set_start_method('spawn') to simulate the behavior of windows.

What happens in the spawn-mode? Let's add some sleeps, so we can investigate the processes:

#bomb.py
import multiprocessing as mp
import sys
import time

def worker():
    time.sleep(50)
    print('Worker')
    return

if __name__ == '__main__':
        print("Starting...")
        time.sleep(20)
        mp.set_start_method('spawn') ## use spawn!
        jobs = []
        for i in range(5):
            p = mp.Process(target=worker)
            jobs.append(p)
            p.start()

By using pgrep python we can see that at first there is only one-python process, then 7(!) different pids. We can see the command-line arguments via cat /proc/<pid>/cmdline. 5 of the new processes have command line

-c "from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=11)" --multiprocessing-fork

and one:

-c "from multiprocessing.semaphore_tracker import main;main(4)"

That means, the parent process starts 6 new python interpreter instances and every newly started interpreter executes a code sent from the parent via the command line options, the information is shared via pipes. One of these 6 python-instances is a tracker, which observes the whole thing.

Ok, what happens if cythonized+embeded? The same as with the normal python, the only difference is that the bomb-executable is started instead of python. But differently as the python-interpreter, it doesn't execute/isn't aware of the command line arguments, so the main function runs over and over and over again.

There is an easy fix: let the bomb-exe to start the python interpreter

 ...
 if __name__ == '__main__':
    mp.set_executable(<PATH TO PYTHON>)
 ....

Now the bomb is no longer a multiprocessing bomb!

However, the goal is probably not to have a python-interpreter around, so we need to make our program aware of possible command lines:

import re
......
if __name__ == '__main__':
    if len(sys.argv)==3:  # should start in semaphore_tracker mode
        nr=list(map(int, re.findall(r'\d+',sys.argv[2])))
        sys.argv[1]='--multiprocessing-fork'   # this canary is needed for multiprocessing module to work
        from multiprocessing.semaphore_tracker import main;main(nr[0])

    elif len(sys.argv)>3: # should start in slave mode
        fd, pipe=map(int, re.findall(r'\d+',sys.argv[2]))
        print("I'm a slave!, fd=%d, pipe=%d"%(fd,pipe))
        sys.argv[1]='--multiprocessing-fork'   # this canary is needed for multiprocessing module to work
        from multiprocessing.spawn import spawn_main;
        spawn_main(tracker_fd=fd, pipe_handle=pipe)

    else: #main mode
        print("Starting...")
        mp.set_start_method('spawn')
        jobs = []
        for i in range(5):
            p = mp.Process(target=worker)
            jobs.append(p)
            p.start()

Now, our bomb doesn't need a stand-alone python-interpreter and stops after the workers are done. Please note the following:

The way it is decide, in which mode bomb should be started is not very error-safe, but I hope you get the gist

--multiprocessing-fork is just a canary, it doesn't do anything it only must be there, see here.

NB: The changed code can be also used with python, because after executing "from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=5, pipe_handle=11)" --multiprocessing-fork python changes the sys.argv so the code no longer sees the original command line and len(sys.argv) is 1.


问:
set airflow schedule interval
I have created tasks in airflow which I scheduled to run hourly and start_date is set to 2016-11-16

```<code>default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2016, 11, 16),
    'email': ['airflow@airflow.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
    # 'queue': 'bash_queue',
    # 'pool': 'backfill',
    # 'priority_weight': 10,
    # 'end_date': datetime(2016, 1, 1),
}

dag = DAG('test_hourly_job', default_args=default_args,schedule_interval="@hourly")
</code>```

I kicked off airflow at current time which is 10:00 AM and I could see Airflow is running it from  00:00 AM, then 01:00 AM and so on:

```<code>INFO - Executing command: airflow run test_hourly_job task1 2016-11-16T00:00:00 --local -sd DAGS_FOLDER/test_airflow.py
........
........
INFO - Executing command: airflow run test_hourly_job task1 2016-11-16T01:00:00 --local -sd DAGS_FOLDER/test_airflow.py
.......
.......
</code>```

How to configure airflow to start say from current time and run hourly going forward, instead of starting from 00:00 ?

答:
Airflow provides gem of an operator called LatestOnlyOperator to skip tasks that are not being run during the most recent scheduled run for a DAG. The LatestOnlyOperator skips all immediate downstream tasks, and itself, if the time right now is not between its execution_time and the next scheduled execution_time. This operator reduces wastes of CPU cycles.

```<code>default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2016, 11, 16),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5)
}

dag = DAG('test_hourly_job', default_args=default_args,schedule_interval="@hourly")

latest_only = LatestOnlyOperator(task_id='latest_only', dag=dag)

task1 = DummyOperator(task_id='task1', dag=dag)

latest_only >> task
</code>```

Latest_only should always be in the upstream of the task that you want to skip.
The advantage of latest_only operator is that whenever you restart the dag it will skip the tasks for all the previous times and run the current dag.

Also its better not to hard code the start time. Instead put:

```<code>from datetime import datetime, timedelta

START_DATE = datetime.combine(datetime.today() - timedelta(1), datetime.min.time())
</code>```

Title: set airflow schedule interval

Body:
I have created tasks in airflow which I scheduled to run hourly and start_date is set to 2016-11-16

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2016, 11, 16),
    'email': ['airflow@airflow.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
    # 'queue': 'bash_queue',
    # 'pool': 'backfill',
    # 'priority_weight': 10,
    # 'end_date': datetime(2016, 1, 1),
}

dag = DAG('test_hourly_job', default_args=default_args,schedule_interval="@hourly")

I kicked off airflow at current time which is 10:00 AM and I could see Airflow is running it from  00:00 AM, then 01:00 AM and so on:

INFO - Executing command: airflow run test_hourly_job task1 2016-11-16T00:00:00 --local -sd DAGS_FOLDER/test_airflow.py
........
........
INFO - Executing command: airflow run test_hourly_job task1 2016-11-16T01:00:00 --local -sd DAGS_FOLDER/test_airflow.py
.......
.......

How to configure airflow to start say from current time and run hourly going forward, instead of starting from 00:00 ?

Body:
Airflow provides gem of an operator called LatestOnlyOperator to skip tasks that are not being run during the most recent scheduled run for a DAG. The LatestOnlyOperator skips all immediate downstream tasks, and itself, if the time right now is not between its execution_time and the next scheduled execution_time. This operator reduces wastes of CPU cycles.

default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2016, 11, 16),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5)
}

dag = DAG('test_hourly_job', default_args=default_args,schedule_interval="@hourly")

latest_only = LatestOnlyOperator(task_id='latest_only', dag=dag)

task1 = DummyOperator(task_id='task1', dag=dag)

latest_only >> task

Latest_only should always be in the upstream of the task that you want to skip.
The advantage of latest_only operator is that whenever you restart the dag it will skip the tasks for all the previous times and run the current dag.

Also its better not to hard code the start time. Instead put:

from datetime import datetime, timedelta

START_DATE = datetime.combine(datetime.today() - timedelta(1), datetime.min.time())


问:
convert days hours minutes seconds to iso 8601
here is my script

```<code>var specialDate = "<?php echo trim(date('Y-m-d\TH:i:s',strtotime($time[1])));?>";
    var countDownDate = new Date(specialDate).getTime();
var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance =   countDownDate -  now;

var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

var countdown = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
</code>```

the above code is working perfectly fine on all the browsers except for safari.
after googling I came to know I need to convert this to iso 8601 compliant to work for safari (currently it is showing nand nanh nanm nans error on safari browser iphone 6 )

I is the detail of of my phone

EDIT:
here is page source

答:
try changing the following:

```<code>var specialDate = "<?php echo trim(date('Y-m-d\TH:i:s',strtotime($time[1])));?>";
    var countDownDate = new Date(specialDate).getTime();
</code>```

To:

```<code>// echo php timestamp
var specialDate = <?php echo strtotime($time[1]);?>;
// multiply by 1000 for equivalent of `Date.getTime()`
var countDownDate = specialDate * 1000;
</code>```

Body:
here is my script

var specialDate = "<?php echo trim(date('Y-m-d\TH:i:s',strtotime($time[1])));?>";
    var countDownDate = new Date(specialDate).getTime();
var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance =   countDownDate -  now;

var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

var countdown = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

the above code is working perfectly fine on all the browsers except for safari.
after googling I came to know I need to convert this to iso 8601 compliant to work for safari (currently it is showing nand nanh nanm nans error on safari browser iphone 6 )

I is the detail of of my phone

EDIT:
here is page source

Body:
try changing the following:

var specialDate = "<?php echo trim(date('Y-m-d\TH:i:s',strtotime($time[1])));?>";
    var countDownDate = new Date(specialDate).getTime();

To:

// echo php timestamp
var specialDate = <?php echo strtotime($time[1]);?>;
// multiply by 1000 for equivalent of `Date.getTime()`
var countDownDate = specialDate * 1000;


问:
Trying to access hash table from finished software
At my company, we bought a huge software package (written in C#) which is currently being rolled out in my department.  Because of trade secret reasons my company opted to not get the service contract with the developer so now I’m in the position of learning the software/hardware on my own along with all the troubleshooting.  While doing this I made a change at some point which caused the below error which I haven’t been able to undo.  When trying to generate a report I get the following error message.

I’m trying to view the contents of the hash table so that I can delete what is reserving the key “1” or so that I can return whatever was changed so that when I generate a report it would try to enter a different key.  Do you have any advice on where the hash table is located or how I can read it?  I’ve seen other posts on how to read hash tables.  I’m just having trouble finding it.

I have access to most if not all the .h and .dll files and so I’ve been exploring those.  I took a few C++ courses a few years ago and so I have a general idea on how to read the code.

Is the hash table in the executable?  Where would it be located?  I couldn’t find it as a .txt or .mdb file.  Once I find it, how would I access it?  I could post some of the code if that would help, but I’m not sure what parts of the code would be useful to you at this point.  Any help would be greatly appreciated.  Thanks in advance.

答:
You are seriously out of luck, if you don't have the source code for that DTL3DTDTP thing - you'll have to reverse-engineer it to understand what happens. If you can connect to the running app from Visual Studio and intercept the exception (with "Just my code" disabled) and you have Reflector add-in installed you will be (probably) able to look at the reassembled source and call stack, maybe even variables. That HashTable is either a field of DTL3DTDTP or a local variable or something else... what and when adds the second (and the first) duplicate key to it is anyone guess... in the worst case you can reassemble the whole product and spend a month reading the code.

Of course all that will be blatantly illegal if the package is commercial - IP owners don't like reverse-engineers.

If you do have the source, just debug it.


问:
How do I track the time a person goes to a place?
I'm working on creating a database for a gym to track the members info. I want to be able to track the times that people go so you will be able to see when it is busiest. I'm not sure how to go about this. Do I need to make a new table for the information of when a member goes or do I add it into the members or gyms table?</p>

答:
Create a visits table with the following columns

visitId

memberId

gymId

entryTime

exitTime

The GymId column may not be required if your member is linked to a gym but it depends on your requirements


问:
Calculate prior ties individuals have had with other team members prior to current team
I want to calculate the number of prior ties each member has had with other team members prior to the formation of the current team.

I have the following table

TeamId UserId Date
1     100   2/1/2017
1     101   2/1/2017
1     102   2/1/2017
2     100   2//1/2016
2     105   2//1/2016
3        100   2//1/2015
3     101   2//1/2015
3        102   2//1/2015
3        105   2//1/2015
3     106   2//1/2015
4     101   1/3/2015
4     102   1/3/2015
4     105   1/3/2015
4        106   1/3/2015```
</div>
</div>
</p>

<p>I want to get the following table</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>TeamId number of previous collaborations
1        4
2         1
3        6
4         0</code>```

For example for team 1:
user 100 has collaborated with user 101 once in team 3 and with user 102 once  in team 3therefore = 1+1=2
user 101 has collaborated with user 102 twice (once in team 3 and once in team 4)= 1+1=2

so the number of previous collaborations for this team is 4.

I do not know how to write the code. any help is appreciated

SELECT [TeamId],
COUNT( SELECT [Date] FROM [submissions] s1
       WHERE s.[UserId] = [submissions].[UserId]
       AND [Date]< [submissions].[Date]
       ORDER BY [DateSubmitted] DESC) as Num_Collaborations
     )
FROM [submissions]```

答:
It's a challenging problem. You have to include the same table 4 times in the query:

```<code>select t1.TeamId, t1.UserId, t2.TeamId as OtherTeam, t3.UserId as Collaborator
from @table t1, @table t2, @table t3, @table t4
where t1.UserId = t2.UserId and
      t2.TheDate < t1.TheDate and
      t3.TeamId = t2.TeamId and
      t4.TeamId = t1.TeamId and
      t4.UserId = t3.UserId and
      t4.UserId < t1.UserId
</code>```

http://rextester.com/LHZS40204

(then you can group by and count to get the final result)

Body:
I want to calculate the number of prior ties each member has had with other team members prior to the formation of the current team.

I have the following table

TeamId UserId Date
1     100   2/1/2017
1     101   2/1/2017
1     102   2/1/2017
2     100   2//1/2016
2     105   2//1/2016
3        100   2//1/2015
3     101   2//1/2015
3        102   2//1/2015
3        105   2//1/2015
3     106   2//1/2015
4     101   1/3/2015
4     102   1/3/2015
4     105   1/3/2015
4        106   1/3/2015

I want to get the following table

TeamId number of previous collaborations
1        4
2         1
3        6
4         0

For example for team 1:
user 100 has collaborated with user 101 once in team 3 and with user 102 once  in team 3therefore = 1+1=2
user 101 has collaborated with user 102 twice (once in team 3 and once in team 4)= 1+1=2

so the number of previous collaborations for this team is 4.

I do not know how to write the code. any help is appreciated

SELECT [TeamId],
COUNT( SELECT [Date] FROM [submissions] s1
       WHERE s.[UserId] = [submissions].[UserId]
       AND [Date]< [submissions].[Date]
       ORDER BY [DateSubmitted] DESC) as Num_Collaborations
     )
FROM [submissions]

Body:
It's a challenging problem. You have to include the same table 4 times in the query:

select t1.TeamId, t1.UserId, t2.TeamId as OtherTeam, t3.UserId as Collaborator
from @table t1, @table t2, @table t3, @table t4
where t1.UserId = t2.UserId and
      t2.TheDate < t1.TheDate and
      t3.TeamId = t2.TeamId and
      t4.TeamId = t1.TeamId and
      t4.UserId = t3.UserId and
      t4.UserId < t1.UserId

http://rextester.com/LHZS40204

(then you can group by and count to get the final result)