问:
How to display the recent added data to the top of the recycler view
I'm creating an app where i am storing data to firebase and retriving it to my reclycler view and but   issue is, i want to display the most recent added data to the top of the recycler view. I am trying to get the latest data and I had done all possibly Solution still I am not getting.

please see the following code....

here is my Mainclass:

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

ProgressDialog progressDialog;
List<DataClass> list = new ArrayList<>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter;

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

    recyclerView = findViewById(R.id.erecyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(ShowDetails.this));
    progressDialog = new ProgressDialog(ShowDetails.this);
    progressDialog.setMessage("Loading Data from Firebase Database");
    progressDialog.show();

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId("1:102738125513:android:3042292623f0448c") // Required for Analytics.
            .setApiKey("AIzaSyAZbWBpPzjAkrg23riK9kwk2T0tDf47dko") // Required for Auth.
            .setDatabaseUrl("https://citycare-fed31.firebaseio.com/") // Required for RTDB.
            .build();
    FirebaseApp.initializeApp(this);
            // Retrieve my other app.
            FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");
    // Get the database for the other app.
    FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
    DatabaseReference data = secondaryDatabase.getInstance().getReference("Electricity");
    data.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                for (DataSnapshot dSnapshot : ds.getChildren()) {

                    DataClass DataClass = dSnapshot.getValue(DataClass.class);

                    Log.d("Show", DataClass.getEname() == null ? "" : DataClass.getEname());
                    list.add(DataClass);

                }
                adapter = new ShowDetails.DataAdapter(ShowDetails.this, list);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            progressDialog.dismiss();
        }
    });

}
</code>```

and this is my Adapter class:

```<code> private class DataAdapter extends RecyclerView.Adapter<ShowDetails.DataAdapter.ViewHolder>  {

    Context context;
    List<DataClass> listData;

    public DataAdapter(Context context, List<DataClass> list) {

        this.context = context;
        this.listData = list;
    }

    @Override
    public ShowDetails.DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
        ShowDetails.DataAdapter.ViewHolder viewHolder = new ShowDetails.DataAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ShowDetails.DataAdapter.ViewHolder holder, int position) {

        final DataClass AllDetails = listData.get(position);
        holder.NameTextView.setText(AllDetails.getEname());
        holder.EmailTextView.setText(AllDetails.getEemail());
        holder.DateTextView.setText(AllDetails.getEdate());
        holder.LocationTextView.setText(AllDetails.getElocation());
        holder.TypeTextView.setText(AllDetails.getEtype());
        Picasso.with(context).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);

        holder.ImageTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, ShowImage.class);
                i.putExtra("img", AllDetails.getImgurl());
                startActivity(i);
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, Email_Activity.class);
                i.putExtra("txt", AllDetails.getEemail());
                startActivity(i);
            }
        });
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public TextView NameTextView;
        public TextView EmailTextView;
        public TextView DateTextView;
        public TextView LocationTextView;
        public TextView TypeTextView;
        public ImageView ImageTextView;
        public ViewHolder(View itemView) {

            super(itemView);
            NameTextView = itemView.findViewById(R.id.ShowNameTextView);
            EmailTextView = itemView.findViewById(R.id.ShowEmailTextView);
            DateTextView = itemView.findViewById(R.id.ShowDateTextView);
            LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
            TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
            ImageTextView = itemView.findViewById(R.id.ShowImageView);
        }
    }
}
</code>```

here is my database

firebase data structure

here is my API response after removing extra for loop
API response

please help me out i am new to programming

答:
You can add your data to list's first iterator in loop,
and move setadapter out of loops:</p>

```<code>for (DataSnapshot ds : dataSnapshot.getChildren()) {
   for (DataSnapshot dSnapshot : ds.getChildren()) {
      DataClass DataClass = dSnapshot.getValue(DataClass.class);
      list.add(0, DataClass);
   }
}
adapter = new ShowDetails.DataAdapter(ShowDetails.this, list);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
</code>```

Body:
I'm creating an app where i am storing data to firebase and retriving it to my reclycler view and but   issue is, i want to display the most recent added data to the top of the recycler view. I am trying to get the latest data and I had done all possibly Solution still I am not getting.

please see the following code....

here is my Mainclass:

public class ShowDetails extends AppCompatActivity {

ProgressDialog progressDialog;
List<DataClass> list = new ArrayList<>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter;

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

    recyclerView = findViewById(R.id.erecyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(ShowDetails.this));
    progressDialog = new ProgressDialog(ShowDetails.this);
    progressDialog.setMessage("Loading Data from Firebase Database");
    progressDialog.show();

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId("1:102738125513:android:3042292623f0448c") // Required for Analytics.
            .setApiKey("AIzaSyAZbWBpPzjAkrg23riK9kwk2T0tDf47dko") // Required for Auth.
            .setDatabaseUrl("https://citycare-fed31.firebaseio.com/") // Required for RTDB.
            .build();
    FirebaseApp.initializeApp(this);
            // Retrieve my other app.
            FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");
    // Get the database for the other app.
    FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
    DatabaseReference data = secondaryDatabase.getInstance().getReference("Electricity");
    data.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                for (DataSnapshot dSnapshot : ds.getChildren()) {

                    DataClass DataClass = dSnapshot.getValue(DataClass.class);

                    Log.d("Show", DataClass.getEname() == null ? "" : DataClass.getEname());
                    list.add(DataClass);

                }
                adapter = new ShowDetails.DataAdapter(ShowDetails.this, list);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            progressDialog.dismiss();
        }
    });

}

and this is my Adapter class:

 private class DataAdapter extends RecyclerView.Adapter<ShowDetails.DataAdapter.ViewHolder>  {

    Context context;
    List<DataClass> listData;

    public DataAdapter(Context context, List<DataClass> list) {

        this.context = context;
        this.listData = list;
    }

    @Override
    public ShowDetails.DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
        ShowDetails.DataAdapter.ViewHolder viewHolder = new ShowDetails.DataAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ShowDetails.DataAdapter.ViewHolder holder, int position) {

        final DataClass AllDetails = listData.get(position);
        holder.NameTextView.setText(AllDetails.getEname());
        holder.EmailTextView.setText(AllDetails.getEemail());
        holder.DateTextView.setText(AllDetails.getEdate());
        holder.LocationTextView.setText(AllDetails.getElocation());
        holder.TypeTextView.setText(AllDetails.getEtype());
        Picasso.with(context).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);

        holder.ImageTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, ShowImage.class);
                i.putExtra("img", AllDetails.getImgurl());
                startActivity(i);
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(ShowDetails.this, Email_Activity.class);
                i.putExtra("txt", AllDetails.getEemail());
                startActivity(i);
            }
        });
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public TextView NameTextView;
        public TextView EmailTextView;
        public TextView DateTextView;
        public TextView LocationTextView;
        public TextView TypeTextView;
        public ImageView ImageTextView;
        public ViewHolder(View itemView) {

            super(itemView);
            NameTextView = itemView.findViewById(R.id.ShowNameTextView);
            EmailTextView = itemView.findViewById(R.id.ShowEmailTextView);
            DateTextView = itemView.findViewById(R.id.ShowDateTextView);
            LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
            TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
            ImageTextView = itemView.findViewById(R.id.ShowImageView);
        }
    }
}

here is my database

firebase data structure

here is my API response after removing extra for loop
API response

please help me out i am new to programming

Body:
You can add your data to list's first iterator in loop,
and move setadapter out of loops:

for (DataSnapshot ds : dataSnapshot.getChildren()) {
   for (DataSnapshot dSnapshot : ds.getChildren()) {
      DataClass DataClass = dSnapshot.getValue(DataClass.class);
      list.add(0, DataClass);
   }
}
adapter = new ShowDetails.DataAdapter(ShowDetails.this, list);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();


来源: stackexchange

问:
How to color a button on button click?
I an trying to color button on another button click..but its not working for.

```<code>function show_col(){
    console.log("hello");
       var path=localStorage.getItem(".physics_section  #color1 button");
      $(''+path+'').css("background","green");
      $(''+path+'').css("color","white");
}
</code>```

when show_col() function get called and it  print "hello" to console but last three didn't get executed.when i put these three line directly to console it work fine but working with simple function call.

```<code>function color_ans(e){

    $('.physics_section #color1 button').removeClass('selected');
    $('.physics_section  #color1 #'+e+'').addClass('selected');
    localStorage.setItem('.physics_section  #color1 button','.physics_section  #color1 #'+e+'')
}
</code>```

Button that call function:

```<code> <button id='cit"+i+"' onclick='doThing_chemistry(event);show_col();'>"+i+"</button>
</code>```

答:
what's  the value of   e  when you call color_ans(e)     </p>

<p>try  ID  '#cit'+e    </p>

```<code>localStorage.setItem('.physics_section  #color1 button','.physics_section  #color1 #cit'+e)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to color a button on button click?

Body:
I an trying to color button on another button click..but its not working for.

function show_col(){
    console.log("hello");
       var path=localStorage.getItem(".physics_section  #color1 button");
      $(''+path+'').css("background","green");
      $(''+path+'').css("color","white");
}

when show_col() function get called and it  print "hello" to console but last three didn't get executed.when i put these three line directly to console it work fine but working with simple function call.

function color_ans(e){

    $('.physics_section #color1 button').removeClass('selected');
    $('.physics_section  #color1 #'+e+'').addClass('selected');
    localStorage.setItem('.physics_section  #color1 button','.physics_section  #color1 #'+e+'')
}

Button that call function:

 <button id='cit"+i+"' onclick='doThing_chemistry(event);show_col();'>"+i+"</button>

Body:
what's  the value of   e  when you call color_ans(e)

try  ID  '#cit'+e

localStorage.setItem('.physics_section  #color1 button','.physics_section  #color1 #cit'+e)


问:
Calculate the standard deviation in R for a specific group of the dependent variable
I am trying to calculate the standard deviation from certain variables for different groups. In my dataset I have a 2 explanatory variables with a 0 or 1 outcome (CH and CH2). I would like to know the difference in the standard deviation of these two groups.

so far I am working with the following command. sample being the dataset and COM being one of the explanatory variables.

```<code>sd(sample$COM, na.rm=TRUE)
</code>```

Is it possible to specify it for CH = 1?
And additionally for CH = 1 or CH2=1?

Thank you in advance and kind regards.

答:
I prefer using subset function:

```<code>with(subset(samples, subset=CH==1),
     sd(COM)
    )
with(subset(samples, subset=CH==1 | CH2==1),
     sd(COM)
    )
</code>```

It's so much easier to read and you don't need to keep repeating the dataset$ stuff all the time.

Body:
I am trying to calculate the standard deviation from certain variables for different groups. In my dataset I have a 2 explanatory variables with a 0 or 1 outcome (CH and CH2). I would like to know the difference in the standard deviation of these two groups.

so far I am working with the following command. sample being the dataset and COM being one of the explanatory variables.

sd(sample$COM, na.rm=TRUE)

Is it possible to specify it for CH = 1?
And additionally for CH = 1 or CH2=1?

Thank you in advance and kind regards.

Body:
I prefer using subset function:

with(subset(samples, subset=CH==1),
     sd(COM)
    )
with(subset(samples, subset=CH==1 | CH2==1),
     sd(COM)
    )

It's so much easier to read and you don't need to keep repeating the dataset$ stuff all the time.


问:
Pulp Killer sudoku - check choices are distinct for choice of variables
I am trying to solve killer Sudoku using Python linear optimization library, Pulp.

https://en.wikipedia.org/wiki/Killer_sudoku

Here is my attempt so far, adding a constraint that each row must add up to 45.

```<code>import pulp
prob = pulp.LpProblem("Sudoku Problem")
prob += 0, "Arbitrary Objective Function"

# 9 by 9 grid of 'choices', integers between 1-9
choices = pulp.LpVariable.dicts(
"Choice", (range(9), range(9)), cat="Integer", lowBound=1, upBound=9)

# identify puzzle rows that must have only 1 of every value
row_groups = [[(i, j) for i in range(9)] for j in range(9)]

# Seems to work, make every row add up 45
for distinct_group in row_groups:
    for i, j in distinct_group:
        distinct_group_constraint = [choices[i][j] for i, j in distinct_group]
    prob += pulp.lpSum(distinct_group_constraint) == 45

# ... Code to add additional constraints for columns, boxes and 'cages'. Excluded for brevity.

prob.solve()
</code>```

The problem is I'm struggling to add a stricter constraint that each value in a row must be different. For example, if a row had these values

[1,9,1,9,1,9,1,9,5]

It would pass the constraint above, but would not be a valid sudoku row because each value is not unique.

Below is my attempt to add a stricter constraint, it seems not work, since the problem doesn't solve

```<code>for n in range(1, 10):
    for distinct_group in row_groups:
        for i, j in distinct_group:
            distinct_group_constraint = [choices[i][j] == n for i, j in distinct_group]
        prob += pulp.lpSum(distinct_group_constraint) == 1
</code>```

I have seen several examples online, resolving this by reframing this optimisation as a 9x9x9 choice of binary flags, rather than 9x9 optimisation of choices of integers 1-9. The issue is, I find it hard to see how to check the sums of 'cages' easily in the 9x9x9 case, whist this is quite simple in 9x9 case.

Here is an example of the 9x9x9 setup for a 'non-killer' sudoku. https://github.com/coin-or/pulp/blob/master/examples/Sudoku1.py

```<code># cells (0,0) and (0,1) must sum to 8
cage_constraints = [(8, [[0, 0], [0, 1]])]

for target, cells in cage_constraints:
    cage_cells_constraint = [choices[i][j] for i, j in cells]
    prob += pulp.lpSum(cage_cells_constraint) == target
</code>```

I am looking to (a) find a way to add this stricter constraint that no choices can be duplicated in the 9x9 setup, or (b) a way to easily add constraints of the 'sum' of cages in the 9x9x9 case. If you would like the entire list of cage-constraints to test on, here are a list of cage-constraints from this puzzle.

```<code>CAGE_CONSTRAINTS = [
(8, [[0, 0], [0, 1]]),
(9, [[0, 6], [0, 7]]),
(8, [[0, 2], [1, 2]]),
(12, [[0, 3], [0, 4], [1, 3]]),
(15, [[0, 5], [1, 5], [2, 5]]),
(19, [[1, 6], [1, 7], [2, 7]]),
(16, [[0, 8], [1, 8], [2, 8]]),
(14, [[1, 0], [1, 1], [2, 0]]),
(15, [[2, 1], [2, 2]]),
(10, [[2, 3], [3, 3]]),
(12, [[1, 4], [2, 4]]),
(7, [[2, 6], [3, 6]]),
(24, [[3, 0], [3, 1], [4, 1]]),
(17, [[3, 7], [3, 8], [4, 8]]),
(8, [[3, 2], [4, 2]]),
(12, [[4, 3], [5, 3]]),
(19, [[3, 4], [4, 4], [5, 4]]),
(4, [[3, 5], [4, 5]]),
(15, [[4, 6], [5, 6]]),
(12, [[4, 0], [5, 0], [5, 1]]),
(7, [[4, 7], [5, 7], [5, 8]]),
(8, [[5, 2], [6, 2]]),
(10, [[6, 4], [7, 4]]),
(14, [[5, 5], [6, 5]]),
(12, [[6, 6], [6, 7]]),
(18, [[6, 8], [7, 7], [7, 8]]),
(15, [[6, 0], [7, 0], [8, 0]]),
(13, [[6, 1], [7, 1], [7, 2]]),
(12, [[6, 3], [7, 3], [8, 3]]),
(15, [[7, 5], [8, 4], [8, 5]]),
(7, [[7, 6], [8, 6]]),
(10, [[8, 1], [8, 2]]),
(8, [[8, 7], [8, 8]]),
]
</code>```

https://www.dailykillersudoku.com/search?dt=2020-02-15

and here is the solution https://www.dailykillersudoku.com/pdfs/19664.solution.pdf

EDIT - if I try changing to a 9x9x9 problem with binary choices, I get results that don't match my desired cage constraints. Here is a snippet.

```<code>choices = pulp.LpVariable.dicts(
    "Choice", (range(9), range(9), range(1, 10),), cat="Binary"
)

# add constraints that only one choice for each 'distinct_group'
for n in range(1, 10):
    for distinct_group in distinct_groups:
        for i, j in distinct_group:
        distinct_group_constraint = [choices[i][j][n] for i, j in
distinct_group]
        prob += pulp.lpSum(distinct_group_constraint) == 1

# add constraints that cells in cages must equal 'cage_total'
for target, cells in CAGE_CONSTRAINTS:
    cage_cells_constraint = [
        choices[i][j][n] * n for i, j in cells for n in range(1, 10)
    ]
    prob += pulp.lpSum(cage_cells_constraint) == target
</code>```

and here is full example https://gist.github.com/olicairns/d8e222526b87a62b2e175837b452c24a

答:
I would reccomend the use of binary variables - as per the examples you have found. It may seem like more variables but as far as I know use use of a smaller number of integer variables will not help solution time at all - the way the 'branch-and-bound' algorithm for solving a problem with integer variables will mean it's just as inefficient as having more binary variables (someone more familiar with this may be able to correct me).

So to answer the second half of your question:

(b) a way to easily add constraints of the 'sum' of cages in the 9x9x9 case.

This is quite straightforward - you just to a sum-product of the binary variables for a cell by the index which each varaible represents.

If you've already developed all the code assuming your choice of variables (9x9 integer variables), you can add the 9x9x9 binary variables, and then constraint your 9x9 integer variables (which would now be auxiliary variables) as follows:

```<code>for i in range(1, 10):
    for j in range(1, 10):
        pulp += choices[i][j] == pulp.lpSum([binary_choices[i][j][k]*k for k in range(1,10)])
</code>```

You now have both sets of variables - one lot of binary variables, and one lot of integer variables which are linked with equality constraints to behave as required. If you want to avoid all the auxillary variables then you would just need to replace a sum-product with the index value as above anywhere you are currently using your integer variables.

Full working code for completeness:

```<code>import pulp

prob = pulp.LpProblem("Sudoku_Problem_KA")
prob += 0, "Arbitrary Objective Function"

CAGE_CONSTRAINTS = [
    (8., [[0, 0], [0, 1]]),
    (9., [[0, 6], [0, 7]]),
    (8., [[0, 2], [1, 2]]),
    (12., [[0, 3], [0, 4], [1, 3]]),
    (15., [[0, 5], [1, 5], [2, 5]]),
    (19., [[1, 6], [1, 7], [2, 7]]),
    (16., [[0, 8], [1, 8], [2, 8]]),
    (14., [[1, 0], [1, 1], [2, 0]]),
    (15., [[2, 1], [2, 2]]),
    (10., [[2, 3], [3, 3]]),
    (12., [[1, 4], [2, 4]]),
    (7., [[2, 6], [3, 6]]),
    (24., [[3, 0], [3, 1], [4, 1]]),
    (17., [[3, 7], [3, 8], [4, 8]]),
    (8., [[3, 2], [4, 2]]),
    (12., [[4, 3], [5, 3]]),
    (19., [[3, 4], [4, 4], [5, 4]]),
    (4., [[3, 5], [4, 5]]),
    (15., [[4, 6], [5, 6]]),
    (12., [[4, 0], [5, 0], [5, 1]]),
    (7., [[4, 7], [5, 7], [5, 8]]),
    (8., [[5, 2], [6, 2]]),
    (10., [[6, 4], [7, 4]]),
    (14., [[5, 5], [6, 5]]),
    (12., [[6, 6], [6, 7]]),
    (18., [[6, 8], [7, 7], [7, 8]]),
    (15., [[6, 0], [7, 0], [8, 0]]),
    (13., [[6, 1], [7, 1], [7, 2]]),
    (12., [[6, 3], [7, 3], [8, 3]]),
    (15., [[7, 5], [8, 4], [8, 5]]),
    (7., [[7, 6], [8, 6]]),
    (10., [[8, 1], [8, 2]]),
    (8., [[8, 7], [8, 8]]),
]

# groups that should only have 1 of each number 1-9
row_groups = [[(i, j) for i in range(9)] for j in range(9)]
col_groups = [[(j, i) for i in range(9)] for j in range(9)]
box_groups = [
    [(3 * i + k, 3 * j + l) for k in range(3) for l in range(3)]
    for i in range(3)
    for j in range(3)
]
distinct_groups = row_groups + col_groups + box_groups

# binary choices: rows, columns and values 1-9
choices = pulp.LpVariable.dicts(
    "choices", (range(9), range(9), range(1, 10)), cat="Binary"
)

# add constraints that only one choice for each 'distinct_group'
for n in range(1, 10):
    for distinct_group in distinct_groups:
        prob += pulp.lpSum([choices[i][j][n] for i, j in distinct_group]) <= 1

# add constraints that cells in cages must equal 'cage_total'
for target, cells in CAGE_CONSTRAINTS:
    prob += pulp.lpSum([choices[i][j][n] * n for i, j in cells for n in range(1, 10)]) >= target

# only pick one binary value per cell:
for i in range(9):
    for j in range(9):
        prob += pulp.lpSum([choices[i][j][n] for n in range(1, 10)]) <= 1

prob.solve()

print('Status:',pulp.LpStatus[prob.status])

# Extract results
res = [[sum([choices[i][j][n].varValue*n for n in range(1,10)]) for j in range(9)] for i in range(9)]

# checking a few constraints match
assert res[8][7] + res[8][8] == 8
assert res[0][0] + res[0][1] == 8

print(res)
</code>```

Body:
I am trying to solve killer Sudoku using Python linear optimization library, Pulp.

https://en.wikipedia.org/wiki/Killer_sudoku

Here is my attempt so far, adding a constraint that each row must add up to 45.

import pulp
prob = pulp.LpProblem("Sudoku Problem")
prob += 0, "Arbitrary Objective Function"

# 9 by 9 grid of 'choices', integers between 1-9
choices = pulp.LpVariable.dicts(
"Choice", (range(9), range(9)), cat="Integer", lowBound=1, upBound=9)

# identify puzzle rows that must have only 1 of every value
row_groups = [[(i, j) for i in range(9)] for j in range(9)]

# Seems to work, make every row add up 45
for distinct_group in row_groups:
    for i, j in distinct_group:
        distinct_group_constraint = [choices[i][j] for i, j in distinct_group]
    prob += pulp.lpSum(distinct_group_constraint) == 45

# ... Code to add additional constraints for columns, boxes and 'cages'. Excluded for brevity.

prob.solve()

The problem is I'm struggling to add a stricter constraint that each value in a row must be different. For example, if a row had these values

[1,9,1,9,1,9,1,9,5]

It would pass the constraint above, but would not be a valid sudoku row because each value is not unique.

Below is my attempt to add a stricter constraint, it seems not work, since the problem doesn't solve

for n in range(1, 10):
    for distinct_group in row_groups:
        for i, j in distinct_group:
            distinct_group_constraint = [choices[i][j] == n for i, j in distinct_group]
        prob += pulp.lpSum(distinct_group_constraint) == 1

I have seen several examples online, resolving this by reframing this optimisation as a 9x9x9 choice of binary flags, rather than 9x9 optimisation of choices of integers 1-9. The issue is, I find it hard to see how to check the sums of 'cages' easily in the 9x9x9 case, whist this is quite simple in 9x9 case.

Here is an example of the 9x9x9 setup for a 'non-killer' sudoku. https://github.com/coin-or/pulp/blob/master/examples/Sudoku1.py

# cells (0,0) and (0,1) must sum to 8
cage_constraints = [(8, [[0, 0], [0, 1]])]

for target, cells in cage_constraints:
    cage_cells_constraint = [choices[i][j] for i, j in cells]
    prob += pulp.lpSum(cage_cells_constraint) == target

I am looking to (a) find a way to add this stricter constraint that no choices can be duplicated in the 9x9 setup, or (b) a way to easily add constraints of the 'sum' of cages in the 9x9x9 case. If you would like the entire list of cage-constraints to test on, here are a list of cage-constraints from this puzzle.

CAGE_CONSTRAINTS = [
(8, [[0, 0], [0, 1]]),
(9, [[0, 6], [0, 7]]),
(8, [[0, 2], [1, 2]]),
(12, [[0, 3], [0, 4], [1, 3]]),
(15, [[0, 5], [1, 5], [2, 5]]),
(19, [[1, 6], [1, 7], [2, 7]]),
(16, [[0, 8], [1, 8], [2, 8]]),
(14, [[1, 0], [1, 1], [2, 0]]),
(15, [[2, 1], [2, 2]]),
(10, [[2, 3], [3, 3]]),
(12, [[1, 4], [2, 4]]),
(7, [[2, 6], [3, 6]]),
(24, [[3, 0], [3, 1], [4, 1]]),
(17, [[3, 7], [3, 8], [4, 8]]),
(8, [[3, 2], [4, 2]]),
(12, [[4, 3], [5, 3]]),
(19, [[3, 4], [4, 4], [5, 4]]),
(4, [[3, 5], [4, 5]]),
(15, [[4, 6], [5, 6]]),
(12, [[4, 0], [5, 0], [5, 1]]),
(7, [[4, 7], [5, 7], [5, 8]]),
(8, [[5, 2], [6, 2]]),
(10, [[6, 4], [7, 4]]),
(14, [[5, 5], [6, 5]]),
(12, [[6, 6], [6, 7]]),
(18, [[6, 8], [7, 7], [7, 8]]),
(15, [[6, 0], [7, 0], [8, 0]]),
(13, [[6, 1], [7, 1], [7, 2]]),
(12, [[6, 3], [7, 3], [8, 3]]),
(15, [[7, 5], [8, 4], [8, 5]]),
(7, [[7, 6], [8, 6]]),
(10, [[8, 1], [8, 2]]),
(8, [[8, 7], [8, 8]]),
]

https://www.dailykillersudoku.com/search?dt=2020-02-15

and here is the solution https://www.dailykillersudoku.com/pdfs/19664.solution.pdf

EDIT - if I try changing to a 9x9x9 problem with binary choices, I get results that don't match my desired cage constraints. Here is a snippet.

choices = pulp.LpVariable.dicts(
    "Choice", (range(9), range(9), range(1, 10),), cat="Binary"
)

# add constraints that only one choice for each 'distinct_group'
for n in range(1, 10):
    for distinct_group in distinct_groups:
        for i, j in distinct_group:
        distinct_group_constraint = [choices[i][j][n] for i, j in
distinct_group]
        prob += pulp.lpSum(distinct_group_constraint) == 1

# add constraints that cells in cages must equal 'cage_total'
for target, cells in CAGE_CONSTRAINTS:
    cage_cells_constraint = [
        choices[i][j][n] * n for i, j in cells for n in range(1, 10)
    ]
    prob += pulp.lpSum(cage_cells_constraint) == target

and here is full example https://gist.github.com/olicairns/d8e222526b87a62b2e175837b452c24a

Body:
I would reccomend the use of binary variables - as per the examples you have found. It may seem like more variables but as far as I know use use of a smaller number of integer variables will not help solution time at all - the way the 'branch-and-bound' algorithm for solving a problem with integer variables will mean it's just as inefficient as having more binary variables (someone more familiar with this may be able to correct me).

So to answer the second half of your question:

(b) a way to easily add constraints of the 'sum' of cages in the 9x9x9 case.

This is quite straightforward - you just to a sum-product of the binary variables for a cell by the index which each varaible represents.

If you've already developed all the code assuming your choice of variables (9x9 integer variables), you can add the 9x9x9 binary variables, and then constraint your 9x9 integer variables (which would now be auxiliary variables) as follows:

for i in range(1, 10):
    for j in range(1, 10):
        pulp += choices[i][j] == pulp.lpSum([binary_choices[i][j][k]*k for k in range(1,10)])

You now have both sets of variables - one lot of binary variables, and one lot of integer variables which are linked with equality constraints to behave as required. If you want to avoid all the auxillary variables then you would just need to replace a sum-product with the index value as above anywhere you are currently using your integer variables.

Full working code for completeness:

import pulp

prob = pulp.LpProblem("Sudoku_Problem_KA")
prob += 0, "Arbitrary Objective Function"

CAGE_CONSTRAINTS = [
    (8., [[0, 0], [0, 1]]),
    (9., [[0, 6], [0, 7]]),
    (8., [[0, 2], [1, 2]]),
    (12., [[0, 3], [0, 4], [1, 3]]),
    (15., [[0, 5], [1, 5], [2, 5]]),
    (19., [[1, 6], [1, 7], [2, 7]]),
    (16., [[0, 8], [1, 8], [2, 8]]),
    (14., [[1, 0], [1, 1], [2, 0]]),
    (15., [[2, 1], [2, 2]]),
    (10., [[2, 3], [3, 3]]),
    (12., [[1, 4], [2, 4]]),
    (7., [[2, 6], [3, 6]]),
    (24., [[3, 0], [3, 1], [4, 1]]),
    (17., [[3, 7], [3, 8], [4, 8]]),
    (8., [[3, 2], [4, 2]]),
    (12., [[4, 3], [5, 3]]),
    (19., [[3, 4], [4, 4], [5, 4]]),
    (4., [[3, 5], [4, 5]]),
    (15., [[4, 6], [5, 6]]),
    (12., [[4, 0], [5, 0], [5, 1]]),
    (7., [[4, 7], [5, 7], [5, 8]]),
    (8., [[5, 2], [6, 2]]),
    (10., [[6, 4], [7, 4]]),
    (14., [[5, 5], [6, 5]]),
    (12., [[6, 6], [6, 7]]),
    (18., [[6, 8], [7, 7], [7, 8]]),
    (15., [[6, 0], [7, 0], [8, 0]]),
    (13., [[6, 1], [7, 1], [7, 2]]),
    (12., [[6, 3], [7, 3], [8, 3]]),
    (15., [[7, 5], [8, 4], [8, 5]]),
    (7., [[7, 6], [8, 6]]),
    (10., [[8, 1], [8, 2]]),
    (8., [[8, 7], [8, 8]]),
]

# groups that should only have 1 of each number 1-9
row_groups = [[(i, j) for i in range(9)] for j in range(9)]
col_groups = [[(j, i) for i in range(9)] for j in range(9)]
box_groups = [
    [(3 * i + k, 3 * j + l) for k in range(3) for l in range(3)]
    for i in range(3)
    for j in range(3)
]
distinct_groups = row_groups + col_groups + box_groups

# binary choices: rows, columns and values 1-9
choices = pulp.LpVariable.dicts(
    "choices", (range(9), range(9), range(1, 10)), cat="Binary"
)

# add constraints that only one choice for each 'distinct_group'
for n in range(1, 10):
    for distinct_group in distinct_groups:
        prob += pulp.lpSum([choices[i][j][n] for i, j in distinct_group]) <= 1

# add constraints that cells in cages must equal 'cage_total'
for target, cells in CAGE_CONSTRAINTS:
    prob += pulp.lpSum([choices[i][j][n] * n for i, j in cells for n in range(1, 10)]) >= target

# only pick one binary value per cell:
for i in range(9):
    for j in range(9):
        prob += pulp.lpSum([choices[i][j][n] for n in range(1, 10)]) <= 1

prob.solve()

print('Status:',pulp.LpStatus[prob.status])

# Extract results
res = [[sum([choices[i][j][n].varValue*n for n in range(1,10)]) for j in range(9)] for i in range(9)]

# checking a few constraints match
assert res[8][7] + res[8][8] == 8
assert res[0][0] + res[0][1] == 8

print(res)


问:
Is it possible to dynamically change from FILE_FLAG_SEQUENTIAL_SCAN to FILE_FLAG_RANDOM_ACCESS?
Good afternoon, We are building a prototype of a Windows/LINUX deduper using the memory mapped file API of Windows and Linux. Our deduper starts out by doing a sequential scan of all the database records to be deduped. Therefore , we pass the flag FILE_FLAG_SEQUENTIAL_SCAN to the Windows API CreateFile during our intial sequential scan of the database records to be deduped.
   Once we finish the first part of our deduping process, we try to use the Windows memory mapping API to randomly access the data. At this point, using the Windows C++ API, is it possible to dynamically change to the FILE_FLAG_RANDOM_ACCESS mode?

```<code>In Linux, we are are able to do this with the following excerpt of code,
  MapPtr = (char*)mmap((void *)BaseMapPtr ,mappedlength,PROT_READ,
            MAP_PRIVATE,  hFile,baseoff );
                    if (MapPtr == MAP_FAILED){
                        perror("mmap");
                        throw cException(ERR_MEMORYMAPPING,TempFileName);
                    }
 madvise(MapPtr,mappedlength,MADV_RANDOM);
</code>```

Are we paying a penalty in Windows by using FILE_FLAG_SEQUENTIAL_SCAN  during the random access phase of our deduping process. Thank you.

答:
The caching hint flags passed to CreateFile() do not affect the manner in which the memory manager satisfies page faults generated by de-referencing an address within a mapped section.  Such I/Os use the same  - they use the same cache pages as regular I/O.

That said, when a handle to the file is created with FILE_FLAG_SEQUENTIAL_SCAN, the cache manager may perform read-ahead operations (and may even read the entire file into memory, if system conditions allow for this).  Which means that that you may encounter fewer hard page faults if you sequentially access the pages of the mapped file.

it seems to me that you'd be best served by simply re-using the handle you've created during your de-dup processing.  Closing and re-opening may cause previously cached pages of the file to be discarded, depending on cache pressure.

ContentLicense: CC BY-SA 3.0

Body:
Good afternoon, We are building a prototype of a Windows/LINUX deduper using the memory mapped file API of Windows and Linux. Our deduper starts out by doing a sequential scan of all the database records to be deduped. Therefore , we pass the flag FILE_FLAG_SEQUENTIAL_SCAN to the Windows API CreateFile during our intial sequential scan of the database records to be deduped.
   Once we finish the first part of our deduping process, we try to use the Windows memory mapping API to randomly access the data. At this point, using the Windows C++ API, is it possible to dynamically change to the FILE_FLAG_RANDOM_ACCESS mode?

In Linux, we are are able to do this with the following excerpt of code,
  MapPtr = (char*)mmap((void *)BaseMapPtr ,mappedlength,PROT_READ,
            MAP_PRIVATE,  hFile,baseoff );
                    if (MapPtr == MAP_FAILED){
                        perror("mmap");
                        throw cException(ERR_MEMORYMAPPING,TempFileName);
                    }
 madvise(MapPtr,mappedlength,MADV_RANDOM);

Are we paying a penalty in Windows by using FILE_FLAG_SEQUENTIAL_SCAN  during the random access phase of our deduping process. Thank you.


问:
Shared GameSettings with U-Net
I have a scene where the player has the option to choose settings for the match they are creating (number of rounds, time per round etc..), I also have a utility class MatchSettings that contains all of these settings, when I run the game on the host everything works fine, however when a client joins the game, the clients match settings are 0 for everything, The settings are used as part of a GameManager class that implements a singleton pattern with a MatchSettings member. So my question is how can I have all the participants of the game share the same settings? ( I am aware that u-net is deprecated)

The Relevant Code for the GameManager:

```<code>public class GameManager : MonoBehaviour
{
    public static GameManager instance;
    public MatchSettings settings;
    void Awake()
    {
        if(instance != null)
        {
            Debug.LogError("Too many game managers");
        }
        else
        {
            instance = this;
            respawnCamera.SetActive(false);
            settings = new MatchSettings();
            timePassed = settings.roundTime * 60;
            roundsPlayed = 0;
            highestKills = 0;
        }
    }
     void Update()
     {
        timePassed -= Time.deltaTime;
        if (timePassed < 0 || highestKills >= settings.maxKills)
        {
            Debug.Log(settings.roundTime); //prints 0 at client runtime
            RoundOver();
        }
        if(roundsPlayed >= settings.roundCount)
        {
            GameOver();
        }
    }
}
</code>```

The relevant code for the MatchSettings:

```<code>[System.Serializable]
public class MatchSettings
{

    public  float roundovertime = 10f;
    public static float roundtime; // the variables from the UI scene are stored in the static members and transferred
    public static int maxkills; // into the regular ones when MatchSettings() is called [in awake in game  manager]
    public static int roundcount;
    public float respawntime = 5f;
    public float roundTime;
    public int maxKills;
    public int roundCount;
    public MatchSettings()
    {
        roundTime = roundtime;
        maxKills = maxkills;
        roundCount = roundcount;
    }
}
</code>```

Thanks in advance!

答:
Unless you synchronize MatchSettings to all clients, you will always have the default values there (zeros in this case).

One way about it using UNET is using SyncVar - You will need to have the settings on a gameobject in the scene, owned by the server which will be your "source of truth".

You only perform changes on the server side, and it will be automatically updated to all clients.

Pseudo-code example:

```<code>class GameSettings : NetworkBehaviour {
 [SyncVar(hook=nameof(FragsRequiredAmountSyncVarChanged))] private int _fragsRequiredToWinSyncVar = 20;

 public void ChangeFragsRequiredToWin(int newAmount) {
  if (!isServer) {
   Debug.LogError("Sync vars can only change on the server!");
   return;
  }
  _fragsRequiredToWinSyncVar = newAmount;
 }

 private void FragsRequiredAmountSyncVarChanged(int newAmount)
 {
  Debug.Log($"Frag requirement changed to {newAmount}");
 }
}
</code>```

I've also included an example on how to attach hooks when the SyncVar changes; I'm pretty sure it gets called on both the server and the client, but my memory might fail me since it's been quite a while since I last used UNET.

Title: Shared GameSettings with U-Net

Body:
I have a scene where the player has the option to choose settings for the match they are creating (number of rounds, time per round etc..), I also have a utility class MatchSettings that contains all of these settings, when I run the game on the host everything works fine, however when a client joins the game, the clients match settings are 0 for everything, The settings are used as part of a GameManager class that implements a singleton pattern with a MatchSettings member. So my question is how can I have all the participants of the game share the same settings? ( I am aware that u-net is deprecated)

The Relevant Code for the GameManager:

public class GameManager : MonoBehaviour
{
    public static GameManager instance;
    public MatchSettings settings;
    void Awake()
    {
        if(instance != null)
        {
            Debug.LogError("Too many game managers");
        }
        else
        {
            instance = this;
            respawnCamera.SetActive(false);
            settings = new MatchSettings();
            timePassed = settings.roundTime * 60;
            roundsPlayed = 0;
            highestKills = 0;
        }
    }
     void Update()
     {
        timePassed -= Time.deltaTime;
        if (timePassed < 0 || highestKills >= settings.maxKills)
        {
            Debug.Log(settings.roundTime); //prints 0 at client runtime
            RoundOver();
        }
        if(roundsPlayed >= settings.roundCount)
        {
            GameOver();
        }
    }
}

The relevant code for the MatchSettings:

[System.Serializable]
public class MatchSettings
{

    public  float roundovertime = 10f;
    public static float roundtime; // the variables from the UI scene are stored in the static members and transferred
    public static int maxkills; // into the regular ones when MatchSettings() is called [in awake in game  manager]
    public static int roundcount;
    public float respawntime = 5f;
    public float roundTime;
    public int maxKills;
    public int roundCount;
    public MatchSettings()
    {
        roundTime = roundtime;
        maxKills = maxkills;
        roundCount = roundcount;
    }
}

Thanks in advance!

Body:
Unless you synchronize MatchSettings to all clients, you will always have the default values there (zeros in this case).

One way about it using UNET is using SyncVar - You will need to have the settings on a gameobject in the scene, owned by the server which will be your "source of truth".

You only perform changes on the server side, and it will be automatically updated to all clients.

Pseudo-code example:

class GameSettings : NetworkBehaviour {
 [SyncVar(hook=nameof(FragsRequiredAmountSyncVarChanged))] private int _fragsRequiredToWinSyncVar = 20;

 public void ChangeFragsRequiredToWin(int newAmount) {
  if (!isServer) {
   Debug.LogError("Sync vars can only change on the server!");
   return;
  }
  _fragsRequiredToWinSyncVar = newAmount;
 }

 private void FragsRequiredAmountSyncVarChanged(int newAmount)
 {
  Debug.Log($"Frag requirement changed to {newAmount}");
 }
}

I've also included an example on how to attach hooks when the SyncVar changes; I'm pretty sure it gets called on both the server and the client, but my memory might fail me since it's been quite a while since I last used UNET.


问:
Login using Selenium Python?
I cannot login to this site.

This is the url.

https://swayam.gov.in/azurelogin?continue=/

What I tried:

```<code>from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://swayam.gov.in/azurelogin?continue=/")
login_google_btn = driver.find_element_by_xpath('//*[@id="GoogleExchange"]')
login_google_btn.click()
</code>```

I need to login with google and hence required to click that button.

Output:

```<code>raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate
element: {"method":"xpath","selector":"//*[@id="next"]"}
(Session info: chrome=80.0.3987.106)
</code>```

Then, I checked to send keys to the username and password fields, but encountered similar error.

What's going wrong?

答:
It seems it uses JavaScript to load data and you have to wait a little for elements on page.

You can use time.sleep(1) or driver.implicitly_wait(1) to wait 1 second.

```<code>from selenium import webdriver
#import time

driver = webdriver.Chrome()
driver.implicitly_wait(1)

driver.get("https://swayam.gov.in/azurelogin?continue=/")
#time.sleep(1)

#login_google_btn = driver.find_element_by_id('GoogleExchange')
login_google_btn = driver.find_element_by_xpath('//*[@id="GoogleExchange"]')
login_google_btn.click()
</code>```

See doc Waits for other methods.

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://swayam.gov.in/azurelogin?continue=/")

wait = WebDriverWait(driver, 10)
#login_google_btn = wait.until(EC.element_to_be_clickable((By.ID, 'GoogleExchange')))
login_google_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="GoogleExchange"]')))
login_google_btn.click()
</code>```

Title: Login using Selenium Python?

Body:
I cannot login to this site.

This is the url.

https://swayam.gov.in/azurelogin?continue=/

What I tried:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://swayam.gov.in/azurelogin?continue=/")
login_google_btn = driver.find_element_by_xpath('//*[@id="GoogleExchange"]')
login_google_btn.click()

I need to login with google and hence required to click that button.

Output:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate
element: {"method":"xpath","selector":"//*[@id="next"]"}
(Session info: chrome=80.0.3987.106)

Then, I checked to send keys to the username and password fields, but encountered similar error.

What's going wrong?

Body:
It seems it uses JavaScript to load data and you have to wait a little for elements on page.

You can use time.sleep(1) or driver.implicitly_wait(1) to wait 1 second.

from selenium import webdriver
#import time

driver = webdriver.Chrome()
driver.implicitly_wait(1)

driver.get("https://swayam.gov.in/azurelogin?continue=/")
#time.sleep(1)

#login_google_btn = driver.find_element_by_id('GoogleExchange')
login_google_btn = driver.find_element_by_xpath('//*[@id="GoogleExchange"]')
login_google_btn.click()

See doc Waits for other methods.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://swayam.gov.in/azurelogin?continue=/")

wait = WebDriverWait(driver, 10)
#login_google_btn = wait.until(EC.element_to_be_clickable((By.ID, 'GoogleExchange')))
login_google_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="GoogleExchange"]')))
login_google_btn.click()


问:
Scroll RecyclerView to show selected item on top
I'm looking for a way to scroll a RecyclerView to show the selected item on top.

In a ListView I was able to do that by using scrollTo(x,y) and getting the top of the element that need to be centered.

Something like:

```<code>@Override
public void onItemClick(View v, int pos){
    mylistView.scrollTo(0, v.getTop());
}
</code>```

The problem is that the RecyclerView returns an error when using it's scrollTo method saying

RecyclerView does not support scrolling to an absolute position

How can I scroll a RecyclerView to put the selected item at the top of the view?

答:
If your LayoutManager is LinearLayoutManager you can use scrollToPositionWithOffset(position,0); on it and it will make your item the first visible item in the list. Otherwise, you can use smoothScrollToPosition on the RecyclerView directly.

I ended up using the below code.

```<code> RecyclerView.LayoutManager layoutManager = mainList.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            // Scroll to item and make it the first visible item of the list.
            ((LinearLayoutManager) layoutManager).scrollToPositionWithOffset(position, 0);
        } else {
            mainList.smoothScrollToPosition(position);
        }
</code>```

Body:
I'm looking for a way to scroll a RecyclerView to show the selected item on top.

In a ListView I was able to do that by using scrollTo(x,y) and getting the top of the element that need to be centered.

Something like:

@Override
public void onItemClick(View v, int pos){
    mylistView.scrollTo(0, v.getTop());
}

The problem is that the RecyclerView returns an error when using it's scrollTo method saying

RecyclerView does not support scrolling to an absolute position

How can I scroll a RecyclerView to put the selected item at the top of the view?

Body:
If your LayoutManager is LinearLayoutManager you can use scrollToPositionWithOffset(position,0); on it and it will make your item the first visible item in the list. Otherwise, you can use smoothScrollToPosition on the RecyclerView directly.

I ended up using the below code.

 RecyclerView.LayoutManager layoutManager = mainList.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            // Scroll to item and make it the first visible item of the list.
            ((LinearLayoutManager) layoutManager).scrollToPositionWithOffset(position, 0);
        } else {
            mainList.smoothScrollToPosition(position);
        }


问:
HttpException Request Time out
i can past this url into my browser and get the server time, https://api.binance.je/api/v3/time

But i am unable to get a response using below code. How can i debug this

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            Console.WriteLine(response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}
</code>```

答:
The problem was down to my vpn. Even though i didnt have an active connection. I killed the background service and restarted it and is now working

Similar issue
  httpclient-getasync-times-out-when-connected-to-vpn

Title: HttpException Request Time out

Body:
i can past this url into my browser and get the server time, https://api.binance.je/api/v3/time

But i am unable to get a response using below code. How can i debug this

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create("https://api.binance.je/api/v3/time");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            Console.WriteLine(response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}


问:
Set Start Value as '0' With Dynamic Data In Chart.js
I've a problem when I used this chart with dynamic data. Does anybody know how to set start value as '0' in chart.js with dynamic data ? Thanks in advance</p>

答:
Supposing your values are displayed on the y-axis, you can define beginAtZero: true for the yAxis ticks inside the chart options.

```<code>options: {
  scales: {
    yAxes: [{
      ticks: {
        beginAtZero: true
      }
    }]
  }
}
</code>```

Alternatively you may

Body:
Supposing your values are displayed on the y-axis, you can define beginAtZero: true for the yAxis ticks inside the chart options.

options: {
  scales: {
    yAxes: [{
      ticks: {
        beginAtZero: true
      }
    }]
  }
}

Alternatively you may


问:
Execute YAML templates from Azure DevOps classic pipeline
I would put my questions through following points, hope it's make clear now:

The application source code is in application_code repo.

The pipeline code(YAMLs) are in pipeline_code repo. Because I'd like to version it and don't like to keep in application_code repo. Just to avoid giving control to Dev team to manage it.

Problem statement:

The pipeline YAML won't be triggered unless it's in the source code repository based on the events pr, commit etc.

Can we trigger or execute YAML file which is in pipeline_repo whenever there's event triggered in application_code repo?

I've tried achieving above using Classic pipeline and YAML template but this don't work together. As I can execute a YAML template from a YAML pipeline only not from a classic pipeline like below:

```<code>#azure-pipeline.yaml
jobs:
  - job: NewJob
  - template: job-template-bd1.yaml
</code>```

Any ideas or better solution than above?

答:
The feature Multi-repository support for YAML pipelines will be available soon for azure devops service. This feature will support for triggering pipelines based on changes made in one of multiple repositories. Please check Azure DevOps Feature Timeline or here. This feature is expected to be rolled out in 2020 Q1 for azure devops service.

Currently you can follow below workaround to achieve above using Build Completion(the pipeline will be triggered on the completion of another build).

1, Setup the triggering pipeline

Create an empty classic pipeline for application_code repo as the triggering pipeline, which will always succeed and do nothing.

And check Enable continuous integration under Triggers tab and setup Bracnh filters

2, setup the triggered pipeline

In the pipeline_code repo using Checkout to Check out multiple repositories in your pipeline. You can specifically checkout the source code of  application_code repo to build. Please refer below example:

```<code>steps:
  - checkout: git://MyProject/application_code_repo@refs/heads/master # Azure Repos Git repository in the same organization

  - task: TaskName
     ...
</code>```

Then in the yaml pipeline edit page, click the 3dots on the top right corner and click Triggers. Then click +Add beside Build Completion and select above triggering pipeline created in step 1 as the triggering build.

After finishing above two steps, when changes made to application_code repo, the triggering pipeline will be executed and completed with success. Then the triggered pipeline will be triggered to run the real build job.

Update:

Show Azure DevOps Build Pipeline Status in Bitbucket.

you can add a python script task at the end of the yaml pipeline to update the Bitbucket build status. You need to set a condtion: always() to always run this task even if other tasks are failed.

You can get the build status with env variable Agent.JobStatus.  For below example:

For more information, please refer to document Integrate your build system with Bitbucket Cloud, and also this thread.

```<code>  - task: PythonScript@0
      condition: always()
      inputs:
        scriptSource: inline
        script: |
          import os
          import requests

          # Use environment variables that your CI server provides to the key, name,
          # and url parameters, as well as commit hash. (The values below are used by
          # Jenkins.)
          data = {
              'key': os.getenv('BUILD_ID'),
              'state': os.getenv('Agent.JobStatus'),
              'name': os.getenv('JOB_NAME'),
              'url': os.getenv('BUILD_URL'),
              'description': 'The build passed.'
          }

          # Construct the URL with the API endpoint where the commit status should be
          # posted (provide the appropriate owner and slug for your repo).
          api_url = ('https://api.bitbucket.org/2.0/repositories/'
                    '%(owner)s/%(repo_slug)s/commit/%(revision)s/statuses/build'
                    % {'owner': 'emmap1',
                        'repo_slug': 'MyRepo',
                        'revision': os.getenv('GIT_COMMIT')})

          # Post the status to Bitbucket. (Include valid credentials here for basic auth.
          # You could also use team name and API key.)
          requests.post(api_url, auth=('auth_user', 'auth_password'), json=data)
</code>```

Body:
I would put my questions through following points, hope it's make clear now:

The application source code is in application_code repo.

The pipeline code(YAMLs) are in pipeline_code repo. Because I'd like to version it and don't like to keep in application_code repo. Just to avoid giving control to Dev team to manage it.

Problem statement:

The pipeline YAML won't be triggered unless it's in the source code repository based on the events pr, commit etc.

Can we trigger or execute YAML file which is in pipeline_repo whenever there's event triggered in application_code repo?

I've tried achieving above using Classic pipeline and YAML template but this don't work together. As I can execute a YAML template from a YAML pipeline only not from a classic pipeline like below:

#azure-pipeline.yaml
jobs:
  - job: NewJob
  - template: job-template-bd1.yaml

Any ideas or better solution than above?

Body:
The feature Multi-repository support for YAML pipelines will be available soon for azure devops service. This feature will support for triggering pipelines based on changes made in one of multiple repositories. Please check Azure DevOps Feature Timeline or here. This feature is expected to be rolled out in 2020 Q1 for azure devops service.

Currently you can follow below workaround to achieve above using Build Completion(the pipeline will be triggered on the completion of another build).

1, Setup the triggering pipeline

Create an empty classic pipeline for application_code repo as the triggering pipeline, which will always succeed and do nothing.

And check Enable continuous integration under Triggers tab and setup Bracnh filters

2, setup the triggered pipeline

In the pipeline_code repo using Checkout to Check out multiple repositories in your pipeline. You can specifically checkout the source code of  application_code repo to build. Please refer below example:

steps:
  - checkout: git://MyProject/application_code_repo@refs/heads/master # Azure Repos Git repository in the same organization

  - task: TaskName
     ...

Then in the yaml pipeline edit page, click the 3dots on the top right corner and click Triggers. Then click +Add beside Build Completion and select above triggering pipeline created in step 1 as the triggering build.

After finishing above two steps, when changes made to application_code repo, the triggering pipeline will be executed and completed with success. Then the triggered pipeline will be triggered to run the real build job.

Update:

Show Azure DevOps Build Pipeline Status in Bitbucket.

you can add a python script task at the end of the yaml pipeline to update the Bitbucket build status. You need to set a condtion: always() to always run this task even if other tasks are failed.

You can get the build status with env variable Agent.JobStatus.  For below example:

For more information, please refer to document Integrate your build system with Bitbucket Cloud, and also this thread.

  - task: PythonScript@0
      condition: always()
      inputs:
        scriptSource: inline
        script: |
          import os
          import requests

          # Use environment variables that your CI server provides to the key, name,
          # and url parameters, as well as commit hash. (The values below are used by
          # Jenkins.)
          data = {
              'key': os.getenv('BUILD_ID'),
              'state': os.getenv('Agent.JobStatus'),
              'name': os.getenv('JOB_NAME'),
              'url': os.getenv('BUILD_URL'),
              'description': 'The build passed.'
          }

          # Construct the URL with the API endpoint where the commit status should be
          # posted (provide the appropriate owner and slug for your repo).
          api_url = ('https://api.bitbucket.org/2.0/repositories/'
                    '%(owner)s/%(repo_slug)s/commit/%(revision)s/statuses/build'
                    % {'owner': 'emmap1',
                        'repo_slug': 'MyRepo',
                        'revision': os.getenv('GIT_COMMIT')})

          # Post the status to Bitbucket. (Include valid credentials here for basic auth.
          # You could also use team name and API key.)
          requests.post(api_url, auth=('auth_user', 'auth_password'), json=data)


问:
How can I re-sort a sorted array by absolute values, in linear time?
You are given a sorted array containing both negative and positive values. Resort the array taking absolute value of negative numbers. Your complexity should be O(n)

Sample Input

```<code>[-8, -5, -3, -1, 3, 6, 9]
</code>```

Expected Output

```<code>[ -1, -3, 3, -5, 6, -8, 9 ]
</code>```

I have done this till now, but output is not correct.

```<code>function sortMe(input) {
   var newArr = [];
   for (var i = 0; i < input.length; i++) {
     var value = Math.abs(input[i]);
     newArr.push(value);
   }
   var c = newArr.sort()
}
</code>```

and it is giving output

```<code>[ 1, 3, 3, 5, 6, 8, 9 ]
</code>```

答:
Here is the code in Python</p>

```<code>    def sorted_array(list1):
        list_negative=[]
        list_positive=[]

        for i in list1:
        if i<0:
            list_negative.append(i)
        else:
            list_positive.append(i)

        list_negative.reverse()

        for i in list_negative:
            for j in range(0, len(list_positive)):
                if abs(i)<=list_positive[j]:
                    list_positive.insert(j,i)
                    break
        print(list_positive)
    list1=[-8,-5,-3,-1,3,6,9,-4]
    sorted_array(list1)
</code>```

Body:
You are given a sorted array containing both negative and positive values. Resort the array taking absolute value of negative numbers. Your complexity should be O(n)

Sample Input

[-8, -5, -3, -1, 3, 6, 9]

Expected Output

[ -1, -3, 3, -5, 6, -8, 9 ]

I have done this till now, but output is not correct.

function sortMe(input) {
   var newArr = [];
   for (var i = 0; i < input.length; i++) {
     var value = Math.abs(input[i]);
     newArr.push(value);
   }
   var c = newArr.sort()
}

and it is giving output

[ 1, 3, 3, 5, 6, 8, 9 ]

Body:
Here is the code in Python

    def sorted_array(list1):
        list_negative=[]
        list_positive=[]

        for i in list1:
        if i<0:
            list_negative.append(i)
        else:
            list_positive.append(i)

        list_negative.reverse()

        for i in list_negative:
            for j in range(0, len(list_positive)):
                if abs(i)<=list_positive[j]:
                    list_positive.insert(j,i)
                    break
        print(list_positive)
    list1=[-8,-5,-3,-1,3,6,9,-4]
    sorted_array(list1)


问:
Collapsible not expanding
I have a button containing a div with contents. When clicking the div, I want the collapsed content to expand. Upon hovering above the div, it changes color and the pointer changes, just as I like. However, upon clicking nothing happens: the collapsed content does not expand. What is wrong with my code?

var coll = document.getElementsByClassName("contents");
var i;
for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var collapse = this.nextElementSibling;
    if (collapse.style.display === "block") {
      collapse.style.display = "none";
    } else {
      collapse.style.display = "block";
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="results">

  <button type="button" class="contents">
          <div class="info">
            ...
          </div>
          </button>
  <div class="collapse">
    <p>Text only shown when expanding</p>
  </div>

</div></code>```

答:
It is better for you to use jQuery as a client-side framework for better performance, cross-browser and fewer lines of code.

You can use $('.collapse').slideToggle() function for your project. Documentation

Title: Collapsible not expanding

Body:
I have a button containing a div with contents. When clicking the div, I want the collapsed content to expand. Upon hovering above the div, it changes color and the pointer changes, just as I like. However, upon clicking nothing happens: the collapsed content does not expand. What is wrong with my code?

var coll = document.getElementsByClassName("contents");
var i;
for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var collapse = this.nextElementSibling;
    if (collapse.style.display === "block") {
      collapse.style.display = "none";
    } else {
      collapse.style.display = "block";
    }
  });
}

  <button type="button" class="contents">

            ...

          </button>

Text only shown when expanding


问:
Prolog jargon: id(X,X). fact or rule?
In Prolog, this is unambiguously a fact:

```<code>foo(bar).
</code>```

And this is unambiguously a rule:

```<code>foo(X) :- bar(X).
</code>```

But what about a clause that has both non-singleton variables and no :- such as

```<code>identity(X,X).
</code>```

or more realistically something like

```<code>my_member(X, [X|_]).
</code>```

I've been calling these rules since I learned Prolog, but now that I've tried to check to be 100% sure, I can't seem to find any source making a stronger distinction than what I have in the first two examples.

So is a rule:

a clause that defines a variable logical relationship, i.e. a clause that will not always succeed.

a clause that that defines a relationship between predicates (or possibly a predicate and itself).

答:
Sometimes terminology itself causes problems the actual Prolog systems do not have at all. In common terminology as well as standard terminology, both identity(X,X). and my_member(X, [X|_]). are facts. However, better use clause when this seems fit.

The unease stems from the set of solutions that are implied by such cases. In fact, there is an infinity of solutions for both examples. Otherwise, ground facts just describe one solution each. Sticking to ground facts only, simplifies bottom-up interpretations.

So what about the clause a :- true. Is it a fact or a rule? It uses a rule-atom. but it's body is true. A Note in 3.72 excludes (:-)/2 as principal functor of facts. Well, all of this is a clear indication that terminology is here a bit too fine grained.

So, stick as much as you can to clause.

Title: Prolog jargon: id(X,X). fact or rule?

Body:
In Prolog, this is unambiguously a fact:

foo(bar).

And this is unambiguously a rule:

foo(X) :- bar(X).

But what about a clause that has both non-singleton variables and no :- such as

identity(X,X).

or more realistically something like

my_member(X, [X|_]).

I've been calling these rules since I learned Prolog, but now that I've tried to check to be 100% sure, I can't seem to find any source making a stronger distinction than what I have in the first two examples.

So is a rule:

a clause that defines a variable logical relationship, i.e. a clause that will not always succeed.

a clause that that defines a relationship between predicates (or possibly a predicate and itself).


问:
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`. in Mac
I am setting up an Android development environment. However, there is a problem in the execution environment. I've already finished the configuration, but I keep saying I can't find the device. However, if you run the server and then run it in the Android studio, it will work normally. What's the problem?

bash_profile

```<code>export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home
export PATH=${PATH}:$JAVA_HOME/bin
export ANDROID_PATH=/Users/myname/Library/Android
export PATH=$PATH:$ANDROID_PATH/sdk/platform-tools
export PATH=$PATH:$ANDROID_PATH/sdk/emulator
export PATH=$PATH:$ANDROID_PATH/sdk/tools
export PATH=$PATH:$ANDROID_PATH/sdk/tools/bin
</code>```

But Error

```<code>$ npx react-native run-android

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 864 file(s) to forward-jetify. Using 8 workers...
info Starting JS server...
/bin/sh: adb: command not found
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon, 5 stopped Daemons could not be reused, use --status for details

> Task :app:stripDebugDebugSymbols UP-TO-DATE
Compatible side by side NDK version was not found.

> Task :app:installDebug

> Task :app:installDebug FAILED
27 actionable tasks: 9 executed, 18 up-to-date
[adb]: * daemon not running; starting now at tcp:5037
[adb]: * daemon started successfully

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: No connected devices!

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 22s

error Failed to install the app. Make sure you have an Android emulator running or a device connected. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
[adb]: * daemon not running; starting now at tcp:5037
[adb]: * daemon started successfully

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: No connected devices!

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 22s

    at checkExecSyncError (child_process.js:611:11)
    at execFileSync (child_process.js:629:15)
    at runOnAllDevices (/Users/myname/AwesomeProject/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:39)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
</code>```

Is there anyone who has the same problem as me?

答:
Try the following:

```<code>> vim ~/.bash_profile
</code>```

Add the following lines:

```<code>export ANDROID_HOME=/Users/myname/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
export PATH=$PATH:$ANDROID_PATH/emulator
export PATH=$PATH:$ANDROID_PATH/tools/bin
</code>```

Save changes and restart terminal.

Run ADB and if you got following it will work.

```<code>> adb devices

List of devices attached

emulator-5554   device
</code>```

Body:
I am setting up an Android development environment. However, there is a problem in the execution environment. I've already finished the configuration, but I keep saying I can't find the device. However, if you run the server and then run it in the Android studio, it will work normally. What's the problem?

bash_profile

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home
export PATH=${PATH}:$JAVA_HOME/bin
export ANDROID_PATH=/Users/myname/Library/Android
export PATH=$PATH:$ANDROID_PATH/sdk/platform-tools
export PATH=$PATH:$ANDROID_PATH/sdk/emulator
export PATH=$PATH:$ANDROID_PATH/sdk/tools
export PATH=$PATH:$ANDROID_PATH/sdk/tools/bin

But Error

$ npx react-native run-android

info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 864 file(s) to forward-jetify. Using 8 workers...
info Starting JS server...
/bin/sh: adb: command not found
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon, 5 stopped Daemons could not be reused, use --status for details

> Task :app:stripDebugDebugSymbols UP-TO-DATE
Compatible side by side NDK version was not found.

> Task :app:installDebug

> Task :app:installDebug FAILED
27 actionable tasks: 9 executed, 18 up-to-date
[adb]: * daemon not running; starting now at tcp:5037
[adb]: * daemon started successfully

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: No connected devices!

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 22s

error Failed to install the app. Make sure you have an Android emulator running or a device connected. Run CLI with --verbose flag for more details.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
[adb]: * daemon not running; starting now at tcp:5037
[adb]: * daemon started successfully

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: No connected devices!

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 22s

    at checkExecSyncError (child_process.js:611:11)
    at execFileSync (child_process.js:629:15)
    at runOnAllDevices (/Users/myname/AwesomeProject/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:39)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Is there anyone who has the same problem as me?

Body:
Try the following:

> vim ~/.bash_profile

Add the following lines:

export ANDROID_HOME=/Users/myname/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
export PATH=$PATH:$ANDROID_PATH/emulator
export PATH=$PATH:$ANDROID_PATH/tools/bin

Save changes and restart terminal.

Run ADB and if you got following it will work.

> adb devices

List of devices attached

emulator-5554   device


问:
Fetch nested data from MongoDB
I have a collection in the following format.

```<code>{
    "_id": "ffffc446-f33d",
    "className": "com.ezdx.vist.model.Visit",
    "organizationId": "0a0beff7-fe1e-4ab7",
    "centerId": "9aef68fe-dffd-4a7d-b0ee-f8dd3fc03303",
    "tests": [{
            "result": 157,
            "type": "PHYSICAL",
            **"name": "HEIGHT",**
            "consumableQuantity": 0,
            "testCost": 0,
            "testExpenseConsumable": 0

        },
        {
            "result": 8,
            "type": "RDT",
            **"name": "URIC",**
            "consumableQuantity": 0,
            "testCost": 0,
            "testExpenseConsumable": 0
        }

    ],
    "repeatVisit": true
}
</code>```

I want the collection where test.name = "Uric" and with particular columns.

```<code>  {
    "result": 8,
    "type": "RDT",
    **"name": "Uric",**
    "consumableQuantity": 0,
    "testCost": 0,
    "testExpenseConsumable": 0
}
</code>```

Somehow I manage to the desired collections but I am not able to get the desired format.
Below is my query

```<code>db.visits.aggregate( [ { $unwind : "$tests" },
{ $match: { $and: [{"tests.name":"URIC"}]
    } } ] )
</code>```

答:
Try this: $replaceWith (=v4.2) or $replaceRoot  (>=v3.4)

```<code>db.visits.aggregate([
  {
    $unwind: "$tests"
  },
  {
    $match: {
      "tests.name": "URIC"
    }
  },
  {
    $replaceWith: "$tests"
  }
])
</code>```

MongoPlayground

Title: Fetch nested data from MongoDB

Body:
I have a collection in the following format.

{
    "_id": "ffffc446-f33d",
    "className": "com.ezdx.vist.model.Visit",
    "organizationId": "0a0beff7-fe1e-4ab7",
    "centerId": "9aef68fe-dffd-4a7d-b0ee-f8dd3fc03303",
    "tests": [{
            "result": 157,
            "type": "PHYSICAL",
            **"name": "HEIGHT",**
            "consumableQuantity": 0,
            "testCost": 0,
            "testExpenseConsumable": 0

        },
        {
            "result": 8,
            "type": "RDT",
            **"name": "URIC",**
            "consumableQuantity": 0,
            "testCost": 0,
            "testExpenseConsumable": 0
        }

    ],
    "repeatVisit": true
}

I want the collection where test.name = "Uric" and with particular columns.

  {
    "result": 8,
    "type": "RDT",
    **"name": "Uric",**
    "consumableQuantity": 0,
    "testCost": 0,
    "testExpenseConsumable": 0
}

Somehow I manage to the desired collections but I am not able to get the desired format.
Below is my query

db.visits.aggregate( [ { $unwind : "$tests" },
{ $match: { $and: [{"tests.name":"URIC"}]
    } } ] )

Body:
Try this: $replaceWith (=v4.2) or $replaceRoot  (>=v3.4)

db.visits.aggregate([
  {
    $unwind: "$tests"
  },
  {
    $match: {
      "tests.name": "URIC"
    }
  },
  {
    $replaceWith: "$tests"
  }
])

MongoPlayground


问:
Improving performance of ifstream in c++
I apologize if this question is a bit vague or just plain stupid, I am still very much a novice.

I need to extract information from a web log file in c++. The string manipulations are relatively, accessing the data in a timely fashion isn't.
What I am doing currently

string str;

ifstream fh("testlog.log",ios::in);

while (getline(fh,str));

From here I get the useful data from the string. This works fine for a log file with 100 entries, but takes forever on a log file with million+ entries.
Any help would greatly be appreciated

答:
@Errata:

are you sure, that your code would be faster than say:

```<code>std::ifstream in("test.txt");
in.unsetf(std::ios::skipws);
std::string contents;
std::copy(
        std::istream_iterator<char>(in),
        std::istream_iterator<char>(),
        std::back_inserter(contents));
</code>```

Also, the OP wants linewise access, which would conveniently be done:

```<code>std::ifstream in("test.txt");
in.unsetf(std::ios::skipws);
size_t count = std::count_if(
        std::istream_iterator<std::string>(in),
        std::istream_iterator<std::string>(),
        &is_interesting);
std::cout << "Interesting log lines: " << count << std::endl;
</code>```

of course define a predicate, e.g.

```<code>static bool is_interesting(const std::string& line)
{
    return std::string::npos != line.find("FATAL");
}
</code>```

Body:
@Errata:

are you sure, that your code would be faster than say:

std::ifstream in("test.txt");
in.unsetf(std::ios::skipws);
std::string contents;
std::copy(
        std::istream_iterator<char>(in),
        std::istream_iterator<char>(),
        std::back_inserter(contents));

Also, the OP wants linewise access, which would conveniently be done:

std::ifstream in("test.txt");
in.unsetf(std::ios::skipws);
size_t count = std::count_if(
        std::istream_iterator<std::string>(in),
        std::istream_iterator<std::string>(),
        &is_interesting);
std::cout << "Interesting log lines: " << count << std::endl;

of course define a predicate, e.g.

static bool is_interesting(const std::string& line)
{
    return std::string::npos != line.find("FATAL");
}


问:
Is it possible to test this Kotlin class?
I am trying to write unit test cases for a Kotlin class A and trying to mock return client() call present in test() method to unit test test() method:

```<code>A.kt kotlin class:
class A (par 1, par 2) : B(par 1, par 2) {
   override fun test(item: String): Boolean {
      return client()
   }
}

B.kt kotlin class:
abstract class B(par 1, par 2) {
    private val client: WebClient by lazy {
        //does something
    }
    protected fun client(): WebClient = client
}
</code>```

Is it possible to mock the client() call in test() method?
And if possible how to do it and what library should I use for mocking?

答:
This should be doable using Mockito testing framework. However, mocking an object returned from a object's method would require mocking the object itself.

```<code>val mockOfA = Mockito.mock(A::class)
val mockOfClient = Mockito.mock(WebClient:class)
Mockito.when(mockOfA.test(anyString())).thenReturn(mockOfClient)  // Mind your original snippet return type Boolean from A.test()
</code>```

If your class A implements internal logic you want to test in your test scenario, there are two possible paths:

Create a Spy instead of a Mock. Mocks do only whatever you explicitly set them up to do. Spy 'falls back' to original implementation when it is not given any mock behaviour.

Rewrite you class A so that it depends on external dependency of a ClientProvider to get an instance of WebClient to return in method test() and inject a mock of said provider to your object of type A during the test.

Body:
I am trying to write unit test cases for a Kotlin class A and trying to mock return client() call present in test() method to unit test test() method:

A.kt kotlin class:
class A (par 1, par 2) : B(par 1, par 2) {
   override fun test(item: String): Boolean {
      return client()
   }
}

B.kt kotlin class:
abstract class B(par 1, par 2) {
    private val client: WebClient by lazy {
        //does something
    }
    protected fun client(): WebClient = client
}

Is it possible to mock the client() call in test() method?
And if possible how to do it and what library should I use for mocking?

Body:
This should be doable using Mockito testing framework. However, mocking an object returned from a object's method would require mocking the object itself.

val mockOfA = Mockito.mock(A::class)
val mockOfClient = Mockito.mock(WebClient:class)
Mockito.when(mockOfA.test(anyString())).thenReturn(mockOfClient)  // Mind your original snippet return type Boolean from A.test()

If your class A implements internal logic you want to test in your test scenario, there are two possible paths:

Create a Spy instead of a Mock. Mocks do only whatever you explicitly set them up to do. Spy 'falls back' to original implementation when it is not given any mock behaviour.

Rewrite you class A so that it depends on external dependency of a ClientProvider to get an instance of WebClient to return in method test() and inject a mock of said provider to your object of type A during the test.


答: Okay...It worked when I put the script tag at the end instead of in the head section!</p>

Title: Collapsible not expanding


问:
how to configure webpack HMR with express
package.json scripts:

```<code> "scripts": {
    "build": "webpack --config config/webpack.prod.config.js",
    "dev": "webpack --config config/webpack.dev.config.js && nodemon ./dist/server.js",
    "start": "nodemon ./dist/server.js"
  }
</code>```

and this is main file:

server.js

```<code>import express from "express";
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from './config/webpack.dev.config';

const app = express();
const compiler = webpack(config);

app.get("/", (req, res) => {
    res.send("Hello");
});

app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath
}));

app.use(webpackHotMiddleware(compiler));

app.listen(4000, () => console.log("Listening to port 4000"))
</code>```

my webpack config divided in three files:

config/webpack.common.config.js

config/webpack.dev.config.js

config/webpack.prod.config.js

this is webpack common config:

webpack.common.config.js

```<code>module.exports = {
    entry: {
        server: './server.js'
    },
    output: {
        path: path.join(__dirname, '../dist'),
        publicPath: "/",
        filename: '[name].js'
    },
    target: 'node',
    externals: [new nodeExternals()],
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin()
    ]
}
</code>```

this is webpack dev config:

webpack.dev.config.js

```<code>module.exports = merge(common, {
    entry: {
        server: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', './server.js']
    },
    mode: 'development',
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    ]
})
</code>```

this is webpack dev config:

webpack.prod.config.js

```<code>module.exports = merge(common, {
    mode: 'production'
});
</code>```

finally this is the error:

what is the problem? how to config the hot reload in webpack and express?

答:
add "devServer" property to your webpack:

```<code>devServer: {
    contentBase: "dist",
    hot: true,
    stats: { colors: true }
  },
</code>```

then add this to the entry point of webpack. in your project it is server.js

```<code> require("webpack-hot-middleware/client?reload=true");
</code>```

Body:
package.json scripts:

 "scripts": {
    "build": "webpack --config config/webpack.prod.config.js",
    "dev": "webpack --config config/webpack.dev.config.js && nodemon ./dist/server.js",
    "start": "nodemon ./dist/server.js"
  }

and this is main file:

server.js

import express from "express";
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from './config/webpack.dev.config';

const app = express();
const compiler = webpack(config);

app.get("/", (req, res) => {
    res.send("Hello");
});

app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath
}));

app.use(webpackHotMiddleware(compiler));

app.listen(4000, () => console.log("Listening to port 4000"))

my webpack config divided in three files:

config/webpack.common.config.js

config/webpack.dev.config.js

config/webpack.prod.config.js

this is webpack common config:

webpack.common.config.js

module.exports = {
    entry: {
        server: './server.js'
    },
    output: {
        path: path.join(__dirname, '../dist'),
        publicPath: "/",
        filename: '[name].js'
    },
    target: 'node',
    externals: [new nodeExternals()],
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin()
    ]
}

this is webpack dev config:

webpack.dev.config.js

module.exports = merge(common, {
    entry: {
        server: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', './server.js']
    },
    mode: 'development',
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    ]
})

this is webpack dev config:

webpack.prod.config.js

module.exports = merge(common, {
    mode: 'production'
});

finally this is the error:

what is the problem? how to config the hot reload in webpack and express?

Body:
add "devServer" property to your webpack:

devServer: {
    contentBase: "dist",
    hot: true,
    stats: { colors: true }
  },

then add this to the entry point of webpack. in your project it is server.js

 require("webpack-hot-middleware/client?reload=true");


问:
JpaRepository: NoSuchBeanDefinitionException
I use spring-data-jpa. Without Spring Boot.

```<code>package ru.spb.repository;

public interface CrudUserRepository extends JpaRepository<User, Integer> {
}
</code>```

repository.

```<code> package ru.spb.repository;

@Repository
public class UserRepository {

  @Autowired
  private CrudUserRepository crudRepository;
}
</code>```

xml-config-files:

spring-app.xml

```<code><context:component-scan base-package="ru.spb.service"/>
<context:component-scan base-package="ru.spb.repository"/
</code>```

spring-db.xml:

```<code><context:component-scan base-package="ru.spb.repository" />
<jpa:repositories base-package="ru.spb.repository"/>
</code>```

in pom

```<code><spring-data-jpa.version>2.2.0.RELEASE</spring-data-jpa.version>

   <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>${spring-data-jpa.version}</version>
    </dependency>
</code>```

But I catch the:

```<code> NoSuchBeanDefinitionException: No qualifying bean of type 'ru.spb.repository.user.CrudUserRepository' available: expected at least 1 bean which qualifies as autowire candidate
</code>```

答:
The problem is solved.
I add "classpath:spring/spring-db.xml" in param-values of contextConfigLocation in my web.xml:</p>

```<code> <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:spring/spring-app.xml
        classpath:spring/spring-db.xml
    </param-value>
  </context-param>
</code>```

Body:
I use spring-data-jpa. Without Spring Boot.

package ru.spb.repository;

public interface CrudUserRepository extends JpaRepository<User, Integer> {
}

repository.

 package ru.spb.repository;

@Repository
public class UserRepository {

  @Autowired
  private CrudUserRepository crudRepository;
}

xml-config-files:

spring-app.xml

<context:component-scan base-package="ru.spb.service"/>
<context:component-scan base-package="ru.spb.repository"/

spring-db.xml:

<context:component-scan base-package="ru.spb.repository" />
<jpa:repositories base-package="ru.spb.repository"/>

in pom

<spring-data-jpa.version>2.2.0.RELEASE</spring-data-jpa.version>

   <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>${spring-data-jpa.version}</version>
    </dependency>

But I catch the:

 NoSuchBeanDefinitionException: No qualifying bean of type 'ru.spb.repository.user.CrudUserRepository' available: expected at least 1 bean which qualifies as autowire candidate

Body:
The problem is solved.
I add "classpath:spring/spring-db.xml" in param-values of contextConfigLocation in my web.xml:

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:spring/spring-app.xml
        classpath:spring/spring-db.xml
    </param-value>
  </context-param>


问:
Convert a list of data frames into a single data frame with list name
I am hoping to determine an efficient way to convert a list of data frames into a single data frame. Below is my reproducible MWE:

```<code>set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)
</code>```

This results in a data frame format (dfFormat) that looks like this:

```<code>'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...
</code>```

and a list of data frames listFormat that looks like this:

```<code>List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...
</code>```

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

1) If there is a common column (name and contents) in each sublist of listFormat (in these examples ID), then they are not repeated in the outputted dfFormat (in this example, it has one final ID column),

2) The rest of the column names in sublists of listFormat become columns in dfFormat and have names such that they retain their sublist name (i.e "A_B") followed by a dot and then their original column name (i.e. Age), so that it becomes (i.e. "A_B.Age") in the dfFormat.

I have tried various unlist() and sapply codes but have been unsuccessful thus far. What is an efficient way to accomplish this?

Body:
I am hoping to determine an efficient way to convert a list of data frames into a single data frame. Below is my reproducible MWE:

set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)

This results in a data frame format (dfFormat) that looks like this:

'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...

and a list of data frames listFormat that looks like this:

List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

1) If there is a common column (name and contents) in each sublist of listFormat (in these examples ID), then they are not repeated in the outputted dfFormat (in this example, it has one final ID column),

2) The rest of the column names in sublists of listFormat become columns in dfFormat and have names such that they retain their sublist name (i.e "A_B") followed by a dot and then their original column name (i.e. Age), so that it becomes (i.e. "A_B.Age") in the dfFormat.

I have tried various unlist() and sapply codes but have been unsuccessful thus far. What is an efficient way to accomplish this?

Body:
You're looking for dplyr::bind_rows:

library(dplyr)
bind_rows(listFormat, .id = "name")

Output:

  name  ID       Age     Points
1  A_B ID1 0.2655087  0.3981059
2  A_B ID2 0.3721239 -0.6120264
3  A_B ID3 0.5728534  0.3411197
4  A_B ID4 0.9082078 -1.1293631
5  A_B ID5 0.2016819  1.4330237
6  A_B ID6 0.8983897  1.9803999