问:
problem white screen with running the program of recyclerView
I am trying to make a program that program Displays data into recyclerView .
I have a problem with my program the screen appears White color nothing  display when I try to display data in recyclerView. If any one know what is problem into the code please help me. attached full code of my project. Also attached full Logcat.

Start with a page MainActivity

```<code>
public class MainActivity extends AppCompatActivity {
    private static final String HI = "https://uniqueandrocode.000webhostapp.com/hiren/androidtutorial/getimagelikedata.php";
    private List<MyListData>myListData;
    private RecyclerView rv;
    private JsonArrayRequest request;
    private RequestQueue requestQueue;
    private MyAdapter adapter;
    public static MyDatabase myDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv=(RecyclerView)findViewById(R.id.recycler_view);
        rv.setHasFixedSize(true);
        rv.setLayoutManager(new LinearLayoutManager(this));

        myListData=new ArrayList();
        myDatabase= Room.databaseBuilder(getApplicationContext(),MyDatabase.class,"mydb").allowMainThreadQueries().build();
       getData();
    }

    private void getData() {
        request=new JsonArrayRequest(HI, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                JSONObject jsonObject=null;
                for (int i=0; i<response.length(); i++){
                    try {
                        JSONObject ob=response.getJSONObject(i);
                        MyListData md=new MyListData(ob.getInt("id"),ob.getString("imageurl"),ob.getString("like"));
                        myListData.add(md);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                setupData(myListData);

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

            }
        });

        requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(request);

    }

    private void setupData(List<MyListData> myListData) {

        adapter=new MyAdapter( myListData,this);
        rv.setAdapter(adapter);

    }
}

</code>```

class of MyAdapter

```<code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private static final String PO ="https://uniqueandrocode.000webhostapp.com/hiren/androidtutorial/dislikedata.php?id=" ;
private static final String DE="https://uniqueandrocode.000webhostapp.com/hiren/androidtutorial/likedata.php?id=";
private List<MyListData>myListData;
private Context ct;
private JsonArrayRequest request,request1;
private RequestQueue requestQueue,rq;

public MyAdapter(List<MyListData> myListData, Context ct) {
        this.myListData = myListData;
        this.ct = ct;
        }

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_data,viewGroup,false);
        return new ViewHolder(view);
        }

@Override
public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {
final MyListData mk=myListData.get(i);
        Picasso.with(ct)
        .load(mk.getImageurl())
        .into(viewHolder.img);
        viewHolder.likecount.setText(mk.getLikecount());
        if (MainActivity.myDatabase.myDao().isLiked(mk.getId())==1)
        viewHolder.likebtn.setImageResource(R.drawable.ic_launcher_background);
        else
        viewHolder.likebtn.setImageResource(R.drawable.ic_launcher_background);

        viewHolder.likebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
        LikeDislike_List mt=new LikeDislike_List();
        //String uid=mk.getId();
        int id=mk.getId();
        String imp=mk.getImageurl();
        mt.setId(id);
        mt.setName(imp);

        if (MainActivity.myDatabase.myDao().isLiked(id)!=1){
        viewHolder.likebtn.setImageResource(R.drawable.ic_launcher_background);
        MainActivity.myDatabase.myDao().addData(mt);

        String mo=mk.getLikecount();
        viewHolder.likecount.setText(mo);

        delieteLike(id,viewHolder);

        }else {
        MainActivity.myDatabase.myDao().delete(mt);
        viewHolder.likebtn.setImageResource(R.drawable.ic_launcher_background);
        String mo=mk.getLikecount();

        addLike(id,viewHolder);

        }

        }
        });
        }

private void addLike(final int id, final ViewHolder viewHolder) {
        request=new JsonArrayRequest(PO + id, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
        JSONObject jsonObject=null;

        for (int i=0; i <response.length(); i++){
        try {
        JSONObject object=response.getJSONObject(i);
        String like=object.getString("like");
        viewHolder.likecount.setText(like);
        } catch (JSONException e) {
        e.printStackTrace();
        }
        }
        }
        }, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

        }
        });
        requestQueue= Volley.newRequestQueue(ct);
        requestQueue.add(request);

        }

private void delieteLike(final int id, final ViewHolder viewHolder) {
        request1 =new JsonArrayRequest(DE + id, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
        JSONObject jsonObject=null;
        for (int i=0; i<response.length(); i++){
        try {
        JSONObject object=response.getJSONObject(i);
        String like=object.getString("like");
        viewHolder.likecount.setText(like);
        } catch (JSONException e) {
        e.printStackTrace();
        }
        }
        }
        }, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

        }
        });
        rq=Volley.newRequestQueue(ct);
        rq.add(request1);

        }

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

public class ViewHolder extends RecyclerView.ViewHolder{
    private ImageView img,likebtn;
    private TextView likecount;
    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        img=(ImageView)itemView.findViewById(R.id.imageview);
        likebtn=(ImageView)itemView.findViewById(R.id.like_btn);
        likecount=(TextView)itemView.findViewById(R.id.like_count);
    }
}
}

</code>```

```<code>public class MyListData {
   private int id;
   private String imageurl;
   private String likecount;

   public MyListData(int id, String imageurl, String likecount) {
       this.id = id;
       this.imageurl = imageurl;
       this.likecount = likecount;
   }

   public int getId() {
       return id;
   }

   public String getImageurl() {
       return imageurl;
   }

   public String getLikecount() {
       return likecount;
   }
}

</code>```

```<code>import androidx.room.Database;
import androidx.room.RoomDatabase;

@Database(entities={LikeDislike_List.class},version = 1, exportSchema = false)
public abstract class MyDatabase extends RoomDatabase  {
    public abstract LikeDislikeDao myDao();
}

</code>```

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

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity(tableName="mydata")
public class LikeDislike_List {
    @PrimaryKey
    private int id;
    @ColumnInfo(name = "user_name")
    private String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

</code>```

```<code>@Dao
public interface LikeDislikeDao {
   @Insert
   public void addData(LikeDislike_List likeDislikeList);

   @Query("select * from mydata")
   public List<LikeDislike_List>getMyData();

   @Query("SELECT EXISTS (SELECT 1 FROM mydata WHERE id=:id)")
   public int isLiked(int id);

   @Delete
   public void delete(LikeDislike_List likeDislikeList);

}

</code>```

Logcat

```<code>02-17 19:04:01.856 7156-7161/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-17 19:04:02.276 7156-7156/? E/dalvikvm: Could not find class 'androidx.core.view.ViewCompat$2', referenced from method androidx.core.view.ViewCompat.addOnUnhandledKeyEventListener
02-17 19:04:02.280 7156-7156/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method androidx.core.view.ViewCompat.dispatchApplyWindowInsets
02-17 19:04:02.364 7156-7156/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method androidx.core.view.ViewCompat.onApplyWindowInsets
02-17 19:04:02.364 7156-7156/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method androidx.core.view.ViewCompat.removeOnUnhandledKeyEventListener
02-17 19:04:02.368 7156-7156/? E/dalvikvm: Could not find class 'androidx.core.view.ViewCompat$1', referenced from method androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener
02-17 19:04:02.636 7156-7156/? E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method androidx.appcompat.widget.AppCompatImageHelper.hasOverlappingRendering
02-17 19:04:02.824 7156-7156/? E/dalvikvm: Could not find class 'android.view.textclassifier.TextClassificationManager', referenced from method androidx.appcompat.widget.AppCompatTextClassifierHelper.getTextClassifier
02-17 19:04:03.044 7156-7156/com.example.myapplication E/RecyclerView: No adapter attached; skipping layout
02-17 19:04:03.060 7156-7156/com.example.myapplication E/RecyclerView: No adapter attached; skipping layout
</code>```

答:
sir you miss the third parameter of defining the that its a GET request</p>

```<code>  private void getData() {
    request=new JsonArrayRequest(HI, Request.Method.GET,
 new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            JSONObject jsonObject=null;
            for (int i=0; i<response.length(); i++){
                try {
                    JSONObject ob=response.getJSONObject(i);
                    MyListData md=new MyListData(ob.getInt("id"),ob.getString("imageurl"),ob.getString("like"));
                    myListData.add(md);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            setupData(myListData);

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

        }
    });

    requestQueue= Volley.newRequestQueue(this);
    requestQueue.add(request);

}
</code>```

Body:
I am trying to make a program that program Displays data into recyclerView .
I have a problem with my program the screen appears White color nothing  display when I try to display data in recyclerView. If any one know what is problem into the code please help me. attached full code of my project. Also attached full Logcat.

Start with a page MainActivity

public class MainActivity extends AppCompatActivity {
    private static final String HI = "https://uniqueandrocode.000webhostapp.com/hiren/androidtutorial/getimagelikedata.php";
    private List<MyListData>myListData;
    private RecyclerView rv;
    private JsonArrayRequest request;
    private RequestQueue requestQueue;
    private MyAdapter adapter;
    public static MyDatabase myDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv=(RecyclerView)findViewById(R.id.recycler_view);
        rv.setHasFixedSize(true);
        rv.setLayoutManager(new LinearLayoutManager(this));

        myListData=new ArrayList();
        myDatabase= Room.databaseBuilder(getApplicationContext(),MyDatabase.class,"mydb").allowMainThreadQueries().build();
       getData();
    }

    private void getData() {
        request=new JsonArrayRequest(HI, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                JSONObject jsonObject=null;
                for (int i=0; i<response.length(); i++){
                    try {
                        JSONObject ob=response.getJSONObject(i);
                        MyListData md=new MyListData(ob.getInt("id"),ob.getString("imageurl"),ob.getString("like"));
                        myListData.add(md);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                setupData(myListData);

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

            }
        });

        requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(request);

    }

    private void setupData(List<MyListData> myListData) {

        adapter=new MyAdapter( myListData,this);
        rv.setAdapter(adapter);

    }
}

class of MyAdapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private static final String PO ="https://uniqueandrocode.000webhostapp.com/hiren/androidtutorial/dislikedata.php?id=" ;
private static final String DE="https://uniqueandrocode.000webhostapp.com/hiren/androidtutorial/likedata.php?id=";
private List<MyListData>myListData;
private Context ct;
private JsonArrayRequest request,request1;
private RequestQueue requestQueue,rq;

public MyAdapter(List<MyListData> myListData, Context ct) {
        this.myListData = myListData;
        this.ct = ct;
        }

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_data,viewGroup,false);
        return new ViewHolder(view);
        }

@Override
public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {
final MyListData mk=myListData.get(i);
        Picasso.with(ct)
        .load(mk.getImageurl())
        .into(viewHolder.img);
        viewHolder.likecount.setText(mk.getLikecount());
        if (MainActivity.myDatabase.myDao().isLiked(mk.getId())==1)
        viewHolder.likebtn.setImageResource(R.drawable.ic_launcher_background);
        else
        viewHolder.likebtn.setImageResource(R.drawable.ic_launcher_background);

        viewHolder.likebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
        LikeDislike_List mt=new LikeDislike_List();
        //String uid=mk.getId();
        int id=mk.getId();
        String imp=mk.getImageurl();
        mt.setId(id);
        mt.setName(imp);

        if (MainActivity.myDatabase.myDao().isLiked(id)!=1){
        viewHolder.likebtn.setImageResource(R.drawable.ic_launcher_background);
        MainActivity.myDatabase.myDao().addData(mt);

        String mo=mk.getLikecount();
        viewHolder.likecount.setText(mo);

        delieteLike(id,viewHolder);

        }else {
        MainActivity.myDatabase.myDao().delete(mt);
        viewHolder.likebtn.setImageResource(R.drawable.ic_launcher_background);
        String mo=mk.getLikecount();

        addLike(id,viewHolder);

        }

        }
        });
        }

private void addLike(final int id, final ViewHolder viewHolder) {
        request=new JsonArrayRequest(PO + id, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
        JSONObject jsonObject=null;

        for (int i=0; i <response.length(); i++){
        try {
        JSONObject object=response.getJSONObject(i);
        String like=object.getString("like");
        viewHolder.likecount.setText(like);
        } catch (JSONException e) {
        e.printStackTrace();
        }
        }
        }
        }, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

        }
        });
        requestQueue= Volley.newRequestQueue(ct);
        requestQueue.add(request);

        }

private void delieteLike(final int id, final ViewHolder viewHolder) {
        request1 =new JsonArrayRequest(DE + id, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
        JSONObject jsonObject=null;
        for (int i=0; i<response.length(); i++){
        try {
        JSONObject object=response.getJSONObject(i);
        String like=object.getString("like");
        viewHolder.likecount.setText(like);
        } catch (JSONException e) {
        e.printStackTrace();
        }
        }
        }
        }, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

        }
        });
        rq=Volley.newRequestQueue(ct);
        rq.add(request1);

        }

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

public class ViewHolder extends RecyclerView.ViewHolder{
    private ImageView img,likebtn;
    private TextView likecount;
    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        img=(ImageView)itemView.findViewById(R.id.imageview);
        likebtn=(ImageView)itemView.findViewById(R.id.like_btn);
        likecount=(TextView)itemView.findViewById(R.id.like_count);
    }
}
}

public class MyListData {
   private int id;
   private String imageurl;
   private String likecount;

   public MyListData(int id, String imageurl, String likecount) {
       this.id = id;
       this.imageurl = imageurl;
       this.likecount = likecount;
   }

   public int getId() {
       return id;
   }

   public String getImageurl() {
       return imageurl;
   }

   public String getLikecount() {
       return likecount;
   }
}

import androidx.room.Database;
import androidx.room.RoomDatabase;

@Database(entities={LikeDislike_List.class},version = 1, exportSchema = false)
public abstract class MyDatabase extends RoomDatabase  {
    public abstract LikeDislikeDao myDao();
}

package com.example.myapplication;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity(tableName="mydata")
public class LikeDislike_List {
    @PrimaryKey
    private int id;
    @ColumnInfo(name = "user_name")
    private String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@Dao
public interface LikeDislikeDao {
   @Insert
   public void addData(LikeDislike_List likeDislikeList);

   @Query("select * from mydata")
   public List<LikeDislike_List>getMyData();

   @Query("SELECT EXISTS (SELECT 1 FROM mydata WHERE id=:id)")
   public int isLiked(int id);

   @Delete
   public void delete(LikeDislike_List likeDislikeList);

}

Logcat

02-17 19:04:01.856 7156-7161/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-17 19:04:02.276 7156-7156/? E/dalvikvm: Could not find class 'androidx.core.view.ViewCompat$2', referenced from method androidx.core.view.ViewCompat.addOnUnhandledKeyEventListener
02-17 19:04:02.280 7156-7156/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method androidx.core.view.ViewCompat.dispatchApplyWindowInsets
02-17 19:04:02.364 7156-7156/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method androidx.core.view.ViewCompat.onApplyWindowInsets
02-17 19:04:02.364 7156-7156/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method androidx.core.view.ViewCompat.removeOnUnhandledKeyEventListener
02-17 19:04:02.368 7156-7156/? E/dalvikvm: Could not find class 'androidx.core.view.ViewCompat$1', referenced from method androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener
02-17 19:04:02.636 7156-7156/? E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method androidx.appcompat.widget.AppCompatImageHelper.hasOverlappingRendering
02-17 19:04:02.824 7156-7156/? E/dalvikvm: Could not find class 'android.view.textclassifier.TextClassificationManager', referenced from method androidx.appcompat.widget.AppCompatTextClassifierHelper.getTextClassifier
02-17 19:04:03.044 7156-7156/com.example.myapplication E/RecyclerView: No adapter attached; skipping layout
02-17 19:04:03.060 7156-7156/com.example.myapplication E/RecyclerView: No adapter attached; skipping layout

Body:
sir you miss the third parameter of defining the that its a GET request

  private void getData() {
    request=new JsonArrayRequest(HI, Request.Method.GET,
 new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            JSONObject jsonObject=null;
            for (int i=0; i<response.length(); i++){
                try {
                    JSONObject ob=response.getJSONObject(i);
                    MyListData md=new MyListData(ob.getInt("id"),ob.getString("imageurl"),ob.getString("like"));
                    myListData.add(md);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            setupData(myListData);

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

        }
    });

    requestQueue= Volley.newRequestQueue(this);
    requestQueue.add(request);

}


来源: stackexchange

问:
HTTPS redirect in .htaccess is causing infinite redirect loop
I'm trying to redirect all HTTP urls to HTTPS using the following in .htaccess:

```<code>RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

However it just causes an infinite redirect loop.  There is a valid SSL certificate and the website is written in asp.net in case it matters.  Google chrome automatically redirects to https, but firefox and edge do not so I need to add this rule.  The only way I can get the site to load in https is if I explicitly type https:// in the address.  What's the possible cause here?

答:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourwebsite.com/$1 [R,L]

try that

or use cloudflare to cache and perfomace your project
https://support.cloudflare.com/hc/en-us/articles/115000219871-Troubleshooting-redirect-loop-errors
https://community.cloudflare.com/t/cloudflare-flexible-ssl-is-it-worth-it/28043
https://developers.cloudflare.com/ssl/origin/ssl-modes/

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to redirect all HTTP urls to HTTPS using the following in .htaccess:

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

However it just causes an infinite redirect loop.  There is a valid SSL certificate and the website is written in asp.net in case it matters.  Google chrome automatically redirects to https, but firefox and edge do not so I need to add this rule.  The only way I can get the site to load in https is if I explicitly type https:// in the address.  What's the possible cause here?


问:
Using a subquery in 'FROM' in gorm
I would like to know how I can use a subquery in FROM clause using gorm. It would look like the following:

```<code>SELECT * FROM
(
  SELECT foo.*
  FROM foo
  WHERE bar = "baz"
) AS t1
WHERE t1.id = 1;
</code>```

I have built the subquery using golang:

```<code>db.Model(Foo{}).Where("bar = ?", "baz")
</code>```

But how can I use this as a subquery in FROM?

If there is a method that turns a gorm query into a SQL string, then I can simply plug that string into a raw SQL. But there does not seem to be such method. Any suggestions?

答:
Solved this issue by creating a package for more flexibility: https://github.com/loeffel-io/sql</p>

```<code>subquery := sql.Create().
    Select(true, "purchases.*").
    Select(true, "...").
    From(true, "purchases").
    Join(true, "transactions ON transactions.purchase_id=purchases.id")

query := sql.Create().Select(true, "*").
    From(true, "(?) purchases", gorm.Expr(subquery.GetSQL(), subquery.GetValues()...)).
    Join(true, "transactions ON transactions.id=purchases.last_transaction_id")

db.
    Raw(query.GetSQL(), query.GetValues()...).
    Offset(...).
    Limit(...).
    Order(...).
    Unscoped().
    Find(&purchases).
    Error
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using a subquery in 'FROM' in gorm

Body:
I would like to know how I can use a subquery in FROM clause using gorm. It would look like the following:

SELECT * FROM
(
  SELECT foo.*
  FROM foo
  WHERE bar = "baz"
) AS t1
WHERE t1.id = 1;

I have built the subquery using golang:

db.Model(Foo{}).Where("bar = ?", "baz")

But how can I use this as a subquery in FROM?

If there is a method that turns a gorm query into a SQL string, then I can simply plug that string into a raw SQL. But there does not seem to be such method. Any suggestions?

Body:
Solved this issue by creating a package for more flexibility: https://github.com/loeffel-io/sql

subquery := sql.Create().
    Select(true, "purchases.*").
    Select(true, "...").
    From(true, "purchases").
    Join(true, "transactions ON transactions.purchase_id=purchases.id")

query := sql.Create().Select(true, "*").
    From(true, "(?) purchases", gorm.Expr(subquery.GetSQL(), subquery.GetValues()...)).
    Join(true, "transactions ON transactions.id=purchases.last_transaction_id")

db.
    Raw(query.GetSQL(), query.GetValues()...).
    Offset(...).
    Limit(...).
    Order(...).
    Unscoped().
    Find(&purchases).
    Error


问:
MySQL : delete all records based on an id and other colums content
I got the following table

```<code>+----+---------+---------+
| id |  val1   |  val2   |
+----+---------+---------+
|  1 |  aaaa   |  bbbb   |
|  2 |  cccc   |  dddd   |
|  3 |  aaaa   |  eeee   |
|  4 |  ffff   |  bbbb   |
|  5 |  aaaa   |  bbbb   |
+----+---------+---------+
</code>```

I have identified I need to delete the record with id = 1

But I want also delete all the records having same val1 and val2 as id 1.

In this case, id 5 should also me removed.

I have tried that with no luck

```<code>SELECT id FROM table t1
INNER JOIN table t2
ON t1.val1 = t2.val1
AND t1.val2 = t2.val2
AND t1.id = 1
</code>```

答:
You can do it with a self join and the condition id = 1 in the WHERE clause:

```<code>delete t1
from tablename t1 inner join tablename t2
on t1.val1 = t2.val1 and t1.val2 = t2.val2
where t2.id = 1;
</code>```

See the demo.

Results:

```<code>| id  | val1 | val2 |
| --- | ---- | ---- |
| 2   | cccc | dddd |
| 3   | aaaa | eeee |
| 4   | ffff | bbbb |
</code>```

Body:
I got the following table

+----+---------+---------+
| id |  val1   |  val2   |
+----+---------+---------+
|  1 |  aaaa   |  bbbb   |
|  2 |  cccc   |  dddd   |
|  3 |  aaaa   |  eeee   |
|  4 |  ffff   |  bbbb   |
|  5 |  aaaa   |  bbbb   |
+----+---------+---------+

I have identified I need to delete the record with id = 1

But I want also delete all the records having same val1 and val2 as id 1.

In this case, id 5 should also me removed.

I have tried that with no luck

SELECT id FROM table t1
INNER JOIN table t2
ON t1.val1 = t2.val1
AND t1.val2 = t2.val2
AND t1.id = 1

Body:
You can do it with a self join and the condition id = 1 in the WHERE clause:

delete t1
from tablename t1 inner join tablename t2
on t1.val1 = t2.val1 and t1.val2 = t2.val2
where t2.id = 1;

See the demo.

Results:

| id  | val1 | val2 |
| --- | ---- | ---- |
| 2   | cccc | dddd |
| 3   | aaaa | eeee |
| 4   | ffff | bbbb |


问:
delete file other than particular extension file format
i have a lot of different type of files in one folder. i need to delete the files but except the pdf file.
I tried to display the pdf file only. but i need to delete the other than pdf files</p>

```<code>ls -1 | xargs file | grep 'PDF document,' | sed 's/:.*//'
</code>```

答:
$ ls
aa.txt  a.pdf  bb.cpp  b.pdf

$ ls | grep -v .pdf | xargs rm -rf

$ ls
a.pdf  b.pdf

:) !

Body:
i have a lot of different type of files in one folder. i need to delete the files but except the pdf file.
I tried to display the pdf file only. but i need to delete the other than pdf files

ls -1 | xargs file | grep 'PDF document,' | sed 's/:.*//'


问:
How do I replace_na over multiple lists
I need to replace NA with FALSE across multiple lists. I can do it in the most basic way. Here is what I have so far -

```<code>mydataframe$POBA<-replace_na(mydataframe$POBA,FALSE)
mydataframe$POBA2<-replace_na(mydataframe$POBA2,FALSE)
mydataframe$POBA3<-replace_na(mydataframe$POBA3,FALSE)
</code>```

Is there a way to combine all three to reduce the code? Using a For Loop or referring to a range of columns?

Just started teaching myself R and I've tried multiple variations, but none that seem to work.

答:
We  can use mutate_at

```<code>library(dplyr)
mydataframe <- mydataframe %>%
                mutate_at(vars(starts_with("POBA)), replace_na, FALSE)
</code>```

In the devel version of dplyr,  across can be used in mutate

```<code>mydataframe %>%
     mutate(across(starts_with("POBA"), replace_na, FALSE))
</code>```

Title: How do I replace_na over multiple lists

Body:
I need to replace NA with FALSE across multiple lists. I can do it in the most basic way. Here is what I have so far -

mydataframe$POBA<-replace_na(mydataframe$POBA,FALSE)
mydataframe$POBA2<-replace_na(mydataframe$POBA2,FALSE)
mydataframe$POBA3<-replace_na(mydataframe$POBA3,FALSE)

Is there a way to combine all three to reduce the code? Using a For Loop or referring to a range of columns?

Just started teaching myself R and I've tried multiple variations, but none that seem to work.

Body:
We  can use mutate_at

library(dplyr)
mydataframe <- mydataframe %>%
                mutate_at(vars(starts_with("POBA)), replace_na, FALSE)

In the devel version of dplyr,  across can be used in mutate

mydataframe %>%
     mutate(across(starts_with("POBA"), replace_na, FALSE))


答:
You could use the apply family for that

```<code>lapply(mydataframe, replace_na, FALSE)
</code>```

Note: This would alter all columns and will return a list object. This can easily be converted to a data.frame again with as.data.frame() if you need that.

```<code>mydataframe <- data.frame(POBA = c(TRUE,TRUE,NA),
                          POBA2 = c(TRUE, NA, TRUE),
                          POBA3 = c(NA, TRUE, TRUE))
lapply(mydataframe, tidyr::replace_na, FALSE)
# $POBA
# [1]  TRUE  TRUE FALSE
#
# $POBA2
# [1]  TRUE FALSE  TRUE
#
# $POBA3
# [1] FALSE  TRUE  TRUE
</code>```

Title: How do I replace_na over multiple lists

Body:
You could use the apply family for that

lapply(mydataframe, replace_na, FALSE)

Note: This would alter all columns and will return a list object. This can easily be converted to a data.frame again with as.data.frame() if you need that.

mydataframe <- data.frame(POBA = c(TRUE,TRUE,NA),
                          POBA2 = c(TRUE, NA, TRUE),
                          POBA3 = c(NA, TRUE, TRUE))
lapply(mydataframe, tidyr::replace_na, FALSE)
# $POBA
# [1]  TRUE  TRUE FALSE
#
# $POBA2
# [1]  TRUE FALSE  TRUE
#
# $POBA3
# [1] FALSE  TRUE  TRUE


问:
How to send a message with login in Laravel?
I have this function for log but I have an error in the compact

```<code>public function redirectPath()
{
    if (Auth::user()){

        $msg_modal = 1;
        return '/', compact('msg_modal');
}
</code>```

to run this script which show me a modal

```<code>@if(!empty($msg_modal) && $msg_modal == 1)

<script>
$(function() {
$('#mostrarmodal').modal('show');
});
</script>

@endif
</code>```

This is the modal that I would like to see when I log

```<code><div class="modal fade" id="mostrarmodal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
       <div class="modal-header">
          <h3><center>System</center></h3>
       </div>
       <div class="modal-body">
          <h4><center>Message</center></h4>
          <center>You are connected!!!</center>
      </div>
       <div class="modal-footer">
      <a href="#" data-dismiss="modal" class="btn btn-info">Continuar</a>
       </div>
  </div>
</code>```

答:
This is the best way to return error message from your controller directly:

```<code>return redirect()->with('message', 'Success');
</code>```

And then you should do something like this:

```<code>@if(Session::has('message'))
<!-- your modal goes here !!! -->
@endif
</code>```

Instead of outputting the modal() method, you can directly assign the show class to your modal, depending on the existing or nonexistent message from the controller.

Body:
I have this function for log but I have an error in the compact

public function redirectPath()
{
    if (Auth::user()){

        $msg_modal = 1;
        return '/', compact('msg_modal');
}

to run this script which show me a modal

@if(!empty($msg_modal) && $msg_modal == 1)

@endif

This is the modal that I would like to see when I log

System

Message

          You are connected!!!

      Continuar

Body:
This is the best way to return error message from your controller directly:

return redirect()->with('message', 'Success');

And then you should do something like this:

@if(Session::has('message'))
<!-- your modal goes here !!! -->
@endif

Instead of outputting the modal() method, you can directly assign the show class to your modal, depending on the existing or nonexistent message from the controller.


问:
How do I make a gulp function run in series? (gulp-download)
I've been trying to set up functions to download and then install frameworks into my development workflow with gulp-download. Every time I run gulp-download in series, it always runs last, so the function tries to move the files, then they download.

I tried to use merge and run this in a single function, then split it and used a task in series to run it. Neither way is successful.

```<code>// DOWNLOAD BOOTSTRAP
function downloadBootstrap(cb) {
  download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
    .pipe(unzip())
    .pipe(gulp.dest('downloads/bootstrap'));
  cb();
}

// INSTALL BOOTSTRAT
function installBootstrap(cb) {

  var css = gulp.src('downloads/bootstrap/css/*.{min.css,min.css.map}')
    .pipe(dest('_developer/2-css/0-frameworks/bootstrap'))

  var js = gulp.src('downloads/bootstrap/js/*.{min.js,min.js.map}')
  .pipe(dest('_developer/3-js/0-frameworks/bootstrap'))

  var clear = gulp.src('downloads/bootstrap', {read: false, allowEmpty: true})
  .pipe(clean())

  return merge(css, js, clear); // Combined src
  cb();
}

gulp.task('bootstrap', gulp.series('downloadBootstrap', 'installBootstrap'));
</code>```

答:
I worked it out, I just had to add return to the download lol. Now I have the download finishing before it moves onto the install, but now only the css is migrated, the js remains and the clean isn't running. I had these working before.</p>

```<code>gulp.task("bootstrap", gulp.series(downloadBootstrap, installBootstrap));

function downloadBootstrap() {

  return download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
    .pipe(unzip())
    .pipe(gulp.dest('downloads/bootstrap'));

}

function installBootstrap() {

  return gulp.src('downloads/bootstrap/css/*.{min.css,min.css.map}') // Gather [developer] css files
    .pipe(gulp.dest('_developer/2-css/0-frameworks/bootstrap')) // Deliver css files to [build]

  return gulp.src('downloads/bootstrap/js/*.{min.js,min.js.map}') // Gather [developer] css files
    .pipe(gulp.dest('_developer/3-js/0-frameworks/bootstrap')) // Deliver css files to [build]

  return gulp.src('downloads/bootstrap', { allowEmpty: true })
    .pipe(clean());

}
</code>```

Body:
I've been trying to set up functions to download and then install frameworks into my development workflow with gulp-download. Every time I run gulp-download in series, it always runs last, so the function tries to move the files, then they download.

I tried to use merge and run this in a single function, then split it and used a task in series to run it. Neither way is successful.

// DOWNLOAD BOOTSTRAP
function downloadBootstrap(cb) {
  download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
    .pipe(unzip())
    .pipe(gulp.dest('downloads/bootstrap'));
  cb();
}

// INSTALL BOOTSTRAT
function installBootstrap(cb) {

  var css = gulp.src('downloads/bootstrap/css/*.{min.css,min.css.map}')
    .pipe(dest('_developer/2-css/0-frameworks/bootstrap'))

  var js = gulp.src('downloads/bootstrap/js/*.{min.js,min.js.map}')
  .pipe(dest('_developer/3-js/0-frameworks/bootstrap'))

  var clear = gulp.src('downloads/bootstrap', {read: false, allowEmpty: true})
  .pipe(clean())

  return merge(css, js, clear); // Combined src
  cb();
}

gulp.task('bootstrap', gulp.series('downloadBootstrap', 'installBootstrap'));

Body:
I worked it out, I just had to add return to the download lol. Now I have the download finishing before it moves onto the install, but now only the css is migrated, the js remains and the clean isn't running. I had these working before.

gulp.task("bootstrap", gulp.series(downloadBootstrap, installBootstrap));

function downloadBootstrap() {

  return download('https://github.com/twbs/bootstrap/releases/download/v4.0.0/bootstrap-4.0.0-dist.zip')
    .pipe(unzip())
    .pipe(gulp.dest('downloads/bootstrap'));

}

function installBootstrap() {

  return gulp.src('downloads/bootstrap/css/*.{min.css,min.css.map}') // Gather [developer] css files
    .pipe(gulp.dest('_developer/2-css/0-frameworks/bootstrap')) // Deliver css files to [build]

  return gulp.src('downloads/bootstrap/js/*.{min.js,min.js.map}') // Gather [developer] css files
    .pipe(gulp.dest('_developer/3-js/0-frameworks/bootstrap')) // Deliver css files to [build]

  return gulp.src('downloads/bootstrap', { allowEmpty: true })
    .pipe(clean());

}


问:
Using Tim2 inside interrupt handler for STM32F1
I am blinking LED using TIM2 General timer.

Code in main.c

```<code>HAL_TIM_Base_Start_IT(&htim2);

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
    if(htim->Instance==TIM2){
        HAL_GPIO_TogglePin(GPIOB, LED_Pin);
    }
}
</code>```

When the button is clicked EXTI interrupt should be called to blink the led faster 20 times. However, LED stays on and stops blinking at all.

```<code>void EXTI0_IRQHandler(void)
{
  HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0);
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin){
    if(GPIO_Pin == BT_Pin){
        for(volatile int i=20; i>0; i--){
            HAL_GPIO_TogglePin(GPIOB, LED_Pin);
            HAL_Delay(100);
        }
    }
}
</code>```

Could you please advice how can i adjust interrupt ISR for EXTI so it will use TIM2 as well with faster blinking.

答:
HAL_GPIO_EXTI_Callback() runs in the interrupt context - it is not appropriate to flash the indicator there much less include a delay.  No other code while run while in the interrupt, and HAL_Delay() is probably not interrupt safe in any case.

Instead, in the button handler, set a down-counter to be decremented in the timer handler, and in the timer handler set the reload depending on the down-counter being zero or not.  Something like this:

[I have not included the HAL calls to do the TODO's above, because I'd have to look them up, but that is the outline.]

```<code>volatile unsigned fast_flash_count = 0 ;

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if(htim->Instance==TIM2)
    {
        HAL_GPIO_TogglePin(GPIOB, LED_Pin);

        if( fast_flash_count > 0 )
        {
            fast_flash_count-- ;

            // Set TIM2 reload to fast-flash period
            TODO
        }
        else
        {
            // Set TIM2 reload to slow-flash period
            TODO
        }
    }
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    if(GPIO_Pin == BT_Pin)
    {
        fast_flash_count = 20 ;

        // Set TIM2 counter to current reload value
        // to force immediate interrupt
        TODO
    }
}
</code>```

Body:
I am blinking LED using TIM2 General timer.

Code in main.c

HAL_TIM_Base_Start_IT(&htim2);

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
    if(htim->Instance==TIM2){
        HAL_GPIO_TogglePin(GPIOB, LED_Pin);
    }
}

When the button is clicked EXTI interrupt should be called to blink the led faster 20 times. However, LED stays on and stops blinking at all.

void EXTI0_IRQHandler(void)
{
  HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0);
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin){
    if(GPIO_Pin == BT_Pin){
        for(volatile int i=20; i>0; i--){
            HAL_GPIO_TogglePin(GPIOB, LED_Pin);
            HAL_Delay(100);
        }
    }
}

Could you please advice how can i adjust interrupt ISR for EXTI so it will use TIM2 as well with faster blinking.

Body:
HAL_GPIO_EXTI_Callback() runs in the interrupt context - it is not appropriate to flash the indicator there much less include a delay.  No other code while run while in the interrupt, and HAL_Delay() is probably not interrupt safe in any case.

Instead, in the button handler, set a down-counter to be decremented in the timer handler, and in the timer handler set the reload depending on the down-counter being zero or not.  Something like this:

[I have not included the HAL calls to do the TODO's above, because I'd have to look them up, but that is the outline.]

volatile unsigned fast_flash_count = 0 ;

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if(htim->Instance==TIM2)
    {
        HAL_GPIO_TogglePin(GPIOB, LED_Pin);

        if( fast_flash_count > 0 )
        {
            fast_flash_count-- ;

            // Set TIM2 reload to fast-flash period
            TODO
        }
        else
        {
            // Set TIM2 reload to slow-flash period
            TODO
        }
    }
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    if(GPIO_Pin == BT_Pin)
    {
        fast_flash_count = 20 ;

        // Set TIM2 counter to current reload value
        // to force immediate interrupt
        TODO
    }
}


问:
Entity Framework and ASP.NET Core UOW Repository pattern
I have an ASP.NET Core application, which is structured in three layers i.e.:

Data access layer (Entity Framework)

Business logic layer (Unit of work, repository pattern)

ASP.NET MVC web application

Until now, I have been used to developing applications in .NET Framework, however, moving to Core I notice that there are significant differences.

To start off, I used a database first approach to initialize my entity framework. Here I used the scaffolding method, and it worked just fine.

However, I noticed that app.config is no longer present in any of my libraries and that my connectionstring has been moved to a method in my source code, i.e.:

```<code>protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//connection stuff here
}
</code>```

Compared to using EF in .net framework, I would normally utilize the connectionstring, which resides in my app.config i.e.:

```<code>public EFClass(string connString)
        : base(connString)
    {
</code>```

This can no longer be done, and i'm forced to utilize the appsettings.json in my MVC web application, which sort of mess up the idea of loosely coupling my application.

Optimally, how would I get to my connectionstring in my dataaccess layer, when I don't have my app.config anymore?

Additionally, I've read several places that the UOW repository pattern is sort of redundant, as DbContext in .NET Core applications can be used for DI as well? Should I get rid of my UOW and just inject my DbContext directly into my repositories?

My question may be wrong, in the sense that I probably miss some major fundamentals here, but you are welcome to point me in a better direction.

答:
EF already implements the UoW pattern - DbSets are your repositories and the DbContext is your unit of work.  Filters and logic you wish to enforce on insert/update/delete of specific entities can all be configured in your DbContext implementation (one way or another).  If I don't think I can trust developers with using the DbContext directly, I prefer to create an API.

In any case, you should be using dependency injection to provide your implementation of DbContext to whatever class(es) should have access to it.  When running your ASP.NET Core application, you register your implementation with the necessary configuration options (whatever those may be - either from your config files or elsewhere).  When unit/integration testing components that utilize your DbContext, you can construct the instance manually and pass into the constructor.

Example (from this):

```<code>public void ConfigureServices(IServiceCollection services)
{
    ...

    // this method allows you to configure you DbContext options
    services.AddDbContext<YourDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    ...
}
</code>```

Body:
I have an ASP.NET Core application, which is structured in three layers i.e.:

Data access layer (Entity Framework)

Business logic layer (Unit of work, repository pattern)

ASP.NET MVC web application

Until now, I have been used to developing applications in .NET Framework, however, moving to Core I notice that there are significant differences.

To start off, I used a database first approach to initialize my entity framework. Here I used the scaffolding method, and it worked just fine.

However, I noticed that app.config is no longer present in any of my libraries and that my connectionstring has been moved to a method in my source code, i.e.:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//connection stuff here
}

Compared to using EF in .net framework, I would normally utilize the connectionstring, which resides in my app.config i.e.:

public EFClass(string connString)
        : base(connString)
    {

This can no longer be done, and i'm forced to utilize the appsettings.json in my MVC web application, which sort of mess up the idea of loosely coupling my application.

Optimally, how would I get to my connectionstring in my dataaccess layer, when I don't have my app.config anymore?

Additionally, I've read several places that the UOW repository pattern is sort of redundant, as DbContext in .NET Core applications can be used for DI as well? Should I get rid of my UOW and just inject my DbContext directly into my repositories?

My question may be wrong, in the sense that I probably miss some major fundamentals here, but you are welcome to point me in a better direction.

Body:
EF already implements the UoW pattern - DbSets are your repositories and the DbContext is your unit of work.  Filters and logic you wish to enforce on insert/update/delete of specific entities can all be configured in your DbContext implementation (one way or another).  If I don't think I can trust developers with using the DbContext directly, I prefer to create an API.

In any case, you should be using dependency injection to provide your implementation of DbContext to whatever class(es) should have access to it.  When running your ASP.NET Core application, you register your implementation with the necessary configuration options (whatever those may be - either from your config files or elsewhere).  When unit/integration testing components that utilize your DbContext, you can construct the instance manually and pass into the constructor.

Example (from this):

public void ConfigureServices(IServiceCollection services)
{
    ...

    // this method allows you to configure you DbContext options
    services.AddDbContext<YourDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    ...
}


问:
my npm-lint is throwing error "missing script: lint"
I am trying to run npm run locally, and ran npm init, that created package.json. Here is my package.json

```<code>    "name": "ironic-ui",
    "version": "1.0.0",
    "description": "======================== Team and repository tags    ========================",
    "main": "test-shim.js",
    "directories": {
    "doc": "doc"
   },
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
   },
    "repository": {
    "type": "git",
    "url": "https://git.openstack.org/openstack/ironic-ui"
  },
    "author": "",
    "license": "ISC"
 }
</code>```

Is there missing something? Or do i need to install something more? I am getting an error "Missing script: lint"
Thanks

答: If you want to remove eslint from your Firebase Functions project, you can go to firebase.json and delete the line npm --prefix \"$RESOURCE_DIR\" run lint (inside predeploy). After this, you can delete the .eslintrc.json file inside your functions project

Body:
I am trying to run npm run locally, and ran npm init, that created package.json. Here is my package.json

    "name": "ironic-ui",
    "version": "1.0.0",
    "description": "======================== Team and repository tags    ========================",
    "main": "test-shim.js",
    "directories": {
    "doc": "doc"
   },
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
   },
    "repository": {
    "type": "git",
    "url": "https://git.openstack.org/openstack/ironic-ui"
  },
    "author": "",
    "license": "ISC"
 }

Is there missing something? Or do i need to install something more? I am getting an error "Missing script: lint"
Thanks


问:
When I try to print(query) , I get the result as <pymongo.cursor.Cursor object at 0x00000273CCF21D90>
When I try to print(query), I get the result as    <pymongo.cursor.Cursor object at 0x00000273CCF21D90>  whereas I want the entire document that contains primaryTitle that has "Friday Night". Please help.

```<code>rgx = re.compile('.*Friday Night.*', re.IGNORECASE)  # compile the regex

query= db.IllegalCollect.find({"$primaryTitle": rgx})
</code>```

答:
find() returns a cursor which you have to iterate to get the results; you can't just print the result as you have found. Your options are to use find_one() (will only return one record though); to use list(query) to convert to a list, or to iterate the cursor with a for loop.

The example below shows each method.

btw your $primaryTitle field in the find query won't work; you likely need primaryTitle without the $

```<code>import pymongo
import re
db = pymongo.MongoClient()['mydatabase']

db.IllegalCollect.insert_one({'primaryTitle': 'Last Friday Night, Yeah we maxed our credit cards'})
db.IllegalCollect.insert_one({'primaryTitle': 'And got kicked out of the bar, So we hit the boulevard'})

rgx = re.compile('.*Friday Night.*', re.IGNORECASE)  # compile the regex

query = db.IllegalCollect.find_one({'primaryTitle': rgx})
print (query)

query = db.IllegalCollect.find({'primaryTitle': rgx})
print (list(query))

query = db.IllegalCollect.find({'primaryTitle': rgx})
for item in query:
    print (item)
</code>```

Body:
When I try to print(query), I get the result as    <pymongo.cursor.Cursor object at 0x00000273CCF21D90>  whereas I want the entire document that contains primaryTitle that has "Friday Night". Please help.

rgx = re.compile('.*Friday Night.*', re.IGNORECASE)  # compile the regex

query= db.IllegalCollect.find({"$primaryTitle": rgx})

Body:
find() returns a cursor which you have to iterate to get the results; you can't just print the result as you have found. Your options are to use find_one() (will only return one record though); to use list(query) to convert to a list, or to iterate the cursor with a for loop.

The example below shows each method.

btw your $primaryTitle field in the find query won't work; you likely need primaryTitle without the $

import pymongo
import re
db = pymongo.MongoClient()['mydatabase']

db.IllegalCollect.insert_one({'primaryTitle': 'Last Friday Night, Yeah we maxed our credit cards'})
db.IllegalCollect.insert_one({'primaryTitle': 'And got kicked out of the bar, So we hit the boulevard'})

rgx = re.compile('.*Friday Night.*', re.IGNORECASE)  # compile the regex

query = db.IllegalCollect.find_one({'primaryTitle': rgx})
print (query)

query = db.IllegalCollect.find({'primaryTitle': rgx})
print (list(query))

query = db.IllegalCollect.find({'primaryTitle': rgx})
for item in query:
    print (item)


问:
Relocation of option and answer key
I want to prepare questions for my students. There are questions in the school's database. The table is as follows:

```<code>| id | qcontent                                                                     | o1  | o2   | o3  |
|----|------------------------------------------------------------------------------|-----|------|-----|
| 1  | Lorem Ipsum is simply dummy text of the printing and typesetting industry.   | ab  | ba   | ce  |
| 2  | Lorem Ipsum has been the industry's standard dummy text ever since the 1500s | ce  | sas  | de  |
| 3  | Contrary to popular belief, Lorem Ipsum is not simply random text.           | ase | sded | def |
</code>```

The correct answers are the o1 option.

```<code><?php

foreach($employee as $element) {

    echo $element->id . ". question: " .$element->qcontent . "<br>";
    echo "A) " .$element->o1. "<br>";
    echo "B) " .$element->o2. "<br>";
    echo "C) " .$element->o3. "<br>";
    echo "D) " .$element->o4. "<br>";
    echo "E) " .$element->o5. "<br>";

}

echo "<hr>";
echo "Answers:";

foreach($employee as $element) {

    echo $element->id. " - " .$element->o1. "<br>";

}
</code>```

When I print the questions, all the right answers are option-A.
How can we generate the location of the questions and the answer key?

答:
By using shuffle() and making an array of all possible column of name:

```<code><?php
// make array of all possible keys
$keys = ['o1', 'o2', 'o3', 'o4', 'o5'];
foreach($employee as $element) {
    // convert object to array
    $element = (array)$element;

    // shuffle it
    shuffle($keys);

    echo $element['id'] . ". question: " .$element['qcontent'] . "<br>";

    echo "A) " .$element[$keys[0]] . "<br>";
    echo "B) " .$element[$keys[1]] . "<br>";
    echo "C) " .$element[$keys[2]] . "<br>";
    echo "D) " .$element[$keys[3]] . "<br>";
    echo "E) " .$element[$keys[4]] . "<br>";

}

echo "<hr>";
echo "Answers:";

foreach($employee as $element) {
    echo $element->id. " - " .$element->o1. "<br>";
}
</code>```

Title: Relocation of option and answer key

Body:
I want to prepare questions for my students. There are questions in the school's database. The table is as follows:

| id | qcontent                                                                     | o1  | o2   | o3  |
|----|------------------------------------------------------------------------------|-----|------|-----|
| 1  | Lorem Ipsum is simply dummy text of the printing and typesetting industry.   | ab  | ba   | ce  |
| 2  | Lorem Ipsum has been the industry's standard dummy text ever since the 1500s | ce  | sas  | de  |
| 3  | Contrary to popular belief, Lorem Ipsum is not simply random text.           | ase | sded | def |

The correct answers are the o1 option.

<?php

foreach($employee as $element) {

    echo $element->id . ". question: " .$element->qcontent . "
";
    echo "A) " .$element->o1. "
";
    echo "B) " .$element->o2. "
";
    echo "C) " .$element->o3. "
";
    echo "D) " .$element->o4. "
";
    echo "E) " .$element->o5. "
";

}

echo "
";
echo "Answers:";

foreach($employee as $element) {

    echo $element->id. " - " .$element->o1. "
";

}

When I print the questions, all the right answers are option-A.
How can we generate the location of the questions and the answer key?

Body:
By using shuffle() and making an array of all possible column of name:

<?php
// make array of all possible keys
$keys = ['o1', 'o2', 'o3', 'o4', 'o5'];
foreach($employee as $element) {
    // convert object to array
    $element = (array)$element;

    // shuffle it
    shuffle($keys);

    echo $element['id'] . ". question: " .$element['qcontent'] . "<br>";

    echo "A) " .$element[$keys[0]] . "<br>";
    echo "B) " .$element[$keys[1]] . "<br>";
    echo "C) " .$element[$keys[2]] . "<br>";
    echo "D) " .$element[$keys[3]] . "<br>";
    echo "E) " .$element[$keys[4]] . "<br>";

}

echo "<hr>";
echo "Answers:";

foreach($employee as $element) {
    echo $element->id. " - " .$element->o1. "<br>";
}


问:
What is the difference between these two Enum(s) in Java
I have a String object:  String theLanguage = "de";

I have these Two Enums:-

Enum 1:

```<code>public enum Lang
{
   French("fr"),
   German("de"),
   English("en"),
   Italian("it"),
   Spanish("sp");

   private String lang;

   Lang(String lang) {
      this.lang = lang;
   }

   public String lang() {
      return lang;
   }
}
</code>```

and Enum 2:

```<code>public enum Lang
{
   French(1, "fr"),
   German(2, "de"),
   English(3, "en"),
   Italian(4, "it"),
   Spanish(5, "sp");

   final int languageID;

   private final String code;

   Lang( int languageID, String code)
   {
      this.languageID = languageID;
      this.code= code;
   }
}
</code>```

------------------------ My Question -----------------------------

Q 1- What is the Difference between these two Enums ( Basically in 2nd Enum, why there are int values) ?

Q 2- What I need to Do OR Add in 2nd Enum in Order to Search/Match the theLanguage object with Enum2. ?

答:
the 2nd just has an extra parameter, the languageID

Add this code to 2nd Enum in order to search by code (e.g "de")

```<code>private static Map<String, Lang> reverseLookup = Arrays.stream(values())
             .collect(Collectors.toMap(Lang::getCode, Function.identity()));

public String getCode() {
    return code;
}

public static Lang fromCode(final String code) {
    return reverseLookup.get(code);
}
</code>```

Body:
I have a String object:  String theLanguage = "de";

I have these Two Enums:-

Enum 1:

public enum Lang
{
   French("fr"),
   German("de"),
   English("en"),
   Italian("it"),
   Spanish("sp");

   private String lang;

   Lang(String lang) {
      this.lang = lang;
   }

   public String lang() {
      return lang;
   }
}

and Enum 2:

public enum Lang
{
   French(1, "fr"),
   German(2, "de"),
   English(3, "en"),
   Italian(4, "it"),
   Spanish(5, "sp");

   final int languageID;

   private final String code;

   Lang( int languageID, String code)
   {
      this.languageID = languageID;
      this.code= code;
   }
}

------------------------ My Question -----------------------------

Q 1- What is the Difference between these two Enums ( Basically in 2nd Enum, why there are int values) ?

Q 2- What I need to Do OR Add in 2nd Enum in Order to Search/Match the theLanguage object with Enum2. ?

Body:
the 2nd just has an extra parameter, the languageID

Add this code to 2nd Enum in order to search by code (e.g "de")

private static Map<String, Lang> reverseLookup = Arrays.stream(values())
             .collect(Collectors.toMap(Lang::getCode, Function.identity()));

public String getCode() {
    return code;
}

public static Lang fromCode(final String code) {
    return reverseLookup.get(code);
}


问:
Checkout shopping cart UICollectionViewCell
I have a shopping cart check out flow using a UICollectionView with full page UICollectionViewCells. When the add button is pressed, the remove button is then visible and vice versa. For some reason when add and remove are repeatedly pressed it disrupts the other cells. It will show remove button on another cell when the add button on that cell was never even pressed. I am not sure what's wrong with my logic.</p>

```<code>   protocol PostCellDelegate {
func removeButtonTapped(cell: PostCell)
func addTapped(cell: PostCell)
   }

    class PostCell: UICollectionViewCell {
  var currentPrice: Float = 0
  var delegate: PostCellDelegate?

   func set(name: String, brand: String, price: String, image: String){
       nameLabel.text = name
       brandLabel.text = brand
       priceLabel.text = "$\(price)"
    photoImageView.loadImage(urlString: image)

   }

 override init(frame: CGRect) {
     super.init(frame: frame)
    self.myButton.addTarget(self, action: #selector(addButtonTapped(sender:)), for: .touchUpInside)
    self.removeButton.addTarget(self, action: #selector(subButtonTapped(sender:)), for: .touchUpInside)
   self.contentView.addSubview(containerView)
    setupCellConstraints()

    }
@objc func addButtonTapped(sender: UIButton){
      self.delegate?.addTapped(cell: self)
      sender.isHidden = true
  }

@objc func subButtonTapped(sender: UIButton){
    self.delegate?.removeButtonTapped(cell: self)
    sender.isHidden = true
}
 }

  class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
   var totalPrice = Float()

   private var hiddenRows = Set<Int>()

  var finalList = [Item]()

  @objc func addTapped(cell: PostCell) {

      guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
      hiddenRows.insert(indexPath.row)
      cell.removeButton.isHidden = false
      let item = itemsArr[indexPath.row]
      finalList.append(item)
      collectionView?.reloadData()
      totalPrice += Float(item.price) ?? 0
       }

    @objc func removeButtonTapped(cell: PostCell) {

    guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
    hiddenRows.insert(indexPath.row)
    cell.myButton.isHidden = false
    let item = itemsArr[indexPath.row]
    finalList.removeAll{ $0.name == item.name}
    totalPrice -= Float(item.price) ?? 0
     }

  extension CollectionViewController {

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell
            cell.delegate = self

    let item = itemsArr[indexPath.row]
    let page = itemsArr[indexPath.item]

    cell.set(name: item.name, brand: item.brand, price: item.price, image: item.image_url)
     if hiddenRows.contains(indexPath.row) {
                cell.myButton.isHidden = true
                cell.removeButton.isHidden = false
            }else{
                cell.removeButton.isHidden = true
                cell.myButton.isHidden = false
            }

    return cell
}
</code>```

答: It was because in removeButtonTapped I had hiddenRows.insert(indexPath.row) instead of   hiddenRows.remove(indexPath.row). I don't know how I missed that.

Body:
I have a shopping cart check out flow using a UICollectionView with full page UICollectionViewCells. When the add button is pressed, the remove button is then visible and vice versa. For some reason when add and remove are repeatedly pressed it disrupts the other cells. It will show remove button on another cell when the add button on that cell was never even pressed. I am not sure what's wrong with my logic.

   protocol PostCellDelegate {
func removeButtonTapped(cell: PostCell)
func addTapped(cell: PostCell)
   }

    class PostCell: UICollectionViewCell {
  var currentPrice: Float = 0
  var delegate: PostCellDelegate?

   func set(name: String, brand: String, price: String, image: String){
       nameLabel.text = name
       brandLabel.text = brand
       priceLabel.text = "$\(price)"
    photoImageView.loadImage(urlString: image)

   }

 override init(frame: CGRect) {
     super.init(frame: frame)
    self.myButton.addTarget(self, action: #selector(addButtonTapped(sender:)), for: .touchUpInside)
    self.removeButton.addTarget(self, action: #selector(subButtonTapped(sender:)), for: .touchUpInside)
   self.contentView.addSubview(containerView)
    setupCellConstraints()

    }
@objc func addButtonTapped(sender: UIButton){
      self.delegate?.addTapped(cell: self)
      sender.isHidden = true
  }

@objc func subButtonTapped(sender: UIButton){
    self.delegate?.removeButtonTapped(cell: self)
    sender.isHidden = true
}
 }

  class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
   var totalPrice = Float()

   private var hiddenRows = Set<Int>()

  var finalList = [Item]()

  @objc func addTapped(cell: PostCell) {

      guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
      hiddenRows.insert(indexPath.row)
      cell.removeButton.isHidden = false
      let item = itemsArr[indexPath.row]
      finalList.append(item)
      collectionView?.reloadData()
      totalPrice += Float(item.price) ?? 0
       }

    @objc func removeButtonTapped(cell: PostCell) {

    guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
    hiddenRows.insert(indexPath.row)
    cell.myButton.isHidden = false
    let item = itemsArr[indexPath.row]
    finalList.removeAll{ $0.name == item.name}
    totalPrice -= Float(item.price) ?? 0
     }

  extension CollectionViewController {

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell
            cell.delegate = self

    let item = itemsArr[indexPath.row]
    let page = itemsArr[indexPath.item]

    cell.set(name: item.name, brand: item.brand, price: item.price, image: item.image_url)
     if hiddenRows.contains(indexPath.row) {
                cell.myButton.isHidden = true
                cell.removeButton.isHidden = false
            }else{
                cell.removeButton.isHidden = true
                cell.myButton.isHidden = false
            }

    return cell
}


问:
margin-bottom / vertical space strategy for CSS columns (flex)

Scenario

One section at the top with two columns (flex). Each column containing multiple elements.

One section below that with a single column.

The vertical space between elements within each column should be 30px (we are considering rem or em sizes, but let's stick to px for this discussion).

The vertical space between sections should be 40px. (I am choosing a different number here to make it more interesting.)

Implementation, first attempt

The first step is to set margin-bottom on different elements.

```<code><style>
.section-top {
  display: flex;
}
.section-top > div {
  width: 50%;
}
.container > section {
  margin-bottom: 40px;
}
.column-left > section,
.column-right > section {
  margin-bottom: 30px;
}
</style>
<div class="container">
  <section class="section-top">
    <!-- top section with two columns (flex) -->
    <div class="column-left">
      <section>Block L1</section>
      <section>Block L2</section>
    </div>
    <div class="column-right">
      <section>Block R1</section>
      <section>Block R2</section>
      <section>Block R3</section>
    </div>
  </section>
  <section class="section-bottom">Section 2</div>
  <section class="section-bottom">Section 3</div>
</div>
</code>```

Problem

Now there is 70px vertical space between the visible content of the top section and the lower sections. Instead, we only want 40px.

This is not surprising, it is known that vertical margin on flex items does not collapse with the margin of the container.

Question

What is a good and common strategy to solve this, and only have 40px instead of 70px space between the top sections and the lower sections?

Ideally this should support:

Different number and height of elements in each column.

Possibility of a column with no elements.

Different vertical spacing for column elements vs top-level sections.

Neutralize or collapse with margins from nested elements.

Component-based CSS, where the definition of the margin between top-level sections is independent of the section contents.

What I tried so far

There are many ways to solve this technically:

Set margin-bottom: 0; on :last-child in each column.

Problem: Does not neutralize margins from nested elements.

Use margin-bottom: 0; on .section-top, and instead have the 40px in each column or on the last-child item inside each column.

Problem: Need to define the 40px in two places. E.g. if I want to change the vertical space between top-level sections to 60px later, I will also need to update the CSS for the columns.

Use negative margins to compensate?

All of this will work, but perhaps there is something better out there which I am not seeing.

答:
Here is one solution. I don't know if it is the best, but it works for me.

We add an ::after pseudo-element into each column.

```<code><style>
.container > section {
  margin-bottom: 40px;
}
.section-top {
  display: flex;
}
.section-top > .column {
  width: 50%;
}
.section-top > .column > section {
  margin-bottom: 30px;
}
.section-top > .column::after {
  /* Optionally change these to 40px / -40px, not sure what is better */
  margin-top: 30px;
  margin-bottom: -30px;
}
</style>
<div class="container">
  <section class="section-top">
    <!-- top section with two columns (flex) -->
    <div class="column column-left">
      <section>Block L1</section>
      <section>Block L2</section>
    </div>
    <div class="column column-right">
      <section>Block R1</section>
      <section>Block R2</section>
      <section>Block R3</section>
    </div>
  </section>
  <section class="section-bottom">Section 2</div>
  <section class="section-bottom">Section 3</div>
</div>
</code>```

Body:
Scenario

One section at the top with two columns (flex). Each column containing multiple elements.

One section below that with a single column.

The vertical space between elements within each column should be 30px (we are considering rem or em sizes, but let's stick to px for this discussion).

The vertical space between sections should be 40px. (I am choosing a different number here to make it more interesting.)

Implementation, first attempt

The first step is to set margin-bottom on different elements.

Block L1

Block L2

Block R1

Block R2

Block R3

Section 2

Section 3

Problem

Now there is 70px vertical space between the visible content of the top section and the lower sections. Instead, we only want 40px.

This is not surprising, it is known that vertical margin on flex items does not collapse with the margin of the container.

Question

What is a good and common strategy to solve this, and only have 40px instead of 70px space between the top sections and the lower sections?

Ideally this should support:

Different number and height of elements in each column.

Possibility of a column with no elements.

Different vertical spacing for column elements vs top-level sections.

Neutralize or collapse with margins from nested elements.

Component-based CSS, where the definition of the margin between top-level sections is independent of the section contents.

What I tried so far

There are many ways to solve this technically:

Set margin-bottom: 0; on :last-child in each column.

Problem: Does not neutralize margins from nested elements.

Use margin-bottom: 0; on .section-top, and instead have the 40px in each column or on the last-child item inside each column.

Problem: Need to define the 40px in two places. E.g. if I want to change the vertical space between top-level sections to 60px later, I will also need to update the CSS for the columns.

Use negative margins to compensate?

All of this will work, but perhaps there is something better out there which I am not seeing.

Body:
Here is one solution. I don't know if it is the best, but it works for me.

We add an ::after pseudo-element into each column.

<style>
.container > section {
  margin-bottom: 40px;
}
.section-top {
  display: flex;
}
.section-top > .column {
  width: 50%;
}
.section-top > .column > section {
  margin-bottom: 30px;
}
.section-top > .column::after {
  /* Optionally change these to 40px / -40px, not sure what is better */
  margin-top: 30px;
  margin-bottom: -30px;
}
</style>
<div class="container">
  <section class="section-top">
    <!-- top section with two columns (flex) -->
    <div class="column column-left">
      <section>Block L1</section>
      <section>Block L2</section>
    </div>
    <div class="column column-right">
      <section>Block R1</section>
      <section>Block R2</section>
      <section>Block R3</section>
    </div>
  </section>
  <section class="section-bottom">Section 2</div>
  <section class="section-bottom">Section 3</div>
</div>


问:
How do you use an object type as a parameter for method/constructor?
I'm currently working on a Java TD game. I have a class called "Wave" that holds the enemy types to spawn (that all extend the class "Enemy") and the delay between the spawns.

```<code>public class Wave {

*I dunno what*[] enemyTypes;
int[] delays;
private Point spawnPoint;

Wave(*I dunno what*[] enemyTypes, int[] delays, Point spawnPoint) {

    this.enemyTypes = enemyTypes;
    this.delays = delays;
    this.spawnPoint = spawnPoint;

}

void spawnWave() {

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

        try {

            Thread.sleep(delays[i]);

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

        Point sP = new Point(spawnPoint);

        *The enemy type to spawn* enemy = new *The enemy type to spawn*.spawn(sP);

    }

}
</code>```

}

I don't know how to code the bits within the **

答:
looks like a use case for factory pattern

you can provide array of factories for your enemy classes

Body:
I'm currently working on a Java TD game. I have a class called "Wave" that holds the enemy types to spawn (that all extend the class "Enemy") and the delay between the spawns.

public class Wave {

*I dunno what*[] enemyTypes;
int[] delays;
private Point spawnPoint;

Wave(*I dunno what*[] enemyTypes, int[] delays, Point spawnPoint) {

    this.enemyTypes = enemyTypes;
    this.delays = delays;
    this.spawnPoint = spawnPoint;

}

void spawnWave() {

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

        try {

            Thread.sleep(delays[i]);

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

        Point sP = new Point(spawnPoint);

        *The enemy type to spawn* enemy = new *The enemy type to spawn*.spawn(sP);

    }

}

}

I don't know how to code the bits within the **


问:
How to get all Saturdays in year with format as "Saturday, dd.MM.YYYY"?
I want to add all Saturdays of 2020/2021 into an object like following:</p>

```<code>saturdays = {
   "Saturday, 22.02.2020" : "Saturday, 22.02.2020" ,
   "Saturday, 29.02.2020" : "Saturday, 29.02.2020"
}
</code>```

答:
It is an unusual format (name is the same as the value) and objects are not ordered so don't expect to get them back in any particular order . . . but it is pretty trivial to do if you want . . .

    saturdays = {};

    function loadSaturdays(startYear, endYear) {
        const SATURDAY = 6;
        let start = new Date("01/01/" + startYear);
        let end = new Date("12/31/" + endYear);
        var dateOptions = {weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric'};

        var current = new Date(start);
        while (current <= end) {
            if (SATURDAY === current.getDay()) {
                let newSaturday = "\"" + current.toLocaleString('en-GB', dateOptions).replace(/\//gi, '.') + "\"";
                // if you want to see the individual ones as you are building the object
                // console.log(newSaturday);
                saturdays[newSaturday] = newSaturday;
            }
            current = new Date(current.setDate(current.getDate() + 1));
        }
    }

    loadSaturdays("2020", "2021");

    // if you want to see the entire object
    //console.log(saturdays);

    // objects are not ordered but they are all there
    for (saturday in saturdays) {
        console.log(saturday);
    }```

Body:
I want to add all Saturdays of 2020/2021 into an object like following:

saturdays = {
   "Saturday, 22.02.2020" : "Saturday, 22.02.2020" ,
   "Saturday, 29.02.2020" : "Saturday, 29.02.2020"
}


答:
1 - The second one can be searched for through both the string and int value (if for example you know the id of the language but not its code). Idk what "WhoisRIR" is doing in the place where your constructor should be.

2 - You need to add a getter for the code string and then foreach the enum until you find a element with code identical to theLanguage.

Title: What is the difference between these two Enum(s) in Java


问:
Code for converting entire data frame to numeric
Is there an R function to convert the entire data frame to numeric. My data frame contains only numeric variables but when queried with r with the is.numeric code, it comes as false. </p>

答:
We can use</p>

```<code>df1[]<-  lapply(df1, as.numeric)
</code>```

Body:
We can use

df1[]<-  lapply(df1, as.numeric)


问:
Ignore App.xaml styles
I am using WPF Material Design where I had to add resource dictionary into my App.xaml. This way styles are applied to each of my control.

App.xaml

```<code>  <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.PopupBox.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</code>```

I have created UserControl where I would like to ignore the MaterialDesign styles is it possible?

答: If you've overridden something like

Title: Ignore App.xaml styles

Body:
I am using WPF Material Design where I had to add resource dictionary into my App.xaml. This way styles are applied to each of my control.

App.xaml

  <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.PopupBox.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

I have created UserControl where I would like to ignore the MaterialDesign styles is it possible?

Body:
If you've overridden something like <Style TargetType={x:Type Button}/> in your app.xaml and are trying to reset it to how Microsoft styled it on a particular page, here's an excellent solution by Marco Zhou:

If you want to apply the luna theme, you could simply merge the theme dictionary under App.Resources as follows:

<Application x:Class="WpfTestHarness.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="RenderNotificationDemo.xaml">
  <Application.Resources>
    <!--This is the relevant bit-->
    <ResourceDictionary Source="/PresentationFramework.luna, Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/luna.normalcolor.xaml" />
  </Application.Resources>
</Application>

Note that you need to add reference to the PresentationFramework.luna dll.


问:
Shifting Cells values in Python
I have the following DataFrame:

SampleTable

Hence the header of the table I imported is divided in two cells I need to shift the cells of the first two columns to shift up. And then to shift the 3 and 4 up. For it to look like this:

What I need

I have tried

```<code>df.at[1,'x'] = None
</code>```

But that just deletes de value without shifting any cell.

What I get

答:
Get the header with</p>

```<code>df.columns = df.loc[0].iloc[:2].tolist() + df.columns[2:].tolist()
df = df.loc[1:].reset_index(drop=True)
</code>```

```<code>   A  B  C  D
0  1  2  3  4
</code>```

Title: Shifting Cells values in Python

Body:
I have the following DataFrame:

SampleTable

Hence the header of the table I imported is divided in two cells I need to shift the cells of the first two columns to shift up. And then to shift the 3 and 4 up. For it to look like this:

What I need

I have tried

df.at[1,'x'] = None

But that just deletes de value without shifting any cell.

What I get

Body:
Get the header with

df.columns = df.loc[0].iloc[:2].tolist() + df.columns[2:].tolist()
df = df.loc[1:].reset_index(drop=True)

   A  B  C  D
0  1  2  3  4


问:
Get max of 2 objects
I am very new to C++. Is there a way I could compare 2 objects of the same class and return the bigger one?

This is some pseudo code to illustrate the idea

```<code>HashMap biggerObject = std::max( obj1, obj2,
                             []( HashMap &a, HashMap &b )
                             {
                                 return a.size() < b.size();
                             } );
</code>```

And how could I write HashMap in a way so that it knows how to compare itself?

答:
The problem is that while it is easy to add an operator< method to your own implementation of HashMap, is this the only meaning of less-than for the HashMap container? If not, then it will cause confusion in the future. Could less-than also mean subset-of?

It may be better to write a generic function that relies on the class having a size() member that it compares, or even just a simple function that takes 2 of your HashMap objects:

```<code>template <class Container>
Container& FewestMembers(Container& lhs, Container& rhs)
{
    if (lhs.size() < rhs.size())
        return lhs;
    else
        return rhs;
}

template <class Container>
Container& MostMembers(Container& lhs, Container& rhs)
{
    if (lhs.size() > rhs.size())
        return lhs;
    else
        return rhs;
}

</code>```

Title: Get max of 2 objects

Body:
I am very new to C++. Is there a way I could compare 2 objects of the same class and return the bigger one?

This is some pseudo code to illustrate the idea

HashMap biggerObject = std::max( obj1, obj2,
                             []( HashMap &a, HashMap &b )
                             {
                                 return a.size() < b.size();
                             } );

And how could I write HashMap in a way so that it knows how to compare itself?

Body:
The problem is that while it is easy to add an operator< method to your own implementation of HashMap, is this the only meaning of less-than for the HashMap container? If not, then it will cause confusion in the future. Could less-than also mean subset-of?

It may be better to write a generic function that relies on the class having a size() member that it compares, or even just a simple function that takes 2 of your HashMap objects:

template <class Container>
Container& FewestMembers(Container& lhs, Container& rhs)
{
    if (lhs.size() < rhs.size())
        return lhs;
    else
        return rhs;
}

template <class Container>
Container& MostMembers(Container& lhs, Container& rhs)
{
    if (lhs.size() > rhs.size())
        return lhs;
    else
        return rhs;
}


问:
How to update multiple rows with values of two arrays in Postgres?
I need to update a set of records in the x table with values stored in arrays. Anyone know how I could do it?

```<code>IDS_NEW_SPONSORS INTEGER[] := ARRAY[]::INTEGER[]; --possible values [1,2,3,4,5,6]
IDS_DEBTORS  INTEGER[] := ARRAY[]::INTEGER[]; --possible values [20,21,22,23,24,25]
-- the arrays will be the same size--
UPDATE x
SET id_sponsor = [IDS_NEW_SPONSORS],-- HOW ADD
id_sponsor_historial = [IDS_DEBTORS], -- HOW ADD
id_patron = 5 -- ALWAYS SAME
WHERE id_sponsor = ANY(IDS_DEBTORS); -- this line working!!! loop each row
</code>```

I'm working with postgres 11...

After update. the table would look like this:

```<code>id_sponsor | id_sponsor_historial | id_patron
1            20                     5
2            21                     5
3            22                     5
4            23                     5
5            24                     5
6            25                     5
</code>```

答:
The next a little tricky query do this work:

(The trick is match value in new values array by position in old values array)

```<code>UPDATE sponsors
SET
    id_sponsor_historial = id_sponsor, -- save previous value as historical
    id_sponsor = (array[1,2,3,4,5,6])[array_position(array[20,21,22,23,24,25], id_sponsor)],-- update new value
    id_patron = 5
WHERE id_sponsor = ANY(array[20,21,22,23,24,25]); -- find rows
</code>```

I rest the integers array for example. In your case it should be changed to variables. The example works only if new and old values arrays have equals lengths.

Body:
I need to update a set of records in the x table with values stored in arrays. Anyone know how I could do it?

IDS_NEW_SPONSORS INTEGER[] := ARRAY[]::INTEGER[]; --possible values [1,2,3,4,5,6]
IDS_DEBTORS  INTEGER[] := ARRAY[]::INTEGER[]; --possible values [20,21,22,23,24,25]
-- the arrays will be the same size--
UPDATE x
SET id_sponsor = [IDS_NEW_SPONSORS],-- HOW ADD
id_sponsor_historial = [IDS_DEBTORS], -- HOW ADD
id_patron = 5 -- ALWAYS SAME
WHERE id_sponsor = ANY(IDS_DEBTORS); -- this line working!!! loop each row

I'm working with postgres 11...

After update. the table would look like this:

id_sponsor | id_sponsor_historial | id_patron
1            20                     5
2            21                     5
3            22                     5
4            23                     5
5            24                     5
6            25                     5

Body:
The next a little tricky query do this work:

(The trick is match value in new values array by position in old values array)

UPDATE sponsors
SET
    id_sponsor_historial = id_sponsor, -- save previous value as historical
    id_sponsor = (array[1,2,3,4,5,6])[array_position(array[20,21,22,23,24,25], id_sponsor)],-- update new value
    id_patron = 5
WHERE id_sponsor = ANY(array[20,21,22,23,24,25]); -- find rows

I rest the integers array for example. In your case it should be changed to variables. The example works only if new and old values arrays have equals lengths.


问:
Determine whether a row is selected in a DataGridView
I'm looping through a DataGridView, and I need to do this :</p>

```<code> for(int i = 0; i < DGV.Rows.Count - 2; i)
 {
    // if the row is selected
    // do something
 }
</code>```

答:
```<code>if (DGV.SelectedRows.Contains(DGW.Rows[i]))
{
    // ...
}
</code>```

Body:
I'm looping through a DataGridView, and I need to do this :

 for(int i = 0; i < DGV.Rows.Count - 2; i)
 {
    // if the row is selected
    // do something
 }


问:
How to return PDF using iText
I am trying to return a PDF with simple text, but getting the following error when downloading the document: Failed to load PDF document.  Any ideas on how to resolve this is appreciated.</p>

```<code>MemoryStream ms = new MemoryStream();

PdfWriter writer = new PdfWriter(ms);
PdfDocument pdfDocument = new PdfDocument(writer);
Document document = new Document(pdfDocument);

document.Add(new Paragraph("Hello World"));

//document.Close();
//writer.Close();

ms.Position = 0;

string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";

return File(ms, "application/pdf", pdfName);
</code>```

答:
You have to close the writer without closing the underlying stream, which will flush its internal buffer. As is, the document isn't being written to the memory stream in its entirety. Everything but ms should be in a using, too.

You can verify this is occuring by checking the length of ms in your code vs. the code below.

When the using (PdfWriter writer =...) closes, it will close the writer, which causes it to flush its pending writes to the underlying stream ms.

```<code>MemoryStream ms = new MemoryStream();

using (PdfWriter writer = new PdfWriter(ms))
using (PdfDocument pdfDocument = new PdfDocument(writer))
using (Document document = new Document(pdfDocument))
{
    /*
     * Depending on iTextSharp version, you might instead use:
     *     writer.SetCloseStream(false);
     */
    writer.CloseStream = false;
    document.Add(new Paragraph("Hello World"));
}

ms.Position = 0;

string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";

return File(ms, "application/pdf", pdfName);
</code>```

Title: How to return PDF using iText

Body:
I am trying to return a PDF with simple text, but getting the following error when downloading the document: Failed to load PDF document.  Any ideas on how to resolve this is appreciated.

MemoryStream ms = new MemoryStream();

PdfWriter writer = new PdfWriter(ms);
PdfDocument pdfDocument = new PdfDocument(writer);
Document document = new Document(pdfDocument);

document.Add(new Paragraph("Hello World"));

//document.Close();
//writer.Close();

ms.Position = 0;

string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";

return File(ms, "application/pdf", pdfName);

Body:
You have to close the writer without closing the underlying stream, which will flush its internal buffer. As is, the document isn't being written to the memory stream in its entirety. Everything but ms should be in a using, too.

You can verify this is occuring by checking the length of ms in your code vs. the code below.

When the using (PdfWriter writer =...) closes, it will close the writer, which causes it to flush its pending writes to the underlying stream ms.

MemoryStream ms = new MemoryStream();

using (PdfWriter writer = new PdfWriter(ms))
using (PdfDocument pdfDocument = new PdfDocument(writer))
using (Document document = new Document(pdfDocument))
{
    /*
     * Depending on iTextSharp version, you might instead use:
     *     writer.SetCloseStream(false);
     */
    writer.CloseStream = false;
    document.Add(new Paragraph("Hello World"));
}

ms.Position = 0;

string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";

return File(ms, "application/pdf", pdfName);


问:
Using Circe to decode Json String
I have a Json string as

```<code>val configInfo =   {
      "car": {
        "requesters": {
          "request1": "key1",
          "request2": "key2"
        },
        "provider": {
          "request1": "key3",
          "request2": "key4"
        }
      },
      "truck": {
        "requesters": {
          "request1": "key2",
          "request2": "key3"
        },
        "provider": {
          "request1": "key2",
          "request2": "key3"
        }
      }
    }
</code>```

I have the following case class to decode json string.

```<code>final case class TenantSettings(requesters: Map[String, String], provider: Map[String, String] = Map.empty)
</code>```

Also, providers in above case class is optional, it may or may not be present in json string.

I want to decode this using circe to

```<code>val value = decode[Map[String, TenantSettings]](configInfo)
</code>```

I understand I need to use custom circe codec, but I am unable to do it, Can someone please help out on this.

答:
This is what I did and worked for me</p>

```<code>implicit val decodeTenantSetting: Decoder[TenantSettings] = new Decoder[TenantSettings] {
      final def apply(c: HCursor): Decoder.Result[TenantSettings] =
        for {
          requesters <- c.downField("requesters").as[Map[String, String]]
        } yield {
          TenantSettings(requesters)
        }
    }

val abc = decode[Map[String, TenantSettings]](configInfo)
</code>```

Title: Using Circe to decode Json String

Body:
I have a Json string as

val configInfo =   {
      "car": {
        "requesters": {
          "request1": "key1",
          "request2": "key2"
        },
        "provider": {
          "request1": "key3",
          "request2": "key4"
        }
      },
      "truck": {
        "requesters": {
          "request1": "key2",
          "request2": "key3"
        },
        "provider": {
          "request1": "key2",
          "request2": "key3"
        }
      }
    }

I have the following case class to decode json string.

final case class TenantSettings(requesters: Map[String, String], provider: Map[String, String] = Map.empty)

Also, providers in above case class is optional, it may or may not be present in json string.

I want to decode this using circe to

val value = decode[Map[String, TenantSettings]](configInfo)

I understand I need to use custom circe codec, but I am unable to do it, Can someone please help out on this.

Body:
This is what I did and worked for me

implicit val decodeTenantSetting: Decoder[TenantSettings] = new Decoder[TenantSettings] {
      final def apply(c: HCursor): Decoder.Result[TenantSettings] =
        for {
          requesters <- c.downField("requesters").as[Map[String, String]]
        } yield {
          TenantSettings(requesters)
        }
    }

val abc = decode[Map[String, TenantSettings]](configInfo)


问:
Correct format specifier to print pointer or address?
Which format specifier should I be using to print the address of a variable? I am confused between the below lot.

%u - unsigned integer

%x - hexadecimal value

%p - void pointer

Which would be the optimum format to print an address?

答:
You can use %x or %X or %p; all of them are correct.

If you use %x, the address is given as lowercase, for example: a3bfbc4

If you use %X, the address is given as uppercase, for example: A3BFBC4

Both of these are correct.

If you use %x or %X it's considering six positions for the address, and if you use %p it's considering eight positions for the address. For example:


问:
How can I access the current executing module or class name in Python?
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module.  Here is some code:

foo.py:

```<code>def f():
    print __name__
</code>```

bar.py:

```<code>from foo import f

def b(): f()
</code>```

This obviously does not work as __name__ is the name of the module that contains the function.  What I would like to be access inside the foo module is the name of the current executing module that is using foo.  So in the case above it would be bar but if any other module imported foo I would like foo to dynamically have access to the name of that module.

Edit: The inspect module looks quite promising but it is not exactly what I was looking for.  What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module.  Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.

Edit: Here is how I am trying to use this.  I have two different Django applications that both need to log errors to file.  Lets say that they are called "AppOne" and "AppTwo".  I also have a place to which I would like to log these files: "/home/hare/app_logs".  In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file.  However what I would like to do is create a directory under app_logs that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.

In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.

答: I think what you want to use is the inspect module, to inspect the python runtime stack.  Check out this tutorial.  I think it provides an almost exact example of what you want to do.</p>

OwnerDisplayName: Andrew Hare

ContentLicense: CC BY-SA 2.5

Body:
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module.  Here is some code:

foo.py:

def f():
    print __name__

bar.py:

from foo import f

def b(): f()

This obviously does not work as __name__ is the name of the module that contains the function.  What I would like to be access inside the foo module is the name of the current executing module that is using foo.  So in the case above it would be bar but if any other module imported foo I would like foo to dynamically have access to the name of that module.

Edit: The inspect module looks quite promising but it is not exactly what I was looking for.  What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module.  Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.

Edit: Here is how I am trying to use this.  I have two different Django applications that both need to log errors to file.  Lets say that they are called "AppOne" and "AppTwo".  I also have a place to which I would like to log these files: "/home/hare/app_logs".  In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file.  However what I would like to do is create a directory under app_logs that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.

In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.

LastEditorDisplayName: Andrew Hare

OwnerDisplayName: nstehr