问:
NgModel populates all input fields in login mask with password when password changes
i am facing a strange behavior and have no explanation for it. The problem is the following: when a user inserts User and Password into a login prompt and something happens behind the scenes, the User field is also populated with the password the user entered. It looks like the form does not populates the fields correctly when it is re-rendered.

The code looks like the following (simplified for demonstration purposes):

LoginComponent.ts

```<code>public selModule = { AuthProps: [{Name: "User", Display: "DUser"}, {Name: "Password", Display: "DPassword"}] };
public loginData: { [key: string]: string } = {};

public changePW() {
    this.loginData['Password'] = "NewTestPw";
}
</code>```

LoginComponent.html

```<code><div *ngFor="let authProp of selModule?.AuthProps">
        <label>{{ authProp.Display }}</label>
        <input [type]="handleInputType(authProp)" [(ngModel)]="loginData[authProp.Name]" name="authProp.Name">
</div>
<button (click)="changePw()">Change PW</button>
</code>```

So if i type in username and password, both the input elements in the UI and the loginDate is populated correctly:

```<code>loginData: {User: "Testuser", Password: "Testpassword"}
User: Testuser
Password: TestPassword
</code>```

By clicking on the button "Change PW" only loginData['Password'] is changed but the input field for the user is populated with "NewTestPW" as well.

```<code>loginData: {User: "Testuser", Password: "NewTestPW"}
User: NewTestPW
Password: NewTestPW
</code>```

Why is this the case?

答:
This is expected, because you have two way binded it with login data password, when you do that if loginData.Password will be changed, it will reflect in text box. If you don't want to behaviour change your

```<code>[(ngModel)]="loginData[authProp.Name]"
</code>```

to

```<code>(change)="handleValue(authProp.Name, $event.target.value)"
</code>```

in typescript

```<code>public handleValue(prop, value) {
     this.loginData[prop] = value;
  }
</code>```

Body:
i am facing a strange behavior and have no explanation for it. The problem is the following: when a user inserts User and Password into a login prompt and something happens behind the scenes, the User field is also populated with the password the user entered. It looks like the form does not populates the fields correctly when it is re-rendered.

The code looks like the following (simplified for demonstration purposes):

LoginComponent.ts

public selModule = { AuthProps: [{Name: "User", Display: "DUser"}, {Name: "Password", Display: "DPassword"}] };
public loginData: { [key: string]: string } = {};

public changePW() {
    this.loginData['Password'] = "NewTestPw";
}

LoginComponent.html

        {{ authProp.Display }}
        <input [type]="handleInputType(authProp)" [(ngModel)]="loginData[authProp.Name]" name="authProp.Name">

<button (click)="changePw()">Change PW</button>

So if i type in username and password, both the input elements in the UI and the loginDate is populated correctly:

loginData: {User: "Testuser", Password: "Testpassword"}
User: Testuser
Password: TestPassword

By clicking on the button "Change PW" only loginData['Password'] is changed but the input field for the user is populated with "NewTestPW" as well.

loginData: {User: "Testuser", Password: "NewTestPW"}
User: NewTestPW
Password: NewTestPW

Why is this the case?

Body:
This is expected, because you have two way binded it with login data password, when you do that if loginData.Password will be changed, it will reflect in text box. If you don't want to behaviour change your

[(ngModel)]="loginData[authProp.Name]"

to

(change)="handleValue(authProp.Name, $event.target.value)"

in typescript

public handleValue(prop, value) {
     this.loginData[prop] = value;
  }


来源: stackexchange

问:
Not enough values to unpack expected two got one
i was following the tutorials on the django official documentation on a polling app, in part 4 of the tutorial i used same code as in the tutorials but i keep getting an error
ValueError: Not enough values to unpack (expected 2, got 1)
here is the code for my views.py

from django.shortcuts import render, get_object_or_404

from django.http import HttpResponse, HttpResponseRedirect

from django.urls import reverse

from django.views import generic

from .models import Choice, Question

class IndexView(generic.ListView):

    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):

        return Question.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView):

    model = Question
    template_name = 'polls/detail.html'

class ResultView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

def votes(request, question_id):

    question = get_object_or_404(Question, pk=question_id)

    try:

        selected_choice = question.choice_set.get(request.POST['choice'])

    except (KeyError, Choice.DoesNotExist):

        return render(request, 'polls/detail.html',
        {'question':question, 'error_message': "You didn't select a choice",})

    else:

        selected_choice.votes += 1
        selected_choice.save()

    return HttpResponseRedirect(reverse('polls:resullts', args=(question_id,)))
```

<p>and the html code for detail.html is below</p>

<pre class="lang-html prettyprint-override"><code><p>{{question.question_text}}</p>

{% if error_message %}<p>{{error_message}}</p>{% endif %}

<form action="{% url 'polls:votes' question.id %}" method="POST">
{% csrf_token %}

{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}" >
    <label for="choice{{forloop.counter}}">{{choice.choice_text}}</label><br>
{% endfor %}

<input type="submit" value="Vote">
</form>
</code>```

```<code>Internal Server Error: /polls/1/votes/
Traceback (most recent call last):
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\polls\views.py", line 45, in votes
    selected_choice = question.choice_set.get(kii)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 404, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1351, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1378, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1248, in build_filter
    arg, value = filter_expr
ValueError: not enough values to unpack (expected 2, got 1)
</code>```

This is the error message i keep getting

答:
I think i figured out the answer, the problem is in the vote function.
The correct code should be

def votes(request, question_id):

    question = get_object_or_404(Question, pk=question_id)

    try:
        selected_choice = question.choice_set.get(id=request.POST['choice'])

    except (KeyError, Choice.DoesNotExist):

        return render(request, 'polls/detail.html',
        {'question':question, 'error_message': "You didn't select a choice",})
```

ContentLicense: CC BY-SA 4.0

Body:
i was following the tutorials on the django official documentation on a polling app, in part 4 of the tutorial i used same code as in the tutorials but i keep getting an error
ValueError: Not enough values to unpack (expected 2, got 1)
here is the code for my views.py

from django.shortcuts import render, get_object_or_404

from django.http import HttpResponse, HttpResponseRedirect

from django.urls import reverse

from django.views import generic

from .models import Choice, Question

class IndexView(generic.ListView):

    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):

        return Question.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView):

    model = Question
    template_name = 'polls/detail.html'

class ResultView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

def votes(request, question_id):

    question = get_object_or_404(Question, pk=question_id)

    try:

        selected_choice = question.choice_set.get(request.POST['choice'])

    except (KeyError, Choice.DoesNotExist):

        return render(request, 'polls/detail.html',
        {'question':question, 'error_message': "You didn't select a choice",})

    else:

        selected_choice.votes += 1
        selected_choice.save()

    return HttpResponseRedirect(reverse('polls:resullts', args=(question_id,)))

and the html code for detail.html is below

{{question.question_text}}

{% if error_message %}
{{error_message}}
{% endif %}

<form action="{% url 'polls:votes' question.id %}" method="POST">
{% csrf_token %}

{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}" >
    {{choice.choice_text}}

{% endfor %}

<input type="submit" value="Vote">
</form>

Internal Server Error: /polls/1/votes/
Traceback (most recent call last):
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\polls\views.py", line 45, in votes
    selected_choice = question.choice_set.get(kii)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 404, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1351, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1378, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1248, in build_filter
    arg, value = filter_expr
ValueError: not enough values to unpack (expected 2, got 1)

This is the error message i keep getting


问:
Trying to change my SQLLITE line by line insert query to bulk insert in python, how I can achieve it
I have this code to insert line by line from CSV file. it is working fine for a small CSV file. However now I have a CSV file with 15 million records. How I can change it to bulk insert. Really appreciate your help.</p>

```<code>with open(goodFilePath+'/'+file, "r") as f:
                    next(f)
                    reader = csv.reader(f, delimiter="\n")
                    for line in enumerate(reader):
                        for list_ in (line[1]):
                            try:
                                conn.execute('INSERT INTO Good_Raw_Data values ({values})'.format(values=(list_)))
                                self.logger.log(log_file," %s: File loaded successfully!!" % file)
                                conn.commit()
                            except Exception as e:
                                raise e
</code>```

答:
This can be accomplished using sqlite's executemany, intended for bulk inserts. It wasn't clear to me how many different values you are inserting, but here's an example if there are two columns:

```<code>conn.executemany(
    'INSERT INTO my_table VALUES (?,?)',
    [
        (1, 'value1'),    # Insert 1 in the first column, and 'value1' in the 2nd col
        (2, 'value2'),
        (3, 'another_value')
    ]
)
</code>```

In other words, you'll want to create either a generator function, or just a list, whose elements are n-tuples where n is the number of values to insert in each row.

Hope this helps, happy coding!

Body:
I have this code to insert line by line from CSV file. it is working fine for a small CSV file. However now I have a CSV file with 15 million records. How I can change it to bulk insert. Really appreciate your help.

with open(goodFilePath+'/'+file, "r") as f:
                    next(f)
                    reader = csv.reader(f, delimiter="\n")
                    for line in enumerate(reader):
                        for list_ in (line[1]):
                            try:
                                conn.execute('INSERT INTO Good_Raw_Data values ({values})'.format(values=(list_)))
                                self.logger.log(log_file," %s: File loaded successfully!!" % file)
                                conn.commit()
                            except Exception as e:
                                raise e

Body:
This can be accomplished using sqlite's executemany, intended for bulk inserts. It wasn't clear to me how many different values you are inserting, but here's an example if there are two columns:

conn.executemany(
    'INSERT INTO my_table VALUES (?,?)',
    [
        (1, 'value1'),    # Insert 1 in the first column, and 'value1' in the 2nd col
        (2, 'value2'),
        (3, 'another_value')
    ]
)

In other words, you'll want to create either a generator function, or just a list, whose elements are n-tuples where n is the number of values to insert in each row.

Hope this helps, happy coding!


问:
Getter returning null when testing get methods
I am trying to get data from my database to show on a listview. The problem I am having is it seems the getters are not working properly. When I test what they are returning, it comes back null.

Any insight would be appreciated as I am lost here. Thanks in advance.

Here is where I initialise the class:

```<code>    public ArrayList<GameStats> getAllData() {
    ArrayList<GameStats> arrayList = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);

    while(cursor.moveToNext()){
        int id = cursor.getInt(0);
        String lName = cursor.getString(1);
        int lScore = cursor.getInt(2);
        String rName = cursor.getString(3);
        int rScore = cursor.getInt(4);
        String notes = cursor.getString(5);

        GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
        arrayList.add(gameStats);

    }
    return arrayList;
}
</code>```

Here is where I am trying to use the getters:

```<code>    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.activity_saved_games, null);
        TextView lName = convertView.findViewById(R.id.lName);
        TextView lScore = convertView.findViewById(R.id.lScore);
        TextView rName = convertView.findViewById(R.id.rName);
        TextView rScore = convertView.findViewById(R.id.rScore);
        TextView notes = convertView.findViewById(R.id.notes);

    GameStats gameStats = arrayList.get(position);
    testVar = gameStats.getlName();
    Log.d("MyAdaptor","gameStats = " + var);
    lName.setText(gameStats.getlName());
    lScore.setText(String.valueOf(gameStats.getlScore()));
    rName.setText(gameStats.getrName());
    rScore.setText(String.valueOf(gameStats.getrScore()));
    notes.setText(gameStats.getNotes());
    return convertView;
}
</code>```

Here is the model class:

```<code>public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;

public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getlScore() {
    return lScore;
}

public void setlScore(int lScore) {
    this.lScore = lScore;
}

public int getrScore() {
    return rScore;
}

public void setrScore(int rScore) {
    this.rScore = rScore;
}

public String getlName() {
    return lName;
}

public void setlName(String lName) {
    this.lName = lName;
}

public String getrName() {
    return rName;
}

public void setrName(String rName) {
    this.rName = rName;
}

public String getNotes() {
    return notes;
}

public void setNotes(String notes) {
    this.notes = notes;
}
</code>```

}

and here is where I am calling the methods:

```<code>public class SavedGameScreen extends AppCompatActivity {

ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saved_game_screen);
    lv1 = findViewById(R.id.lv1);
    databaseHelper = new DatabaseHelper(this);
    arrayList = new ArrayList<>();
    loadData();
}

private void loadData() {
    arrayList = databaseHelper.getAllData();
    myAdaptor = new MyAdaptor(this, arrayList);
    lv1.setAdapter(myAdaptor);
    myAdaptor.notifyDataSetChanged();
}
</code>```

}

答:
You are passing the values to the model constructor but you are not assigning it to the model variables. You need to change the code as below,

```<code>public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
    this.id = id;
    this.lName = IName;
    this.lScore = IScore;
    this.rName = rName;
    this.rScore = rScore;
    this.notes = notes;
    }
</code>```

Else initialise each variable through setter() method.

Body:
I am trying to get data from my database to show on a listview. The problem I am having is it seems the getters are not working properly. When I test what they are returning, it comes back null.

Any insight would be appreciated as I am lost here. Thanks in advance.

Here is where I initialise the class:

    public ArrayList<GameStats> getAllData() {
    ArrayList<GameStats> arrayList = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);

    while(cursor.moveToNext()){
        int id = cursor.getInt(0);
        String lName = cursor.getString(1);
        int lScore = cursor.getInt(2);
        String rName = cursor.getString(3);
        int rScore = cursor.getInt(4);
        String notes = cursor.getString(5);

        GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
        arrayList.add(gameStats);

    }
    return arrayList;
}

Here is where I am trying to use the getters:

    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.activity_saved_games, null);
        TextView lName = convertView.findViewById(R.id.lName);
        TextView lScore = convertView.findViewById(R.id.lScore);
        TextView rName = convertView.findViewById(R.id.rName);
        TextView rScore = convertView.findViewById(R.id.rScore);
        TextView notes = convertView.findViewById(R.id.notes);

    GameStats gameStats = arrayList.get(position);
    testVar = gameStats.getlName();
    Log.d("MyAdaptor","gameStats = " + var);
    lName.setText(gameStats.getlName());
    lScore.setText(String.valueOf(gameStats.getlScore()));
    rName.setText(gameStats.getrName());
    rScore.setText(String.valueOf(gameStats.getrScore()));
    notes.setText(gameStats.getNotes());
    return convertView;
}

Here is the model class:

public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;

public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getlScore() {
    return lScore;
}

public void setlScore(int lScore) {
    this.lScore = lScore;
}

public int getrScore() {
    return rScore;
}

public void setrScore(int rScore) {
    this.rScore = rScore;
}

public String getlName() {
    return lName;
}

public void setlName(String lName) {
    this.lName = lName;
}

public String getrName() {
    return rName;
}

public void setrName(String rName) {
    this.rName = rName;
}

public String getNotes() {
    return notes;
}

public void setNotes(String notes) {
    this.notes = notes;
}

}

and here is where I am calling the methods:

public class SavedGameScreen extends AppCompatActivity {

ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saved_game_screen);
    lv1 = findViewById(R.id.lv1);
    databaseHelper = new DatabaseHelper(this);
    arrayList = new ArrayList<>();
    loadData();
}

private void loadData() {
    arrayList = databaseHelper.getAllData();
    myAdaptor = new MyAdaptor(this, arrayList);
    lv1.setAdapter(myAdaptor);
    myAdaptor.notifyDataSetChanged();
}

}

Body:
You are passing the values to the model constructor but you are not assigning it to the model variables. You need to change the code as below,

public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
    this.id = id;
    this.lName = IName;
    this.lScore = IScore;
    this.rName = rName;
    this.rScore = rScore;
    this.notes = notes;
    }

Else initialise each variable through setter() method.


问:
Rails: conflict error overwrite /home/username/blog/.gitignore?
I'm desperately trying to run a server and keep getting this mistake: conflict  .gitignore

The output is:

```<code>rails new blog
exist
identical  README.md
identical  Rakefile
identical  .ruby-version
identical  config.ru
conflict  .gitignore

Overwrite /home/jules/blog/.gitignore? (enter "h" for help) [Ynaqdhm]
</code>```

What should I do? I'm using Ubuntu 20.04. I'm an absolute beginner.

答:
When you run command $rails new it tries to create new rails application for you. But inside that folder that you are running this command file .gitignore already exists.

So, all that you need is to decide do you want to use your .gitignore file that already exists in current folder or to overwrite it with default one.

I think you made some mistake and just to make things simplier, try to run your command rails new blog in some separate empty folder.

Body:
I'm desperately trying to run a server and keep getting this mistake: conflict  .gitignore

The output is:

rails new blog
exist
identical  README.md
identical  Rakefile
identical  .ruby-version
identical  config.ru
conflict  .gitignore

Overwrite /home/jules/blog/.gitignore? (enter "h" for help) [Ynaqdhm]

What should I do? I'm using Ubuntu 20.04. I'm an absolute beginner.


问:
Filtering the dataFrame based on when condition
Hi i am trying to filter the dataframe based on when condition and then apply schema if it matches else leave it as it is.

```<code>val schema = ArrayType(StructType(StructField("packQty",FloatType,true):: StructField("gtin",StringType,true) :: Nil))

+--------------+---------+-----------+-----+--------------------------------------+
|orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins
|
+--------------+---------+-----------+--------------------------------------------+
|5203754   |15.0     |1.0        |5.0         |[{"packQty":120.0,"gtin":"00052000042276"}]|
|5203754   |15.0     |1.0        |2.0         |[{"packQty":120.0,"gtin":"00052000042276"}|
|5243700   |25.0     |1.0        |2.0         |na
|
+--------------+---------+-----------+------------+-------------------------------+
</code>```

i am tryin to add a column based on schema if the gtins column is not "na" if it is  i am adding 0, but it is throwing the error saying

```<code> df.withColumn("jsonData",when($"gtins"=!="na",from_json($"gtins",schema)).otherwise(0))

 Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve 'CASE
 WHEN contains(`gtins`, 'na') THEN 0 ELSE jsontostructs(`gtins`) END' due to data type
 mismatch: THEN and ELSE expressions should all be same type or coercible to a common type;;

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",explode($"jsonData").as("jsonData"))

 +--------------+---------+-----------+-----+--------------+
 |orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins|JsonData
 +--------------+---------+-----------+--------------------+
 |5203754   |15.0|1.0|5.0|[{"packQty":120.0,"gtin":"00052000042276”}]|[120.0, 00052000042276]
 |5203754   |15.0|1.0 |2.0|[{"packQty":120.0,"gtin":"00052000042276”}|[120.0,00052000042276]
 |5243700   |25.0 |1.0|2.0  |na  |null
 +--------------+---------+-----------+------------+----+

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",$"jsonData.packQty".as("packQty"),$"jsonData.gtin".as("gtin")
</code>```

this select is only selecting data where jsonData is not null

```<code>+---------+-----------+------------+-------+--------------+
 orderupcnumber |enrichqty|allocoutqty|allocatedqty|packQty|gtin  |
 +-----------+------------+----------------+------------+
 5203754|15.0     |1.0        |5.0         |120.0  |00052000042276|
 5203754|15.0     |1.0        |5.0         |144.0  |00052000042283|
 5243700|25.0     |1.0        |5.0         |  | |
 +-----------+------------+----------------+------------+----------
</code>```

how can i include one with null as well.

答:
The problem with your when and otherwise clause it it expects same return type as from_json which is possible only when you use same the function from_json with same schema formatting

```<code>import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{ArrayType, FloatType, StringType, StructField, StructType}

object ApplySchema {

  def main(args: Array[String]): Unit = {

    val spark = Constant.getSparkSess

    import spark.implicits._

    //Create Dataframe from the List
    val sampleDf = List((5203754,15.0,1.0,5.0,"""[{"packQty":120.0,"gtin":"00052000042276"}]"""),
      (5203754,15.0,1.0,2.0,"""[{"packQty":120.0,"gtin":"00052000042276"}]""")
      ,(5203754,25.0,1.0,2.0,"na")
    ).toDF("orderupcnumber","enrichqty","allocoutqty","allocatedqty","gtins") // Map the column to data

    //JSON schema
    val schema = ArrayType(StructType(StructField("packQty",FloatType,true)::
      StructField("gtin",StringType,true) :: Nil))

    //Add column JSON parsed column "jsonData"
    sampleDf.withColumn("jsonData",
      when($"gtins"=!="na",from_json($"gtins",schema)) // Check if the value is NA then parse the JSON
      .otherwise(from_json(lit("[]"),schema))) // Else parse an empty JSON array
      .show()
  }

}

</code>```

Body:
Hi i am trying to filter the dataframe based on when condition and then apply schema if it matches else leave it as it is.

val schema = ArrayType(StructType(StructField("packQty",FloatType,true):: StructField("gtin",StringType,true) :: Nil))

+--------------+---------+-----------+-----+--------------------------------------+
|orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins
|
+--------------+---------+-----------+--------------------------------------------+
|5203754   |15.0     |1.0        |5.0         |[{"packQty":120.0,"gtin":"00052000042276"}]|
|5203754   |15.0     |1.0        |2.0         |[{"packQty":120.0,"gtin":"00052000042276"}|
|5243700   |25.0     |1.0        |2.0         |na
|
+--------------+---------+-----------+------------+-------------------------------+

i am tryin to add a column based on schema if the gtins column is not "na" if it is  i am adding 0, but it is throwing the error saying

 df.withColumn("jsonData",when($"gtins"=!="na",from_json($"gtins",schema)).otherwise(0))

 Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve 'CASE
 WHEN contains(`gtins`, 'na') THEN 0 ELSE jsontostructs(`gtins`) END' due to data type
 mismatch: THEN and ELSE expressions should all be same type or coercible to a common type;;

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",explode($"jsonData").as("jsonData"))

 +--------------+---------+-----------+-----+--------------+
 |orderupcnumber|enrichqty|allocoutqty|allocatedqty|gtins|JsonData
 +--------------+---------+-----------+--------------------+
 |5203754   |15.0|1.0|5.0|[{"packQty":120.0,"gtin":"00052000042276”}]|[120.0, 00052000042276]
 |5203754   |15.0|1.0 |2.0|[{"packQty":120.0,"gtin":"00052000042276”}|[120.0,00052000042276]
 |5243700   |25.0 |1.0|2.0  |na  |null
 +--------------+---------+-----------+------------+----+

 df.select($"orderupcnumber",$"enrichqty",$"allocoutqty",$"allocatedqty",$"jsonData.packQty".as("packQty"),$"jsonData.gtin".as("gtin")

this select is only selecting data where jsonData is not null

+---------+-----------+------------+-------+--------------+
 orderupcnumber |enrichqty|allocoutqty|allocatedqty|packQty|gtin  |
 +-----------+------------+----------------+------------+
 5203754|15.0     |1.0        |5.0         |120.0  |00052000042276|
 5203754|15.0     |1.0        |5.0         |144.0  |00052000042283|
 5243700|25.0     |1.0        |5.0         |  | |
 +-----------+------------+----------------+------------+----------

how can i include one with null as well.

Body:
The problem with your when and otherwise clause it it expects same return type as from_json which is possible only when you use same the function from_json with same schema formatting

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{ArrayType, FloatType, StringType, StructField, StructType}

object ApplySchema {

  def main(args: Array[String]): Unit = {

    val spark = Constant.getSparkSess

    import spark.implicits._

    //Create Dataframe from the List
    val sampleDf = List((5203754,15.0,1.0,5.0,"""[{"packQty":120.0,"gtin":"00052000042276"}]"""),
      (5203754,15.0,1.0,2.0,"""[{"packQty":120.0,"gtin":"00052000042276"}]""")
      ,(5203754,25.0,1.0,2.0,"na")
    ).toDF("orderupcnumber","enrichqty","allocoutqty","allocatedqty","gtins") // Map the column to data

    //JSON schema
    val schema = ArrayType(StructType(StructField("packQty",FloatType,true)::
      StructField("gtin",StringType,true) :: Nil))

    //Add column JSON parsed column "jsonData"
    sampleDf.withColumn("jsonData",
      when($"gtins"=!="na",from_json($"gtins",schema)) // Check if the value is NA then parse the JSON
      .otherwise(from_json(lit("[]"),schema))) // Else parse an empty JSON array
      .show()
  }

}


问:
Add func in onDelete's perform in SwiftUI
The code is as following:

```<code>Section(header: Text("Head")) {
    ForEach() { child in
        ...
    }
    .onDelete(perform: self.db.delete)  <-- how to add other func in perform???
}
</code>```

And I want to add some other func when onDelete occurs like:

```<code>    .onDelete(perform: self.db.delete,
        otherFunc()
    )

func otherFunc() {
}
</code>```

The self.db.delete after perform is not easy to move to otherFunc() and I want to keep it not changing.

Then how to make it? Thanks for any help.

答:
You can create another function and pass to it the same parameters from onDelete(perform:):

```<code>Section(header: Text("Head")) {
    ForEach() { child in
        ...
    }
    .onDelete(perform: delete)
}
</code>```

And inside call self.db.delete with the same parameters as originally.

```<code>func delete(at offsets: IndexSet) {
    self.db.delete(offsets)
    otherFunction()
}
</code>```

Body:
The code is as following:

Section(header: Text("Head")) {
    ForEach() { child in
        ...
    }
    .onDelete(perform: self.db.delete)  <-- how to add other func in perform???
}

And I want to add some other func when onDelete occurs like:

    .onDelete(perform: self.db.delete,
        otherFunc()
    )

func otherFunc() {
}

The self.db.delete after perform is not easy to move to otherFunc() and I want to keep it not changing.

Then how to make it? Thanks for any help.

Body:
You can create another function and pass to it the same parameters from onDelete(perform:):

Section(header: Text("Head")) {
    ForEach() { child in
        ...
    }
    .onDelete(perform: delete)
}

And inside call self.db.delete with the same parameters as originally.

func delete(at offsets: IndexSet) {
    self.db.delete(offsets)
    otherFunction()
}


问:
How to search for patterns that are not exactly same each time?
I have a list like this:

```<code> list <- c("xxx 23 cut", "yyy", "zzz", "www 55 cut", "kkk", "ggg", "yyy", "eee 7 cut", "ccd" )
</code>```

The searching patter in this case is "any-number cut".  Thus, to visualize the list in a better way, the list is in the following pattern

```<code>"before item (=xxx) "  "any number cut (= 23 cut)"
"after item (=yyy)"
"after item (=zzz)"
"before item (=www) "  "any number cut (= 55 cut)"
"after item (=kkk)"
"after item (=ggg)"
"after items (=yyy)"
"before item (=eee) "  "any number cut (= 7cut)"
"after item (=cce)"
</code>```

I want place the "before items" to column 1, until it found another "any number cut" pattern, and put the "after items" to column 2.  The final results would as follows:

```<code>xxx yyy
xxx zzz
www kkk
www ggg
www yyy
eee ccd
</code>```

Could experts teach me how to do it with R?  I learn from previous stackoverflow messages that R can search for fixed items (e.g. cut) and strsplit them into different cells.  The challenge here (to me) is the searching pattern is changing that the number before the word "cut" is different for each of them.  what is the most efficient way to search and cut it in the right place using R?

答:
The following works with your example data:

```<code>x <- c("xxx 23 cut", "yyy", "zzz", "www 55 cut", "kkk", "ggg", "yyy", "eee 7 cut", "ccd" )
</code>```

First, create a regex pattern to use with grep:  The following pattern searches for digits (\d) followed by a space and the word cut.  See ?regexp and ?grep for details.

```<code>cut_pattern <- "\\d* cut"

cut_positions <- grep(cut_pattern, x)
cut_repeat <- c(cut_positions[-1], length(x) + 1) - cut_positions -1
before_items <- rep(x[cut_positions], times=cut_repeat)
after_items <- x[!grepl(cut_pattern, x)]

data.frame(
    before = before_items,
    after  = after_items
)
</code>```

The results:

```<code>      before after
1 xxx 23 cut   yyy
2 xxx 23 cut   zzz
3 www 55 cut   kkk
4 www 55 cut   ggg
5 www 55 cut   yyy
6  eee 7 cut   ccd
</code>```

I will leave it as an exercise to you to do the cleanup of the data in column 1.  Hint: Use str_extract in package stringr.  You can refer to this question: How can I use back references with `grep` in R? for examples of how to do this.  Further hint, your patterns should be something like "(.*) \\d* cut".

ContentLicense: CC BY-SA 3.0

Body:
I have a list like this:

 list <- c("xxx 23 cut", "yyy", "zzz", "www 55 cut", "kkk", "ggg", "yyy", "eee 7 cut", "ccd" )

The searching patter in this case is "any-number cut".  Thus, to visualize the list in a better way, the list is in the following pattern

"before item (=xxx) "  "any number cut (= 23 cut)"
"after item (=yyy)"
"after item (=zzz)"
"before item (=www) "  "any number cut (= 55 cut)"
"after item (=kkk)"
"after item (=ggg)"
"after items (=yyy)"
"before item (=eee) "  "any number cut (= 7cut)"
"after item (=cce)"

I want place the "before items" to column 1, until it found another "any number cut" pattern, and put the "after items" to column 2.  The final results would as follows:

xxx yyy
xxx zzz
www kkk
www ggg
www yyy
eee ccd

Could experts teach me how to do it with R?  I learn from previous stackoverflow messages that R can search for fixed items (e.g. cut) and strsplit them into different cells.  The challenge here (to me) is the searching pattern is changing that the number before the word "cut" is different for each of them.  what is the most efficient way to search and cut it in the right place using R?

Body:
The following works with your example data:

x <- c("xxx 23 cut", "yyy", "zzz", "www 55 cut", "kkk", "ggg", "yyy", "eee 7 cut", "ccd" )

First, create a regex pattern to use with grep:  The following pattern searches for digits (\d) followed by a space and the word cut.  See ?regexp and ?grep for details.

cut_pattern <- "\\d* cut"

cut_positions <- grep(cut_pattern, x)
cut_repeat <- c(cut_positions[-1], length(x) + 1) - cut_positions -1
before_items <- rep(x[cut_positions], times=cut_repeat)
after_items <- x[!grepl(cut_pattern, x)]

data.frame(
    before = before_items,
    after  = after_items
)

The results:

      before after
1 xxx 23 cut   yyy
2 xxx 23 cut   zzz
3 www 55 cut   kkk
4 www 55 cut   ggg
5 www 55 cut   yyy
6  eee 7 cut   ccd

I will leave it as an exercise to you to do the cleanup of the data in column 1.  Hint: Use str_extract in package stringr.  You can refer to this question: How can I use back references with `grep` in R? for examples of how to do this.  Further hint, your patterns should be something like "(.*) \\d* cut".


问:
How do I install Rainmeter plugins
I just downloaded Rainmeter and I went to the plugins page https://docs.rainmeter.net/manual/plugins/.

But I am not sure how to add plugins to my rainmeter install. For example, lets say I want too add the core temp plugin https://docs.rainmeter.net/manual/plugins/coretemp/

How do I go about doing that.

答:
I'm not sure this question really belongs on StackOverflow, might be more of a SuperUser question, but I'll provide an answer anyway.

For the plugins listed in the manual for Rainmeter, there is no installation needed, they come with Rainmeter (check the /Rainmeter/Plugins folder), and for 3rd party plugins you may find some instructions in the main plugins page of the Rainmeter manual.

Normally these would be distributed with a skin and installed using the Rainmeter Skin Installer, but may be manually installed by placing the .dll file in the Plugins folder under the settings path for the Rainmeter installation.

For the CoreTemp plugin specifically you'll need the CoreTemp application, which actually gathers the data from the temperature sensors, the plugin just exposes that data to Rainmeter skins. Instructions on how to integrate those data into your own skins is detailed on the page you've linked to.

Title: How do I install Rainmeter plugins


问:
Logout function not working React-Native to Ruby on Rails? I can't delete the session
I am having trouble with my authentication actions from react-native to my ruby on rails backend api. I thought my signup/ sign in actions were working fine until I made my logout action and I began receiving a rails controller error.  My logout function, requests a delete of user's session and can't find it, but my login/signup functions have no problem creating a session.

My Sessions#Controller:

```<code>class SessionsController < ApplicationController
  def create
  @user = User.find_by_credentials(
    params[:user][:username],
    params[:user][:password]
  )

  if @user
    login(@user)
    render "users/show.json.jbuilder"
  else
    render json: ["Invalid username/password combination"], status: 401
  end
end

def destroy
  @user = current_user   # I believe the problem is here, as it can't find current_user see
                         # application controller below
  if @user
    logout
    render json: {}
  else
    render json: ["Nobody signed in"], status: 404
  end
end
end
</code>```

Application#controller , where I find the current user based on the session_token

```<code>class ApplicationController < ActionController::Base
  skip_before_action :verify_authenticity_token

  helper_method :current_user, :logged_in?, :logout

  # private

  def current_user
    return nil unless session[:session_token]
    @current_user ||= User.find_by(session_token: session[:session_token])
  end

  def logged_in?
    !!current_user
  end

  def login(user)
    user.reset_session_token!
    session[:session_token] = user.session_token
    @current_user = user
  end

  def logout
    current_user.reset_session_token!
    session[:session_token] = nil
    @current_user = nil
  end
end
</code>```

My logout action:

```<code>export const testLogout = () => dispatch => {
  dispatch(loadSpinner());
  axios({
    method: 'delete',
    url: 'http://10.0.2.2:3000/session',
  })
  .then((response) => {
    console.log("response: ", response);
    if(reponse.status === 200) {
      {dispatch(logoutCurrentUser(response))}
    } else {
      console.log("status", response.status);
    };
  });
};

</code>```

My routes:

```<code>Rails.application.routes.draw do
  resources :users, only: [:create, :show]
  resource :session, only: [:create, :destroy, :show]
end
</code>```

The errors (1):
Started DELETE "/session" for 127.0.0.1 at 2020-05-27 10:23:23 -0700
Processing by SessionsController#destroy as HTML
Completed 404 Not Found in 0ms (Views: 0.2ms | ActiveRecord: 0.0ms).

(2):
Possible Unhandled Promise Rejection (id: 0):
Error: Request failed with status code 404

Error 2 from the testLogout() function never even makes it to the .then(response) in the function.

Now this 404 error is my own from the #destroy method in my sessions_controller and I am a bit unsure how to get a better error here but from what I am reading online is that react-native handles browser cookies differently and I am concerned I am missing something conceptually but I am very unsure of what it is.  I know I could use AsyncStorage for persisting sessions but how does that factor in with the back-end rails authentication? Any help figuring out how to log out a user is greatly appreciated thank you!

答:
I highly recommend using some form of a JWT for authentication handling. Using sessions with an external client is certainly possible, but it's a headache you probably don't want to deal with. Read about CORS. In short, you don't want to deal with CORS if you don't have to.

This seems like a fairly decent guide if you're using devise: https://medium.com/@eth3rnit3/crud-react-native-ror-backend-with-devise-auth-token-4407cac3aa0b

Body:
I am having trouble with my authentication actions from react-native to my ruby on rails backend api. I thought my signup/ sign in actions were working fine until I made my logout action and I began receiving a rails controller error.  My logout function, requests a delete of user's session and can't find it, but my login/signup functions have no problem creating a session.

My Sessions#Controller:

class SessionsController < ApplicationController
  def create
  @user = User.find_by_credentials(
    params[:user][:username],
    params[:user][:password]
  )

  if @user
    login(@user)
    render "users/show.json.jbuilder"
  else
    render json: ["Invalid username/password combination"], status: 401
  end
end

def destroy
  @user = current_user   # I believe the problem is here, as it can't find current_user see
                         # application controller below
  if @user
    logout
    render json: {}
  else
    render json: ["Nobody signed in"], status: 404
  end
end
end

Application#controller , where I find the current user based on the session_token

class ApplicationController < ActionController::Base
  skip_before_action :verify_authenticity_token

  helper_method :current_user, :logged_in?, :logout

  # private

  def current_user
    return nil unless session[:session_token]
    @current_user ||= User.find_by(session_token: session[:session_token])
  end

  def logged_in?
    !!current_user
  end

  def login(user)
    user.reset_session_token!
    session[:session_token] = user.session_token
    @current_user = user
  end

  def logout
    current_user.reset_session_token!
    session[:session_token] = nil
    @current_user = nil
  end
end

My logout action:

export const testLogout = () => dispatch => {
  dispatch(loadSpinner());
  axios({
    method: 'delete',
    url: 'http://10.0.2.2:3000/session',
  })
  .then((response) => {
    console.log("response: ", response);
    if(reponse.status === 200) {
      {dispatch(logoutCurrentUser(response))}
    } else {
      console.log("status", response.status);
    };
  });
};

My routes:

Rails.application.routes.draw do
  resources :users, only: [:create, :show]
  resource :session, only: [:create, :destroy, :show]
end

The errors (1):
Started DELETE "/session" for 127.0.0.1 at 2020-05-27 10:23:23 -0700
Processing by SessionsController#destroy as HTML
Completed 404 Not Found in 0ms (Views: 0.2ms | ActiveRecord: 0.0ms).

(2):
Possible Unhandled Promise Rejection (id: 0):
Error: Request failed with status code 404

Error 2 from the testLogout() function never even makes it to the .then(response) in the function.

Now this 404 error is my own from the #destroy method in my sessions_controller and I am a bit unsure how to get a better error here but from what I am reading online is that react-native handles browser cookies differently and I am concerned I am missing something conceptually but I am very unsure of what it is.  I know I could use AsyncStorage for persisting sessions but how does that factor in with the back-end rails authentication? Any help figuring out how to log out a user is greatly appreciated thank you!


问:
How to get the smallest item from the second items of a tuple list?
First of all sorry for the confusing title, I had no idead how to explain my problem without an example.

I have the following graph

```<code>graph = {
    1: [(3, 5), (4, 1),  (5, 4)],
    2: [(5, 9)],
    3: [(5, 1), (6, 1)],
    4: [(2, 11), (8, 2)],
    5: [(4, 6), (2, 6)],
    6: [(7, 1)],
    7: [(5, 7), (2, 1)],
    8: [(2, 6)],
}
</code>```

I want to be able to get the smallest number from the second item of the tupels for a given number. For example, if I gave the function the number 1 I would want it to return the 1 from the second tupel. If the input was 4 instead I would expect it to return a 2 form the second tupel.

My current approach is min((graph[s])[1]), but this doesn't really work and mostly returns Index Errors.

Edit:
I solved the problem with (min(graph[s])[0], min(graph[s])[1])[1] now (for some reason) it works in all cases (the problems were with lists that only contained one tupel).

答:
min((graph[key])[1]) works for me.

You can try : min([x[1] for x in graph[key]])

Body:
First of all sorry for the confusing title, I had no idead how to explain my problem without an example.

I have the following graph

graph = {
    1: [(3, 5), (4, 1),  (5, 4)],
    2: [(5, 9)],
    3: [(5, 1), (6, 1)],
    4: [(2, 11), (8, 2)],
    5: [(4, 6), (2, 6)],
    6: [(7, 1)],
    7: [(5, 7), (2, 1)],
    8: [(2, 6)],
}

I want to be able to get the smallest number from the second item of the tupels for a given number. For example, if I gave the function the number 1 I would want it to return the 1 from the second tupel. If the input was 4 instead I would expect it to return a 2 form the second tupel.

My current approach is min((graph[s])[1]), but this doesn't really work and mostly returns Index Errors.

Edit:
I solved the problem with (min(graph[s])[0], min(graph[s])[1])[1] now (for some reason) it works in all cases (the problems were with lists that only contained one tupel).


答:
It seems like you run rails new blog instead of rails s/rails server.
Since it already has all the files of a rails application called "blog", it's asking if it should overwrite the existing files with the new files it is creating because you ran rails new blog.

Title: Rails: conflict error overwrite /home/username/blog/.gitignore?


问:
cvlib detect_common_objects is not working
https://github.com/arunponnusamy/cvlib/tree/f46a22f8e13bc4b0267b9057fa88de170d41f96a

I'm checking examples of cvlib and trying on my own on spyder Python 3.7
Face detection is working very fine..
Gender detection working very fine but object detection is not working...
Output is the image itself.
I have tried BGR2RGB but nothing happens.

here is code

```<code>import cvlib as cv
from cvlib.object_detection import draw_bbox
import cv2
path = r'C:\Users\user\desktop\cod\object_detection_input.jpg'
image = cv2.imread(path)
bbox, label, conf = cv.detect_common_objects(image)
print(bbox, label, conf)
out = draw_bbox(image, bbox, label, conf)
cv2.imshow("object_detection", out)
cv2.waitKey()
cv2.destroyAllWindows()
</code>```

答:
If the function return empty list, the probable reason is problems in yolov3.cfg, yolov3.weights files that train the model (yolov3.weights is  242 mg file).

In windows these files should be in folder:

```<code>C:\Users\USER_NAME\.cvlib\object_detection\yolo\yolov3
</code>```

The files are download in the first time the function work. If the files are corrupted, the function will not work but also will not throw an error!!

fix: Delete these files and run the function again you will see download of both files.

Body:
https://github.com/arunponnusamy/cvlib/tree/f46a22f8e13bc4b0267b9057fa88de170d41f96a

I'm checking examples of cvlib and trying on my own on spyder Python 3.7
Face detection is working very fine..
Gender detection working very fine but object detection is not working...
Output is the image itself.
I have tried BGR2RGB but nothing happens.

here is code

import cvlib as cv
from cvlib.object_detection import draw_bbox
import cv2
path = r'C:\Users\user\desktop\cod\object_detection_input.jpg'
image = cv2.imread(path)
bbox, label, conf = cv.detect_common_objects(image)
print(bbox, label, conf)
out = draw_bbox(image, bbox, label, conf)
cv2.imshow("object_detection", out)
cv2.waitKey()
cv2.destroyAllWindows()

Body:
If the function return empty list, the probable reason is problems in yolov3.cfg, yolov3.weights files that train the model (yolov3.weights is  242 mg file).

In windows these files should be in folder:

C:\Users\USER_NAME\.cvlib\object_detection\yolo\yolov3

The files are download in the first time the function work. If the files are corrupted, the function will not work but also will not throw an error!!

fix: Delete these files and run the function again you will see download of both files.


问:
Receiving error while creating project with Razor page template
Immediately I click on create and the project loads. I always receive the below error. I cannot do anything without correcting this.

This is the error:

Severity  Code    Description Project File    Line    Suppression State
  Error   NETSDK1004  Assets file 'C:\Users\HARBIORLAR PC\Desktop\VB Web Projects\BookList\BookList\BookList\obj\project.assets.json' not found. Run a NuGet package restore to generate this file.   BookList    C:\Program Files\dotnet\sdk\3.1.300\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets    234

Screen shot of the error:

答:
This is what i did and it works,I Enable automatic package restore by choosing Tools > Options > NuGet Package Manager, and then selecting Automatically check for missing packages during build in Visual Studio under Package Restore.
Then I build the project with internet connection on and the missing file was downloaded.
This the Screen shot After successful</p>


问:
Python: Mock AWS with Click
I have a click cli app and I am trying to mock AWS SSM Parameter Store, but runner.invoke is not returning the expected results.

This is test_demo.py:

```<code>from click.testing import CliRunner

import os
import boto3
from moto import mock_ssm
import pytest

@pytest.fixture(scope='package')
def aws_credentials():
    """Mocked AWS Credentials for moto."""
    os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
    os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
    os.environ['AWS_SECURITY_TOKEN'] = 'testing'
    os.environ['AWS_SESSION_TOKEN'] = 'testing'
    os.environ['AWS_DEFAULT_REGION'] = 'us-west-2'

@pytest.fixture(scope='package')
def ssm(aws_credentials):
    with mock_ssm():
        yield boto3.client('ssm')

def test_get_mock_ssm(ssm):
    # We need to create the ssm entry first since this is all in Moto's 'virtual' AWS account
    ssm.put_parameter(
        Name='test',
        Description='name',
        Value='text',
        Type='String',
        Overwrite=True,
        Tier='Standard',
        DataType='text'
    )
    out = ssm.get_parameter(Name='test')
    print('without cli')
    print(out)
    from src.cli import entrypoint
    runner = CliRunner()
    response = runner.invoke(entrypoint, ["get", "--name", "test"])
    print('with cli')
    print(response)
    assert response.exit_code == 0

</code>```

The results of the test are:

```<code>without cli
{'Parameter': {'Name': 'test', 'Type': 'String', 'Value': 'text', 'Version': 1, 'LastModifiedDate': datetime.datetime(2020, 5, 31, 9, 3, 21, 920000, tzinfo=tzlocal()), 'ARN': 'arn:aws:ssm:us-west-2:1234567890:parameter/test'}, 'ResponseMetadata': {'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}

with cli
<Result okay>
PASSED
</code>```

I expect the out of the cli to be same as withoutcli.

click code:

```<code>import click

import manage_secrets

@click.group()
def entrypoint():
    pass

@entrypoint.command()
@click.option('--name', required=True,
              help='Name of parameter to get value from SSM')
def get(name):
    """get secrets"""
    click.echo("getting value of: {0}" .format(name))
    print(manage_secrets.get_value_from_parameter_store(name))

if __name__ == "__main__":
    entrypoint()

</code>```

manage_secrets code:

```<code>import boto3

parameter_name = None

def get_value_from_parameter_store(name):
    client = boto3.client('ssm')
    try:
        parameter = client.get_parameter(Name=name, WithDecryption=True)
        return parameter
    except client.exceptions.ParameterNotFound:
        print("parameter not found")

</code>```

I have added a return and its just default, not parsing and I think it is the same for ssm.get_parameter. I am not sure what I am missing. Any pointers or suggestions?

答:
My result was ok, I need to get the response.output from the test.

This helped: https://gist.github.com/lbillingham/6412cdc19f9a44901b03841e0443fbf7

Title: Python: Mock AWS with Click

Body:
I have a click cli app and I am trying to mock AWS SSM Parameter Store, but runner.invoke is not returning the expected results.

This is test_demo.py:

from click.testing import CliRunner

import os
import boto3
from moto import mock_ssm
import pytest

@pytest.fixture(scope='package')
def aws_credentials():
    """Mocked AWS Credentials for moto."""
    os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
    os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
    os.environ['AWS_SECURITY_TOKEN'] = 'testing'
    os.environ['AWS_SESSION_TOKEN'] = 'testing'
    os.environ['AWS_DEFAULT_REGION'] = 'us-west-2'

@pytest.fixture(scope='package')
def ssm(aws_credentials):
    with mock_ssm():
        yield boto3.client('ssm')

def test_get_mock_ssm(ssm):
    # We need to create the ssm entry first since this is all in Moto's 'virtual' AWS account
    ssm.put_parameter(
        Name='test',
        Description='name',
        Value='text',
        Type='String',
        Overwrite=True,
        Tier='Standard',
        DataType='text'
    )
    out = ssm.get_parameter(Name='test')
    print('without cli')
    print(out)
    from src.cli import entrypoint
    runner = CliRunner()
    response = runner.invoke(entrypoint, ["get", "--name", "test"])
    print('with cli')
    print(response)
    assert response.exit_code == 0

The results of the test are:

without cli
{'Parameter': {'Name': 'test', 'Type': 'String', 'Value': 'text', 'Version': 1, 'LastModifiedDate': datetime.datetime(2020, 5, 31, 9, 3, 21, 920000, tzinfo=tzlocal()), 'ARN': 'arn:aws:ssm:us-west-2:1234567890:parameter/test'}, 'ResponseMetadata': {'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}

with cli
<Result okay>
PASSED

I expect the out of the cli to be same as withoutcli.

click code:

import click

import manage_secrets

@click.group()
def entrypoint():
    pass

@entrypoint.command()
@click.option('--name', required=True,
              help='Name of parameter to get value from SSM')
def get(name):
    """get secrets"""
    click.echo("getting value of: {0}" .format(name))
    print(manage_secrets.get_value_from_parameter_store(name))

if __name__ == "__main__":
    entrypoint()

manage_secrets code:

import boto3

parameter_name = None

def get_value_from_parameter_store(name):
    client = boto3.client('ssm')
    try:
        parameter = client.get_parameter(Name=name, WithDecryption=True)
        return parameter
    except client.exceptions.ParameterNotFound:
        print("parameter not found")

I have added a return and its just default, not parsing and I think it is the same for ssm.get_parameter. I am not sure what I am missing. Any pointers or suggestions?


问:
Generating a new dataframe from existing columns
I am trying to create a new column D from existing A, B, C column.

first value in Col D is A1

second value in Col D is B2

third value in Col D is C3

fourth value in Col D is A4

fifth value in Col D is B5

sixth value in Col D is C6

following this pattern, the rest of the values in Col D is iteration of this pattern. Please reference the graph.

Any code ideas?

Click the link to see the picture

答:
We can use, pd.concat to create a dataframe having the columns A, B, C with the values in the columns are filled accordingly by consecutively iterating through the columns and selecting the next value from that column as per the conditions then use DataFrame.agg to agg the dataframe by droping the NaN values:

```<code>d = pd.concat([df[col].iloc[i::df.columns.size] for i, col in enumerate(df.columns)], axis=1)
df['D'] = d.agg(lambda s: s.dropna().iloc[0], axis=1)
</code>```

Result:

```<code># print(df)
    A   B   C   D
0  A1  B1  C1  A1
1  A2  B2  C2  B2
2  A3  B3  C3  C3
3  A4  B4  C4  A4
4  A5  B5  C5  B5
5  A6  B6  C6  C6
</code>```

Body:
We can use, pd.concat to create a dataframe having the columns A, B, C with the values in the columns are filled accordingly by consecutively iterating through the columns and selecting the next value from that column as per the conditions then use DataFrame.agg to agg the dataframe by droping the NaN values:

d = pd.concat([df[col].iloc[i::df.columns.size] for i, col in enumerate(df.columns)], axis=1)
df['D'] = d.agg(lambda s: s.dropna().iloc[0], axis=1)

Result:

# print(df)
    A   B   C   D
0  A1  B1  C1  A1
1  A2  B2  C2  B2
2  A3  B3  C3  C3
3  A4  B4  C4  A4
4  A5  B5  C5  B5
5  A6  B6  C6  C6


问:
Why I am unale to connect to my Atlas Cluster?
I am learning basic course of MongoDatabase at Mongo University, and I am Unable to connect my own Cluster.

Although I have named my cluster differently which is StockMarketAnalysis.

```<code>mongo "mongodb+srv://sandbox-xxxxx.mongodb.net/test"  --username m001-student --password m001-mongodb-basics
</code>```

Output I am getting

```<code>DNSHostNotFound: Failed to look up service "":DNS name does not exist.
try 'mongo --help' for more information
</code>```

After doing npm as one of given below answer

I am still not able to do it

答:
I've had the same problem while following the instructions on MongoDB University.
The problem here is before running the following code you'll have to edit the xxxxx to the one found in your connection string. The following was just a generalized sandbox code.

```<code>mongo "mongodb+srv://sandbox-**xxxxx**.mongodb.net/test"  --username m001-student --password m001-mongodb-basics
</code>```

It would be different for your own sandbox.It would be something like :

```<code>mongo "mongodb+srv://sandbox-**byutb**.mongodb.net/test" --username m001-student --password m001-mongodb-basics
</code>```

I hope this was helpful.

Body:
I am learning basic course of MongoDatabase at Mongo University, and I am Unable to connect my own Cluster.

Although I have named my cluster differently which is StockMarketAnalysis.

mongo "mongodb+srv://sandbox-xxxxx.mongodb.net/test"  --username m001-student --password m001-mongodb-basics

Output I am getting

DNSHostNotFound: Failed to look up service "":DNS name does not exist.
try 'mongo --help' for more information

After doing npm as one of given below answer

I am still not able to do it

Body:
I've had the same problem while following the instructions on MongoDB University.
The problem here is before running the following code you'll have to edit the xxxxx to the one found in your connection string. The following was just a generalized sandbox code.

mongo "mongodb+srv://sandbox-**xxxxx**.mongodb.net/test"  --username m001-student --password m001-mongodb-basics

It would be different for your own sandbox.It would be something like :

mongo "mongodb+srv://sandbox-**byutb**.mongodb.net/test" --username m001-student --password m001-mongodb-basics

I hope this was helpful.


问:
I can't connect to mysql in docker from my localhost with DataGrip database client
I have the following docker-compose.yml file:

```<code>version: '3.2'

services:

  mysql:
    image: mysql:5.7
    environment:
      - MYSQL_ROOT_PASSWORD=verysecret
      - MYSQL_DATABASE=yii2advanced
      - MYSQL_USER=yii2advanced
      - MYSQL_PASSWORD=secret
</code>```

I run it via docker-compose up -d. But I can't connect from SQL client to my database (I use DataGrip from JetBrains). Here is my configuration:

The password of course is secret. I have already tried to check allowed hosts for yii2advanced user:

As you can see for my yii2advanced connection is allowed from any host. I have tried to change mysqld.cnf and set bind-address    = 0.0.0.0. Tried to setbind-address to *. Tried to set not 127.0.0.1 but 172.17.0.1 in the settings of my SQL client. Tried to create manually new one user with full privileges.  No effect. The problem still exists. I can't connect to mysql in the container from my localhost.

What is wrong?

答:
By default, docker-compose create a bridge network that will isolate your application from outside including the localhost.

You need to expose 3306 port from isolated network to localhost.

Try this.

```<code>version: '3.2'

services:

  mysql:
    image: mysql:5.7
    environment:
      - MYSQL_ROOT_PASSWORD=verysecret
      - MYSQL_DATABASE=yii2advanced
      - MYSQL_USER=yii2advanced
      - MYSQL_PASSWORD=secret
    ports:
      - 3306:3306 # <host port>:<container port>
</code>```

Good to read docker network section. https://docs.docker.com/network/

Body:
I have the following docker-compose.yml file:

version: '3.2'

services:

  mysql:
    image: mysql:5.7
    environment:
      - MYSQL_ROOT_PASSWORD=verysecret
      - MYSQL_DATABASE=yii2advanced
      - MYSQL_USER=yii2advanced
      - MYSQL_PASSWORD=secret

I run it via docker-compose up -d. But I can't connect from SQL client to my database (I use DataGrip from JetBrains). Here is my configuration:

The password of course is secret. I have already tried to check allowed hosts for yii2advanced user:

As you can see for my yii2advanced connection is allowed from any host. I have tried to change mysqld.cnf and set bind-address    = 0.0.0.0. Tried to setbind-address to *. Tried to set not 127.0.0.1 but 172.17.0.1 in the settings of my SQL client. Tried to create manually new one user with full privileges.  No effect. The problem still exists. I can't connect to mysql in the container from my localhost.

What is wrong?

Body:
By default, docker-compose create a bridge network that will isolate your application from outside including the localhost.

You need to expose 3306 port from isolated network to localhost.

Try this.

version: '3.2'

services:

  mysql:
    image: mysql:5.7
    environment:
      - MYSQL_ROOT_PASSWORD=verysecret
      - MYSQL_DATABASE=yii2advanced
      - MYSQL_USER=yii2advanced
      - MYSQL_PASSWORD=secret
    ports:
      - 3306:3306 # <host port>:<container port>

Good to read docker network section. https://docs.docker.com/network/


问:
c# custom xml serialization, do not include the name of the nested class list in the xml tags
In .NET Coew 3.1 I am trying to generate an XML file of the following class, but without the orders tag showing in the XML file, meaning I have the root tag, than only the list of items

```<code>[XmlRoot("data")]
public class PurchaseOrder
{
    [XmlElement("orders")]
    public Item [] ItemsOrders;
}
[XmlRoot("item")]
public class Item
{
    [XmlElement("itemid")]
    public string ItemID;
    [XmlElement("price")]
    public decimal ItemPrice;
}
</code>```

would result in

```<code><data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <orders>
        <item>
            <itemid>aaa111</itemid>
            <ItemPrice>34.22</ItemPrice>
        </item>
        <item>
            <itemid>bbb222</itemid>
            <price>2.89</price>
        </item>
    </orders>
</data>
</code>```

but I need to remove the orders tag. The result I need to produce is

```<code><data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <item>
        <itemid>aaa111</itemid>
        <ItemPrice>34.22</ItemPrice>
    </item>
    <item>
        <itemid>bbb222</itemid>
        <price>2.89</price>
    </item>
</data>
</code>```

答:
The best way to get the correct classes you require would be to copy the XML you want to the clipboard, and then (in VS2019) Edit/Paste Special/Paste Classes As XML.

This will create the correct classes for the XML you supplied.

Body:
In .NET Coew 3.1 I am trying to generate an XML file of the following class, but without the orders tag showing in the XML file, meaning I have the root tag, than only the list of items

[XmlRoot("data")]
public class PurchaseOrder
{
    [XmlElement("orders")]
    public Item [] ItemsOrders;
}
[XmlRoot("item")]
public class Item
{
    [XmlElement("itemid")]
    public string ItemID;
    [XmlElement("price")]
    public decimal ItemPrice;
}

would result in

<data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <orders>
        <item>
            <itemid>aaa111</itemid>
            <ItemPrice>34.22</ItemPrice>
        </item>
        <item>
            <itemid>bbb222</itemid>
            <price>2.89</price>
        </item>
    </orders>
</data>

but I need to remove the orders tag. The result I need to produce is

<data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <item>
        <itemid>aaa111</itemid>
        <ItemPrice>34.22</ItemPrice>
    </item>
    <item>
        <itemid>bbb222</itemid>
        <price>2.89</price>
    </item>
</data>


问:
Vectors divisible by 3 and 4
Im trying to make 2 empty vectors C and D and if vector (1:n) will be divisible by 3%%==0 then its need to be divide by a and be written into vector C same with D but 4%%==0 and then divide by b and writte to D vector</p>

```<code>funkcia = function(a,b,n)
{
  vektor = 1:n
  C <- vector()
  D <- vector()
  for (i in 1:lenght(vektor)) {

    if(vektor[i]%%3==0)
      {
      y = vektor[i]/a
      C = c(C,y)
    }

    else if (vektor[i]%%4==0)
      {
      x = vektor[i]/b
      D = c(D,x)
    }
    print("vector C")
    print(C)
    print("vector D")
    print(D)
  }
}

funkcia(3,4,9)
</code>```

答:
I think its working right</p>

```<code>funkcia = function(a,b,n)
{
  vektor = 1:n
  C <- vector()
  D <- vector()
  for (i in 1:length(vektor)) {

    if(vektor[i]%%3==0)
      {
      y = vektor[i]/a
      C = c(C,y)
    }

    else if (vektor[i]%%4==0)
      {
      x = vektor[i]/b
      D = c(D,x)
    }

  }
  print("vector C")
  print(C)
  print("vector D")
  print(D)
}

funkcia(3,4,9)
</code>```

Title: Vectors divisible by 3 and 4

Body:
Im trying to make 2 empty vectors C and D and if vector (1:n) will be divisible by 3%%==0 then its need to be divide by a and be written into vector C same with D but 4%%==0 and then divide by b and writte to D vector

funkcia = function(a,b,n)
{
  vektor = 1:n
  C <- vector()
  D <- vector()
  for (i in 1:lenght(vektor)) {

    if(vektor[i]%%3==0)
      {
      y = vektor[i]/a
      C = c(C,y)
    }

    else if (vektor[i]%%4==0)
      {
      x = vektor[i]/b
      D = c(D,x)
    }
    print("vector C")
    print(C)
    print("vector D")
    print(D)
  }
}

funkcia(3,4,9)

Body:
I think its working right

funkcia = function(a,b,n)
{
  vektor = 1:n
  C <- vector()
  D <- vector()
  for (i in 1:length(vektor)) {

    if(vektor[i]%%3==0)
      {
      y = vektor[i]/a
      C = c(C,y)
    }

    else if (vektor[i]%%4==0)
      {
      x = vektor[i]/b
      D = c(D,x)
    }

  }
  print("vector C")
  print(C)
  print("vector D")
  print(D)
}

funkcia(3,4,9)


问:
Unable to drag and drop in selenium for only this website
```<code>WebDriver driver = new ChromeDriver(); //Launch the chrome browser
driver.get("https://www.seleniumeasy.com/test/drag-and-drop-demo.html");
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[@id=\"todrag\"]/span[2]"));
WebElement from = driver.findElement(By.xpath("//*[@id=\"todrag\"]/span[2]"));
WebElement to = driver.findElement(By.xpath("//*[@id='mydropzone']"));
Actions builder = new Actions(driver);
builder.dragAndDrop(from, to).perform();
</code>```

答:
I put it in Junit test. Works fine for me.

But I noticed you're not setting property to use a local chromedriver.

Have you got a chromedriver downloaded?

```<code>
    private WebDriver driver;

    @Before
    public void setUp() throws Exception {
        System.setProperty("webdriver.chrome.driver",
                //"C:/path/to/your/chromedriver.exe"
                "/path/to/your/chromedriver"); // Might be this.
        driver= new ChromeDriver();
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
    }

    @Test
    public void testDragNDrop() {
        driver.get("https://www.seleniumeasy.com/test/drag-and-drop-demo.html");
        driver.manage().window().maximize();
        driver.findElement(By.xpath("//*[@id=\"todrag\"]/span[2]"));
        WebElement from = driver.findElement(By.xpath("//*[@id=\"todrag\"]/span[2]"));
        WebElement to = driver.findElement(By.xpath("//*[@id='mydropzone']"));
        Actions builder = new Actions(driver);
        builder.dragAndDrop(from, to).perform();
    }
</code>```

Body:
I put it in Junit test. Works fine for me.

But I noticed you're not setting property to use a local chromedriver.

Have you got a chromedriver downloaded?

    private WebDriver driver;

    @Before
    public void setUp() throws Exception {
        System.setProperty("webdriver.chrome.driver",
                //"C:/path/to/your/chromedriver.exe"
                "/path/to/your/chromedriver"); // Might be this.
        driver= new ChromeDriver();
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
    }

    @Test
    public void testDragNDrop() {
        driver.get("https://www.seleniumeasy.com/test/drag-and-drop-demo.html");
        driver.manage().window().maximize();
        driver.findElement(By.xpath("//*[@id=\"todrag\"]/span[2]"));
        WebElement from = driver.findElement(By.xpath("//*[@id=\"todrag\"]/span[2]"));
        WebElement to = driver.findElement(By.xpath("//*[@id='mydropzone']"));
        Actions builder = new Actions(driver);
        builder.dragAndDrop(from, to).perform();
    }


问:
How check if html5 form validation is complete
I have a form which am using html5 to validate for email and required fields.
The form is to be submitted via ajax.
How do i determine that the form passed validation before i allow to form to submitted via ajax.

This is my html:

<form action="" method="post" id="comment_form">
  <input type="hidden" name="post_id" value="<?=$post->ID ?>" />
  Name
  <input type="text" name="name" required="required">

  Email Address
  <input type="email" name="email" required="required">

  Comment
  <textarea name="comment" required="required" >
  </textarea>

  <button type="submit"class="button green meduim" id="comment_btn">Submit</button>
</form>
```

<p>This is my jquery</p>

<pre class="lang-js prettyprint-override"><code>$("#comment_btn").click(function(e){
  //the request url
  var url = site_url+'comments/post_comment';
  //cross site request forgery token
  var xtoken = $("input[name='xtoken']").val();
  //post data
  var dataObj = {
    "name":$('#name').val(),
    "email":$("#email").val(),
    "comment":$("#comment").val(),
    "post_id":$("input[name='post_id']").val(),
    "xtoken":xtoken
  };
  //dim form
  $('#comment_form').addClass('dim');
  //make request
  $.ajax({
    url:url,
    type:'POST',
    data:dataObj,
    dataType:'json',
    error:function() {},
    success:function(resp) {
      if(resp.status == "ok")
      {
        $('#comment_form').removeClass('dim');
      }else {
        alert("An error was encountered");
      }
    }
  });
  e.preventDefault();
});
</code>```

Is there a way to determine if the form is validated?

答:
It's been long, but here is my aproach to this kind of situation. Especially when i prefer to use AJAX with native HTML validation.

```<code>document.getElementById("myBtn").addEventListener("click", checkIfValid);
const checkIfValid = {} => {
  if(document.getElementById('myForm').checkValidity()) {
      event.preventDefault();
      // Do some AJAX stuff;
    }
}
</code>```

PS: If event.preventDefault() is used outside if clause, it doesn't do the trick.

Body:
I have a form which am using html5 to validate for email and required fields.
The form is to be submitted via ajax.
How do i determine that the form passed validation before i allow to form to submitted via ajax.

This is my html:

<form action="" method="post" id="comment_form">
  <input type="hidden" name="post_id" value="<?=$post->ID ?>" />
  Name
  <input type="text" name="name" required="required">

  Email Address
  <input type="email" name="email" required="required">

  Comment
  <textarea name="comment" required="required" >
  </textarea>

  <button type="submit"class="button green meduim" id="comment_btn">Submit</button>
</form>

This is my jquery

$("#comment_btn").click(function(e){
  //the request url
  var url = site_url+'comments/post_comment';
  //cross site request forgery token
  var xtoken = $("input[name='xtoken']").val();
  //post data
  var dataObj = {
    "name":$('#name').val(),
    "email":$("#email").val(),
    "comment":$("#comment").val(),
    "post_id":$("input[name='post_id']").val(),
    "xtoken":xtoken
  };
  //dim form
  $('#comment_form').addClass('dim');
  //make request
  $.ajax({
    url:url,
    type:'POST',
    data:dataObj,
    dataType:'json',
    error:function() {},
    success:function(resp) {
      if(resp.status == "ok")
      {
        $('#comment_form').removeClass('dim');
      }else {
        alert("An error was encountered");
      }
    }
  });
  e.preventDefault();
});

Is there a way to determine if the form is validated?

Body:
It's been long, but here is my aproach to this kind of situation. Especially when i prefer to use AJAX with native HTML validation.

document.getElementById("myBtn").addEventListener("click", checkIfValid);
const checkIfValid = {} => {
  if(document.getElementById('myForm').checkValidity()) {
      event.preventDefault();
      // Do some AJAX stuff;
    }
}

PS: If event.preventDefault() is used outside if clause, it doesn't do the trick.


问:
LinkedIn and Open Graph : site not shareable on LinkedIn without reason
I'm trying to make my website shareable on LinkedIn.

URL : https://www.jedecouvremercator.com/

My website is W3C validate. I have followed all the LinkedIn recommendations and Google recommendations. My Open Graph meta is correct and the website is shareable on all other platforms.

But when I'm trying to share it on LinkedIn or when I use a custom link to share it, LinkedIn can't display the meta information.

(I always use garbage into the URL to kill cache before verifying my changes).

Can somebody tell me why?

Thanks a lot.

答:
The site in your URL is down, and you didn't post any code, so that makes this difficult, but not impossible.  I can still view your URL through archive.org, and when I try to share the archive.org URL, like this...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fweb.archive.org%2Fweb%2F20190618064744%2Fhttps%3A%2F%2Fwww.jedecouvremercator.com%2F
</code>```

When I click the above, everything works perfectly fine for me.  Example:

If you need more info: Official LinkedIn Documentation for Formatting URL and Official LinkedIn Documentation for OpenGraph Tags and Prefilled Sharing.

Body:
The site in your URL is down, and you didn't post any code, so that makes this difficult, but not impossible.  I can still view your URL through archive.org, and when I try to share the archive.org URL, like this...

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fweb.archive.org%2Fweb%2F20190618064744%2Fhttps%3A%2F%2Fwww.jedecouvremercator.com%2F

When I click the above, everything works perfectly fine for me.  Example:

If you need more info: Official LinkedIn Documentation for Formatting URL and Official LinkedIn Documentation for OpenGraph Tags and Prefilled Sharing.


问:
dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
I installed vapor via homebrew and then immediately wanted to jump into a project by executing vapor new Hello but then got the following message back in the terminal:

```<code>dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
Referenced from: /usr/local/bin/vapor
Reason: image not found
zsh: abort      vapor new Hello
</code>```

I tried some approaches to fix this like uninstalling and reinstalling openssl via brew but that didn't work . Also tried something I found in the internet but nothing worked. I assume it has something to do with vapor only working with version 1.0.0 but not 1.1.1 and that's what I have. I guess I need to downgrade to 1.0.0 but how'd I do that? I'm on MacOS Catalina if that matters.

答:
I spent a lot of time trying all of the above, and nothing seemed to solve. Then I resorted the reinstalling ruby, and 2 minutes later the problem entirely vanished.

I hope this saves something else some time.

Body:
I installed vapor via homebrew and then immediately wanted to jump into a project by executing vapor new Hello but then got the following message back in the terminal:

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
Referenced from: /usr/local/bin/vapor
Reason: image not found
zsh: abort      vapor new Hello

I tried some approaches to fix this like uninstalling and reinstalling openssl via brew but that didn't work . Also tried something I found in the internet but nothing worked. I assume it has something to do with vapor only working with version 1.0.0 but not 1.1.1 and that's what I have. I guess I need to downgrade to 1.0.0 but how'd I do that? I'm on MacOS Catalina if that matters.


问:
How to disable warnings and notices by php.ini
I write this code in php.ini to disable warnings and notices, but it is not working for me. error_reporting = E_ALL & ~E_NOTICE & ~E_WARNING.

Below is my error handling code of php.ini.

```<code>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; error_reporting is a bit-field.  Or each number up to get desired error
; reporting level
; E_ALL             - All errors and warnings (doesn't include E_STRICT)
; E_ERROR           - fatal run-time errors
; E_RECOVERABLE_ERROR  - almost fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it's automatically initialized to an
;                     empty string)
; E_STRICT          - run-time notices, enable to have PHP suggest changes
;                     to your code which will ensure the best interoperability
;                     and forward compatibility of your code
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
;
; Examples:
;
;   - Show all errors, except for notices and coding standards warnings
;
 error_reporting = E_ALL & ~E_NOTICE & ~E_WARNING
;
;   - Show all errors, except for notices
;
; error_reporting = E_ALL & ~E_NOTICE | E_STRICT
;
;   - Show only errors
;
; error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR
;
;   - Show all errors, except coding standards warnings
;

; Print out errors (as a part of the output).  For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below).  Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
;
; possible values for display_errors:
;
; Off          - Do not display any errors
; stderr       - Display errors to STDERR (affects only CGI/CLI binaries!)
; On or stdout - Display errors to STDOUT (default)
;
; To output errors to STDERR with CGI/CLI:
;display_errors = "stderr"
;
; Default
;
display_errors = On

; Even when display_errors is on, errors that occur during PHP's startup
; sequence are not displayed.  It's strongly recommended to keep
; display_startup_errors off, except for when debugging.
display_startup_errors = On

; Log errors into a log file (server-specific log, stderr, or error_log (below))
; As stated above, you're strongly advised to use error logging in place of
; error displaying on production web sites.
log_errors = On

; Set maximum length of log_errors. In error_log information about the source is
; added. The default is 1024 and 0 allows to not apply any maximum length at all.
log_errors_max_len = 1024

; Do not log repeated messages. Repeated errors must occur in same file on same
; line unless ignore_repeated_source is set true.
ignore_repeated_errors = Off

; Ignore source of message when ignoring repeated messages. When this setting
; is On you will not log errors with repeated messages from different files or
; source lines.
ignore_repeated_source = Off

; If this parameter is set to Off, then memory leaks will not be shown (on
; stdout or in the log). This has only effect in a debug compile, and if
; error reporting includes E_WARNING in the allowed list
report_memleaks = On

;report_zend_debug = 0

; Store the last error/warning message in $php_errormsg (boolean).
track_errors = Off

; Turn off normal error reporting and emit XML-RPC error XML
;xmlrpc_errors = 0
; An XML-RPC faultCode
;xmlrpc_error_number = 0

; Disable the inclusion of HTML tags in error messages.
; Note: Never use this feature for production boxes.
;html_errors = Off

; If html_errors is set On PHP produces clickable error messages that direct
; to a page describing the error or function causing the error in detail.
; You can download a copy of the PHP manual from http://www.php.net/docs.php
; and change docref_root to the base URL of your local copy including the
; leading '/'. You must also specify the file extension being used including
; the dot.
; Note: Never use this feature for production boxes.
;docref_root = "/phpmanual/"
;docref_ext = .html

; String to output before an error message.
;error_prepend_string = "<font color=#ff0000>"

; String to output after an error message.
;error_append_string = "</font>"

; Log errors to specified file.
;error_log = filename

; Log errors to syslog (Event Log on NT, not valid in Windows 95).
;error_log = syslog
</code>```

Is there a the solution to the disappearing of warning and notices?

答:
why dont you just add
display_errors = off
on the php.ini? thad should do the job

Body:
I write this code in php.ini to disable warnings and notices, but it is not working for me. error_reporting = E_ALL & ~E_NOTICE & ~E_WARNING.

Below is my error handling code of php.ini.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; error_reporting is a bit-field.  Or each number up to get desired error
; reporting level
; E_ALL             - All errors and warnings (doesn't include E_STRICT)
; E_ERROR           - fatal run-time errors
; E_RECOVERABLE_ERROR  - almost fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it's automatically initialized to an
;                     empty string)
; E_STRICT          - run-time notices, enable to have PHP suggest changes
;                     to your code which will ensure the best interoperability
;                     and forward compatibility of your code
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
;
; Examples:
;
;   - Show all errors, except for notices and coding standards warnings
;
 error_reporting = E_ALL & ~E_NOTICE & ~E_WARNING
;
;   - Show all errors, except for notices
;
; error_reporting = E_ALL & ~E_NOTICE | E_STRICT
;
;   - Show only errors
;
; error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR
;
;   - Show all errors, except coding standards warnings
;

; Print out errors (as a part of the output).  For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below).  Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
;
; possible values for display_errors:
;
; Off          - Do not display any errors
; stderr       - Display errors to STDERR (affects only CGI/CLI binaries!)
; On or stdout - Display errors to STDOUT (default)
;
; To output errors to STDERR with CGI/CLI:
;display_errors = "stderr"
;
; Default
;
display_errors = On

; Even when display_errors is on, errors that occur during PHP's startup
; sequence are not displayed.  It's strongly recommended to keep
; display_startup_errors off, except for when debugging.
display_startup_errors = On

; Log errors into a log file (server-specific log, stderr, or error_log (below))
; As stated above, you're strongly advised to use error logging in place of
; error displaying on production web sites.
log_errors = On

; Set maximum length of log_errors. In error_log information about the source is
; added. The default is 1024 and 0 allows to not apply any maximum length at all.
log_errors_max_len = 1024

; Do not log repeated messages. Repeated errors must occur in same file on same
; line unless ignore_repeated_source is set true.
ignore_repeated_errors = Off

; Ignore source of message when ignoring repeated messages. When this setting
; is On you will not log errors with repeated messages from different files or
; source lines.
ignore_repeated_source = Off

; If this parameter is set to Off, then memory leaks will not be shown (on
; stdout or in the log). This has only effect in a debug compile, and if
; error reporting includes E_WARNING in the allowed list
report_memleaks = On

;report_zend_debug = 0

; Store the last error/warning message in $php_errormsg (boolean).
track_errors = Off

; Turn off normal error reporting and emit XML-RPC error XML
;xmlrpc_errors = 0
; An XML-RPC faultCode
;xmlrpc_error_number = 0

; Disable the inclusion of HTML tags in error messages.
; Note: Never use this feature for production boxes.
;html_errors = Off

; If html_errors is set On PHP produces clickable error messages that direct
; to a page describing the error or function causing the error in detail.
; You can download a copy of the PHP manual from http://www.php.net/docs.php
; and change docref_root to the base URL of your local copy including the
; leading '/'. You must also specify the file extension being used including
; the dot.
; Note: Never use this feature for production boxes.
;docref_root = "/phpmanual/"
;docref_ext = .html

; String to output before an error message.
;error_prepend_string = ""

; String to output after an error message.
;error_append_string = ""

; Log errors to specified file.
;error_log = filename

; Log errors to syslog (Event Log on NT, not valid in Windows 95).
;error_log = syslog

Is there a the solution to the disappearing of warning and notices?


问:
How to find fast the number of files in directory?
I have thousands log files in a few directories in my system. Mostly I need to know just number of these files in directory. I fear that this attitude:

```<code>$files = count(scandir("logs")) - 2;
</code>```

Is not very effective (memory, filesystem). I am considering some global counter (incremented after file is added), unless there is some other effective way?

答:
I am also considering this "unary counter" solution: After each file is added, run this command

```<code>file_put_contents("counter_myDir","1",FILE_APPEND);
</code>```

Then I would have some few kB more in each directory (there are just a few dirs, it is ok) and the reading seems to be very effective and portable, too:

```<code>$files = filesize("counter_myDir");
</code>```

Can you please compare this to other solutions suggested here? I really need to know the number of files as effectively as possible.

Body:
I have thousands log files in a few directories in my system. Mostly I need to know just number of these files in directory. I fear that this attitude:

$files = count(scandir("logs")) - 2;

Is not very effective (memory, filesystem). I am considering some global counter (incremented after file is added), unless there is some other effective way?

Body:
I am also considering this "unary counter" solution: After each file is added, run this command

file_put_contents("counter_myDir","1",FILE_APPEND);

Then I would have some few kB more in each directory (there are just a few dirs, it is ok) and the reading seems to be very effective and portable, too:

$files = filesize("counter_myDir");

Can you please compare this to other solutions suggested here? I really need to know the number of files as effectively as possible.


问:
Divide two Pandas Pivoted Tables and generate third table with result of division between the two tables
I have two dataframes df1 and df2, where

1) I have applied pivot table for df1, in which it contains sum of the ITEM VALUES IN THE TABLE.

Below is the python code

```<code>df_val = pd.pivot_table(df1, values = ['ITEM VALUE'], index=['B', 'C', 'D'], columns = ['Year','A'], aggfunc={'ITEM VALUE': sum})
</code>```

Pivot table of df_val

and

2) I have applied pivot table for df2 as well, in which it contains sum of the PART COUNT IN THE TABLE.

Below is the python code

```<code>df_cot = pd.pivot_table(df2, values = ['PART COUNT'], index=['B', 'C', 'D'], columns = ['Year','A'],aggfunc={'PART COUNT':sum})
</code>```

Pivot table of df_cot

What I would like to achieve is to make new column "CPI DATA" to DataFrame df3 which should have the result of the division of column "PART COUNT" from df_cot with "ITEM VALUE" column from df_val.

I have tried the code

```<code>df3['CPI DATA']= df_cot['PART COUNT'] / df_val['ITEM VALUE']
</code>```

and the output was generated as 'NAN' for the column "CPI DATA".

How to generate a third table with the result of division between two tables?
below is the required table which i want to generate..

Required OUTPUT table

答:
I'll leave it up to you to figure out what you need to do with the inconsistencies between the two tables - some keys are present in one and not the other - but I would recommend not calculating across multiple tables and merge them instead first.

If you only wanted to keep the entries that exist in both tables, you could do something like this:

import pandas as pd

df_combined = pd.merge(df_cot, df_val, how = "inner", on = ["A", "B", "C", "D", "YEAR"])

df_combined["CPI DATA"] = df_combined["PART COUNT"] / df_combined["ITEM VALUE"]
```

Changing the how parameter to left, right, or outer will do different things in terms of keeping rows without corresponding entries in the other table, equivalent to SQL JOIN.

To me, it's a strong best practice to not manipulate over separate tables before joining since Panda's strong indexing structure could do plenty of things you don't expect.

Body:
I have two dataframes df1 and df2, where

1) I have applied pivot table for df1, in which it contains sum of the ITEM VALUES IN THE TABLE.

Below is the python code

df_val = pd.pivot_table(df1, values = ['ITEM VALUE'], index=['B', 'C', 'D'], columns = ['Year','A'], aggfunc={'ITEM VALUE': sum})

Pivot table of df_val

and

2) I have applied pivot table for df2 as well, in which it contains sum of the PART COUNT IN THE TABLE.

Below is the python code

df_cot = pd.pivot_table(df2, values = ['PART COUNT'], index=['B', 'C', 'D'], columns = ['Year','A'],aggfunc={'PART COUNT':sum})

Pivot table of df_cot

What I would like to achieve is to make new column "CPI DATA" to DataFrame df3 which should have the result of the division of column "PART COUNT" from df_cot with "ITEM VALUE" column from df_val.

I have tried the code

df3['CPI DATA']= df_cot['PART COUNT'] / df_val['ITEM VALUE']

and the output was generated as 'NAN' for the column "CPI DATA".

How to generate a third table with the result of division between two tables?
below is the required table which i want to generate..

Required OUTPUT table

Body:
I'll leave it up to you to figure out what you need to do with the inconsistencies between the two tables - some keys are present in one and not the other - but I would recommend not calculating across multiple tables and merge them instead first.

If you only wanted to keep the entries that exist in both tables, you could do something like this:

import pandas as pd

df_combined = pd.merge(df_cot, df_val, how = "inner", on = ["A", "B", "C", "D", "YEAR"])

df_combined["CPI DATA"] = df_combined["PART COUNT"] / df_combined["ITEM VALUE"]

Changing the how parameter to left, right, or outer will do different things in terms of keeping rows without corresponding entries in the other table, equivalent to SQL JOIN.

To me, it's a strong best practice to not manipulate over separate tables before joining since Panda's strong indexing structure could do plenty of things you don't expect.