问:
Export a function to a .csv or .xlsx file in Python
I am using an apripori algorithm in Python and would like to know how can I export the results to excel or csv?

from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori
apriori(df_one_hot,min_support=0.05,use_colnames=True).sort_values(by='support',ascending=False)
```

答:
Store the results in a pandas dataframe and use to_csv to write to a CSV file.

```<code>import pandas as pd
results = apriori(df_one_hot,min_support=0.05,use_colnames=True).sort_values(by='support',ascending=False)
results_df = pd.DataFrame(results)
results_df.to_csv('results.csv', index=False)
</code>```

Body:
Store the results in a pandas dataframe and use to_csv to write to a CSV file.

import pandas as pd
results = apriori(df_one_hot,min_support=0.05,use_colnames=True).sort_values(by='support',ascending=False)
results_df = pd.DataFrame(results)
results_df.to_csv('results.csv', index=False)


来源: stackexchange

问:
Condition parameter type does not match schema type
I have a table in dynamoDB called 'Contributors'. I have a primary composite key where the hash key is 'UserId' and the sort key is 'NoteId'. I want to query for all the items belonging to a particular hashkey.

Now if I use aws-cli, following command works:

```<code>aws dynamodb query \
--table-name Contributors \
--key-condition-expression 'UserId = :UserId' \
--expression-attribute-values '{
    ":UserId": {"N":"2"}
}'
</code>```

But when I write the query in Node.js, neither of the below 2 param objects work:

```<code>var params = {
    TableName: "Contributors",
    KeyConditionExpression: "#UserId = :UserId",
    ExpressionAttributeNames: {
        "#UserId": "UserId"
    },
    ExpressionAttributeValues: {
        ":UserId": { "N": "2" }
    }
};
</code>```

OR this:

```<code>var params = {
    TableName: "Contributors",
    KeyConditionExpression: "#UserId = :UserId",
    ExpressionAttributeNames: {
        "#UserId": "UserId"
    },
    ExpressionAttributeValues: {
        ":UserId": "2"
    }
};
</code>```

I get the following error:

ValidationException: One or more parameter values were invalid:
  Condition parameter type does not match schema type

What should be the correct param object?

答:
Replacing:

```<code>var docClient = new AWS.DynamoDB.DocumentClient();
</code>```

With:

```<code>var docClient = new AWS.DynamoDB();
</code>```

Instantly solved this problem for me.

ContentLicense: CC BY-SA 3.0

Body:
I have a table in dynamoDB called 'Contributors'. I have a primary composite key where the hash key is 'UserId' and the sort key is 'NoteId'. I want to query for all the items belonging to a particular hashkey.

Now if I use aws-cli, following command works:

aws dynamodb query \
--table-name Contributors \
--key-condition-expression 'UserId = :UserId' \
--expression-attribute-values '{
    ":UserId": {"N":"2"}
}'

But when I write the query in Node.js, neither of the below 2 param objects work:

var params = {
    TableName: "Contributors",
    KeyConditionExpression: "#UserId = :UserId",
    ExpressionAttributeNames: {
        "#UserId": "UserId"
    },
    ExpressionAttributeValues: {
        ":UserId": { "N": "2" }
    }
};

OR this:

var params = {
    TableName: "Contributors",
    KeyConditionExpression: "#UserId = :UserId",
    ExpressionAttributeNames: {
        "#UserId": "UserId"
    },
    ExpressionAttributeValues: {
        ":UserId": "2"
    }
};

I get the following error:

ValidationException: One or more parameter values were invalid:
  Condition parameter type does not match schema type

What should be the correct param object?

Body:
Replacing:

var docClient = new AWS.DynamoDB.DocumentClient();

With:

var docClient = new AWS.DynamoDB();

Instantly solved this problem for me.

ContentLicense: CC BY-SA 4.0


问:
PHP Composer organize vendor imports and private common packages
I am developing a PHP framework as a composer package that will be reused in 50+ projects (web sites) in my company.

Every website is relatively small (15-20 PHP files, less than 1-2 MB total).
The websites will also use composer.

The framework package:

is small contains 10-15 base PHP classes. All 50+ projects will
extend them (inherit their classes).

requries about 8-9 composer packages (from packagist.org, like Monolog, Redis, etc), which require about 100 MB disk space.

The websites:

Require the framework package in their composer.json (see below).

Contains 10-15 classes that extends (inherit) the framework classes.

Are independent of each other. Each one live on its own and are not realted to each other.

Are also composer projects, using all composer stuff (autoloading, psr4, etc).

Both framework and website are private projects and due to company policy, cannot be shared neither in GITHUB, nor Packagist.

Framework composer.json

```<code>{
    "name": "Company/Framework",
    "require": {
        "php": ">=5.6.4",
        "mpdf/mpdf": "dev-master",
        "monolog/monolog":"1.2"
    },
    "autoload": {
        "psr-4": {
            "Company\\Framework\\": "src/"
        }
    }
}
</code>```

Each website composer.json:

```<code>{
    "repositories": [
        {
            "type": "path",
            "url": "../Framework/",
            "options": {
                "symlink": false
            }
        }
    ],
    "require": {
        "Company/Framework": "dev-master",
        "mpdf/mpdf": "dev-master"
    },
    "autoload": {
        "psr-4": {
            "Company\\Site01\\": "src/"
        }
    }
}
</code>```

My problem is, that composer populates every website's vendor directory with its dependencies and entire framework directory.

Finally, All ended up with a huge ammount of disk space used, about 40+ GB, mainly with a same VENDOR packages, repeated over and over again.
Our PHP code is less than 1% of the entire project.

My questions are:

What are the best practices to develop my private packages (not
shared in the public) and reuse them in other projects?

How can I properly reuse common composer libraries, without duplicating hude ammount of Vendor code over and over again?

答:
You shouldn't keep the vendor folders inside your libraries code. Delete the vendor folders, and just have the libraries' dependencies declared in the libraries' composer.json.

When you run composer install from the project, composer will copy your libraries to the project's vendor folder, and install the libraries' dependencies inside the project.

An even better alternative is to use private repositories, from GitHub or Bitbucket, cause you can control who has access to it, but you can still use things like tags for versioning.

Body:
I am developing a PHP framework as a composer package that will be reused in 50+ projects (web sites) in my company.

Every website is relatively small (15-20 PHP files, less than 1-2 MB total).
The websites will also use composer.

The framework package:

is small contains 10-15 base PHP classes. All 50+ projects will
extend them (inherit their classes).

requries about 8-9 composer packages (from packagist.org, like Monolog, Redis, etc), which require about 100 MB disk space.

The websites:

Require the framework package in their composer.json (see below).

Contains 10-15 classes that extends (inherit) the framework classes.

Are independent of each other. Each one live on its own and are not realted to each other.

Are also composer projects, using all composer stuff (autoloading, psr4, etc).

Both framework and website are private projects and due to company policy, cannot be shared neither in GITHUB, nor Packagist.

Framework composer.json

{
    "name": "Company/Framework",
    "require": {
        "php": ">=5.6.4",
        "mpdf/mpdf": "dev-master",
        "monolog/monolog":"1.2"
    },
    "autoload": {
        "psr-4": {
            "Company\\Framework\\": "src/"
        }
    }
}

Each website composer.json:

{
    "repositories": [
        {
            "type": "path",
            "url": "../Framework/",
            "options": {
                "symlink": false
            }
        }
    ],
    "require": {
        "Company/Framework": "dev-master",
        "mpdf/mpdf": "dev-master"
    },
    "autoload": {
        "psr-4": {
            "Company\\Site01\\": "src/"
        }
    }
}

My problem is, that composer populates every website's vendor directory with its dependencies and entire framework directory.

Finally, All ended up with a huge ammount of disk space used, about 40+ GB, mainly with a same VENDOR packages, repeated over and over again.
Our PHP code is less than 1% of the entire project.

My questions are:

What are the best practices to develop my private packages (not
shared in the public) and reuse them in other projects?

How can I properly reuse common composer libraries, without duplicating hude ammount of Vendor code over and over again?


问:
Why does my listview display the button and edittext as well?
My listview display all componenents.
But I want to display only messages.

Here the pic of whatit looks like...

Loooks very messy
The pic

The TextView(source of message) and Button were repeated below the next message.if there is possibility that I can se that function without a textview I think it would be better.I mean if that list view receives messages directly from the URL (googlespreadsheet).

Here those are my scripts.Thanks in advance

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Message">

    <TextView
        android:id="@+id/mesaj"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="42dp"
        android:textColor="@android:color/white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/listviewmes" />
    <EditText
        android:id="@+id/mesajtext"
        android:layout_width="298dp"
        android:layout_height="46dp"
        android:layout_marginStart="16dp"
        android:layout_marginBottom="16dp"
        android:hint="Mesajiniz..."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/sendbutton"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mesaj"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/sendbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="7dp"
        app:layout_constraintBaseline_toBaselineOf="@+id/mesajtext"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/mesajtext"
        app:layout_constraintTop_toTopOf="parent"/>

    <ListView
        android:id="@+id/listviewmes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bck"
        android:theme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </ListView>

</android.support.constraint.ConstraintLayout>

public class Message extends AppCompatActivity {
FirebaseUser fuser;
FirebaseDatabase database;
FirebaseAuth mAuth;
EditText et;
TextView tv;
ProgressDialog pd;
ListView lview;
ListAdapter adaptery;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_message);
    database = FirebaseDatabase.getInstance();
    mAuth = FirebaseAuth.getInstance();

    Button sendbtn;
    Toolbar toolbar;

    sendbtn = findViewById(R.id.sendbutton);
    //tv = findViewById(R.id.mesaj);
    et = findViewById(R.id.mesajtext);
    lview = findViewById(R.id.listviewmes);
    getItems();

    sendbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addItemToSheet();
            et.getText().clear();

        }
    });
}`

`private void addItemToSheet() {
    final String mesaj = et.getText().toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, "MY URL SEND TO GOOGLE SHEET",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> parmas = new HashMap<>();
            parmas.put("action", "addItem");
            parmas.put("mesaj", mesaj);

            return parmas;
        }
    };
    int socketTimeOut = 50000;// u can change this .. here it is 50 seconds
    RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(retryPolicy);

    RequestQueue queue = Volley.newRequestQueue(this);

    queue.add(stringRequest);
}

public void sendMessage(View v) {
    FirebaseUser user = mAuth.getCurrentUser();
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference();
    UUID uuid = UUID.randomUUID();
    String stuuid = uuid.toString();
    String mesaj = et.getText().toString();

}

private void getItems() {

    pd = ProgressDialog.show(this, "Loading", "please wait", false, true);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, "MY URL MESSAGES GET FROM GOOGLE SHEET",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    parseItems(response);

                }

            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }
    );
    int socketTimeOut = 50000;// u can change this .. here it is 50 seconds

    RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(retryPolicy);

    RequestQueue queue = Volley.newRequestQueue(this);

    queue.add(stringRequest);
}
private void parseItems(String jsonResposnce) {

    ArrayList<HashMap<String, String>> list = new ArrayList<>();
    ArrayList<String>Mesajlar=new ArrayList<String>();

    try {
        JSONObject jobj = new JSONObject(jsonResposnce);
        JSONArray jarray = jobj.getJSONArray("items");

        for (int i = 0; i < jarray.length(); i++) {

            JSONObject jo = jarray.getJSONObject(i);
            String mesaj = jo.getString("mesaj");

            HashMap<String, String> item = new HashMap<>();
            item.put("mesaj", mesaj);

            list.add(item);

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

    `adaptery = new SimpleAdapter(this,list,R.layout.activity_message,
            new String[]{"mesaj"},new int[]{R.id.mesaj, android.R.layout.simple_list_item_1,list});

    lview.setAdapter(adaptery);
    pd.dismiss();
}}
</code>```

答:
user RecyclerView instead of ListView (ListView don't free memory but RecyclerView is a ListView that is work better) and then in the Adapter Class you have a class named MyViewHolder that extend from RecyclerView.ViewHolder
in this class you will have all of your view in the layout you want to set to the RecyclerView
in the Adapetr Class you have a function named : onBindViewHolder and has an input of your MyViewHolder , you can hide the button there

```<code>public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i)
        {
             if(condition)
                myViewHolder.button.setVisibilty(View.GONE);
        }
</code>```

here is the myViewHolder

```<code>public class MyViewHolder extends RecyclerView.ViewHolder
{
    TextView txt;
    Button btn;
    public MyViewHolder(View itemView)
    {
        super(itemView);
        txt= itemView.findViewById(R.id.txt);
        btn= itemView.findViewById(R.id.btn)
    }
}
</code>```

i don't know why every row has a button and a EditText in you code , but if the EditText is fro URL and button for confirm the operation(loading data from URL) you don't need to add those in your list layout ! you should add one button and one EditText above of your activity and set a RecyclerView below them

Body:
My listview display all componenents.
But I want to display only messages.

Here the pic of whatit looks like...

Loooks very messy
The pic

The TextView(source of message) and Button were repeated below the next message.if there is possibility that I can se that function without a textview I think it would be better.I mean if that list view receives messages directly from the URL (googlespreadsheet).

Here those are my scripts.Thanks in advance

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Message">

    <TextView
        android:id="@+id/mesaj"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="42dp"
        android:textColor="@android:color/white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/listviewmes" />
    <EditText
        android:id="@+id/mesajtext"
        android:layout_width="298dp"
        android:layout_height="46dp"
        android:layout_marginStart="16dp"
        android:layout_marginBottom="16dp"
        android:hint="Mesajiniz..."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/sendbutton"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mesaj"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/sendbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="7dp"
        app:layout_constraintBaseline_toBaselineOf="@+id/mesajtext"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/mesajtext"
        app:layout_constraintTop_toTopOf="parent"/>

    <ListView
        android:id="@+id/listviewmes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bck"
        android:theme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </ListView>

</android.support.constraint.ConstraintLayout>

public class Message extends AppCompatActivity {
FirebaseUser fuser;
FirebaseDatabase database;
FirebaseAuth mAuth;
EditText et;
TextView tv;
ProgressDialog pd;
ListView lview;
ListAdapter adaptery;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_message);
    database = FirebaseDatabase.getInstance();
    mAuth = FirebaseAuth.getInstance();

    Button sendbtn;
    Toolbar toolbar;

    sendbtn = findViewById(R.id.sendbutton);
    //tv = findViewById(R.id.mesaj);
    et = findViewById(R.id.mesajtext);
    lview = findViewById(R.id.listviewmes);
    getItems();

    sendbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addItemToSheet();
            et.getText().clear();

        }
    });
}`

`private void addItemToSheet() {
    final String mesaj = et.getText().toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, "MY URL SEND TO GOOGLE SHEET",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> parmas = new HashMap<>();
            parmas.put("action", "addItem");
            parmas.put("mesaj", mesaj);

            return parmas;
        }
    };
    int socketTimeOut = 50000;// u can change this .. here it is 50 seconds
    RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(retryPolicy);

    RequestQueue queue = Volley.newRequestQueue(this);

    queue.add(stringRequest);
}

public void sendMessage(View v) {
    FirebaseUser user = mAuth.getCurrentUser();
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference();
    UUID uuid = UUID.randomUUID();
    String stuuid = uuid.toString();
    String mesaj = et.getText().toString();

}

private void getItems() {

    pd = ProgressDialog.show(this, "Loading", "please wait", false, true);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, "MY URL MESSAGES GET FROM GOOGLE SHEET",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    parseItems(response);

                }

            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }
    );
    int socketTimeOut = 50000;// u can change this .. here it is 50 seconds

    RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(retryPolicy);

    RequestQueue queue = Volley.newRequestQueue(this);

    queue.add(stringRequest);
}
private void parseItems(String jsonResposnce) {

    ArrayList<HashMap<String, String>> list = new ArrayList<>();
    ArrayList<String>Mesajlar=new ArrayList<String>();

    try {
        JSONObject jobj = new JSONObject(jsonResposnce);
        JSONArray jarray = jobj.getJSONArray("items");

        for (int i = 0; i < jarray.length(); i++) {

            JSONObject jo = jarray.getJSONObject(i);
            String mesaj = jo.getString("mesaj");

            HashMap<String, String> item = new HashMap<>();
            item.put("mesaj", mesaj);

            list.add(item);

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

    `adaptery = new SimpleAdapter(this,list,R.layout.activity_message,
            new String[]{"mesaj"},new int[]{R.id.mesaj, android.R.layout.simple_list_item_1,list});

    lview.setAdapter(adaptery);
    pd.dismiss();
}}

Body:
user RecyclerView instead of ListView (ListView don't free memory but RecyclerView is a ListView that is work better) and then in the Adapter Class you have a class named MyViewHolder that extend from RecyclerView.ViewHolder
in this class you will have all of your view in the layout you want to set to the RecyclerView
in the Adapetr Class you have a function named : onBindViewHolder and has an input of your MyViewHolder , you can hide the button there

public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i)
        {
             if(condition)
                myViewHolder.button.setVisibilty(View.GONE);
        }

here is the myViewHolder

public class MyViewHolder extends RecyclerView.ViewHolder
{
    TextView txt;
    Button btn;
    public MyViewHolder(View itemView)
    {
        super(itemView);
        txt= itemView.findViewById(R.id.txt);
        btn= itemView.findViewById(R.id.btn)
    }
}

i don't know why every row has a button and a EditText in you code , but if the EditText is fro URL and button for confirm the operation(loading data from URL) you don't need to add those in your list layout ! you should add one button and one EditText above of your activity and set a RecyclerView below them


问:
Methods, Loops and the `this` Keyword
I am new at Javascript. I am currently looking at the keyword this and methods and how to return strings.
I am struggling to return a string using the keyword this.

I have successfully created code that returns the string, but the problem is that it shows the error that "the object is already defined".

Here is the exercise I am working on and also the code I have tried to create which fails to return the correct results:

```<code>function exerciseTwo(userObj) {

  // Exercise Two: You will be given an object called 'userObj'
  // userObject will already have a key on it called 'name'
  // Add a method to userObj, called 'greeting'.
  // Using the keyword 'this', the greeting method should return the following string:
  // 'Hi, my name is ' and the users name.
  // eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
  // NOTE: DO NOT create a new object.
  // NOTE: DO NOT create a key called name the key is already on the object.

  let userObj = {
    name: "Lisa",
    greeting: function() {
      return "Hi, my name is " + this.name;
    },
  };
  console.log(userObj.greeting());
}

//In the first line of code it shows a error which says that "userObj" is already defined. So I do not know how to return the string without creating a new object and creating a key called name.

//Here is another option I tried but it also did not work out:

function greeting() {
  this.name = "Lisa";
  let result = "Hi, my name is " + this.name;
  return result;
},
userObj.greeting();
}

//The exercise should add a greeting method to userObject object.
</code>```

So if userObj has a name: 'Lisa', greeting should return: 'Hi, my name is Lisa'

答:
The problem is that your local variable has the same name as the function parameter. You're supposed to add a method to the existing variable, not create a new variable. The instructions specifically say "DO NOT create a new object", yet that is what you did.

function exerciseTwo(userObj) {

  // Exercise Two: You will be given an object called 'userObj'
  // userObject will already have a key on it called 'name'
  // Add a method to userObj, called 'greeting'.
  // Using the keyword 'this', the greeting method should return the following string:
  // 'Hi, my name is ' and the users name.
  // eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
  // NOTE: DO NOT create a new object.
  // NOTE: DO NOT create a key called name the key is already on the object.

  userObj.greeting = function() {
    return "Hi, my name is " + this.name;
  };
  console.log(userObj.greeting());
}

let obj = {
  name: "Joe"
};
exerciseTwo(obj);```

Title: Methods, Loops and the `this` Keyword

Body:
I am new at Javascript. I am currently looking at the keyword this and methods and how to return strings.
I am struggling to return a string using the keyword this.

I have successfully created code that returns the string, but the problem is that it shows the error that "the object is already defined".

Here is the exercise I am working on and also the code I have tried to create which fails to return the correct results:

function exerciseTwo(userObj) {

  // Exercise Two: You will be given an object called 'userObj'
  // userObject will already have a key on it called 'name'
  // Add a method to userObj, called 'greeting'.
  // Using the keyword 'this', the greeting method should return the following string:
  // 'Hi, my name is ' and the users name.
  // eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
  // NOTE: DO NOT create a new object.
  // NOTE: DO NOT create a key called name the key is already on the object.

  let userObj = {
    name: "Lisa",
    greeting: function() {
      return "Hi, my name is " + this.name;
    },
  };
  console.log(userObj.greeting());
}

//In the first line of code it shows a error which says that "userObj" is already defined. So I do not know how to return the string without creating a new object and creating a key called name.

//Here is another option I tried but it also did not work out:

function greeting() {
  this.name = "Lisa";
  let result = "Hi, my name is " + this.name;
  return result;
},
userObj.greeting();
}

//The exercise should add a greeting method to userObject object.

So if userObj has a name: 'Lisa', greeting should return: 'Hi, my name is Lisa'


问:
TransactionTooLargeException when startActivityForResult
I have an Android app that is failing in devices with 1GB of RAM.

I'm getting TransactionTooLargeException when opening activities with startActivityForResult. If a change them to startActivity it works but I need the result of those activities.

I follow some suggestions like the following but it didn't work for me:

```<code>@Override
    protected void onSaveInstanceState(Bundle oldInstanceState) {
        super.onSaveInstanceState(oldInstanceState);
        oldInstanceState.clear();
    }
</code>```

An important comment is that I'm not getting any information from the backend, so it's not a large json file which is causing this.

Also the intent is very simple:

```<code>intent = new Intent(getActivity(), OtherPaymentAddActivity.class);
                intent.putExtra("isAdd", true);
                startActivityForResult(intent, Constants.OTHER_PAYMENT_ADDED);
                break;
</code>```

Is there a way to avoid this issue?

Here you have the LogCat

```<code>    Event recorded: Event{appId='com.payment.collection', name='screen_view(_vs)', params=Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainFragmentManager, firebase_previous_id(_pi)=-1269867677418891571, firebase_screen_class(_sc)=CheckAddActivity, firebase_screen_id(_si)=-1269867677418891570}]}
05-28 13:20:57.631 2291-3874/com.google.android.gms V/FA: Upload scheduled in approximately ms: 3362813
    Cancelling job. JobID: 812057698
05-28 13:20:57.632 2291-3874/com.google.android.gms V/FA: Scheduling upload with GcmTaskService
    Scheduling task with Gcm. time: 3362813
05-28 13:20:57.635 2291-3874/com.google.android.gms V/FA: Background event processing time, ms: 8
05-28 13:20:58.004 3564-3564/com.payment.collection E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 523184)
05-28 13:20:58.004 3564-3564/com.payment.collection D/AndroidRuntime: Shutting down VM

    --------- beginning of crash
05-28 13:20:58.007 3564-3564/com.payment.collection E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.payment.collection, PID: 3564
    java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 523184 bytes
        at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3752)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: android.os.TransactionTooLargeException: data parcel size 523184 bytes
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(Binder.java:615)
        at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3606)
        at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3744)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
05-28 13:20:58.011 1615-1863/system_process W/ActivityManager:   Force finishing activity com.payment.collection/.MainActivities.CheckAddActivity
05-28 13:20:58.055 1615-1683/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
05-28 13:20:58.055 1615-1683/system_process D/OpenGLRenderer: Swap behavior 1
05-28 13:20:58.056 1615-1683/system_process W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVE
</code>```

答:
At the end, it was that I was sending in a Bundle to a Fragment a list of items as serializable that contains like 3K items, it were not complex items, just Objects with some properties...

So, I re adjust the logic to avoid having to do that. As a lesson learnt, attention to what you put in:

```<code>Bundle bundle = new Bundle();
bundle.putSerializable("list", itemList);
</code>```

Body:
I have an Android app that is failing in devices with 1GB of RAM.

I'm getting TransactionTooLargeException when opening activities with startActivityForResult. If a change them to startActivity it works but I need the result of those activities.

I follow some suggestions like the following but it didn't work for me:

@Override
    protected void onSaveInstanceState(Bundle oldInstanceState) {
        super.onSaveInstanceState(oldInstanceState);
        oldInstanceState.clear();
    }

An important comment is that I'm not getting any information from the backend, so it's not a large json file which is causing this.

Also the intent is very simple:

intent = new Intent(getActivity(), OtherPaymentAddActivity.class);
                intent.putExtra("isAdd", true);
                startActivityForResult(intent, Constants.OTHER_PAYMENT_ADDED);
                break;

Is there a way to avoid this issue?

Here you have the LogCat

    Event recorded: Event{appId='com.payment.collection', name='screen_view(_vs)', params=Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=MainFragmentManager, firebase_previous_id(_pi)=-1269867677418891571, firebase_screen_class(_sc)=CheckAddActivity, firebase_screen_id(_si)=-1269867677418891570}]}
05-28 13:20:57.631 2291-3874/com.google.android.gms V/FA: Upload scheduled in approximately ms: 3362813
    Cancelling job. JobID: 812057698
05-28 13:20:57.632 2291-3874/com.google.android.gms V/FA: Scheduling upload with GcmTaskService
    Scheduling task with Gcm. time: 3362813
05-28 13:20:57.635 2291-3874/com.google.android.gms V/FA: Background event processing time, ms: 8
05-28 13:20:58.004 3564-3564/com.payment.collection E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 523184)
05-28 13:20:58.004 3564-3564/com.payment.collection D/AndroidRuntime: Shutting down VM

    --------- beginning of crash
05-28 13:20:58.007 3564-3564/com.payment.collection E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.payment.collection, PID: 3564
    java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 523184 bytes
        at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3752)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: android.os.TransactionTooLargeException: data parcel size 523184 bytes
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(Binder.java:615)
        at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3606)
        at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3744)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
05-28 13:20:58.011 1615-1863/system_process W/ActivityManager:   Force finishing activity com.payment.collection/.MainActivities.CheckAddActivity
05-28 13:20:58.055 1615-1683/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
05-28 13:20:58.055 1615-1683/system_process D/OpenGLRenderer: Swap behavior 1
05-28 13:20:58.056 1615-1683/system_process W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVE

Body:
At the end, it was that I was sending in a Bundle to a Fragment a list of items as serializable that contains like 3K items, it were not complex items, just Objects with some properties...

So, I re adjust the logic to avoid having to do that. As a lesson learnt, attention to what you put in:

Bundle bundle = new Bundle();
bundle.putSerializable("list", itemList);


问:
How to delegate back to the previous veiwcontroller
here is my navigation on my app

1) homescreenview controller-->composemessageviewcontroller (i am able to use delegate to send data back to homescreenview)

2)homescreenview controller -->messageslistcontroller(tableview)-->detailmessageviewcontroller(which is where my reply button is).

my problem is when i hit reply i want to send back information to homescreenviewcontroller with delegate . how can i do this?

Thanks in advance.

----UPDATE

@XJones, thanks for the detailed explanaion. is this what is should be doing in when i push detailview? please correct me if i am wrong.

(void)pushDetailMessageController{
DetailMessagetController *detailmessage = [[DetailMessagetController alloc] init];
detailmessage.delegate = self;
// push messageListController onto navigation controller here
[detail release];
}

答:
How about adding a method in the messageslistcontroller? I personally would add the delegate "homescreenview" to the detailmessageviewcontroller as the messageslistcontroller doesn't have anything to do with the reply and apperantly the homescreenviewcontroller does.

when you create the detailmessageviewcontroller in the messageslistcontroller do this:

```<code>detailmessageviewcontroller.homeScreenDelegate = self.delegate;
</code>```

Body:
How about adding a method in the messageslistcontroller? I personally would add the delegate "homescreenview" to the detailmessageviewcontroller as the messageslistcontroller doesn't have anything to do with the reply and apperantly the homescreenviewcontroller does.

when you create the detailmessageviewcontroller in the messageslistcontroller do this:

detailmessageviewcontroller.homeScreenDelegate = self.delegate;


问:
how do i sum all results that match criteria on 2 axis
I have a grid with variable headers on the X and Y axis and values under some of those (think of an old distance to - from in the back of an old MAP) with the same headers on both axis however some headers will be repeated. i want to sum all the matches on my given singular criteria of the header

i.e. a b c along the top a b a c a d along the side and various number filling in the grid I want to count all where a is the header on both axis

I have tried various sum, match, index, UDF  Functions that i cant seem to get right

```<code>=SUM(INDEX(C4:P35,MATCH("SICK",C4:C35,0),MATCH("SICK",C4:P4,)))
</code>```

This seems to return the first match but not sum any subsequent matches

I expect the sum to return all the matches to the index rather than the first

Body:
I have a grid with variable headers on the X and Y axis and values under some of those (think of an old distance to - from in the back of an old MAP) with the same headers on both axis however some headers will be repeated. i want to sum all the matches on my given singular criteria of the header

i.e. a b c along the top a b a c a d along the side and various number filling in the grid I want to count all where a is the header on both axis

I have tried various sum, match, index, UDF  Functions that i cant seem to get right

=SUM(INDEX(C4:P35,MATCH("SICK",C4:C35,0),MATCH("SICK",C4:P4,)))

This seems to return the first match but not sum any subsequent matches

I expect the sum to return all the matches to the index rather than the first

Body: =SUMPRODUCT($D$5:$P$35*($C$5:$C$35="SICK")*($D$4:$P$4="SICK"))


问:
Swift didReceiveRemoteNotification not called
I have an app with oneSignal as push provider. I can receive push notifications, that work good. But if I try to access push payload I get nothing as didReceiveRemoteNotification not called.

I have following code

```<code>func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

 if application.applicationState != UIApplicationState.Background {

        let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
        let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
        var pushPayload = false
        if let options = launchOptions {
            pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
        }

    }
    if application.respondsToSelector("registerUserNotificationSettings:") {
        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    } else {
        let types : UIRemoteNotificationType =  [.Badge, .Alert, .Sound]
        application.registerForRemoteNotificationTypes(types)
    }

}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    if userInfo["d"] as! String == "t"  {

        print("key was received")

    }
    print(userInfo)
    print("PREVED")

}
</code>```

Problem is that nothing prints out when I receive push. What am I doing wrong ?

答:
Pretty old post but solutions can be found here in my post Push Notifications are delivered but didReceiveRemoteNotification is never called Swift or here didReceiveRemoteNotification function doesn't called with FCM notification server.
Check for this parameter: "content_available": truein your notification definition or push notification service. With underscore is how it should be set.

Body:
I have an app with oneSignal as push provider. I can receive push notifications, that work good. But if I try to access push payload I get nothing as didReceiveRemoteNotification not called.

I have following code

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

 if application.applicationState != UIApplicationState.Background {

        let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
        let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
        var pushPayload = false
        if let options = launchOptions {
            pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
        }

    }
    if application.respondsToSelector("registerUserNotificationSettings:") {
        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    } else {
        let types : UIRemoteNotificationType =  [.Badge, .Alert, .Sound]
        application.registerForRemoteNotificationTypes(types)
    }

}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    if userInfo["d"] as! String == "t"  {

        print("key was received")

    }
    print(userInfo)
    print("PREVED")

}

Problem is that nothing prints out when I receive push. What am I doing wrong ?


问:
How to get unique customer names those have different IDS
I am working with a table that contains Account_No as unique ID, Customer_Name, Building_Name. The table below is an example:

It can be seen for few cases there are same customer name and same building however different Account_No. I need to remove duplicate names even though they have unique Account_No. Building_Name and Customer_Name are ties together. For example "William----Science City" and "William-----River Club" should be count as two customers since they are residing in different buildings. The result table should look as below;

I need to use SQL for creating the resulting table. Kindly use Customer Table as the reference for SQL query. Thanks

答:
```<code>Select Min(Account_No) As Account_No
       ,Customer_Name,Building_Name
From Customer_Table
Group By Customer_Name, Building_Name
</code>```


问:
SOCAT, forwarding TCP socket to a Unix Socket, changes recvmsg() to read(), drops ancillary data
I am using socat to forward a TCP socket to a unix domain socket

Here is an example command:

```<code>socat TCP-LISTEN:<PORT> UNIX-CONNECT:<UNIX DOMAIN SOCKET>
</code>```

I need to read ancillary data out of the socket, and my problem is that socat is 'changing' the recvmsg() calls (from my TCP socket), and normal read() calls on the unix socket. As I understand, there is no way a read() call can get the ancillary data.

My (python) client is remote, and calls recvmsg on the tcp socket.

From a strace of my client:

```<code>recvmsg(3, {msg_name(0)=0x7ffc14322490, msg_iov(1)=[{"\360", 1}], msg_controllen=0, msg_flags=0}, 0) = 1
recvmsg(3, {msg_name(0)=0x7ffc14322490, msg_iov(1)=[{"\252", 1}], msg_controllen=0, msg_flags=0}, 0) = 1
</code>```

Here is a strace of a program that reads directly from the unix socket, The data I need is the [5], in the ancillary data. This is what I want the strace on my remote machine to look like:

```<code>recvmmsg(3, {{
{msg_name(0)=NULL, msg_iov(1)=[{"\360", 1}], msg_controllen=20, [{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, [5]}], msg_flags=0}, 1}, {
{msg_name(0)=NULL, msg_iov(1)=[{"\252", 1}], msg_controllen=20, [{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, [6]}], msg_flags=0}, 1}, {
</code>```

Here is a strace on the remote maching where socat is running / the read syscalls are being made. Notice that its reading the msg_iov data (the non ancillary data). The very top recvmsg's from my client are being translated into read() calls by socat on my remote machine

```<code>read(5, "\360", 8192)                   = 1
read(5, "\252", 8192)                   = 1
</code>```

Is there a way I can make socat not change these recvmsg calls into read() calls?

答: Ancillary data is not sent over the wire / via TCP. Thats the answer I believe, frustratingly this information is seldom provided.</p>

Body:
I am using socat to forward a TCP socket to a unix domain socket

Here is an example command:

socat TCP-LISTEN:<PORT> UNIX-CONNECT:<UNIX DOMAIN SOCKET>

I need to read ancillary data out of the socket, and my problem is that socat is 'changing' the recvmsg() calls (from my TCP socket), and normal read() calls on the unix socket. As I understand, there is no way a read() call can get the ancillary data.

My (python) client is remote, and calls recvmsg on the tcp socket.

From a strace of my client:

recvmsg(3, {msg_name(0)=0x7ffc14322490, msg_iov(1)=[{"\360", 1}], msg_controllen=0, msg_flags=0}, 0) = 1
recvmsg(3, {msg_name(0)=0x7ffc14322490, msg_iov(1)=[{"\252", 1}], msg_controllen=0, msg_flags=0}, 0) = 1

Here is a strace of a program that reads directly from the unix socket, The data I need is the [5], in the ancillary data. This is what I want the strace on my remote machine to look like:

recvmmsg(3, {{
{msg_name(0)=NULL, msg_iov(1)=[{"\360", 1}], msg_controllen=20, [{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, [5]}], msg_flags=0}, 1}, {
{msg_name(0)=NULL, msg_iov(1)=[{"\252", 1}], msg_controllen=20, [{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, [6]}], msg_flags=0}, 1}, {

Here is a strace on the remote maching where socat is running / the read syscalls are being made. Notice that its reading the msg_iov data (the non ancillary data). The very top recvmsg's from my client are being translated into read() calls by socat on my remote machine

read(5, "\360", 8192)                   = 1
read(5, "\252", 8192)                   = 1

Is there a way I can make socat not change these recvmsg calls into read() calls?


问:
.NET Core adding client certificate to POST to Kestrel REST API on Linux fails server cert validation
I am using .NET Core 2.1, Kestrel on Linux.

My web application acting as client makes a request as so (following guides dotted around, this seems to the way to go):

```<code>var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
X509Certificate2 cert = GetClientCertificate();
handler.ClientCertificates.Add(cert);

using (var client = new HttpClient(handler))
     {
        var myRequest= new myRequest()
          {
                foo = bar,
            };

var response = await client.PostAsync(myUrl, myRequest, new JsonMediaTypeFormatter());
</code>```

I have configured Kestrel as so:

```<code>    return WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Listen(IPAddress.Any, 443, listenOptions =>
            {

            var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
                {
                    ClientCertificateMode = ClientCertificateMode.RequireCertificate,
                    SslProtocols = System.Security.Authentication.SslProtocols.Tls12,
                    ServerCertificate = GetSSLCertificate(),
                    ClientCertificateValidation = CertificateValidator.MyCustomerValidatorForLogging
                };
                listenOptions.UseHttps(httpsConnectionAdapterOptions);
            });
        }
        )
    .Build();
</code>```

I added a custom validator (just to see what is going on, looks like this):

```<code>public static bool MyCustomerValidatorForLogging(X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors)
        {
            Log.Info("Received Request");
            Log.Error(errors.ToString());

            if (errors == SslPolicyErrors.None)
            {
                return true;
            }

            return false;
        }
</code>```

GetClientCertificate() is the certificate for client authentication SSL cert signed by an intermediate CA.

GetSSLCertificate() is the certificate for a standard server authentication SSL cert.

I have copied the issuing Sub CA and CA certs of the client authentication cert in to  /usr/local/share/ca-certificates/ (the "store") and issued the "update-ca-certificates" command. I believe it is these certs that are used to verify the client cert.

When the server receives the request, the errors value is:
"RemoteCertificateChainErrors" and rejects the request.

Anyone have any ideas please?

答:
Turns out this is actually working! I just needed to get the correct certificates in place!

Specifically, I had to include the Root CA and Intermediate CA at the Server side.

The Client side, I had to include only the Root CA to verify.

Body:
I am using .NET Core 2.1, Kestrel on Linux.

My web application acting as client makes a request as so (following guides dotted around, this seems to the way to go):

var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
X509Certificate2 cert = GetClientCertificate();
handler.ClientCertificates.Add(cert);

using (var client = new HttpClient(handler))
     {
        var myRequest= new myRequest()
          {
                foo = bar,
            };

var response = await client.PostAsync(myUrl, myRequest, new JsonMediaTypeFormatter());

I have configured Kestrel as so:

    return WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            options.Listen(IPAddress.Any, 443, listenOptions =>
            {

            var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
                {
                    ClientCertificateMode = ClientCertificateMode.RequireCertificate,
                    SslProtocols = System.Security.Authentication.SslProtocols.Tls12,
                    ServerCertificate = GetSSLCertificate(),
                    ClientCertificateValidation = CertificateValidator.MyCustomerValidatorForLogging
                };
                listenOptions.UseHttps(httpsConnectionAdapterOptions);
            });
        }
        )
    .Build();

I added a custom validator (just to see what is going on, looks like this):

public static bool MyCustomerValidatorForLogging(X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors)
        {
            Log.Info("Received Request");
            Log.Error(errors.ToString());

            if (errors == SslPolicyErrors.None)
            {
                return true;
            }

            return false;
        }

GetClientCertificate() is the certificate for client authentication SSL cert signed by an intermediate CA.

GetSSLCertificate() is the certificate for a standard server authentication SSL cert.

I have copied the issuing Sub CA and CA certs of the client authentication cert in to  /usr/local/share/ca-certificates/ (the "store") and issued the "update-ca-certificates" command. I believe it is these certs that are used to verify the client cert.

When the server receives the request, the errors value is:
"RemoteCertificateChainErrors" and rejects the request.

Anyone have any ideas please?


问:
Selenium Webdrive (VBA) - find an element's attribute, where there are duplicate attributes of the same name
I am trying to store the value "1234567!1234567" from the attribute data-orderid in a cell within my worksheet

The code I'm using in VBA is:

```<code>Cells(x,y) = d.FindElementByXPath("/html/body/table[3]/tr[@class='report']").getAttribute("data-orderid").Text
</code>```

And this is an example of the HTML code I am trying to get the info from:

```<code><body>
<table class="report">
    <tr class="wide">...</tr>
    <tr data-orderid="1234567!1234567" data-index="1" data-
    thumbnail="www.image.jpg">...</tr>`
</code>```

The expected output is "1234567!1234567" but the error: NoSuchElementError, ElementNotFound pops up as I try to run my code

答:
Try the following. The method for selenium vba is Attribute

```<code>d.findElementByCss("[data-index='1']").Attribute("data-orderid")
</code>```

You don't need .text on the end.

Body:
I am trying to store the value "1234567!1234567" from the attribute data-orderid in a cell within my worksheet

The code I'm using in VBA is:

Cells(x,y) = d.FindElementByXPath("/html/body/table[3]/tr[@class='report']").getAttribute("data-orderid").Text

And this is an example of the HTML code I am trying to get the info from:

...

...
`

The expected output is "1234567!1234567" but the error: NoSuchElementError, ElementNotFound pops up as I try to run my code

Body:
Try the following. The method for selenium vba is Attribute

d.findElementByCss("[data-index='1']").Attribute("data-orderid")

You don't need .text on the end.


问:
Are all apps localized to, say, Serbian by default?
My app is in the App Store and I had pulled it up so I can share the link with someone. I looked at the languages and saw something really strange.

The app was listed as localized for several languages which I didn't use. I don't even know what half of those languages sound like.

Is this a problem with iTunes, or is it more likely with my App submission?

Here's a screenshot:

Edit - iTunes Connect seems to read the same info from the binary:

答:
Your submission, most likely. Check iTunesConnect and edit the details of your app, unchecking any languages you don't support.

Automatic localization occurs for default controls (e.g. an Edit nav bar button), but nothing else is automatic.

OwnerDisplayName: Moshe


问:
Any ideas why VBA isn't being case-sensitive in a VLookup?
I've created a VBA Macro to look at a string of input text in the cell E3, split it into individual characters and then VLookup those characters against a table of individual character pixel widths, which is added to the code using a named range, "pw_Table".

The pixel-widths for each letter are then summed and displayed in a cell below the text input box - "Cells(4,5)". Hitting return is meant to show the combined pixel-width total for the complete string.

The problem is that it is not being case sensitive and is using the same VLookup value for both upper and lower case characters.

All the manuals I've seen say VBA is case sensitive on VLookup, and all I can find are ways to get around this.

For my issue, however, the VLookup must be case sensitive to make sure I get the correct pixel width for each letter, for example, "c" is 9 pixels wide, "C" is 13.

I have tried reordering the upper and lower case characters in the table to see if that made a difference, but it only uses the first values it encounters for each letter of the alphabet, whether they be upper- or lower-case.

I thought that I might use INDEX, MATCH, and EXACT, but couldn't see how to implement that in VBA.

This is the Macro code ...

```<code>Private Sub ReadCharacter()
    cell_value = ThisWorkbook.Sheets("Pixel-widths").Range("E3")
    Character_Value = 0
    For rep = 1 To Len(cell_value)
        Character = Mid(cell_value, rep, 1)
        On Error GoTo MyErrorHandler
        Character_Value = Application.WorksheetFunction.VLookup(Character, [pw_Table], 2, 0)
        Pixel_Width = Pixel_Width + Character_Value
MyErrorHandler:
        Character_Value = 10
        Resume Next
    Next rep
        Cells(4, 5) = Pixel_Width
End Sub
</code>```

I had some issues with numbers, with VBA reporting Run-time Error 1004, but I bodged this by adding an error trap because all the numerals from 0-9 are 10 pixels wide.

I simply can't see why VBA is breaking its own rules.

答:
Vlookup isnt case sensitive.

ive found this function that "simulates" a vlookup case sensitive.

```<code>Function CaseVLook(FindValue, TableArray As Range, Optional ColumnID As Integer = 1) As Variant
    Dim xCell As Range
    Application.Volatile
    CaseVLook = "Not Found"
    For Each xCell In TableArray.Columns(1).Cells
        If xCell = FindValue Then
            CaseVLook = xCell.Offset(0, ColumnID - 1)
            Exit For
        End If
    Next
End Function
</code>```

to use it just call it CaseVLook(F1,A1:C7,3)

more information in here

https://www.extendoffice.com/documents/excel/3449-excel-vlookup-case-sensitive-insensitive.html

good luck

Body:
I've created a VBA Macro to look at a string of input text in the cell E3, split it into individual characters and then VLookup those characters against a table of individual character pixel widths, which is added to the code using a named range, "pw_Table".

The pixel-widths for each letter are then summed and displayed in a cell below the text input box - "Cells(4,5)". Hitting return is meant to show the combined pixel-width total for the complete string.

The problem is that it is not being case sensitive and is using the same VLookup value for both upper and lower case characters.

All the manuals I've seen say VBA is case sensitive on VLookup, and all I can find are ways to get around this.

For my issue, however, the VLookup must be case sensitive to make sure I get the correct pixel width for each letter, for example, "c" is 9 pixels wide, "C" is 13.

I have tried reordering the upper and lower case characters in the table to see if that made a difference, but it only uses the first values it encounters for each letter of the alphabet, whether they be upper- or lower-case.

I thought that I might use INDEX, MATCH, and EXACT, but couldn't see how to implement that in VBA.

This is the Macro code ...

Private Sub ReadCharacter()
    cell_value = ThisWorkbook.Sheets("Pixel-widths").Range("E3")
    Character_Value = 0
    For rep = 1 To Len(cell_value)
        Character = Mid(cell_value, rep, 1)
        On Error GoTo MyErrorHandler
        Character_Value = Application.WorksheetFunction.VLookup(Character, [pw_Table], 2, 0)
        Pixel_Width = Pixel_Width + Character_Value
MyErrorHandler:
        Character_Value = 10
        Resume Next
    Next rep
        Cells(4, 5) = Pixel_Width
End Sub

I had some issues with numbers, with VBA reporting Run-time Error 1004, but I bodged this by adding an error trap because all the numerals from 0-9 are 10 pixels wide.

I simply can't see why VBA is breaking its own rules.

Body:
Vlookup isnt case sensitive.

ive found this function that "simulates" a vlookup case sensitive.

Function CaseVLook(FindValue, TableArray As Range, Optional ColumnID As Integer = 1) As Variant
    Dim xCell As Range
    Application.Volatile
    CaseVLook = "Not Found"
    For Each xCell In TableArray.Columns(1).Cells
        If xCell = FindValue Then
            CaseVLook = xCell.Offset(0, ColumnID - 1)
            Exit For
        End If
    Next
End Function

to use it just call it CaseVLook(F1,A1:C7,3)

more information in here

https://www.extendoffice.com/documents/excel/3449-excel-vlookup-case-sensitive-insensitive.html

good luck


问:
Execute get-childitem, but iterate in reverse order?
I have a folder full of 500,00+ files. I'm trying to iterate through this folder and run some logic to determine if we can delete unneeded files. The problem is this process needs to run semi-regularly and the new files that need to be deleted are currently at the end of the list it seems.

I put together the following list of code to sort through it all:

```<code>gci $RPT | %{
$flag = 0;

$number = [int]($_.Name | select-string -pattern "\d{12}" -Allmatches).Matches.Value

if ($submidlist -match "^$number$"){
    if ($_ -notmatch "acct\.csv|jpd\.csv|jss\.pdf|jman\.pdf|3600\.pdf|cont\.pdf|msl\.txt|pres\.pdf|tray\.pdf|qual\.pdf|zipl\.pdf"){
        echo "DELETE SUBMID $_"
        remove-item $RPT\$_

        $count++
        $totalcount++
        $flag = 1;
    }
}

if ($jobidlist -match "^$number$"){
    if ($_ -match "acct\.csv|jpd\.csv|jss\.pdf|jman\.pdf|3600\.pdf|cont\.pdf|msl\.txt|pres\.pdf|tray\.pdf|qual\.pdf|zipl\.pdf"){
        echo "DELETE JOBID $_"
        remove-item $RPT\$_
        $count++
        $totalcount++
        $flag = 1;
    }
}

}

</code>```

Currently, running the above script takes over 24 hours and it still doesn't make it to the end of the list. Is there a way to optimize this or reverse the order that get-childitem iterates through this folder?

答:
```<code>function Delete-Items($List, [string]$ListName){

    $DoNotDelete = @("acct.csv","jpd.csv","jss.pdf","jman.pdf","3600.pdf","cont.pdf","msl.txt","pres.pdf","tray.pdf","qual.pdf","zipl.pdf")

    $List = $List | %{
        "*$_*"
    }
    Get-ChildItem C:\TEST\56381643\ -Recurse -Include $List -Directory | %{
        Get-ChildItem $_.FullName -Exclude $DoNotDelete -Recurse | %{
                echo "DELETE $ListName $($_.name | select-string -pattern "\d{12}")"
                Remove-Item -Path $_.FullName -WhatIf
        }
    }
}

#Example Usage
$JobList = @(
    098765432109
    123456789012

)

$SubmitList = @(
    234567890123
)

Delete-Items -List $JobList -ListName JOBID
Delete-Items -List $SubmitList -ListName SUBMID
</code>```

Lets go over a basic rundown of whats happening in the function.

We have a array of files not to delete

We turn the $list numbers into wildcards by adding a * before and after each item in the array. We then only search for those directories that contain those numbers.

We then use another Get-ChildItem to get the files in each directory but exclude the ones mentioned in$DoNotDelete`.

If you want to delete the files delete the -Whatif on the remove-item

Body:
I have a folder full of 500,00+ files. I'm trying to iterate through this folder and run some logic to determine if we can delete unneeded files. The problem is this process needs to run semi-regularly and the new files that need to be deleted are currently at the end of the list it seems.

I put together the following list of code to sort through it all:

gci $RPT | %{
$flag = 0;

$number = [int]($_.Name | select-string -pattern "\d{12}" -Allmatches).Matches.Value

if ($submidlist -match "^$number$"){
    if ($_ -notmatch "acct\.csv|jpd\.csv|jss\.pdf|jman\.pdf|3600\.pdf|cont\.pdf|msl\.txt|pres\.pdf|tray\.pdf|qual\.pdf|zipl\.pdf"){
        echo "DELETE SUBMID $_"
        remove-item $RPT\$_

        $count++
        $totalcount++
        $flag = 1;
    }
}

if ($jobidlist -match "^$number$"){
    if ($_ -match "acct\.csv|jpd\.csv|jss\.pdf|jman\.pdf|3600\.pdf|cont\.pdf|msl\.txt|pres\.pdf|tray\.pdf|qual\.pdf|zipl\.pdf"){
        echo "DELETE JOBID $_"
        remove-item $RPT\$_
        $count++
        $totalcount++
        $flag = 1;
    }
}

}

Currently, running the above script takes over 24 hours and it still doesn't make it to the end of the list. Is there a way to optimize this or reverse the order that get-childitem iterates through this folder?

Body:
function Delete-Items($List, [string]$ListName){

    $DoNotDelete = @("acct.csv","jpd.csv","jss.pdf","jman.pdf","3600.pdf","cont.pdf","msl.txt","pres.pdf","tray.pdf","qual.pdf","zipl.pdf")

    $List = $List | %{
        "*$_*"
    }
    Get-ChildItem C:\TEST\56381643\ -Recurse -Include $List -Directory | %{
        Get-ChildItem $_.FullName -Exclude $DoNotDelete -Recurse | %{
                echo "DELETE $ListName $($_.name | select-string -pattern "\d{12}")"
                Remove-Item -Path $_.FullName -WhatIf
        }
    }
}

#Example Usage
$JobList = @(
    098765432109
    123456789012

)

$SubmitList = @(
    234567890123
)

Delete-Items -List $JobList -ListName JOBID
Delete-Items -List $SubmitList -ListName SUBMID

Lets go over a basic rundown of whats happening in the function.

We have a array of files not to delete

We turn the $list numbers into wildcards by adding a * before and after each item in the array. We then only search for those directories that contain those numbers.

We then use another Get-ChildItem to get the files in each directory but exclude the ones mentioned in$DoNotDelete`.

If you want to delete the files delete the -Whatif on the remove-item


问:
How to set process ID in Linux for a specific program
I was wondering if there is some way to force to use some specific process ID to Linux to some application before running it. I need to know in advance the process ID.</p>

答:
On CentOS7.2 you can simply do the following:

Let's say you want to execute the sleep command with a PID of 1894.

```<code>sudo echo 1893 > /proc/sys/kernel/ns_last_pid; sleep 1000
</code>```

(However, keep in mind that if by chance another process executes in the extremely brief amount of time between the echo and sleep command you could end up with a PID of 1895+.  I've tested it hundreds of times and it has never happened to me.  If you want to guarantee the PID you will need to lock the file after you write to it, execute sleep, then unlock the file as suggested in Ruslan's answer above.)

Body:
On CentOS7.2 you can simply do the following:

Let's say you want to execute the sleep command with a PID of 1894.

sudo echo 1893 > /proc/sys/kernel/ns_last_pid; sleep 1000

(However, keep in mind that if by chance another process executes in the extremely brief amount of time between the echo and sleep command you could end up with a PID of 1895+.  I've tested it hundreds of times and it has never happened to me.  If you want to guarantee the PID you will need to lock the file after you write to it, execute sleep, then unlock the file as suggested in Ruslan's answer above.)


问:
Is there a standard docstring format to show what signature is expected for an argument that takes a function?
My __init__ method accepts another function as an argument called func_convert:

```<code>class Adc:
    """Reads data from ADC

    """
    def __init__(self, func_convert):
        """Setup the ADC

        Parameters
        ----------
        func_convert : [???]
            user-supplied conversion function
        """
        self._func_convert = func_convert

    def read(self):
        data = 0 #some fake data
        return self._func_convert(data)
</code>```

The argument func_convert allows a custom scaling function to be supplied once at instantiation that gets called to convert the data each time it's read.  The function must accept a single int argument and return a single float.  One possible example would be:

```<code>def adc_to_volts(value):
    return value * 3.0 / 2**16 - 1.5

adc = Adc(adc_to_volts)
volts = adc.read()

</code>```

Is there a standard way to document what the expected signature of func_convert is in the parameters section of the __init__ docstring?  If it makes a difference, I'm using numpy docstring style (I think).

答:
I don't know if this standard exists for docstrings - you can of course explain what the function needs in simple sentences, but I assume you want a standard, documentation generator-friendly way to do this.

If you don't mind switching tools, this is possible using type hints and the Callable object from the typing module:

```<code>from typing import Callable

class Adc:
    """
    Reads data from ADC

    """
    def __init__(self, func_convert: Callable[[int], float]) -> None:
        self._func_convert = func_convert

    def read(self):
        data = 0  # some fake data
        return self._func_convert(data)
</code>```

Body:
My __init__ method accepts another function as an argument called func_convert:

class Adc:
    """Reads data from ADC

    """
    def __init__(self, func_convert):
        """Setup the ADC

        Parameters
        ----------
        func_convert : [???]
            user-supplied conversion function
        """
        self._func_convert = func_convert

    def read(self):
        data = 0 #some fake data
        return self._func_convert(data)

The argument func_convert allows a custom scaling function to be supplied once at instantiation that gets called to convert the data each time it's read.  The function must accept a single int argument and return a single float.  One possible example would be:

def adc_to_volts(value):
    return value * 3.0 / 2**16 - 1.5

adc = Adc(adc_to_volts)
volts = adc.read()

Is there a standard way to document what the expected signature of func_convert is in the parameters section of the __init__ docstring?  If it makes a difference, I'm using numpy docstring style (I think).

Body:
I don't know if this standard exists for docstrings - you can of course explain what the function needs in simple sentences, but I assume you want a standard, documentation generator-friendly way to do this.

If you don't mind switching tools, this is possible using type hints and the Callable object from the typing module:

from typing import Callable

class Adc:
    """
    Reads data from ADC

    """
    def __init__(self, func_convert: Callable[[int], float]) -> None:
        self._func_convert = func_convert

    def read(self):
        data = 0  # some fake data
        return self._func_convert(data)


问:
How do I handle rollback in case of failure using handlers in Ansible?
I wrote below yml file which will install the SSM and cloudwatch agent but I want to rollback the installation in case of any failures during the installation. I tried use FAIL but not working..Please advise..</p>

```<code>---
# tasks file for SSMAgnetInstall
- name: status check
  command: systemctl status amazon-ssm-agent
  register: s_status
- debug:
    msg: "{{ s_status  }}"

- name: Get CPU architecture
  command: getconf LONG_BIT
  register: cpu_arch
  changed_when: False
  check_mode: no
  when: s_status.stdout == ""
  ignore_errors: true

- name: Install rpm file for Redhat Family (Amazon Linux, RHEL, and CentOS) 32/64-bit
  yum:
    name: "https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_386/amazon-ssm-agent.rpm"
    state: present
  when: s_status.stdout == ""
  become: yes
  ignore_errors: true

- name: cloud status check
  command: systemctl status amazon-cloudwatch-agent
  register: cld_status
  become: yes
- debug:
    msg: "{{ cld_status  }}"

- name: Register to cloud watch service
  become: yes
  become_user: root
  service:
    name: amazon-ssm-agent
    enabled: yes
    state: started

- name: copy the output to a local file
  copy:
    content: "{{ myshell_output.stdout }}"
    dest: "/home/ansible/rama/output.txt"
  delegate_to: localhost
</code>```

答:
You should have a look at the the documentation on blocks, more specifically the error handling part. This is the general idea with an oversimplified example, you will have to adapt to your specific case.

The test.yml playbook

---
- hosts: localhost
  gather_facts: false

  tasks:
    - block:

        - name: I am a task that can fail
          debug:
            msg: "I {{ gen_fail | default(false) | bool | ternary('failed', 'succeeded') }}"
          failed_when: gen_fail | default(false) | bool

        - name: I am a task that will never fail
          debug:
            msg: I succeeded

      rescue:

        - name: I am a task in a block played when a failure happens
          debug:
            msg: rescue task

      always:

        - name: I am a task always played whatever happens
          debug:
            msg: always task
```
<p>Played normally (no fail)</p>
```$ ansible-playbook test.yml

PLAY [localhost] ************************************************************************

TASK [I am a task that can fail] ********************************************************
ok: [localhost] => {
    "msg": "I succeeded"
}

TASK [I am a task that will never fail] *************************************************
ok: [localhost] => {
    "msg": "I succeeded"
}

TASK [I am a task always played whatever happens] ***************************************
ok: [localhost] => {
    "msg": "always task"
}

PLAY RECAP ******************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
```
<p>Played forcing a fail</p>
```$ ansible-playbook test.yml -e gen_fail=true

PLAY [localhost] ************************************************************************

TASK [I am a task that can fail] ********************************************************
fatal: [localhost]: FAILED! => {
    "msg": "I failed"
}

TASK [I am a task in a block played when a failure happens] *****************************
ok: [localhost] => {
    "msg": "rescue task"
}

TASK [I am a task always played whatever happens] ***************************************
ok: [localhost] => {
    "msg": "always task"
}

PLAY RECAP ******************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=1    ignored=0
```

Body:
I wrote below yml file which will install the SSM and cloudwatch agent but I want to rollback the installation in case of any failures during the installation. I tried use FAIL but not working..Please advise..

---
# tasks file for SSMAgnetInstall
- name: status check
  command: systemctl status amazon-ssm-agent
  register: s_status
- debug:
    msg: "{{ s_status  }}"

- name: Get CPU architecture
  command: getconf LONG_BIT
  register: cpu_arch
  changed_when: False
  check_mode: no
  when: s_status.stdout == ""
  ignore_errors: true

- name: Install rpm file for Redhat Family (Amazon Linux, RHEL, and CentOS) 32/64-bit
  yum:
    name: "https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_386/amazon-ssm-agent.rpm"
    state: present
  when: s_status.stdout == ""
  become: yes
  ignore_errors: true

- name: cloud status check
  command: systemctl status amazon-cloudwatch-agent
  register: cld_status
  become: yes
- debug:
    msg: "{{ cld_status  }}"

- name: Register to cloud watch service
  become: yes
  become_user: root
  service:
    name: amazon-ssm-agent
    enabled: yes
    state: started

- name: copy the output to a local file
  copy:
    content: "{{ myshell_output.stdout }}"
    dest: "/home/ansible/rama/output.txt"
  delegate_to: localhost

Body:
You should have a look at the the documentation on blocks, more specifically the error handling part. This is the general idea with an oversimplified example, you will have to adapt to your specific case.

The test.yml playbook

---
- hosts: localhost
  gather_facts: false

  tasks:
    - block:

        - name: I am a task that can fail
          debug:
            msg: "I {{ gen_fail | default(false) | bool | ternary('failed', 'succeeded') }}"
          failed_when: gen_fail | default(false) | bool

        - name: I am a task that will never fail
          debug:
            msg: I succeeded

      rescue:

        - name: I am a task in a block played when a failure happens
          debug:
            msg: rescue task

      always:

        - name: I am a task always played whatever happens
          debug:
            msg: always task

Played normally (no fail)

$ ansible-playbook test.yml

PLAY [localhost] ************************************************************************

TASK [I am a task that can fail] ********************************************************
ok: [localhost] => {
    "msg": "I succeeded"
}

TASK [I am a task that will never fail] *************************************************
ok: [localhost] => {
    "msg": "I succeeded"
}

TASK [I am a task always played whatever happens] ***************************************
ok: [localhost] => {
    "msg": "always task"
}

PLAY RECAP ******************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Played forcing a fail

$ ansible-playbook test.yml -e gen_fail=true

PLAY [localhost] ************************************************************************

TASK [I am a task that can fail] ********************************************************
fatal: [localhost]: FAILED! => {
    "msg": "I failed"
}

TASK [I am a task in a block played when a failure happens] *****************************
ok: [localhost] => {
    "msg": "rescue task"
}

TASK [I am a task always played whatever happens] ***************************************
ok: [localhost] => {
    "msg": "always task"
}

PLAY RECAP ******************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=1    ignored=0


问:
Converting a repeating binary number to decimal
How do I represent 0.1011111.... or 0.10(1) as a fraction a/b?
With a & b being integers.

I have being trying this method

x = 0.10(1)
x = 10.(1) / 4

Now y = 10.(1)

2y = 101.(1)

which implies 2y - y = 91
y = 91

x = 91/4
But a = 91 & b = 4 is wrong.

How do I go about to solve this?

答:
You need to observe that the numbers are still in binary. Thus in decimal you get that the integer part of y is 2 and of 2y is 5, so that in the difference y=3.

Note that in binary 0.1(1)=1, just as in decimal 0.9(9)=1. Thus in an alternative way, x is exactly 0.11 binary, which is 1/2+1/4=3/4.


问:
Does super need to be called for onViewRecycled?
I override onViewRecycled in class MyAdapter extends RecyclerView.Adapter.

```<code>@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {

    ...
    super.onViewRecycled(holder);
}
</code>```

Does super have to be called when overriding?

Side note

I also wonder because I get the (well known) error when calling super:

Unchecked call to 'onViewRecycled(VH)' as a member of raw type
'android.support.v7.widget.RecyclerView.Adapter'

答: No, because RecyclerView.Adapter is an abstract class and has no concrete implementation. See docs:

Body:
I override onViewRecycled in class MyAdapter extends RecyclerView.Adapter.

@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {

    ...
    super.onViewRecycled(holder);
}

Does super have to be called when overriding?

Side note

I also wonder because I get the (well known) error when calling super:

Unchecked call to 'onViewRecycled(VH)' as a member of raw type
'android.support.v7.widget.RecyclerView.Adapter'


问:
How to kill child processes in Bash?
I am trying to do an operation in linux trying to burn cpu using openssl speed

this is my code from netflix simian army

```<code>#!/bin/bash
# Script for BurnCpu Chaos Monkey

cat << EOF > /tmp/infiniteburn.sh
#!/bin/bash
while true;
   do openssl speed;
done
EOF

# 32 parallel 100% CPU tasks should hit even the biggest EC2 instances
for i in {1..32}
do
  nohup /bin/bash /tmp/infiniteburn.sh &
done
</code>```

so this is Netflix simian army code to do burn cpu, this executes properly but the issue is I cannot kill all 32 processes, I tried everything

```<code>pkill -f pid/process name
killall -9 pid/process name
etc.,
</code>```

the only successful way I killed the process is through killing it via user

```<code>pkill -u username
</code>```

How can I kill these process without using username?

any help is greatly appreciated

答:
I had a similar problem and solution where I needed to kill a NodeJS server after some amount of time.

To do this, I enabled Job control, and killed async processes by group id with jobs:

set -m
./node_modules/.bin/node src/index.js &
sleep 2

kill -- -$(jobs -p)
```

Title: How to kill child processes in Bash?

Body:
I am trying to do an operation in linux trying to burn cpu using openssl speed

this is my code from netflix simian army

#!/bin/bash
# Script for BurnCpu Chaos Monkey

cat << EOF > /tmp/infiniteburn.sh
#!/bin/bash
while true;
   do openssl speed;
done
EOF

# 32 parallel 100% CPU tasks should hit even the biggest EC2 instances
for i in {1..32}
do
  nohup /bin/bash /tmp/infiniteburn.sh &
done

so this is Netflix simian army code to do burn cpu, this executes properly but the issue is I cannot kill all 32 processes, I tried everything

pkill -f pid/process name
killall -9 pid/process name
etc.,

the only successful way I killed the process is through killing it via user

pkill -u username

How can I kill these process without using username?

any help is greatly appreciated


问:
Determining the best data structure for a problem form a complexity standpoint
So I have found the following problem proposed a few years ago at a programming Olympiad in Romania:

Say you have a language with exactly N words. Two words are said to be K-similar if they have the same first K letters and the k+1 letter differs.

The similarity degree between T words it's said to be K if any two words are K-similar but not (K+1)-similar.

Given M random words determine the degree of similarity between them.

I was wondering what is the data structure that would be best in terms of complexity for implementing this program.

I have tried implementing it by using arrays of strings or arrays of arrays of chars.

Example: For asdf, asdffff and asdg the similarity degree should be 3.

答:
From your description, it sounds like you're looking for the longest common prefix. That doesn't require any special data structure.

Start with the first two words, "asdf" and "adsffff". Compare character-by-character until you find a mismatch. You end up with the common letters "asdf".

Then compare the next word to the result from that comparison. You compare "asdf" with "asdg", and find that there is a mismatch on the 4th character, so your the longest common prefix now is "asd".

You can continue in that way through all the words in your list. And if you run across a word that starts with anything other than 'a', then your longest common prefix is 0, and you can exit.

Based on your question and clarification in the comments, the above will solve the problem. I still think, however, that your understanding of the problem is not correct.


问:
Script only entering last value to postgres database
Very new to python.  I am trying to get the data from an RSS feed, parse the data and then insert the data to a database.  My short bit of code gets the correct items and I can print the results but I can only get the last item in the RSS feed to post to the database. I believe I may have defined "html" and "link" incorrectly.  I want the item.title and item.link to populate a list that will then get entered into the database in the correct order.  Any help much appreciated.</p>

```<code>import sys
import requests
import urllib2
import feedparser
import psycopg2
import psycopg2.extras
from psycopg2.extras import execute_values
import time

url = "https://www.ferc.gov/xml/whats-new.xml"
response = urllib2.urlopen(url).read()

#saving the xml file
response = requests.get(url)
#with open('whats_hot.xml', 'wb') as file:
#    file.write(response.content)

d = feedparser.parse('https://www.ferc.gov/xml/whats-new.xml')

for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    html = item.published + item.title
    link = item.link

con = psycopg2.connect(database="xx",
user="xx", password="xx", host="127.0.0.1",
port="5432")
print("Database opened successfully")

cur = con.cursor()

#try:
psycopg2.extras.execute_values(cur,
"insert into ferc_hots (link,html) values %s",
      [(link,html)])
#except psycopg2.IntegrityError:
#     print 'Duplicate values found.  Insert was not successful'

con.commit()
print("Records inserted successfully")
con.close()
</code>```

答:
html and link are just single string values. They keep changing through your loop, but by the time you go to insert, they just have the last value given. You need to keep a list of value tuples that will be passed to your insert. Note the double parentheses are because a tuple is being appended to the values list. A tuple is defined like (item, item), so you are appending (item, item) and not just item.

```<code>values = []
for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    values.append((item.link, item.published + item.title))
</code>```

...

```<code>psycopg2.extras.execute_values(cur,
    "insert into ferc_hots (link,html) values %s",
        values)
</code>```

Body:
Very new to python.  I am trying to get the data from an RSS feed, parse the data and then insert the data to a database.  My short bit of code gets the correct items and I can print the results but I can only get the last item in the RSS feed to post to the database. I believe I may have defined "html" and "link" incorrectly.  I want the item.title and item.link to populate a list that will then get entered into the database in the correct order.  Any help much appreciated.

import sys
import requests
import urllib2
import feedparser
import psycopg2
import psycopg2.extras
from psycopg2.extras import execute_values
import time

url = "https://www.ferc.gov/xml/whats-new.xml"
response = urllib2.urlopen(url).read()

#saving the xml file
response = requests.get(url)
#with open('whats_hot.xml', 'wb') as file:
#    file.write(response.content)

d = feedparser.parse('https://www.ferc.gov/xml/whats-new.xml')

for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    html = item.published + item.title
    link = item.link

con = psycopg2.connect(database="xx",
user="xx", password="xx", host="127.0.0.1",
port="5432")
print("Database opened successfully")

cur = con.cursor()

#try:
psycopg2.extras.execute_values(cur,
"insert into ferc_hots (link,html) values %s",
      [(link,html)])
#except psycopg2.IntegrityError:
#     print 'Duplicate values found.  Insert was not successful'

con.commit()
print("Records inserted successfully")
con.close()

Body:
html and link are just single string values. They keep changing through your loop, but by the time you go to insert, they just have the last value given. You need to keep a list of value tuples that will be passed to your insert. Note the double parentheses are because a tuple is being appended to the values list. A tuple is defined like (item, item), so you are appending (item, item) and not just item.

values = []
for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    values.append((item.link, item.published + item.title))

...

psycopg2.extras.execute_values(cur,
    "insert into ferc_hots (link,html) values %s",
        values)


问:
Methods, Loops and the `this` Keyword
I am new at Javascript. I am currently looking at the keyword this and methods and how to return strings.
I am struggling to return a string using the keyword this.

I have successfully created code that returns the string, but the problem is that it shows the error that "the object is already defined".

Here is the exercise I am working on and also the code I have tried to create which fails to return the correct results:

```<code>function exerciseTwo(userObj) {

  // Exercise Two: You will be given an object called 'userObj'
  // userObject will already have a key on it called 'name'
  // Add a method to userObj, called 'greeting'.
  // Using the keyword 'this', the greeting method should return the following string:
  // 'Hi, my name is ' and the users name.
  // eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
  // NOTE: DO NOT create a new object.
  // NOTE: DO NOT create a key called name the key is already on the object.

  let userObj = {
    name: "Lisa",
    greeting: function() {
      return "Hi, my name is " + this.name;
    },
  };
  console.log(userObj.greeting());
}

//In the first line of code it shows a error which says that "userObj" is already defined. So I do not know how to return the string without creating a new object and creating a key called name.

//Here is another option I tried but it also did not work out:

function greeting() {
  this.name = "Lisa";
  let result = "Hi, my name is " + this.name;
  return result;
},
userObj.greeting();
}

//The exercise should add a greeting method to userObject object.
</code>```

So if userObj has a name: 'Lisa', greeting should return: 'Hi, my name is Lisa'

答:
```<code>function exerciseTwo(userObj){ // The argument for this "exerciseTwo" function has been declared as "userObj"

  let userObj = { // Here you are trying to declare another variable "userObj"
    name: "Lisa",
    greeting: function() {
      return "Hi, my name is " + this.name;
    }
  };

  console.log(userObj.greeting());
}
</code>```

To solve your issue,
- Declare the let userObj = { ... } block outside the "exerciseTwo" function and pass it in as a variable

```<code>let lisa = {
  name: "Lisa"
};

function exerciseTwo(userObj){ // Whatever variable you pass into this function will be synonymous to `userObj` within this function
  userObj.greeting = function () {
    return "Hi, my name is " + this.name;
  }
  console.log(userObj.greeting());
}

exerciseTwo(lisa) // lisa will take the position of `userObj` above
</code>```

Title: Methods, Loops and the `this` Keyword

Body:
I am new at Javascript. I am currently looking at the keyword this and methods and how to return strings.
I am struggling to return a string using the keyword this.

I have successfully created code that returns the string, but the problem is that it shows the error that "the object is already defined".

Here is the exercise I am working on and also the code I have tried to create which fails to return the correct results:

function exerciseTwo(userObj) {

  // Exercise Two: You will be given an object called 'userObj'
  // userObject will already have a key on it called 'name'
  // Add a method to userObj, called 'greeting'.
  // Using the keyword 'this', the greeting method should return the following string:
  // 'Hi, my name is ' and the users name.
  // eg: If userObj has a name: 'Dan', greeting should return: Hi, my name is Dan'
  // NOTE: DO NOT create a new object.
  // NOTE: DO NOT create a key called name the key is already on the object.

  let userObj = {
    name: "Lisa",
    greeting: function() {
      return "Hi, my name is " + this.name;
    },
  };
  console.log(userObj.greeting());
}

//In the first line of code it shows a error which says that "userObj" is already defined. So I do not know how to return the string without creating a new object and creating a key called name.

//Here is another option I tried but it also did not work out:

function greeting() {
  this.name = "Lisa";
  let result = "Hi, my name is " + this.name;
  return result;
},
userObj.greeting();
}

//The exercise should add a greeting method to userObject object.

So if userObj has a name: 'Lisa', greeting should return: 'Hi, my name is Lisa'

Body:
function exerciseTwo(userObj){ // The argument for this "exerciseTwo" function has been declared as "userObj"

  let userObj = { // Here you are trying to declare another variable "userObj"
    name: "Lisa",
    greeting: function() {
      return "Hi, my name is " + this.name;
    }
  };

  console.log(userObj.greeting());
}

To solve your issue,
- Declare the let userObj = { ... } block outside the "exerciseTwo" function and pass it in as a variable

let lisa = {
  name: "Lisa"
};

function exerciseTwo(userObj){ // Whatever variable you pass into this function will be synonymous to `userObj` within this function
  userObj.greeting = function () {
    return "Hi, my name is " + this.name;
  }
  console.log(userObj.greeting());
}

exerciseTwo(lisa) // lisa will take the position of `userObj` above


问:
How to include firebase admin in angular project
I want to add the ability to admin users in my Angular 7 project using firebase for user authentication.

My application is successfully using firebase authentication of users in my project.

Now I want to give admin users of my program the ability to list users, update users, add users, control user roles, etc.  I do not want my users to need to access the firebase admin console.

My first test is just to list firebase users using the admin.auth().listUsers function.  There is good documentation on how to do this using node.js but not the next step with angular.

My issue is that the variable "admin" needs to be defined.

When I use the node.js code of:

var admin = require('firebase-admin');

I get a whole bunch of errors like:

ERROR in ./node_modules/google-gax/build/src/operationsClient.js
Module not found: Error: Can't resolve './operations_client_config' in '/Users/Stan/Sites/google/dallas/node_modules/google-gax/build/src'
ERROR in ./node_modules/google-auth-library/build/src/auth/googleauth.js
Module not found: Error: Can't resolve 'child_process' in '/Users/Stan/Sites/google/dallas/node_modules/google-auth-library/build/src/auth'
ERROR in ./node_modules/google-gax/node_modules/google-auth-library/build/src/auth/googleauth.js
Module not found: Error: Can't resolve 'child_process' in '/Users/Stan/Sites/google/dallas/node_modules/google-gax/node_modules/google-auth-library/build/src/auth'

When i don't put in the above require line the only issue is that "admin" is not defined.

I assume that there is some small set-up issue I have missed, but would really appreciate any help past this.

答:
The admin sdk is only available for nodejs. So you cannot use it on the front-end.

You can create a firebase cloud function for that. And deploy it in your project. Then you can call that function in your angular application.


问:
How to escape single quote (') character in scilab?
I want to print the symbol ' (quote)

for example:

disp (' ' ')

and the output that I would like to get is:
'

But, as the ' is the string delimiter, I can't use that way.

Is there a code which I can use instead of the symbol ' ?

thank you

disp (' ' ')

答:
I have found the answer. Inside a string, if you write quotes twice (''), Scylab will know that you mean only one quote, '.

So, to display:
'

you have to write
''''


问:
How to get similar records using SQL
I need to write sql query for get similar records from table.It has 100 of records with difference of values. But some records have similar name.Similar names start with capital or simple.   </p>

<p>ex- I want to get all the similar records who has similar names. </p>

```<code>Student_no | student_Name | Subject   |class
  1        | Abc          | Java      | 1
  2        | Abc          | Java      | 1
  3        | xyz          | AngularJS | 2
  4        | xyz          | AngularJS | 2
  5        | Abc Def      | SpringBoot| 3
</code>```

答:
In your instance, a statement like:

```<code>SELECT * FROM TABLE WHERE UPPER(student_Name) like UPPER('xyz')
</code>```

would shift all student_Name values to uppercase, then retrieve all uppercase (or, just all) "XYZ" values.

If not all names are like "xyz" (or, some are "xyz1", "1_xyz", or "ABCXYZDEF"), you need to use like with % representing any number of missing values:

```<code>SELECT * FROM TABLE WHERE UPPER(student_Name) like UPPER('%xyz%')
</code>```

Please see the attached link for more information: SQL- Ignore case while searching for a string

Title: How to get similar records using SQL

Body:
I need to write sql query for get similar records from table.It has 100 of records with difference of values. But some records have similar name.Similar names start with capital or simple.

ex- I want to get all the similar records who has similar names.

Student_no | student_Name | Subject   |class
  1        | Abc          | Java      | 1
  2        | Abc          | Java      | 1
  3        | xyz          | AngularJS | 2
  4        | xyz          | AngularJS | 2
  5        | Abc Def      | SpringBoot| 3

Body:
In your instance, a statement like:

SELECT * FROM TABLE WHERE UPPER(student_Name) like UPPER('xyz')

would shift all student_Name values to uppercase, then retrieve all uppercase (or, just all) "XYZ" values.

If not all names are like "xyz" (or, some are "xyz1", "1_xyz", or "ABCXYZDEF"), you need to use like with % representing any number of missing values:

SELECT * FROM TABLE WHERE UPPER(student_Name) like UPPER('%xyz%')

Please see the attached link for more information: SQL- Ignore case while searching for a string