问:
How to close all the processes one by one in a program that operates with multiprocessing by means of an 'if' validation found in one of them process?

import multiprocessing
from threading import Thread
import speech_recognition as sr

def actions_func(conn1_3,conn2_3):

def capture_cam(conn1, conn1b):

def audio_listening(conn2, conn2b):
    global catch_current_frame
    catch_current_frame = False

    # start dameon thread to handle frame requests:
    Thread(target=handle_catch_current_frame_requests, args=(conn2,), daemon=True).start()
    Thread(target=handle_cam_activate_requests, args=(conn2b,), daemon=True).start()

    while True:
        r = sr.Recognizer()

        with sr.Microphone() as source:
            catch_current_frame = False
            r.adjust_for_ambient_noise(source)
            print("Please say something...")
            audio = r.listen(source)

            try:
                text = r.recognize_google(audio, language="es-ES")
                print("You have said: \n " + repr(text))

                #Verifications
                if text.lower() == "capture":
                    catch_current_frame = True
                elif text.lower() == "Close your program":
                    #This is where I need to close processes p1, p2 and p3
                    break
                else:
                    pass

            except Exception as e:
                print("Error : " + str(e))

def main_process(finish_state):
    conn1, conn1_3 = multiprocessing.Pipe(duplex=True)
    conn2, conn2_3 = multiprocessing.Pipe(duplex=True)
    conn1b, conn2b = multiprocessing.Pipe(duplex=True)

    #Process 1
    p1 = multiprocessing.Process(target=capture_cam, args=(conn1, conn1b, ))
    p1.start()
    #Process 2
    p2 = multiprocessing.Process(target=audio_listening, args=(conn2, conn2b, ))
    p2.start()
    #Process 3
    p3 = multiprocessing.Process(target=actions_func, args=(conn1_3 ,conn2_3 ,))
    p3.start()

if __name__ == '__main__':
    finish_state = multiprocessing.Event()
    main_process(finish_state)

print("continue the code... ")

```
<p>I need that when the variable <code>text</code> is equal to <code>"Close your program"</code> the 3 active processes(<code>p1</code>,<code>p2</code>,<code>p3</code>) are closed.</p>
<p>I have tried to do something like this:</p>
<pre class="lang-py prettyprint-override"><code>elif text.lower() == "Close your program":
    print("the process has been interrupted!")
    finish_state.set()
    for process in [p1, p2, p3]:
        process.terminate()
</code>```

But it is not working for me, and I would need a better code that allows me to close them one by one in that code block if text is equal to "Close your program".

What should I do so that under that condition all the processes are closed one by one?

答:
You could try the following Event-based solution (but there are even simpler solutions to follow):

Have main_process pass to audio_listening an additional argument, finish_state:

def main_process():
    conn1, conn1_3 = multiprocessing.Pipe(duplex=True)
    conn2, conn2_3 = multiprocessing.Pipe(duplex=True)
    conn1b, conn2b = multiprocessing.Pipe(duplex=True)

    #Process 1
    p1 = multiprocessing.Process(target=capture_cam, args=(conn1, conn1b, ))
    p1.start()
    #Process 2
    finish_state = multiprocessing.Event()
    p2 = multiprocessing.Process(target=audio_listening, args=(conn2, conn2b, finish_state))
    p2.start()
    #Process 3
    p3 = multiprocessing.Process(target=actions_func, args=(conn1_3 ,conn2_3 ,))
    p3.start()

    finish_state.wait()
    p1.terminate()
    p2.terminate() # Not really necessary since the process is ending by itself
    p3.terminate()

if __name__ == '__main__':
    main_process()
```
<p>Note that it is now <code>main_process</code> that is creating the <code>finish_state</code> <code>multiprocessing.Event</code> instance; there appears to be no need for it to be passed as an argument. When the event is set, the main process will terminate the subprocesses that it has created.</p>
<p>Then in <code>audio_processing:</code></p>
<pre class="lang-py prettyprint-override"><code>def audio_listening(conn2, conn2b, finish_state):
    ...
                if text.lower() == "capture":
                    catch_current_frame = True
                elif text.lower() == "Close your program":
                    # Set the finish state event:
                    finish_state.set()
                    break
</code>```

There are even two simpler alternatives that do not even require an Event variable:

The audio_process process is in an infinite loop until it either gets a "Close your program" message or it gets an exception. In both cases it terminates and presumably we then want the other two processes to terminate, also. Therefore, the main process can just issue a call to p2.join() after it has started all the other processes in order to wait for the audio_process process to complete and then either:

Call p1.terminate() followed by p3.terminate().

Or start processes p1 and p3 specifying daemon=True, e.g. p1 = multiprocessing.Process(target=capture_cam, args=(conn1, conn1b), daemon=True). Being daemon processes they will now automatically terminate as soon as the main process terminates. Therefore, there is no need to call terminate on these processes.

Body:
import multiprocessing
from threading import Thread
import speech_recognition as sr

def actions_func(conn1_3,conn2_3):

def capture_cam(conn1, conn1b):

def audio_listening(conn2, conn2b):
    global catch_current_frame
    catch_current_frame = False

    # start dameon thread to handle frame requests:
    Thread(target=handle_catch_current_frame_requests, args=(conn2,), daemon=True).start()
    Thread(target=handle_cam_activate_requests, args=(conn2b,), daemon=True).start()

    while True:
        r = sr.Recognizer()

        with sr.Microphone() as source:
            catch_current_frame = False
            r.adjust_for_ambient_noise(source)
            print("Please say something...")
            audio = r.listen(source)

            try:
                text = r.recognize_google(audio, language="es-ES")
                print("You have said: \n " + repr(text))

                #Verifications
                if text.lower() == "capture":
                    catch_current_frame = True
                elif text.lower() == "Close your program":
                    #This is where I need to close processes p1, p2 and p3
                    break
                else:
                    pass

            except Exception as e:
                print("Error : " + str(e))

def main_process(finish_state):
    conn1, conn1_3 = multiprocessing.Pipe(duplex=True)
    conn2, conn2_3 = multiprocessing.Pipe(duplex=True)
    conn1b, conn2b = multiprocessing.Pipe(duplex=True)

    #Process 1
    p1 = multiprocessing.Process(target=capture_cam, args=(conn1, conn1b, ))
    p1.start()
    #Process 2
    p2 = multiprocessing.Process(target=audio_listening, args=(conn2, conn2b, ))
    p2.start()
    #Process 3
    p3 = multiprocessing.Process(target=actions_func, args=(conn1_3 ,conn2_3 ,))
    p3.start()

if __name__ == '__main__':
    finish_state = multiprocessing.Event()
    main_process(finish_state)

print("continue the code... ")

I need that when the variable text is equal to "Close your program" the 3 active processes(p1,p2,p3) are closed.

I have tried to do something like this:

elif text.lower() == "Close your program":
    print("the process has been interrupted!")
    finish_state.set()
    for process in [p1, p2, p3]:
        process.terminate()

But it is not working for me, and I would need a better code that allows me to close them one by one in that code block if text is equal to "Close your program".

What should I do so that under that condition all the processes are closed one by one?

Body:
You could try the following Event-based solution (but there are even simpler solutions to follow):

Have main_process pass to audio_listening an additional argument, finish_state:

def main_process():
    conn1, conn1_3 = multiprocessing.Pipe(duplex=True)
    conn2, conn2_3 = multiprocessing.Pipe(duplex=True)
    conn1b, conn2b = multiprocessing.Pipe(duplex=True)

    #Process 1
    p1 = multiprocessing.Process(target=capture_cam, args=(conn1, conn1b, ))
    p1.start()
    #Process 2
    finish_state = multiprocessing.Event()
    p2 = multiprocessing.Process(target=audio_listening, args=(conn2, conn2b, finish_state))
    p2.start()
    #Process 3
    p3 = multiprocessing.Process(target=actions_func, args=(conn1_3 ,conn2_3 ,))
    p3.start()

    finish_state.wait()
    p1.terminate()
    p2.terminate() # Not really necessary since the process is ending by itself
    p3.terminate()

if __name__ == '__main__':
    main_process()

Note that it is now main_process that is creating the finish_state multiprocessing.Event instance; there appears to be no need for it to be passed as an argument. When the event is set, the main process will terminate the subprocesses that it has created.

Then in audio_processing:

def audio_listening(conn2, conn2b, finish_state):
    ...
                if text.lower() == "capture":
                    catch_current_frame = True
                elif text.lower() == "Close your program":
                    # Set the finish state event:
                    finish_state.set()
                    break

There are even two simpler alternatives that do not even require an Event variable:

The audio_process process is in an infinite loop until it either gets a "Close your program" message or it gets an exception. In both cases it terminates and presumably we then want the other two processes to terminate, also. Therefore, the main process can just issue a call to p2.join() after it has started all the other processes in order to wait for the audio_process process to complete and then either:

Call p1.terminate() followed by p3.terminate().

Or start processes p1 and p3 specifying daemon=True, e.g. p1 = multiprocessing.Process(target=capture_cam, args=(conn1, conn1b), daemon=True). Being daemon processes they will now automatically terminate as soon as the main process terminates. Therefore, there is no need to call terminate on these processes.


来源: stackexchange

问:
What's the cheapest way to store an auto increment indexed list of values in AWS?
I have a DynamoDB-based web application that uses DynamoDB to store my large JSON objects and perform simple CRUD operations on them via a web API. I would like to add a new table that acts like a categorization of these values. The user should be able to select from a selection box which category the object belongs to. If a desirable category does not exist, the user should be able to create a new category specifying a name which will be available to other objects in the future.

It is critical to the application that every one of these categories be given a integer ID that increments starting the first at 1. These numbers that are auto generated will turn into reproducible serial numbers for back end reports that will not use the user-visible text name.

So I would like to have a simple API available from the web fronted that allows me to:

A) GET /category : produces { int : string, ... } of all categories mapped to an ID

B) PUSH /category : accepts string and stores the string to the next integer

Here are some ideas for how to handle this kind of project.

Store it in DynamoDB with integer indexes. This leaves has some benefits but it leaves a lot to be desired. Firstly, there's no auto incrementing ID in DynamoDB, but I could definitely get the state of the table, create a new ID, and store the result. This might have issues with consistency and race conditions but there's probably a way to achieve this safely. It might, however, be a big anti pattern to use DynamoDB this way.

Store it in DynamoDB as one object in a table with some random index. Just store the mapping as a JSON object. This really forgets the notion of tables in DynamoDB and uses it as a simple file. It might also run into some issues with race conditions.

Use AWS ElasticCache to have a Redis key value store. This might be "the right" decision but the downside is that ElasticCache is an always on DB offering where you pay per hour. For a low-traffic web site like mine I'd be paying minumum $12/mo I think and I would really like for this to be pay per access/update due to the low volume. I'm not sure there's an auto increment feature for Redis built in the way I'd need it. But it's pretty trivial to make a trasaction that gets the length of the table, adds one, and stores a new value. Race conditions are easily avoid with this solution.

Use a SQL database like AWS Aurora or MYSQL. Well this has the same upsides as Redis, but it's also more overkill than Redis is, and also it costs a lot more and it's still always on.

Run my own in memory web service or MongoDB etc... still you're paying for constant containers running. Writing my own thing is obviously silly but I'm sure there are services that match this issue perfectly but they'd all require a constant container to run.

Is there a food way to just store a simple list, or integer mapping like this that doesn't cost a constant monthly cost? Is there a better way to do this with DynamoDB?

答:
Store the maxCounterValue as an item in DyanamoDB.
For the PUSH /category, perform the following:

Get the current maxCounterValue.

TransactWrite:

Put the category name and id into a new item with id = maxCounterValue + 1.

Update the maxCounterValue +1, add a ConditionExpression to check that maxCounterValue = :valueFromGetOperation.

If TransactWrite fails, start at 1 again, try X more times

ContentLicense: CC BY-SA 4.0


问:
How can I have PHP avoid lazy evaluation?
I have an interesting question about the way PHP evaluates boolean expressions.   When you have, for example,

```<code>$expression = $expression1 and $expression2;
</code>```

or

```<code>if ($expression1 and $expression2)
</code>```

PHP first checks if $expression1 evaluates to true. If this is not the case, then $expression2 is simply skipped to avoid unnecessary calculations.  In a script I am writing, I have:

```<code>if ($validator->valid("title") and $validator->valid("text"))
</code>```

I need to have the second statement ($validator->valid("text")) evaluated even if the first one evaluates to false.  I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!

答:
try to evaluate each term separately:</p>

```<code>$term1 = $validator->valid("title");
$term2 = $validator->valid("text");
if($term1 && $term2) {
//things to do
}
</code>```

LastEditorDisplayName: Eddie

ContentLicense: CC BY-SA 2.5

Body:
I have an interesting question about the way PHP evaluates boolean expressions.   When you have, for example,

$expression = $expression1 and $expression2;

or

if ($expression1 and $expression2)

PHP first checks if $expression1 evaluates to true. If this is not the case, then $expression2 is simply skipped to avoid unnecessary calculations.  In a script I am writing, I have:

if ($validator->valid("title") and $validator->valid("text"))

I need to have the second statement ($validator->valid("text")) evaluated even if the first one evaluates to false.  I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!

Body:
try to evaluate each term separately:

$term1 = $validator->valid("title");
$term2 = $validator->valid("text");
if($term1 && $term2) {
//things to do
}

OwnerDisplayName: chosta


问:
notifyDataSetChanged does not update my recycler view
I have a ArrayList getting data from IntentService. After I got my data I updated my adapter and called notifyDataSetChanged(). But it does not change data.

Here is my code:

```<code>public class Nearby_ViewPager_Stations extends Fragment {

private View mRootView = null;
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private StationsReceiver mStationsReciever;
private MKLoader mProgressBar;

private RecyclerView.Adapter mAdapter;
private Context mContext;
ArrayList<ArrayList<StationArrivalPOJO>> stationArrivalPOJO = new ArrayList<>();

private static final String TAG = "NearbyViewPagerStations";

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (mRootView == null) {
        mRootView = inflater.inflate(R.layout.nearby_viewpager_stations, container, false);
        mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.recycler_view);
        mProgressBar = (MKLoader) mRootView.findViewById(R.id.progressBar);
    }

    mStationsReciever = new StationsReceiver(new Handler());
    mLayoutManager = new LinearLayoutManager(mContext);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new Adapter_recyclerView(stationArrivalPOJO);
    mRecyclerView.setAdapter(mAdapter);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            startIntentService();
            handler.postDelayed(this, 20*1000);
        }
    }, 1000);
    return mRootView;
}

private void startIntentService() {
    Intent intent1 = new Intent(mContext, GetAllStationsAndStopsIntentService.class);
    intent1.putExtra("Receiver", mStationsReciever);
    intent1.putExtra("latitude", Constants.latitude);
    intent1.putExtra("longitude", Constants.longitude);
    mContext.startService(intent1);
}

void addAdapter(ArrayList<ArrayList<StationArrivalPOJO>> resultData) {
    mProgressBar.setVisibility(View.GONE);

    if (stationArrivalPOJO.size() > 0)
        stationArrivalPOJO.clear();
    stationArrivalPOJO.addAll(resultData);
    mAdapter.notifyDataSetChanged();

    Log.v(TAG, "added all data: "+ stationArrivalPOJO.get(0).get(0).getTimeToStation());
}

public class StationsReceiver extends ResultReceiver {
    StationsReceiver(Handler handler) {
        super(handler);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        super.onReceiveResult(resultCode, resultData);

        addAdapter((ArrayList<ArrayList<StationArrivalPOJO>>)resultData.getSerializable("StationPOJO"));
    }
}
</code>```

}

And here is my Adapter code:

```<code> class Adapter_recyclerView extends RecyclerView.Adapter {

private ArrayList<ArrayList<StationArrivalPOJO>> mStationPojoList;
private LinearLayout mLinearLayout;

private Context mContext;

private static final String TAG = "AdapterRecyclerView";

Adapter_recyclerView(ArrayList<ArrayList<StationArrivalPOJO>> data) {
    mStationPojoList = data;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    ((ViewHolder)holder).stationNameTV.setText(mStationPojoList.get(position).get(0).getStationName());

    ArrayList<String> mUniqueStationName = new ArrayList<>();  //Unique platform names of a station got from hash set 'uniqStatNames'
    HashSet<String> uniqStatNames = new HashSet<>(); //Unique platform names of a station

    for (int i = 0;i<mStationPojoList.get(position).size(); i++) {
        uniqStatNames.add(mStationPojoList.get(position).get(i).getPlatformName()
        + mStationPojoList.get(position).get(i).getTowards());
    }

    for(Iterator<String> it = uniqStatNames.iterator() ; it.hasNext() ; ) {
        mUniqueStationName.add(it.next());
    }

    for (int j=0; j<mUniqueStationName.size(); j++) {
        ArrayList<StationArrivalPOJO> arrivalPOJOs = new ArrayList<>();   //Platform wise categorized train details
        for (int i = 0;i<mStationPojoList.get(position).size(); i++) {
            if (mUniqueStationName.get(j).contains(mStationPojoList.get(position).get(i).getPlatformName())
                    && mUniqueStationName.get(j).contains(mStationPojoList.get(position).get(i).getTowards())) {
                arrivalPOJOs.add(mStationPojoList.get(position).get(i));
            }
        }

        Collections.sort(arrivalPOJOs, new Comparator<StationArrivalPOJO>() {
            @Override
            public int compare(StationArrivalPOJO stationArrivalPOJO, StationArrivalPOJO t1) {
                return stationArrivalPOJO.getTimeToStation() - t1.getTimeToStation();
            }
        });

        for (int k=0; k<arrivalPOJOs.size(); k++) {
        Log.v(TAG, j+":"+mUniqueStationName.size()+"boo"+arrivalPOJOs.toString());
        Log.v(TAG, "boom " + arrivalPOJOs.get(k).getPlatformName() + ":" + arrivalPOJOs.get(k).getTowards());

        RelativeLayout relativeLayout = new RelativeLayout(mContext);
        relativeLayout.setPadding(16, 16, 16, 16);
        LinearLayout linearLayout = new LinearLayout(mContext);
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        TextView trainName = new TextView(mContext);
        trainName.setText(arrivalPOJOs.get(k).getPlatformName());

        TextView towards = new TextView(mContext);
        towards.setText(arrivalPOJOs.get(k).getTowards());

        linearLayout.addView(trainName);
        linearLayout.addView(towards);

        RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        linearLayout.setLayoutParams(layoutParams1);

        TextView time = new TextView(mContext);
        time.setText(String.valueOf(arrivalPOJOs.get(k).getTimeToStation()));

        RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        time.setLayoutParams(layoutParams2);

        relativeLayout.addView(linearLayout);
        relativeLayout.addView(time);

        mLinearLayout.addView(relativeLayout);
        }}
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View rootView =  LayoutInflater.from(parent.getContext())
            .inflate(R.layout.adapter_recyclerview,parent,false);
    mContext = parent.getContext();

    mLinearLayout = (LinearLayout) rootView.findViewById(R.id.cardViewLinearLayout);
    TextView mStationName = (TextView) rootView.findViewById(R.id.stationName);

    return new ViewHolder(rootView, mStationName);
}

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

private static class ViewHolder extends RecyclerView.ViewHolder {
    TextView stationNameTV;

    ViewHolder(View view, TextView stationNameTV) {
        super(view);
        this.stationNameTV = stationNameTV;
    }
}
</code>```

}

When I retrieve data from ArrayList and print in log station I get updated values. But that updates are not getting reflected in my recycler list.

I have seen other questions in Stack Overflow saying that:

we need update data from the same Fragment object

notifyDataSetChanged()` should be called from ui thread.

I dont understand what I am missing.

答:
TL;DR: Don't store your adapter in a property of your activity/fragment. Always call and cast from mRecyclerView.getAdapter()

I had the same issue.

All people only say is use notifyDataSetChanged() and that should do it (some might argue on using the notifyItem* ones, I'd say it depends)

Just fixed it thanks to your comments on the accepted answer (even when is not the correct one)

Yes, notifyDataSetChanged() is being called on my adapter, but is not the correct adapter to update.

I have a recycler with around 500 items being filtered, I can see that the new items list is being reduced to 10 items, but the UI was still showing all of the items.

This comment made me question if mine was being called, so I put some logs and well, I saw that it was still using the original 500 items list even after I got the logs that the adapter had a new list with just 10.

Well, this was caused by having a property in my fragment and updating that adapter.

private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;

onCreateView() {
    // Retrieve data and more code
    mRecyclerView = view.findViewById(R.id.recycler_view);
    mAdapter = new MyRecyclerViewAdapter(data);
    mRecyclerView.setAdapter(mAdapter);
}

filter(String txt) {
    // Here the adapter handles filtering the list
    // and calling notifyDataSetChanged()
    mAdapter.filter(query);
}
```
<p>Now it's like this and is working</p>
<pre class="lang-java prettyprint-override"><code>private RecyclerView mRecyclerView;

onCreateView() {
    // Retrieve data and more code
    mRecyclerView = view.findViewById(R.id.recycler_view);
    mRecyclerView.setAdapter(new MyRecyclerViewAdapter(data));
}

filter(String txt) {
    // Here the adapter handles filtering the list
    // and calling notifyDataSetChanged()
    ((MyRecyclerViewAdapter)mRecyclerView.getAdapter()).filter(query)
}
</code>```

 I'd say you don't have to accept an answer if it didn't help resolve your issue.

 And if you solved it yourself you can answer your own question and accept your own answer.

ContentLicense: CC BY-SA 3.0

Body:
I have a ArrayList getting data from IntentService. After I got my data I updated my adapter and called notifyDataSetChanged(). But it does not change data.

Here is my code:

public class Nearby_ViewPager_Stations extends Fragment {

private View mRootView = null;
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private StationsReceiver mStationsReciever;
private MKLoader mProgressBar;

private RecyclerView.Adapter mAdapter;
private Context mContext;
ArrayList<ArrayList<StationArrivalPOJO>> stationArrivalPOJO = new ArrayList<>();

private static final String TAG = "NearbyViewPagerStations";

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (mRootView == null) {
        mRootView = inflater.inflate(R.layout.nearby_viewpager_stations, container, false);
        mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.recycler_view);
        mProgressBar = (MKLoader) mRootView.findViewById(R.id.progressBar);
    }

    mStationsReciever = new StationsReceiver(new Handler());
    mLayoutManager = new LinearLayoutManager(mContext);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new Adapter_recyclerView(stationArrivalPOJO);
    mRecyclerView.setAdapter(mAdapter);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            startIntentService();
            handler.postDelayed(this, 20*1000);
        }
    }, 1000);
    return mRootView;
}

private void startIntentService() {
    Intent intent1 = new Intent(mContext, GetAllStationsAndStopsIntentService.class);
    intent1.putExtra("Receiver", mStationsReciever);
    intent1.putExtra("latitude", Constants.latitude);
    intent1.putExtra("longitude", Constants.longitude);
    mContext.startService(intent1);
}

void addAdapter(ArrayList<ArrayList<StationArrivalPOJO>> resultData) {
    mProgressBar.setVisibility(View.GONE);

    if (stationArrivalPOJO.size() > 0)
        stationArrivalPOJO.clear();
    stationArrivalPOJO.addAll(resultData);
    mAdapter.notifyDataSetChanged();

    Log.v(TAG, "added all data: "+ stationArrivalPOJO.get(0).get(0).getTimeToStation());
}

public class StationsReceiver extends ResultReceiver {
    StationsReceiver(Handler handler) {
        super(handler);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        super.onReceiveResult(resultCode, resultData);

        addAdapter((ArrayList<ArrayList<StationArrivalPOJO>>)resultData.getSerializable("StationPOJO"));
    }
}

}

And here is my Adapter code:

 class Adapter_recyclerView extends RecyclerView.Adapter {

private ArrayList<ArrayList<StationArrivalPOJO>> mStationPojoList;
private LinearLayout mLinearLayout;

private Context mContext;

private static final String TAG = "AdapterRecyclerView";

Adapter_recyclerView(ArrayList<ArrayList<StationArrivalPOJO>> data) {
    mStationPojoList = data;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    ((ViewHolder)holder).stationNameTV.setText(mStationPojoList.get(position).get(0).getStationName());

    ArrayList<String> mUniqueStationName = new ArrayList<>();  //Unique platform names of a station got from hash set 'uniqStatNames'
    HashSet<String> uniqStatNames = new HashSet<>(); //Unique platform names of a station

    for (int i = 0;i<mStationPojoList.get(position).size(); i++) {
        uniqStatNames.add(mStationPojoList.get(position).get(i).getPlatformName()
        + mStationPojoList.get(position).get(i).getTowards());
    }

    for(Iterator<String> it = uniqStatNames.iterator() ; it.hasNext() ; ) {
        mUniqueStationName.add(it.next());
    }

    for (int j=0; j<mUniqueStationName.size(); j++) {
        ArrayList<StationArrivalPOJO> arrivalPOJOs = new ArrayList<>();   //Platform wise categorized train details
        for (int i = 0;i<mStationPojoList.get(position).size(); i++) {
            if (mUniqueStationName.get(j).contains(mStationPojoList.get(position).get(i).getPlatformName())
                    && mUniqueStationName.get(j).contains(mStationPojoList.get(position).get(i).getTowards())) {
                arrivalPOJOs.add(mStationPojoList.get(position).get(i));
            }
        }

        Collections.sort(arrivalPOJOs, new Comparator<StationArrivalPOJO>() {
            @Override
            public int compare(StationArrivalPOJO stationArrivalPOJO, StationArrivalPOJO t1) {
                return stationArrivalPOJO.getTimeToStation() - t1.getTimeToStation();
            }
        });

        for (int k=0; k<arrivalPOJOs.size(); k++) {
        Log.v(TAG, j+":"+mUniqueStationName.size()+"boo"+arrivalPOJOs.toString());
        Log.v(TAG, "boom " + arrivalPOJOs.get(k).getPlatformName() + ":" + arrivalPOJOs.get(k).getTowards());

        RelativeLayout relativeLayout = new RelativeLayout(mContext);
        relativeLayout.setPadding(16, 16, 16, 16);
        LinearLayout linearLayout = new LinearLayout(mContext);
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        TextView trainName = new TextView(mContext);
        trainName.setText(arrivalPOJOs.get(k).getPlatformName());

        TextView towards = new TextView(mContext);
        towards.setText(arrivalPOJOs.get(k).getTowards());

        linearLayout.addView(trainName);
        linearLayout.addView(towards);

        RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        linearLayout.setLayoutParams(layoutParams1);

        TextView time = new TextView(mContext);
        time.setText(String.valueOf(arrivalPOJOs.get(k).getTimeToStation()));

        RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        time.setLayoutParams(layoutParams2);

        relativeLayout.addView(linearLayout);
        relativeLayout.addView(time);

        mLinearLayout.addView(relativeLayout);
        }}
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View rootView =  LayoutInflater.from(parent.getContext())
            .inflate(R.layout.adapter_recyclerview,parent,false);
    mContext = parent.getContext();

    mLinearLayout = (LinearLayout) rootView.findViewById(R.id.cardViewLinearLayout);
    TextView mStationName = (TextView) rootView.findViewById(R.id.stationName);

    return new ViewHolder(rootView, mStationName);
}

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

private static class ViewHolder extends RecyclerView.ViewHolder {
    TextView stationNameTV;

    ViewHolder(View view, TextView stationNameTV) {
        super(view);
        this.stationNameTV = stationNameTV;
    }
}

}

When I retrieve data from ArrayList and print in log station I get updated values. But that updates are not getting reflected in my recycler list.

I have seen other questions in Stack Overflow saying that:

we need update data from the same Fragment object

notifyDataSetChanged()` should be called from ui thread.

I dont understand what I am missing.

Body:
TL;DR: Don't store your adapter in a property of your activity/fragment. Always call and cast from mRecyclerView.getAdapter()

I had the same issue.

All people only say is use notifyDataSetChanged() and that should do it (some might argue on using the notifyItem* ones, I'd say it depends)

Just fixed it thanks to your comments on the accepted answer (even when is not the correct one)

Yes, notifyDataSetChanged() is being called on my adapter, but is not the correct adapter to update.

I have a recycler with around 500 items being filtered, I can see that the new items list is being reduced to 10 items, but the UI was still showing all of the items.

This comment made me question if mine was being called, so I put some logs and well, I saw that it was still using the original 500 items list even after I got the logs that the adapter had a new list with just 10.

Well, this was caused by having a property in my fragment and updating that adapter.

private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;

onCreateView() {
    // Retrieve data and more code
    mRecyclerView = view.findViewById(R.id.recycler_view);
    mAdapter = new MyRecyclerViewAdapter(data);
    mRecyclerView.setAdapter(mAdapter);
}

filter(String txt) {
    // Here the adapter handles filtering the list
    // and calling notifyDataSetChanged()
    mAdapter.filter(query);
}

Now it's like this and is working

private RecyclerView mRecyclerView;

onCreateView() {
    // Retrieve data and more code
    mRecyclerView = view.findViewById(R.id.recycler_view);
    mRecyclerView.setAdapter(new MyRecyclerViewAdapter(data));
}

filter(String txt) {
    // Here the adapter handles filtering the list
    // and calling notifyDataSetChanged()
    ((MyRecyclerViewAdapter)mRecyclerView.getAdapter()).filter(query)
}

 I'd say you don't have to accept an answer if it didn't help resolve your issue.

 And if you solved it yourself you can answer your own question and accept your own answer.


问:
Error "Could not resolve all files for configuration" in Android Studio
I try to run an app that have no visible error in coding. However when I try to run it this error pop up:

Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':app:debugRuntimeClasspath'.

Not sure this error is important or not but I'll show here anyway:

```<code>API 'BaseVariant.getApplicationIdTextResource' is obsolete and has been replaced with 'VariantProperties.applicationId'.
It will be removed in version 7.0 of the Android Gradle plugin.
For more information, see TBD.
To determine what is calling BaseVariant.getApplicationIdTextResource, use -Pandroid.debug.obsoleteApi=true on the command line to display more information.
</code>```

答:
Have you tried turning off The offline mode ?
On the top right side of the Window .

Click on Gradle 2nd number option(just near of Setting option) click on it then you will be able to do work continue sally.

As you can see the image

Body:
I try to run an app that have no visible error in coding. However when I try to run it this error pop up:

Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':app:debugRuntimeClasspath'.

Not sure this error is important or not but I'll show here anyway:

API 'BaseVariant.getApplicationIdTextResource' is obsolete and has been replaced with 'VariantProperties.applicationId'.
It will be removed in version 7.0 of the Android Gradle plugin.
For more information, see TBD.
To determine what is calling BaseVariant.getApplicationIdTextResource, use -Pandroid.debug.obsoleteApi=true on the command line to display more information.


问:
How to make a polygon radar (spider) chart in python
```<code>import matplotlib.pyplot as plt
import numpy as np

labels=['Siege', 'Initiation', 'Crowd_control', 'Wave_clear', 'Objective_damage']
markers = [0, 1, 2, 3, 4, 5]
str_markers = ["0", "1", "2", "3", "4", "5"]

def make_radar_chart(name, stats, attribute_labels=labels,
                     plot_markers=markers, plot_str_markers=str_markers):

    labels = np.array(attribute_labels)

    angles = np.linspace(0, 2*np.pi, len(labels), endpoint=False)
    stats = np.concatenate((stats,[stats[0]]))
    angles = np.concatenate((angles,[angles[0]]))

    fig = plt.figure()
    ax = fig.add_subplot(111, polar=True)
    ax.plot(angles, stats, 'o-', linewidth=2)
    ax.fill(angles, stats, alpha=0.25)
    ax.set_thetagrids(angles * 180/np.pi, labels)
    plt.yticks(markers)
    ax.set_title(name)
    ax.grid(True)

    fig.savefig("static/images/%s.png" % name)

    return plt.show()

make_radar_chart("Agni", [2,3,4,4,5]) # example
</code>```

Basically I want the chart to be a pentagon instead of circle. Can anyone help with this. I am using python matplotlib to save an image which will stored and displayed later. I want my chart to have the form of the second picture

EDIT:

```<code>    gridlines = ax.yaxis.get_gridlines()
    for gl in gridlines:
        gl.get_path()._interpolation_steps = 5
</code>```

adding this section of code from answer below helped a lot. I am getting this chart. Still need to figure out how to get rid of the outer most ring:

答:
As shown in this other post the answer from @ImportanceOfBeingErnest doesn't work in matplotlib>3.2.2 in that you get circular grids. As shown in this PR you can use the following

import numpy as np

import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
from matplotlib.spines import Spine
from matplotlib.transforms import Affine2D

def radar_factory(num_vars, frame='circle'):
    """Create a radar chart with `num_vars` axes.

    This function creates a RadarAxes projection and registers it.

    Parameters
    ----------
    num_vars : int
        Number of variables for radar chart.
    frame : {'circle' | 'polygon'}
        Shape of frame surrounding axes.

    """
    # calculate evenly-spaced axis angles
    theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)

    class RadarTransform(PolarAxes.PolarTransform):
        def transform_path_non_affine(self, path):
            # Paths with non-unit interpolation steps correspond to gridlines,
            # in which case we force interpolation (to defeat PolarTransform's
            # autoconversion to circular arcs).
            if path._interpolation_steps > 1:
                path = path.interpolated(num_vars)
            return Path(self.transform(path.vertices), path.codes)

    class RadarAxes(PolarAxes):

        name = 'radar'

        PolarTransform = RadarTransform

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # rotate plot such that the first axis is at the top
            self.set_theta_zero_location('N')

        def fill(self, *args, closed=True, **kwargs):
            """Override fill so that line is closed by default"""
            return super().fill(closed=closed, *args, **kwargs)

        def plot(self, *args, **kwargs):
            """Override plot so that line is closed by default"""
            lines = super().plot(*args, **kwargs)
            for line in lines:
                self._close_line(line)

        def _close_line(self, line):
            x, y = line.get_data()
            # FIXME: markers at x[0], y[0] get doubled-up
            if x[0] != x[-1]:
                x = np.concatenate((x, [x[0]]))
                y = np.concatenate((y, [y[0]]))
                line.set_data(x, y)

        def set_varlabels(self, labels):
            self.set_thetagrids(np.degrees(theta), labels)

        def _gen_axes_patch(self):
            # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
            # in axes coordinates.
            if frame == 'circle':
                return Circle((0.5, 0.5), 0.5)
            elif frame == 'polygon':
                return RegularPolygon((0.5, 0.5), num_vars,
                                      radius=.5, edgecolor="k")
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

        def draw(self, renderer):
            """ Draw. If frame is polygon, make gridlines polygon-shaped """
            if frame == 'polygon':
                gridlines = self.yaxis.get_gridlines()
                for gl in gridlines:
                    gl.get_path()._interpolation_steps = num_vars
            super().draw(renderer)

        def _gen_axes_spines(self):
            if frame == 'circle':
                return super()._gen_axes_spines()
            elif frame == 'polygon':
                # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.
                spine = Spine(axes=self,
                              spine_type='circle',
                              path=Path.unit_regular_polygon(num_vars))
                # unit_regular_polygon gives a polygon of radius 1 centered at
                # (0, 0) but we want a polygon of radius 0.5 centered at (0.5,
                # 0.5) in axes coordinates.
                spine.set_transform(Affine2D().scale(.5).translate(.5, .5)
                                    + self.transAxes)

                return {'polar': spine}
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

    register_projection(RadarAxes)
    return theta

data = [['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'],
        ('Basecase', [
            [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],
            [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],
            [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],
            [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],
            [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]])]

N = len(data[0])
theta = radar_factory(N, frame='polygon')

spoke_labels = data.pop(0)
title, case_data = data[0]

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(projection='radar'))
fig.subplots_adjust(top=0.85, bottom=0.05)

ax.set_rgrids([0.2, 0.4, 0.6, 0.8])
ax.set_title(title,  position=(0.5, 1.1), ha='center')

for d in case_data:
    line = ax.plot(theta, d)
    ax.fill(theta, d, alpha=0.25, label='_nolegend_')
ax.set_varlabels(spoke_labels)

plt.show()
```

to get the desired:

Body:
import matplotlib.pyplot as plt
import numpy as np

labels=['Siege', 'Initiation', 'Crowd_control', 'Wave_clear', 'Objective_damage']
markers = [0, 1, 2, 3, 4, 5]
str_markers = ["0", "1", "2", "3", "4", "5"]

def make_radar_chart(name, stats, attribute_labels=labels,
                     plot_markers=markers, plot_str_markers=str_markers):

    labels = np.array(attribute_labels)

    angles = np.linspace(0, 2*np.pi, len(labels), endpoint=False)
    stats = np.concatenate((stats,[stats[0]]))
    angles = np.concatenate((angles,[angles[0]]))

    fig = plt.figure()
    ax = fig.add_subplot(111, polar=True)
    ax.plot(angles, stats, 'o-', linewidth=2)
    ax.fill(angles, stats, alpha=0.25)
    ax.set_thetagrids(angles * 180/np.pi, labels)
    plt.yticks(markers)
    ax.set_title(name)
    ax.grid(True)

    fig.savefig("static/images/%s.png" % name)

    return plt.show()

make_radar_chart("Agni", [2,3,4,4,5]) # example

Basically I want the chart to be a pentagon instead of circle. Can anyone help with this. I am using python matplotlib to save an image which will stored and displayed later. I want my chart to have the form of the second picture

EDIT:

    gridlines = ax.yaxis.get_gridlines()
    for gl in gridlines:
        gl.get_path()._interpolation_steps = 5

adding this section of code from answer below helped a lot. I am getting this chart. Still need to figure out how to get rid of the outer most ring:

Body:
As shown in this other post the answer from @ImportanceOfBeingErnest doesn't work in matplotlib>3.2.2 in that you get circular grids. As shown in this PR you can use the following

import numpy as np

import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
from matplotlib.spines import Spine
from matplotlib.transforms import Affine2D

def radar_factory(num_vars, frame='circle'):
    """Create a radar chart with `num_vars` axes.

    This function creates a RadarAxes projection and registers it.

    Parameters
    ----------
    num_vars : int
        Number of variables for radar chart.
    frame : {'circle' | 'polygon'}
        Shape of frame surrounding axes.

    """
    # calculate evenly-spaced axis angles
    theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)

    class RadarTransform(PolarAxes.PolarTransform):
        def transform_path_non_affine(self, path):
            # Paths with non-unit interpolation steps correspond to gridlines,
            # in which case we force interpolation (to defeat PolarTransform's
            # autoconversion to circular arcs).
            if path._interpolation_steps > 1:
                path = path.interpolated(num_vars)
            return Path(self.transform(path.vertices), path.codes)

    class RadarAxes(PolarAxes):

        name = 'radar'

        PolarTransform = RadarTransform

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # rotate plot such that the first axis is at the top
            self.set_theta_zero_location('N')

        def fill(self, *args, closed=True, **kwargs):
            """Override fill so that line is closed by default"""
            return super().fill(closed=closed, *args, **kwargs)

        def plot(self, *args, **kwargs):
            """Override plot so that line is closed by default"""
            lines = super().plot(*args, **kwargs)
            for line in lines:
                self._close_line(line)

        def _close_line(self, line):
            x, y = line.get_data()
            # FIXME: markers at x[0], y[0] get doubled-up
            if x[0] != x[-1]:
                x = np.concatenate((x, [x[0]]))
                y = np.concatenate((y, [y[0]]))
                line.set_data(x, y)

        def set_varlabels(self, labels):
            self.set_thetagrids(np.degrees(theta), labels)

        def _gen_axes_patch(self):
            # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
            # in axes coordinates.
            if frame == 'circle':
                return Circle((0.5, 0.5), 0.5)
            elif frame == 'polygon':
                return RegularPolygon((0.5, 0.5), num_vars,
                                      radius=.5, edgecolor="k")
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

        def draw(self, renderer):
            """ Draw. If frame is polygon, make gridlines polygon-shaped """
            if frame == 'polygon':
                gridlines = self.yaxis.get_gridlines()
                for gl in gridlines:
                    gl.get_path()._interpolation_steps = num_vars
            super().draw(renderer)

        def _gen_axes_spines(self):
            if frame == 'circle':
                return super()._gen_axes_spines()
            elif frame == 'polygon':
                # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.
                spine = Spine(axes=self,
                              spine_type='circle',
                              path=Path.unit_regular_polygon(num_vars))
                # unit_regular_polygon gives a polygon of radius 1 centered at
                # (0, 0) but we want a polygon of radius 0.5 centered at (0.5,
                # 0.5) in axes coordinates.
                spine.set_transform(Affine2D().scale(.5).translate(.5, .5)
                                    + self.transAxes)

                return {'polar': spine}
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

    register_projection(RadarAxes)
    return theta

data = [['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'],
        ('Basecase', [
            [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],
            [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],
            [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],
            [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],
            [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]])]

N = len(data[0])
theta = radar_factory(N, frame='polygon')

spoke_labels = data.pop(0)
title, case_data = data[0]

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(projection='radar'))
fig.subplots_adjust(top=0.85, bottom=0.05)

ax.set_rgrids([0.2, 0.4, 0.6, 0.8])
ax.set_title(title,  position=(0.5, 1.1), ha='center')

for d in case_data:
    line = ax.plot(theta, d)
    ax.fill(theta, d, alpha=0.25, label='_nolegend_')
ax.set_varlabels(spoke_labels)

plt.show()

to get the desired:


问:
Removing the .0 from a double
I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0

example: display 5.5 as 5.5 and 5.0 as 5

This is what I have so far: (answer is a double)

```<code>double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);
System.out.println(output);
</code>```

this work's fine up to about 1e18 then will error out because of the maximum size of a Long.
So how would I achieve this on bigger numbers like 5.43e86

答:
The DecimalFormat suggestions are the easiest way to handle this.  If they aren't sufficient, here's another idea.

If you're starting to hit the maximum values that can be represented by primitives in Java, then you may need to move to BigInteger and BigDecimal.

Try playing around with the BigDecimal.toBigInteger() method coupled with the toString() methods on BigDecimal and BigInteger.

Title: Removing the .0 from a double

Body:
I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0

example: display 5.5 as 5.5 and 5.0 as 5

This is what I have so far: (answer is a double)

double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);
System.out.println(output);

this work's fine up to about 1e18 then will error out because of the maximum size of a Long.
So how would I achieve this on bigger numbers like 5.43e86


问:
OR operator in Django filter creates duplicates
when I print Brand.objects.filter(Q(name__icontains=keyword)|Q(tag__name__icontains=keyword)), it yields two objects as opposed to my expectation. It should be only one.

My models.py is like

```<code>class Brand(models.Model):
    name = models.CharField(max_length=20)
    tag = models.ManyToManyField('Tag', blank=True)
class Tag(models.Model):
    name = models.CharField(max_length=20)
</code>```

When I print Brand.objects.filter(name__icontains=keyword) and Brand.objects.filter(tag__name__icontains=keyword) seperately, each one yields only one same object. But when I merge these two queries, it yields duplicates. I found out .distinct() solves this problem but I wanna know why. Looking forward to help!

答:
It is not the or condition that results in duplicates, it is the fact that you are filtering on a related model with a ManyToManyField. This means that the query will look like:

```SELECT brand.*
FROM brand
<b>LEFT OUTER JOIN</b> brand_tag ON brand_tag.brand_id = brand.id
<b>LEFT OUTER JOIN</b> tag ON tag.id = brand_tag.tag_id
WHERE brand.name LIKE <em>%keyword</em>% OR tag.name LIKE <em>%keyword</em>%```

You thus will JOIN on the tag model, and if multiple tags match the keyword, then that brand will be repeated that many times in the QuerySet.

If you thus would have filtered with .filter(tag__name__icontains=keyword), you would have gotten duplicates as well.

Note: There is a django-taggit package [GitHub] to work with content that contains tags. This might be better than implementing your own tag system.

Body:
when I print Brand.objects.filter(Q(name__icontains=keyword)|Q(tag__name__icontains=keyword)), it yields two objects as opposed to my expectation. It should be only one.

My models.py is like

class Brand(models.Model):
    name = models.CharField(max_length=20)
    tag = models.ManyToManyField('Tag', blank=True)
class Tag(models.Model):
    name = models.CharField(max_length=20)

When I print Brand.objects.filter(name__icontains=keyword) and Brand.objects.filter(tag__name__icontains=keyword) seperately, each one yields only one same object. But when I merge these two queries, it yields duplicates. I found out .distinct() solves this problem but I wanna know why. Looking forward to help!

Body:
It is not the or condition that results in duplicates, it is the fact that you are filtering on a related model with a ManyToManyField. This means that the query will look like:

SELECT brand.*
FROM brand
LEFT OUTER JOIN brand_tag ON brand_tag.brand_id = brand.id
LEFT OUTER JOIN tag ON tag.id = brand_tag.tag_id
WHERE brand.name LIKE %keyword% OR tag.name LIKE %keyword%

You thus will JOIN on the tag model, and if multiple tags match the keyword, then that brand will be repeated that many times in the QuerySet.

If you thus would have filtered with .filter(tag__name__icontains=keyword), you would have gotten duplicates as well.

Note: There is a django-taggit package [GitHub] to work with content that contains tags. This might be better than implementing your own tag system.


问:
How to use/install sodium-plus
I have an issue, I don't understand how to "install" sodium-plus for using on my website.

I installed :

```<code><script src="https://cdn.jsdelivr.net/npm/sodium-plus@0.9.0/index.min.js"></script>

<script type="text/javascript" src="/require.js"></script>
</code>```

and I want to test this script :

```<code><script>
(async function() {
    if (!window.sodium) window.sodium = await SodiumPlus.auto();

    // You can now use the sodium object here.

    // Just some example code to ensure it s running:
    let random = await sodium.randombytes_buf(32);
    let hash = await sodium.crypto_generichash(
    "hello world");
    console.log({
        "random": random.toString("hex"),
        "hash": hash.toString("hex")
    });
})();
</script>
</code>```

But I have two errors :

Uncaught ReferenceError: module is not defined Uncaught (in promise)

TypeError: Cannot read properties of undefined (reading 'auto')

答:
It works with this link :

src="https://cdn.jsdelivr.net/npm/sodium-plus@0.9.0/dist/sodium-plus.min.js"

and I delete the code :

```<code>let { SodiumPlus } = "sodium-plus";
require(["sodium-plus"], function(result){
    SodiumPlus = result;
});
</code>```

But I keep the requirejs script from this website (at the bottom of my scripts because there is sometimes an issue with jQuery) :

https://cdnjs.com/libraries/require.js

And after, to avoid an issue about requirejs script, I do this :

```<code>define(function (require) {
    const { SodiumPlus } = require("sodium-plus");
});
let sodium;
</code>```

Not this :

```<code>const { SodiumPlus } = require('sodium-plus');
let sodium;
</code>```

Title: How to use/install sodium-plus

Body:
I have an issue, I don't understand how to "install" sodium-plus for using on my website.

I installed :

and I want to test this script :

But I have two errors :

Uncaught ReferenceError: module is not defined Uncaught (in promise)

TypeError: Cannot read properties of undefined (reading 'auto')

Body:
It works with this link :

src="https://cdn.jsdelivr.net/npm/sodium-plus@0.9.0/dist/sodium-plus.min.js"

and I delete the code :

let { SodiumPlus } = "sodium-plus";
require(["sodium-plus"], function(result){
    SodiumPlus = result;
});

But I keep the requirejs script from this website (at the bottom of my scripts because there is sometimes an issue with jQuery) :

https://cdnjs.com/libraries/require.js

And after, to avoid an issue about requirejs script, I do this :

define(function (require) {
    const { SodiumPlus } = require("sodium-plus");
});
let sodium;

Not this :

const { SodiumPlus } = require('sodium-plus');
let sodium;


问:
How to know if user is active in firebase in Flutter
I'm trying to make chat app in Flutter with Firebase and had a trouble which I can't know if my user is active (using the app) or not.
I tried to make a native code that run when app terminated but didn't work.

I tried to make it with lifecycle method but didn't work .

```<code>@override
  void didChangeAppLifecycleState(AppLifecycleState state) {

    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.detached:
          FirebaseFirestore.instance.collection("users").doc(id).update({"active" : false});
        break;
      default:
    }
  }
</code>```

But it does nothing when app is terminated. Does anyone have an idea for it in Flutter?

答:
There is no way to guarantee that your update({"active" : false}) code will still be able to execute the write operation when the user is no longer actively using the app. Firestore has no built-in capability to write something in the database after the client has disconnected.

Firebase's other database: the Realtime Database, does have the ability with its onDisconnect handlers, which are delayed write instructions that you to the database when you are connected, and which the database then executes once it detects that the connection is gone.

You can combine the Realtime Database with Firestore as shown this documentation page on connecting Realtime Database and Firestore to get presence information into Firestore too. I'd also recommend reading the non-Flutter specific documentation on building a presence system with the Realtime Database.

Body:
I'm trying to make chat app in Flutter with Firebase and had a trouble which I can't know if my user is active (using the app) or not.
I tried to make a native code that run when app terminated but didn't work.

I tried to make it with lifecycle method but didn't work .

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {

    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.detached:
          FirebaseFirestore.instance.collection("users").doc(id).update({"active" : false});
        break;
      default:
    }
  }

But it does nothing when app is terminated. Does anyone have an idea for it in Flutter?


问:
Matching ASP.NET MVC routes across /
I know that when there is a route of the form

```<code>Alpha/Bravo/{Charlie}
</code>```

and another of the form

```<code>Alpha/Bravo/Delta/{Echo}
</code>```

the first route will match everything for both routes, because Delta/{Echo} is accepted as {Charlie}. Although this can be a pain when organizing routes, it can also be useful for the purpose of simplicity. I would like to be able to use this concept in the middle of a route string. I would like to make something like

```<code>Alpha/{Bravo}/Charlie
</code>```

match URLs of the form

```<code>Alpha/bravo/Charlie
</code>```

AND

```<code>Alpha/bravo/bravo2/Charlie
</code>```

Is there a way to do this?

答:
Use a regular expression route. Something like the following could match the {variant} parameter with 1 or more trailing digits

```<code>routes.MapRoute(
    "Title",
    "Controller/something/{variant}/Action",
    new { controller = "Controller", action = "Action" },
    new { variant = @"something\d+" }
);
</code>```

Your route looks a little odd (maybe it's missing some curly braces), but my answer describes how you could use regular expressions for a number of parameters in your route.

With your exact route, Controller/something/{variant}/Action (again, this is odd), my mapped route would catch requests like:

```<code>/Controller/something/something123/Action
/Controller/something/something1/Action
</code>```

But not

```<code>/Controller/something/somethingelse/Action
/Controller/something/nothing/Action
</code>```

Edit

If {variant} doesn't have a pattern, then I don't think you can use regular expressions. Otherwise, Routing wasn't designed like this.

If you want more than one parameter to be variable, use more than one reqular expression

```<code>routes.MapRoute(
    "Title",
    "Controller/{something}/{variant}/Action",
    new { controller = "Controller", action = "Action" },
    new { variant = @"something\d+", something = @"(something|somethinglese)" }
);
</code>```

If you need {something} to be optional, I can't quite remember, but you might need to move it to the last parameter and change the route to:

```<code>    routes.MapRoute(
    "Title",
    "Controller/{variant}/Action/{something}",
    new { controller = "Controller", action = "Action", something = UrlParameter.Optional },
    new { variant = @"something\d+", something = @"(something|somethinglese)" }
);
</code>```

Title: Matching ASP.NET MVC routes across /

Body:
I know that when there is a route of the form

Alpha/Bravo/{Charlie}

and another of the form

Alpha/Bravo/Delta/{Echo}

the first route will match everything for both routes, because Delta/{Echo} is accepted as {Charlie}. Although this can be a pain when organizing routes, it can also be useful for the purpose of simplicity. I would like to be able to use this concept in the middle of a route string. I would like to make something like

Alpha/{Bravo}/Charlie

match URLs of the form

Alpha/bravo/Charlie

AND

Alpha/bravo/bravo2/Charlie

Is there a way to do this?

Body:
Use a regular expression route. Something like the following could match the {variant} parameter with 1 or more trailing digits

routes.MapRoute(
    "Title",
    "Controller/something/{variant}/Action",
    new { controller = "Controller", action = "Action" },
    new { variant = @"something\d+" }
);

Your route looks a little odd (maybe it's missing some curly braces), but my answer describes how you could use regular expressions for a number of parameters in your route.

With your exact route, Controller/something/{variant}/Action (again, this is odd), my mapped route would catch requests like:

/Controller/something/something123/Action
/Controller/something/something1/Action

But not

/Controller/something/somethingelse/Action
/Controller/something/nothing/Action

Edit

If {variant} doesn't have a pattern, then I don't think you can use regular expressions. Otherwise, Routing wasn't designed like this.

If you want more than one parameter to be variable, use more than one reqular expression

routes.MapRoute(
    "Title",
    "Controller/{something}/{variant}/Action",
    new { controller = "Controller", action = "Action" },
    new { variant = @"something\d+", something = @"(something|somethinglese)" }
);

If you need {something} to be optional, I can't quite remember, but you might need to move it to the last parameter and change the route to:

    routes.MapRoute(
    "Title",
    "Controller/{variant}/Action/{something}",
    new { controller = "Controller", action = "Action", something = UrlParameter.Optional },
    new { variant = @"something\d+", something = @"(something|somethinglese)" }
);


问:
How do I do a forward declaration of a struct with a typename?
I am trying to do a forward declaration of a struct in c++ that has a typename. Something like this is entirely valid:

```<code>typedef struct foo foo;

struct foo{
    int f;
};
</code>```

My struct just instead has a typename, so I tried this:

```<code>template <typename T>
typedef struct mV<T> mV;

template <typename T>
struct mV{
   //contents of struct
};
</code>```

However, I then get the errors a typedef cannot be a template, explicit specialization of undeclared template struct and redefinition of 'mV' as different kind of symbol. How can I go about fixing that?

答:
You're describing a forward- declaration . (A future is something completely different in modern C++).

typedef aliasing structure tags is not needed, and rarely desired, in C++. Instead you simply declare the class type and be done with it.

```<code>// typedef struct mV mV;  // not this
struct mV;                // instead this
</code>```

The same goes for templates

```<code>template<class T>
struct mV;
</code>```

If you need/want to attach an alias to your template type, you still can do so via using

```<code>template<class T>
struct mV;

template<class T>
using MyAliasNameHere = mV<T>;
</code>```

Armed with all of that, and heading off what I surmise you'll be discovering in short order, you'll probably need to read this as well: Why can templates only be implemented in header files?. Something tells me that's about to become highly relevant.

Body:
I am trying to do a forward declaration of a struct in c++ that has a typename. Something like this is entirely valid:

typedef struct foo foo;

struct foo{
    int f;
};

My struct just instead has a typename, so I tried this:

template <typename T>
typedef struct mV<T> mV;

template <typename T>
struct mV{
   //contents of struct
};

However, I then get the errors a typedef cannot be a template, explicit specialization of undeclared template struct and redefinition of 'mV' as different kind of symbol. How can I go about fixing that?

Body:
You're describing a forward- declaration . (A future is something completely different in modern C++).

typedef aliasing structure tags is not needed, and rarely desired, in C++. Instead you simply declare the class type and be done with it.

// typedef struct mV mV;  // not this
struct mV;                // instead this

The same goes for templates

template<class T>
struct mV;

If you need/want to attach an alias to your template type, you still can do so via using

template<class T>
struct mV;

template<class T>
using MyAliasNameHere = mV<T>;

Armed with all of that, and heading off what I surmise you'll be discovering in short order, you'll probably need to read this as well: Why can templates only be implemented in header files?. Something tells me that's about to become highly relevant.


问:
In a list of lists, how can I find the mean of the values for each subindex?
I want to find the average of each index in a list of lists. Say I have this:

```<code>import statistics

my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]
</code>```

I want to find the average of each interior list index, so:

for index 0, I would have the value of (1 + 4 + 7 + 10)/4

for index 1, I would have the value of (2 + 5 + 8 + 11)/4

for index 2, I would have the value of (3 + 9)/2

and so on. How can I do this? Note that I do not need to save the values, just print them as they are computed.

答:
You can use the package pandas to achieve your goal.</p>
```<code>#import pandas
import pandas as pd
#you list
my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]
#Create a DataFrame from your list
df = pd.DataFrame(my_list)
#mean for each row
df.mean()

</code>```

Body:
I want to find the average of each index in a list of lists. Say I have this:

import statistics

my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]

I want to find the average of each interior list index, so:

for index 0, I would have the value of (1 + 4 + 7 + 10)/4

for index 1, I would have the value of (2 + 5 + 8 + 11)/4

for index 2, I would have the value of (3 + 9)/2

and so on. How can I do this? Note that I do not need to save the values, just print them as they are computed.

Body:
You can use the package pandas to achieve your goal.

#import pandas
import pandas as pd
#you list
my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]
#Create a DataFrame from your list
df = pd.DataFrame(my_list)
#mean for each row
df.mean()


问:
SwiftUI decoding JSON from API
I know there are already some articles regarding this issue, but I could not find anything related to my JSON.

This is how my JSON likes like:

```<code>{
  "message": {
    "affenpinscher": [],
    "african": [],
    "airedale": [],
    "akita": [],
    "appenzeller": [],
    "australian": [
      "shepherd"
    ],
    "basenji": []
  },
  "status: "succes"
}
</code>```

So, if I understand it correctly it is dictionary because it starts with {, but what are the things inside the "message"?

This is my Dog.swift class where I am re-writing the JSON, but I am not sure if it is correct:

```<code>class Dog: Decodable, Identifiable {

    var message: Message?
    var status: String?
}

struct Message: Decodable {

    var affenpinscher: [String:[String]]?
    var african: [String]?
    var airedale: [String]?
    var akita: [String]?
    var appenzeller: [String]?
    var australian: [String]?
    var basenji: [String]?
}
</code>```

As you can see in the first value I was trying to play with data types, but no success.

I am decoding and parsing JSON here:

```<code>class ContentModel: ObservableObject {

    @Published var dogs = Message()

    init() {
        getDogs()
    }

    func getDogs(){

        // Create URL
        let urlString = Constants.apiUrl
        let url = URL(string: urlString)

        if let url = url {
            // Create URL request
            var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
            request.httpMethod = "GET"

            // Get URLSession
            let session = URLSession.shared

            // Create Data Task
            let dataTask = session.dataTask(with: request) { (data, response, error) in
                // Check that there is not an error
                if error == nil {

                    do {
                        // Parse JSON
                        let decoder = JSONDecoder()
                        let result = try decoder.decode(Dog.self, from: data!)
                        print(result)

                        // Assign result to the dogs property
                        DispatchQueue.main.async {
                            self.dogs = result.message!
                        }
                    } catch {
                        print(error)
                    }
                }
            }

            // Start the Data Task
            dataTask.resume()
        }
    }

}
</code>```

And here I would love to iterate through it eventually, which I also have no idea how to do it:

```<code>struct ContentView: View {

    @EnvironmentObject var model: ContentModel

    var body: some View {
        NavigationView {
            ScrollView {
                LazyVStack {
                    if model.dogs != nil {
//                        ForEach(Array(model.dogs.keys), id: \.self) { d in
//                            Text(d)
//                        }
                    }
                }
                .navigationTitle("All Dogs")
            }

        }
    }
}
</code>```

What can I try next to resolve this?

答:
Using the native Swift approach that @vadian answered is a much lighter weight solution, but if you work with JSON often I'd recommend using SwiftyJSON.

You can parse the URL data task response into a Swifty json object like so:

import SwiftyJSON

guard let data = data, let json = try? JSON(data: data) else {
    return
}

// Make sure the json fetch was successful
if json["status"].stringValue != "success" {
   return
}

```
<p>Then you can access the message object safely without the verbosity of using Decodable. Here the message is parsed into an array of dog structs:</p>
<pre class="lang-swift prettyprint-override"><code>struct Dog {
    let name : String
    let types : [String]
}

var dogs: [Dog] = []

/// Load the docs into an array
for (name, typesJson) in json["message"].dictionaryValue {
    dogs.append(Dog(name: name, types: typesJson.arrayValue.map { $0.stringValue }))
}

print("dogs", dogs)
</code>```

Title: SwiftUI decoding JSON from API

Body:
I know there are already some articles regarding this issue, but I could not find anything related to my JSON.

This is how my JSON likes like:

{
  "message": {
    "affenpinscher": [],
    "african": [],
    "airedale": [],
    "akita": [],
    "appenzeller": [],
    "australian": [
      "shepherd"
    ],
    "basenji": []
  },
  "status: "succes"
}

So, if I understand it correctly it is dictionary because it starts with {, but what are the things inside the "message"?

This is my Dog.swift class where I am re-writing the JSON, but I am not sure if it is correct:

class Dog: Decodable, Identifiable {

    var message: Message?
    var status: String?
}

struct Message: Decodable {

    var affenpinscher: [String:[String]]?
    var african: [String]?
    var airedale: [String]?
    var akita: [String]?
    var appenzeller: [String]?
    var australian: [String]?
    var basenji: [String]?
}

As you can see in the first value I was trying to play with data types, but no success.

I am decoding and parsing JSON here:

class ContentModel: ObservableObject {

    @Published var dogs = Message()

    init() {
        getDogs()
    }

    func getDogs(){

        // Create URL
        let urlString = Constants.apiUrl
        let url = URL(string: urlString)

        if let url = url {
            // Create URL request
            var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
            request.httpMethod = "GET"

            // Get URLSession
            let session = URLSession.shared

            // Create Data Task
            let dataTask = session.dataTask(with: request) { (data, response, error) in
                // Check that there is not an error
                if error == nil {

                    do {
                        // Parse JSON
                        let decoder = JSONDecoder()
                        let result = try decoder.decode(Dog.self, from: data!)
                        print(result)

                        // Assign result to the dogs property
                        DispatchQueue.main.async {
                            self.dogs = result.message!
                        }
                    } catch {
                        print(error)
                    }
                }
            }

            // Start the Data Task
            dataTask.resume()
        }
    }

}

And here I would love to iterate through it eventually, which I also have no idea how to do it:

struct ContentView: View {

    @EnvironmentObject var model: ContentModel

    var body: some View {
        NavigationView {
            ScrollView {
                LazyVStack {
                    if model.dogs != nil {
//                        ForEach(Array(model.dogs.keys), id: \.self) { d in
//                            Text(d)
//                        }
                    }
                }
                .navigationTitle("All Dogs")
            }

        }
    }
}

What can I try next to resolve this?

Body:
Using the native Swift approach that @vadian answered is a much lighter weight solution, but if you work with JSON often I'd recommend using SwiftyJSON.

You can parse the URL data task response into a Swifty json object like so:

import SwiftyJSON

guard let data = data, let json = try? JSON(data: data) else {
    return
}

// Make sure the json fetch was successful
if json["status"].stringValue != "success" {
   return
}

Then you can access the message object safely without the verbosity of using Decodable. Here the message is parsed into an array of dog structs:

struct Dog {
    let name : String
    let types : [String]
}

var dogs: [Dog] = []

/// Load the docs into an array
for (name, typesJson) in json["message"].dictionaryValue {
    dogs.append(Dog(name: name, types: typesJson.arrayValue.map { $0.stringValue }))
}

print("dogs", dogs)


问:
Replacing NaN values in timeseries Pandas dataframe with mean values
I have a dataframe that has 2 columns, date and values.
I want to replace NaN values in the dataframe with mean values, but with specific condition.

```<code>import pandas as pd

dates = ["2022-02-01", "2022-02-02", "2022-02-03", "2022-02-04", "2022-02-05", "2022-02-06",
         "2021-02-01", "2021-02-02", "2021-02-03", "2021-02-04", "2021-02-05", "2021-02-06"]

values = [3,1,6,2,5,7,3, None, 3, None, None, None]

df = pd.DataFrame({"date": dates,
                   "values": values
                    })

df = df.sort_values(by = 'date', ascending = False)
print(df)

          date  values
0   2022-02-06     7.0
1   2022-02-05     5.0
2   2022-02-04     2.0
3   2022-02-03     6.0
4   2022-02-02     1.0
5   2022-02-01     3.0
6   2021-02-06     NaN
7   2021-02-05     NaN
8   2021-02-04     NaN
9   2021-02-03     3.0
10  2021-02-02     NaN
11  2021-02-01     3.0
</code>```

NaN values should be replaced with mean value of the values from the same period for the year that has that value (+/- 1 day).

Value for 2021-02-04 should be:

```<code>(6 + 2 + 5) / 3 = 4.33
</code>```

Because dates "2022-02-03", "2022-02-04", "2022-02-05" have values of 6,2 and 5.

I know how to fill nan values with just mean value, but I do not know how to solve the problem of +/- one day.

答:
Really hard to say what exactly you want to do, but given your data:

import pandas as pd
import numpy as np

dates = ["2022-02-01", "2022-02-02", "2022-02-03", "2022-02-04", "2022-02-05", "2022-02-06",
         "2021-02-01", "2021-02-02", "2021-02-03", "2021-02-04", "2021-02-05", "2021-02-06"]

values = [3,1,6,2,5,7,3, None, 3, None, None, None]

df = pd.DataFrame({"date": dates,
                   "values": values
                    })
df = df.sort_values(by = 'date', ascending = False).reset_index(drop=True)
```
<p>You can try something like this:</p>
<pre class="lang-py prettyprint-override"><code>def process_data(dates, values):
  new_values = np.copy(values)
  indices = np.argwhere(np.isnan(values))
  dates_without_year = ['-'.join(d.split('-')[1:]) for d in dates.astype(str)]
  for i, d in enumerate(dates):
    if i in indices:
      possible_dates = np.array(pd.Series(pd.date_range(d - pd.Timedelta(days=1), d + pd.Timedelta(days=1))), dtype='datetime64[D]')
      possible_dates = ['-'.join(d.split('-')[1:]) for d in possible_dates.astype(str)]
      mean_values = values[np.argwhere(np.isin(dates_without_year, possible_dates))]
      new_values[i] = np.mean(mean_values[~np.isnan(mean_values)])
  return new_values
df['values'] = process_data(np.array(df['date'].values, dtype='datetime64[D]'), df['values'].to_numpy())
</code>```
```<code>          date    values
0   2022-02-06  7.000000
1   2022-02-05  5.000000
2   2022-02-04  2.000000
3   2022-02-03  6.000000
4   2022-02-02  1.000000
5   2022-02-01  3.000000
6   2021-02-06  6.000000
7   2021-02-05  4.666667
8   2021-02-04  4.000000
9   2021-02-03  3.000000
10  2021-02-02  3.200000
11  2021-02-01  3.000000
</code>```

Take a close look at, for example, 2021-02-04 which had a NaN value. I disregard the years (as mentioned in the comments) and just look at the months and days resulting in (6 + 2 + 5 + 3) / 4 = 4.0, since "2022-02-03", "2022-02-04", "2022-02-05", and "2021-02-03" have values of 6, 2, 5, and 3.

Body:
I have a dataframe that has 2 columns, date and values.
I want to replace NaN values in the dataframe with mean values, but with specific condition.

import pandas as pd

dates = ["2022-02-01", "2022-02-02", "2022-02-03", "2022-02-04", "2022-02-05", "2022-02-06",
         "2021-02-01", "2021-02-02", "2021-02-03", "2021-02-04", "2021-02-05", "2021-02-06"]

values = [3,1,6,2,5,7,3, None, 3, None, None, None]

df = pd.DataFrame({"date": dates,
                   "values": values
                    })

df = df.sort_values(by = 'date', ascending = False)
print(df)

          date  values
0   2022-02-06     7.0
1   2022-02-05     5.0
2   2022-02-04     2.0
3   2022-02-03     6.0
4   2022-02-02     1.0
5   2022-02-01     3.0
6   2021-02-06     NaN
7   2021-02-05     NaN
8   2021-02-04     NaN
9   2021-02-03     3.0
10  2021-02-02     NaN
11  2021-02-01     3.0

NaN values should be replaced with mean value of the values from the same period for the year that has that value (+/- 1 day).

Value for 2021-02-04 should be:

(6 + 2 + 5) / 3 = 4.33

Because dates "2022-02-03", "2022-02-04", "2022-02-05" have values of 6,2 and 5.

I know how to fill nan values with just mean value, but I do not know how to solve the problem of +/- one day.

Body:
Really hard to say what exactly you want to do, but given your data:

import pandas as pd
import numpy as np

dates = ["2022-02-01", "2022-02-02", "2022-02-03", "2022-02-04", "2022-02-05", "2022-02-06",
         "2021-02-01", "2021-02-02", "2021-02-03", "2021-02-04", "2021-02-05", "2021-02-06"]

values = [3,1,6,2,5,7,3, None, 3, None, None, None]

df = pd.DataFrame({"date": dates,
                   "values": values
                    })
df = df.sort_values(by = 'date', ascending = False).reset_index(drop=True)

You can try something like this:

def process_data(dates, values):
  new_values = np.copy(values)
  indices = np.argwhere(np.isnan(values))
  dates_without_year = ['-'.join(d.split('-')[1:]) for d in dates.astype(str)]
  for i, d in enumerate(dates):
    if i in indices:
      possible_dates = np.array(pd.Series(pd.date_range(d - pd.Timedelta(days=1), d + pd.Timedelta(days=1))), dtype='datetime64[D]')
      possible_dates = ['-'.join(d.split('-')[1:]) for d in possible_dates.astype(str)]
      mean_values = values[np.argwhere(np.isin(dates_without_year, possible_dates))]
      new_values[i] = np.mean(mean_values[~np.isnan(mean_values)])
  return new_values
df['values'] = process_data(np.array(df['date'].values, dtype='datetime64[D]'), df['values'].to_numpy())

          date    values
0   2022-02-06  7.000000
1   2022-02-05  5.000000
2   2022-02-04  2.000000
3   2022-02-03  6.000000
4   2022-02-02  1.000000
5   2022-02-01  3.000000
6   2021-02-06  6.000000
7   2021-02-05  4.666667
8   2021-02-04  4.000000
9   2021-02-03  3.000000
10  2021-02-02  3.200000
11  2021-02-01  3.000000

Take a close look at, for example, 2021-02-04 which had a NaN value. I disregard the years (as mentioned in the comments) and just look at the months and days resulting in (6 + 2 + 5 + 3) / 4 = 4.0, since "2022-02-03", "2022-02-04", "2022-02-05", and "2021-02-03" have values of 6, 2, 5, and 3.


问:
Is there a recursion that checks whether the matrix diagonally has a sequence of alphabetic letters
I got a homework assignment, I have to find a recursive function that gets a 2D matrix and the number of rows in a matrix and returns true / false If the diagonal of the matrix has a sequence of letters a b c,

Can not think of a solution

```<code>public static void main(String[] args) {
    char[][] mat = new char[5][5];

    for (int i = 0; i < mat.length; i++) {
        for (int j = 0; j < mat[i].length; j++)
            mat[i][j] = (char) (int) ((Math.random() * 26) + 'a');
    }

    for (int i=0 ; i <mat.length ; i++)
        mat[i][i] = (char)('a' + i);
    //mat[2][2] = 'b';

    for (int i = 0; i < mat.length; i++) {
        for (int j = 0; j < mat[i].length; j++)
            System.out.print(mat[i][j] + " ");
        System.out.println();
    }

    System.out.println(isDiagonalLettersSequence(mat, mat.length));

}[Here are two examples that I hope will help me explain myself][1]
</code>```

https://i.stack.imgur.com/Z6qmn.png

答:
In the main function:

```<code>String[][] arr =  {     {"a","e","d"},
                        {"h","b","c"},
                        {"f","f","c"}};

    if(diagonal(arr, 0).equals("abc"))
        System.out.print("true");
</code>```

And the global recursive function should be:

```<code>public static String diagonal(String[][] arr, int i) {
    if(i == arr.length - 1)
        return arr[i][i];
    return arr[i][i] + diagonal(arr, i + 1);
}
</code>```

Body:
I got a homework assignment, I have to find a recursive function that gets a 2D matrix and the number of rows in a matrix and returns true / false If the diagonal of the matrix has a sequence of letters a b c,

Can not think of a solution

public static void main(String[] args) {
    char[][] mat = new char[5][5];

    for (int i = 0; i < mat.length; i++) {
        for (int j = 0; j < mat[i].length; j++)
            mat[i][j] = (char) (int) ((Math.random() * 26) + 'a');
    }

    for (int i=0 ; i <mat.length ; i++)
        mat[i][i] = (char)('a' + i);
    //mat[2][2] = 'b';

    for (int i = 0; i < mat.length; i++) {
        for (int j = 0; j < mat[i].length; j++)
            System.out.print(mat[i][j] + " ");
        System.out.println();
    }

    System.out.println(isDiagonalLettersSequence(mat, mat.length));

}[Here are two examples that I hope will help me explain myself][1]

https://i.stack.imgur.com/Z6qmn.png

Body:
In the main function:

String[][] arr =  {     {"a","e","d"},
                        {"h","b","c"},
                        {"f","f","c"}};

    if(diagonal(arr, 0).equals("abc"))
        System.out.print("true");

And the global recursive function should be:

public static String diagonal(String[][] arr, int i) {
    if(i == arr.length - 1)
        return arr[i][i];
    return arr[i][i] + diagonal(arr, i + 1);
}


问:
Do all STL containers return their elements by reference?
I am learning STL these days and I was wondering if STL containers return by reference?

e.g:

```<code>vector.first();
map[key];
*vector.begin();
Or any possible return that ends with element (or value type) of container
</code>```

e.g:

```<code>std::vector<int> elements;
elements.push_back(20);
elements[0]=60; // this will also change the value
elements.front() = 23; // even the functions also behave same way like subscript operator
</code>```

is this the case with all containers? or there are some points to consider which I didn't show?

答:
Returning the added element, or the container in container member functions is not possible in a safe way. STL containers mostly provide the "strong guarantee". Returning the manipulated element or the container would make it impossible to provide the strong guarantee (it would only provide the "basic guarantee"). An explanation of these terms is provided at boost's website on Exception-Safety in Generic Components. See below from Boost's website.

The basic guarantee: that the invariants of the component are preserved, and no resources are leaked.

The strong guarantee: that the operation has either completed successfully or thrown an exception, leaving the program state exactly as it was before the operation started.

The no-throw guarantee: that the operation will not throw an exception.

Back to the topic: Per this previous SO answer, the reason behind this is, that returning something could possibly invoke an copy-constructor, which may throw an exception. But the function already exited, so it fulfilled its main task successfully, but still threw an exception, which is a violation of the strong guarantee. You maybe think: "Well then lets return by reference!", while this sounds like a good solution, its not perfectly safe either. Consider following example:

```<code>MyClass bar = myvector.push_back(functionReturningMyClass()); // imagine push_back returns MyClass&
</code>```

Still, if the copy-assignment operator throws, we don't know if push_back succeeded or not, thus indirectly violating the strong-guarantee. Even though this is not a direct violation. Of course using MyClass& bar = //... instead would fix this issue, but it would be quite inconvenient, that a container might get into an indeterminate state, just because someone forgot a &.

A quite similar reasoning is behind the fact that std::stack::pop() does not return the popped value. Instead top() returns the topmost value in a safe way. after calling top, even when a copy-constructor, or a copy-assignment constructor throws, you still know that the stack is unchanged.

Body:
I am learning STL these days and I was wondering if STL containers return by reference?

e.g:

vector.first();
map[key];
*vector.begin();
Or any possible return that ends with element (or value type) of container

e.g:

std::vector<int> elements;
elements.push_back(20);
elements[0]=60; // this will also change the value
elements.front() = 23; // even the functions also behave same way like subscript operator

is this the case with all containers? or there are some points to consider which I didn't show?

Body:
Returning the added element, or the container in container member functions is not possible in a safe way. STL containers mostly provide the "strong guarantee". Returning the manipulated element or the container would make it impossible to provide the strong guarantee (it would only provide the "basic guarantee"). An explanation of these terms is provided at boost's website on Exception-Safety in Generic Components. See below from Boost's website.

The basic guarantee: that the invariants of the component are preserved, and no resources are leaked.

The strong guarantee: that the operation has either completed successfully or thrown an exception, leaving the program state exactly as it was before the operation started.

The no-throw guarantee: that the operation will not throw an exception.

Back to the topic: Per this previous SO answer, the reason behind this is, that returning something could possibly invoke an copy-constructor, which may throw an exception. But the function already exited, so it fulfilled its main task successfully, but still threw an exception, which is a violation of the strong guarantee. You maybe think: "Well then lets return by reference!", while this sounds like a good solution, its not perfectly safe either. Consider following example:

MyClass bar = myvector.push_back(functionReturningMyClass()); // imagine push_back returns MyClass&

Still, if the copy-assignment operator throws, we don't know if push_back succeeded or not, thus indirectly violating the strong-guarantee. Even though this is not a direct violation. Of course using MyClass& bar = //... instead would fix this issue, but it would be quite inconvenient, that a container might get into an indeterminate state, just because someone forgot a &.

A quite similar reasoning is behind the fact that std::stack::pop() does not return the popped value. Instead top() returns the topmost value in a safe way. after calling top, even when a copy-constructor, or a copy-assignment constructor throws, you still know that the stack is unchanged.


问:
How to sum from a list of reference in Excel?
I have a list of reference in Excel the content of which I want to sum up.
How would I do that ?

Let say I want to sum up the content of B1 and C2 using the list in A1:A2 ? so I get the result 11 ?

A
B
C

1
B1
8
0

2
C2
0
3

=sum(indirect(A1:A2)) ??

hum... find my answer asking the question ! Somehow that is working.

答:
Try,

```<code>=SUM(INDIRECT(A1&":"&A2))
</code>```

or,

```<code>=SUMPRODUCT(INDIRECT(A1&":"&A2))
</code>```

Body:
Try,

=SUM(INDIRECT(A1&":"&A2))

or,

=SUMPRODUCT(INDIRECT(A1&":"&A2))


问:
Import functions from another directory
I am running a python script (app.py) where I have to use two functions from another script (src.py), located inside another directory. The structure is the following:

```<code>Dir:
   Dir_1:
        __init__.py
        src.py
   Dir_2:
        app.py
</code>```

I am using, in app.py, the following lines:

```<code>from pathlib import Path
PROJECT = Path(__file__).resolve().parent.parent
PROJECT = PROJECT/'Dir_1'

import sys
sys.path.insert(1, PROJECT)
from src import odd_all, even_all
</code>```

to access to the functions odd_all, even_all declared inside src.py. However, I get the error: ModuleNotFoundError: No module named 'src'.

How could I solve this problem?

答:
You can use the sys.path.append() to append the path of your file to the system's path:

```<code>import sys
sys.path.append('/.../Dir/Dir_1')

from src import odd_all, even_all
</code>```

Title: Import functions from another directory

Body:
I am running a python script (app.py) where I have to use two functions from another script (src.py), located inside another directory. The structure is the following:

Dir:
   Dir_1:
        __init__.py
        src.py
   Dir_2:
        app.py

I am using, in app.py, the following lines:

from pathlib import Path
PROJECT = Path(__file__).resolve().parent.parent
PROJECT = PROJECT/'Dir_1'

import sys
sys.path.insert(1, PROJECT)
from src import odd_all, even_all

to access to the functions odd_all, even_all declared inside src.py. However, I get the error: ModuleNotFoundError: No module named 'src'.

How could I solve this problem?

Body:
You can use the sys.path.append() to append the path of your file to the system's path:

import sys
sys.path.append('/.../Dir/Dir_1')

from src import odd_all, even_all


问:
How to check if a list exist inside another list
So I have a list a that contain the string "ab" and another list b that contain a list that contain the string "ab". So it look something like this:

```<code>var a = ["ab"]
var b = [["ab"]]
</code>```

How can I check if a is in b. I have try using b.includes(a) that result in a false and I also have try b.indexOf(a) which also return false. The way that I currently use is this:

```<code>var flag = false
var a = ["ab"]
var b = [["ab"]]

b.forEach((i) => {
    if (i.join("") == a.join("")) flag = true
})
console.log(flag)
</code>```

Is there like a shorter way?

Thanks y'all.

答:
If you have references you can do as follows:

```<code>var a = ["ab"];
var b = [a];
b.includes(a); // true
</code>```

Otherwise you need to convert those arrays to strings and compare those as others suggested or compare inside values of those nested arrays one by one because:

```<code>['a'] != ['a'] // this is true because those are 2 different arrays
</code>```

Body:
So I have a list a that contain the string "ab" and another list b that contain a list that contain the string "ab". So it look something like this:

var a = ["ab"]
var b = [["ab"]]

How can I check if a is in b. I have try using b.includes(a) that result in a false and I also have try b.indexOf(a) which also return false. The way that I currently use is this:

var flag = false
var a = ["ab"]
var b = [["ab"]]

b.forEach((i) => {
    if (i.join("") == a.join("")) flag = true
})
console.log(flag)

Is there like a shorter way?

Thanks y'all.

Body:
If you have references you can do as follows:

var a = ["ab"];
var b = [a];
b.includes(a); // true

Otherwise you need to convert those arrays to strings and compare those as others suggested or compare inside values of those nested arrays one by one because:

['a'] != ['a'] // this is true because those are 2 different arrays


答:
If you prefer vanilla python, you can try the following:

```<code>my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]

d = {}

for elem in my_list:
    for i in range(len(elem)):
        if i in d:
            d[i].append(elem[i])
        else:
            d[i] = [elem[i]]

for k,v in d.items():
    print(f'The average of idx {k} is {sum(v) / len(v)}')

</code>```

Output:

```<code>The average of idx 0 is 5.5
The average of idx 1 is 6.5
The average of idx 2 is 6.0
</code>```

Title: In a list of lists, how can I find the mean of the values for each subindex?

Body:
If you prefer vanilla python, you can try the following:

my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]

d = {}

for elem in my_list:
    for i in range(len(elem)):
        if i in d:
            d[i].append(elem[i])
        else:
            d[i] = [elem[i]]

for k,v in d.items():
    print(f'The average of idx {k} is {sum(v) / len(v)}')

Output:

The average of idx 0 is 5.5
The average of idx 1 is 6.5
The average of idx 2 is 6.0


问:
How to retrieve data from Future object properly?
I'm using shared preferences. I want to get the list of strings, but for some reason it's always a null though it shouldn't be. I think I'm making a mistake in asynchronous stuff. Can somebody help me? With explanation if possible.</p>
```<code>List<String> getSaved() {
  List<String>? items;
  Future<SharedPreferences> prefs = SharedPreferences.getInstance();
  prefs.then((prefs) async {
    items = prefs.getStringList('saved');
  });
  // SharedPreferences prefs = await SharedPreferences.getInstance();
  // items = prefs.getStringList('saved');
  return items ?? [];
}
</code>```

答:
Because you want the result when the future completed your function should be of type Future<List<String>> and you can use then or await knowing that items should be of the same type too

```<code> Future<List<String>> getSaved() async {
       List<String>? items;
       SharedPreferences prefs = await SharedPreferences.getInstance();
         items = prefs.getStringList('saved');
       // SharedPreferences prefs = await SharedPreferences.getInstance();
       // items = prefs.getStringList('saved');
       return items ?? [];
     }
</code>```

Body:
I'm using shared preferences. I want to get the list of strings, but for some reason it's always a null though it shouldn't be. I think I'm making a mistake in asynchronous stuff. Can somebody help me? With explanation if possible.

List<String> getSaved() {
  List<String>? items;
  Future<SharedPreferences> prefs = SharedPreferences.getInstance();
  prefs.then((prefs) async {
    items = prefs.getStringList('saved');
  });
  // SharedPreferences prefs = await SharedPreferences.getInstance();
  // items = prefs.getStringList('saved');
  return items ?? [];
}

Body:
Because you want the result when the future completed your function should be of type Future<List<String>> and you can use then or await knowing that items should be of the same type too

 Future<List<String>> getSaved() async {
       List<String>? items;
       SharedPreferences prefs = await SharedPreferences.getInstance();
         items = prefs.getStringList('saved');
       // SharedPreferences prefs = await SharedPreferences.getInstance();
       // items = prefs.getStringList('saved');
       return items ?? [];
     }