问:
How to make a loop in a loop (Python)?
I would like to execute a loop in a loop, but when I try to do that I catch a wrong calculation comparing to a singular loop.

My code with a singular loop that works:

```<code>betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(numofbets):
    #random list: 1 - win, 0 - loss
    test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
    betresult.append(test)

    #number of win and loss
    winbets = np.sum(betresult)
    lossbets = numofbets - winbets

    #sum of win and loss
    winsum = winbets * win
    losssum = lossbets * loss

    #final sum
    result = budget - (winsum + losssum)

print(result)
</code>```

And I would like to put that code in a new loop, but if I make something obviously with while or for, I catch a wrong calculation.

With a singular loop I usually get one number between 1100 and 1800.

Code with a wrong calculation:

```<code>betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(10):
    for j in range(numofbets):
        #random list: 1 - win, 0 - loss
        test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
        betresult.append(test)

        #number of win and loss
        winbets = np.sum(betresult)
        lossbets = numofbets - winbets

        #sum of win and loss
        winsum = winbets * win
        losssum = lossbets * loss

        #final sum
        result = budget - (winsum + losssum)

     print(result)
</code>```

With a double loop I usually get a number under 0. And the bigger a loop range, the bigger a number under 0.

An example of wrong execution (calculation):

```<code>1470.0
7.5
-1590.0
-3007.5
-4447.5
-5910.0
-7440.0
-8835.0
-10410.0
-11985.0
</code>```

答:
The problem is the betresult is appending all the value for 10 iterations that's why you get negative answers</p>

```<code>import numpy as np

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(10):
    #declaring inside the first loop
    betresult = []
    for j in range(numofbets):
        #random list: 1 - win, 0 - loss
        test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
        betresult.append(test)

        #number of win and loss
        winbets = np.sum(betresult)
        lossbets = numofbets - winbets

        #sum of win and loss
        winsum = winbets * win
        losssum = lossbets * loss

        #final sum
        result = budget - (winsum + losssum)
    print(result)
</code>```

Title: How to make a loop in a loop (Python)?

Body:
I would like to execute a loop in a loop, but when I try to do that I catch a wrong calculation comparing to a singular loop.

My code with a singular loop that works:

betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(numofbets):
    #random list: 1 - win, 0 - loss
    test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
    betresult.append(test)

    #number of win and loss
    winbets = np.sum(betresult)
    lossbets = numofbets - winbets

    #sum of win and loss
    winsum = winbets * win
    losssum = lossbets * loss

    #final sum
    result = budget - (winsum + losssum)

print(result)

And I would like to put that code in a new loop, but if I make something obviously with while or for, I catch a wrong calculation.

With a singular loop I usually get one number between 1100 and 1800.

Code with a wrong calculation:

betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(10):
    for j in range(numofbets):
        #random list: 1 - win, 0 - loss
        test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
        betresult.append(test)

        #number of win and loss
        winbets = np.sum(betresult)
        lossbets = numofbets - winbets

        #sum of win and loss
        winsum = winbets * win
        losssum = lossbets * loss

        #final sum
        result = budget - (winsum + losssum)

     print(result)

With a double loop I usually get a number under 0. And the bigger a loop range, the bigger a number under 0.

An example of wrong execution (calculation):

1470.0
7.5
-1590.0
-3007.5
-4447.5
-5910.0
-7440.0
-8835.0
-10410.0
-11985.0

Body:
The problem is the betresult is appending all the value for 10 iterations that's why you get negative answers

import numpy as np

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(10):
    #declaring inside the first loop
    betresult = []
    for j in range(numofbets):
        #random list: 1 - win, 0 - loss
        test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
        betresult.append(test)

        #number of win and loss
        winbets = np.sum(betresult)
        lossbets = numofbets - winbets

        #sum of win and loss
        winsum = winbets * win
        losssum = lossbets * loss

        #final sum
        result = budget - (winsum + losssum)
    print(result)


来源: stackexchange

问:
Firestore recycler adapter - disappearing items after scrolling
I'm trying to create chatting service for my project, in order to do that I store my messages in a Firestore database that I fetch from the server and assign the text comparing the sender id to current user id.
When I start the activity, the messages show properly, but when I scroll down, either my messages stop showing up, or other user's messages disappear, depending whether on which account the chat is opened.

I can't seem to figure out why that happens.

My readMessages function:

```<code>private void readMessages(){
    Query query = DataRef.collection("rooms").document(roomID).collection("messages").orderBy("timestamp", Query.Direction.ASCENDING);
    FirestoreRecyclerOptions<MessageModel> options = new FirestoreRecyclerOptions.Builder<MessageModel>().setQuery(query, MessageModel.class).build();
    adapter = new FirestoreRecyclerAdapter<MessageModel, MessageAdapter.ViewHolder>(options) {
        @Override
        protected void onBindViewHolder(MessageAdapter.ViewHolder holder, int position, MessageModel model) {
            if (myUid.equals(model.getUid())) {
                Log.d(TAG, "status1");
                holder.msg_right.setText(String.valueOf(model.getMsg()));
                holder.msg_left.setVisibility(View.INVISIBLE);
                holder.profile_image.setVisibility(View.INVISIBLE);
                holder.msg_nick.setVisibility(View.INVISIBLE);
            }
            else
            {
                DataRef.collection("users").document(String.valueOf(model.getUid())).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        DocumentSnapshot document = task.getResult();
                        msgNick = document.getString("usernm");
                    }
                });
                holder.msg_nick.setText(msgNick);
                holder.msg_left.setText(String.valueOf(model.getMsg()));
                holder.msg_right.setVisibility(View.INVISIBLE);
                Log.d(TAG, "status0" );
        }
        }
        @NonNull
        @Override
        public MessageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType){
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message,parent,false);
            return new MessageAdapter.ViewHolder(v);
        }
    };
    adapter.startListening();
    recyclerView.setAdapter(adapter);
}
</code>```

My message adapter class:

```<code>public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView msg_right;
        public ImageView profile_image;
        public TextView msg_left;
        public TextView msg_nick;

        public ViewHolder(View itemView) {
            super(itemView);

            msg_right = itemView.findViewById(R.id.msg_right);
            profile_image = itemView.findViewById(R.id.msg_leftavatar);
            msg_left = itemView.findViewById(R.id.msg_left);
            msg_nick = itemView.findViewById(R.id.msg_nick);
        }
    }
}
</code>```

State of the chat before scrolling down and up:

"

And after doing so:

答:
Please try to move the blow block of code of setting the holder members within the callback listener in else statement.

```<code>private void readMessages(){
    Query query = DataRef.collection("rooms").document(roomID).collection("messages").orderBy("timestamp", Query.Direction.ASCENDING);
    FirestoreRecyclerOptions<MessageModel> options = new FirestoreRecyclerOptions.Builder<MessageModel>().setQuery(query, MessageModel.class).build();
    adapter = new FirestoreRecyclerAdapter<MessageModel, MessageAdapter.ViewHolder>(options) {
        @Override
        protected void onBindViewHolder(MessageAdapter.ViewHolder holder, int position, MessageModel model) {
            if (myUid.equals(model.getUid())) {
                Log.d(TAG, "status1");
                holder.msg_right.setText(String.valueOf(model.getMsg()));
                holder.msg_left.setVisibility(View.INVISIBLE);
                holder.profile_image.setVisibility(View.INVISIBLE);
                holder.msg_nick.setVisibility(View.INVISIBLE);
            }
            else
            {
                DataRef.collection("users").document(String.valueOf(model.getUid())).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        DocumentSnapshot document = task.getResult();
                        msgNick = document.getString("usernm");
                        holder.msg_nick.setText(msgNick);
                        holder.msg_left.setText(String.valueOf(model.getMsg()));
                        holder.msg_right.setVisibility(View.INVISIBLE);
                        Log.d(TAG, "status0" );                    }
                });

        }
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create chatting service for my project, in order to do that I store my messages in a Firestore database that I fetch from the server and assign the text comparing the sender id to current user id.
When I start the activity, the messages show properly, but when I scroll down, either my messages stop showing up, or other user's messages disappear, depending whether on which account the chat is opened.

I can't seem to figure out why that happens.

My readMessages function:

private void readMessages(){
    Query query = DataRef.collection("rooms").document(roomID).collection("messages").orderBy("timestamp", Query.Direction.ASCENDING);
    FirestoreRecyclerOptions<MessageModel> options = new FirestoreRecyclerOptions.Builder<MessageModel>().setQuery(query, MessageModel.class).build();
    adapter = new FirestoreRecyclerAdapter<MessageModel, MessageAdapter.ViewHolder>(options) {
        @Override
        protected void onBindViewHolder(MessageAdapter.ViewHolder holder, int position, MessageModel model) {
            if (myUid.equals(model.getUid())) {
                Log.d(TAG, "status1");
                holder.msg_right.setText(String.valueOf(model.getMsg()));
                holder.msg_left.setVisibility(View.INVISIBLE);
                holder.profile_image.setVisibility(View.INVISIBLE);
                holder.msg_nick.setVisibility(View.INVISIBLE);
            }
            else
            {
                DataRef.collection("users").document(String.valueOf(model.getUid())).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        DocumentSnapshot document = task.getResult();
                        msgNick = document.getString("usernm");
                    }
                });
                holder.msg_nick.setText(msgNick);
                holder.msg_left.setText(String.valueOf(model.getMsg()));
                holder.msg_right.setVisibility(View.INVISIBLE);
                Log.d(TAG, "status0" );
        }
        }
        @NonNull
        @Override
        public MessageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType){
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message,parent,false);
            return new MessageAdapter.ViewHolder(v);
        }
    };
    adapter.startListening();
    recyclerView.setAdapter(adapter);
}

My message adapter class:

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView msg_right;
        public ImageView profile_image;
        public TextView msg_left;
        public TextView msg_nick;

        public ViewHolder(View itemView) {
            super(itemView);

            msg_right = itemView.findViewById(R.id.msg_right);
            profile_image = itemView.findViewById(R.id.msg_leftavatar);
            msg_left = itemView.findViewById(R.id.msg_left);
            msg_nick = itemView.findViewById(R.id.msg_nick);
        }
    }
}

State of the chat before scrolling down and up:

"

And after doing so:

Body:
Please try to move the blow block of code of setting the holder members within the callback listener in else statement.

private void readMessages(){
    Query query = DataRef.collection("rooms").document(roomID).collection("messages").orderBy("timestamp", Query.Direction.ASCENDING);
    FirestoreRecyclerOptions<MessageModel> options = new FirestoreRecyclerOptions.Builder<MessageModel>().setQuery(query, MessageModel.class).build();
    adapter = new FirestoreRecyclerAdapter<MessageModel, MessageAdapter.ViewHolder>(options) {
        @Override
        protected void onBindViewHolder(MessageAdapter.ViewHolder holder, int position, MessageModel model) {
            if (myUid.equals(model.getUid())) {
                Log.d(TAG, "status1");
                holder.msg_right.setText(String.valueOf(model.getMsg()));
                holder.msg_left.setVisibility(View.INVISIBLE);
                holder.profile_image.setVisibility(View.INVISIBLE);
                holder.msg_nick.setVisibility(View.INVISIBLE);
            }
            else
            {
                DataRef.collection("users").document(String.valueOf(model.getUid())).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        DocumentSnapshot document = task.getResult();
                        msgNick = document.getString("usernm");
                        holder.msg_nick.setText(msgNick);
                        holder.msg_left.setText(String.valueOf(model.getMsg()));
                        holder.msg_right.setVisibility(View.INVISIBLE);
                        Log.d(TAG, "status0" );                    }
                });

        }
        }


问:
Add values to an identity(1,1) column in SQL Server
I have two tables:

```<code>CREATE TABLE project.teacher
(
    PROFESSOR_Codigo SMALLINT IDENTITY( 100, 1),
    birth            DATE NOT NULL,
    phone            VARCHAR(15)
);

CREATE TABLE project.student
(
    STUDENT_Codigo IDENTITY( 1, 1),
    birth          DATE NOT NULL,
    phone          VARCHAR(15)
);
</code>```

When I add a student to the student table it will increment 1 from the number 1, and stay (1, 2, 3, 4, 5, 6, ...)

In the teacher table I already have data entered, and start with a value of 100 in the identity column, but when I add 1, it gets identity 1, not 101

I've tried everything, scope_identity(), @@identity, but I couldn't! Does anyone have any ideas?

What I do to insert a row into the teacher table:

```<code>INSERT INTO project.student
VALUES ('1998-05-08', '963597461');

INSERT INTO project.teacher
VALUES ('1994-05-09', '968413692');
</code>```

答:
try

```<code>dbcc checkident(teacher, noreseed)
</code>```

this will return the current identity value of the ident column. your create statement is fine so maybe something went wrong on the on create?

Body:
I have two tables:

CREATE TABLE project.teacher
(
    PROFESSOR_Codigo SMALLINT IDENTITY( 100, 1),
    birth            DATE NOT NULL,
    phone            VARCHAR(15)
);

CREATE TABLE project.student
(
    STUDENT_Codigo IDENTITY( 1, 1),
    birth          DATE NOT NULL,
    phone          VARCHAR(15)
);

When I add a student to the student table it will increment 1 from the number 1, and stay (1, 2, 3, 4, 5, 6, ...)

In the teacher table I already have data entered, and start with a value of 100 in the identity column, but when I add 1, it gets identity 1, not 101

I've tried everything, scope_identity(), @@identity, but I couldn't! Does anyone have any ideas?

What I do to insert a row into the teacher table:

INSERT INTO project.student
VALUES ('1998-05-08', '963597461');

INSERT INTO project.teacher
VALUES ('1994-05-09', '968413692');

Body:
try

dbcc checkident(teacher, noreseed)

this will return the current identity value of the ident column. your create statement is fine so maybe something went wrong on the on create?


问:
Number Format Patterns for Currency
i'd made this currency pattern to prefix a sign (+ or -) based on the value

static final String _currencyWithPrefixSignAndSymbol = "+ \u00A4 0.00 ;- \u00A4 0.00";
```

the pattern put a + prefix if the value is positive and a - if negative;

Problem: i need to remove these signs when the value is 0, is there a way to do this in the pattern ? without doing something like a string.Replace at the final?

答:
As an option.

Since Dart 2.7 you can create extensions.
So you can create num extension like this:

```<code>extension MyCurrencyFormat on num {
  static final _currencyWithPrefixSignAndSymbol = NumberFormat("+ \u00A4 0.00;- \u00A4 0.00");
  static final _currencyZero = NumberFormat("  \u00A4 0.00");

  String toCurrencyFormat() {
    return this == 0 ? _currencyZero.format(this) : _currencyWithPrefixSignAndSymbol.format(this);
  }
}
</code>```

and then use it in code in that way:

```<code>var str1 = 42.toCurrencyFormat(); //  + USD 42.00
var str2 = 0.toCurrencyFormat();  //  USD 0.00
</code>```

Title: Number Format Patterns for Currency

Body:
i'd made this currency pattern to prefix a sign (+ or -) based on the value

static final String _currencyWithPrefixSignAndSymbol = "+ \u00A4 0.00 ;- \u00A4 0.00";

the pattern put a + prefix if the value is positive and a - if negative;

Problem: i need to remove these signs when the value is 0, is there a way to do this in the pattern ? without doing something like a string.Replace at the final?

Body:
As an option.

Since Dart 2.7 you can create extensions.
So you can create num extension like this:

extension MyCurrencyFormat on num {
  static final _currencyWithPrefixSignAndSymbol = NumberFormat("+ \u00A4 0.00;- \u00A4 0.00");
  static final _currencyZero = NumberFormat("  \u00A4 0.00");

  String toCurrencyFormat() {
    return this == 0 ? _currencyZero.format(this) : _currencyWithPrefixSignAndSymbol.format(this);
  }
}

and then use it in code in that way:

var str1 = 42.toCurrencyFormat(); //  + USD 42.00
var str2 = 0.toCurrencyFormat();  //  USD 0.00


问:
Django: How to get related data from different db tables and display it as one
I have this two models which creates my tables, now my question is, how can I get only home_team and away_team fields on Events table then get odd from Bets table and display it in one match</p>

```<code>

class Event(models.Model):
    sport_id = models.ManyToManyField(Sport)
    league_id = models.ManyToManyField(League)
    home_team = models.CharField(max_length=255)
    away_team = models.CharField(max_length=255)
    match_date = models.DateField()
    match_time = models.TimeField()
    featured = models.IntegerField()

class Bet(models.Model):
    league_id = models.ManyToManyField(League)
    match_id = models.ForeignKey(
        'Event',
        on_delete=models.CASCADE,
    )
    bet_id = models.IntegerField()
    bet_name = models.CharField(max_length=255)
    choice_id = models.IntegerField()
    choice_name = models.CharField(max_length=255)
    odd = models.FloatField()
    match_date = models.DateField()

</code>```

答:
```<code>bet = Bet.objects.get(id=ID)
home_team = bet.match_id.home_team
away_team = bet.match_id.away_team
odd = bet.odd
</code>```

ID is the bet id you are trying to access

For more reference you may visit django 3 official documentation for many-to-one relationship

Body:
I have this two models which creates my tables, now my question is, how can I get only home_team and away_team fields on Events table then get odd from Bets table and display it in one match

class Event(models.Model):
    sport_id = models.ManyToManyField(Sport)
    league_id = models.ManyToManyField(League)
    home_team = models.CharField(max_length=255)
    away_team = models.CharField(max_length=255)
    match_date = models.DateField()
    match_time = models.TimeField()
    featured = models.IntegerField()

class Bet(models.Model):
    league_id = models.ManyToManyField(League)
    match_id = models.ForeignKey(
        'Event',
        on_delete=models.CASCADE,
    )
    bet_id = models.IntegerField()
    bet_name = models.CharField(max_length=255)
    choice_id = models.IntegerField()
    choice_name = models.CharField(max_length=255)
    odd = models.FloatField()
    match_date = models.DateField()

Body:
bet = Bet.objects.get(id=ID)
home_team = bet.match_id.home_team
away_team = bet.match_id.away_team
odd = bet.odd

ID is the bet id you are trying to access

For more reference you may visit django 3 official documentation for many-to-one relationship


问:
Read multiple CSVs & merge those CSVs into separate files based on year in filename python
Suppose I have the following data sets that I successfully read into my notebook:

```<code>data1-format1-1991-1992.csv
data2-format1-1993-1994.csv
data3-format1-1995-1996.csv

data4-format2-1991-1992.csv
data5-format2-1993-1994.csv
data6-format2-1995-1996.csv
</code>```

I can easily read these sets in, from their own directories like so:

```<code>files1 = [filename for filename in os.listdir(master_dir_1) if filename.startswith("data-")] # would do same for second set of files, in master_dir_2

for filename in files1:
    df = pd.read_csv(filename)
    print(df)
</code>```

This prints them out in one frame - but I need to read them in, and then pd.merge() each separate file based on the year in the file name. E.g., data1-format1-1991-1992.csv gets joined with data1-format2-1991-1992.csv, and so on.

The process would be to read in both sets from their own directories with the loop above, and then have another loop that combines and saves based on the matching years in the file names (I think). How do I split based on the years, and save each joined file separately, with the years in the saved csv name? I've got the process for reading in single data sets and joining/saving, but not for multiple read ins, joins, and saves.

This question gets me some of the way there, because of how .format() is utilized.

答:
You can try a for loop with a .groupby

```<code>for year, x in df.groupby(['Year']):
    x.to_csv(f'data1-format1-{year}.csv', index=False)
</code>```

Body:
Suppose I have the following data sets that I successfully read into my notebook:

data1-format1-1991-1992.csv
data2-format1-1993-1994.csv
data3-format1-1995-1996.csv

data4-format2-1991-1992.csv
data5-format2-1993-1994.csv
data6-format2-1995-1996.csv

I can easily read these sets in, from their own directories like so:

files1 = [filename for filename in os.listdir(master_dir_1) if filename.startswith("data-")] # would do same for second set of files, in master_dir_2

for filename in files1:
    df = pd.read_csv(filename)
    print(df)

This prints them out in one frame - but I need to read them in, and then pd.merge() each separate file based on the year in the file name. E.g., data1-format1-1991-1992.csv gets joined with data1-format2-1991-1992.csv, and so on.

The process would be to read in both sets from their own directories with the loop above, and then have another loop that combines and saves based on the matching years in the file names (I think). How do I split based on the years, and save each joined file separately, with the years in the saved csv name? I've got the process for reading in single data sets and joining/saving, but not for multiple read ins, joins, and saves.

This question gets me some of the way there, because of how .format() is utilized.

Body:
You can try a for loop with a .groupby

for year, x in df.groupby(['Year']):
    x.to_csv(f'data1-format1-{year}.csv', index=False)


问:
copying c++ abstract classes
Ok heres some code.

```<code>#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
};
void Main()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(new A(*aclasses[0]));
    aclasses2.push_back(new A(*aclasses[1]));
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.

}
</code>```

Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.

Now the current modified version

```<code>#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
    virtual ~A() {}             // don't forget the virtual destructor
    virtual A* clone() const {
       return new A(*this);
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
    virtual B* clone() {     // return type is co-variant
       return new B( *this );
    }
};
void MainRUNNER()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(aclasses[0]->clone());
    aclasses2.push_back(aclasses[1]->clone());
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.
}
</code>```

答:
You need to provide a virtual copy constructor – usually this is a method called clone – which is overridden in each class to return the correct type:

```<code>class A {
    virtual A* clone() {
        return new A();
    }
};

class B : public A {
    void A* clone() {
        return new B();
    }
};
</code>```

The methods can of course be arbitrarily complex in order to copy the whole state.

Of course, this leaks rather a lot of memory. Use appropriate smart pointers instead of raw pointers (e.g. std::shared_ptr if your compiler supports it, boost::shared_ptr otherwise).

ContentLicense: CC BY-SA 3.0

Title: copying c++ abstract classes

Body:
Ok heres some code.

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
};
void Main()
{
    deque aclasses = deque(0);
    deque aclasses2 = deque(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(new A(*aclasses[0]));
    aclasses2.push_back(new A(*aclasses[1]));
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.

}

Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.

Now the current modified version

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
    virtual ~A() {}             // don't forget the virtual destructor
    virtual A* clone() const {
       return new A(*this);
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
    virtual B* clone() {     // return type is co-variant
       return new B( *this );
    }
};
void MainRUNNER()
{
    deque aclasses = deque(0);
    deque aclasses2 = deque(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(aclasses[0]->clone());
    aclasses2.push_back(aclasses[1]->clone());
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.
}

Body:
You need to provide a virtual copy constructor – usually this is a method called clone – which is overridden in each class to return the correct type:

class A {
    virtual A* clone() {
        return new A();
    }
};

class B : public A {
    void A* clone() {
        return new B();
    }
};

The methods can of course be arbitrarily complex in order to copy the whole state.

Of course, this leaks rather a lot of memory. Use appropriate smart pointers instead of raw pointers (e.g. std::shared_ptr if your compiler supports it, boost::shared_ptr otherwise).


问:
c++ Why shouldn't I unlock a mutex from a different thread
Why shouldn't I unlock a mutex from a different thread? In the c++ standard it says it pretty clearly: If the mutex is not currently locked by the calling thread, it causes undefined behavior. But as far as I can see, everything works as expected on Linux(Fedora 31 with GCC). I seriously tried everything but I could not get it to behave strangely.
All I'm asking for is an example where something, literally anything is affected by unlocking a mutex from a different thread.

Here is a quick test I wrote which is super wrong and shoudn't work but it does:

```<code>std::mutex* testEvent;

int main()
{
    testEvent = new std::mutex[1000];

    for(uint32_t i = 0; i < 1000; ++i) testEvent[i].lock();

    std::thread threads[2000];

    auto lock = [](uint32_t index) ->void { testEvent[index].lock(); assert(!testEvent[index].try_lock()); };
    auto unlock = [](uint32_t index) ->void { testEvent[index].unlock(); };

    for(uint32_t j = 0; j < 1000; ++j)
    {
        for(uint32_t i = 0; i < 1000; ++i)
        {
            threads[i]      = std::thread(lock,i);
            threads[i+1000] = std::thread(unlock,i);
        }
        for(uint32_t i = 0; i < 2000; ++i)
        {
            threads[i].join();
        }
        std::cout << j << std::endl;
    }

    delete[] testEvent;
}
</code>```

答:
As you already said, it is UB. UB means it may work. Or not. Or randomly switch between working and making your computer sing itself a lullaby. (See also "nasal demons".)

Here are just a few ways someone can break your program on Fedora 31 with GCC on x86-64:

Compile with -fsanitize=thread. It will now crash every time, which is still a valid C++ implementation, because UB.

Run unter helgrind (valgrind --tool=helgrind ./a.out). It will crash every time -- still a valid way to host a C++ program, because UB.

The libstdc++/glibc/pthread implementation on the target system switches from using "fast" mutexes by default to "error checking" or "recursive" mutexes (https://manpages.debian.org/jessie/glibc-doc/pthread_mutex_init.3.en.html). Note that this is probably possible in a manner that is ABI-compatible with your program, meaning that it does not even have to be recompiled for it to suddenly stop working.

That being said, since you are using a platform on which the C++ mutex boils down to a futex-implemented "fast" pthread mutex, this does not work by accident. It is just not guaranteed to keep working for any time, or in any circumstance that actually checks if you are doing the right thing.

Body:
Why shouldn't I unlock a mutex from a different thread? In the c++ standard it says it pretty clearly: If the mutex is not currently locked by the calling thread, it causes undefined behavior. But as far as I can see, everything works as expected on Linux(Fedora 31 with GCC). I seriously tried everything but I could not get it to behave strangely.
All I'm asking for is an example where something, literally anything is affected by unlocking a mutex from a different thread.

Here is a quick test I wrote which is super wrong and shoudn't work but it does:

std::mutex* testEvent;

int main()
{
    testEvent = new std::mutex[1000];

    for(uint32_t i = 0; i < 1000; ++i) testEvent[i].lock();

    std::thread threads[2000];

    auto lock = [](uint32_t index) ->void { testEvent[index].lock(); assert(!testEvent[index].try_lock()); };
    auto unlock = [](uint32_t index) ->void { testEvent[index].unlock(); };

    for(uint32_t j = 0; j < 1000; ++j)
    {
        for(uint32_t i = 0; i < 1000; ++i)
        {
            threads[i]      = std::thread(lock,i);
            threads[i+1000] = std::thread(unlock,i);
        }
        for(uint32_t i = 0; i < 2000; ++i)
        {
            threads[i].join();
        }
        std::cout << j << std::endl;
    }

    delete[] testEvent;
}


问:
How to simulate onFailureListener & resultCode != Activity.RESULT_OK In App Updates?
How can I test this onFailureListener & resultCode != Activity.RESULT_OK?

When I open the app, I create a force Update State depending on my versionName of both apps shared on Google Play Internal Sharing.

At first, it will show me a custom dialog. On Negative Btn -> The app close

On Positive Btn -> The checkForUpdate() fun will start.

I use AppUpdateType.IMMEDIATE. So it will show me only the Google Play dialog for UPDATE.

I just made a build for inAppUpdates and I'm trying to handle onFailureListener.
Without putting just a printstacktrace, I want to Open Google Play, and let user to install the app from there.

```<code>fun checkForAppUpdate() {
        val appUpdateManager = AppUpdateManagerFactory.create(this)
        val appUpdatedListener: InstallStateUpdatedListener by lazy {
            object : InstallStateUpdatedListener {
                override fun onStateUpdate(installState: InstallState) {
                    if(installState.installStatus() == InstallStatus.INSTALLED) {
                        appUpdateManager.unregisterListener(this)
                    }
                    else {Log.d("inAPPtag","InstallStateUpdatedListener: state: %s" + installState.installStatus())
                    }
                }
            }
        }
        // Returns an intent object that you use to check for an update.
        val appUpdateInfoTask = appUpdateManager.appUpdateInfo
        // Checks that the platform will allow the specified type of update.
        appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE || appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {

                appUpdateManager.registerListener(appUpdatedListener)
                // Request the update.
                try {
                    appUpdateManager.startUpdateFlowForResult(
                        appUpdateInfo,
                        AppUpdateType.IMMEDIATE,
                        this,
                         APP_UPDATE_REQUEST_CODE
                    )
                } catch (e: IntentSender.SendIntentException) {
                    e.printStackTrace()
                }
            }
        }
        appUpdateInfoTask.addOnFailureListener {
            it.printStackTrace()
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(Constants.STORE_URL))
            if (intent.resolveActivity(this.packageManager) != null) {
                splashTrace.putAttribute("SPLASH", "appUpdate")
                startActivity(intent)
                finish()
            }
        }
    }
</code>```

Also, if resultCode != Activity.RESULT_OK. The same thing, to let the user install the app from Google Play.

```<code>if (requestCode == APP_UPDATE_REQUEST_CODE) {
           if (resultCode != Activity.RESULT_OK) {
               val intent = Intent(Intent.ACTION_VIEW, Uri.parse(Constants.STORE_URL))
               if (intent.resolveActivity(this.packageManager) != null) {
                   splashTrace.putAttribute("SPLASH", "appUpdate")
                   startActivity(intent)
                   finish()
                }
            }
        }
</code>```

答:
You have two places where your trying to catch an error in your app.

The first one is a SendIntentException, as per documentation here it says that:

Exception thrown when trying to send through a PendingIntent that has been canceled or is otherwise no longer able to execute the request.

I guess this would happen if you trigger the startUpdateFlowForResult from another part of your code then the first one will get canceled and trigger this exception.

The second error is on the appUpdateInfoTask.addOnFailureListener {. I believe this one will get triggered if the phone doesn't have the Google Play Store or if the device has no internet connection.

Regarding your second question, you can check here. For an onActivityResult you have three options:

RESULT_OK: the update was a success

RESULT_CANCELED: user hit the back button

RESULT_FIRST_USER: a user defined flow

Body:
How can I test this onFailureListener & resultCode != Activity.RESULT_OK?

When I open the app, I create a force Update State depending on my versionName of both apps shared on Google Play Internal Sharing.

At first, it will show me a custom dialog. On Negative Btn -> The app close

On Positive Btn -> The checkForUpdate() fun will start.

I use AppUpdateType.IMMEDIATE. So it will show me only the Google Play dialog for UPDATE.

I just made a build for inAppUpdates and I'm trying to handle onFailureListener.
Without putting just a printstacktrace, I want to Open Google Play, and let user to install the app from there.

fun checkForAppUpdate() {
        val appUpdateManager = AppUpdateManagerFactory.create(this)
        val appUpdatedListener: InstallStateUpdatedListener by lazy {
            object : InstallStateUpdatedListener {
                override fun onStateUpdate(installState: InstallState) {
                    if(installState.installStatus() == InstallStatus.INSTALLED) {
                        appUpdateManager.unregisterListener(this)
                    }
                    else {Log.d("inAPPtag","InstallStateUpdatedListener: state: %s" + installState.installStatus())
                    }
                }
            }
        }
        // Returns an intent object that you use to check for an update.
        val appUpdateInfoTask = appUpdateManager.appUpdateInfo
        // Checks that the platform will allow the specified type of update.
        appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE || appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {

                appUpdateManager.registerListener(appUpdatedListener)
                // Request the update.
                try {
                    appUpdateManager.startUpdateFlowForResult(
                        appUpdateInfo,
                        AppUpdateType.IMMEDIATE,
                        this,
                         APP_UPDATE_REQUEST_CODE
                    )
                } catch (e: IntentSender.SendIntentException) {
                    e.printStackTrace()
                }
            }
        }
        appUpdateInfoTask.addOnFailureListener {
            it.printStackTrace()
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(Constants.STORE_URL))
            if (intent.resolveActivity(this.packageManager) != null) {
                splashTrace.putAttribute("SPLASH", "appUpdate")
                startActivity(intent)
                finish()
            }
        }
    }

Also, if resultCode != Activity.RESULT_OK. The same thing, to let the user install the app from Google Play.

if (requestCode == APP_UPDATE_REQUEST_CODE) {
           if (resultCode != Activity.RESULT_OK) {
               val intent = Intent(Intent.ACTION_VIEW, Uri.parse(Constants.STORE_URL))
               if (intent.resolveActivity(this.packageManager) != null) {
                   splashTrace.putAttribute("SPLASH", "appUpdate")
                   startActivity(intent)
                   finish()
                }
            }
        }


问:
Java Generics : no suitable constructor found for ArrayList(List<CAP#1>)
So the questions needs me to design a method d to take in a list and a class and return it's contents back.

```<code>Write a class D that passes the following test.
jshell> class E { public String toString() { return "E"; }}
jshell> class F extends E { public String toString() { return "F"; }}
jshell> List<E> p = D.add(new ArrayList<E>(), new E())
jshell> List<F> q = D.add(new LinkedList<F>(), new F())
jshell> List<E> r = D.add(D.add(new LinkedList<E>(), new E()), new F())
jshell> List<F> s = D.add(D.add(new ArrayList<F>(), new F()), new F())
jshell> /var
| List<E> p = [E]
| List<F> q = [F]
| List<E> r = [E, F]
| List<F> s = [F, F]
jshell> List<E> x = D.join(p, q) // join q to the end of p
jshell> List<E> y = D.join(p, p)
jshell> List<F> z = D.join(q, q)
jshell> /var
| List<E> p = [E]
| List<F> q = [F]
| List<E> r = [E, F]
| List<F> s = [F, F]
| List<E> x = [E, F]
| List<E> y = [E]
| List<F> z = [F]
</code>```

My current code looks like this

```<code>import java.util.List;
import java.util.ArrayList;

class D {

    public static <T> List <T> add(List<? super T> s,T t) {
        s.add(t);
        return new ArrayList<T>(s);
    }
}
</code>```

I keep gettinng this error : no suitable constructor found for ArrayList(List)

I'm supposed to input the toString value of this into the ArrayList however
s.add(t.toString());
also gives an error

答:
A List<? super T> isn't a supertype of a List<T>. Even this return new ArrayList<T>(s); won't work, since s isn't the same type as that new ArrayList being created. You also can't take a bunch of objects that are instances of a supertype of T and return a collection that's T. Imagine if s were List<Object> and t were a String. Your method would be required to return a List<String>, which is impossible unless you somehow know that all the objects in s are secretly strings.

Also, why are you adding t to s and then returning a new ArrayList that's just s? You're modifying s by doing that.

What you should probably do is

```<code>public static <T> List <T> add(List<T> s, T t) {
    List<T> res = new ArrayList<>(s);
    res.add(t);
    return res;
}
</code>```

You could also do this if t's type could be less specific than the elements in s.

```<code>public static <T> List <T> add(List<? extends T> s, T t) {
    List<T> res = new ArrayList<>(s);
    res.add(t);
    return res;
}
</code>```

Body:
So the questions needs me to design a method d to take in a list and a class and return it's contents back.

Write a class D that passes the following test.
jshell> class E { public String toString() { return "E"; }}
jshell> class F extends E { public String toString() { return "F"; }}
jshell> List<E> p = D.add(new ArrayList<E>(), new E())
jshell> List<F> q = D.add(new LinkedList<F>(), new F())
jshell> List<E> r = D.add(D.add(new LinkedList<E>(), new E()), new F())
jshell> List<F> s = D.add(D.add(new ArrayList<F>(), new F()), new F())
jshell> /var
| List<E> p = [E]
| List<F> q = [F]
| List<E> r = [E, F]
| List<F> s = [F, F]
jshell> List<E> x = D.join(p, q) // join q to the end of p
jshell> List<E> y = D.join(p, p)
jshell> List<F> z = D.join(q, q)
jshell> /var
| List<E> p = [E]
| List<F> q = [F]
| List<E> r = [E, F]
| List<F> s = [F, F]
| List<E> x = [E, F]
| List<E> y = [E]
| List<F> z = [F]

My current code looks like this

import java.util.List;
import java.util.ArrayList;

class D {

    public static <T> List <T> add(List<? super T> s,T t) {
        s.add(t);
        return new ArrayList<T>(s);
    }
}

I keep gettinng this error : no suitable constructor found for ArrayList(List)

I'm supposed to input the toString value of this into the ArrayList however
s.add(t.toString());
also gives an error

Body:
A List<? super T> isn't a supertype of a List<T>. Even this return new ArrayList<T>(s); won't work, since s isn't the same type as that new ArrayList being created. You also can't take a bunch of objects that are instances of a supertype of T and return a collection that's T. Imagine if s were List<Object> and t were a String. Your method would be required to return a List<String>, which is impossible unless you somehow know that all the objects in s are secretly strings.

Also, why are you adding t to s and then returning a new ArrayList that's just s? You're modifying s by doing that.

What you should probably do is

public static <T> List <T> add(List<T> s, T t) {
    List<T> res = new ArrayList<>(s);
    res.add(t);
    return res;
}

You could also do this if t's type could be less specific than the elements in s.

public static <T> List <T> add(List<? extends T> s, T t) {
    List<T> res = new ArrayList<>(s);
    res.add(t);
    return res;
}


问:
Azure DevOps API - git log equivalent
I'm trying to replicate this git command: git log "$labelCommit..HEAD" --decorate using the Azure Devops api

I thought this would do the trick:

GET https://dev.azure.com/fabrikam/_apis/git/repositories/{repositoryId}/commits?searchCriteria.compareVersion.version=$labelCommit&searchCriteria.compareVersion.versionType=commit&api-version=6.0-preview.1

But I just seem to keep getting everything back. Looking at my repo I should get 7 commits back, but I can get thousands.

The documentation is non-existent on what searchCriteria.compareVersion is or how to use it, what the various options actually mean.

Has anyone achieved anything similar?

答:
I believe this gives me what I want:</p>

```<code>var gitQueryCommitsCriteria = new GitQueryCommitsCriteria()
        {
            CompareVersion = new GitVersionDescriptor()
            {
                Version = branchName,
                VersionType = GitVersionType.Branch
            },
            Top = 10000,
            IncludeLinks = true,
            IncludeWorkItems = true,
            ItemVersion = new GitVersionDescriptor()
            {
                Version = tagName,
                VersionType = GitVersionType.Tag,
                VersionOptions = GitVersionOptions.None
            }

        };

        var commits = await GitHttpClient.GetCommitsAsync("projectName", repo, gitQueryCommitsCriteria);
</code>```

Title: Azure DevOps API - git log equivalent

Body:
I believe this gives me what I want:

var gitQueryCommitsCriteria = new GitQueryCommitsCriteria()
        {
            CompareVersion = new GitVersionDescriptor()
            {
                Version = branchName,
                VersionType = GitVersionType.Branch
            },
            Top = 10000,
            IncludeLinks = true,
            IncludeWorkItems = true,
            ItemVersion = new GitVersionDescriptor()
            {
                Version = tagName,
                VersionType = GitVersionType.Tag,
                VersionOptions = GitVersionOptions.None
            }

        };

        var commits = await GitHttpClient.GetCommitsAsync("projectName", repo, gitQueryCommitsCriteria);


问:
Django/Heroku: FATAL: too many connections for role
So I just launched a website with Channels 2.0 Daphne 2.2.0 and asgi via Heroku (Hobby) and Postgres (trial). When I launch my website, I click around for a few pages and I get a 500 error. The error message I get emailed is FATAL:  too many connections for role ..."

When I run heroku pg:killall or wait long enough I can click around a few more times until the error message repeats itself. However, when I run heroku pg it shows Connections 0/20. Does anyone know what is going on and how I can stop the errors?  It's possible that I have two many connections open for a second, but it doesn't seem that way.

```<code>File "/app/.heroku/python/lib/python3.6/site-

packages/django/contrib/sessions/backends/base.py" in _get_session
  191.             return self._session_cache

During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred:

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  216.                 self.connect()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect
  194.         self.connection = self.get_new_connection(conn_params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py" in get_new_connection
  168.         connection = Database.connect(**conn_params)

File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py" in connect
  130.     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)

The above exception (FATAL:  too many connections for role "polewdwynmvyyt"
) was the direct cause of the following exception:

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "./myproject/views.py" in home_page
  8.     print(request.session.get("first_name","Unknown")) #getter

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in get
  66.         return self._session.get(key, default)

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in _get_session
  196.                 self._session_cache = self.load()

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py" in load
  34.                 expire_date__gt=timezone.now()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in get
  397.         num = len(clone)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in __len__
  254.         self._fetch_all()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in _fetch_all
  1179.             self._result_cache = list(self._iterable_class(self))

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
  53.         results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1066.             cursor = self.connection.cursor()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in cursor
  255.         return self._cursor()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in _cursor
  232.         self.ensure_connection()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  216.                 self.connect()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  216.                 self.connect()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect
  194.         self.connection = self.get_new_connection(conn_params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py" in get_new_connection
  168.         connection = Database.connect(**conn_params)

File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py" in connect
  130.     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
</code>```

答:
I had this exact same problem, using the heroku add-on pgbouncer you can close old connections and limit the number of connections to the database.

the heroku documentation does a great job of explaining it just don't try using anything but a Procfile: django pgbouncer docs

Body:
So I just launched a website with Channels 2.0 Daphne 2.2.0 and asgi via Heroku (Hobby) and Postgres (trial). When I launch my website, I click around for a few pages and I get a 500 error. The error message I get emailed is FATAL:  too many connections for role ..."

When I run heroku pg:killall or wait long enough I can click around a few more times until the error message repeats itself. However, when I run heroku pg it shows Connections 0/20. Does anyone know what is going on and how I can stop the errors?  It's possible that I have two many connections open for a second, but it doesn't seem that way.

File "/app/.heroku/python/lib/python3.6/site-

packages/django/contrib/sessions/backends/base.py" in _get_session
  191.             return self._session_cache

During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred:

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  216.                 self.connect()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect
  194.         self.connection = self.get_new_connection(conn_params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py" in get_new_connection
  168.         connection = Database.connect(**conn_params)

File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py" in connect
  130.     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)

The above exception (FATAL:  too many connections for role "polewdwynmvyyt"
) was the direct cause of the following exception:

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "./myproject/views.py" in home_page
  8.     print(request.session.get("first_name","Unknown")) #getter

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in get
  66.         return self._session.get(key, default)

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in _get_session
  196.                 self._session_cache = self.load()

File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py" in load
  34.                 expire_date__gt=timezone.now()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in get
  397.         num = len(clone)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in __len__
  254.         self._fetch_all()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in _fetch_all
  1179.             self._result_cache = list(self._iterable_class(self))

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
  53.         results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1066.             cursor = self.connection.cursor()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in cursor
  255.         return self._cursor()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in _cursor
  232.         self.ensure_connection()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  216.                 self.connect()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection
  216.                 self.connect()

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect
  194.         self.connection = self.get_new_connection(conn_params)

File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py" in get_new_connection
  168.         connection = Database.connect(**conn_params)

File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py" in connect
  130.     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)


问:
How to download file via SftpRemoteFileTemplate from endpoint
I have File controller like below;

```<code>@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
public class FileController {

     private final SftpRemoteFileTemplate sftpRemoteFileTemplate;

    @PostMapping("/generate/{exportId}")
    public void generate(@PathVariable("exportId") String exportId) {
        File csvFile = createCsvFile(System.getProperty(JAVA_IO_TMPDIR));
        CsvUtils.write(csvFile, prepareExports(exportId));
        Message<File> message = MessageBuilder.withPayload(file).build();
        String path = remoteFileTemplate.send(message, FileExistsMode.REPLACE);
        //store path to download after etc...
    }

    @GetMapping("/download/{filePath}")
    public ResponseEntity<Resource> download(@PathVariable("filePath") String filePath) {
        //I didn't imagine how can i use it to download response?
        sftpRemoteFileTemplate.get(filePath, stream -> {

        });
    }
}
</code>```

i can upload to file to my SFTP server by using ; remoteFileTemplate.send(message, FileExistsMode.REPLACE)

But i couldn't imagine how to download it by  sftpRemoteFileTemplate.get method.

it requires InputStreamCallback, how can i use it to make download response?

答:
Jus create a FileOutputStream and copy the data from the input stream to it. e.g.

FileCopyUtils.copy(stream, new FileOutputStream(new File("local/path"));

Body:
I have File controller like below;

@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
public class FileController {

     private final SftpRemoteFileTemplate sftpRemoteFileTemplate;

    @PostMapping("/generate/{exportId}")
    public void generate(@PathVariable("exportId") String exportId) {
        File csvFile = createCsvFile(System.getProperty(JAVA_IO_TMPDIR));
        CsvUtils.write(csvFile, prepareExports(exportId));
        Message<File> message = MessageBuilder.withPayload(file).build();
        String path = remoteFileTemplate.send(message, FileExistsMode.REPLACE);
        //store path to download after etc...
    }

    @GetMapping("/download/{filePath}")
    public ResponseEntity<Resource> download(@PathVariable("filePath") String filePath) {
        //I didn't imagine how can i use it to download response?
        sftpRemoteFileTemplate.get(filePath, stream -> {

        });
    }
}

i can upload to file to my SFTP server by using ; remoteFileTemplate.send(message, FileExistsMode.REPLACE)

But i couldn't imagine how to download it by  sftpRemoteFileTemplate.get method.

it requires InputStreamCallback, how can i use it to make download response?


问:
How to identify the element using Selenium and Python
I've been tinkering with Selenium (Python) for the day working on a project. I'm stuck trying to click on a link of the webpage because I'm unable to retrieve the element by any of the ways I've found until now.

The link is this:

```<code><p>
<a href="0_fr.asp?contenido=0actunor.asp" target="mainFrame"><font size="3" face="Arial" color="#CC9900">
<b>Base de datos de Disposiciones Vigentes</b></font></a>
</font>
</p>
</code>```

Now, I've tried these things so far, and all give me NoSuchElementException:

driver.find_element_by_css_selector("a[href=0_fr.asp?contenido=0actunor.asp]")

driver.find_element_by_css_selector('div:contains("Base de datos de Disposiciones Vigentes")')

same as 1) but copying and pasting CSS selector alone as a String

by link text and partial link text using the content between  and

by using id just in case it does something.

And several more found across other StackOverflow questions and online guides to build my own css selectors and such, but I don't know any HTML or CSS so it's been a bit difficult to follow them.
I can provide more information if needed, but i'm unable to link the webpage as you would have to log in and it's a job thing.

Any help or places to search for more information are greatly welcome!

SOLVED: The problem was that the link was inside a frame, which was inside another frame. I just hade to use driver.switch_to.frame("frameName") twice, then use css_selector normally and works as it should.

答:
Try the following command.

driver.find_element_by_link_text("Base de datos de Disposiciones Vigentes")

Body:
I've been tinkering with Selenium (Python) for the day working on a project. I'm stuck trying to click on a link of the webpage because I'm unable to retrieve the element by any of the ways I've found until now.

The link is this:

Base de datos de Disposiciones Vigentes

Now, I've tried these things so far, and all give me NoSuchElementException:

driver.find_element_by_css_selector("a[href=0_fr.asp?contenido=0actunor.asp]")

driver.find_element_by_css_selector('div:contains("Base de datos de Disposiciones Vigentes")')

same as 1) but copying and pasting CSS selector alone as a String

by link text and partial link text using the content between  and

by using id just in case it does something.

And several more found across other StackOverflow questions and online guides to build my own css selectors and such, but I don't know any HTML or CSS so it's been a bit difficult to follow them.
I can provide more information if needed, but i'm unable to link the webpage as you would have to log in and it's a job thing.

Any help or places to search for more information are greatly welcome!

SOLVED: The problem was that the link was inside a frame, which was inside another frame. I just hade to use driver.switch_to.frame("frameName") twice, then use css_selector normally and works as it should.


问:
How to get real time data from android Recognizer Intent?

I would like to call the RecognizerIntent and have it loop forever until the user decides to close it, how would I go about doing this?  the current android recognizer intent closes whenever the sound stops after a recognized input. For example: if "hi" was recognized, if the user doesn't say anything after that for about one or two seconds the Activity closes. Any way I can stop the activity from closing? and going forever until I choose to close it(perhaps by a click of the button a second time?)'

I would also like to get real-time data back as to what is being said, instead of having it passed as extra data from the activity after it closes.

```<code>package com.example.myapplication

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.speech.RecognizerIntent
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_recordinit.*
import java.lang.Exception
import java.util.*

class Recordinit : AppCompatActivity() {

 val   REQUESTCODE3 = 4

fun audioaction(){
    val speechtotextintent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    speechtotextintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.EXTRA_LANGUAGE_MODEL)
    speechtotextintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE , Locale.getDefault())
    speechtotextintent.putExtra(RecognizerIntent.EXTRA_PROMPT , "Click To Begin Listening on the threat!!")
    try {
        //check to see if the activity can work on this device... and it meets the requirements
        startActivityForResult(speechtotextintent , REQUESTCODE3 )

    }
    //if there is any errors we will let the user know in a popup message.
    catch (e : Exception){
        Toast.makeText(this , e.message , Toast.LENGTH_SHORT  ).show()

    }

}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_recordinit)
    microphonebutton.setOnClickListener{
        audioaction()

    }

}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

     if (REQUESTCODE3 == requestCode ){
        when (resultCode == Activity.RESULT_OK ){

        }

    }
    super.onActivityResult(requestCode, resultCode, data)
}
</code>```

}

EDIT: I found out that the EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS would allow me do dictate how the activity reacts to silence. But I still would like to find a way to monitor what is being said in real-time.

答:
Maybe this helps you to get the words said when activity called.</p>

```<code>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_CODE10) {
        if (resultCode == RESULT_OK && data != null) {
            var result : ArrayList<String> = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
        }
    }
}
</code>```

Body:
I would like to call the RecognizerIntent and have it loop forever until the user decides to close it, how would I go about doing this?  the current android recognizer intent closes whenever the sound stops after a recognized input. For example: if "hi" was recognized, if the user doesn't say anything after that for about one or two seconds the Activity closes. Any way I can stop the activity from closing? and going forever until I choose to close it(perhaps by a click of the button a second time?)'

I would also like to get real-time data back as to what is being said, instead of having it passed as extra data from the activity after it closes.

package com.example.myapplication

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.speech.RecognizerIntent
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_recordinit.*
import java.lang.Exception
import java.util.*

class Recordinit : AppCompatActivity() {

 val   REQUESTCODE3 = 4

fun audioaction(){
    val speechtotextintent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    speechtotextintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.EXTRA_LANGUAGE_MODEL)
    speechtotextintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE , Locale.getDefault())
    speechtotextintent.putExtra(RecognizerIntent.EXTRA_PROMPT , "Click To Begin Listening on the threat!!")
    try {
        //check to see if the activity can work on this device... and it meets the requirements
        startActivityForResult(speechtotextintent , REQUESTCODE3 )

    }
    //if there is any errors we will let the user know in a popup message.
    catch (e : Exception){
        Toast.makeText(this , e.message , Toast.LENGTH_SHORT  ).show()

    }

}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_recordinit)
    microphonebutton.setOnClickListener{
        audioaction()

    }

}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

     if (REQUESTCODE3 == requestCode ){
        when (resultCode == Activity.RESULT_OK ){

        }

    }
    super.onActivityResult(requestCode, resultCode, data)
}

}

EDIT: I found out that the EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS would allow me do dictate how the activity reacts to silence. But I still would like to find a way to monitor what is being said in real-time.

Body:
Maybe this helps you to get the words said when activity called.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_CODE10) {
        if (resultCode == RESULT_OK && data != null) {
            var result : ArrayList<String> = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
        }
    }
}


问:
MySQL licensing and GPL
As far as I know, when I build a desktop/server app using any GPL code like MySQL I will have to release the source code of my software under the GPL.

If I want to develop a web-app using MySQL, my code will link against the MySQL libraries. Must I release the sourcecode of my webapp in this situation to be in accordance with the GPL?

答:
You must either release the source (under GPL), or pay for a proprietary license to MySQL so that you gain the right to distribute the MySQL binaries under a license that is more amenable to that which proprietary products use.  It's best to take this type of question to your lawyer, though.

ETA: Just to clarify a little bit; if you write your own library which talks to MySQL using its wire-line protocol, then you'll always be 100% in the clear.  Likewise, if you use a library that has done just that, but is BSD licensed (as an example), then you'd also be in the clear, because you're only talking to MySQL over a socket connection, and not actually calling into GPL'd code.  I am not immediately aware of any BSD licensed interfaces to the MySQL protocol, but it's certainly possible that there is one out there somewhere.

ContentLicense: CC BY-SA 2.5

Title: MySQL licensing and GPL

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Michael Trausch

LastEditorDisplayName: Michael Trausch


问:
Python Script - module, main_function and package_runner contain error
I have a script that previously worked on an old server. This was kind of thrown at me, so forgive me with my lack of python knowledge. I studied plenty of other languages and have been troubleshooting this for days!

I have updated the paths appropriately but always get the following errors when running on a new error:
Powershell errors with line numbers

The line numbers given in the image are 241, 117, and 140. The code is as followed

```<code>def main_function(todayDate):
zipFileName = ''

print todayDate
for root, dirname, files in os.walk(workingDir, topdown=True):
    del dirname[:]
    for file in files:
        if file.startswith('datawarehousefeed_' + currentDwfVersion) or file.startswith('datawarehousefeed_' + currentDwfVersionBackfill):
            if file.endswith('11692.zip'):
                if (file.__contains__('BACKFILL_') and file.split('_')[4] == todayDate) or (file.__contains__(todayDate) and 'BACKFILL_' not in file):
                    zipFileName = workingDir + '\\' + file
                    print zipFileName

                    if not os.path.exists(archiveDir):
                        os.mkdir(archiveDir)

                    if os.path.exists(processingDir):
                        shutil.rmtree(processingDir)
                    os.mkdir(processingDir)

                    if os.path.exists(finalDir):
                        shutil.rmtree(finalDir)
                    os.mkdir(finalDir)

                    with zipfile.ZipFile(zipFileName, 'r') as zf:
                        zf.extractall(processingDir)

                    for root, dirname, files in os.walk(processingDir):
                        for file in files:
                            if not (file.startswith('qmresult')):
                                 if not (file.startswith('rolepermission')):
                                      if file:
                                           if file:
                                              tableName = file[:file.find('_')]
                                              with open((processingDir + '\\' + file), 'rb') as read:
                                                  reader = csv.reader((line.replace('\0','') for line in read))
                                                  #reader = csv.reader(read)
                                                  with open((finalDir + '\\' + tableName + '.csv'), 'wb') as write:
                                                      writer = csv.writer(write, delimiter=',', quotechar="\"", lineterminator='\n')
                                                      for row in reader:
                                                          rowFixed = []
                                                          for column in row:
                                                              fixedColumn = string.replace(column, "\"", "\'\'")
                                                              fixedColumn2 = string.replace(fixedColumn, '\n', ' ')
                                                              rowFixed.append(fixedColumn2)
                                                          writer.writerow(rowFixed)
                                                      read.close
                                                      write.close
                    package_runner(zipFileName)
def package_runner(zipFileName):
try:
    retcode = subprocess.call(r'dtexec /f "FILE PATH HERE"', shell=True)
    if retcode > 0:
        print >>sys.stderr, "Child was terminated by signal", -retcode
        sendEmail("ssis failure", (zipFileName + " " + "DWF_1_A_ClaimAudit.dtsx" + " " + str(retcode)))
        print (10/0)
    else:
        print >>sys.stderr, "Child returned", retcode
except OSError as e:
    print >>sys.stderr, "Execution failed:", e
    sendEmail("ssis failure", (zipFileName + " " + "DWF_1_A_ClaimAudit.dtsx" + " " +  e))
    sys.exit("error, exiting")

for single_date in daterange(startDate, endDate):
print single_date.strftime("%Y%m%d")
todayDate = single_date.strftime("%Y%m%d")
main_function(todayDate)
</code>```

答: The error simply says Division Error by 0. This error means that you are trying to divide a number with 0, which is not possible. Consider changing it to number other that zero</p>

Body:
I have a script that previously worked on an old server. This was kind of thrown at me, so forgive me with my lack of python knowledge. I studied plenty of other languages and have been troubleshooting this for days!

I have updated the paths appropriately but always get the following errors when running on a new error:
Powershell errors with line numbers

The line numbers given in the image are 241, 117, and 140. The code is as followed

def main_function(todayDate):
zipFileName = ''

print todayDate
for root, dirname, files in os.walk(workingDir, topdown=True):
    del dirname[:]
    for file in files:
        if file.startswith('datawarehousefeed_' + currentDwfVersion) or file.startswith('datawarehousefeed_' + currentDwfVersionBackfill):
            if file.endswith('11692.zip'):
                if (file.__contains__('BACKFILL_') and file.split('_')[4] == todayDate) or (file.__contains__(todayDate) and 'BACKFILL_' not in file):
                    zipFileName = workingDir + '\\' + file
                    print zipFileName

                    if not os.path.exists(archiveDir):
                        os.mkdir(archiveDir)

                    if os.path.exists(processingDir):
                        shutil.rmtree(processingDir)
                    os.mkdir(processingDir)

                    if os.path.exists(finalDir):
                        shutil.rmtree(finalDir)
                    os.mkdir(finalDir)

                    with zipfile.ZipFile(zipFileName, 'r') as zf:
                        zf.extractall(processingDir)

                    for root, dirname, files in os.walk(processingDir):
                        for file in files:
                            if not (file.startswith('qmresult')):
                                 if not (file.startswith('rolepermission')):
                                      if file:
                                           if file:
                                              tableName = file[:file.find('_')]
                                              with open((processingDir + '\\' + file), 'rb') as read:
                                                  reader = csv.reader((line.replace('\0','') for line in read))
                                                  #reader = csv.reader(read)
                                                  with open((finalDir + '\\' + tableName + '.csv'), 'wb') as write:
                                                      writer = csv.writer(write, delimiter=',', quotechar="\"", lineterminator='\n')
                                                      for row in reader:
                                                          rowFixed = []
                                                          for column in row:
                                                              fixedColumn = string.replace(column, "\"", "\'\'")
                                                              fixedColumn2 = string.replace(fixedColumn, '\n', ' ')
                                                              rowFixed.append(fixedColumn2)
                                                          writer.writerow(rowFixed)
                                                      read.close
                                                      write.close
                    package_runner(zipFileName)
def package_runner(zipFileName):
try:
    retcode = subprocess.call(r'dtexec /f "FILE PATH HERE"', shell=True)
    if retcode > 0:
        print >>sys.stderr, "Child was terminated by signal", -retcode
        sendEmail("ssis failure", (zipFileName + " " + "DWF_1_A_ClaimAudit.dtsx" + " " + str(retcode)))
        print (10/0)
    else:
        print >>sys.stderr, "Child returned", retcode
except OSError as e:
    print >>sys.stderr, "Execution failed:", e
    sendEmail("ssis failure", (zipFileName + " " + "DWF_1_A_ClaimAudit.dtsx" + " " +  e))
    sys.exit("error, exiting")

for single_date in daterange(startDate, endDate):
print single_date.strftime("%Y%m%d")
todayDate = single_date.strftime("%Y%m%d")
main_function(todayDate)


问:
How to configure a Daphne server to invite clients to add the Certificate Authority that issued my certificate if they hadn't done it yet?
If I make a request to my Daphne/Django server in Postman or the Android app we're developing, Daphne serves the certificate, but it's rejected. If I first make a simple get request to https://letsencrypt.org/ and then make a request to my server, the certificate is accepted.

How can I make sure a client will trust my certificate, even if it's the first time this client is seeing a certificate issued by this CA?

Everything bellow can serve as a history of how I studied the problem.

Original title: SSL Certificate works in browser but can't be verified by Postman

I have an AWS EC2 instance running Ubuntu 18.04, with python 3, Django, a bunch of project dependencies, Daphne running with ASGI, with a certificate by Let's Encrypt. Daphne is using port 8000 for HTTP and por 4430 for HTTPS, iptables is configured to redirect requests from port 80 to 8000 and from port 443 to 4430. Django is configured to enforce secure connections with SECURE_SSL_REDIRECT=True in the settings.py file.

There's a "Site in Construction" temporary page being served, and it's properly accessible from every browser and every device I tested so far. If I explicitly type http, I get redirected to https and the certificate is accepted. Every browser I tested (Firefox, Brave, Chrome, Chrome for Android) says cert is good.

Curl outputs the HTML content returned from the server. I don't know if it accepts the certificate or ignores it.

The Problem

Postman, however, says "Error: unable to verify the first certificate". Only works when I disable "SSL certificate verification", which doesn't answer my question: why Postman is unable to verify my Let's Encrypt certificate?

I'm building an API that runs on the same server, using the same domain, and it's meant to be consumed by a mobile app. Currently, the Android app is throwing a "TypeError: Network request failed", which I suspect could be caused by the same thing Postman is complaining about.

When I spin the server locally and configure 1) the app to use http://localhost:8000 and 2) the server not to enforce SSL, it works in browsers, Postman and in the Android app.

I've being looking for answers in many places for days, so any clue will be very welcome.

EDIT

Interesting clue:

If I make a request to my Daphne/Django server, it servers the certificate, which is rejected. But if I first make a request to https://letsencrypt.org/ and then make a request to my server, it works!

This pattern holds true in both Postman and our Android app.

It also happens when I first make a request to https://alloy.city (instead of letsencrypt.org), which is served by a Node.js app, and uses a certificate also issued by the Let's Encrypt CA.

So maybe the question should be: how to configure my server to politely invite clients to add the CA that issued my certificate if they hadn't done it yet?.

Apparently, that's what my Node.js server does.

答:
Yes, in settings, tap ssl verification off

File > Settings > General > SSL Certificate Verification > off


问:
When trying to test laravel auth for the register rout
I'm trying check out the auth scaffolding for laravel in my project. After creating my database and migrating, I get this error when i want to test the register auth.

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into users (name, email, password, updated_at, created_at) values (jonas, jokansey@gmail.com, $2y$10$9yqGB0hk0O5npBcsq1ImGeRYfTvkJe6ftC5QQ.nmezckbROw6CR06, 2020-05-28 16:18:49, 2020-05-28 16:18:49))
http://todaybusiness.test/register

答:
Your users table is missing timestamp. Check database/migrations/2014_10_12_000000_create_users_table.php

Add line,  $table->timestamps(); at the end of the up() table,

```<code>public function up()
{
    Schema::create('users', function (Blueprint $table) {
        ...
        $table->timestamps();
    });
}
</code>```

Body:
Your users table is missing timestamp. Check database/migrations/2014_10_12_000000_create_users_table.php

Add line,  $table->timestamps(); at the end of the up() table,

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        ...
        $table->timestamps();
    });
}


问:
How to check if a script is still running in my server?
So I started a script that sends me an email if a specific condition occours and its running from vps, but since I've not yet received any emails, I'm wondering if the script is still running. I also forgot the name of the "xxxxxx.py" file thats running.

What can I do??

答:
If your VPS is linux-based with a ssh server listening, you should be able to connect to it, opening a terminal. After that You can try using the ps ax or top or htop command to display all processes running.

You can then use a pipe to filter out the word "py" :
ps ax | grep "py"


问:
C# - StyleCop - SA1121: UseBuiltInTypeAlias - Readability Rules
Not found it in StyleCop Help Manual, on SO and Google so here it is ;)

During StyleCop use I have a warning:

SA1121 - UseBuiltInTypeAlias -
  Readability Rules

The code uses one of the basic C#
  types, but does not use the built-in
  alias for the type.

Rather than using the type name or the
  fully-qualified type name, the
  built-in aliases for these types
  should always be used: bool, byte,
  char, decimal, double, short, int,
  long, object, sbyte, float, string,
  ushort, uint, ulong.

so String.Empty is wrong (depend on above rules) and string.Empty is good.

Why using built-in aliases is better? Can String. Int32, Int64 (etc.) complicate something in the code on special scenarios?

答: Less confusing? It seems very akward to me for a base data type, which traditionally is just a value, to include static functions. I understand using the base data type equivalent if you're just storing a value, but for accessing members of the class, it seems very akward to put a .(dot) after the base type name.</p>


答:
Using the ps command with -A and -f flags and pipe the output to grep and search for py
Check this :

```<code>ps -A -f | grep "py"
</code>```

Title: How to check if a script is still running in my server?

Body:
So I started a script that sends me an email if a specific condition occours and its running from vps, but since I've not yet received any emails, I'm wondering if the script is still running. I also forgot the name of the "xxxxxx.py" file thats running.

What can I do??

Body:
Using the ps command with -A and -f flags and pipe the output to grep and search for py
Check this :

ps -A -f | grep "py"


问:
Checkbox only changes value when clicked twice
As title says, I set up a checkbox which has the issue that I need to click on it twice to change it's state

The first time I click it behaves as expected, but every attempt after that requires double clicking.

```<code>state = {
    notification: true,
};

handleInputChange= (event) => {
//I use event.target to operate since I'm trying to set up multiple checkboxes
    this.setState({ [event.target.id]: !event.target.checked });
};

<AppSwitch
  checked={this.state.notification}
  onChange={this.handleInputChange}
  className={"mx-1 switch-color"}
  color={"success"}
  variant={"pill"}
  id="notification"
  name="notification"
/>
</code>```

答: You don't need to ! when you're setting state here. It should be this.setState({ [event.target.id]: event.target.checked });, since event.target.checked returns the checked state of the checkbox. So, if you click the checkbox and it transitions to checked, then it will be true. Then, if you click the checkbox and it transitions to unchecked then it will be false.

Body:
As title says, I set up a checkbox which has the issue that I need to click on it twice to change it's state

The first time I click it behaves as expected, but every attempt after that requires double clicking.

state = {
    notification: true,
};

handleInputChange= (event) => {
//I use event.target to operate since I'm trying to set up multiple checkboxes
    this.setState({ [event.target.id]: !event.target.checked });
};

<AppSwitch
  checked={this.state.notification}
  onChange={this.handleInputChange}
  className={"mx-1 switch-color"}
  color={"success"}
  variant={"pill"}
  id="notification"
  name="notification"
/>


问:
Make a delete button
I'm working on a digital marketplace. I'm trying to make a delete button where it will delete the product out of my admin portal. When I click the delete button it redirects me back to the product page in it says deleted but the row is still there.

```<code><form action='delete.php?product_id="<?php echo $product_id; ?>"' method="post">
<input type="hidden" name="product_id" value="<?php echo $loadProduct['product_id']; ?>">
<button class="btn btn-sm btn-alt-danger" type="submit" name="DeleteProduct"><i class="fa fa-fw fa-times text-danger"></i></button
</form>
</code>```

Here's my delete.php code

```<code><?php
  require_once('../inc/config.php');

  if(isset($_POST['DeleteProduct'])){
    $product_id = $_GET['product_id'];

    $result = $db->delete('DELETE FROM products WHERE product_id = ?', array($product_id));
    if ($result) {
        header('Location: products.php?action=deleted');
    } else {
        header('Location: products.php?error=notremoved');
        }
    }

?>
</code>```

答:
Remove the querystring from the action attribute, but not the script name. You are using POST and have that product_id placed in the hidden <input>

```<code><form action="delete.php" method="post">

    <input type="hidden" name="product_id" value="<?php echo $loadProduct['product_id']; ?>">
    <button class="btn btn-sm btn-alt-danger" type="submit" name="DeleteProduct">
        <i class="fa fa-fw fa-times text-danger"></i>
    </button
</form>
</code>```

Then in your PHP use $_POST['product_id'] to access that value again

Title: Make a delete button

Body:
I'm working on a digital marketplace. I'm trying to make a delete button where it will delete the product out of my admin portal. When I click the delete button it redirects me back to the product page in it says deleted but the row is still there.

<form action='delete.php?product_id="<?php echo $product_id; ?>"' method="post">
<input type="hidden" name="product_id" value="<?php echo $loadProduct['product_id']; ?>">
<button class="btn btn-sm btn-alt-danger" type="submit" name="DeleteProduct"></button
</form>

Here's my delete.php code

<?php
  require_once('../inc/config.php');

  if(isset($_POST['DeleteProduct'])){
    $product_id = $_GET['product_id'];

    $result = $db->delete('DELETE FROM products WHERE product_id = ?', array($product_id));
    if ($result) {
        header('Location: products.php?action=deleted');
    } else {
        header('Location: products.php?error=notremoved');
        }
    }

?>

Body:
Remove the querystring from the action attribute, but not the script name. You are using POST and have that product_id placed in the hidden <input>

<form action="delete.php" method="post">

    <input type="hidden" name="product_id" value="<?php echo $loadProduct['product_id']; ?>">
    <button class="btn btn-sm btn-alt-danger" type="submit" name="DeleteProduct">
        <i class="fa fa-fw fa-times text-danger"></i>
    </button
</form>

Then in your PHP use $_POST['product_id'] to access that value again


问:
Springboot standalone application deploy in production
I am trying to deploy my springboot standalone application in production in linux server.I am trying to use the out of the box tomcat server.

'java -jar jarname.jar'

This works fine , but if I close my putty session the application is unistalled.

Now I used

'nohup java -jar jarname.jar &'

this works good and my application is not shutdown even if my putty session is closed.But the logs will not roll correctly(I have configured log4j to create a new log file for each day) in this case. So was wondering if this is the right way to do this.

I have searched several documentation but was not able to find a correct solution for this problem.
Please help.

Thanks

答:
You can run your spring boot application as jar, but you need to create a service so you can execute your spring boot as daemon.

https://dzone.com/articles/run-your-java-application-as-a-service-on-ubuntu

With this, you can start or stop your application like

$ sudo service myspringbootapp stop

$ sudo service myspringbootapp start


问:
Azure and NX, error while running a pipeline : npm : Another process, with id 4224, is currently running ngcc
I'm trying to run a pipeline with Azure, when it comes to build, it fails with this error :

When I run the nx affected --target=build --base=origin/master --prod --parallel command locally, I also have the Another process... message but it doesn't show as an error which lets the build continues. But on Azure it just fails :(

Any idea how I can solve this? Thanks

答:
This is a known issue with how NGCC runs, you can reference it here:

GitHub Issue 35362

and as a work around add this to your package.json file:  (in the script section)

```<code>"postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points",
</code>```

it also appears to be blocking using the --parallel flag.  try dropping that.

Body:
This is a known issue with how NGCC runs, you can reference it here:

GitHub Issue 35362

and as a work around add this to your package.json file:  (in the script section)

"postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points",

it also appears to be blocking using the --parallel flag.  try dropping that.