问:
How to handle different button onclick within a cardview and passing intents?
I have a cardview which is presenting the upcoming events with title, date, etc. and there are two imageviews that should function as buttons: if clicked on one it should go to the participation confirming activity, if on the other on the detail activity. Both of these should also pass informations using intents(name, date, user id, token). I have followed this tutorial, because this was the closest solution to my problem but it still does not work. Whatever I change these are the errors I get:  Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference (this is given when  I call the setButtons function), or if the onclick somehow works the intents don't get passed and i get a nullpointerexception. I made sure I have used the right ids and names.
Additional information: i am using Laravel, and retrofit.
EventsActivity:

```<code>public class EventsActivity extends AppCompatActivity {
private static final String TAG = "EventsActivity";
private static final int ACTIVITY_NUM = 1;
private static final String PREFS_NAME = "LoginPrefs";
public static final String EVENT_DETAIL = "EVENT_DETAIL";
private Context mContext = EventsActivity.this;
private Event mEvent = new Event();
private String token, name;
private int id;
private EventAdapter adapter;
private RecyclerView recyclerView;
private List<Event> eventList = new ArrayList<>();
private List<Response> result;
private TextView noEvents;
private Button add, more;

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

    //Get token and id from shared preferences
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    token = settings.getString("token", "");
    id = settings.getInt("id", 0);
    Log.d(TAG, "onResponse: id " + id + "token " + token);

    noEvents = findViewById(R.id.noEvents);
    recyclerView = findViewById(R.id.event_recyclerview);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);
    recyclerView.setLayoutManager(layoutManager);
    adapter = new EventAdapter(mContext, eventList);
    recyclerView.setAdapter(adapter);

    adapter.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
        @Override
        public void onAddClicked(int position) {
           addClick(position);
        }

        @Override
        public void onMoreClicked(int position) {
            moreClick(position);
        }
    });

    loadData();
    setButtons();
}

public void addClick(int position){
    final Event event = eventList.get(position);
    Intent i = new Intent(EventsActivity.this, EventInvitationActivity.class);
    i.putExtra("name", event.getName());
    i.putExtra("name", event.getDescription());
    i.putExtra("name", event.getDate());
    i.putExtra("name", event.getLocation());
    Log.i("hello", event.getName());
    startActivity(i);
}

public void moreClick(int position){
    final Event event = eventList.get(position);
    Intent i = new Intent(EventsActivity.this, EventDetailActivity.class);
    i.putExtra("name", event.getName());
    Log.i("hello", event.getName());
    startActivity(i);
}

void setButtons() {
     add = findViewById(R.id.add_icon);
     more = findViewById(R.id.more_icon);
    Log.d(TAG, "setButtons: called");
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: add onclicklistener");
            int position = Integer.parseInt(v.getTag().toString());
            addClick(position);
        }
    });
    more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = Integer.parseInt(v.getTag().toString());
            moreClick(position);
        }
    });
}

//Listing events
private void loadData(){
    ApiEvents service = RetrofitBuilder.getRetrofitInstance().create(ApiEvents.class);
    Call<List<Event>> call = service.listEvents("Bearer" + token, id);
    call.enqueue(new Callback<List<Event>>() {
        @Override
        public void onResponse(@NonNull Call<List<Event>> call, @NonNull Response<List<Event>> response) {
            if (response.isSuccessful() && response.body()!=null) {
                Log.d(TAG, "onResponse: loadData called");
                eventList = response.body();
                adapter = new EventAdapter(mContext, eventList);
                recyclerView.setAdapter(adapter);
                adapter.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
                    @Override
                    public void onAddClicked(int position) {
                        addClick(position);
                    }

                    @Override
                    public void onMoreClicked(int position) {
                        moreClick(position);
                    }
                });
            }
            else if(response.body() == null){
                noEvents.setVisibility(View.VISIBLE);
            }
            else{
                Log.d(TAG, "onResponse: " + response.body());
            }
        }

        @Override
        public void onFailure(@NonNull Call<List<Event>> call, @NonNull Throwable t) {
            Log.d("Response", "onFailure: " + t.toString());
        }
    });
}
</code>```

}

EventAdapter

```<code>public class EventAdapter extends RecyclerView.Adapter<EventAdapter.MyViewHolder> {
private Context mContext;
private List<Event> eventList;
private static final String TAG = "EventDetailActivity";
private OnItemClickListener clickListener;

public EventAdapter(Context mContext, List<Event> eventList){
    this.mContext = mContext;
    this.eventList = eventList;
}

public interface OnItemClickListener {
    void onAddClicked(int position);
    void onMoreClicked(int position);
}

public void setOnItemClickListener(OnItemClickListener clickListener) {
    this.clickListener = clickListener;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_layout, parent,
false);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
    Event event = eventList.get(position);
    holder.itemView.setTag(event);
    holder.title.setText(eventList.get(position).getName());
    holder.description.setText(eventList.get(position).getDescription());
    holder.date.setText(eventList.get(position).getDate());
    holder.location.setText(eventList.get(position).getLocation());
    holder.add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(clickListener != null){
                int position = (int)v.getTag();
                clickListener.onAddClicked(position);
                final Event event = (Event)v.getTag();
                if(event!= null){
                    Intent i = new Intent(mContext, EventInvitationActivity.class);
                    i.putExtra("EVENT_DETAIL", event);
                    v.getContext().startActivity(i);
                }
            }
        }
    });

    holder.more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(clickListener != null){
                int position = (int)v.getTag();
                clickListener.onMoreClicked(position);
                final Event event = (Event)v.getTag();
                if(event!= null){
                    Intent i = new Intent(mContext, EventDetailActivity.class);
                    i.putExtra("EVENT_DETAIL", event);
                    v.getContext().startActivity(i);
                }
            }
        }
    });

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

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView title, description, date, location;
    Button add, more;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        title = itemView.findViewById(R.id.event_name);
        description = itemView.findViewById(R.id.event_description);
        date = itemView.findViewById(R.id.event_date);
        location = itemView.findViewById(R.id.event_location);
        add = itemView.findViewById(R.id.add_icon);

    }

}
</code>```

And this is the way I am trying to get the passed intents in the two activities:

```<code>//Getting resources
    mName = findViewById(R.id.eventName);
    mDescription = findViewById(R.id.description);
    mLocation = findViewById(R.id.location);
    mDate = findViewById(R.id.date);

    mEvent = Objects.requireNonNull(getIntent().getExtras()).getParcelable(EVENT_DETAIL);
   if(mEvent != null){
    mName.setText(mEvent.getName());
    mDescription.setText(mEvent.getDescription());
    mLocation.setText(mEvent.getLocation());
    mDate.setText(mEvent.getDate());
   }
</code>```

And here is a button example within the cardview:

```<code><Button
            android:id="@+id/add_icon"
            android:layout_width="80dp"
            android:layout_height="40dp"
            android:layout_below="@+id/image"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="5dp"
            android:layout_toEndOf="@id/event_description"
            android:drawableStart="@drawable/ic_add_black_24dp"
            android:scaleType="centerCrop"
            android:transitionName="img"
            android:visibility="visible"
            android:textColor="@color/colorAccent"
           />
</code>```

So the question is, how can I make this work?

EDIT
I have figured out what the problem is: the add and more imageviews are on the event_layout as part of the CardView and not on activity_events, where the programme is looking for them. But then, I don't really know how to make the two buttons work, when they are placed on the CardView.

答:
I am assuming the on click that crashes is the more button click listener, if yes then its because you don't initialize the button more:

```<code>public MyViewHolder(@NonNull View itemView) {
    super(itemView);
    title = itemView.findViewById(R.id.event_name);
    description = itemView.findViewById(R.id.event_description);
    date = itemView.findViewById(R.id.event_date);
    location = itemView.findViewById(R.id.event_location);
    add = itemView.findViewById(R.id.add_icon);

    //here you must initialize more also
    more = itemView.findViewById(.......);

}
</code>```

Now to pass the data and get them on the other activity, I would suggest you pass the individual data:

```<code>holder.add.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(clickListener != null){
            int position = (int)v.getTag();
            clickListener.onAddClicked(position);
            final Event event = (Event)v.getTag();
            if(event!= null){
                Intent i = new Intent(mContext, EventInvitationActivity.class);
                i.putExtra("name", event.getName());
                i.putExtra("date", event.getDate());
                i.putExtra("description", event.getDescription());
                i.putExtra("location", event.getLocation());
                v.getContext().startActivity(i);
            }
        }
    }
});

//do the same for more button
</code>```

In the EventInvitationActivity:

```<code>...........

//get the data
String name = getIntent().getStringExtra("name");
String date = getIntent().getStringExtra("date");
String description = getIntent().getStringExtra("description");
String location = getIntent().getStringExtra("location");

//set the data
mName.setText(name);
mDescription.setText(description);
mLocation.setText(location);
mDate.setText(date);
.........
</code>```

Body:
I have a cardview which is presenting the upcoming events with title, date, etc. and there are two imageviews that should function as buttons: if clicked on one it should go to the participation confirming activity, if on the other on the detail activity. Both of these should also pass informations using intents(name, date, user id, token). I have followed this tutorial, because this was the closest solution to my problem but it still does not work. Whatever I change these are the errors I get:  Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference (this is given when  I call the setButtons function), or if the onclick somehow works the intents don't get passed and i get a nullpointerexception. I made sure I have used the right ids and names.
Additional information: i am using Laravel, and retrofit.
EventsActivity:

public class EventsActivity extends AppCompatActivity {
private static final String TAG = "EventsActivity";
private static final int ACTIVITY_NUM = 1;
private static final String PREFS_NAME = "LoginPrefs";
public static final String EVENT_DETAIL = "EVENT_DETAIL";
private Context mContext = EventsActivity.this;
private Event mEvent = new Event();
private String token, name;
private int id;
private EventAdapter adapter;
private RecyclerView recyclerView;
private List<Event> eventList = new ArrayList<>();
private List<Response> result;
private TextView noEvents;
private Button add, more;

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

    //Get token and id from shared preferences
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    token = settings.getString("token", "");
    id = settings.getInt("id", 0);
    Log.d(TAG, "onResponse: id " + id + "token " + token);

    noEvents = findViewById(R.id.noEvents);
    recyclerView = findViewById(R.id.event_recyclerview);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);
    recyclerView.setLayoutManager(layoutManager);
    adapter = new EventAdapter(mContext, eventList);
    recyclerView.setAdapter(adapter);

    adapter.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
        @Override
        public void onAddClicked(int position) {
           addClick(position);
        }

        @Override
        public void onMoreClicked(int position) {
            moreClick(position);
        }
    });

    loadData();
    setButtons();
}

public void addClick(int position){
    final Event event = eventList.get(position);
    Intent i = new Intent(EventsActivity.this, EventInvitationActivity.class);
    i.putExtra("name", event.getName());
    i.putExtra("name", event.getDescription());
    i.putExtra("name", event.getDate());
    i.putExtra("name", event.getLocation());
    Log.i("hello", event.getName());
    startActivity(i);
}

public void moreClick(int position){
    final Event event = eventList.get(position);
    Intent i = new Intent(EventsActivity.this, EventDetailActivity.class);
    i.putExtra("name", event.getName());
    Log.i("hello", event.getName());
    startActivity(i);
}

void setButtons() {
     add = findViewById(R.id.add_icon);
     more = findViewById(R.id.more_icon);
    Log.d(TAG, "setButtons: called");
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: add onclicklistener");
            int position = Integer.parseInt(v.getTag().toString());
            addClick(position);
        }
    });
    more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = Integer.parseInt(v.getTag().toString());
            moreClick(position);
        }
    });
}

//Listing events
private void loadData(){
    ApiEvents service = RetrofitBuilder.getRetrofitInstance().create(ApiEvents.class);
    Call<List<Event>> call = service.listEvents("Bearer" + token, id);
    call.enqueue(new Callback<List<Event>>() {
        @Override
        public void onResponse(@NonNull Call<List<Event>> call, @NonNull Response<List<Event>> response) {
            if (response.isSuccessful() && response.body()!=null) {
                Log.d(TAG, "onResponse: loadData called");
                eventList = response.body();
                adapter = new EventAdapter(mContext, eventList);
                recyclerView.setAdapter(adapter);
                adapter.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
                    @Override
                    public void onAddClicked(int position) {
                        addClick(position);
                    }

                    @Override
                    public void onMoreClicked(int position) {
                        moreClick(position);
                    }
                });
            }
            else if(response.body() == null){
                noEvents.setVisibility(View.VISIBLE);
            }
            else{
                Log.d(TAG, "onResponse: " + response.body());
            }
        }

        @Override
        public void onFailure(@NonNull Call<List<Event>> call, @NonNull Throwable t) {
            Log.d("Response", "onFailure: " + t.toString());
        }
    });
}

}

EventAdapter

public class EventAdapter extends RecyclerView.Adapter<EventAdapter.MyViewHolder> {
private Context mContext;
private List<Event> eventList;
private static final String TAG = "EventDetailActivity";
private OnItemClickListener clickListener;

public EventAdapter(Context mContext, List<Event> eventList){
    this.mContext = mContext;
    this.eventList = eventList;
}

public interface OnItemClickListener {
    void onAddClicked(int position);
    void onMoreClicked(int position);
}

public void setOnItemClickListener(OnItemClickListener clickListener) {
    this.clickListener = clickListener;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_layout, parent,
false);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
    Event event = eventList.get(position);
    holder.itemView.setTag(event);
    holder.title.setText(eventList.get(position).getName());
    holder.description.setText(eventList.get(position).getDescription());
    holder.date.setText(eventList.get(position).getDate());
    holder.location.setText(eventList.get(position).getLocation());
    holder.add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(clickListener != null){
                int position = (int)v.getTag();
                clickListener.onAddClicked(position);
                final Event event = (Event)v.getTag();
                if(event!= null){
                    Intent i = new Intent(mContext, EventInvitationActivity.class);
                    i.putExtra("EVENT_DETAIL", event);
                    v.getContext().startActivity(i);
                }
            }
        }
    });

    holder.more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(clickListener != null){
                int position = (int)v.getTag();
                clickListener.onMoreClicked(position);
                final Event event = (Event)v.getTag();
                if(event!= null){
                    Intent i = new Intent(mContext, EventDetailActivity.class);
                    i.putExtra("EVENT_DETAIL", event);
                    v.getContext().startActivity(i);
                }
            }
        }
    });

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

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView title, description, date, location;
    Button add, more;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        title = itemView.findViewById(R.id.event_name);
        description = itemView.findViewById(R.id.event_description);
        date = itemView.findViewById(R.id.event_date);
        location = itemView.findViewById(R.id.event_location);
        add = itemView.findViewById(R.id.add_icon);

    }

}

And this is the way I am trying to get the passed intents in the two activities:

//Getting resources
    mName = findViewById(R.id.eventName);
    mDescription = findViewById(R.id.description);
    mLocation = findViewById(R.id.location);
    mDate = findViewById(R.id.date);

    mEvent = Objects.requireNonNull(getIntent().getExtras()).getParcelable(EVENT_DETAIL);
   if(mEvent != null){
    mName.setText(mEvent.getName());
    mDescription.setText(mEvent.getDescription());
    mLocation.setText(mEvent.getLocation());
    mDate.setText(mEvent.getDate());
   }

And here is a button example within the cardview:

<Button
            android:id="@+id/add_icon"
            android:layout_width="80dp"
            android:layout_height="40dp"
            android:layout_below="@+id/image"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="5dp"
            android:layout_toEndOf="@id/event_description"
            android:drawableStart="@drawable/ic_add_black_24dp"
            android:scaleType="centerCrop"
            android:transitionName="img"
            android:visibility="visible"
            android:textColor="@color/colorAccent"
           />

So the question is, how can I make this work?

EDIT
I have figured out what the problem is: the add and more imageviews are on the event_layout as part of the CardView and not on activity_events, where the programme is looking for them. But then, I don't really know how to make the two buttons work, when they are placed on the CardView.

Body:
I am assuming the on click that crashes is the more button click listener, if yes then its because you don't initialize the button more:

public MyViewHolder(@NonNull View itemView) {
    super(itemView);
    title = itemView.findViewById(R.id.event_name);
    description = itemView.findViewById(R.id.event_description);
    date = itemView.findViewById(R.id.event_date);
    location = itemView.findViewById(R.id.event_location);
    add = itemView.findViewById(R.id.add_icon);

    //here you must initialize more also
    more = itemView.findViewById(.......);

}

Now to pass the data and get them on the other activity, I would suggest you pass the individual data:

holder.add.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(clickListener != null){
            int position = (int)v.getTag();
            clickListener.onAddClicked(position);
            final Event event = (Event)v.getTag();
            if(event!= null){
                Intent i = new Intent(mContext, EventInvitationActivity.class);
                i.putExtra("name", event.getName());
                i.putExtra("date", event.getDate());
                i.putExtra("description", event.getDescription());
                i.putExtra("location", event.getLocation());
                v.getContext().startActivity(i);
            }
        }
    }
});

//do the same for more button

In the EventInvitationActivity:

...........

//get the data
String name = getIntent().getStringExtra("name");
String date = getIntent().getStringExtra("date");
String description = getIntent().getStringExtra("description");
String location = getIntent().getStringExtra("location");

//set the data
mName.setText(name);
mDescription.setText(description);
mLocation.setText(location);
mDate.setText(date);
.........


来源: stackexchange

问:
Receiver 'ClassName' is a forward class and corresponding @interface may not exist
Im currently trying to find a UIPickerTable within the UIPickerView.subviews ... so i loop through and do isKindOfClass:[UIPickerTable class] .... which works.. but because the header of UIPickerTable isn't exposed i get a warning that "receiver 'UIPickerTable' is a forward class and corresponding @interface may not exist'

In order to even be able to compile I do @class UIPickerTable, and obviously it want's me to #include it.

I'm wondering if there's a way to get around seeing this warning.

TIA!

答:
I don't think that you can suppress that warning with a compiler option. You could make it go away by simply creating your own header file for the class, containing:

```<code>@interface FacesViewController : NSObject {
}
</code>```

I suppose it goes without saying that having your application depend on the internal structure of a UIKit class is probably not the best strategy. Presumably you have a good reason for mucking about inside the UIPicker...

OwnerDisplayName: dizy

ContentLicense: CC BY-SA 3.0

Body:
I don't think that you can suppress that warning with a compiler option. You could make it go away by simply creating your own header file for the class, containing:

@interface FacesViewController : NSObject {
}

I suppose it goes without saying that having your application depend on the internal structure of a UIKit class is probably not the best strategy. Presumably you have a good reason for mucking about inside the UIPicker...

OwnerDisplayName: Mark Bessey


问:
Migrating from EJB3 to Spring, Hibernate
We have a desktop based application based upon EJB3, Oracle 10 and JBoss 4. This was created around three years back. JPA entities were used for ORM and the business logic was implemented in the Stateless Session beans. The client was developed using Swing API.

Now there is a requirement to replace the previous technology with Spring, Hibernate and JBoss for the next release of application. Client will still be in Swing. The plan is to replace the entities with POJOs and put the business logic from Session Beans to Spring Beans i.e. Data Access Objects (which extend HibernateDaoSupport).

So the question is, is it possible that we completely free our application from Session Beans and move the business logic to Spring Dao? Or do we still have to keep the Session Beans? If Session Beans are completely avoided, how will the client application be able to access the business methods? Like in case of JavaEE based app, the session beans were accessible through Jndi lookup.

Any suggestion are greatly appreciated.

答:
This is completely possible, in fact these technologies aren't that different. To get immediately started, try this:

```<code><context:component-scan
        base-package="com.example.project"
        scope-resolver="org.springframework.context.annotation.Jsr330ScopeMetadataResolver">
    <context:include-filter type="annotation" expression="javax.ejb.Stateless"/>
</context:component-scan>
</code>```

Snap! Now all your SLSB are now prototype Spring beans. If some SLSBs have state (duh!), you will have to wrap them in pooling proxy and there is much more to be done. But Spring already supports majority of EE features. For instance at the beginning stick with JPA and Hibernate backend - no changes in the DAO code required, @EntityManger can be injected the same way to Spring beans.

Also in the meantime you can mix Spring and EJB - EJBs can be easily injected to Spring beans, providing nice interoperability.

UPDATE: Also, why do you want to "downgrade" from JPA do Hibernate? If your application works fine with JPA, use it in Spring application as well - and when you need Hibernate specific features, you can still use them occasionally.

Body:
This is completely possible, in fact these technologies aren't that different. To get immediately started, try this:

<context:component-scan
        base-package="com.example.project"
        scope-resolver="org.springframework.context.annotation.Jsr330ScopeMetadataResolver">
    <context:include-filter type="annotation" expression="javax.ejb.Stateless"/>
</context:component-scan>

Snap! Now all your SLSB are now prototype Spring beans. If some SLSBs have state (duh!), you will have to wrap them in pooling proxy and there is much more to be done. But Spring already supports majority of EE features. For instance at the beginning stick with JPA and Hibernate backend - no changes in the DAO code required, @EntityManger can be injected the same way to Spring beans.

Also in the meantime you can mix Spring and EJB - EJBs can be easily injected to Spring beans, providing nice interoperability.

UPDATE: Also, why do you want to "downgrade" from JPA do Hibernate? If your application works fine with JPA, use it in Spring application as well - and when you need Hibernate specific features, you can still use them occasionally.


问:
How to write a $match on a $lookup document in MongoDB
I have two MongoDB collections that look like this:

```<code>Products      Specials
----------    ----------
_id           _id
name          product_id
country       zip
price         percent_discount
              out_of_stock
</code>```

I'm using GraphQL as well so I wrote up an aggregate pipeline that returns the data in this structure:

```<code>specials {
  _id
  product {
    _id
    name
    country
    price
  }
  zip
  percent_discount
  out_of_stock
}
</code>```

This aggregate pipeline I wrote works great and looks like this:

```<code>let response = await Specials.aggregate([
    {
        $lookup: {
            from: 'products',
            localField: 'product_id',
            foreignField: '_id',
            as: 'product'
        }
    },
    {
        $unwind: '$product'
    },
    {
        $match: {
            zip: zip
        }
    }
])

return response;
</code>```

Now I'm trying to add a filter into this. The filter should match the name or country in the product collection preferably with regex. So I tried writing something like this but it's yielding over 8000 results when there should be only 2-3:

```<code>let response = await Specials.aggregate([
    {
        $match: { zip: zip }
    },
    {
        $lookup: {
            from: "products",
            let: { product_id: "$product_id" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                {
                                    _id: "$$product_id"
                                },
                                {
                                    $or: [
                                        {
                                            name: filter
                                        },
                                        {
                                            country: filter
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                }
            ],
            as: "product"
        }
    },
    {
        $unwind: "$product"
    }
])
</code>```

答:
If you're using Mongo version 4.2+ you can use $regexMatch</p>

```<code>let response = await Specials.aggregate([
    {
        $lookup: {
            from: "products",
            let: { product_id: "$product_id" },
            pipeline: [
                {
                    $match: {
                       $expr: {
                            $and: [
                                {
                                    $eq: ["$$product_id", "$_id"]
                                },
                                {
                                    $or: [
                                        {
                                            $regexMatch: { input: "$name", regex: filterRegex }
                                        },
                                        {
                                            $regexMatch: { input: "$country", regex: filterRegex }
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                }
            ],
            as: "product"
        }
    },
    {
        $unwind: "$product"
    },
    {
        $match: {
            $and: [
                {
                    zip: zip
                }
            ]
        }
    }
])

return response;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two MongoDB collections that look like this:

Products      Specials
----------    ----------
_id           _id
name          product_id
country       zip
price         percent_discount
              out_of_stock

I'm using GraphQL as well so I wrote up an aggregate pipeline that returns the data in this structure:

specials {
  _id
  product {
    _id
    name
    country
    price
  }
  zip
  percent_discount
  out_of_stock
}

This aggregate pipeline I wrote works great and looks like this:

let response = await Specials.aggregate([
    {
        $lookup: {
            from: 'products',
            localField: 'product_id',
            foreignField: '_id',
            as: 'product'
        }
    },
    {
        $unwind: '$product'
    },
    {
        $match: {
            zip: zip
        }
    }
])

return response;

Now I'm trying to add a filter into this. The filter should match the name or country in the product collection preferably with regex. So I tried writing something like this but it's yielding over 8000 results when there should be only 2-3:

let response = await Specials.aggregate([
    {
        $match: { zip: zip }
    },
    {
        $lookup: {
            from: "products",
            let: { product_id: "$product_id" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                {
                                    _id: "$$product_id"
                                },
                                {
                                    $or: [
                                        {
                                            name: filter
                                        },
                                        {
                                            country: filter
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                }
            ],
            as: "product"
        }
    },
    {
        $unwind: "$product"
    }
])

Body:
If you're using Mongo version 4.2+ you can use $regexMatch

let response = await Specials.aggregate([
    {
        $lookup: {
            from: "products",
            let: { product_id: "$product_id" },
            pipeline: [
                {
                    $match: {
                       $expr: {
                            $and: [
                                {
                                    $eq: ["$$product_id", "$_id"]
                                },
                                {
                                    $or: [
                                        {
                                            $regexMatch: { input: "$name", regex: filterRegex }
                                        },
                                        {
                                            $regexMatch: { input: "$country", regex: filterRegex }
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                }
            ],
            as: "product"
        }
    },
    {
        $unwind: "$product"
    },
    {
        $match: {
            $and: [
                {
                    zip: zip
                }
            ]
        }
    }
])

return response;


问:
angular routing not redirecting to the component
I have a problem with angular routing, I want to navigate to the component PageWidgetsComponent when I click on the button "validate"

The component.html:

```<code><div class="form-group">
  <button mat-raised-button color="primary" class="btn btn-success btn-lg btn-block" type="submit"
  (click)= "OnSubmit()" [mat-dialog-close]="true">Validate</button>
  <button mat-raised-button color="primary" class="btn btn-success btn-lg btn-block"  [mat-dialog-
  close]="true">Close</button>
</div>
</code>```

The component.ts :

```<code> OnSubmit(){
   this.router.navigate(['/widgets'])
  }
</code>```

The app-routing.module.ts:

```<code>const appRoutes: Routes = [
  { path: 'widgets', component: PageWidgetsComponent }
  ];
@NgModule({
imports: [
  RouterModule.forRoot(appRoutes)
],
exports: [RouterModule] })
export class AppRoutingModule {}
</code>```

When I click on validate button , nothing happen I don't get the html page I want but the url changed to http://localhost:4200/widgets.
I also tried routerlink but it still the same problem.
Anyone know how to fix that ? thanks for help

答:
Do you have the router-outlet tag in your AppComponent?

I prepared a small Stackblitz. Hope it helps.

https://stackblitz.com/edit/angular-ivy-gbif2p?file=src%2Fapp%2Fpages%2Fpage-widgets%2Fpage-widgets.component.html

app-routing.module.ts

```<code>import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { PageWidgetsComponent } from "./pages/page-widgets/page-widgets.component";
import { PageHomeComponent } from "./pages/page-home/page-home.component";

const appRoutes: Routes = [
  { path: "", component: PageHomeComponent },
  { path: "widgets", component: PageWidgetsComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})

export class AppRoutingModule {}
</code>```

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';
import { PageWidgetsComponent } from './pages/page-widgets/page-widgets.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }
</code>```

page-home-routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from "@angular/router";
import { PageHomeComponent } from './page-home.component';

const appRoutes: Routes = [
  { path: "", component: PageHomeComponent }
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forChild(appRoutes)
  ],
  exports: [RouterModule]
})
export class PageHomeRoutingModule { }
</code>```

page-home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-page-home',
  templateUrl: './page-home.component.html',
  styleUrls: ['./page-home.component.css']
})

export class PageHomeComponent implements OnInit {

  constructor(
    private router: Router
  ) { }

  ngOnInit() {
  }

  goTo(url: string){
   this.router.navigate([url]);
  }
}
</code>```

page-home.component.html

page-home works!

```<code><button mat-raised-button color="primary" class="btn btn-success btn-lg btn-block" type="submit"
  (click)= "goTo('/widgets')">Go To Widgets</button>
</code>```

Plus the same for the page-widgets.component/module.

Additionally you could extract the goTo() Fn to a separate service i.e.

Body:
I have a problem with angular routing, I want to navigate to the component PageWidgetsComponent when I click on the button "validate"

The component.html:

  <button mat-raised-button color="primary" class="btn btn-success btn-lg btn-block" type="submit"
  (click)= "OnSubmit()" [mat-dialog-close]="true">Validate</button>
  <button mat-raised-button color="primary" class="btn btn-success btn-lg btn-block"  [mat-dialog-
  close]="true">Close</button>

The component.ts :

 OnSubmit(){
   this.router.navigate(['/widgets'])
  }

The app-routing.module.ts:

const appRoutes: Routes = [
  { path: 'widgets', component: PageWidgetsComponent }
  ];
@NgModule({
imports: [
  RouterModule.forRoot(appRoutes)
],
exports: [RouterModule] })
export class AppRoutingModule {}

When I click on validate button , nothing happen I don't get the html page I want but the url changed to http://localhost:4200/widgets.
I also tried routerlink but it still the same problem.
Anyone know how to fix that ? thanks for help

Body:
Do you have the router-outlet tag in your AppComponent?

I prepared a small Stackblitz. Hope it helps.

https://stackblitz.com/edit/angular-ivy-gbif2p?file=src%2Fapp%2Fpages%2Fpage-widgets%2Fpage-widgets.component.html

app-routing.module.ts

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { PageWidgetsComponent } from "./pages/page-widgets/page-widgets.component";
import { PageHomeComponent } from "./pages/page-home/page-home.component";

const appRoutes: Routes = [
  { path: "", component: PageHomeComponent },
  { path: "widgets", component: PageWidgetsComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})

export class AppRoutingModule {}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';
import { PageWidgetsComponent } from './pages/page-widgets/page-widgets.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }

page-home-routing.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from "@angular/router";
import { PageHomeComponent } from './page-home.component';

const appRoutes: Routes = [
  { path: "", component: PageHomeComponent }
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forChild(appRoutes)
  ],
  exports: [RouterModule]
})
export class PageHomeRoutingModule { }

page-home.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-page-home',
  templateUrl: './page-home.component.html',
  styleUrls: ['./page-home.component.css']
})

export class PageHomeComponent implements OnInit {

  constructor(
    private router: Router
  ) { }

  ngOnInit() {
  }

  goTo(url: string){
   this.router.navigate([url]);
  }
}

page-home.component.html

page-home works!

<button mat-raised-button color="primary" class="btn btn-success btn-lg btn-block" type="submit"
  (click)= "goTo('/widgets')">Go To Widgets</button>

Plus the same for the page-widgets.component/module.

Additionally you could extract the goTo() Fn to a separate service i.e.


问:
How can I get top 5 values from json which stored in one column?
I have table name log_requests where I store json array into request column, which is like following

{"game_id":"1","score":"820",}

game_ids are 1 to 20, now I want to know which game_id is used many time. To getting count of a game_id I am using following query which is working fine

SELECT * FROM log_requests WHERE json_contains(request, '{"game_id" : "1"}')

But how can I get top 5 game_id from this table?

答:
"I shoot myself in a foot, how to create a crutch?"

Do not store relational data in JSON fields.

Period.

Create a sensible table structure, store your games in a separate table and you will never have a problem like this, having your data from a simple conventional SQL

```<code>select game_id, count(1) cnt from games group by game_id order by cnt desc limit 5
</code>```

Body:
"I shoot myself in a foot, how to create a crutch?"

Do not store relational data in JSON fields.

Period.

Create a sensible table structure, store your games in a separate table and you will never have a problem like this, having your data from a simple conventional SQL

select game_id, count(1) cnt from games group by game_id order by cnt desc limit 5


问:
Stuck on how to find QueryDSL predicate in spring data app
I have a problem in querying some data, I will explain my problem briefly and set an example for clarification

I use Spring data, QueryDSL and MySQL.

I want to query like this in queryDSL method. A specific example is just a simple example to give an idea.

Say for example, there are two tables Employee and Certificate. Relation between two is ONE (Employee) to MANY (Certificate)

Following are tables

```<code>Employee (id, first_name, last_name);
Certificate (id, name, date, fk_emp);
</code>```

Following are the entities,

```<code>@Entity
@Table(name = "EMPLOYEE")
class Employee {
  @Id
  @Column(name = "ID")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name = "FIRST_NAME")
  private String firstName;

  @Column(name = "LAST_NAME")
  private String lastName;

  @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
  private List<Certificate> certificates = new ArrayList<>();
}

@Entity
@Table(name = "CERTIFICATE")
class Certificate {
  @Id
  @Column(name = "ID")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name = "CERTIFICATE_NAME")
  private String certificateName;

  @Column(name = "DATE")
  private Date date;

  @ManyToOne
  @JoinColumn(name = "REF_EMPLOYEE")
  private Employee employee;
}
</code>```

What should the QueryDSL predicate be for
Returning all employees with name contains (in first_name and last_name) and from that result whose certification between date 22-12-2014 to 22-12-2015

At the same time, I want to obtain all employees who do not have any certificates

example of results:

```<code>+----+--------------------+---------------------+--------+
| id | name               | date                | fk_emp |
+----+--------------------+---------------------+--------+
|  1 | FirstName LastName | 2014-02-01 00:00:00 |  11111 |
+----+--------------------+---------------------+--------+
|  2 | FirstName LastName | 2014-03-01 00:00:00 |  null  |
+----+--------------------+---------------------+--------+
|  3 | FirstName LastName | 2014-04-01 00:00:00 |        |
+----+--------------------+---------------------+--------+
|  5 | FirstName LastName | 2014-05-01 00:00:00 |        |
+----+--------------------+---------------------+--------+
| 12 | FirstName LastName | 2014-06-01 00:00:00 |  25555 |
+----+--------------------+---------------------+--------+
| 13 | FirstName LastName | 2014-07-01 00:00:00 |  78888 |
+----+--------------------+---------------------+--------+
| 16 | FirstName LastName | 2014-08-01 00:00:00 |  null  |
+----+--------------------+---------------------+--------+
</code>```

Thank you

答:
Native JPQL Query:

```<code>SELECT * FROM EMPLOYEE A
LEFT JOIN CERTIFICATE B ON A.ID = B.REF_EMPLOYEE AND DATE BETWEEN CAST('2014-12-22' AS DATE) AND CAST('2015-12-22' AS DATE);
</code>```

Querydsl join variant:

```<code>query.from(employee)
    .leftJoin(employee.certificates, certificate)
    .on(certificate.date.between('from_date', 'to_date'))
    .list(employee);
</code>```

Note: Date format can be different here and please change according to your need

Body:
I have a problem in querying some data, I will explain my problem briefly and set an example for clarification

I use Spring data, QueryDSL and MySQL.

I want to query like this in queryDSL method. A specific example is just a simple example to give an idea.

Say for example, there are two tables Employee and Certificate. Relation between two is ONE (Employee) to MANY (Certificate)

Following are tables

Employee (id, first_name, last_name);
Certificate (id, name, date, fk_emp);

Following are the entities,

@Entity
@Table(name = "EMPLOYEE")
class Employee {
  @Id
  @Column(name = "ID")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name = "FIRST_NAME")
  private String firstName;

  @Column(name = "LAST_NAME")
  private String lastName;

  @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
  private List<Certificate> certificates = new ArrayList<>();
}

@Entity
@Table(name = "CERTIFICATE")
class Certificate {
  @Id
  @Column(name = "ID")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name = "CERTIFICATE_NAME")
  private String certificateName;

  @Column(name = "DATE")
  private Date date;

  @ManyToOne
  @JoinColumn(name = "REF_EMPLOYEE")
  private Employee employee;
}

What should the QueryDSL predicate be for
Returning all employees with name contains (in first_name and last_name) and from that result whose certification between date 22-12-2014 to 22-12-2015

At the same time, I want to obtain all employees who do not have any certificates

example of results:

+----+--------------------+---------------------+--------+
| id | name               | date                | fk_emp |
+----+--------------------+---------------------+--------+
|  1 | FirstName LastName | 2014-02-01 00:00:00 |  11111 |
+----+--------------------+---------------------+--------+
|  2 | FirstName LastName | 2014-03-01 00:00:00 |  null  |
+----+--------------------+---------------------+--------+
|  3 | FirstName LastName | 2014-04-01 00:00:00 |        |
+----+--------------------+---------------------+--------+
|  5 | FirstName LastName | 2014-05-01 00:00:00 |        |
+----+--------------------+---------------------+--------+
| 12 | FirstName LastName | 2014-06-01 00:00:00 |  25555 |
+----+--------------------+---------------------+--------+
| 13 | FirstName LastName | 2014-07-01 00:00:00 |  78888 |
+----+--------------------+---------------------+--------+
| 16 | FirstName LastName | 2014-08-01 00:00:00 |  null  |
+----+--------------------+---------------------+--------+

Thank you

Body:
Native JPQL Query:

SELECT * FROM EMPLOYEE A
LEFT JOIN CERTIFICATE B ON A.ID = B.REF_EMPLOYEE AND DATE BETWEEN CAST('2014-12-22' AS DATE) AND CAST('2015-12-22' AS DATE);

Querydsl join variant:

query.from(employee)
    .leftJoin(employee.certificates, certificate)
    .on(certificate.date.between('from_date', 'to_date'))
    .list(employee);

Note: Date format can be different here and please change according to your need


问:
Time difference query using MS SQL
I'm trying to take out difference between two times, first and second time using AM , PM
I've columns:

```<code>FirstTime    SecondTime
10:14:42 PM  1:05:25 AM.
</code>```

When i'm using DateDiff function it return wrong value and also i want access this in whole table not for single row and max is required on particular table

I've tried following queries:

```<code>select DATEDIFF(MINUTE, first_time, second_time) AS 'Duration'  FROM tbl_weight

SELECT max (DATEDIFF(MINUTE, first_time, second_time)) AS 'Duration' , sr_no
    FROM tbl_weight where first_weight != '0' and  second_weight != '0' group by sr_no  ;
</code>```

but in both it return wrong value.

答:
You can use a CASE expression to reverse the DATEDIFF expression when the second time is before the first. This will provide the expected results when the second time is the following day.

```<code>SELECT
    CASE WHEN first_time < second_time
        THEN DATEDIFF(MINUTE, first_time, second_time)
    ELSE
        DATEDIFF(MINUTE, second_time, first_time)
    END AS Duration
FROM tbl_weight;
</code>```

Title: Time difference query using MS SQL

Body:
I'm trying to take out difference between two times, first and second time using AM , PM
I've columns:

FirstTime    SecondTime
10:14:42 PM  1:05:25 AM.

When i'm using DateDiff function it return wrong value and also i want access this in whole table not for single row and max is required on particular table

I've tried following queries:

select DATEDIFF(MINUTE, first_time, second_time) AS 'Duration'  FROM tbl_weight

SELECT max (DATEDIFF(MINUTE, first_time, second_time)) AS 'Duration' , sr_no
    FROM tbl_weight where first_weight != '0' and  second_weight != '0' group by sr_no  ;

but in both it return wrong value.

Body:
You can use a CASE expression to reverse the DATEDIFF expression when the second time is before the first. This will provide the expected results when the second time is the following day.

SELECT
    CASE WHEN first_time < second_time
        THEN DATEDIFF(MINUTE, first_time, second_time)
    ELSE
        DATEDIFF(MINUTE, second_time, first_time)
    END AS Duration
FROM tbl_weight;


问:
Android giving error while accessing json data from the internet
I am a beginner, building a goofy app that uses an online API. I uploaded the .json file to GitHub, from where my app accesses it and gives the output. However, it always runs the statements for onErrorResponse. Am I doing something wrong?
Here's the code for MainActivity:

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

import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    RequestQueue requestQueue;
    Button search;
    EditText input;
    TextView word;
    TextView meaning;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        search = findViewById(R.id.button_getMeaning);
        input = findViewById(R.id.editText_input);
        word = findViewById(R.id.textView_word);
        meaning = findViewById(R.id.textView_meaning);
        requestQueue = Volley.newRequestQueue(this);

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String term = input.getText().toString().toLowerCase();
                String displayInput = term.toUpperCase() + ":";
                word.setText(displayInput);

                JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, "https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json", null,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                try {
                                    String definition = response.getString(term);
                                    meaning.setText(definition);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    meaning.setText("Sorry, this word doesn't exist in the boner database.");
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, "Connection error, please check internet connection.", Toast.LENGTH_SHORT).show();
                    }
                });
                requestQueue.add(jsonObjectRequest1);
            }
        });

    }
}
</code>```

The project uses Volley and I have added Internet permission in the manifest.

Edit: here's the .json :
https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json

答:
The json url you have posted is a link to someone's github page with the json, but not the json itself. Whats most likely happening is volley is downloading the HTML page in its entirety which contains the json. Its then complaining that its not correctly formatted json.

If you want that json directly you need to find a way to host it somewhere. For example github has an api that you can access json files like this https://api.github.com/users/mralexgray/repos

For local testing you could always copy it into a local json file and import into the res/raw of your app and reference it from there.

Body:
I am a beginner, building a goofy app that uses an online API. I uploaded the .json file to GitHub, from where my app accesses it and gives the output. However, it always runs the statements for onErrorResponse. Am I doing something wrong?
Here's the code for MainActivity:

package com.example.jsonparsing;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    RequestQueue requestQueue;
    Button search;
    EditText input;
    TextView word;
    TextView meaning;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        search = findViewById(R.id.button_getMeaning);
        input = findViewById(R.id.editText_input);
        word = findViewById(R.id.textView_word);
        meaning = findViewById(R.id.textView_meaning);
        requestQueue = Volley.newRequestQueue(this);

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String term = input.getText().toString().toLowerCase();
                String displayInput = term.toUpperCase() + ":";
                word.setText(displayInput);

                JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, "https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json", null,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                try {
                                    String definition = response.getString(term);
                                    meaning.setText(definition);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    meaning.setText("Sorry, this word doesn't exist in the boner database.");
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, "Connection error, please check internet connection.", Toast.LENGTH_SHORT).show();
                    }
                });
                requestQueue.add(jsonObjectRequest1);
            }
        });

    }
}

The project uses Volley and I have added Internet permission in the manifest.

Edit: here's the .json :
https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json


问:
Cannot do git checkout because of file errors and unable to git stash
I am trying to do a git checkout of a branch:

```<code>$ git checkout remotes/origin/QuestionFormJN
error: Your local changes to the following files would be overwritten by
checkout:
    ICompute-api/.vs/ICompute-api/v15/Server/sqlite3/storage.ide-shm
    ICompute-api/.vs/ICompute-api/v15/Server/sqlite3/storage.ide-wal
Please commit your changes or stash them before you switch branches.
Aborting
</code>```

Then I try to do a git stash and get this error:

```<code>$ git stash
Saved working directory and index state WIP on master: e52c54c fixed login
Unlink of file 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-shm' failed. Should I try again? (y/n) y
Unlink of file 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-shm' failed. Should I try again? (y/n) n
error: unable to unlink old 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-shm': Invalid argument
Unlink of file 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-wal' failed. Should I try again? (y/n) n
error: unable to unlink old 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-wal': Invalid argument
fatal: Could not reset index file to revision 'HEAD'.
</code>```

What am I doing wrong?

答: I was using Windows 10 and faced this same issue. After closing Visual Studio, it works fine.</p>

Body:
I am trying to do a git checkout of a branch:

$ git checkout remotes/origin/QuestionFormJN
error: Your local changes to the following files would be overwritten by
checkout:
    ICompute-api/.vs/ICompute-api/v15/Server/sqlite3/storage.ide-shm
    ICompute-api/.vs/ICompute-api/v15/Server/sqlite3/storage.ide-wal
Please commit your changes or stash them before you switch branches.
Aborting

Then I try to do a git stash and get this error:

$ git stash
Saved working directory and index state WIP on master: e52c54c fixed login
Unlink of file 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-shm' failed. Should I try again? (y/n) y
Unlink of file 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-shm' failed. Should I try again? (y/n) n
error: unable to unlink old 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-shm': Invalid argument
Unlink of file 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-wal' failed. Should I try again? (y/n) n
error: unable to unlink old 'ICompute-api/.vs/ICompute-
api/v15/Server/sqlite3/storage.ide-wal': Invalid argument
fatal: Could not reset index file to revision 'HEAD'.

What am I doing wrong?


问:
Passing variable Timestamp with JSON in POSTMAN
I have a field named acceptance_time in the database:

And I want to add new order using the POST method in postman.
This is my code in java:

```<code> @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss.SS", timezone="Europe/Berlin")
    @Column
    private Timestamp acceptanceTime;
</code>```

When I send the request from the postman, I am getting this error.

It says:Cannot parse date \"2018-09-13 18:41:02.36\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ',

How do I go about fixing this?

答:
I had also faced this issue sometime back. In my case, upgrading the Jackson version to 2.9.2 had fixed the issue. In your Pom.xml, look for the Jackson dependency and change the version to 2.9.2.

```<code>    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>
</code>```

This might help, please check once.

Body:
I have a field named acceptance_time in the database:

And I want to add new order using the POST method in postman.
This is my code in java:

 @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss.SS", timezone="Europe/Berlin")
    @Column
    private Timestamp acceptanceTime;

When I send the request from the postman, I am getting this error.

It says:Cannot parse date \"2018-09-13 18:41:02.36\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ',

How do I go about fixing this?

Body:
I had also faced this issue sometime back. In my case, upgrading the Jackson version to 2.9.2 had fixed the issue. In your Pom.xml, look for the Jackson dependency and change the version to 2.9.2.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>

This might help, please check once.


问:
Python regex to find "document" word in a given string in forward direction and replace by empty string
If the word "document" can be produced by removing characters from a given string, the letters spelling "document" are to be removed from the string. If letters from the resulting string can be removed to leave the string "document", the letters spelling "document" in that string are removed. This continues until letters cannot be removed to leave "document", at which time the final string is to be returned.

For example, if the string were:

```<code>documdocumententer
     ^^^^^^^^
</code>```

"document" can be formed by removing "docum" from the beginning and "enter" at the "end", so "document" in the middle is removed, leaving

```<code>documenter
^^^^^^^^
</code>```

The process would then be repeated to leave

```<code>er
</code>```

As "er" does not contain "document", "er" would be returned.

Similarly, if the string were:

```<code>adbocucdmefgnhtj
 ^ ^^^  ^^  ^ ^
</code>```

the letters spelling "document" would be removed to leave:

```<code>abcdfghj
</code>```

This string would be returned because it does not contain "document".

Examples

doconeument is converted to one

documdocumentent is converted to an empty string

documentone is converted to one

pydocdbument is converted to pydb

documentdocument is converted to an empty string

How can I obtain the string of interest from a given string (for the specific word "document" only).

i tried this query by python for loop, but i didn't get idea how to do with only regex
my code is below

```<code>import re
def fun1(text):
    print('original string:', text)
    pattern = r"((d|D).*o.*c.*u.*m.*e.*n.*t){1,}"
    result = re.sub(pattern, '', text)
    if len(result) == len(text):
        print('return original string because it does not contain "document" word forward direction:')
        return text

    # if word is containing "document" in forward direction

    temp = []   # for storing letter and its index

    # find each letter and index in "document" word
    search_str = 'document'
    for index in range(len(search_str)):
        # if it is a last letter in "document" that is t
        if index == len(search_str)-1:
            current_letter = search_str[index]
            pattern = r'.*n.*t'

        else:
            next_letter = search_str[index + 1]
            current_letter = search_str[index]
            pattern = rf".*{current_letter}.*{next_letter}"

        result = re.match(pattern, text)
        a, b = result.span()
        if temp:
            # value of last dict in temp list
            val = list(temp[-1].values())[0]
            current_letter = val + text[val:].index(current_letter)
        else:
            # first time when temp list is empty
            current_letter = text[a:b].rindex(current_letter)

        temp.append({search_str[index]: current_letter})

    # now using temp list we remove "document" word at specific index
    text = list(text)

    # create a list with index decending order to remove from text
    remove_index_list = [list(i.values())[0] for i in temp]
    remove_index_list.sort(reverse=True)

    for j in remove_index_list:
        text.pop(j)

    final_txt = ''.join(text)
    # to check if text containing or not one more "document" word
    pattern = r"((d|D).*o.*c.*u.*m.*e.*n.*t){1,}"
    result = re.findall(pattern, final_txt)
    if result:
        print('The word again containing "document" in it')
        final_txt = fun1(final_txt)
    return final_txt
print('final_output:', fun1('doconeument'))
</code>```

答:
If the given string fails to match the regular expression:

```<code>r'^([a-z]*)d([a-z]*)o([a-z]*)c([a-z]*)u([a-z]*)m([a-z]*)e([a-z]*)n([a-z]*)t([a-z]*)$'
</code>```

the string is returned. If the regex matches the string, the string:

```<code>"\1\2\3\4\5\6\7\8\9"
</code>```

is formed and an attempt is made to match that string with the regex. This process is repeated until there is no match, at which time the last string tested is returned. Note that each string thus produced contains 8 characters fewer than the preceding string.

Demo, step 1

Demo, step 2

If the regex matches the string, capture group 1 will contain the substring that precedes "d" in "document", capture group 2 will contain the substring that is between "d" and "o", and so on, with capture group 9 containing the substring that follows "t". Some or all of these substrings may be empty.

I will leave it to the OP to produce the Python code needed to implement this algorithm.

Body:
If the word "document" can be produced by removing characters from a given string, the letters spelling "document" are to be removed from the string. If letters from the resulting string can be removed to leave the string "document", the letters spelling "document" in that string are removed. This continues until letters cannot be removed to leave "document", at which time the final string is to be returned.

For example, if the string were:

documdocumententer
     ^^^^^^^^

"document" can be formed by removing "docum" from the beginning and "enter" at the "end", so "document" in the middle is removed, leaving

documenter
^^^^^^^^

The process would then be repeated to leave

er

As "er" does not contain "document", "er" would be returned.

Similarly, if the string were:

adbocucdmefgnhtj
 ^ ^^^  ^^  ^ ^

the letters spelling "document" would be removed to leave:

abcdfghj

This string would be returned because it does not contain "document".

Examples

doconeument is converted to one

documdocumentent is converted to an empty string

documentone is converted to one

pydocdbument is converted to pydb

documentdocument is converted to an empty string

How can I obtain the string of interest from a given string (for the specific word "document" only).

i tried this query by python for loop, but i didn't get idea how to do with only regex
my code is below

import re
def fun1(text):
    print('original string:', text)
    pattern = r"((d|D).*o.*c.*u.*m.*e.*n.*t){1,}"
    result = re.sub(pattern, '', text)
    if len(result) == len(text):
        print('return original string because it does not contain "document" word forward direction:')
        return text

    # if word is containing "document" in forward direction

    temp = []   # for storing letter and its index

    # find each letter and index in "document" word
    search_str = 'document'
    for index in range(len(search_str)):
        # if it is a last letter in "document" that is t
        if index == len(search_str)-1:
            current_letter = search_str[index]
            pattern = r'.*n.*t'

        else:
            next_letter = search_str[index + 1]
            current_letter = search_str[index]
            pattern = rf".*{current_letter}.*{next_letter}"

        result = re.match(pattern, text)
        a, b = result.span()
        if temp:
            # value of last dict in temp list
            val = list(temp[-1].values())[0]
            current_letter = val + text[val:].index(current_letter)
        else:
            # first time when temp list is empty
            current_letter = text[a:b].rindex(current_letter)

        temp.append({search_str[index]: current_letter})

    # now using temp list we remove "document" word at specific index
    text = list(text)

    # create a list with index decending order to remove from text
    remove_index_list = [list(i.values())[0] for i in temp]
    remove_index_list.sort(reverse=True)

    for j in remove_index_list:
        text.pop(j)

    final_txt = ''.join(text)
    # to check if text containing or not one more "document" word
    pattern = r"((d|D).*o.*c.*u.*m.*e.*n.*t){1,}"
    result = re.findall(pattern, final_txt)
    if result:
        print('The word again containing "document" in it')
        final_txt = fun1(final_txt)
    return final_txt
print('final_output:', fun1('doconeument'))

Body:
If the given string fails to match the regular expression:

r'^([a-z]*)d([a-z]*)o([a-z]*)c([a-z]*)u([a-z]*)m([a-z]*)e([a-z]*)n([a-z]*)t([a-z]*)$'

the string is returned. If the regex matches the string, the string:

"\1\2\3\4\5\6\7\8\9"

is formed and an attempt is made to match that string with the regex. This process is repeated until there is no match, at which time the last string tested is returned. Note that each string thus produced contains 8 characters fewer than the preceding string.

Demo, step 1

Demo, step 2

If the regex matches the string, capture group 1 will contain the substring that precedes "d" in "document", capture group 2 will contain the substring that is between "d" and "o", and so on, with capture group 9 containing the substring that follows "t". Some or all of these substrings may be empty.

I will leave it to the OP to produce the Python code needed to implement this algorithm.


问:
Chrome not giving expected output of bootstrap code
I am using bootstrap. I have added all the necessary references to the bootstrap library but it still will not work in google chrome. Here's a screenshot of the out put I'm getting:

I am using a jumbotron on the "This is a Jumbotron" text but it is not working. My HTML code is as follows:

     <!DOCTYPE html>

            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

            <title>Hello, world!</title>

Hello, world!

        This is a Jumbotron.

        ```

As you can see the references are included in this code but it still won't work in chrome. Please Note that I have copied this code from bootstrap.com starter template. So is there, something wrong with my browser? Please answer this question if you know the answer. Thanks in advance. There is no CSS for this code. And also I use Visual Studio Code as my code editor.

答: I found the answer: It wasn't about the code editor but I had installed an extension in Chrome that wouldn't let me access the script links (via script websites). Once I removed the extension (or you could try disabling it) bootstrap started to work again. This answer is to anyone out there facing the same problems as I have. </p>

Body:
I am using bootstrap. I have added all the necessary references to the bootstrap library but it still will not work in google chrome. Here's a screenshot of the out put I'm getting:

I am using a jumbotron on the "This is a Jumbotron" text but it is not working. My HTML code is as follows:

     <!DOCTYPE html>

            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

            <title>Hello, world!</title>

Hello, world!

        This is a Jumbotron.

As you can see the references are included in this code but it still won't work in chrome. Please Note that I have copied this code from bootstrap.com starter template. So is there, something wrong with my browser? Please answer this question if you know the answer. Thanks in advance. There is no CSS for this code. And also I use Visual Studio Code as my code editor.


问:
Changing CSS properties using jQuery for a markup and different CSS files
I've a HTML markup and I've several CSS files with different properties assigned for the HTML elements which will act as the theme of the markup. Say the Markup is something like

```<code><div id=main>
    <div>{More HTML elements, divs, spans etc}</div>
    <div>{More HTML elements, divs, spans etc}</div>
</div>
</code>```

And the css is like

```<code>/*first.css*/
#main{
    someProperty: values;
}

#main div, #main ul li {
    someProperty: values;
}
</code>```

Another css file

```<code>/*second.css*/
#main{
    someProperty: some other values;
}

#main div, #main ul li {
    someProperty: some other values;
}
</code>```

There are more css files with different properties and values.

What I want to do is, at the click of a button, I want to change the CSS of the markup without changing the markup. So it will be something like

```<code>$('.btn').click(function(){
    var file = $(this).attr('id');
    //remove the previous css file
    //add the new css file (filename is the js var file+'.css')
});
</code>```

I cannot keep doing $('#someId').css({ /* properties */}); as there are many properties in the CSS file.

So how do I best handle this??

答:
You can easily remove link elements from the head with jQuery, they are treated as any other HTML element.

You can remove a certain CSS file from the document using:

```<code>$('link[href="fos.css"]').remove();
</code>```

And then you can add another into the head:

```<code>var newCss='fos2.css';
$('head').append('<link rel="stylesheet" type="text/css" href="'+newCss+'">');
</code>```

or if you want to play nice:

```<code>var newCss='fos2.css';
$('<link>')
    .attr({
        rel: 'stylesheet',
        type: 'text/css',
        href: newCss
    })
    .appendTo('head');
</code>```

I've created a simple jsFiddle test case for you.

Body:
I've a HTML markup and I've several CSS files with different properties assigned for the HTML elements which will act as the theme of the markup. Say the Markup is something like

{More HTML elements, divs, spans etc}

{More HTML elements, divs, spans etc}

And the css is like

/*first.css*/
#main{
    someProperty: values;
}

#main div, #main ul li {
    someProperty: values;
}

Another css file

/*second.css*/
#main{
    someProperty: some other values;
}

#main div, #main ul li {
    someProperty: some other values;
}

There are more css files with different properties and values.

What I want to do is, at the click of a button, I want to change the CSS of the markup without changing the markup. So it will be something like

$('.btn').click(function(){
    var file = $(this).attr('id');
    //remove the previous css file
    //add the new css file (filename is the js var file+'.css')
});

I cannot keep doing $('#someId').css({ /* properties */}); as there are many properties in the CSS file.

So how do I best handle this??

Body:
You can easily remove link elements from the head with jQuery, they are treated as any other HTML element.

You can remove a certain CSS file from the document using:

$('link[href="fos.css"]').remove();

And then you can add another into the head:

var newCss='fos2.css';
$('head').append('<link rel="stylesheet" type="text/css" href="'+newCss+'">');

or if you want to play nice:

var newCss='fos2.css';
$('<link>')
    .attr({
        rel: 'stylesheet',
        type: 'text/css',
        href: newCss
    })
    .appendTo('head');

I've created a simple jsFiddle test case for you.


问:
How to change the shape of Chips component in android?
When I added ChipGroup and Chips to XML, first it gave me rendering issue which caused activity crash.
I solved it by changing the support library version in the gradle.app from implementation 'com.google.android.material:material:1.2.0-alpha05' to alpha02 & changed AppTheme to "Theme.MaterialComponents.Light.DarkActionBar".

**Now the issue is that in the design section of androidStudio shape of the chip is default i.e. rounded but on emulator & actual device it is diamond shaped.
I tried the app:chipCornerRadius="5dp" property but it did not gave the desired result.

How to change the shape of the chip to rounded/default?**

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.our_team.OurTeamActivity">

    <HorizontalScrollView
        android:id="@+id/horizontalScrollView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:scrollbars="none"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.chip.ChipGroup
            android:id="@+id/chipGroup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="36dp"
            app:singleLine="true"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <com.google.android.material.chip.Chip
                android:id="@+id/chip4"
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipCornerRadius="5dp"
                android:layout_marginStart="5dp"
                android:layout_marginEnd="5dp"
                android:text="One Choice"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption" />

            <com.google.android.material.chip.Chip
                android:id="@+id/chip5"
                style="@style/Widget.MaterialComponents.Chip.Action"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:layout_marginEnd="5dp"
                android:text="Two Action"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption" />

            <com.google.android.material.chip.Chip
                android:id="@+id/chip6"
                style="@style/Widget.MaterialComponents.Chip.Entry"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:layout_marginEnd="5dp"
                android:text="Three Entry"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption" />

            <com.google.android.material.chip.Chip
                android:id="@+id/chip7"
                style="@style/Widget.MaterialComponents.Chip.Filter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:layout_marginEnd="5dp"
                android:text="Four Filter"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption" />
        </com.google.android.material.chip.ChipGroup>

    </HorizontalScrollView>

</code>```

答:
In the Chip the default value of the corner is defined in the style by the shapeAppearanceOverlay attribute:

```<code><item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MaterialComponents.Chip</item>
</code>```

with:

```<code>  <style name="ShapeAppearanceOverlay.MaterialComponents.Chip" parent="">
    <item name="cornerSize">50%</item>
  </style>
</code>```

Just remove in your layout app:chipCornerRadius="5dp".

Body:
When I added ChipGroup and Chips to XML, first it gave me rendering issue which caused activity crash.
I solved it by changing the support library version in the gradle.app from implementation 'com.google.android.material:material:1.2.0-alpha05' to alpha02 & changed AppTheme to "Theme.MaterialComponents.Light.DarkActionBar".

**Now the issue is that in the design section of androidStudio shape of the chip is default i.e. rounded but on emulator & actual device it is diamond shaped.
I tried the app:chipCornerRadius="5dp" property but it did not gave the desired result.

How to change the shape of the chip to rounded/default?**

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.our_team.OurTeamActivity">

    <HorizontalScrollView
        android:id="@+id/horizontalScrollView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:scrollbars="none"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.chip.ChipGroup
            android:id="@+id/chipGroup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="36dp"
            app:singleLine="true"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <com.google.android.material.chip.Chip
                android:id="@+id/chip4"
                style="@style/Widget.MaterialComponents.Chip.Choice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:chipCornerRadius="5dp"
                android:layout_marginStart="5dp"
                android:layout_marginEnd="5dp"
                android:text="One Choice"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption" />

            <com.google.android.material.chip.Chip
                android:id="@+id/chip5"
                style="@style/Widget.MaterialComponents.Chip.Action"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:layout_marginEnd="5dp"
                android:text="Two Action"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption" />

            <com.google.android.material.chip.Chip
                android:id="@+id/chip6"
                style="@style/Widget.MaterialComponents.Chip.Entry"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:layout_marginEnd="5dp"
                android:text="Three Entry"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption" />

            <com.google.android.material.chip.Chip
                android:id="@+id/chip7"
                style="@style/Widget.MaterialComponents.Chip.Filter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:layout_marginEnd="5dp"
                android:text="Four Filter"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption" />
        </com.google.android.material.chip.ChipGroup>

    </HorizontalScrollView>

Body:
In the Chip the default value of the corner is defined in the style by the shapeAppearanceOverlay attribute:

<item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MaterialComponents.Chip</item>

with:

  <style name="ShapeAppearanceOverlay.MaterialComponents.Chip" parent="">
    <item name="cornerSize">50%</item>
  </style>

Just remove in your layout app:chipCornerRadius="5dp".


问:
How to treat ALL C# 8 nullable reference warnings as errors?
Using Visual Studio 2019 v16.3.2 with a .NET Core 3.0 project set to C# 8 and nullable reference types enabled.

<PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <Nullable>enable</Nullable>
</PropertyGroup>

```
<p>If I set it to treat all warnings as errors:</p>
<p><img src="https://i.stack.imgur.com/zneFB.png" alt="warnings as errors radio button selected" /></p>
<pre class="lang-xml prettyprint-override"><code><TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsAsErrors />
</code>```

It reports other warnings as errors. For example, CS0168 The variable 'x' is declared but never used is reported as an error. But all the nullable reference warnings are still reported as warnings. For example, CS8600 Converting null literal or possible null value to non-nullable type. is still reported as a warning.

How do I treat all nullable reference warnings as errors?

Note: even setting CS8600 specifically to be treated as an error doesn't cause it to be reported as an error. If that worked, it still wouldn't help with treating them all as errors because there are so many.

Edit: setting specific warnings to be treated as errors puts <WarningsAsErrors>CS8600;CS8602;CS8603</WarningsAsErrors> in the csproj and doesn't work.

答:
It is now possible to treat all nullable-related warnings as errors without explicitly specifying them all. To achieve this, you have to set <WarningsAsErrors>Nullable</WarningsAsErrors> in your *.csproj file [source].

Full example:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <Nullable>enable</Nullable>
    <WarningsAsErrors>Nullable</WarningsAsErrors>
  </PropertyGroup>
</Project>

```

Body:
Using Visual Studio 2019 v16.3.2 with a .NET Core 3.0 project set to C# 8 and nullable reference types enabled.

<PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <Nullable>enable</Nullable>
</PropertyGroup>

If I set it to treat all warnings as errors:

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsAsErrors />

It reports other warnings as errors. For example, CS0168 The variable 'x' is declared but never used is reported as an error. But all the nullable reference warnings are still reported as warnings. For example, CS8600 Converting null literal or possible null value to non-nullable type. is still reported as a warning.

How do I treat all nullable reference warnings as errors?

Note: even setting CS8600 specifically to be treated as an error doesn't cause it to be reported as an error. If that worked, it still wouldn't help with treating them all as errors because there are so many.

Edit: setting specific warnings to be treated as errors puts <WarningsAsErrors>CS8600;CS8602;CS8603</WarningsAsErrors> in the csproj and doesn't work.


问:
How to add text mark to a Vega Lite grouped bar chart
I wasn't able to add a text mark layer to a grouped bar chart, I've tried editing the Vega Lite example to add sum label on top of every bar:

https://vega.github.io/editor/#/examples/vega-lite/bar_grouped

But what happens is either "layer" property wasn't accepted, or bars get squashed into one bar. How to make this happen?

答:
When you want to add a text mark to a faceted chart, the pattern to use is a Layered view within a Facet Operator.

For example (vega editor):

```<code>{
  "data": {"url": "data/population.json"},
  "transform": [
    {"filter": "datum.year == 2000"},
    {"calculate": "datum.sex == 2 ? 'Female' : 'Male'", "as": "gender"}
  ],
  "width": {"step": 12},
  "facet": {"field": "age", "type": "ordinal"},
  "spec": {
    "encoding": {
      "y": {
        "aggregate": "sum",
        "field": "people",
        "type": "quantitative",
        "axis": {"title": "population", "grid": false}
      },
      "x": {"field": "gender", "type": "nominal", "axis": {"title": ""}}
    },
    "layer": [
      {
        "mark": "bar",
        "encoding": {
          "color": {
            "field": "gender",
            "type": "nominal",
            "scale": {"range": ["#675193", "#ca8861"]}
          }
        }
      },
      {
        "mark": {
          "type": "text",
          "dx": -5,
          "angle": 90,
          "baseline": "middle",
          "align": "right"
        },
        "encoding": {
          "text": {
            "aggregate": "sum",
            "field": "people",
            "type": "quantitative",
            "format": ".3s"
          }
        }
      }
    ]
  },
  "config": {
    "view": {"stroke": "transparent"},
    "facet": {"spacing": 10},
    "axis": {"domainWidth": 1}
  }
}
</code>```

Body:
When you want to add a text mark to a faceted chart, the pattern to use is a Layered view within a Facet Operator.

For example (<a href="https://vega.github.io/editor/#/url/vega-lite/N4IgJghgLhIFygK4CcA29zQgegA4HtdFVoBLfAOwDoArAZ0pAF8AaEKZCCugM32QC28ANqgepVFACmyDJCiIBVAJ5SIyAAQBeLRoBMABiPMWoAMYRUZ4tClzoiqnSkAPbbr0aA-BoDkAMSkBSylfDTg-AFkQ3xA2CDoMAHMpCjAZZgBdNgB3UjAoAAt4UDppXHgARj1WEB4IMykoErrSKVQwDAgUuPZlXDs4EH4wUgpLExA6AbMW1LN8UYokluUW7qTkKSTbDDpFXvF2zqGBwlQ7Nih+wZAAR0QuKFIYZ4A3S5AIF1JEhHYXhcMAQiCRnow2Jt8vB6qhnExai4WkcOslUulZFcbhgKPgBGMJvEfn9QM8oEChswEWwSKpZHBRCBgsgANYYABG6l680WYxW-wWqH4yLaqKGKTSGSxAxxeIJ6DYdAsFNAnGWg2EIAAxAA2ADsAFZKgBOADMvS1FgAHFadZUQJkEdTQMy2f9rjKhtIXM02GAkXAALQG+LLCnGgxsTnOVBjW74sBgIHxWNJCgYZCkJKFZq1HlLfmk1zNf4bLY7aR7A5sFEnEBnXDJvqe+6PChksgfQ78YIlkBUU2JJ2OtgLCjiQsgN5tHItMrIfAs24cLjTdSpXM1hpNOe4Bp8qoGWrfX4tMB4iBjADq+SKVSdQA" rel="noreferrer">vega editor):

{
  "data": {"url": "data/population.json"},
  "transform": [
    {"filter": "datum.year == 2000"},
    {"calculate": "datum.sex == 2 ? 'Female' : 'Male'", "as": "gender"}
  ],
  "width": {"step": 12},
  "facet": {"field": "age", "type": "ordinal"},
  "spec": {
    "encoding": {
      "y": {
        "aggregate": "sum",
        "field": "people",
        "type": "quantitative",
        "axis": {"title": "population", "grid": false}
      },
      "x": {"field": "gender", "type": "nominal", "axis": {"title": ""}}
    },
    "layer": [
      {
        "mark": "bar",
        "encoding": {
          "color": {
            "field": "gender",
            "type": "nominal",
            "scale": {"range": ["#675193", "#ca8861"]}
          }
        }
      },
      {
        "mark": {
          "type": "text",
          "dx": -5,
          "angle": 90,
          "baseline": "middle",
          "align": "right"
        },
        "encoding": {
          "text": {
            "aggregate": "sum",
            "field": "people",
            "type": "quantitative",
            "format": ".3s"
          }
        }
      }
    ]
  },
  "config": {
    "view": {"stroke": "transparent"},
    "facet": {"spacing": 10},
    "axis": {"domainWidth": 1}
  }
}


问:
Laravel Database connection Error: SQLSTATE[HY000] [2002] No route to host
I have this weird issue happened to me when I was setting up my Laravel application on live server, it gives me this error:

```<code>SQLSTATE[HY000] [2002] No route to host
</code>```

everything is correct though because I tested it using plain PHP PDO connection code and it's working fine but still Laravel gives me the above error, any idea how to solve this issue.

答: It looks like you put incorrect database host in .env file.</p>

Body:
I have this weird issue happened to me when I was setting up my Laravel application on live server, it gives me this error:

SQLSTATE[HY000] [2002] No route to host

everything is correct though because I tested it using plain PHP PDO connection code and it's working fine but still Laravel gives me the above error, any idea how to solve this issue.