问:
R: Match an odd number of repetitions
I would like to match a string like \code, but not when the backslash is escaped.

I think that one way of doing this could be matching an odd number of backslashes. Then for example, assuming \code is an expression to be replaced by 1234:

\code would be 1234, but \\code, should stay as is, \\\code would be \\1234, etc.

In R, given the strings:

```<code>message(o <- "\\\\\\code")
# \\\code
message(e <- "\\\\code")
# \\code
</code>```

A partially working attempt in R is:

```<code>message(gsub("((?:\\\\{2})?)\\\\code", "\\11234", o, perl=TRUE))
# \\1234
message(gsub("((?:\\\\{2})*)\\\\code", "\\11234", e, perl=TRUE))
# \1234
</code>```

The regex matches both the odd and even case. To make it work, I should find a way to match the double backslashes, "\", more greedily (always when they are present) so that the second backslash doesn't.

Of course, if there is a better strategy to match a "\sequence" (when not escaped) that would be equally fine.

答:
You may use

```<code>rx <- "(?<!\\\\)(?:\\\\{2})*\\K\\\\code"
</code>```

Replace with 1234. See the regex demo.

Details

(?<!\\) - fail if there is a \ immediately to the left of the current location

(?:\\{2})*  - match and consume 0 or more occurrences of double backslash

\K - match reset operator that discards all text matched so far

\\code - \code text.

See an R demo online:

```<code>rx <- "(?<!\\\\)(?:\\\\{2})*\\K\\\\code"
message(gsub(rx, "1234", "\\\\\\code", perl=TRUE)) # \\\code
# => \\1234
message(gsub(rx, "1234", "\\\\code", perl=TRUE))   # \\code
# => \\code
message(gsub(rx, "1234", "\\code", perl=TRUE)) # \code
# => 1234
</code>```

Title: R: Match an odd number of repetitions

Body:
I would like to match a string like \code, but not when the backslash is escaped.

I think that one way of doing this could be matching an odd number of backslashes. Then for example, assuming \code is an expression to be replaced by 1234:

\code would be 1234, but \\code, should stay as is, \\\code would be \\1234, etc.

In R, given the strings:

message(o <- "\\\\\\code")
# \\\code
message(e <- "\\\\code")
# \\code

A partially working attempt in R is:

message(gsub("((?:\\\\{2})?)\\\\code", "\\11234", o, perl=TRUE))
# \\1234
message(gsub("((?:\\\\{2})*)\\\\code", "\\11234", e, perl=TRUE))
# \1234

The regex matches both the odd and even case. To make it work, I should find a way to match the double backslashes, "\", more greedily (always when they are present) so that the second backslash doesn't.

Of course, if there is a better strategy to match a "\sequence" (when not escaped) that would be equally fine.

Body:
You may use

rx <- "(?<!\\\\)(?:\\\\{2})*\\K\\\\code"

Replace with 1234. See the regex demo.

Details

(?<!\\) - fail if there is a \ immediately to the left of the current location

(?:\\{2})*  - match and consume 0 or more occurrences of double backslash

\K - match reset operator that discards all text matched so far

\\code - \code text.

See an R demo online:

rx <- "(?<!\\\\)(?:\\\\{2})*\\K\\\\code"
message(gsub(rx, "1234", "\\\\\\code", perl=TRUE)) # \\\code
# => \\1234
message(gsub(rx, "1234", "\\\\code", perl=TRUE))   # \\code
# => \\code
message(gsub(rx, "1234", "\\code", perl=TRUE)) # \code
# => 1234


来源: stackexchange

问:
Difference in quotas of free and GSuite Enterprise Google products
I try to find differences in quotas of Google Spreadsheets and App Scripts, used by free account vs. GSuite Enterprise account.

The only document i've got is https://developers.google.com/apps-script/guides/services/quotas. But there i miss such quotas as ImportXml.

答:
Besides looking in https://developers.google.com/apps-script also look at

https://support.google.com/docs Goodle Docs Editors Help Center

https://support.google.com/a G Suite Help Center for G Suite Administrator

https://developers.google.com/sheets "Micro-site" about Google Sheets for developers

You might also should subscribe/follow to the G Suite Update Blog where changes to G Suite (including Google Sheets) are usually announced.

ContentLicense: CC BY-SA 4.0


问:
Working on eclipse project in subversion
All,
I have a 20 member dev team working on a development project.
To provide greater control we have created a workspace with necessary projects and configurations (like project preferences, set-ups etc) in IBM RAD.

The idea is to have the pre-configured project in subversion so that when the dev team members checkout the project they get a complete workspace, so that they do not have to configure setups them selves.

However the problem is everytime someone checks out the workspace IBM RAD will also edit the .metadata (and some other folders and properties file) folder that has been checked in.

Idea is the developer should not have to change anything except the source code folders or application specific files.

I think many other teams might have faced situations like this.
Can anybody provide the best practices/process/references on how this is done in development projects?

Thanks

答:
I think svn ignore will solve your problem.
check http://svnbook.red-bean.com/en/1.1/ch07s02.html

The svn:ignore property contains a
  list of file patterns which certain
  Subversion operations will ignore.
  Perhaps the most commonly used special
  property, it works in conjunction with
  the global-ignores run-time
  configuration option (see the section
  called “Config”) to filter unversioned
  files and directories out of commands
  svn status, svn add, and svn import.

ContentLicense: CC BY-SA 3.0


问:
Bookdown different even and odd pages margins with pdf output
I am using bookdown package version 0.13 with R 3.6.0.

When I generate a pdf output, the even and odd pages have different margins. Even pages are shifted to the right and odd ones to the left (see picture below). Is this some type of feature? For example, for printing?

How can I disable this behavior?

I get the same margin differences when trying the minimal example provided in the official demo. The _bookdown.yml file has this content:

```<code>book_filename: "bookdown-demo"
language:
  ui:
    chapter_name: "Chapter "
delete_merged_file: true
new_session: yes
</code>```

答:
The margins are changed because by default the format is twoside. I fixed this by changing it to oneside. This was done by adding the following in index.Rmd

```<code>classoption: oneside
</code>```

in latex this is specified with:

```<code>\documentclass[oneside]{book}
</code>```

Body:
I am using bookdown package version 0.13 with R 3.6.0.

When I generate a pdf output, the even and odd pages have different margins. Even pages are shifted to the right and odd ones to the left (see picture below). Is this some type of feature? For example, for printing?

How can I disable this behavior?

I get the same margin differences when trying the minimal example provided in the official demo. The _bookdown.yml file has this content:

book_filename: "bookdown-demo"
language:
  ui:
    chapter_name: "Chapter "
delete_merged_file: true
new_session: yes

Body:
The margins are changed because by default the format is twoside. I fixed this by changing it to oneside. This was done by adding the following in index.Rmd

classoption: oneside

in latex this is specified with:

\documentclass[oneside]{book}


问:
Failed to convert a value of type java.lang.String to int?
I am trying to display the total expenses in a Text view but the application keeps giving me this error. The application uses Firebase and I had the getAmount() and setAmount() initiated as String since I only needed to display. It works as Strings but the amount doesn't get added to himself it just goes in front of the first amount, like a string. Anyone know what can I do to have my to application reed integer.

I'm using the getAmount() type and it is initiated as an integer.

Error is in the personal fragment inside the addValueEvent Listener
HELP!

Personal fragment where the addValueEventListener should display me the total amount.

```<code>import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class personalFragment extends Fragment {

    private FirebaseAuth mAuth;
    private String currentUserID;
    private RecyclerView recyclerView;
    private FirebaseRecyclerAdapter adapter;
    String [] listValue = {};
    private DatabaseReference mDatabase;
    private TextView expense_txt;

    @SuppressLint("SourceLockedOrientationActivity")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View myView = inflater.inflate(R.layout.fragment_personal, container, false);

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        String uid = user.getUid();
        mDatabase    = FirebaseDatabase.getInstance().getReference("Expenses").child(uid);
        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        recyclerView = myView.findViewById(R.id.recycler_expense);
        expense_txt = myView.findViewById(R.id.expenses_txt);
        getActivity().setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setStackFromEnd(true);
        layoutManager.setReverseLayout(true);
        recyclerView.setHasFixedSize(true);

        Query query = FirebaseDatabase.getInstance()
                .getReference("Expenses")
                .child(currentUserID)
                .limitToLast(100);

        FirebaseRecyclerOptions<PersonalExpenses> options =
                new FirebaseRecyclerOptions.Builder<PersonalExpenses>()
                        .setQuery(query, PersonalExpenses.class)
                        .build();

        adapter = new FirebaseRecyclerAdapter<PersonalExpenses, MyViewHolder>(options) {
            @Override
            protected void onBindViewHolder(final MyViewHolder holder, int position, PersonalExpenses personalExpenses) {

                holder.setDate(personalExpenses.getDate());
                holder.setDescription(personalExpenses.getDescription());
                holder.setAmount(personalExpenses.getAmount());
                holder.setType(personalExpenses.getType());
                //holder.setCurrency(personalExpenses.getCurrency());
            }

            @Override
            public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.expense_recycler, parent, false);
                return new MyViewHolder(view);
            }
        };
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

        final ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder target, int i) {

               int swipedPosition = target.getAdapterPosition();
               adapter.notifyDataSetChanged();

            }
        });
        helper.attachToRecyclerView(recyclerView);

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                int totalsum = 0;
                for(DataSnapshot mySnapshot: dataSnapshot.getChildren()){

                    PersonalExpenses personal = mySnapshot.getValue(PersonalExpenses.class);// Error appears for this line of code
                    totalsum += personal.getAmount();

                    String stTotalsum = String.valueOf((totalsum));

                    expense_txt.setText(stTotalsum);
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        return myView;
    }

    @Override
    public void onStart() {

        super.onStart();
        adapter.startListening();
    }

    @Override
    public void onStop() {

        super.onStop();
        adapter.stopListening();
    }

   public static class MyViewHolder extends RecyclerView.ViewHolder {

        private final View mView;

        public MyViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }

        protected void setDate(String date) {
            TextView mDate = mView.findViewById(R.id.date_income);
            mDate.setText(date);
        }

        protected void setType(String type) {
            TextView mType = mView.findViewById(R.id.type_txt);
            mType.setText(type);
        }

        protected void setDescription(String description) {
            TextView mNote = mView.findViewById(R.id.note_txt);
            mNote.setText(description);
        }

        protected void setAmount(int amount) {
            TextView mAmount = mView.findViewById(R.id.ammount_income);
            String strammount = String.valueOf(amount);
            mAmount.setText(strammount);
        }
        /*
       protected void setCurrency(String currency) {
           TextView mCurrency = mView.findViewById(R.id.ammount_income);
           mCurrency.setText(currency);
       }*/
    }
}
</code>```

Personal Expense data

```<code>public class PersonalExpenses {

    public String description;
    public int amount;
    public String date;
    public String type;
    public String currency;

    public PersonalExpenses() {}

    public PersonalExpenses(String description, int amount, String date, String type, String currency) {
        this.amount = amount;
        this.date = date;
        this.type = type;
        this.currency = currency;
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getAmount() { return amount; }

    public void setAmount(int amount) { this.amount = amount; }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getType() {return type;}

    public void setType(String type) { this.type = type; }

    public String getCurrency() { return currency; }

    public void setCurrency(String currency) { this.currency = currency; }

}
</code>```

This the error

```<code> com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertInteger(com.google.firebase:firebase-database@@19.2.1:363)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToPrimitive(com.google.firebase:firebase-database@@19.2.1:289)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.2.1:214)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database@@19.2.1:178)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(com.google.firebase:firebase-database@@19.2.1:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.1:592)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.1:562)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@19.2.1:432)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.2.1:231)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@19.2.1:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@19.2.1:203)
        at uk.brighton.ama75.project.personalFragment$3.onDataChange(personalFragment.java:118)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

Here is the database from Firebase

This is how I am storing the data in the database

```<code>expenses.setDescription(mDescription.getText().toString().trim());
                expenses.setAmount(Integer.valueOf(mAmount.getText().toString().trim()));
                expenses.setDate(mDate.getText().toString().trim());
                expenses.setType(text.trim());
                mDatabase.push().setValue(expenses);
</code>```

答:
I guess your database is sending getAmount in String format.
Use</p>

```<code>int totalsum = 0;
for(DataSnapshot mySnapshot: dataSnapshot.getChildren()) {
PersonalExpenses personal = mySnapshot.getValue(PersonalExpenses.class);
totalsum += Integer.parseInt(personal.getAmount());
}
String stTotalsum = String.valueOf(totalsum);
expense_txt.setText(stTotalsum);
</code>```

Body:
I am trying to display the total expenses in a Text view but the application keeps giving me this error. The application uses Firebase and I had the getAmount() and setAmount() initiated as String since I only needed to display. It works as Strings but the amount doesn't get added to himself it just goes in front of the first amount, like a string. Anyone know what can I do to have my to application reed integer.

I'm using the getAmount() type and it is initiated as an integer.

Error is in the personal fragment inside the addValueEvent Listener
HELP!

Personal fragment where the addValueEventListener should display me the total amount.

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class personalFragment extends Fragment {

    private FirebaseAuth mAuth;
    private String currentUserID;
    private RecyclerView recyclerView;
    private FirebaseRecyclerAdapter adapter;
    String [] listValue = {};
    private DatabaseReference mDatabase;
    private TextView expense_txt;

    @SuppressLint("SourceLockedOrientationActivity")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View myView = inflater.inflate(R.layout.fragment_personal, container, false);

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        String uid = user.getUid();
        mDatabase    = FirebaseDatabase.getInstance().getReference("Expenses").child(uid);
        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        recyclerView = myView.findViewById(R.id.recycler_expense);
        expense_txt = myView.findViewById(R.id.expenses_txt);
        getActivity().setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setStackFromEnd(true);
        layoutManager.setReverseLayout(true);
        recyclerView.setHasFixedSize(true);

        Query query = FirebaseDatabase.getInstance()
                .getReference("Expenses")
                .child(currentUserID)
                .limitToLast(100);

        FirebaseRecyclerOptions<PersonalExpenses> options =
                new FirebaseRecyclerOptions.Builder<PersonalExpenses>()
                        .setQuery(query, PersonalExpenses.class)
                        .build();

        adapter = new FirebaseRecyclerAdapter<PersonalExpenses, MyViewHolder>(options) {
            @Override
            protected void onBindViewHolder(final MyViewHolder holder, int position, PersonalExpenses personalExpenses) {

                holder.setDate(personalExpenses.getDate());
                holder.setDescription(personalExpenses.getDescription());
                holder.setAmount(personalExpenses.getAmount());
                holder.setType(personalExpenses.getType());
                //holder.setCurrency(personalExpenses.getCurrency());
            }

            @Override
            public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.expense_recycler, parent, false);
                return new MyViewHolder(view);
            }
        };
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

        final ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder target, int i) {

               int swipedPosition = target.getAdapterPosition();
               adapter.notifyDataSetChanged();

            }
        });
        helper.attachToRecyclerView(recyclerView);

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                int totalsum = 0;
                for(DataSnapshot mySnapshot: dataSnapshot.getChildren()){

                    PersonalExpenses personal = mySnapshot.getValue(PersonalExpenses.class);// Error appears for this line of code
                    totalsum += personal.getAmount();

                    String stTotalsum = String.valueOf((totalsum));

                    expense_txt.setText(stTotalsum);
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        return myView;
    }

    @Override
    public void onStart() {

        super.onStart();
        adapter.startListening();
    }

    @Override
    public void onStop() {

        super.onStop();
        adapter.stopListening();
    }

   public static class MyViewHolder extends RecyclerView.ViewHolder {

        private final View mView;

        public MyViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }

        protected void setDate(String date) {
            TextView mDate = mView.findViewById(R.id.date_income);
            mDate.setText(date);
        }

        protected void setType(String type) {
            TextView mType = mView.findViewById(R.id.type_txt);
            mType.setText(type);
        }

        protected void setDescription(String description) {
            TextView mNote = mView.findViewById(R.id.note_txt);
            mNote.setText(description);
        }

        protected void setAmount(int amount) {
            TextView mAmount = mView.findViewById(R.id.ammount_income);
            String strammount = String.valueOf(amount);
            mAmount.setText(strammount);
        }
        /*
       protected void setCurrency(String currency) {
           TextView mCurrency = mView.findViewById(R.id.ammount_income);
           mCurrency.setText(currency);
       }*/
    }
}

Personal Expense data

public class PersonalExpenses {

    public String description;
    public int amount;
    public String date;
    public String type;
    public String currency;

    public PersonalExpenses() {}

    public PersonalExpenses(String description, int amount, String date, String type, String currency) {
        this.amount = amount;
        this.date = date;
        this.type = type;
        this.currency = currency;
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getAmount() { return amount; }

    public void setAmount(int amount) { this.amount = amount; }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getType() {return type;}

    public void setType(String type) { this.type = type; }

    public String getCurrency() { return currency; }

    public void setCurrency(String currency) { this.currency = currency; }

}

This the error

 com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertInteger(com.google.firebase:firebase-database@@19.2.1:363)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToPrimitive(com.google.firebase:firebase-database@@19.2.1:289)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.2.1:214)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database@@19.2.1:178)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(com.google.firebase:firebase-database@@19.2.1:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.1:592)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.1:562)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@19.2.1:432)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.2.1:231)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@19.2.1:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@19.2.1:203)
        at uk.brighton.ama75.project.personalFragment$3.onDataChange(personalFragment.java:118)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Here is the database from Firebase

This is how I am storing the data in the database

expenses.setDescription(mDescription.getText().toString().trim());
                expenses.setAmount(Integer.valueOf(mAmount.getText().toString().trim()));
                expenses.setDate(mDate.getText().toString().trim());
                expenses.setType(text.trim());
                mDatabase.push().setValue(expenses);

Body:
I guess your database is sending getAmount in String format.
Use

int totalsum = 0;
for(DataSnapshot mySnapshot: dataSnapshot.getChildren()) {
PersonalExpenses personal = mySnapshot.getValue(PersonalExpenses.class);
totalsum += Integer.parseInt(personal.getAmount());
}
String stTotalsum = String.valueOf(totalsum);
expense_txt.setText(stTotalsum);


问:
how to parse xml with php
I am trying to read a weather feed from Yahoo to my site.
Using the code below I was able to print the xml.
What I really want to achieve now is to put the temperature and image in two different variables</p>

```<code> $zipCode = "44418";
 $url = "http://weather.yahooapis.com/forecastrss";
 $zip = "?w=$zipCode";
 $fullUrl = $url . $zip.'&u=c';
 $curlObject = curl_init();
 curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
 curl_setopt($curlObject,CURLOPT_HEADER,false);
 curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
 $returnYahooWeather = curl_exec($curlObject);
 curl_close($curlObject);
 print "yahooWeather". $returnYahooWeather;

//$temperature
//$image
</code>```

答:
You should go ahead and use simplexml or DOM to parse the XML and then you can iterate over the results. With SimpleXML this looks like this:</p>

```<code>$zipCode = "44418";
$url = "http://weather.yahooapis.com/forecastrss";
$zip = "?w=$zipCode";
$fullUrl = $url . $zip.'&u=c';
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
curl_setopt($curlObject,CURLOPT_HEADER,false);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
$returnYahooWeather = curl_exec($curlObject);
curl_close($curlObject);
//print "here". $returnYahooWeather;

$xmlobj=simplexml_load_string($returnYahooWeather);

$res = $xmlobj->xpath("//yweather:condition");
$tmp = false;
while(list( , $node) = each($res)) {
  $tmp = $node;
 }
$attribs = $tmp->attributes();
print "Temperature [".$attribs['temp']."]";
</code>```

Title: how to parse xml with php

Body:
I am trying to read a weather feed from Yahoo to my site.
Using the code below I was able to print the xml.
What I really want to achieve now is to put the temperature and image in two different variables

 $zipCode = "44418";
 $url = "http://weather.yahooapis.com/forecastrss";
 $zip = "?w=$zipCode";
 $fullUrl = $url . $zip.'&u=c';
 $curlObject = curl_init();
 curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
 curl_setopt($curlObject,CURLOPT_HEADER,false);
 curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
 $returnYahooWeather = curl_exec($curlObject);
 curl_close($curlObject);
 print "yahooWeather". $returnYahooWeather;

//$temperature
//$image

Body:
You should go ahead and use simplexml or DOM to parse the XML and then you can iterate over the results. With SimpleXML this looks like this:

$zipCode = "44418";
$url = "http://weather.yahooapis.com/forecastrss";
$zip = "?w=$zipCode";
$fullUrl = $url . $zip.'&u=c';
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
curl_setopt($curlObject,CURLOPT_HEADER,false);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
$returnYahooWeather = curl_exec($curlObject);
curl_close($curlObject);
//print "here". $returnYahooWeather;

$xmlobj=simplexml_load_string($returnYahooWeather);

$res = $xmlobj->xpath("//yweather:condition");
$tmp = false;
while(list( , $node) = each($res)) {
  $tmp = $node;
 }
$attribs = $tmp->attributes();
print "Temperature [".$attribs['temp']."]";


问:
From n x k DataFrame, generate a (n over 2) x 2k DataFrame of all pairs of rows
Given a pandas DataFrame x of dimensions n x k, how can we efficiently generate a DataFrame y of dimensions (n over 2) x 2k, whose rows are all possible combinations of rows pairs of rows from x?
For example, if x is

```<code>[[1 11],
 [2,22],
 [3,33],
 [4,44]]
</code>```

then y should be

```<code>[[1,11,2,22],
 [1,11,3,33],
 [1,11,4,44],
 [2,22,3,33],
 [2,22,4,44],
 [3,33,4,44]]
</code>```

Body:
Given a pandas DataFrame x of dimensions n x k, how can we efficiently generate a DataFrame y of dimensions (n over 2) x 2k, whose rows are all possible combinations of rows pairs of rows from x?
For example, if x is

[[1 11],
 [2,22],
 [3,33],
 [4,44]]

then y should be

[[1,11,2,22],
 [1,11,3,33],
 [1,11,4,44],
 [2,22,3,33],
 [2,22,4,44],
 [3,33,4,44]]

Body:
We can try combinations

from itertools import combinations
[*map(lambda x : sum(x,[]),combinations(l,r=2))]
Out[80]:
[[1, 11, 2, 22],
 [1, 11, 3, 33],
 [1, 11, 4, 44],
 [2, 22, 3, 33],
 [2, 22, 4, 44],
 [3, 33, 4, 44]]


问:
node js express, req.body returns nothing
I have this web server setup with express, everything works fine except the req.body returns nothing it seems. I don't get any error it just doesn't do anything. The console.log(req.body) doesn't do anything. When I check the console I see nothing. But the rest of the application works ok.

What am I missing?

server.js file is below

```<code>if (process.env.NODE_ENV !== "production") {
    require("dotenv").config();
}

const clientId = process.env.client_id;
const clientSecret = process.env.client_secret;
const refreshToken = process.env.refresh_token;

const date = new Date();
date.setDate(date.getDate() - 2);

const express = require("express");
const app = express();

app.use(express.json());
app.use(express.static("public"));

app.post("/alerts", async (req, res) => {
    console.log(req.body)
    const alertsUrl = `https://www.g2smart.com/g2smart/api/alert?range=last7Days&cpo=${req.body.selection}&status=Opened&limit=100&page=1`
    const axios = require("axios");
    const oauth = require("axios-oauth-client");

    const getRefreshToken = oauth.client(axios.create(), {
        url: "https://www.g2smart.com/g2smart/api/oauth2/token",
        grant_type: "refresh_token",
        client_id: `${clientId}`,
        client_secret: `${clientSecret}`,
        refresh_token: `${refreshToken}`,
    });

    const auth = await getRefreshToken();

    axios({
        url: alertsUrl
            ,
        headers: {
            accept: "application/json, text/plain, */*",
            authorization: `Bearer ${auth["access_token"]}`,
        },
        responseType: "json",
    }).then((data) => res.json(data.data.items));
});

app.listen(process.env.port || 3000);

console.log("Running at Port 3000");
</code>```

and here is the script.js below, where i have my fetch function.

```<code>const selectElement = document.querySelector('[data-cpo-select]')
const cpo = {
    france: "total_fr_hpc",
    netherlands: "total_nl_hpc",
    te61: "te61"}

selectElement.addEventListener("change", (event) => {
    const selection = event.target.value
    fetch("/alerts", {
        method: "POST",
        headers: {
            "Content-Type": "application",
            "Accept": "application/json",
        },
        body: JSON.stringify({
            selection: cpo[selection]
        })
    })
        .then((res) => res.json())
        .then((data) => {
            setAlertsData(data);
        });

    const alertTypeElement = document.querySelector("[data-alert-type]");
    const locationElement = document.querySelector("[data-location]");
    const statusElement = document.querySelector("[data-status]");
    const severityElement = document.querySelector("[data-severity]");
    const chargePointElement = document.querySelector("[data-charge-point]");

    function setAlertsData(data) {
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        const today = new Date();
        locationElement.textContent = data["0"]["locationName"];
        severityElement.textContent = `${new Date(data["0"]["openDate"]).toLocaleString()} ${data["0"]["severity"]}`
        alertTypeElement.textContent = data["0"]["alertType"];
        chargePointElement.textContent = data["0"]["equipmentId"].slice(9,);
        statusElement.textContent = data["0"]["status"];

        console.log(new Date(data["0"]["openDate"]).toLocaleString(options))
    }
})
</code>```

答:
```<code>let response = await fetch('http://*******', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    });
</code>```

Body:
I have this web server setup with express, everything works fine except the req.body returns nothing it seems. I don't get any error it just doesn't do anything. The console.log(req.body) doesn't do anything. When I check the console I see nothing. But the rest of the application works ok.

What am I missing?

server.js file is below

if (process.env.NODE_ENV !== "production") {
    require("dotenv").config();
}

const clientId = process.env.client_id;
const clientSecret = process.env.client_secret;
const refreshToken = process.env.refresh_token;

const date = new Date();
date.setDate(date.getDate() - 2);

const express = require("express");
const app = express();

app.use(express.json());
app.use(express.static("public"));

app.post("/alerts", async (req, res) => {
    console.log(req.body)
    const alertsUrl = `https://www.g2smart.com/g2smart/api/alert?range=last7Days&cpo=${req.body.selection}&status=Opened&limit=100&page=1`
    const axios = require("axios");
    const oauth = require("axios-oauth-client");

    const getRefreshToken = oauth.client(axios.create(), {
        url: "https://www.g2smart.com/g2smart/api/oauth2/token",
        grant_type: "refresh_token",
        client_id: `${clientId}`,
        client_secret: `${clientSecret}`,
        refresh_token: `${refreshToken}`,
    });

    const auth = await getRefreshToken();

    axios({
        url: alertsUrl
            ,
        headers: {
            accept: "application/json, text/plain, */*",
            authorization: `Bearer ${auth["access_token"]}`,
        },
        responseType: "json",
    }).then((data) => res.json(data.data.items));
});

app.listen(process.env.port || 3000);

console.log("Running at Port 3000");

and here is the script.js below, where i have my fetch function.

const selectElement = document.querySelector('[data-cpo-select]')
const cpo = {
    france: "total_fr_hpc",
    netherlands: "total_nl_hpc",
    te61: "te61"}

selectElement.addEventListener("change", (event) => {
    const selection = event.target.value
    fetch("/alerts", {
        method: "POST",
        headers: {
            "Content-Type": "application",
            "Accept": "application/json",
        },
        body: JSON.stringify({
            selection: cpo[selection]
        })
    })
        .then((res) => res.json())
        .then((data) => {
            setAlertsData(data);
        });

    const alertTypeElement = document.querySelector("[data-alert-type]");
    const locationElement = document.querySelector("[data-location]");
    const statusElement = document.querySelector("[data-status]");
    const severityElement = document.querySelector("[data-severity]");
    const chargePointElement = document.querySelector("[data-charge-point]");

    function setAlertsData(data) {
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        const today = new Date();
        locationElement.textContent = data["0"]["locationName"];
        severityElement.textContent = `${new Date(data["0"]["openDate"]).toLocaleString()} ${data["0"]["severity"]}`
        alertTypeElement.textContent = data["0"]["alertType"];
        chargePointElement.textContent = data["0"]["equipmentId"].slice(9,);
        statusElement.textContent = data["0"]["status"];

        console.log(new Date(data["0"]["openDate"]).toLocaleString(options))
    }
})


问:
Firebase Storage: String does not match format 'base64': Invalid character found
I'm working on a react-native and I need to upload an image to Firebase using Firebase Storage. I'm using react-native-image-picker to select the image from the phone which gives me the base64 encoded data.

When I try to upload the image to Firebase it gives me the error Firebase Storage: String does not match format 'base64': Invalid character found but I already checked if the string is a valid base64 string with regex and it is!

I already read a few answers from here but I tried all that. Here's my code:

```<code>function uploadImage(image){
  const user = getCurrentUser();
  const refImage = app.storage().ref(`profileImages/${user.uid}`);

  refImage.putString(image, 'base64').then(() => {
    console.log('Image uploaded');
  });
}
</code>```

The image picker:

```<code>ImagePicker.showImagePicker(ImageOptions, (response) => {
  if (response.didCancel) {
    console.log('User cancelled image picker');
  }
  else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  }
  else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  }
  else {
    uploadImage(response.data);
  }
});
</code>```

答:
I use split().</p>

```<code>function uploadImage(image){
  const user = getCurrentUser();
  const refImage = app.storage().ref(`profileImages/${user.uid}`);

  refImage.putString(image.split(',')[1], 'base64').then(() => {
    console.log('Image uploaded');
  });
}
</code>```

Body:
I'm working on a react-native and I need to upload an image to Firebase using Firebase Storage. I'm using react-native-image-picker to select the image from the phone which gives me the base64 encoded data.

When I try to upload the image to Firebase it gives me the error Firebase Storage: String does not match format 'base64': Invalid character found but I already checked if the string is a valid base64 string with regex and it is!

I already read a few answers from here but I tried all that. Here's my code:

function uploadImage(image){
  const user = getCurrentUser();
  const refImage = app.storage().ref(`profileImages/${user.uid}`);

  refImage.putString(image, 'base64').then(() => {
    console.log('Image uploaded');
  });
}

The image picker:

ImagePicker.showImagePicker(ImageOptions, (response) => {
  if (response.didCancel) {
    console.log('User cancelled image picker');
  }
  else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  }
  else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  }
  else {
    uploadImage(response.data);
  }
});

Body:
I use split().

function uploadImage(image){
  const user = getCurrentUser();
  const refImage = app.storage().ref(`profileImages/${user.uid}`);

  refImage.putString(image.split(',')[1], 'base64').then(() => {
    console.log('Image uploaded');
  });
}


问:
Dart: checking if an object implements interface
I have the following classes and interfaces:

class Place extends Entity
    with ChangeNotifier, FieldGetters
    implements Scannable, Likable {
// ...some stuff
}
```

<pre class="lang-dart prettyprint-override"><code>
abstract class Likable {
// ... some stuff
}

</code>```

Entity is just a base class for other classes.

So, the problem is that I want to check whether the object that implements the Likable interface is of class Place or not. To do so, I use the following code:

logger.i('likable is ${like.likable.runtimeType}');
logger.i('likable is Place: ${like.likable is Place}');
```

<p>The first line works as expected and shows the following output:</p>

```I/flutter ( 1635): [38;5;12m┌───────────────────────────────────────────────────────────────────────────────[0m
I/flutter ( 1635): [38;5;12m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄[0m
I/flutter ( 1635): [38;5;12m│  likable is Place[0m
I/flutter ( 1635): [38;5;12m└───────────────────────────────────────────────────────────────────────────────[0m
```

<p>However, the second line of code acts weird and shows the following:</p>

```I/flutter ( 1635): [38;5;12m┌───────────────────────────────────────────────────────────────────────────────[0m
I/flutter ( 1635): [38;5;12m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄[0m
I/flutter ( 1635): [38;5;12m│  likable is Place: false[0m
I/flutter ( 1635): [38;5;12m└───────────────────────────────────────────────────────────────────────────────[0m
```

The official documentation suggests that the interface inheritance can be checked via is keyword. I am confused. How can I check the interface inheritance in this case?

Dart: v2.8.1

Flutter: v1.17.0

答:
In Dart a class can only inherit from one superclass (for Place it is Entity) and implement from multiple (i.e. grab functions from those classes).

As far as I could understand from your description, you are doing something like this (you can run it here).

```<code>class Person extends LivingCreature implements Mammal{
  final _name;
  void _toDrinkMilk(){
    print("I drink milk as a person!");
  }
  Person(this._name);
}

class Mammal {
  void _toDrinkMilk(){
    print("I drink milk!");
  }
}

class LivingCreature {

  void _toLive(){
    print("I live!");
  }
}

void main() {
  final bob = Person('Bob');
  final mammal = Mammal();
  print(mammal is LivingCreature);
  print(bob.runtimeType);
  bob._toDrinkMilk();
  bob._toLive();
  print('Bob is mammal: ${bob is Mammal}');
  print('Mammal is Person: ${mammal is Person}');
}
</code>```

And this code yields following output:

```<code>true
Person
I drink milk as a person!
I live!
Bob is mammal: true
Mammal is Person: false
</code>```

So, now let us talk about what just happens in your case, your like.likable should be a Likable abstract class (I assume). Place in the meantime implements Likable, so it should implement all methods of Likable.

Now, you are trying to ask Dart is the type of your Likable (which does not extend or implement anything) is Place, which is false as given in the log.

If it has been class Likable extends Place {... then in the log you would have like.likable is Place be equal to true

For more on extends, implements, with you can refer to the Dart docs

P.S. I did not make Mammal abstract to instantiate it quickly in print()

Hope it helps!

Body:
I have the following classes and interfaces:

class Place extends Entity
    with ChangeNotifier, FieldGetters
    implements Scannable, Likable {
// ...some stuff
}

abstract class Likable {
// ... some stuff
}

Entity is just a base class for other classes.

So, the problem is that I want to check whether the object that implements the Likable interface is of class Place or not. To do so, I use the following code:

logger.i('likable is ${like.likable.runtimeType}');
logger.i('likable is Place: ${like.likable is Place}');

The first line works as expected and shows the following output:

I/flutter ( 1635): [38;5;12m┌───────────────────────────────────────────────────────────────────────────────[0m
I/flutter ( 1635): [38;5;12m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄[0m
I/flutter ( 1635): [38;5;12m│  likable is Place[0m
I/flutter ( 1635): [38;5;12m└───────────────────────────────────────────────────────────────────────────────[0m

However, the second line of code acts weird and shows the following:

I/flutter ( 1635): [38;5;12m┌───────────────────────────────────────────────────────────────────────────────[0m
I/flutter ( 1635): [38;5;12m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄[0m
I/flutter ( 1635): [38;5;12m│  likable is Place: false[0m
I/flutter ( 1635): [38;5;12m└───────────────────────────────────────────────────────────────────────────────[0m

The official documentation suggests that the interface inheritance can be checked via is keyword. I am confused. How can I check the interface inheritance in this case?

Dart: v2.8.1

Flutter: v1.17.0

Body:
In Dart a class can only inherit from one superclass (for Place it is Entity) and implement from multiple (i.e. grab functions from those classes).

As far as I could understand from your description, you are doing something like this (you can run it here).

class Person extends LivingCreature implements Mammal{
  final _name;
  void _toDrinkMilk(){
    print("I drink milk as a person!");
  }
  Person(this._name);
}

class Mammal {
  void _toDrinkMilk(){
    print("I drink milk!");
  }
}

class LivingCreature {

  void _toLive(){
    print("I live!");
  }
}

void main() {
  final bob = Person('Bob');
  final mammal = Mammal();
  print(mammal is LivingCreature);
  print(bob.runtimeType);
  bob._toDrinkMilk();
  bob._toLive();
  print('Bob is mammal: ${bob is Mammal}');
  print('Mammal is Person: ${mammal is Person}');
}

And this code yields following output:

true
Person
I drink milk as a person!
I live!
Bob is mammal: true
Mammal is Person: false

So, now let us talk about what just happens in your case, your like.likable should be a Likable abstract class (I assume). Place in the meantime implements Likable, so it should implement all methods of Likable.

Now, you are trying to ask Dart is the type of your Likable (which does not extend or implement anything) is Place, which is false as given in the log.

If it has been class Likable extends Place {... then in the log you would have like.likable is Place be equal to true

For more on extends, implements, with you can refer to the Dart docs

P.S. I did not make Mammal abstract to instantiate it quickly in print()

Hope it helps!


问:
React native interval state not updating
interval function in state change not working help me please.

state not change

```<code>function Home({ route, navigation }) {
const [ marker, setMarker ] = useState(0);

_stropeText = () => {
  if (marker == 0){
   setMarker(marker => 1);
  } else {
   setMarker(marker => 0);
  }
}

React.useEffect(() => {
    setLoading(true);
    const unsubscribe = navigation.addListener('focus', () => {
      setInterval(_stropeText, 500);
    });
    return () => {  };
  }, [navigation]);
}
</code>```

https://snack.expo.io/Hbedd4HVh

答:
If you are using useState hooks, the set function accepts one parameter, the value you want to set.

```<code>_stropeText = () => {
  if (marker == 0){
   setMarker(1);
  } else {
   setMarker(0);
  }
}
setInterval(_stropeText, 500);
</code>```

Update:

according to the snack you provided, the setLocation function is asynchronous, so you are trying to display the new value of location before it has been set. You need an effect that responds to the change in value of the location variable to display the new value. E.g.

```<code>React.useEffect(() => {
  alert(location)
}, [location])
</code>```

Body:
interval function in state change not working help me please.

state not change

function Home({ route, navigation }) {
const [ marker, setMarker ] = useState(0);

_stropeText = () => {
  if (marker == 0){
   setMarker(marker => 1);
  } else {
   setMarker(marker => 0);
  }
}

React.useEffect(() => {
    setLoading(true);
    const unsubscribe = navigation.addListener('focus', () => {
      setInterval(_stropeText, 500);
    });
    return () => {  };
  }, [navigation]);
}

https://snack.expo.io/Hbedd4HVh

Body:
If you are using useState hooks, the set function accepts one parameter, the value you want to set.

_stropeText = () => {
  if (marker == 0){
   setMarker(1);
  } else {
   setMarker(0);
  }
}
setInterval(_stropeText, 500);

Update:

according to the snack you provided, the setLocation function is asynchronous, so you are trying to display the new value of location before it has been set. You need an effect that responds to the change in value of the location variable to display the new value. E.g.

React.useEffect(() => {
  alert(location)
}, [location])


问:
Organising multiple columns into a row based on another column
Absolute R newbie, and I know this should be simple, but I have spent 2 hours without any success.

How can I convert my dataframe from this (First 6 lines of dataframe)

```<code>Symbol  AF  wave
CUX1    0.0975  1
CUX1    0.0337  3
CUX1    0.0217  4
LUC7L2  0.0488  1
LUC7L2  0.0515  3
LUC7L2  0.0422  4
</code>```

to something like this?

```<code>Symbol  AF  wave 1  wave 2  wave 3  wave 4
CUX1    0.0975  0.0975  NA  0.0337  0.0217
LUC7L2  0.0337  0.0488  NA  0.0515  0.0422
</code>```

Hi Akron,

with your advice I get something like this:

```<code>Symbol  AF  wave 1  wave 2  wave 3  wave 4
CUX1    0.0975  0.0975  NA  NA  NA
LUC7L2  0.0337  0.0337  NA  NA  NA
CUX1    0.0975  NA  0.0337  NA  NA
LUC7L2  0.0337  NA  0.0515  NA  NA
CUX1    0.0975  NA  NA  0.082   NA
LUC7L2  0.0337  NA  NA  0.0781  NA
</code>```

So almost there...

答:
We need to first complete the missing 'wave' and then do the pivot_wider to reshape from 'long' to 'wide' format

```<code>library(dplyr)
library(tidyr)
library(stringr)
library(data.table)
df1 %>%
    mutate(wave = str_c('wave', wave)) %>%
    complete(wave = str_c('wave', 1:4)) %>%
    mutate(rn = rowid(wave)) %>%
    pivot_wider(names_from = wave, values_from = AF) %>%
    filter(!is.na(Symbol)) %>%
    select(-rn)
# A tibble: 2 x 5
#  Symbol  wave1 wave2  wave3  wave4
#  <chr>   <dbl> <dbl>  <dbl>  <dbl>
#1 CUX1   0.0975    NA 0.0337 0.0217
#2 LUC7L2 0.0488    NA 0.0515 0.0422
</code>```

data

```<code>df1 <- structure(list(Symbol = c("CUX1", "CUX1", "CUX1", "LUC7L2", "LUC7L2",
"LUC7L2"), AF = c(0.0975, 0.0337, 0.0217, 0.0488, 0.0515, 0.0422
), wave = c(1L, 3L, 4L, 1L, 3L, 4L)), class = "data.frame", row.names = c(NA,
-6L))
</code>```

Body:
Absolute R newbie, and I know this should be simple, but I have spent 2 hours without any success.

How can I convert my dataframe from this (First 6 lines of dataframe)

Symbol  AF  wave
CUX1    0.0975  1
CUX1    0.0337  3
CUX1    0.0217  4
LUC7L2  0.0488  1
LUC7L2  0.0515  3
LUC7L2  0.0422  4

to something like this?

Symbol  AF  wave 1  wave 2  wave 3  wave 4
CUX1    0.0975  0.0975  NA  0.0337  0.0217
LUC7L2  0.0337  0.0488  NA  0.0515  0.0422

Hi Akron,

with your advice I get something like this:

Symbol  AF  wave 1  wave 2  wave 3  wave 4
CUX1    0.0975  0.0975  NA  NA  NA
LUC7L2  0.0337  0.0337  NA  NA  NA
CUX1    0.0975  NA  0.0337  NA  NA
LUC7L2  0.0337  NA  0.0515  NA  NA
CUX1    0.0975  NA  NA  0.082   NA
LUC7L2  0.0337  NA  NA  0.0781  NA

So almost there...

Body:
We need to first complete the missing 'wave' and then do the pivot_wider to reshape from 'long' to 'wide' format

library(dplyr)
library(tidyr)
library(stringr)
library(data.table)
df1 %>%
    mutate(wave = str_c('wave', wave)) %>%
    complete(wave = str_c('wave', 1:4)) %>%
    mutate(rn = rowid(wave)) %>%
    pivot_wider(names_from = wave, values_from = AF) %>%
    filter(!is.na(Symbol)) %>%
    select(-rn)
# A tibble: 2 x 5
#  Symbol  wave1 wave2  wave3  wave4
#  <chr>   <dbl> <dbl>  <dbl>  <dbl>
#1 CUX1   0.0975    NA 0.0337 0.0217
#2 LUC7L2 0.0488    NA 0.0515 0.0422

data

df1 <- structure(list(Symbol = c("CUX1", "CUX1", "CUX1", "LUC7L2", "LUC7L2",
"LUC7L2"), AF = c(0.0975, 0.0337, 0.0217, 0.0488, 0.0515, 0.0422
), wave = c(1L, 3L, 4L, 1L, 3L, 4L)), class = "data.frame", row.names = c(NA,
-6L))


问:
What does this code mean: new Action(()=>{})
I found this code:

```<code>new Action(()=>{})
</code>```

I would like to understand what the code between parenthesis mean

答:
Let me break this down:

Action - this is the type of a function. (Yes, you can treat a function like data);

() => {} - This is a lambda expression. In this case, it defines a function that takes no parameters, returns nothing, and does nothing.

Consider the following code:

```<code>void Main()
{
   Action action = new Action(doNothing);

   // Now we can call the function to do nothing
   action();
}

void doNothing()
{
}
</code>```

We could re-write it as

```<code>void Main()
{
   Action action = new Action(() => {});

   // Now we can call the function to do nothing
   action();
}
</code>```

It does the same thing.

Body:
I found this code:

new Action(()=>{})

I would like to understand what the code between parenthesis mean

Body:
Let me break this down:

Action - this is the type of a function. (Yes, you can treat a function like data);

() => {} - This is a lambda expression. In this case, it defines a function that takes no parameters, returns nothing, and does nothing.

Consider the following code:

void Main()
{
   Action action = new Action(doNothing);

   // Now we can call the function to do nothing
   action();
}

void doNothing()
{
}

We could re-write it as

void Main()
{
   Action action = new Action(() => {});

   // Now we can call the function to do nothing
   action();
}

It does the same thing.


问:
How to run multiple threads created by loop simultaneous using boost.thread?
I'm using learning the basic of boost.thread. So far, I can create each thread one by one manually to let them run at the same time. However, when creating by loop, it runs sequentially not concurrency anymore.</p>

```<code>#include <iostream>
#include <boost/thread.hpp>
void workerFunc()
{
  boost::posix_time::seconds workTime(3);
  std::cout << "Worker: Running" << '\n';
  boost::this_thread::sleep(workTime);
  std::cout<< "Worker: Finished" << '\n';
}

int main()
{
  std::cout << "main: startup" << '\n';
  boost::thread workerThread(workerFunc);
  std::cout << "main: waiting for thread" << '\n';
  //these are ok
  boost::thread t(workerFunc), t2(workerFunc), t3(workerFunc), t4(workerFunc);
  t.join();
  t2.join();
  t3.join();
  t4.join();
  //these are not
  for (int i = 0; i < 2; ++i)
    {
      boost::thread z(workerFunc);
      z.join();
    }
  std::cout << "main:done" << '\n';
  return 0;
}
</code>```

答:
Ok I found the answer through the problem of someone else, as well as learn their problem:

How to make boost::thread_group execute a fixed number of parallel threads

Body:
I'm using learning the basic of boost.thread. So far, I can create each thread one by one manually to let them run at the same time. However, when creating by loop, it runs sequentially not concurrency anymore.

#include <iostream>
#include <boost/thread.hpp>
void workerFunc()
{
  boost::posix_time::seconds workTime(3);
  std::cout << "Worker: Running" << '\n';
  boost::this_thread::sleep(workTime);
  std::cout<< "Worker: Finished" << '\n';
}

int main()
{
  std::cout << "main: startup" << '\n';
  boost::thread workerThread(workerFunc);
  std::cout << "main: waiting for thread" << '\n';
  //these are ok
  boost::thread t(workerFunc), t2(workerFunc), t3(workerFunc), t4(workerFunc);
  t.join();
  t2.join();
  t3.join();
  t4.join();
  //these are not
  for (int i = 0; i < 2; ++i)
    {
      boost::thread z(workerFunc);
      z.join();
    }
  std::cout << "main:done" << '\n';
  return 0;
}


问:
How to get a result from fragment using Navigation Architecture Component?
Let's say that we have two fragments: MainFragment and SelectionFragment. The second one is build for selecting some object, e.g. an integer. There are different approaches in receiving result from this second fragment like callbacks, buses etc.

Now, if we decide to use Navigation Architecture Component in order to navigate to second fragment we can use this code:

```<code>NavHostFragment.findNavController(this).navigate(R.id.action_selection, bundle)
</code>```

where bundle is an instance of Bundle (of course). As you can see there is no access to SelectionFragment where we could put a callback. The question is, how to receive a result with Navigation Architecture Component?

答:
with a little improvement of @LeHaine 's answer, you can use these methods for navigation 2.3.0-alpha02 and above

```<code>fun <T> Fragment.getNavigationResult(key: String) =
    findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<T>(key)

fun <T> Fragment.setNavigationResult(result: T, key: String) {
    findNavController().previousBackStackEntry?.savedStateHandle?.set(key, result)
}
</code>```

Body:
Let's say that we have two fragments: MainFragment and SelectionFragment. The second one is build for selecting some object, e.g. an integer. There are different approaches in receiving result from this second fragment like callbacks, buses etc.

Now, if we decide to use Navigation Architecture Component in order to navigate to second fragment we can use this code:

NavHostFragment.findNavController(this).navigate(R.id.action_selection, bundle)

where bundle is an instance of Bundle (of course). As you can see there is no access to SelectionFragment where we could put a callback. The question is, how to receive a result with Navigation Architecture Component?

Body:
with a little improvement of @LeHaine 's answer, you can use these methods for navigation 2.3.0-alpha02 and above

fun <T> Fragment.getNavigationResult(key: String) =
    findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<T>(key)

fun <T> Fragment.setNavigationResult(result: T, key: String) {
    findNavController().previousBackStackEntry?.savedStateHandle?.set(key, result)
}


问:
Merging two sorted linked list in c++
I am trying to code an algo to merge two sorted linked lists. I am not able to understand why this doesn't give me the correct answer. Why does the answer does not have memory of the earlier assignments, it just returns the most recent assignment being done. (i.e a linked list of length 1). I am creating an initial node called cur, then I am adding nexts to it depending on the values of l1 and l2 and doing cur.next every time. Thanks

```<code>struct ListNode {
  int val;
  ListNode* next;
  ListNode() : val(0), next(nullptr){};
  ListNode(int x) : val(x), next(nullptr){};
  ListNode(int x, ListNode* next) : val(x), next(next){};
};

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
  ListNode cur;
  ListNode* ans = new ListNode;
  ans = &cur;

  while (l1 && l2) {
    if (l1->val < l2->val) {
      ListNode temp(l1->val);
      cur.next = &temp;
      l1 = l1->next;
      cur = *(cur.next);
    } else {
      ListNode temp(l2->val);
      cur.next = &temp;
      l2 = l2->next;
      cur = *(cur.next);
    }
  }
  if (l1) {
    cur.next = (l1);
  }
  if (l2) {
    cur.next = (l2);
  }
  return ans->next;
};
</code>```

答:
Lets walk through the code you have inside the if blocks to try and understand what is going on.

```<code>ListNode temp(l1->val);
cur.next = &temp;
l1 = l1->next;
cur = *(cur.next);
</code>```

Line #1 creates a new ListNode variable called temp in a newly allocated memory location. Lets say the address of this memory location is X123. At this memory location, temp.val stores l1->val and temp.next is nullptr.

Line #2 asks to store the address of the temp variable in cur.next so cur.next will be storing X123 after Line #2 has executed.

Line #3 asks to make l1 point to l1->next. This is doing what you expect.

Now pay close attention to Line #4. It isn't doing what you think it is doing. In a comment above, you said:

I am doing cur=*(cur.next), which should move cur forward.

But this is not exactly correct. "Moving cur forward" does not make sense because cur is not a pointer to ListNode, it is simply a ListNode object. So  Line #4 is asking to copy the object stored at the memory location cur.next (i.e. memory location X123), and paste it into the memory location occupied by cur. In other words, it is asking to copy the temp object into the memory location occupied by the cur object. So after Line #4 executes, cur.val will store whatever was in temp.val (i.e. the most recent l1->val), and cur.next will store whatever was in temp.next (i.e. nullptr).

In doing so you lose the pointer to temp's memory location X123, since cur.next was storing this and now you have overwritten it with nullptr! This is why at the end you have a cur with the last (most recent) assignment. All the earlier assignments are lost since you overwrite the contents of cur with new stuff in each iteration. You never "move cur forward".

The solution is to work with pointers. Have cur be a ListNode* pointer instead of a ListNode object, and try to work your way through the problem.

Hope this helps, and welcome to SO. Cheers!

Title: Merging two sorted linked list in c++

Body:
I am trying to code an algo to merge two sorted linked lists. I am not able to understand why this doesn't give me the correct answer. Why does the answer does not have memory of the earlier assignments, it just returns the most recent assignment being done. (i.e a linked list of length 1). I am creating an initial node called cur, then I am adding nexts to it depending on the values of l1 and l2 and doing cur.next every time. Thanks

struct ListNode {
  int val;
  ListNode* next;
  ListNode() : val(0), next(nullptr){};
  ListNode(int x) : val(x), next(nullptr){};
  ListNode(int x, ListNode* next) : val(x), next(next){};
};

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
  ListNode cur;
  ListNode* ans = new ListNode;
  ans = &cur;

  while (l1 && l2) {
    if (l1->val < l2->val) {
      ListNode temp(l1->val);
      cur.next = &temp;
      l1 = l1->next;
      cur = *(cur.next);
    } else {
      ListNode temp(l2->val);
      cur.next = &temp;
      l2 = l2->next;
      cur = *(cur.next);
    }
  }
  if (l1) {
    cur.next = (l1);
  }
  if (l2) {
    cur.next = (l2);
  }
  return ans->next;
};

Body:
Lets walk through the code you have inside the if blocks to try and understand what is going on.

ListNode temp(l1->val);
cur.next = &temp;
l1 = l1->next;
cur = *(cur.next);

Line #1 creates a new ListNode variable called temp in a newly allocated memory location. Lets say the address of this memory location is X123. At this memory location, temp.val stores l1->val and temp.next is nullptr.

Line #2 asks to store the address of the temp variable in cur.next so cur.next will be storing X123 after Line #2 has executed.

Line #3 asks to make l1 point to l1->next. This is doing what you expect.

Now pay close attention to Line #4. It isn't doing what you think it is doing. In a comment above, you said:

I am doing cur=*(cur.next), which should move cur forward.

But this is not exactly correct. "Moving cur forward" does not make sense because cur is not a pointer to ListNode, it is simply a ListNode object. So  Line #4 is asking to copy the object stored at the memory location cur.next (i.e. memory location X123), and paste it into the memory location occupied by cur. In other words, it is asking to copy the temp object into the memory location occupied by the cur object. So after Line #4 executes, cur.val will store whatever was in temp.val (i.e. the most recent l1->val), and cur.next will store whatever was in temp.next (i.e. nullptr).

In doing so you lose the pointer to temp's memory location X123, since cur.next was storing this and now you have overwritten it with nullptr! This is why at the end you have a cur with the last (most recent) assignment. All the earlier assignments are lost since you overwrite the contents of cur with new stuff in each iteration. You never "move cur forward".

The solution is to work with pointers. Have cur be a ListNode* pointer instead of a ListNode object, and try to work your way through the problem.

Hope this helps, and welcome to SO. Cheers!


问:
Airflow Scheduler is continuously issuing warning when using postgresSQL 12 as backend database
While executing airflow scheduler is continue printing following messages and tasks are NOT getting picked up.

```<code>[2020-02-21 09:21:20,696] {dag_processing.py:663} WARNING - DagFileProcessorManager (PID=11895) exited with exit code -11 - re-launching
[2020-02-21 09:21:20,699] {dag_processing.py:556} INFO - Launched DagFileProcessorManager with pid: 11898
[2020-02-21 09:21:20,711] {settings.py:54} INFO - Configured default timezone <Timezone [UTC]>
[2020-02-21 09:21:20,725] {settings.py:253} INFO - settings.configure_orm(): Using pool settings. pool_size=5, max_overflow=10, pool_recycle=1800, pid=11898
[2020-02-21 09:21:22,701] {dag_processing.py:663} WARNING - DagFileProcessorManager (PID=11898) exited with exit code -11 - re-launching
[2020-02-21 09:21:22,704] {dag_processing.py:556} INFO - Launched DagFileProcessorManager with pid: 11905
[2020-02-21 09:21:22,712] {settings.py:54} INFO - Configured default timezone <Timezone [UTC]>
[2020-02-21 09:21:22,722] {settings.py:253} INFO - settings.configure_orm(): Using pool settings. pool_size=5, max_overflow=10, pool_recycle=1800, pid=11905
[2020-02-21 09:21:24,704] {dag_processing.py:663} WARNING - DagFileProcessorManager (PID=11905) exited with exit code -11 - re-launching
[2020-02-21 09:21:24,706] {dag_processing.py:556} INFO - Launched DagFileProcessorManager with pid: 11907
[2020-02-21 09:21:24,717] {settings.py:54} INFO - Configured default timezone <Timezone [UTC]>
[2020-02-21 09:21:24,728] {settings.py:253} INFO - settings.configure_orm(): Using pool settings. pool_size=5, max_overflow=10, pool_recycle=1800, pid=11907
[2020-02-21 09:21:26,710] {dag_processing.py:663} WARNING - DagFileProcessorManager (PID=11907) exited with exit code -11 - re-launching
</code>```

Setup: PostgreSQL 12 as backend database with airflow v1.10.9.

But if I change to PostgreSQL 11 scheduler runs as expected. Does any one faced same issue?

答:
is there any particular reason you want to use Postgres ver 12? As of writing this post, Postgresql ver 12 is not supported by 1.10.x.

According to its github page,
Apache Airflow is tested with:

Master version (2.0.0dev)
Python versions: 3.6, 3.7
Postgres DB: 9.6, 10
MySQL DB: 5.7
Sqlite - latest stable (it is used mainly for development purpose)

Stable version (1.10.9)
Python versions: 2.7, 3.5, 3.6, 3.7
Postgres DB: 9.6, 10
MySQL DB: 5.6, 5.7
Sqlite - latest stable (it is used mainly for development purpose)

Body:
While executing airflow scheduler is continue printing following messages and tasks are NOT getting picked up.

[2020-02-21 09:21:20,696] {dag_processing.py:663} WARNING - DagFileProcessorManager (PID=11895) exited with exit code -11 - re-launching
[2020-02-21 09:21:20,699] {dag_processing.py:556} INFO - Launched DagFileProcessorManager with pid: 11898
[2020-02-21 09:21:20,711] {settings.py:54} INFO - Configured default timezone <Timezone [UTC]>
[2020-02-21 09:21:20,725] {settings.py:253} INFO - settings.configure_orm(): Using pool settings. pool_size=5, max_overflow=10, pool_recycle=1800, pid=11898
[2020-02-21 09:21:22,701] {dag_processing.py:663} WARNING - DagFileProcessorManager (PID=11898) exited with exit code -11 - re-launching
[2020-02-21 09:21:22,704] {dag_processing.py:556} INFO - Launched DagFileProcessorManager with pid: 11905
[2020-02-21 09:21:22,712] {settings.py:54} INFO - Configured default timezone <Timezone [UTC]>
[2020-02-21 09:21:22,722] {settings.py:253} INFO - settings.configure_orm(): Using pool settings. pool_size=5, max_overflow=10, pool_recycle=1800, pid=11905
[2020-02-21 09:21:24,704] {dag_processing.py:663} WARNING - DagFileProcessorManager (PID=11905) exited with exit code -11 - re-launching
[2020-02-21 09:21:24,706] {dag_processing.py:556} INFO - Launched DagFileProcessorManager with pid: 11907
[2020-02-21 09:21:24,717] {settings.py:54} INFO - Configured default timezone <Timezone [UTC]>
[2020-02-21 09:21:24,728] {settings.py:253} INFO - settings.configure_orm(): Using pool settings. pool_size=5, max_overflow=10, pool_recycle=1800, pid=11907
[2020-02-21 09:21:26,710] {dag_processing.py:663} WARNING - DagFileProcessorManager (PID=11907) exited with exit code -11 - re-launching

Setup: PostgreSQL 12 as backend database with airflow v1.10.9.

But if I change to PostgreSQL 11 scheduler runs as expected. Does any one faced same issue?


问:
Access the containing object in a constructor function
I want to access the parent object when calling a function contained inside that object as a constructor. See this example:

```<code>var users = {
    // The count of users
    count: 0,

    // Naturally _this is undefined
    _this: this,

    // Constructor function
    CreateUser: function (name, email) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        users.count++;
    },

    getCount: function () {
        return this.count;
    },
};
</code>```

If I try to invoke the CreateUser function as a constructor, then this will be a reference to the blank object that the new operator created. See this:

```<code>var user = new users.CreateUser('Rick', 'rick@example.com')
</code>```

How can I access the users containing object in this case without explicitly referring to it?

答:
It looks like what you are looking for is a static property, which are still to come in JS.

It is an experimental feature though.

Currently:

Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:

```<code>Rectangle.staticWidth = 20;
Rectangle.prototype.prototypeWidth = 25;
</code>```

Since what you do here is somehow similar to Joshua Bloch's idea of a static factory method or factory method pattern in general, it makes sense to move new keyword up to CreateUser method of users object.

By doing so you can use closure to save the reference to users object, implement nested constructor function and invoke it with new keyword.

Working example:

var users = {
    count: 0,

    CreateUser: function (name, email) {
        var self = this;
        const createUser = function(name, email) {
              this.name = name;
              this.email = email;
              self.count++;

        }
        return new createUser(name, email)
    },

    getCount: function () {
        return this.count;
    },
};
var user = users.CreateUser('Rick', 'rick@example.com')
console.log(user)
console.log(users.getCount())
users.CreateUser('Morty', 'morty@example.com')
users.CreateUser('Jerry', 'apples@example.com')
console.log(users.getCount())```

Body:
I want to access the parent object when calling a function contained inside that object as a constructor. See this example:

var users = {
    // The count of users
    count: 0,

    // Naturally _this is undefined
    _this: this,

    // Constructor function
    CreateUser: function (name, email) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        users.count++;
    },

    getCount: function () {
        return this.count;
    },
};

If I try to invoke the CreateUser function as a constructor, then this will be a reference to the blank object that the new operator created. See this:

var user = new users.CreateUser('Rick', 'rick@example.com')

How can I access the users containing object in this case without explicitly referring to it?

Body:
It looks like what you are looking for is a static property, which are still to come in JS.

It is an experimental feature though.

Currently:

Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:

Rectangle.staticWidth = 20;
Rectangle.prototype.prototypeWidth = 25;

Since what you do here is somehow similar to Joshua Bloch's idea of a static factory method or factory method pattern in general, it makes sense to move new keyword up to CreateUser method of users object.

By doing so you can use closure to save the reference to users object, implement nested constructor function and invoke it with new keyword.

Working example:

var users = {
    count: 0,

    CreateUser: function (name, email) {
        var self = this;
        const createUser = function(name, email) {
              this.name = name;
              this.email = email;
              self.count++;

        }
        return new createUser(name, email)
    },

    getCount: function () {
        return this.count;
    },
};
var user = users.CreateUser('Rick', 'rick@example.com')
console.log(user)
console.log(users.getCount())
users.CreateUser('Morty', 'morty@example.com')
users.CreateUser('Jerry', 'apples@example.com')
console.log(users.getCount())


问:
When calling a stored procedure it cannot find the database in Node and mysql
I am trying to call a stored procedure in nodejs and my database is made in mysql, currently I need to copy a table into a new database, when trying to test my method it throws me the message ER_NO_DB_ERROR: No database selected. the method of which I call this stored procedure is as follows.

  var mysql = require('mysql');
    var uuid = require('uuid');
    let config = require('../config/db.config');

let connection = mysql.createConnection(config);

let  sql = `CALL ReplyDB(?)`;

     app.post('/', function (req, res) {
        connection.query(sql,true, (error, results, fields) => {
            if (error) {
              return console.error("Fallo la replicación" , error.message);
            }
            console.log("El id único es: ", uuid.v4());
            console.log(" Replicación completada", results[0]);
          });

          connection.end();

    });```
</div>
</div>
</p>

<p>the stored procedure it generates is as follows.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    PROCEDURE `demo`.`ReplyDB`(IN done BOOLEAN)
    /*LANGUAGE SQL
    | [NOT] DETERMINISTIC
    | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
    | SQL SECURITY { DEFINER | INVOKER }
    | COMMENT 'string'*/
 BEGIN
  INSERT INTO testdb.backup_sales_order
  SELECT *
  FROM demo.sales_order;
 END $$

DELIMITER ;</code>```

I do not receive any parameters, I just need that when I position myself in the main path, the method is executed and the data is inserted.

答:
db.config

has also to have a database in it

Like:

```<code>var databaseOptions = {
    host     : 'localhost',
    database : 'demo',
    user     : 'root',
    password : 'secretpassword',
    port     : '3306'
};
</code>```

or call use demo

Like:

```<code>let database = 'demo';
connection.query(`USE ${database}`, (error, results, fields) => {
    ...
  });
</code>```

every call to a mysql function must have a hook that is a database

so  spencer7593 is of course right, that

```<code>let  sql = 'CALL demo.ReplyDB(?)';
</code>```

Would also do the trick, but i thought that you want to run more query on demo, so using USE or using demo in the connection string, would make it easier.

Body:
I am trying to call a stored procedure in nodejs and my database is made in mysql, currently I need to copy a table into a new database, when trying to test my method it throws me the message ER_NO_DB_ERROR: No database selected. the method of which I call this stored procedure is as follows.

  var mysql = require('mysql');
    var uuid = require('uuid');
    let config = require('../config/db.config');

let connection = mysql.createConnection(config);

let  sql = `CALL ReplyDB(?)`;

     app.post('/', function (req, res) {
        connection.query(sql,true, (error, results, fields) => {
            if (error) {
              return console.error("Fallo la replicación" , error.message);
            }
            console.log("El id único es: ", uuid.v4());
            console.log(" Replicación completada", results[0]);
          });

          connection.end();

    });

the stored procedure it generates is as follows.

DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    PROCEDURE `demo`.`ReplyDB`(IN done BOOLEAN)
    /*LANGUAGE SQL
    | [NOT] DETERMINISTIC
    | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
    | SQL SECURITY { DEFINER | INVOKER }
    | COMMENT 'string'*/
 BEGIN
  INSERT INTO testdb.backup_sales_order
  SELECT *
  FROM demo.sales_order;
 END $$

DELIMITER ;

I do not receive any parameters, I just need that when I position myself in the main path, the method is executed and the data is inserted.

Body:
db.config

has also to have a database in it

Like:

var databaseOptions = {
    host     : 'localhost',
    database : 'demo',
    user     : 'root',
    password : 'secretpassword',
    port     : '3306'
};

or call use demo

Like:

let database = 'demo';
connection.query(`USE ${database}`, (error, results, fields) => {
    ...
  });

every call to a mysql function must have a hook that is a database

so  spencer7593 is of course right, that

let  sql = 'CALL demo.ReplyDB(?)';

Would also do the trick, but i thought that you want to run more query on demo, so using USE or using demo in the connection string, would make it easier.


问:
Remove first line from txt file using python3
So I have this code that writes the ping results to a txt file but its skipps the first line which means the file always gets an empty first line.

how can I remove it?
or even better, how can i print directly to the first line?

```<code>file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
with open(file, 'w+') as output:
    sub.call(['ping', f'{host}'], stdout=output)
</code>```

答:
In Python3, that is a 2 liner:

```<code>some_string = 'this will be the new first line of the file\n'

with open(fr'c:/users/{os.getlogin()}/Desktop/default.txt', 'r') as old: data = old.read()
with open(fr'c:/users/{os.getlogin()}/Desktop/default.txt', 'w') as new: new.write(some_string + data)
</code>```

To answer the original question for any poor lads stumbling upon this thread, here is how you delete the first line of a file using python array (yes, I know it is technically called list...) slicing:

```<code>filename = fr'c:/users/{os.getlogin()}/Desktop/default.txt'

# split file after every newline to get an array of strings
with open(filename, 'r') as old: data = old.read().splitlines(True)
# slice the array and save it back to our file
with open(filename, 'w') as new: new.writelines(data[1:])
</code>```

More info on list slicing: https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html

Extended list slicing: https://docs.python.org/2.3/whatsnew/section-slices.html

Body:
So I have this code that writes the ping results to a txt file but its skipps the first line which means the file always gets an empty first line.

how can I remove it?
or even better, how can i print directly to the first line?

file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
with open(file, 'w+') as output:
    sub.call(['ping', f'{host}'], stdout=output)

Body:
In Python3, that is a 2 liner:

some_string = 'this will be the new first line of the file\n'

with open(fr'c:/users/{os.getlogin()}/Desktop/default.txt', 'r') as old: data = old.read()
with open(fr'c:/users/{os.getlogin()}/Desktop/default.txt', 'w') as new: new.write(some_string + data)

To answer the original question for any poor lads stumbling upon this thread, here is how you delete the first line of a file using python array (yes, I know it is technically called list...) slicing:

filename = fr'c:/users/{os.getlogin()}/Desktop/default.txt'

# split file after every newline to get an array of strings
with open(filename, 'r') as old: data = old.read().splitlines(True)
# slice the array and save it back to our file
with open(filename, 'w') as new: new.writelines(data[1:])

More info on list slicing: https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html

Extended list slicing: https://docs.python.org/2.3/whatsnew/section-slices.html


问:
How can i convert NSBezierPath to CGPath
How can i convert between NSBezierPath to CGPath.

Thanks.

答:
c# Xamarin</p>

```<code>        private CGPath convertNSBezierPathToCGPath(NSBezierPath sourcePath)
    {
        CGPath destinationPath = new CGPath();

        int i, numElements;

        // Then draw the path elements.
        numElements = (int)Convert.ToInt64(sourcePath.ElementCount);

        if (numElements > 0)
        {

            CGPath path = new CGPath();
            CGPoint[] points;
            bool didClosePath = true;

            for (i = 0; i < numElements; i++)
            {
                switch (sourcePath.ElementAt(i, out points))
                {
                    case NSBezierPathElement.MoveTo:
                        path.MoveToPoint(points[0]);
                        break;

                    case NSBezierPathElement.LineTo:
                        path.MoveToPoint(points[0]);
                        didClosePath = false;
                        break;

                    case NSBezierPathElement.CurveTo:
                        path.AddCurveToPoint(cp1: points[0], cp2: points[1], points[2]);
                        didClosePath = false;
                        break;

                    case NSBezierPathElement.ClosePath:
                        path.CloseSubpath();
                        didClosePath = true;
                        break;
                }
            }

            if (!didClosePath)
                path.CloseSubpath();

            destinationPath = new CGPath(path);

        }

        return destinationPath;

}
</code>```

Body:
c# Xamarin

        private CGPath convertNSBezierPathToCGPath(NSBezierPath sourcePath)
    {
        CGPath destinationPath = new CGPath();

        int i, numElements;

        // Then draw the path elements.
        numElements = (int)Convert.ToInt64(sourcePath.ElementCount);

        if (numElements > 0)
        {

            CGPath path = new CGPath();
            CGPoint[] points;
            bool didClosePath = true;

            for (i = 0; i < numElements; i++)
            {
                switch (sourcePath.ElementAt(i, out points))
                {
                    case NSBezierPathElement.MoveTo:
                        path.MoveToPoint(points[0]);
                        break;

                    case NSBezierPathElement.LineTo:
                        path.MoveToPoint(points[0]);
                        didClosePath = false;
                        break;

                    case NSBezierPathElement.CurveTo:
                        path.AddCurveToPoint(cp1: points[0], cp2: points[1], points[2]);
                        didClosePath = false;
                        break;

                    case NSBezierPathElement.ClosePath:
                        path.CloseSubpath();
                        didClosePath = true;
                        break;
                }
            }

            if (!didClosePath)
                path.CloseSubpath();

            destinationPath = new CGPath(path);

        }

        return destinationPath;

}


问:
Overflow in exp when curve_fit of datetime
I tried to fit datetime vs. float data using curve_fit. As far as I understand, curve_fit does not work with datetime, so I first have to convert the data to numerical values. This gives me very large values for x that cause an overflow in the exp function. My code is below. The same code does work if I fit with a polynomial instead of the exponential.

```<code>    def func(x, a):
        return (np.exp(a*x))

    def fit_exponential(gd):
        gdtemp['Date'] = pd.to_datetime(gdtemp.Date)

        mask = (gdtemp['Date'] > '2020-01-30') & (gdtemp['Date'] <= '2020-03-20')

        gdtemp = gdtemp.loc[mask].copy()

        x = pd.to_numeric(gdtemp.Date)
        y=gdtemp['Confirmed']

        popt, pcov = curve_fit(func,x, y)
</code>```

How can I modify the code to work with the exponential?

I have two ideas on how to fix this but am not sure how to go about implementing this:

1st idea: Don't convert with to_numeric, but in some other way that produces smaller numbers. My input data is fairly simple and consists of exactly 1 row per day, so I don't need time or anything else. Is there another function similar to to_numeric() that ignores the time part and produces smaller numbers?

2nd idea: divide the numeric date values by some large number and later multiply back. What number should I use for dividing?

答:
I solved this, by mapping the large numerical x values to the interval [0;1] and fitting on this interval.

The essential modifications are:

```<code>small_x = (x - x.min()) / (x.max() - x.min())
popt, pcov = curve_fit(func4 ,small_x, y )
</code>```

The values in the exponent are now reasonable (on the order of 1 in my case) and there is no problem with overflows.

Without this mapping I would end up with very large x values (on the order of 10^(15)) and very tiny values for a (on the order of 10^(-15)) which obviously the fititng function did not like.

Body:
I tried to fit datetime vs. float data using curve_fit. As far as I understand, curve_fit does not work with datetime, so I first have to convert the data to numerical values. This gives me very large values for x that cause an overflow in the exp function. My code is below. The same code does work if I fit with a polynomial instead of the exponential.

    def func(x, a):
        return (np.exp(a*x))

    def fit_exponential(gd):
        gdtemp['Date'] = pd.to_datetime(gdtemp.Date)

        mask = (gdtemp['Date'] > '2020-01-30') & (gdtemp['Date'] <= '2020-03-20')

        gdtemp = gdtemp.loc[mask].copy()

        x = pd.to_numeric(gdtemp.Date)
        y=gdtemp['Confirmed']

        popt, pcov = curve_fit(func,x, y)

How can I modify the code to work with the exponential?

I have two ideas on how to fix this but am not sure how to go about implementing this:

1st idea: Don't convert with to_numeric, but in some other way that produces smaller numbers. My input data is fairly simple and consists of exactly 1 row per day, so I don't need time or anything else. Is there another function similar to to_numeric() that ignores the time part and produces smaller numbers?

2nd idea: divide the numeric date values by some large number and later multiply back. What number should I use for dividing?

Body:
I solved this, by mapping the large numerical x values to the interval [0;1] and fitting on this interval.

The essential modifications are:

small_x = (x - x.min()) / (x.max() - x.min())
popt, pcov = curve_fit(func4 ,small_x, y )

The values in the exponent are now reasonable (on the order of 1 in my case) and there is no problem with overflows.

Without this mapping I would end up with very large x values (on the order of 10^(15)) and very tiny values for a (on the order of 10^(-15)) which obviously the fititng function did not like.


问:
SQL injection login bypass
I am preparing SQL injection vulnerable page to test skills, here is my code:

```<code><?php
    echo "<center><h1>Login Bypass</h1></center>";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "<center>".$query_string."</center><br/>";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "<center>SUCCESS</center><br/>";
    else echo "<center>ACCESS DENIED</center><br/>";
    echo "<center>".$row['email']."</center><br/>";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />
</head>

<body>
    <center>
    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>
    </center>
</body>

</html>
</code>```

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

```<code>$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
</code>```

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

```<code>SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '
</code>```

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?

答:
Because the SQL statement itself is not valid.  It doesn't pass the test of proper formatting.

```<code>SELECT *
  FROM users
 WHERE username = 'agajan' /* ' AND password = ' '
</code>```

Consider input like "agajan'; SELECT 1 FROM users WHERE user = 'agajan'"

```<code>UPDATE users
 SET priv = 'superuser'
 WHERE username = 'agajan'; SELECT * FROM users WHERE user = 'agajan' AND password = ' '
</code>```

Title: SQL injection login bypass

Body:
I am preparing SQL injection vulnerable page to test skills, here is my code:

<?php
    echo "
Login Bypass
";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "".$query_string."
";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "SUCCESS
";
    else echo "ACCESS DENIED
";
    echo "".$row['email']."
";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />

    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?

Body:
Because the SQL statement itself is not valid.  It doesn't pass the test of proper formatting.

SELECT *
  FROM users
 WHERE username = 'agajan' /* ' AND password = ' '

Consider input like "agajan'; SELECT 1 FROM users WHERE user = 'agajan'"

UPDATE users
 SET priv = 'superuser'
 WHERE username = 'agajan'; SELECT * FROM users WHERE user = 'agajan' AND password = ' '


问:
How to type hint parameter of type <class 'module'>
I have a function that takes in a package and returns a list of classes in it (as well as subpackages) that inherits from foo.

```<code>def list_foo_classes_from_package(package) -> List[foo]:
    ...
    code to find attribute that is issubclass(attribute, foo)
    ...
    return list_of_foo_classes

import boo
class_list = list_classes(boo)
</code>```

I want to type hint the input package. however module is not a keyword. The closest thing I found was types.ModuleType, i.e.

```<code>def list_classes_from_package(self, package: types.ModuleType) -> List[foo]:
</code>```

However I get a warning:

```<code>expected type ModuleType, got "__init__.py" instead
</code>```

How do I type hint package as parameter to a function?

答: Turned out types.ModuleType was correct. It was an issue with Pycharm (thanks @user2357112 supports Monica). When searching for "Pycharm module type hint" on google led me to this answer.

Body:
I have a function that takes in a package and returns a list of classes in it (as well as subpackages) that inherits from foo.

def list_foo_classes_from_package(package) -> List[foo]:
    ...
    code to find attribute that is issubclass(attribute, foo)
    ...
    return list_of_foo_classes

import boo
class_list = list_classes(boo)

I want to type hint the input package. however module is not a keyword. The closest thing I found was types.ModuleType, i.e.

def list_classes_from_package(self, package: types.ModuleType) -> List[foo]:

However I get a warning:

expected type ModuleType, got "__init__.py" instead

How do I type hint package as parameter to a function?