问:
Return button to previous activity with BaseAdapter
I currently have two activities doing HTTP requests.

The first activity contains a CustomList class extends BaseAdapter.

On the second, there is a previous button allowing me to return to the first activity.

Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.

My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)

I put all the code because I really don't know how can I do this :/

First activity:

```<code>public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();

private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;

int id = 0;
String infos_user;
String email;
String password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.get_children_list);

    infos_user = (String) getIntent().getSerializableExtra("infos_user");

    Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
    intent.putExtra("username", infos_user);

    btn_previous = (Button) findViewById(R.id.btn_previous);

    btn_previous.setOnClickListener(this);

    tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);

    tv_signin_success.setText("Bonjour " + infos_user + "!");

    itemsListView  = (ListView)findViewById(R.id.list_view_children);

    new GetChildrenAsync().execute();
}

class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>>  {

    private Dialog loadingDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
    }

    @Override
    protected ArrayList<Child> doInBackground(String... params) {

        int age = 0;
        email = (String) getIntent().getSerializableExtra("email");
        password = (String) getIntent().getSerializableExtra("password");
        String first_name = null;
        String last_name = null;

        try {

            SendRequest sr = new SendRequest();
            String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);

            String jsonResult = "{ \"children\":" + result + "}";

            Log.d("result1", jsonResult);

            //Manage JSON result
            JSONObject jsonObject = new JSONObject(jsonResult);
            JSONArray childrenArray = jsonObject.getJSONArray("children");

            for (int i = 0; i < childrenArray.length(); ++i) {
                JSONObject child = childrenArray.getJSONObject(i);
                id = child.getInt("id");
                first_name = child.getString("first_name");
                last_name = child.getString("last_name");
                age = child.getInt("age");

                String name = first_name + " " + last_name;

                childrenImeList.add(new Child(id,name,age));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return childrenImeList;

    }

    @Override
    protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
        loadingDialog.dismiss();
        if(childrenListInformation.size() > 0) {
            CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
            itemsListView.setAdapter(adapter);
        }
        else{
            Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
        }
    }
}
}
</code>```

BaseAdapter:

```<code>public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;

public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
    this.context = context;
    this.children = children;
}

@Override
public int getCount() {
    return children.size(); //returns total item in the list
}

@Override
public Object getItem(int position) {
    return children.get(position); //returns the item at the specified position
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view;

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.layout_list_view_children,null);
        childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
        childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
        btnChoose = (Button) view.findViewById(R.id.btn_choose);
        btnChoose.setOnClickListener(this);

    } else {
        view = convertView;
    }

    btnChoose.setTag(position);

    Child currentItem = (Child) getItem(position);
    childrenName.setText(currentItem.getChildName());
    childrenAge.setText(currentItem.getChildAge() + "");

    return view;
}

@Override
public void onClick(View v) {
    Integer position = (Integer) v.getTag();
    Child item = (Child) getItem(position);
    String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
    String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");

    Intent intent = new Intent(context, GetLearningGoalsList.class);
    intent.putExtra("idChild",item.getId());
    intent.putExtra("email",email);
    intent.putExtra("password",password);

    context.startActivity(intent);

}
}
</code>```

Second Activity:

```<code>public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();

private Button btn_previous;
private ListView itemsListView;

String email;
String password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.get_learning_goals_list);

    btn_previous = (Button) findViewById(R.id.btn_previous);

    btn_previous.setOnClickListener(this);

    itemsListView  = (ListView)findViewById(R.id.list_view_learning_goals);

    new GetLearningGoalsAsync().execute();
}

@Override
public void onClick(View v) {
    Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(myIntent);
    return;
}

class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>>  {

    private Dialog loadingDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
    }

    @Override
    protected ArrayList<LearningGoal> doInBackground(String... params) {

        int id = 0;
        email = (String) getIntent().getSerializableExtra("email");
        password = (String) getIntent().getSerializableExtra("password");
        int idChild = (int) getIntent().getSerializableExtra("idChild");
        String name = null;
        String start_date = null;
        String end_date = null;

        try {

            List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
            parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));

            SendRequest sr = new SendRequest();
            String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);

            String jsonResult = "{ \"learningGoals\":" + result + "}";

            Log.d("result1", jsonResult);

            //Manage JSON result
            JSONObject jsonObject = new JSONObject(jsonResult);
            JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");

            for (int i = 0; i < learningGoalsArray.length(); ++i) {
                JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
                id = learningGoal.getInt("id");
                name = learningGoal.getString("name");
                start_date = learningGoal.getString("start_date");
                end_date = learningGoal.getString("end_date");

                childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return childrenLearningList;

    }

    @Override
    protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
        loadingDialog.dismiss();
        if(learningListInformation.size() > 0) {
            CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
            itemsListView.setAdapter(adapter);
        }
        else{
            Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
        }
    }
}
}
</code>```

Thanks for your help.

答:
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow

replace in GetLearningGoalsList

```<code>@Override
public void onClick(View v) {
    Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(myIntent);
    return;
}
</code>```

with

```<code>@Override
public void onClick(View v) {
   finish();
}
</code>```

Body:
I currently have two activities doing HTTP requests.

The first activity contains a CustomList class extends BaseAdapter.

On the second, there is a previous button allowing me to return to the first activity.

Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.

My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)

I put all the code because I really don't know how can I do this :/

First activity:

public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();

private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;

int id = 0;
String infos_user;
String email;
String password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.get_children_list);

    infos_user = (String) getIntent().getSerializableExtra("infos_user");

    Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
    intent.putExtra("username", infos_user);

    btn_previous = (Button) findViewById(R.id.btn_previous);

    btn_previous.setOnClickListener(this);

    tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);

    tv_signin_success.setText("Bonjour " + infos_user + "!");

    itemsListView  = (ListView)findViewById(R.id.list_view_children);

    new GetChildrenAsync().execute();
}

class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>>  {

    private Dialog loadingDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
    }

    @Override
    protected ArrayList<Child> doInBackground(String... params) {

        int age = 0;
        email = (String) getIntent().getSerializableExtra("email");
        password = (String) getIntent().getSerializableExtra("password");
        String first_name = null;
        String last_name = null;

        try {

            SendRequest sr = new SendRequest();
            String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);

            String jsonResult = "{ \"children\":" + result + "}";

            Log.d("result1", jsonResult);

            //Manage JSON result
            JSONObject jsonObject = new JSONObject(jsonResult);
            JSONArray childrenArray = jsonObject.getJSONArray("children");

            for (int i = 0; i < childrenArray.length(); ++i) {
                JSONObject child = childrenArray.getJSONObject(i);
                id = child.getInt("id");
                first_name = child.getString("first_name");
                last_name = child.getString("last_name");
                age = child.getInt("age");

                String name = first_name + " " + last_name;

                childrenImeList.add(new Child(id,name,age));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return childrenImeList;

    }

    @Override
    protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
        loadingDialog.dismiss();
        if(childrenListInformation.size() > 0) {
            CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
            itemsListView.setAdapter(adapter);
        }
        else{
            Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
        }
    }
}
}

BaseAdapter:

public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;

public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
    this.context = context;
    this.children = children;
}

@Override
public int getCount() {
    return children.size(); //returns total item in the list
}

@Override
public Object getItem(int position) {
    return children.get(position); //returns the item at the specified position
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view;

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.layout_list_view_children,null);
        childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
        childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
        btnChoose = (Button) view.findViewById(R.id.btn_choose);
        btnChoose.setOnClickListener(this);

    } else {
        view = convertView;
    }

    btnChoose.setTag(position);

    Child currentItem = (Child) getItem(position);
    childrenName.setText(currentItem.getChildName());
    childrenAge.setText(currentItem.getChildAge() + "");

    return view;
}

@Override
public void onClick(View v) {
    Integer position = (Integer) v.getTag();
    Child item = (Child) getItem(position);
    String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
    String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");

    Intent intent = new Intent(context, GetLearningGoalsList.class);
    intent.putExtra("idChild",item.getId());
    intent.putExtra("email",email);
    intent.putExtra("password",password);

    context.startActivity(intent);

}
}

Second Activity:

public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();

private Button btn_previous;
private ListView itemsListView;

String email;
String password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.get_learning_goals_list);

    btn_previous = (Button) findViewById(R.id.btn_previous);

    btn_previous.setOnClickListener(this);

    itemsListView  = (ListView)findViewById(R.id.list_view_learning_goals);

    new GetLearningGoalsAsync().execute();
}

@Override
public void onClick(View v) {
    Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(myIntent);
    return;
}

class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>>  {

    private Dialog loadingDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
    }

    @Override
    protected ArrayList<LearningGoal> doInBackground(String... params) {

        int id = 0;
        email = (String) getIntent().getSerializableExtra("email");
        password = (String) getIntent().getSerializableExtra("password");
        int idChild = (int) getIntent().getSerializableExtra("idChild");
        String name = null;
        String start_date = null;
        String end_date = null;

        try {

            List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
            parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));

            SendRequest sr = new SendRequest();
            String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);

            String jsonResult = "{ \"learningGoals\":" + result + "}";

            Log.d("result1", jsonResult);

            //Manage JSON result
            JSONObject jsonObject = new JSONObject(jsonResult);
            JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");

            for (int i = 0; i < learningGoalsArray.length(); ++i) {
                JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
                id = learningGoal.getInt("id");
                name = learningGoal.getString("name");
                start_date = learningGoal.getString("start_date");
                end_date = learningGoal.getString("end_date");

                childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return childrenLearningList;

    }

    @Override
    protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
        loadingDialog.dismiss();
        if(learningListInformation.size() > 0) {
            CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
            itemsListView.setAdapter(adapter);
        }
        else{
            Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
        }
    }
}
}

Thanks for your help.

Body:
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow

replace in GetLearningGoalsList

@Override
public void onClick(View v) {
    Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(myIntent);
    return;
}

with

@Override
public void onClick(View v) {
   finish();
}


来源: stackexchange

问:
Image cannot be located when referenced in other UWP project
We wish to share visual assets between two UWP projects in a solution. The visual assets are in a UWP class library which is also in the same solution.

We can deploy a project when the visual assets are included in the same project by referencing them in Package.appxmanifest like this

Assets\SplashScreen1240x600.png

but if we try to reference visual assets in the class library like this

OtherProect.Assets\SplashScreen1240x600.png

we get this error

the splash screen image [SplashScreen1240x600.png] cannot be located.

How do we reference visual assets that are in a class library?

答:
You could reference UWP class library which is also in the same solution. if you want to reference visual assets in the class library please write your path like the following.</p>

```<code>OtherProect\Assets\SplashScreen1240x600.png
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You could reference UWP class library which is also in the same solution. if you want to reference visual assets in the class library please write your path like the following.

OtherProect\Assets\SplashScreen1240x600.png


问:
Find key different from given key when iterating list of dictionaries
I have list of dictionaries and in each one of them the key site exists.
So in other words, this code returns True:

```<code>all('site' in site for site in summary)
</code>```

Question is, what will be the pythonic way to iterate over the list of dictionaries and return True if a key different from site exists in any of the dictionaries?

Example: in the following list I would like to return True because of the existence of cost in the last dictionary BUT, I can't tell what will be the other key, it can be cost as in the example and it can be other strings; random keys for that matter.

```<code>[
    {"site": "site_A"},
    {"site": "site_B"},
    {"site": "site_C", "cost": 1000}
]
</code>```

答:
If all dictionaries have the key site, the dictionaries have a length of at least 1. The presence of any other key would increase the dictionary size to be greater than 1, test for that:

```<code>any(len(d) > 1 for d in summary)
</code>```

Body:
I have list of dictionaries and in each one of them the key site exists.
So in other words, this code returns True:

all('site' in site for site in summary)

Question is, what will be the pythonic way to iterate over the list of dictionaries and return True if a key different from site exists in any of the dictionaries?

Example: in the following list I would like to return True because of the existence of cost in the last dictionary BUT, I can't tell what will be the other key, it can be cost as in the example and it can be other strings; random keys for that matter.

[
    {"site": "site_A"},
    {"site": "site_B"},
    {"site": "site_C", "cost": 1000}
]

Body:
If all dictionaries have the key site, the dictionaries have a length of at least 1. The presence of any other key would increase the dictionary size to be greater than 1, test for that:

any(len(d) > 1 for d in summary)


问:
Toolkit for DSL / custom types in C#?
So, I've got a C# application with a custom types hierarchy that's ~4 layers deep.

This layering exists to provide a clean implementation of data validation and change event propagation.

An example would be:
DocumentNameValue -> NameValue - > StringValue -> BaseDataValue.

The system works fine, but given all the layers of indirection, performance surfers.  In absolute terms, it's not a huge hit, but it does add up.

To clarify, the performance issue seems to be as a result of the nested calls that happen on data access.

For instance, calling DocumentNameValue.setValue("test.doc") will result in each layer of hierarchy running certain validation tests on the input.  These start at the base and move up.  Various events are also fired along the way.  The value is actually "stored" at the base of the hierarchy, if that makes any sense.

Since all I've really done is define a strict hierarchy of types, does there exist a recommended method to do either of:

Transform this C# code in to a "flat" high performance equivalent? (Run-time or Compile-time)

Or, perhaps better, construct a DSL that would just spit out the equivalent list of types/objects?

The overall goal is twofold:  Have strong types that are specific to my application problem domain, provide a clean place to put my validation rules.

Can anyone provide some tips / suggestions?  Am I doing this all wrong?

Thank you

答:
My first instinct is to question how you know this is the reason for your performance hit.  Have you ran a profiler?

My second question is to ask for a code-sample.  Is this layering reflected via OOP (inheritance)?

From what I understand you're using different Types to represent different concerns--and this is good.  You've built something like ViewModel / Model / DataModel, which is quite standard.

Given your comment, I suggest you download a trial of ANTS Performance Profiler and use it to profile the slow implementation; it will tell you precisely what methods are taking the longest, and will let you quantify results of changes.

I wouldn't suggest tearing apart your layered approach just yet, unless the application is very simple.  Learning how to cleanly implement a layered system can pay off with your sanity later.

ContentLicense: CC BY-SA 2.5

Title: Toolkit for DSL / custom types in C#?


问:
C program recursive call to main() with and without parameters
Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?

```<code>#include <stdio.h>
int main()
{
    static int i = 2;
    if (i<7)
    {
        main();
        printf("%d ", i);
        i++;
        //main(10);
    }
}
</code>```

-

```<code>#include <stdio.h>
int main()
{
    static int i = 5;
    if (--i)
    {
     //main();
     printf("%d ", i);
     main(10);
    }
}
</code>```

答:
In the first case, i is never incremented, hence, the main keeps getting called and soon enough there is no more stack memory available to the program.

In the second case, the last updated value of i is intact throughout the lifetime of i. As i is static, program is referring to the same  memory address on all the iterations. While printing i you see the last updated value, that is 0, as output.

Body:
Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?

#include <stdio.h>
int main()
{
    static int i = 2;
    if (i<7)
    {
        main();
        printf("%d ", i);
        i++;
        //main(10);
    }
}

-

#include <stdio.h>
int main()
{
    static int i = 5;
    if (--i)
    {
     //main();
     printf("%d ", i);
     main(10);
    }
}


问:
Did the author make a mistake in explaining stack and heap in C++ or am I misreading something?
Here is the code:

```<code>int main()
{
    using namespace std;
    int nights = 1001;
    int * pt = new int; // allocate space for an int
    *pt = 1001;         // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;

    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl;
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;

    return 0;
}
</code>```

Now here is the author's note about the code:

Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.

Initial Question:

Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

Am I missing something here? Thank you very much in advance for your inputs.

Revised Question/Follow-up based on the hold:

This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:

I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.

So, it confused me when he wrote that the variable pd has is value
  stored in the stack, but again how is that possible if the variable
  was create during "runtime" with the keyword new, so it should be
  in the heap, not the stack.

Please try to use the code above as the reference and in particular the **variables (nights, pd, and pt) in your answer so that I can understand it from that code's perspective.

答:
The pointer variables pt and pd are stored on the stack. The values they point at, allocated with new, are stored on the heap.

If I write a sign with an arrow labelled "lake", it doesn't mean that the sign itself is a lake, nor that it must be mounted in a lake. Rather, it should be mounted on solid ground, pointing in the direction of the lake.

ContentLicense: CC BY-SA 4.0

Body:
Here is the code:

int main()
{
    using namespace std;
    int nights = 1001;
    int * pt = new int; // allocate space for an int
    *pt = 1001;         // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;

    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl;
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;

    return 0;
}

Now here is the author's note about the code:

Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.

Initial Question:

Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

Am I missing something here? Thank you very much in advance for your inputs.

Revised Question/Follow-up based on the hold:

This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:

I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.

So, it confused me when he wrote that the variable pd has is value
  stored in the stack, but again how is that possible if the variable
  was create during "runtime" with the keyword new, so it should be
  in the heap, not the stack.

Please try to use the code above as the reference and in particular the **variables (nights, pd, and pt) in your answer so that I can understand it from that code's perspective.


问:
Achieve a square aligned with 3 rows with bootstrap
I'm trying to get this result with boostrap :

The idea would be that : the black square stay as a square, even with the right "rows" being resized (on mobile for example)
And the red rows would be having the same height/width (I failed that on the image, just a quick paint mockup)

I'd love to show you some code that would be a starting point but after a few hours I'm unable to achieve this effect...

I found that template that use this kind of structure :
Gridus

答:
You mean something like this? I didn't bother with the borders, but I can put it if you like

.left-div {
  background-color: pink;
  height: 120px;
  width: 120px;
  float:left;
}

.right-div {
  background-color: red;
  height: 120px;
  float:left;
}
.col-xs-12{
  height: 40px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div class="left-div">Column 1</div>
    <div class="right-div">
      <div class="row">
        <div class="col-xs-12">Row 1</div>
        <div class="col-xs-12">Row 2</div>
        <div class="col-xs-12">Row 3</div>
      </div>
    </div>
  </div>
</div></code>```

Body:
You mean something like this? I didn't bother with the borders, but I can put it if you like

.left-div {
  background-color: pink;
  height: 120px;
  width: 120px;
  float:left;
}

.right-div {
  background-color: red;
  height: 120px;
  float:left;
}
.col-xs-12{
  height: 40px;

}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div class="left-div">Column 1</div>
    <div class="right-div">
      <div class="row">
        <div class="col-xs-12">Row 1</div>
        <div class="col-xs-12">Row 2</div>
        <div class="col-xs-12">Row 3</div>
      </div>
    </div>
  </div>
</div>


问:
Android ) java.lang.NoClassDefFoundError: com.google.android.gms.internal.zzno
I fixed again and again but the final error I'm having is:

```<code>java.lang.NoClassDefFoundError: com.google.android.gms.internal.zzno
</code>```

My build.gradle is below:

```<code>buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'
    classpath 'com.google.gms:google-services:1.5.0-beta2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
    repositories {
        jcenter()
    }
}

subprojects {
    repositories {
        mavenCentral()
        maven { url 'http://devrepo.kakao.com:8088/nexus/content/groups/public/' }
    }
}
</code>```

And another build.gradle is below :

```<code>    apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

dexOptions {
    javaMaxHeapSize "4g"
}

defaultConfig {
    applicationId "com.example.min.photozzle"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:multidex:1.0.1'

    compile group: 'com.kakao.sdk', name: 'kakaolink', version: '1.1.0'
    compile group: 'com.kakao.sdk', name: 'kakaostory', version: '1.1.0'// 카카오스토리 sdk를 사용하기 위해 필요.
    compile group: 'com.kakao.sdk', name: 'kakaotalk', version: '1.1.0'    // 카카오톡 sdk를 사용하기 위해 필요.
    compile group: 'com.kakao.sdk', name: 'push', version: '1.1.0'    // push sdk를 사용하기 위해 필요.

    compile 'com.squareup.retrofit:retrofit:1.9.0'
    //compile 'com.google.android.gms:play-services-gcm:8.3.0'
    compile "com.google.android.gms:play-services:8.3.0"
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'

}
</code>```

Fianlly my manifest is below :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.min.photozzle" >

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<permission
    android:name="com.example.min.photozzle.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.min.photozzle.permission.C2D_MESSAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <activity android:name=".StoryGame" />
    <activity android:name=".StoryMode" />
    <activity android:name=".CustomMode" />
    <activity android:name=".Title" />
    <activity android:name=".Splash" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>

            <!-- Receives the actual messages. -->
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <!-- Receives the registration id. -->
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="com.example.min.photozzle" />

        </intent-filter>
    </receiver>

    <service
        android:name=".GCM.RegistrationIntentService"
        android:exported="false" >
    </service>

    <service
        android:name=".GCM.MyInstanceIDListenerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID"/>
        </intent-filter>
    </service>

    <service
        android:name=".GCM.MyGcmListenerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

    <meta-data
        android:name="com.kakao.sdk.AppKey"
        android:value="@string/kakao_app_key" />
</application>
</code>```

And our error log is below:

```<code>12-08 20:16:32.306  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzd', referenced from method com.google.android.gms.measurement.internal.zzt.zzBK
12-08 20:16:32.306  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzd', referenced from method com.google.android.gms.measurement.internal.zzt.zzBK
12-08 20:16:32.311  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzc', referenced from method com.google.android.gms.measurement.internal.zzt.zzBK
12-08 20:16:32.311  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzd', referenced from method com.google.android.gms.measurement.internal.zzt.zza
12-08 20:16:32.381  19305-19305/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.min.photozzle, PID: 19305
    java.lang.NoClassDefFoundError: com.google.android.gms.internal.zzno
            at com.google.android.gms.measurement.internal.zzx.zzj(Unknown Source)
            at com.google.android.gms.measurement.internal.zzt.<init>(Unknown Source)
            at com.google.android.gms.measurement.internal.zzx.zzBQ(Unknown Source)
            at com.google.android.gms.measurement.internal.zzt.zzaU(Unknown Source)
            at com.google.android.gms.measurement.AppMeasurementContentProvider.onCreate(Unknown Source)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1591)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1562)
            at android.app.ActivityThread.installProvider(ActivityThread.java:5233)
            at android.app.ActivityThread.installContentProviders(ActivityThread.java:4828)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4711)
            at android.app.ActivityThread.access$1600(ActivityThread.java:175)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5602)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)
</code>```

I googled it for an hour and introduced that but that doesn't work well for me.
Am I'm trying to use GCM for my application.

答:
I encounter the same issue. And add content in following file into proguard-project.txt helps. Please give it a try.

https://github.com/google/google-api-java-client-samples/blob/master/calendar-android-sample/proguard-google-api-client.txt

Body:
I fixed again and again but the final error I'm having is:

java.lang.NoClassDefFoundError: com.google.android.gms.internal.zzno

My build.gradle is below:

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'
    classpath 'com.google.gms:google-services:1.5.0-beta2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
    repositories {
        jcenter()
    }
}

subprojects {
    repositories {
        mavenCentral()
        maven { url 'http://devrepo.kakao.com:8088/nexus/content/groups/public/' }
    }
}

And another build.gradle is below :

    apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

dexOptions {
    javaMaxHeapSize "4g"
}

defaultConfig {
    applicationId "com.example.min.photozzle"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:multidex:1.0.1'

    compile group: 'com.kakao.sdk', name: 'kakaolink', version: '1.1.0'
    compile group: 'com.kakao.sdk', name: 'kakaostory', version: '1.1.0'// 카카오스토리 sdk를 사용하기 위해 필요.
    compile group: 'com.kakao.sdk', name: 'kakaotalk', version: '1.1.0'    // 카카오톡 sdk를 사용하기 위해 필요.
    compile group: 'com.kakao.sdk', name: 'push', version: '1.1.0'    // push sdk를 사용하기 위해 필요.

    compile 'com.squareup.retrofit:retrofit:1.9.0'
    //compile 'com.google.android.gms:play-services-gcm:8.3.0'
    compile "com.google.android.gms:play-services:8.3.0"
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'

}

Fianlly my manifest is below :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.min.photozzle" >

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<permission
    android:name="com.example.min.photozzle.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.min.photozzle.permission.C2D_MESSAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <activity android:name=".StoryGame" />
    <activity android:name=".StoryMode" />
    <activity android:name=".CustomMode" />
    <activity android:name=".Title" />
    <activity android:name=".Splash" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>

            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="com.example.min.photozzle" />

        </intent-filter>
    </receiver>

    <service
        android:name=".GCM.RegistrationIntentService"
        android:exported="false" >
    </service>

    <service
        android:name=".GCM.MyInstanceIDListenerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID"/>
        </intent-filter>
    </service>

    <service
        android:name=".GCM.MyGcmListenerService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

    <meta-data
        android:name="com.kakao.sdk.AppKey"
        android:value="@string/kakao_app_key" />
</application>

And our error log is below:

12-08 20:16:32.306  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzd', referenced from method com.google.android.gms.measurement.internal.zzt.zzBK
12-08 20:16:32.306  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzd', referenced from method com.google.android.gms.measurement.internal.zzt.zzBK
12-08 20:16:32.311  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzc', referenced from method com.google.android.gms.measurement.internal.zzt.zzBK
12-08 20:16:32.311  19305-19305/? E/dalvikvm﹕ Could not find class 'com.google.android.gms.internal.zzqq$zzd', referenced from method com.google.android.gms.measurement.internal.zzt.zza
12-08 20:16:32.381  19305-19305/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.min.photozzle, PID: 19305
    java.lang.NoClassDefFoundError: com.google.android.gms.internal.zzno
            at com.google.android.gms.measurement.internal.zzx.zzj(Unknown Source)
            at com.google.android.gms.measurement.internal.zzt.<init>(Unknown Source)
            at com.google.android.gms.measurement.internal.zzx.zzBQ(Unknown Source)
            at com.google.android.gms.measurement.internal.zzt.zzaU(Unknown Source)
            at com.google.android.gms.measurement.AppMeasurementContentProvider.onCreate(Unknown Source)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1591)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1562)
            at android.app.ActivityThread.installProvider(ActivityThread.java:5233)
            at android.app.ActivityThread.installContentProviders(ActivityThread.java:4828)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4711)
            at android.app.ActivityThread.access$1600(ActivityThread.java:175)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5602)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

I googled it for an hour and introduced that but that doesn't work well for me.
Am I'm trying to use GCM for my application.


问:
Need to generate a 2D python list with each column having 2 possibilities, for each row
I need to generate a two-dimensional python list. It would consist of 10 columns, with each column value being either '1' or '0'. Given these conditions, my list needs to be an exhaustive list of all the combinations that can be formed in this way. It'd naturally end up being 1024 rows long (2^10). However, I have no clue where to get started on this. Can anyone help?</p>

答:
If performance isn't a concern, you could always count from 0 to 1023, create the string representation of that number in base 2 then convert to a list.

```<code>def binary_cols(n_cols):
    for i in range(2**n_cols):
        k = [int(j) for j in "{:b}".format(i)]
        k = [0]*(n_cols - len(k)) + k
        yield k
</code>```

for col in binary_cols(10):
    print col

gives

```<code>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1]
...
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

print(len(list(binary_cols(10))))
1024
</code>```

edit: I've just noticed that my answer is essentially a duplicate of Saleh Hindi's. Leaving mine here as there is a big enough difference in the specific tools used for the task, but their answer has a better explanation.

Body:
If performance isn't a concern, you could always count from 0 to 1023, create the string representation of that number in base 2 then convert to a list.

def binary_cols(n_cols):
    for i in range(2**n_cols):
        k = [int(j) for j in "{:b}".format(i)]
        k = [0]*(n_cols - len(k)) + k
        yield k

for col in binary_cols(10):
    print col

gives

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1]
...
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

print(len(list(binary_cols(10))))
1024

edit: I've just noticed that my answer is essentially a duplicate of Saleh Hindi's. Leaving mine here as there is a big enough difference in the specific tools used for the task, but their answer has a better explanation.


问:
Pairs of duplicate, identical rows. Update just one of them
Working on pretty large table in SQL-Server. Table has some identical rows. I need to remove duplicate rows. Problem is I cannot alter this table i.e. to create an ID column.

I could update one column value of the other row on pairs of duplicates. Then delete afterwards using this value.

How to update only one these rows?
For example: Firstly / lastly inserted, First occurrence, newest / oldest..

Thanks!

table Structure

```<code>NrValue |   Comment |   Value1  |   Value2  |   Value3      |
--------|-----------|-----------|-----------|---------------|
00000   |   data0   |   zz      |   top     |   vivalasvegas|
00100   |   NULL    |   N/A     |   sex     |   no          |
00100   |   NULL    |   N/A     |   sex     |   no          |
00200   |   NULL    |   female  |   sex     |   yes         |
00200   |   NULL    |   female  |   sex     |   yes         |
00300   |   NULL    |   male    |   sex     |   yesplease   |
00300   |   NULL    |   male    |   sex     |   yesplease   |
00400   |   data21  |   M       |   --      |   na          |
00500   |   NULL    |   F       |   ezig    |   na          |
</code>```

So, I could use 'Comment' -column to update but I cannot touch other than duplicate rows. I know by NrValue which rows can be updated.
Result would be:

```<code>NrValue |   Comment |   Value1  |   Value2  |   Value3      |
--------|-----------|-----------|-----------|---------------|
00000   |   data0   |   zz      |   top     |   vivalasvegas|
00100   |   1       |   N/A     |   sex     |   no          |
00100   |   2       |   N/A     |   sex     |   no          |
00200   |   3       |   female  |   sex     |   yes         |
00200   |   4       |   female  |   sex     |   yes         |
00300   |   5       |   male    |   sex     |   yesplease   |
00300   |   6       |   male    |   sex     |   yesplease   |
00400   |   data21  |   M       |   --      |   na          |
00500   |   NULL    |   F       |   ezig    |   na          |
</code>```

Lastly I delete rows where NrValue = 00100, 00200 or 00300 AND Comment = 2, 4 or 6.

答:
Use something like

```<code>ROW_NUMBER() OVER(PARTITION BY AllRelevantColumns ORDER BY SomeOrderCriteria)
</code>```

This will generate a 1 for all rows, but duplicates get a 2 (or a 3 ...)

You might place this value in a new column or use this for cleaning...

UPDATE Following your test data...

```<code>DECLARE @mockup TABLE(NrValue INT,Comment VARCHAR(100),Value1 VARCHAR(100),Value2 VARCHAR(100),Value3 VARCHAR(100));
INSERT INTO @mockup  VALUES
 (00000,'data0','zz','top','vivalasvegas')
,(00100,'NULL','N/A','sex','no')
,(00100,'NULL','N/A','sex','no')
,(00200,'NULL','female','sex','yes')
,(00200,'NULL','female','sex','yes')
,(00300,'NULL','male','sex','yesplease')
,(00300,'NULL','male','sex','yesplease')
,(00400,'data21','M','--','na')
,(00500,'NULL','F','ezig','na');

WITH Numbered AS
(
    SELECT ROW_NUMBER() OVER(PARTITION BY NrValue ORDER BY (SELECT NULL)) AS DupNr
          ,*
    FROM @mockup
)
DELETE FROM Numbered
WHERE DupNr>1;

SELECT * FROM @mockup;
</code>```

This concept is called updateable CTE. The DELETE FROM Numbered ... will affect the underlying table actually...

If the NrValue is not enough to detect a row as duplicate, just add more columns to the PARTITION BY

Body:
Working on pretty large table in SQL-Server. Table has some identical rows. I need to remove duplicate rows. Problem is I cannot alter this table i.e. to create an ID column.

I could update one column value of the other row on pairs of duplicates. Then delete afterwards using this value.

How to update only one these rows?
For example: Firstly / lastly inserted, First occurrence, newest / oldest..

Thanks!

table Structure

NrValue |   Comment |   Value1  |   Value2  |   Value3      |
--------|-----------|-----------|-----------|---------------|
00000   |   data0   |   zz      |   top     |   vivalasvegas|
00100   |   NULL    |   N/A     |   sex     |   no          |
00100   |   NULL    |   N/A     |   sex     |   no          |
00200   |   NULL    |   female  |   sex     |   yes         |
00200   |   NULL    |   female  |   sex     |   yes         |
00300   |   NULL    |   male    |   sex     |   yesplease   |
00300   |   NULL    |   male    |   sex     |   yesplease   |
00400   |   data21  |   M       |   --      |   na          |
00500   |   NULL    |   F       |   ezig    |   na          |

So, I could use 'Comment' -column to update but I cannot touch other than duplicate rows. I know by NrValue which rows can be updated.
Result would be:

NrValue |   Comment |   Value1  |   Value2  |   Value3      |
--------|-----------|-----------|-----------|---------------|
00000   |   data0   |   zz      |   top     |   vivalasvegas|
00100   |   1       |   N/A     |   sex     |   no          |
00100   |   2       |   N/A     |   sex     |   no          |
00200   |   3       |   female  |   sex     |   yes         |
00200   |   4       |   female  |   sex     |   yes         |
00300   |   5       |   male    |   sex     |   yesplease   |
00300   |   6       |   male    |   sex     |   yesplease   |
00400   |   data21  |   M       |   --      |   na          |
00500   |   NULL    |   F       |   ezig    |   na          |

Lastly I delete rows where NrValue = 00100, 00200 or 00300 AND Comment = 2, 4 or 6.

Body:
Use something like

ROW_NUMBER() OVER(PARTITION BY AllRelevantColumns ORDER BY SomeOrderCriteria)

This will generate a 1 for all rows, but duplicates get a 2 (or a 3 ...)

You might place this value in a new column or use this for cleaning...

UPDATE Following your test data...

DECLARE @mockup TABLE(NrValue INT,Comment VARCHAR(100),Value1 VARCHAR(100),Value2 VARCHAR(100),Value3 VARCHAR(100));
INSERT INTO @mockup  VALUES
 (00000,'data0','zz','top','vivalasvegas')
,(00100,'NULL','N/A','sex','no')
,(00100,'NULL','N/A','sex','no')
,(00200,'NULL','female','sex','yes')
,(00200,'NULL','female','sex','yes')
,(00300,'NULL','male','sex','yesplease')
,(00300,'NULL','male','sex','yesplease')
,(00400,'data21','M','--','na')
,(00500,'NULL','F','ezig','na');

WITH Numbered AS
(
    SELECT ROW_NUMBER() OVER(PARTITION BY NrValue ORDER BY (SELECT NULL)) AS DupNr
          ,*
    FROM @mockup
)
DELETE FROM Numbered
WHERE DupNr>1;

SELECT * FROM @mockup;

This concept is called updateable CTE. The DELETE FROM Numbered ... will affect the underlying table actually...

If the NrValue is not enough to detect a row as duplicate, just add more columns to the PARTITION BY


问:
How to efficiently build a tree from a flat structure?
I have a bunch of objects in a flat structure. These objects have an ID and a ParentID property so they can be arranged in trees. They are in no particular order.
Each ParentID property does not necessarily matches with an ID in the structure. Therefore their could be several trees emerging from these objects.

How would you process these objects to create the resulting trees ?

I'm not so far from a solution but I'm sure it is far from optimal...

I need to create these trees to then insert Data into a database, in proper order.

There are no circular references. A Node is a RootNode when ParentID == null or when ParentID can't be found in the other objects

答:
Store IDs of the objects in a hash table mapping to the specific object. Enumerate through all the objects and find their parent if it exists and update its parent pointer accordingly.

class MyObject
{ // The actual object
    public int ParentID { get; set; }
    public int ID { get; set; }
}

class Node
{
    public List<Node> Children = new List<Node>();
    public Node Parent { get; set; }
    public MyObject AssociatedObject { get; set; }
}

IEnumerable<Node> BuildTreeAndGetRoots(List<MyObject> actualObjects)
{
    Dictionary<int, Node> lookup = new Dictionary<int, Node>();
    actualObjects.ForEach(x => lookup.Add(x.ID, new Node { AssociatedObject = x }));
    foreach (var item in lookup.Values) {
        Node proposedParent;
        if (lookup.TryGetValue(item.AssociatedObject.ParentID, out proposedParent)) {
            item.Parent = proposedParent;
            proposedParent.Children.Add(item);
        }
    }
    return lookup.Values.Where(x => x.Parent == null);
}
```

OwnerDisplayName: Costo

LastEditorDisplayName: Costo

OwnerDisplayName: Mehrdad Afshari

LastEditorDisplayName: Mehrdad Afshari


问:
How to obtain the absolut path of the copy when copying files?
I'm copying like this:

```<code>cp "$input_file_absolut_path" "$output_directory_absolut_path"
</code>```

Now I want to do something with the copied file, but i CAN'T just:

```<code>copy_absolut_path="$output_directory_absolut_path/$input_file_absolut_path"
</code>```

Any tip to obtain the absolut path of the copied file?

答: if your filename doesn't contain slash, you can concatenate $output_directory_absolut_path and basename "$input_file_absolut_path"

Body:
I'm copying like this:

cp "$input_file_absolut_path" "$output_directory_absolut_path"

Now I want to do something with the copied file, but i CAN'T just:

copy_absolut_path="$output_directory_absolut_path/$input_file_absolut_path"

Any tip to obtain the absolut path of the copied file?


问:
parse multiple json string into one object in javascript
I have a json output where it gets two strings with format such as

```<code>   [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
   [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
</code>```

I want to parse these strings into one object. I have used the JSON.parse(data) but its giving me first string in object and not the all strings. How do I achieve this.

i want the output should be

```<code>   [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"},
   {"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
</code>```

答:
I guess you'd want an array with both of the objects inside, otherwise, please specify what is your expected output.

If you are unable to modify the JSON string received to make it look like a proper array, I'd substitute the '][' for a comma ',' so you can parse the JSON string and receive back an array with two objects inside, like so:

```<code>original = '[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}][{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]';
replaced = original.replace('][', ',');
parsed = JSON.parse(replaced);
</code>```

Edited:

Just in case your input contains a line break between the closing and opening square brackets, your substitution should be like that:

```<code>replaced = original.replace(']\n[', ',');
</code>```

2nd edit:

If your input contains more than two lines like these, there is no problem, your replace call will substitute every one of the matches if you write it like that:

```<code>replaced = original.replace(/\]\[/g, ',');
</code>```

This is a regular expression that substitutes every occurence of ][ (expressed as \]\[ because these are special characters for regular expressions), with the help of the global flag specified at the end of the regular expression.

Body:
I have a json output where it gets two strings with format such as

   [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
   [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]

I want to parse these strings into one object. I have used the JSON.parse(data) but its giving me first string in object and not the all strings. How do I achieve this.

i want the output should be

   [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"},
   {"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]

Body:
I guess you'd want an array with both of the objects inside, otherwise, please specify what is your expected output.

If you are unable to modify the JSON string received to make it look like a proper array, I'd substitute the '][' for a comma ',' so you can parse the JSON string and receive back an array with two objects inside, like so:

original = '[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}][{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]';
replaced = original.replace('][', ',');
parsed = JSON.parse(replaced);

Edited:

Just in case your input contains a line break between the closing and opening square brackets, your substitution should be like that:

replaced = original.replace(']\n[', ',');

2nd edit:

If your input contains more than two lines like these, there is no problem, your replace call will substitute every one of the matches if you write it like that:

replaced = original.replace(/\]\[/g, ',');

This is a regular expression that substitutes every occurence of ][ (expressed as \]\[ because these are special characters for regular expressions), with the help of the global flag specified at the end of the regular expression.


问:
Angular 2: Custom validation for file extensions
I am new to angular. I want to create a custom validation for checking the file size and extension. I am using FormBuilder for validation and FileReader API for fetching file name and size of the input element field data.

Problem: We are able to trigger custom validation on change event but could not fetch value of input type field.

Please suggest how we can implement custom validation for file extensions and size in angular 2.

HTML:

```<code><input type="file" [formControl] = "formName.controls['thumbnailImg']" (change)="changeThumbFile($event)">
</code>```

Component:

```<code>//custom validation
function validateExt(c: FormControl) {
    let extension = ['png', 'jpeg', 'gif'];
    return extension.indexOf(c.value)? null : { validateExt: { valid: false } }
}

this.form = this.formBuilder.group({
  'thumbnailImg': ['', validateExt],
});
changeThumbFile($event){
    var file: File = $event.target.files[0];
    var fReader: FileReader = new FileReader();

    var imgName = file.name;
    this.thumbnailName = imgName;

    this.formGp.controls['thumbnailImg'].updateValueAndValidity();
}
</code>```

答:
I have a solution, maybe not the perfect one, but it works(same thing would be for file size), here it is:

First on the html file I got the form for file upload, and on it each time I upload a file I call a specific function called fileEvent(), The layout file contains:

```<code>   <form [formGroup]="photoForm" (submit)="savePhoto()">
          <table>
            <tr>
              <td>Photo</td>
              <td>
                <div class="file-edit">
                  <input type="file" (change)="fileEvent($event)" formControlName="newPhoto" class="form-control" required #newPhoto>
                </div>
              </td>
              <td><p class="warning">{{fileExtensionMessage}}</p></td>
            </tr>
            <br/>
            <tr>
              <td></td>
              <td><button type="submit" [disabled]='fileExtensionError' class="submit-btn">Save</button></td>
            </tr>
          </table>
        </form>
</code>```

Please note that if fileExtensionError variable is true the submit button is disabled.

The function fileEvent() which checks validation also gives me the filename, file extension and file content is as below:

```<code> fileEvent(event) : any {
    //*-- this function gets content of uploaded file and validation --
     */
    var file = event.target.files[0];
    this.photoName = file.name;

    var allowedExtensions =
       ["jpg","jpeg","png","JPG","JPEG","JFIF","BMP","SVG"];
    this.fileExtension = this.photoName.split('.').pop();

    if(this.isInArray(allowedExtensions, this.fileExtension)) {
        this.fileExtensionError = false;
        this.fileExtensionMessage = ""
    } else {
        this.fileExtensionMessage = "Only photos allowed!!"
        this.fileExtensionError = true;
    }

    if (file) {
        var reader = new FileReader();
        reader.onloadend = (e: any) => {
            var contents = e.target.result;
            this.photoContent = contents;
        }
        reader.readAsDataURL(file);
    } else {
        alert("Failed to load file");
    }
}

/*- checks if word exists in array -*/
 isInArray(array, word) {
    return array.indexOf(word.toLowerCase()) > -1;
}
</code>```

Of course I have these variables declared in my class:

```<code>photoName: any;
photoContent : any;
fileExtension: any;
fileExtensionError: boolean = false;
fileExtensionMessage: any;
photoForm : FormGroup;
</code>```

Hope it helps someone :D

Body:
I am new to angular. I want to create a custom validation for checking the file size and extension. I am using FormBuilder for validation and FileReader API for fetching file name and size of the input element field data.

Problem: We are able to trigger custom validation on change event but could not fetch value of input type field.

Please suggest how we can implement custom validation for file extensions and size in angular 2.

HTML:

<input type="file" [formControl] = "formName.controls['thumbnailImg']" (change)="changeThumbFile($event)">

Component:

//custom validation
function validateExt(c: FormControl) {
    let extension = ['png', 'jpeg', 'gif'];
    return extension.indexOf(c.value)? null : { validateExt: { valid: false } }
}

this.form = this.formBuilder.group({
  'thumbnailImg': ['', validateExt],
});
changeThumbFile($event){
    var file: File = $event.target.files[0];
    var fReader: FileReader = new FileReader();

    var imgName = file.name;
    this.thumbnailName = imgName;

    this.formGp.controls['thumbnailImg'].updateValueAndValidity();
}

Body:
I have a solution, maybe not the perfect one, but it works(same thing would be for file size), here it is:

First on the html file I got the form for file upload, and on it each time I upload a file I call a specific function called fileEvent(), The layout file contains:

   <form [formGroup]="photoForm" (submit)="savePhoto()">
          <table>
            <tr>
              <td>Photo</td>
              <td>
                <div class="file-edit">
                  <input type="file" (change)="fileEvent($event)" formControlName="newPhoto" class="form-control" required #newPhoto>
                </div>
              </td>
              <td><p class="warning">{{fileExtensionMessage}}</p></td>
            </tr>
            <br/>
            <tr>
              <td></td>
              <td><button type="submit" [disabled]='fileExtensionError' class="submit-btn">Save</button></td>
            </tr>
          </table>
        </form>

Please note that if fileExtensionError variable is true the submit button is disabled.

The function fileEvent() which checks validation also gives me the filename, file extension and file content is as below:

 fileEvent(event) : any {
    //*-- this function gets content of uploaded file and validation --
     */
    var file = event.target.files[0];
    this.photoName = file.name;

    var allowedExtensions =
       ["jpg","jpeg","png","JPG","JPEG","JFIF","BMP","SVG"];
    this.fileExtension = this.photoName.split('.').pop();

    if(this.isInArray(allowedExtensions, this.fileExtension)) {
        this.fileExtensionError = false;
        this.fileExtensionMessage = ""
    } else {
        this.fileExtensionMessage = "Only photos allowed!!"
        this.fileExtensionError = true;
    }

    if (file) {
        var reader = new FileReader();
        reader.onloadend = (e: any) => {
            var contents = e.target.result;
            this.photoContent = contents;
        }
        reader.readAsDataURL(file);
    } else {
        alert("Failed to load file");
    }
}

/*- checks if word exists in array -*/
 isInArray(array, word) {
    return array.indexOf(word.toLowerCase()) > -1;
}

Of course I have these variables declared in my class:

photoName: any;
photoContent : any;
fileExtension: any;
fileExtensionError: boolean = false;
fileExtensionMessage: any;
photoForm : FormGroup;

Hope it helps someone :D


问:
Designing better git branching model strategy

Brief overview

We are product company and we are providing solutions to more than 50 clients and they are growing each month and we have fairly simple branching model which I would like to upgrade if possible.

The model

We are doing agile therefore we have sprints and releases. Each month or two we are opening new release branch from master which will be stabilized and  later will be given to clients that are interested in features in it. So far so good. During development new clients are created. Let's say we start working on a client A and we decide that this client will go with certain version, let's say release/1.0 so we make branch release/A_1.0 and we start our development there, once we are done we merge release/A_1.0 -> release/1.0 and we deploy to production from release/1.0 branch this client.

Before I continue to explain where the problem is I will set some rules that we are keeping:

Once release branch is open master is never merged there.

release/{client}_{version} branches are occasionally updated with release/{version} branch (version numbers should match).

Only hotfix branches are merged into release/{version} branch.

Before opening new release/{version} branch 2-3 previous version release branches are merged to master so all the hotfixes from these previous versions are in the new version as well.

Hotfixes from previous version are not allowed once release/{version} branch is opened.

Where is the problem?

Tbh problem is bad planning, but this happens and it can't be avoided.
Let's say we negotiated with a client(B) and we decided to give them version 1.0, that would be opening a branch making it release/B_v1.0 while we are developing this client in this branch time goes by and our product team sprint opens another release, for instance 1.1.Sometimes development process of client takes enough time for product to open if not one but two or three new release/{version} branches. So if this happens management and the client might decide to go live with newer version(let's say 1.3 - previously it was developed for 1.0).
Now what it has to be done is that we need to open branch from release/1.3 for this client and then merge previously opened branch - that would be making merge  release/B_1.0 --> release/B_1.3 and this can be PAINFUL to be done. Why?

Because release/B_1.0 is occasionally updated with release/1.0
  this means that all hotfixes from version 1.0 will be in
  release/B_1.0 (this can't be avoid as some hotfixes are crucial to
  development of the client) and when it comes time to merge
  release/B_1.0 --> release/B_1.3 this will include all these hotfixes
  from version 1.0 in release/B_1.3 and later when release/B_1.3 -->
  release/1.3 merge is introduced they will be included in version 1.3
  which is forbidden.

What I do in situations like this?

I cherry-pick all commits/merges, that were in release/B_1.0 and are not hotfixes that came from release/1.0, into release/B_1.3 but this can be really time consuming and mistakes can be made also due to the fact how git history works.

I proposed that these client branches can be locked for committing so only merges goes in there and when this kind of merge can be made I can easily cherry-pick only the merges from relevant branches(ignoring merges from release/{version}) and not worry about leaving trailing commits, but this means that everyone working in this branch has to make his own branch and merge it in it which kinda slows the development process in my opinion.

Do you have any other suggestions that would ease such merges?

答:
Why not manage these clients for different git repositories?

Manage all the clients in a git repo seems efficient, but actually it’s not. And it based on that all the clients have the same requriemnts/bugs or you must negotiate them to sync with the other.

So you’d better manage them separately. Even if two clients have the same  features, you can use the features cross repositories easily:

```<code># In repoA
git remote add B <URL for repo B> -f
gitk --all # find the commit of repoB you want to use in repoA
git cherry-pick <commit in repoB>
</code>```

Body:
Why not manage these clients for different git repositories?

Manage all the clients in a git repo seems efficient, but actually it’s not. And it based on that all the clients have the same requriemnts/bugs or you must negotiate them to sync with the other.

So you’d better manage them separately. Even if two clients have the same  features, you can use the features cross repositories easily:

# In repoA
git remote add B <URL for repo B> -f
gitk --all # find the commit of repoB you want to use in repoA
git cherry-pick <commit in repoB>


问:
want the loop to show result one by one on each iteration
Home page of my site is loading too slow. After examining my site I found that a 'for' loop which I used to retrieve data dynamically from an rss feed is making the problem.

The site takes 6-8sec for initial loading.
The loop which takes each item from the feed and echo the result in desired format. But only shows the site after the completion of the loop iteration with the whole result.

I want a solution for this
say for example

```<code>for($i=0;$i<10;$i++){

echo $i;
}
</code>```

I want the page load with result as '0' then successively shows 1,2,3...9

please suggest a method to solve this issue. Please if I get an example with your answer

答:
The speed problem is not in the loop, it's in loading the RSS xml file.  The best option would be to read from a local cache, and setup a cron job/daemon to update the cache regularly.

To do this, create an XML file on the system, and instead of reading from the remote file, read from your XML file.  To make a cron job to update the cache, write a script that reads from the remote file, and writes to the local XML file.  To make the cron job run, see here:

http://articles.sitepoint.com/article/introducing-cron

Body:
Home page of my site is loading too slow. After examining my site I found that a 'for' loop which I used to retrieve data dynamically from an rss feed is making the problem.

The site takes 6-8sec for initial loading.
The loop which takes each item from the feed and echo the result in desired format. But only shows the site after the completion of the loop iteration with the whole result.

I want a solution for this
say for example

for($i=0;$i<10;$i++){

echo $i;
}

I want the page load with result as '0' then successively shows 1,2,3...9

please suggest a method to solve this issue. Please if I get an example with your answer


问:
Laravel -Trigger a controller method in x minutes within a code
In my controller method,

Once all the payment details are validated for format,

We initiate the payment.

Now, on initiation of this (and every other) payment, I need to schedule a Controller call in 15 min with parameters (payment gateway token) to check if the payment was completed..else dismiss it.

Now, I can use a cron every minute to check for payments made 15 minutes back. But running a one time scheduled call would put less effort and pressure on system than running a cron every minute endlessly.

I explored the options in laravel like queuing or task scheduling. But none of it is one-time call (task scheduling) or queuing in x minutes.

Is there something that I am missing or some feature in laravel on similar grounds for the given requirement?

答:
I would personally create a ValidatePaymentJob, which you call in your controller method like this:

```<code>public function validatePaymentDetails()
{

    //Logic for validation the payment details goes up here

    dispatch(new ValidatePaymentJob($all, $needed, $parameters))
        ->delay(Carbon::now()->addMinutes(x));
}
</code>```

Then in your ValidatePaymentJob you can make a call to your payment provider to check if the payment was successful or not. You could even pass your transaction object with it and set a succeeded property to true.

You can check out the docs for Jobs here

Body:
I would personally create a ValidatePaymentJob, which you call in your controller method like this:

public function validatePaymentDetails()
{

    //Logic for validation the payment details goes up here

    dispatch(new ValidatePaymentJob($all, $needed, $parameters))
        ->delay(Carbon::now()->addMinutes(x));
}

Then in your ValidatePaymentJob you can make a call to your payment provider to check if the payment was successful or not. You could even pass your transaction object with it and set a succeeded property to true.

You can check out the docs for Jobs here


问:
How to override "ModuleCore" class? (/classes/module/Module.php)
How to override ModuleCore class located in /classes/module/Module.php?

If I put class ModuleOverride extends ModuleCore (...) in /override/classes/module/Module.php, the file is ignored.

答:
The override of built in class is the same name without the "Core". In ModuleCore the override class would be just class Module extends ModuleCore (...) and the location is correct, the same, but inside the folder override. The Override suffix is for modules classes.
Dont' forget to delete de cache/class_index.php file.


问:
Cannot find mysql.sock
I just had to re-install mysql and I am having a problem starting it up.  It cannot find the socket (mysql.sock).  The problem is that neither can I.  In my Mac OS X 10.4 terminal, I type: locate mysql.sock, and I get back /private/tmp/mysql.sock.  It makes sense that the socket file exist in that location, but it actually does not.

How can I find the socket file?

If locate is returning a false location, it must have some sort of memory and probably indexes.  How can I refresh that index?

答:
I couldn't find mysql socket at all so reinstalled mysql server(all tables and phpmyadmin settings were preserved). Here are the commands:

1) Install

sudo apt-get install mysql-server

2) Follow terminal configuration steps

sudo mysql_secure_installation

3) Check status: (Should return "Active: active (running)")

systemctl status mysql.service

Title: Cannot find mysql.sock


问:
Laravel Records Relationship issue
I have one to many relationship between Applicant and pendingJob, Where my Applicant model have cnic primary key, Where pendingJob have applicant_id and pointing it to Applicant model cnic column as foreign key.

Applicant model :

```<code>protected $primaryKey = 'cnic';

public function pending_jobs() {
    return $this->hasMany('App\PendingJobs', 'applicant_id');
}
</code>```

PendingJob model :

```<code>public function applicant() {
    return $this->belongsTo('App\Applicant', 'applicant_id');
}
</code>```

I am inserting record in Applicant like :

```<code>$req = new \App\Applicant;
$req->full_name = $request->get('full_name');
$req->cnic = $request->get('cnic');
$req->mobile_number = $request->get('mobile_number');
$req->save();
</code>```

Then record in PendingJob :

```<code>$reqr = new \App\PendingJob;
$reqr->applicant_id = $request->get('cnic');
$reqr->job_type = 'residence';
$reqr->status = 'pending';
$reqr->save();
</code>```

The record saves and cnic which is the primary key of the Applicant and the Pendingjob's applicant_id which is pointing to the Applicant's cnic comes the same.

But

The relationship does not loads, Manual record insertion from phpmydamin works fine.

答:
The workflow should be this:

```<code>$reqr = new \App\PendingJob;
$reqr->job_type = 'residence';
$reqr->status = 'pending';

$req = new \App\Applicant;
$req->full_name = $request->get('full_name');
$req->cnic = $request->get('cnic');
$req->mobile_number = $request->get('mobile_number');

$reqr->applicant()->associate($req);

$reqr->save();
</code>```

source: https://laravel.com/docs/5.4/eloquent-relationships#the-save-method

Also, I'm noticing that your primary key for the applicant is cnic so your relationship should specify the local_key according to the Laravel documentation:

App\Application

```<code>public function pending_jobs() {
    return $this->hasMany('App\PendingJobs', 'applicant_id', 'cnic');
}
</code>```

App\PendingJob

```<code>public function applicant() {
    return $this->belongsTo('App\Applicant', 'applicant_id', 'id');
}
</code>```

Title: Laravel Records Relationship issue

Body:
I have one to many relationship between Applicant and pendingJob, Where my Applicant model have cnic primary key, Where pendingJob have applicant_id and pointing it to Applicant model cnic column as foreign key.

Applicant model :

protected $primaryKey = 'cnic';

public function pending_jobs() {
    return $this->hasMany('App\PendingJobs', 'applicant_id');
}

PendingJob model :

public function applicant() {
    return $this->belongsTo('App\Applicant', 'applicant_id');
}

I am inserting record in Applicant like :

$req = new \App\Applicant;
$req->full_name = $request->get('full_name');
$req->cnic = $request->get('cnic');
$req->mobile_number = $request->get('mobile_number');
$req->save();

Then record in PendingJob :

$reqr = new \App\PendingJob;
$reqr->applicant_id = $request->get('cnic');
$reqr->job_type = 'residence';
$reqr->status = 'pending';
$reqr->save();

The record saves and cnic which is the primary key of the Applicant and the Pendingjob's applicant_id which is pointing to the Applicant's cnic comes the same.

But

The relationship does not loads, Manual record insertion from phpmydamin works fine.

Body:
The workflow should be this:

$reqr = new \App\PendingJob;
$reqr->job_type = 'residence';
$reqr->status = 'pending';

$req = new \App\Applicant;
$req->full_name = $request->get('full_name');
$req->cnic = $request->get('cnic');
$req->mobile_number = $request->get('mobile_number');

$reqr->applicant()->associate($req);

$reqr->save();

source: https://laravel.com/docs/5.4/eloquent-relationships#the-save-method

Also, I'm noticing that your primary key for the applicant is cnic so your relationship should specify the local_key according to the Laravel documentation:

App\Application

public function pending_jobs() {
    return $this->hasMany('App\PendingJobs', 'applicant_id', 'cnic');
}

App\PendingJob

public function applicant() {
    return $this->belongsTo('App\Applicant', 'applicant_id', 'id');
}


问:
ASP.NET MVC create absolute url from c# code
How do i generate an absolute url from the c# code?

I want to generate a url like this: localhost/{controller}/{action}/{id}. Is there a way to do it in c# like how it can be done in the views?

It wont be generated inside the controller but inside a ViewModel.

答:
```<code>string absUrl = Url.Action("Index", "Products", null, Request.Url.Scheme);
</code>```

Just add Request.Url.Scheme. What this does is add a protocol to the url which forces it to generate an absolute URL.

Body:
string absUrl = Url.Action("Index", "Products", null, Request.Url.Scheme);

Just add Request.Url.Scheme. What this does is add a protocol to the url which forces it to generate an absolute URL.


问:
Create multi-level lookup table with lodash
Lets pretend an api is returning the structure in apiResult, and I want to create a two-level index for looking up what comments a given author have made on a given article.

The lookup table for the authors, articles and comments it self is easy enough, but I struggle with the CommentsByArticleAndAuthor-lookup.

In the mapped structure, I'm showing how I'm making the lookup index for the three 'easy' parts, and also how I want the CommentsByArticleAndAuthor to look.

How can I go forward generating this index?

var apiResult = {
  Authors: [
    {
      Id: "author-id-1",
      Name: "Author One"
    },
    {
      Id: "author-id-2",
      Name: "Author Two"
    }
  ],
  Articles: [
    {
      Id: "article-id-1",
      Title: "This Great Article"
    }
  ],
  Comments: [
    {
       Id: "comment-id-1",
       AuthorId: "author-id-1",
       ArticleId: "article-id-1",
       Comment: "that great, hu?"
    },
    {
      Id: "comment-id-2",
      AuthorId: "author-id-2",
      ArticleId: "article-id-1",
      Comment: "yes, that great"
    }
  ]
}

var mapped = {
  Authors: _.keyBy(apiResult.Authors, 'Id'),
  Articles: _.keyBy(apiResult.Articles, 'Id'),
  Comments: _.keyBy(apiResult.Comments, 'Id'),
  CommentsByArticleAndAuthor: {
    "article-id-1": {
      "author-id-1": [ "comment-id-1" ],
      "author-id-2": [ "comment-id-2" ]
    }
  }
}

console.log(JSON.stringify(mapped, null, 2));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script></code>```

答:
Thanks to Ninas great answer I came up with this generic solution:

const apiResult = {
  Authors: [{ Id: "author-id-1", Name: "Author One" },
            { Id: "author-id-2", Name: "Author Two" }],
  Articles: [{ Id: "article-id-1", Title: "This Great Article" }],
  Comments: [{ Id: "comment-id-1", AuthorId: "author-id-1", ArticleId: "article-id-1", Comment: "that great, hu?" },
             { Id: "comment-id-2", AuthorId: "author-id-2", ArticleId: "article-id-1", Comment: "yes, that great" }]
};
const mapped = {};

const indexBy = function(collection, keys, map = (item) => item) {
  let result = {};

  collection.forEach((item) => {
    keys.reduce((r, k, idx) => {
      let value = _.get(item, k);
      if (idx === keys.length - 1)
        return r[value] = [...r[value] || [], map(item)];

      return r[value] = r[value] || {}
    }, result);
  });

  return result;
}

mapped.CommentsByArticlesAndAuthor = indexBy(apiResult.Comments, ['ArticleId', 'AuthorId'], (item) => item.Id);
mapped.CommentsByAuthorAndArticle = indexBy(apiResult.Comments, ['AuthorId', 'ArticleId'], (item) => item.Id);

console.log(mapped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {  max-height: 100% !important;  top: 0; }</code>```

```

It let me index on as many levels that I want, and it let me transform the item indexed, defaulting to just store the full item. It also utilize get from lodash to support nested key values, e.g. Author.Id instead of AuthorId.

Body:
Thanks to Ninas great answer I came up with this generic solution:

const apiResult = {
  Authors: [{ Id: "author-id-1", Name: "Author One" },
            { Id: "author-id-2", Name: "Author Two" }],
  Articles: [{ Id: "article-id-1", Title: "This Great Article" }],
  Comments: [{ Id: "comment-id-1", AuthorId: "author-id-1", ArticleId: "article-id-1", Comment: "that great, hu?" },
             { Id: "comment-id-2", AuthorId: "author-id-2", ArticleId: "article-id-1", Comment: "yes, that great" }]
};
const mapped = {};

const indexBy = function(collection, keys, map = (item) => item) {
  let result = {};

  collection.forEach((item) => {
    keys.reduce((r, k, idx) => {
      let value = _.get(item, k);
      if (idx === keys.length - 1)
        return r[value] = [...r[value] || [], map(item)];

      return r[value] = r[value] || {}
    }, result);
  });

  return result;
}

mapped.CommentsByArticlesAndAuthor = indexBy(apiResult.Comments, ['ArticleId', 'AuthorId'], (item) => item.Id);
mapped.CommentsByAuthorAndArticle = indexBy(apiResult.Comments, ['AuthorId', 'ArticleId'], (item) => item.Id);

console.log(mapped);

.as-console-wrapper {  max-height: 100% !important;  top: 0; }

<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

It let me index on as many levels that I want, and it let me transform the item indexed, defaulting to just store the full item. It also utilize get from lodash to support nested key values, e.g. Author.Id instead of AuthorId.


问:
Convert string dates in java
I need to compare two string dates in java:

```<code>String date1 = "2017-05-02";
String date2 = "5/2/2017";
//formatter for the first date
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
Date formattedDate1 = formatter.parse(date1);
//formatter for the second date
formatter = new SimpleDateFormat("m/d/yyyy");
Date formattedDate2 = formatter.parse(date2);
//Wrong results
String formatted1 = formattedDate1.toString(); //Mon Jan 02 00:05:00 EET 2017
String formatted2 = formattedDate2.toString(); //Mon Jan 02 00:05:00 EET 2017
</code>```

Actually if i compare those 2 i probably will get 'true' but my dates are not the January, it's 'May 5th 2017'.

The other question is that I can't use Date object, I need to actually convert "2017-05-02" into "5/2/2017" and then pass it to another function

答:
And because old java date is broken and we all should stop learning that, and since new features in java8 will be helpfull for all us in the future, here another option using javaTime api</p>

```<code>String date1 = "2017-05-02";
String date2 = "5/2/2017";
LocalDate d1 = LocalDate.parse(date1, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDate d2 = LocalDate.parse(date2, DateTimeFormatter.ofPattern("M/d/yyyy"));

System.out.println(d1);
System.out.println(d2);
System.out.println(d2.isEqual(d1));
</code>```

Title: Convert string dates in java

Body:
I need to compare two string dates in java:

String date1 = "2017-05-02";
String date2 = "5/2/2017";
//formatter for the first date
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
Date formattedDate1 = formatter.parse(date1);
//formatter for the second date
formatter = new SimpleDateFormat("m/d/yyyy");
Date formattedDate2 = formatter.parse(date2);
//Wrong results
String formatted1 = formattedDate1.toString(); //Mon Jan 02 00:05:00 EET 2017
String formatted2 = formattedDate2.toString(); //Mon Jan 02 00:05:00 EET 2017

Actually if i compare those 2 i probably will get 'true' but my dates are not the January, it's 'May 5th 2017'.

The other question is that I can't use Date object, I need to actually convert "2017-05-02" into "5/2/2017" and then pass it to another function

Body:
And because old java date is broken and we all should stop learning that, and since new features in java8 will be helpfull for all us in the future, here another option using javaTime api

String date1 = "2017-05-02";
String date2 = "5/2/2017";
LocalDate d1 = LocalDate.parse(date1, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDate d2 = LocalDate.parse(date2, DateTimeFormatter.ofPattern("M/d/yyyy"));

System.out.println(d1);
System.out.println(d2);
System.out.println(d2.isEqual(d1));


答:
No, you have to use the $input_file_absolut_path. But since you copied only the file, not the whole directory structure into $output_directory_absolut_path, you have to do it like this:

```<code>copy_absolut_path="$output_directory_absolut_path/$(basename $input_file_absolut_path)"
</code>```

basename will get you just the filename without the directory structure. Then you concatenate it with the output_directory_absolut_path.

Title: How to obtain the absolut path of the copy when copying files?

Body:
No, you have to use the $input_file_absolut_path. But since you copied only the file, not the whole directory structure into $output_directory_absolut_path, you have to do it like this:

copy_absolut_path="$output_directory_absolut_path/$(basename $input_file_absolut_path)"

basename will get you just the filename without the directory structure. Then you concatenate it with the output_directory_absolut_path.


答: You will not be able to do this only in PHP.  You will need to set up the page so that everything is loaded and then use Javascript to pull the RSS feed into the page as it is loaded.</p>

Title: want the loop to show result one by one on each iteration