问:
Kotlin Firebase Realtime database transaction errors
I have the following code

```<code>   database.child("users").child(this.invitedBy).runTransaction(object : Transaction.Handler {
                override fun doTransaction(mutableData: MutableData): Transaction.Result {
                    val u = mutableData.getValue(User::class.java)
                        ?: return Transaction.success(mutableData)

                    if (u.numReferrals == null || u.referralEarning == null) {
                        // Unstar the post and remove self from stars
                        u.numReferrals = 1
                        u.referralEarning = 1;
                    } else {
                        // Star the post and add self to stars
                        u.numReferrals = u.numReferrals!! + 1
                        u.referralEarning = u.referralEarning!! + 1;
                    }

                    // Set value and report transaction success
                    mutableData.value = u
                    return Transaction.success(mutableData)
                }

                override fun onComplete(
                    databaseError: DatabaseError?,
                    committed: Boolean,
                    currentData: DataSnapshot?
                ) {
                    // Transaction completed
                    Log.d("MUser", "postTransaction:onComplete:" + databaseError!!)
                }
            })
</code>```

When I run it, it gives me the following error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.test.test, PID: 5375
    kotlin.KotlinNullPointerException
        at com.test.test.MUser$setReferral$1.onComplete(MUser.kt:229)
        at com.google.firebase.database.core.Repo$16$1.run(com.google.firebase:firebase-database@@19.2.1:1006)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
W/System.err: kotlin.KotlinNullPointerException
W/System.err:     at com.test.test.MUser$setReferral$1.onComplete(MUser.kt:229)
        at com.google.firebase.database.core.Repo$16$1.run(com.google.firebase:firebase-database@@19.2.1:1006)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
</code>```

Here's my User.kt

```<code>import com.google.firebase.database.IgnoreExtraProperties

// [START rtdb_user_class]
@IgnoreExtraProperties
data class User(
    var id: String = "",
    var name: String = "",
    var email: String = "",
    var userReads: Int? = 0,
    var userPlays: Int? = 0,
    var userWatches: Int? = 0,
    var paidDate : Int? = 0,
    var endPaidDate : Int? = 0,
    var paidStatus : String? = "",
    var paymentMethod : String? = "",
    var planid : String? = "",
    var firebaseUid : String? = "",
    var referralEarning : Int? = 0,
    var numReferrals : Int? = 0
)
</code>```

What am I doing wrong?

答:
Please take a look at onComplete method:

```<code>override fun onComplete(
                    databaseError: DatabaseError?,
                    committed: Boolean,
                    currentData: DataSnapshot?
                ) {
                    // Transaction completed
                    Log.d("MUser", "postTransaction:onComplete:" + databaseError!!)
                }
</code>```

You are using !! operator when referencing databaseError parameter, but it can be null, so you can't use !!. To avoid that Exception just remove !! operator:

```<code>Log.d("MUser", "postTransaction:onComplete:" + databaseError)
</code>```

databaseError: DatabaseError? - it is a nullable object (nullable objects marked with ? operator), you can't use !! operator on it if you are not 100% sure that it is not null.

Also you can use ? operator on nullable objects to call its methods or properties, e.g.:

```<code>Log.d("MUser", "postTransaction:onComplete:" + databaseError?.getMessage())
</code>```

More info about Null Safety in Kotlin.

Body:
I have the following code

   database.child("users").child(this.invitedBy).runTransaction(object : Transaction.Handler {
                override fun doTransaction(mutableData: MutableData): Transaction.Result {
                    val u = mutableData.getValue(User::class.java)
                        ?: return Transaction.success(mutableData)

                    if (u.numReferrals == null || u.referralEarning == null) {
                        // Unstar the post and remove self from stars
                        u.numReferrals = 1
                        u.referralEarning = 1;
                    } else {
                        // Star the post and add self to stars
                        u.numReferrals = u.numReferrals!! + 1
                        u.referralEarning = u.referralEarning!! + 1;
                    }

                    // Set value and report transaction success
                    mutableData.value = u
                    return Transaction.success(mutableData)
                }

                override fun onComplete(
                    databaseError: DatabaseError?,
                    committed: Boolean,
                    currentData: DataSnapshot?
                ) {
                    // Transaction completed
                    Log.d("MUser", "postTransaction:onComplete:" + databaseError!!)
                }
            })

When I run it, it gives me the following error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.test.test, PID: 5375
    kotlin.KotlinNullPointerException
        at com.test.test.MUser$setReferral$1.onComplete(MUser.kt:229)
        at com.google.firebase.database.core.Repo$16$1.run(com.google.firebase:firebase-database@@19.2.1:1006)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
W/System.err: kotlin.KotlinNullPointerException
W/System.err:     at com.test.test.MUser$setReferral$1.onComplete(MUser.kt:229)
        at com.google.firebase.database.core.Repo$16$1.run(com.google.firebase:firebase-database@@19.2.1:1006)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)

Here's my User.kt

import com.google.firebase.database.IgnoreExtraProperties

// [START rtdb_user_class]
@IgnoreExtraProperties
data class User(
    var id: String = "",
    var name: String = "",
    var email: String = "",
    var userReads: Int? = 0,
    var userPlays: Int? = 0,
    var userWatches: Int? = 0,
    var paidDate : Int? = 0,
    var endPaidDate : Int? = 0,
    var paidStatus : String? = "",
    var paymentMethod : String? = "",
    var planid : String? = "",
    var firebaseUid : String? = "",
    var referralEarning : Int? = 0,
    var numReferrals : Int? = 0
)

What am I doing wrong?

Body:
Please take a look at onComplete method:

override fun onComplete(
                    databaseError: DatabaseError?,
                    committed: Boolean,
                    currentData: DataSnapshot?
                ) {
                    // Transaction completed
                    Log.d("MUser", "postTransaction:onComplete:" + databaseError!!)
                }

You are using !! operator when referencing databaseError parameter, but it can be null, so you can't use !!. To avoid that Exception just remove !! operator:

Log.d("MUser", "postTransaction:onComplete:" + databaseError)

databaseError: DatabaseError? - it is a nullable object (nullable objects marked with ? operator), you can't use !! operator on it if you are not 100% sure that it is not null.

Also you can use ? operator on nullable objects to call its methods or properties, e.g.:

Log.d("MUser", "postTransaction:onComplete:" + databaseError?.getMessage())

More info about Null Safety in Kotlin.


来源: stackexchange

问:
Change li tag color when making new todolist

const weather = document.querySelector(".js-weather");
const body = document.querySelector("body");
const weatherClock = document.querySelector(".clock");
const weatherGreetings = document.querySelector(".js-greetings");
const todolist = document.querySelector(".js-toDoList");
const li = todolist.querySelector("li");

function changeBlack() {
  console.log(li)
  weatherClock.classList.add("black");
  weatherGreetings.classList.add("black");
  weather.classList.add("black");
  li.classList.add('black');

}

function changeBg(imgweather) {
  const image = new Image();
  if (imgweather === "Clear") {
    image.src = `img/clear.jpg`;
    changeBlack();
  } else if (imgweather === "= Rain") {
    image.src = `img/Rain.jpg`;
  } else if (imgweather === "Clouds") {
    image.src = `img/Clouds.jpg`;
    changeBlack();
  } else if (imgweather === "Snow") {
    image.src = `img/Snow.jpg`;
    changeBlack();
  }
  image.classList.add("bgImage");
  body.prepend(image);
}

.black{
  color: black;
}
```

I want to change li tag color when making new li tag
so I add class black if I want to change black
but only one li tag change

when imgweather is Clear, I want to change all font color black because background color is white

答:
Instead of:

```<code>const li = todolist.querySelector("li");
</code>```

use querySelectorAll to select all list items:

```<code>const li = todolist.querySelectorAll("li");
</code>```

Then you need to loop over all of your list elements inside of your changeblack() function:

```<code>for(var i = 0; i < li.length; i++){
  li[i].classList.add('black');
}
</code>```

or if you prefer arrow functions:

```<code>li.forEach((item) => {
  item.classList.add('black');
});
</code>```

Updated: forgot to mention querySelectorAll

ContentLicense: CC BY-SA 4.0

Body:
const weather = document.querySelector(".js-weather");
const body = document.querySelector("body");
const weatherClock = document.querySelector(".clock");
const weatherGreetings = document.querySelector(".js-greetings");
const todolist = document.querySelector(".js-toDoList");
const li = todolist.querySelector("li");

function changeBlack() {
  console.log(li)
  weatherClock.classList.add("black");
  weatherGreetings.classList.add("black");
  weather.classList.add("black");
  li.classList.add('black');

}

function changeBg(imgweather) {
  const image = new Image();
  if (imgweather === "Clear") {
    image.src = `img/clear.jpg`;
    changeBlack();
  } else if (imgweather === "= Rain") {
    image.src = `img/Rain.jpg`;
  } else if (imgweather === "Clouds") {
    image.src = `img/Clouds.jpg`;
    changeBlack();
  } else if (imgweather === "Snow") {
    image.src = `img/Snow.jpg`;
    changeBlack();
  }
  image.classList.add("bgImage");
  body.prepend(image);
}

.black{
  color: black;
}

I want to change li tag color when making new li tag
so I add class black if I want to change black
but only one li tag change

when imgweather is Clear, I want to change all font color black because background color is white

Body:
Instead of:

const li = todolist.querySelector("li");

use querySelectorAll to select all list items:

const li = todolist.querySelectorAll("li");

Then you need to loop over all of your list elements inside of your changeblack() function:

for(var i = 0; i < li.length; i++){
  li[i].classList.add('black');
}

or if you prefer arrow functions:

li.forEach((item) => {
  item.classList.add('black');
});

Updated: forgot to mention querySelectorAll


问:
How to make chart from javascript be responsive inside of HTML div
I am having a hard time trying to make a google charts javascript chart responsive in my html page - the only way it seems to be working when trying to change screen size is to refresh the page. I am trying to make it so when you click and drag the window, the aspect changes accordingly to the screen size. But to no avail! Perhaps someone has encouncted this problem before or maybe it doesnt work for the charts? Thanks!

https://codepen.io/limtu/pen/QWyLGEX

```<code>      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
      <script type="text/javascript">
       google.charts.load('current', {'packages':['corechart']});
       google.charts.setOnLoadCallback(drawChart);

       function drawChart() {
       var queryString = encodeURIComponent('SELECT A, B');

       var query = new google.visualization.Query(
      'https://docs.google.com/spreadsheets/d/1dXP9yGEzNlmRxuSwCr2kyMM9CcS5hloIxKvef0RSa10/gviz/tq?
       gid=0&headers=1&tq=' + queryString);
       query.send(handleQueryResponse);

       };
       function handleQueryResponse(response) {
       if (response.isError()) {
       alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
        };

        var data = response.getDataTable();

        var high = ((data.getColumnRange(1).max));
        var low = (data.getColumnRange(1).min);
        var dif = high-low;
        var trail_percent = 0.1;
        var trail = (trail_percent*dif);
        var min_trail = 1
        var min_y = 0;
        trail = Math.max.apply(null, [trail,min_trail]);
        var max_price = high + trail;
        var min_price = low - trail;
        min_price = Math.max.apply(null, [min_price, min_y]);

        var options = {
        title: '1D',
        areaOpacity: 0.5,
        focusTarget: 'category',
         animation: {startup: true, duration: 100,easing: 'in'},
         crosshair: {trigger: 'both', orientation: 'vertical', opacity: 1, color : 'fcb247' },
         tooltip:{trigger:'both'},
         series: {0:{color: '#0173a3', visibleInLegend: false}},
         legend: {position: 'none'},

         hAxis: {title: '',
         format: 'HH:00',
         gridlines:{count : 4, color:'FFFFFF'}},

         vAxis: {minValue: min_price, maxValue: max_price,
         gridlines:{count : 4},minorGridlines:{interval:0}}
         };
         var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
         chart.draw(data, options);
         }
         </script>
         </head>
         <body>
         <div id="chart_div" style="width: 100%; height: 500px;"></div>
         </body>
</code>```

答:
you should use vm for widthand vh for height

can see this page

```<code> <div id="chart_div" style="width: 100vw; height: 100vh;"></div>
//for width and height 100%;

 <div id="chart_div" style="width: 50vw; height: 50vh;"></div>
//for width and height 50%;
</code>```

Body:
you should use vm for widthand vh for height

can see this page

 <div id="chart_div" style="width: 100vw; height: 100vh;"></div>
//for width and height 100%;

 <div id="chart_div" style="width: 50vw; height: 50vh;"></div>
//for width and height 50%;


问:
make site available only from given ip
Is it possible to set my entaire web application available only from given ip address ? Can I use global.asax or something to place the code only in one place and be able to remove this freely ?

Thanks for any hints

答:
you could create a HTTP Module for that and than register it inside web.config in case if you do not have access to your IIS.

HttpModule structure should look like as below;

```<code>namespace MyApp {

    public class MyModule : IHttpModule {

        public void Init(HttpApplication context) {

        }

        public void Dispose() {

        }

    }
}
</code>```

after you implement your logic inside Init event, you need to register the module inside web.config file  in order to execute it on every request;

```<code><configuration>
   <system.web>
      <httpModules>
         <add name="MyModule" type="MyApp.MyModule, MyApp" />
      </httpModules>
   </system.web>
</configuration>
</code>```

If you are on integrated mode of IIS 7 or 7.5, this registration should be done inside <system.webServer> tag of web.config

ContentLicense: CC BY-SA 3.0

Title: make site available only from given ip

Body:
you could create a HTTP Module for that and than register it inside web.config in case if you do not have access to your IIS.

HttpModule structure should look like as below;

namespace MyApp {

    public class MyModule : IHttpModule {

        public void Init(HttpApplication context) {

        }

        public void Dispose() {

        }

    }
}

after you implement your logic inside Init event, you need to register the module inside web.config file  in order to execute it on every request;

<configuration>
   <system.web>
      <httpModules>
         <add name="MyModule" type="MyApp.MyModule, MyApp" />
      </httpModules>
   </system.web>
</configuration>

If you are on integrated mode of IIS 7 or 7.5, this registration should be done inside <system.webServer> tag of web.config


问:
Split a Matlab table in several tables dynamically
I am working in MATLAB and I did not find yet a way to split a table T in different tables {T1,T2,T3,...} dynamically. What I mean with dynamic is that it must be done based on some conditions of the table T that are not known a priori. For now, I do it in a non-dynamic way with the following code (I hard-code the number of tables I want to have).

```<code>%% Separate data of table T in tables T1,T2,T3
starting_index = 1;
T1 = T(1:counter_simulations(1),:);
starting_index = counter_simulations(1)+1;
T2 = T(starting_index:starting_index+counter_simulations(2)-1,:);
starting_index = starting_index + counter_simulations(2);
T3 = T(starting_index:starting_index+counter_simulations(3)-1,:);
</code>```

Any ideas on how to do it dynamically? I would like to do something like that:

```<code>for (i=1:number_of_tables_to_create)
   T{i} = ...
end
</code>```

EDIT: the variable counter_simulations is an array containing the number of rows I want to extract for each table. Example: counter_simulations(1)=200 will mean that the first table will be T1= T(1:200, :). If counter_simulations(2)=300 the first table will be T1= T(counter_simulations(1)+1:300, :) and so on.

I hope I was clear.

Should I use cell arrays instead of tables maybe?

Thanks!

答:
For the example you give, where counter_simulations contains a list of the number of rows to take from T in each of the output tables, MATLAB's mat2cell function actually implements this behaviour directly:

```<code>T = mat2cell(T,counter_simulations);
</code>```

While you haven't specified the contents of counter_simulations, it's clear that if sum(counter_simulations) > height(T) the example would fail. If sum(counter_simulations) < height(T) (and so your desired output doesn't contain the last row(s) of T) then you would need to add a final element to counter_simulations and then discard the resulting output table:

```<code>counter_simulations(end+1) = height(T) - sum(counter_simulations);
T = mat2cell(T,counter_simulations);
T(end) = [];
</code>```

Whether this solution applies to all examples of

some conditions of the table T that are not known a priori

you ask for in the question depends on the range of conditions you actually mean; for a broad enough interpretation there will not be a general solution but you might be able to narrow it down if mat2cell performs too specific a job for your actual problem.

Body:
I am working in MATLAB and I did not find yet a way to split a table T in different tables {T1,T2,T3,...} dynamically. What I mean with dynamic is that it must be done based on some conditions of the table T that are not known a priori. For now, I do it in a non-dynamic way with the following code (I hard-code the number of tables I want to have).

%% Separate data of table T in tables T1,T2,T3
starting_index = 1;
T1 = T(1:counter_simulations(1),:);
starting_index = counter_simulations(1)+1;
T2 = T(starting_index:starting_index+counter_simulations(2)-1,:);
starting_index = starting_index + counter_simulations(2);
T3 = T(starting_index:starting_index+counter_simulations(3)-1,:);

Any ideas on how to do it dynamically? I would like to do something like that:

for (i=1:number_of_tables_to_create)
   T{i} = ...
end

EDIT: the variable counter_simulations is an array containing the number of rows I want to extract for each table. Example: counter_simulations(1)=200 will mean that the first table will be T1= T(1:200, :). If counter_simulations(2)=300 the first table will be T1= T(counter_simulations(1)+1:300, :) and so on.

I hope I was clear.

Should I use cell arrays instead of tables maybe?

Thanks!

Body:
For the example you give, where counter_simulations contains a list of the number of rows to take from T in each of the output tables, MATLAB's mat2cell function actually implements this behaviour directly:

T = mat2cell(T,counter_simulations);

While you haven't specified the contents of counter_simulations, it's clear that if sum(counter_simulations) > height(T) the example would fail. If sum(counter_simulations) < height(T) (and so your desired output doesn't contain the last row(s) of T) then you would need to add a final element to counter_simulations and then discard the resulting output table:

counter_simulations(end+1) = height(T) - sum(counter_simulations);
T = mat2cell(T,counter_simulations);
T(end) = [];

Whether this solution applies to all examples of

some conditions of the table T that are not known a priori

you ask for in the question depends on the range of conditions you actually mean; for a broad enough interpretation there will not be a general solution but you might be able to narrow it down if mat2cell performs too specific a job for your actual problem.


问:
Can you tripleclick() a text to select a paragraph in python selenium?
Can you tripleclick() a text to select the paragraph in python selenium? Or doubleclick()? And then copy-paste it with ActionChains? Without having to ctrl+a.</p>

答:
```<code>from selenium.webdriver.common.action_chains import ActionChains
actionChains = ActionChains(driver)

actionChains.double_click("element variable name").perform()
</code>```


问:
How can i make a plugin execute a command from another plugin?
i need help in developing pretty simple plugin for miencraft version 1.15.2

Plugin is made to check if user has allready logged for a first time if not:
i adds him to a hashmap (so it wont check him twice) and executes a command on a player to add give him permission from plugin LuckPerms.

I've found out that there is PluginCommand:
https://hub.spigotmc.org/javadocs/spigot/org/bukkit/command/PluginCommand.html
But im not quite sure how to use it to make it perform (as server):
/lp user playerName group add groupname

EDIT:
I just can't find how to execute a command so the player will get the permission.

Thanks for your time.

答: Get luckperms or permissions ex to manage permissions</p>


问:
Android viewbinding deprecation warning persists in Android Studio 4 after making appropriate update
After updating to Androis Studio 4.0 I received a warning that android.viewBinding.enabled was deprecated and shoud lbe replaces with android.buildFeatures.viewBinding.

I therefoe changed the appropraiet part of my build.gradle (app) from:

```<code>android {
    ...
    viewBinding {
        enable = true
    }
    ...
}
</code>```

to:

```<code>android {
    ...
    buildFeatures {
        viewBinding {
            enabled true
        }
    }
    ...
}
</code>```

I no longer get the warning, but still get an information box in my build window as follows:

build.gradle: DSL element 'android.viewBinding.enabled' is obsolete and has been replaced with 'android.buildFeatures.viewBinding'.
It will be removed in version 5.0 of the Android Gradle plugin.

Is this normal? I knows it's not a warning or an error, but it seems odd to tell me about something that has been fixed - or have I not fixed it correctly (my app still works using viewBinding as expected).

(Note also that when adding the buildFeatures section to the file, none of the required entires, including buildFeatures pops up in teh auto-complete prompt.)

答:
Solved it!

Although it was working - i.e. the View bindings were working fine - the correct new syntax appears to be:

```<code>android
    ...
    buildFeatures {
        viewBinding true
    }
    ...
}
</code>```

...still not popping up in the auto-complete, though.

Update: After a few buids and rebuilds I checked again and now buildFeatures IS popping up in teh auto-complete... Guess I wasn't being patient enough for everything to catch up. Just a bit odd that invalidating the caches didn't fix the auto-complete straight away.

Body:
After updating to Androis Studio 4.0 I received a warning that android.viewBinding.enabled was deprecated and shoud lbe replaces with android.buildFeatures.viewBinding.

I therefoe changed the appropraiet part of my build.gradle (app) from:

android {
    ...
    viewBinding {
        enable = true
    }
    ...
}

to:

android {
    ...
    buildFeatures {
        viewBinding {
            enabled true
        }
    }
    ...
}

I no longer get the warning, but still get an information box in my build window as follows:

build.gradle: DSL element 'android.viewBinding.enabled' is obsolete and has been replaced with 'android.buildFeatures.viewBinding'.
It will be removed in version 5.0 of the Android Gradle plugin.

Is this normal? I knows it's not a warning or an error, but it seems odd to tell me about something that has been fixed - or have I not fixed it correctly (my app still works using viewBinding as expected).

(Note also that when adding the buildFeatures section to the file, none of the required entires, including buildFeatures pops up in teh auto-complete prompt.)

Body:
Solved it!

Although it was working - i.e. the View bindings were working fine - the correct new syntax appears to be:

android
    ...
    buildFeatures {
        viewBinding true
    }
    ...
}

...still not popping up in the auto-complete, though.

Update: After a few buids and rebuilds I checked again and now buildFeatures IS popping up in teh auto-complete... Guess I wasn't being patient enough for everything to catch up. Just a bit odd that invalidating the caches didn't fix the auto-complete straight away.


问:
Java Stream filter nested objects return top level fields
I have a following hierarchy in my model:

```<code>class Item {
    String name;
    ...
    List<SubItem> subItems;
}

class SubItem {
    String name;
    ...
    List<String> ids;
}
</code>```

I'd like to find an Item and its SubItem where subItem.ids list contains some specific id and return a Pair of Item.name and SubItem.name. I assume all names and ids are unique, so I'm interested only in the first result.

I can do this using two foreach loops:

```<code>for (Item item : items) {
    for (SubItem subItem : item.subItems) {
        if (subItem.ids.contains("some value")) {
            return Pair<String, String>(item.name, subItem.name)
        }
    }
}
</code>```

I was wondering if I can achieve the same result using Java 8 Streams?

I found this answer How to filter nested objects with Stream, but I need to return some top level fields (names) as well.

答:
You can use flatMap:

```<code>return items.stream()
            .flatMap(i -> i.getSubItems()
                           .stream()
                           .filter(si -> si.ids.contains("some value"))
                           .map(si -> new Pair<String, String>(i.name, si.name)))
            .findFirst()
            .orElse(null);
</code>```

Body:
I have a following hierarchy in my model:

class Item {
    String name;
    ...
    List<SubItem> subItems;
}

class SubItem {
    String name;
    ...
    List<String> ids;
}

I'd like to find an Item and its SubItem where subItem.ids list contains some specific id and return a Pair of Item.name and SubItem.name. I assume all names and ids are unique, so I'm interested only in the first result.

I can do this using two foreach loops:

for (Item item : items) {
    for (SubItem subItem : item.subItems) {
        if (subItem.ids.contains("some value")) {
            return Pair<String, String>(item.name, subItem.name)
        }
    }
}

I was wondering if I can achieve the same result using Java 8 Streams?

I found this answer How to filter nested objects with Stream, but I need to return some top level fields (names) as well.

Body:
You can use flatMap:

return items.stream()
            .flatMap(i -> i.getSubItems()
                           .stream()
                           .filter(si -> si.ids.contains("some value"))
                           .map(si -> new Pair<String, String>(i.name, si.name)))
            .findFirst()
            .orElse(null);


问:
Inaccessible Cash State
I am running into an issue with cash states. Basically I have a node that issues itself money and is unable to access an existing state to use for payment/anything. Let’s say this state is 5 dollars, if I issue 10 more, both rpcOps and the servicehub getCashBalances will say that I have 15 dollars. However, any cash flows that try to use more than 10 dollars will tell me I don’t have sufficient balance.

I’ve set up api endpoints for the node to even just exit the cash but it will say that I’m exiting more than I have. When I query the vault with QueryCriteria.VaultQueryCriteria(Vault.StateStatus.UNCONSUMED), I can see the state is there, and there doesn’t seem to be anything that differentiates the inaccessible state from any subsequent accessible states.

Could there be anything I’m overlooking here? The issuers are the same and the owners are hashed but should be the same, as well.

Updated with command / code:

```<code>fun selfIssueTime(@QueryParam(value = "amount") amount: Long,
                  @QueryParam(value = "currency") currency: String): Response {

    // 1. Prepare issue request.
    val issueAmount = Amount(amount.toLong() * 100, Currency.getInstance(currency))
    val notary = rpcOps.notaryIdentities().firstOrNull() ?: throw IllegalStateException("Could not find a notary.")
    val issueRef = OpaqueBytes.of(0)
    val issueRequest = CashIssueFlow.IssueRequest(issueAmount, issueRef, notary)
    val self = myIdentity

    // 2. Start flow and wait for response.
    val (status, message) = try {
        val flowHandle = rpcOps.startFlowDynamic(
                CashIssueFlow::class.java,
                issueRequest
        )

        flowHandle.use { it.returnValue.getOrThrow() }
        CREATED to "$issueAmount issued to $self."
    } catch (e: Exception) {
        BAD_REQUEST to e.message
    }

    // 3. Return the response.
    return Response.status(status).entity(message).build()
}
</code>```

答:
I believe this is fixed via the later version of Corda finance jars. We have developed a couple more CorDapps samples using the currency  class, and we did not run into any issue. For example: https://github.com/corda/samples-java/blob/master/Tokens/dollartohousetoken/workflows/src/main/java/net/corda/examples/dollartohousetoken/flows/FiatCurrencyIssueFlow.java#L39

Further more, with the release of the Corda TokenSDk, Currency on Corda has actually a new way to get issue, transfer and redeem. This is done by:

```<code>        /* Create an instance of the fiat currency token */
        TokenType token = FiatCurrency.Companion.getInstance(currency);

        /* Create an instance of IssuedTokenType for the fiat currency */
        IssuedTokenType issuedTokenType = new IssuedTokenType(getOurIdentity(), token);

        /* Create an instance of FungibleToken for the fiat currency to be issued */
        FungibleToken fungibleToken = new FungibleToken(new Amount<>(amount, issuedTokenType), recipient, null);

        /* Issue the required amount of the token to the recipient */
        return subFlow(new IssueTokens(ImmutableList.of(fungibleToken), ImmutableList.of(recipient)));
</code>```

Title: Inaccessible Cash State

Body:
I am running into an issue with cash states. Basically I have a node that issues itself money and is unable to access an existing state to use for payment/anything. Let’s say this state is 5 dollars, if I issue 10 more, both rpcOps and the servicehub getCashBalances will say that I have 15 dollars. However, any cash flows that try to use more than 10 dollars will tell me I don’t have sufficient balance.

I’ve set up api endpoints for the node to even just exit the cash but it will say that I’m exiting more than I have. When I query the vault with QueryCriteria.VaultQueryCriteria(Vault.StateStatus.UNCONSUMED), I can see the state is there, and there doesn’t seem to be anything that differentiates the inaccessible state from any subsequent accessible states.

Could there be anything I’m overlooking here? The issuers are the same and the owners are hashed but should be the same, as well.

Updated with command / code:

fun selfIssueTime(@QueryParam(value = "amount") amount: Long,
                  @QueryParam(value = "currency") currency: String): Response {

    // 1. Prepare issue request.
    val issueAmount = Amount(amount.toLong() * 100, Currency.getInstance(currency))
    val notary = rpcOps.notaryIdentities().firstOrNull() ?: throw IllegalStateException("Could not find a notary.")
    val issueRef = OpaqueBytes.of(0)
    val issueRequest = CashIssueFlow.IssueRequest(issueAmount, issueRef, notary)
    val self = myIdentity

    // 2. Start flow and wait for response.
    val (status, message) = try {
        val flowHandle = rpcOps.startFlowDynamic(
                CashIssueFlow::class.java,
                issueRequest
        )

        flowHandle.use { it.returnValue.getOrThrow() }
        CREATED to "$issueAmount issued to $self."
    } catch (e: Exception) {
        BAD_REQUEST to e.message
    }

    // 3. Return the response.
    return Response.status(status).entity(message).build()
}

Body:
I believe this is fixed via the later version of Corda finance jars. We have developed a couple more CorDapps samples using the currency  class, and we did not run into any issue. For example: https://github.com/corda/samples-java/blob/master/Tokens/dollartohousetoken/workflows/src/main/java/net/corda/examples/dollartohousetoken/flows/FiatCurrencyIssueFlow.java#L39

Further more, with the release of the Corda TokenSDk, Currency on Corda has actually a new way to get issue, transfer and redeem. This is done by:

        /* Create an instance of the fiat currency token */
        TokenType token = FiatCurrency.Companion.getInstance(currency);

        /* Create an instance of IssuedTokenType for the fiat currency */
        IssuedTokenType issuedTokenType = new IssuedTokenType(getOurIdentity(), token);

        /* Create an instance of FungibleToken for the fiat currency to be issued */
        FungibleToken fungibleToken = new FungibleToken(new Amount<>(amount, issuedTokenType), recipient, null);

        /* Issue the required amount of the token to the recipient */
        return subFlow(new IssueTokens(ImmutableList.of(fungibleToken), ImmutableList.of(recipient)));


问:
Importing a firebase collection into BigQuery using fs-bq-import-collection fails
I have installed the new BigQuery export firebase extension on my firestore database and it works great.

Now I am trying to import the existing data in the collection by following the instructions on the extension but getting the error below.

https://github.com/firebase/extensions/blob/master/firestore-bigquery-export/guides/IMPORT_EXISTING_DOCUMENTS.md

Any ideas how to resolve this error?

Note: I ran gcloud components update to update to the latest gcloud versions

```<code>npx @firebaseextensions/fs-bq-import-collection
</code>```

```<code>Importing data from Cloud Firestore Collection: members, to BigQuery Dataset: qmtbc_dev_export, Table: members_raw_changelog
Error unlinking journal file C:\Users\fullo\AppData\Roaming\npm-cache\_npx\10884\node_modules\@firebaseextensions\fs-bq-import-collection\lib/from-members-to-qmtbc-dev:qmtbc_dev_export:members_raw_changelog
after successful import: Error: ENOENT: no such file or directory, unlink 'C:\Users\fullo\AppData\Roaming\npm-cache\_npx\10884\node_modules\@firebaseextensions\fs-bq-import-collection\lib\from-members-to-qmtbc-dev:qmtbc_dev_export:members_raw_changelog'
---------------------------------------------------------
Finished importing 0 Firestore rows to BigQuery
---------------------------------------------------------
Error importing Collection to BigQuery: Error: EPERM: operation not permitted, unlink 'C:\Users\fullo\AppData\Roaming\npm-cache\_npx\10884\node_modules\@firebaseextensions\fs-bq-import-collection\node_modules\grpc\src\node\extension_binary\node-v64-win32-x64-unknown\grpc_node.node'
</code>```

Update 1:

I have been stuck on this for over 24hrs now.

I have reinstalled nodejs to v12.13 and killed my virus checker, rebooted etc
No luck.
Also tried npm rebuild

The closest issues I have seen are:
https://github.com/phoenixframework/phoenix/issues/2464#issuecomment-325497850
https://github.com/phoenixframework/phoenix/issues/2464#issuecomment-328853460

Update 2:

I have uninstalled node and tried versions 8.16.2, 10.17 and 12.13
I deleted my npm and npm cache folders and reinstalled my global node packages.
Still no luck.  I may try this method instead: https://cloud.google.com/bigquery/docs/loading-data-cloud-firestore

Update 3:

I have given up.  It would be good to know if this script actually works for others.

答: you have to export GOOGLE_APPLICATION_CREDENTIALS json file first and then issue npx @firebaseextensions/fs-bq-import-collection command</p>

Body:
I have installed the new BigQuery export firebase extension on my firestore database and it works great.

Now I am trying to import the existing data in the collection by following the instructions on the extension but getting the error below.

https://github.com/firebase/extensions/blob/master/firestore-bigquery-export/guides/IMPORT_EXISTING_DOCUMENTS.md

Any ideas how to resolve this error?

Note: I ran gcloud components update to update to the latest gcloud versions

npx @firebaseextensions/fs-bq-import-collection

Importing data from Cloud Firestore Collection: members, to BigQuery Dataset: qmtbc_dev_export, Table: members_raw_changelog
Error unlinking journal file C:\Users\fullo\AppData\Roaming\npm-cache\_npx\10884\node_modules\@firebaseextensions\fs-bq-import-collection\lib/from-members-to-qmtbc-dev:qmtbc_dev_export:members_raw_changelog
after successful import: Error: ENOENT: no such file or directory, unlink 'C:\Users\fullo\AppData\Roaming\npm-cache\_npx\10884\node_modules\@firebaseextensions\fs-bq-import-collection\lib\from-members-to-qmtbc-dev:qmtbc_dev_export:members_raw_changelog'
---------------------------------------------------------
Finished importing 0 Firestore rows to BigQuery
---------------------------------------------------------
Error importing Collection to BigQuery: Error: EPERM: operation not permitted, unlink 'C:\Users\fullo\AppData\Roaming\npm-cache\_npx\10884\node_modules\@firebaseextensions\fs-bq-import-collection\node_modules\grpc\src\node\extension_binary\node-v64-win32-x64-unknown\grpc_node.node'

Update 1:

I have been stuck on this for over 24hrs now.

I have reinstalled nodejs to v12.13 and killed my virus checker, rebooted etc
No luck.
Also tried npm rebuild

The closest issues I have seen are:
https://github.com/phoenixframework/phoenix/issues/2464#issuecomment-325497850
https://github.com/phoenixframework/phoenix/issues/2464#issuecomment-328853460

Update 2:

I have uninstalled node and tried versions 8.16.2, 10.17 and 12.13
I deleted my npm and npm cache folders and reinstalled my global node packages.
Still no luck.  I may try this method instead: https://cloud.google.com/bigquery/docs/loading-data-cloud-firestore

Update 3:

I have given up.  It would be good to know if this script actually works for others.


问:
What could be the cause for DEADLOCK with two update statements?
I see the deadlock extended event capture two update statements as process which is causing deadlock. Both processes look exactly same.

Process #1:

```<code>update CL
set N1 = @P0, N2 = @P1, N3 = @P2 etc.
</code>```

Process #2:

```<code>update CL
set N1 = @P0, N2 = @P1, N3 = @P2 etc.
</code>```

Under resource list I see this:

```<code><keylock hobtid="72057594321698816" dbid="5" objectname="CLINE" indexname="PK_CLINE"
<keylock hobtid="72057594320584704" dbid="5" objectname="CL" indexname="PK_CL"
</code>```

I could get the two rows from the %%lockerss%%

What could be the issue?

答:
Do you have some transactions where you update both tables CI and CLINE (in the same transaction)?
If you have a transaction where you update first CI and then CLINE and another transaction where you update first CLINE and then table CI, this can cause deadlocks.</p>

Body:
I see the deadlock extended event capture two update statements as process which is causing deadlock. Both processes look exactly same.

Process #1:

update CL
set N1 = @P0, N2 = @P1, N3 = @P2 etc.

Process #2:

update CL
set N1 = @P0, N2 = @P1, N3 = @P2 etc.

Under resource list I see this:

<keylock hobtid="72057594321698816" dbid="5" objectname="CLINE" indexname="PK_CLINE"
<keylock hobtid="72057594320584704" dbid="5" objectname="CL" indexname="PK_CL"

I could get the two rows from the %%lockerss%%

What could be the issue?


问:
Importing complex Excel with pandas
I have a problem importing data from a complex excel file. The file looks like the following:

I want import the data and therefore need to perform two steps:

Delete the first 2 rows before importing (this data is not needed)

Pivot "Headphones", "TV" and "Radio"

How can I do this?

EDIT:

I want "Headphones", "TV" and "Radio" in a column after "Name" called "product".

So the columns should be: "Country" "Name" "product" "Sales" "Price" " Bestseller"

example:

```<code>US | Tom | Headphones | 1200 | 100 | Headphone 1
US | Tom | TV         | 1546 | 500 | TV 1
</code>```

答:
Thank you very much, that helped getting rid of the first lines. What I have now is:

Unnamed: 0    Unnamed: 1 Headphones  Unnamed: 3  Unnamed: 4    TV      ...
  0  Country  Name        Sales      Price       Bestseller    Sales   ...
  1  US          Tom        1200        100  Headphone 1   1546    ...

  # And what I want is

  Country Name product     Sales Price Bestseller
  US    Tom  Headphones  1200  100   Headphone 1
  US      Tom  TV          1546  500   TV 1```

Title: Importing complex Excel with pandas

Body:
I have a problem importing data from a complex excel file. The file looks like the following:

I want import the data and therefore need to perform two steps:

Delete the first 2 rows before importing (this data is not needed)

Pivot "Headphones", "TV" and "Radio"

How can I do this?

EDIT:

I want "Headphones", "TV" and "Radio" in a column after "Name" called "product".

So the columns should be: "Country" "Name" "product" "Sales" "Price" " Bestseller"

example:

US | Tom | Headphones | 1200 | 100 | Headphone 1
US | Tom | TV         | 1546 | 500 | TV 1


问:
how to set an action button when creating an alarm clock using tkinter
I am trying my first project in python and wanted to create an alarm clock the ask the user to input the hour, minute and am or pm to set an alarm. I am having issues on how to set an action button so that when the user click on "set alarm", the alarm will be set.</p>

```<code>import datetime

import winsound

import tkinter as tk

filename = "old-fashioned-door-bell.wav"

window = tk.Tk()

window.title("Alarm Clock")

window.geometry("400x400")

window.configure(background="Brown")

def alarm_Clock():

    alarmHour = int(Entry1.get())

    alarmMinute = int(Entry2.get())

    amPm = str(Entry3.get())

    if (amPm == "pm"):

        alarmHour += 12

    while (1 == 1):

        if (alarmHour == datetime.datetime.now().hour and

            alarmMinute == datetime.datetime.now().minute):

            winsound.PlaySound(filename, winsound.SND_LOOP)

            break

def update_btn():

    alarmHour, alarmMinute, amPM = Entry1.get(), Entry2.get(), Entry3.get()

    if alarmHour.isdigit() and alarmMinute.isdigit() and amPM.isdigit():

       return alarm_Clock()

Prompts1 = tk.Label(text="Kels Alarm Clock", font=("Times New Roman", 40), bg="brown", fg="white")

Prompts1.grid(column=0, row=0)

Prompts2 = tk.Label(text="Please enter the time Alarm should ring!", font=("Times New Roman", 15),

bg="brown", fg="white")

Prompts2.grid(column=0, row=1, sticky="W")

Label1 = tk.Label(text="Enter Hour", bg="brown", fg="white", font="Garamond")

Label1.grid(column=0, row=2, sticky="W")

Label2 = tk.Label(text="Enter Minute", bg="brown", fg="white", font="Garamond")

Label2.grid(column=0, row=3, sticky="W")

Label3 = tk.Label(text="Am or Pm", bg="brown", fg="white", font="Garamond")

Label3.grid(column=0, row=4, sticky="W")

Entry1 = tk.Entry()

Entry1.grid(column=1, row=2)

Entry2 = tk.Entry()

Entry2.grid(column=1, row=3)

Entry3 = tk.Entry()

Entry3.grid(column=1, row=4)

Button1 = tk.Button(text="Set Alarm", command="update_btn")

Button1.grid(column=1, row=5)

window.mainloop()
</code>```

答: First of all, there are a few errors in your code. Enter1, Enter2... is local to the function "update_btn()". To use it in other function pass it or use "global" keyword in the function "alarm_clk". If possible Post the entire code in the code section instead of chunks. </p>

Body:
I am trying my first project in python and wanted to create an alarm clock the ask the user to input the hour, minute and am or pm to set an alarm. I am having issues on how to set an action button so that when the user click on "set alarm", the alarm will be set.

import datetime

import winsound

import tkinter as tk

filename = "old-fashioned-door-bell.wav"

window = tk.Tk()

window.title("Alarm Clock")

window.geometry("400x400")

window.configure(background="Brown")

def alarm_Clock():

    alarmHour = int(Entry1.get())

    alarmMinute = int(Entry2.get())

    amPm = str(Entry3.get())

    if (amPm == "pm"):

        alarmHour += 12

    while (1 == 1):

        if (alarmHour == datetime.datetime.now().hour and

            alarmMinute == datetime.datetime.now().minute):

            winsound.PlaySound(filename, winsound.SND_LOOP)

            break

def update_btn():

    alarmHour, alarmMinute, amPM = Entry1.get(), Entry2.get(), Entry3.get()

    if alarmHour.isdigit() and alarmMinute.isdigit() and amPM.isdigit():

       return alarm_Clock()

Prompts1 = tk.Label(text="Kels Alarm Clock", font=("Times New Roman", 40), bg="brown", fg="white")

Prompts1.grid(column=0, row=0)

Prompts2 = tk.Label(text="Please enter the time Alarm should ring!", font=("Times New Roman", 15),

bg="brown", fg="white")

Prompts2.grid(column=0, row=1, sticky="W")

Label1 = tk.Label(text="Enter Hour", bg="brown", fg="white", font="Garamond")

Label1.grid(column=0, row=2, sticky="W")

Label2 = tk.Label(text="Enter Minute", bg="brown", fg="white", font="Garamond")

Label2.grid(column=0, row=3, sticky="W")

Label3 = tk.Label(text="Am or Pm", bg="brown", fg="white", font="Garamond")

Label3.grid(column=0, row=4, sticky="W")

Entry1 = tk.Entry()

Entry1.grid(column=1, row=2)

Entry2 = tk.Entry()

Entry2.grid(column=1, row=3)

Entry3 = tk.Entry()

Entry3.grid(column=1, row=4)

Button1 = tk.Button(text="Set Alarm", command="update_btn")

Button1.grid(column=1, row=5)

window.mainloop()


问:
Liferay: Get URL in portal.normal.vm from properties file
I have problems to read info from properties file "liferay-portal-6.1.0/tomcat-7.0.23/lib/myweb-application.properties" in portal_normal.vm
myweb-application.properties:

```<code>redirect.docs.url = http://stackoverflow.com/questions/ask
</code>```

"liferay-portal-6.1.0/tomcat-7.0.23/webapps/web-theme/templates/portal_normal.vm":

```<code> #set ($docsURL =  $propsUtil.get("redirect.docs.url"))  <a href="$docsURL">#language("foot.docs")</a>
</code>```

答:
Get value of portal-ext.properties

eg. test.name="sachin"

```<code>${propsUtil.get("test.name")}
</code>```

Body:
I have problems to read info from properties file "liferay-portal-6.1.0/tomcat-7.0.23/lib/myweb-application.properties" in portal_normal.vm
myweb-application.properties:

redirect.docs.url = http://stackoverflow.com/questions/ask

"liferay-portal-6.1.0/tomcat-7.0.23/webapps/web-theme/templates/portal_normal.vm":

 #set ($docsURL =  $propsUtil.get("redirect.docs.url"))  #language("foot.docs")

Body:
Get value of portal-ext.properties

eg. test.name="sachin"

${propsUtil.get("test.name")}


问:
How do I get child process PIDs when using ProcessPoolExecuter?
I'm using  ProcessPoolExecutor  context manager to run several Kafka consumers in parallel. I need to store the process IDs of the child processes so that later, I can cleanly terminate those processes. I have such code:

```<code>Class MultiProcessConsumer:
    ...

    def run_in_parallel(self):
        parallelism_factor = 5

        with ProcessPoolExecutor() as executor:
            processes = [executor.submit(self.consume) for _ in range(parallelism_factor)]
            # It would be nice If I could write [process.pid for process in processes] to a file here.

    def consume(self):
        while True:
            for message in self.kafka_consumer:
                do_stuff(message)
</code>```

I know I can use os.get_pid() in the consume method to get PIDs. But, handling them properly (in case of constant shutting down or starting up of consumers) requires some extra work.

How would you propose that I get and store PIDs of the child processes in such a context?

答:
os.get_pid() seems to be the way to go. Just pass them through a Queue or Pipe in combination with maybe some random UUID that you pass to the process before to identify the PID.

```<code>from concurrent.futures import ProcessPoolExecutor
import os
import time
import uuid
#from multiprocessing import Process, Queue
import multiprocessing
import queue
#The Empty exception in in Queue, multiprocessing borrows
#it from there

# https://stackoverflow.com/questions/9908781/sharing-a-result-queue-among-several-processes
m = multiprocessing.Manager()
q = m.Queue()

def task(n, queue, uuid):
    my_pid = os.getpid()
    print("Executing our Task on Process {}".format(my_pid))
    queue.put((uuid, my_pid))
    time.sleep(n)
    return n * n

def main():

    with ProcessPoolExecutor(max_workers = 3) as executor:

        some_dict = {}
        for i in range(10):
            print(i)

            u = uuid.uuid4()
            f = executor.submit(task, i, q, u)
            some_dict[u] = [f, None] # PID not known here

            try:
                rcv_uuid, rcv_pid = q.get(block=True, timeout=1)
                some_dict[rcv_uuid][1] = rcv_pid # store PID
            except queue.Empty as e:
                print('handle me', e)
            print('I am', rcv_uuid, 'and my PID is', rcv_pid)

if __name__ == '__main__':
    main()
</code>```

Body:
I'm using  ProcessPoolExecutor  context manager to run several Kafka consumers in parallel. I need to store the process IDs of the child processes so that later, I can cleanly terminate those processes. I have such code:

Class MultiProcessConsumer:
    ...

    def run_in_parallel(self):
        parallelism_factor = 5

        with ProcessPoolExecutor() as executor:
            processes = [executor.submit(self.consume) for _ in range(parallelism_factor)]
            # It would be nice If I could write [process.pid for process in processes] to a file here.

    def consume(self):
        while True:
            for message in self.kafka_consumer:
                do_stuff(message)

I know I can use os.get_pid() in the consume method to get PIDs. But, handling them properly (in case of constant shutting down or starting up of consumers) requires some extra work.

How would you propose that I get and store PIDs of the child processes in such a context?

Body:
os.get_pid() seems to be the way to go. Just pass them through a Queue or Pipe in combination with maybe some random UUID that you pass to the process before to identify the PID.

from concurrent.futures import ProcessPoolExecutor
import os
import time
import uuid
#from multiprocessing import Process, Queue
import multiprocessing
import queue
#The Empty exception in in Queue, multiprocessing borrows
#it from there

# https://stackoverflow.com/questions/9908781/sharing-a-result-queue-among-several-processes
m = multiprocessing.Manager()
q = m.Queue()

def task(n, queue, uuid):
    my_pid = os.getpid()
    print("Executing our Task on Process {}".format(my_pid))
    queue.put((uuid, my_pid))
    time.sleep(n)
    return n * n

def main():

    with ProcessPoolExecutor(max_workers = 3) as executor:

        some_dict = {}
        for i in range(10):
            print(i)

            u = uuid.uuid4()
            f = executor.submit(task, i, q, u)
            some_dict[u] = [f, None] # PID not known here

            try:
                rcv_uuid, rcv_pid = q.get(block=True, timeout=1)
                some_dict[rcv_uuid][1] = rcv_pid # store PID
            except queue.Empty as e:
                print('handle me', e)
            print('I am', rcv_uuid, 'and my PID is', rcv_pid)

if __name__ == '__main__':
    main()


问:
MongoDb fulltext search AND condition
I try to use text-index in mongodb:
{$text: {$search: 'sport hockey'}}

Is uses OR condition for searching by phrase: 'sport' OR 'hockey'. For example the result can be the following list of titles:

Sport something today...

Sport is hockey

Hockey players

The most relevant document is on the second position (actually I'd like to exclude all other results except this one: 'Sport is hockey').
Is it possible to use AND condition in $text?

Quotation marks are not suitable because {$text: {$search: "\"sport hockey\""}} uses search by exact match.

答:
For anyone coming to this thread again, required search criteria of "AND" can be achieved using following find query

```<code>{$text:{$search:"\"sport\" \"hockey\""}}
</code>```

Give attention to how different words are escaped.

In node js, following can be done to create desire search text for "AND" condition

```<code>searchText = '"' + userInput.split(" ").join('" "') + '"';
</code>```

then

```<code>collectionObj.find({$text:{$search:searchText}})
</code>```

Title: MongoDb fulltext search AND condition

Body:
For anyone coming to this thread again, required search criteria of "AND" can be achieved using following find query

{$text:{$search:"\"sport\" \"hockey\""}}

Give attention to how different words are escaped.

In node js, following can be done to create desire search text for "AND" condition

searchText = '"' + userInput.split(" ").join('" "') + '"';

then

collectionObj.find({$text:{$search:searchText}})


问:
i have converted python program to an .exe file but on opening the .exe file i don't see an output, but just a empty cmd window
i have converted the python file to an exe file using the pyinstaller. The command i used is this "pyinstaller --onefile snake_game.py". i just an empty cmd window and it closes after few seconds =>. i have also tried to convert other python programs they work just fine but this one does not work. From my inspection the code is correct.

```<code>import pygame
import time
import random

pygame.init()
pygame.mixer.init()

white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
glow_blue = (115, 194, 251)

dis_width = 800
dis_height = 600

FPS = 20
fpsClock = pygame.time.Clock()

dis = pygame.display.set_mode([dis_width,dis_height])
pygame.display.set_caption("Snake Game ")

snake_block = 20

score_font = pygame.font.SysFont("Algerian", 35)
finish_font = pygame.font.SysFont("copper", 55)

back_image = pygame.image.load(r"C:\Users\vicky\OneDrive\Desktop\ALL PYTHON\snake game final\back_ground2.jpg")

game_finish = pygame.image.load(r"C:\Users\vicky\OneDrive\Desktop\ALL PYTHON\snake game final\finish.jpg")

last_score = pygame.font.SysFont("Algerian", 35)
finish_score = last_score.render("Your Score", True, black)

def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, red)
    dis.blit(value, [20, 20])

def our_snake(snake_block, snake_list):
    for x in snake_list:
        #dis.blit(snake_logo,[x[0], x[1], snake_block, snake_block])

        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])

def message(msg, color):
    mesg = finish_font.render(msg, True, color)
    dis.blit(mesg, [130, 468])

def gameLoop():
    game_over = False
    game_close = False

    x1 = dis_width / 2
    y1 = dis_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 20) * 20
    foody = round(random.randrange(0, dis_height - snake_block) / 20) * 20

    while not game_over:

        while game_close == True:
            dis.blit(game_finish,[-130,0])
            message("Press C-Play Again or Q-Quit", white)
            Your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()
                    if event.type == pygame.QUIT:
                        game_over = True

                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            pygame.quit()
                            quit()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            pygame.mixer.music.load("out.wav")
            pygame.mixer.music.play()
            game_close = True

        x1 += x1_change
        y1 += y1_change

        dis.blit(back_image,[0,0])
        pygame.draw.rect(dis, white, [foodx, foody, snake_block, snake_block])
        #pygame.draw.circle(dis, white, [foodx, foody], 15,0)
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            pygame.mixer.music.load("beep.wav")
            pygame.mixer.music.play()
            foodx = round(random.randrange(0, dis_width - snake_block) / 20.0) * 20.0
            foody = round(random.randrange(0, dis_height - snake_block) / 20.0) * 20.0
            Length_of_snake += 1

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    quit()

        fpsClock.tick(FPS)

    pygame.quit()
    quit()

gameLoop()
</code>```

答:
There is an issue with the font use used. Maybe try to replace these:

```<code>score_font = pygame.font.SysFont("Algerian", 35)
finish_font = pygame.font.SysFont("copper", 55)
</code>```

with these:

```<code>score_font = pygame.font.SysFont("comicsansms", 35)
finish_font = pygame.font.SysFont("comicsansms", 55)
</code>```

According to pygame documentation:

[pygame.font.SysFont()] Return a new Font object that is loaded from the system fonts. The font will match the requested bold and italic flags. If a suitable system font is not found this will fall back on loading the default pygame font. The font name can be a comma separated list of font names to look for.

When you set 'Algerian' or 'copper' as fonts and compile the program in an .exe file, pygame fails to find a suitable system font.

Body:
i have converted the python file to an exe file using the pyinstaller. The command i used is this "pyinstaller --onefile snake_game.py". i just an empty cmd window and it closes after few seconds =>. i have also tried to convert other python programs they work just fine but this one does not work. From my inspection the code is correct.

import pygame
import time
import random

pygame.init()
pygame.mixer.init()

white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
glow_blue = (115, 194, 251)

dis_width = 800
dis_height = 600

FPS = 20
fpsClock = pygame.time.Clock()

dis = pygame.display.set_mode([dis_width,dis_height])
pygame.display.set_caption("Snake Game ")

snake_block = 20

score_font = pygame.font.SysFont("Algerian", 35)
finish_font = pygame.font.SysFont("copper", 55)

back_image = pygame.image.load(r"C:\Users\vicky\OneDrive\Desktop\ALL PYTHON\snake game final\back_ground2.jpg")

game_finish = pygame.image.load(r"C:\Users\vicky\OneDrive\Desktop\ALL PYTHON\snake game final\finish.jpg")

last_score = pygame.font.SysFont("Algerian", 35)
finish_score = last_score.render("Your Score", True, black)

def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, red)
    dis.blit(value, [20, 20])

def our_snake(snake_block, snake_list):
    for x in snake_list:
        #dis.blit(snake_logo,[x[0], x[1], snake_block, snake_block])

        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])

def message(msg, color):
    mesg = finish_font.render(msg, True, color)
    dis.blit(mesg, [130, 468])

def gameLoop():
    game_over = False
    game_close = False

    x1 = dis_width / 2
    y1 = dis_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 20) * 20
    foody = round(random.randrange(0, dis_height - snake_block) / 20) * 20

    while not game_over:

        while game_close == True:
            dis.blit(game_finish,[-130,0])
            message("Press C-Play Again or Q-Quit", white)
            Your_score(Length_of_snake - 1)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()
                    if event.type == pygame.QUIT:
                        game_over = True

                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            pygame.quit()
                            quit()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            pygame.mixer.music.load("out.wav")
            pygame.mixer.music.play()
            game_close = True

        x1 += x1_change
        y1 += y1_change

        dis.blit(back_image,[0,0])
        pygame.draw.rect(dis, white, [foodx, foody, snake_block, snake_block])
        #pygame.draw.circle(dis, white, [foodx, foody], 15,0)
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            pygame.mixer.music.load("beep.wav")
            pygame.mixer.music.play()
            foodx = round(random.randrange(0, dis_width - snake_block) / 20.0) * 20.0
            foody = round(random.randrange(0, dis_height - snake_block) / 20.0) * 20.0
            Length_of_snake += 1

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    quit()

        fpsClock.tick(FPS)

    pygame.quit()
    quit()

gameLoop()

Body:
There is an issue with the font use used. Maybe try to replace these:

score_font = pygame.font.SysFont("Algerian", 35)
finish_font = pygame.font.SysFont("copper", 55)

with these:

score_font = pygame.font.SysFont("comicsansms", 35)
finish_font = pygame.font.SysFont("comicsansms", 55)

According to pygame documentation:

[pygame.font.SysFont()] Return a new Font object that is loaded from the system fonts. The font will match the requested bold and italic flags. If a suitable system font is not found this will fall back on loading the default pygame font. The font name can be a comma separated list of font names to look for.

When you set 'Algerian' or 'copper' as fonts and compile the program in an .exe file, pygame fails to find a suitable system font.


答:
@Fat Monk

Please add this line to your app build.gradle file.

```<code>android.buildFeatures.viewBinding = true
</code>```

Title: Android viewbinding deprecation warning persists in Android Studio 4 after making appropriate update

Body:
After updating to Androis Studio 4.0 I received a warning that android.viewBinding.enabled was deprecated and shoud lbe replaces with android.buildFeatures.viewBinding.

I therefoe changed the appropraiet part of my build.gradle (app) from:

android {
    ...
    viewBinding {
        enable = true
    }
    ...
}

to:

android {
    ...
    buildFeatures {
        viewBinding {
            enabled true
        }
    }
    ...
}

I no longer get the warning, but still get an information box in my build window as follows:

build.gradle: DSL element 'android.viewBinding.enabled' is obsolete and has been replaced with 'android.buildFeatures.viewBinding'.
It will be removed in version 5.0 of the Android Gradle plugin.

Is this normal? I knows it's not a warning or an error, but it seems odd to tell me about something that has been fixed - or have I not fixed it correctly (my app still works using viewBinding as expected).

(Note also that when adding the buildFeatures section to the file, none of the required entires, including buildFeatures pops up in teh auto-complete prompt.)

Body:
@Fat Monk

Please add this line to your app build.gradle file.

android.buildFeatures.viewBinding = true


问:
Oracle - get data from first day of previous month at particular time to first day of current month at particular time
My requirement is to get the data of a particular date range in Oracle as follows -

```<code>CompletedDate = Range between First Day of Previous Month @12:00AM to First Day of Current Month @4:00PM
</code>```

And also

```<code>CompleteDate = Range between previous Friday at 4:31 PM and current Friday at 4:30 PM
</code>```

Can you please give me a solution.

答:
That would be

```<code>select *
from your_table
where date_column between add_months(trunc(sysdate, 'mm'), -1)
                      and trunc(sysdate, 'mm') + 16/24
</code>```

and

```<code>select *
from your_table
where date_column between next_day(trunc(sysdate), 'FRIDAY') - 7 + 16/24 + 31/(24*60)
                      and next_day(trunc(sysdate), 'FRIDAY') + 16/24 + 30/(24*60)
</code>```

Body:
My requirement is to get the data of a particular date range in Oracle as follows -

CompletedDate = Range between First Day of Previous Month @12:00AM to First Day of Current Month @4:00PM

And also

CompleteDate = Range between previous Friday at 4:31 PM and current Friday at 4:30 PM

Can you please give me a solution.

Body:
That would be

select *
from your_table
where date_column between add_months(trunc(sysdate, 'mm'), -1)
                      and trunc(sysdate, 'mm') + 16/24

and

select *
from your_table
where date_column between next_day(trunc(sysdate), 'FRIDAY') - 7 + 16/24 + 31/(24*60)
                      and next_day(trunc(sysdate), 'FRIDAY') + 16/24 + 30/(24*60)


问:
CreateThread seems to behave like fork()
I have this function

```<code>int APIENTRY _tWinMain(HINSTANCE hInstance,
                 HINSTANCE hPrevInstance,
                 LPTSTR    lpCmdLine,
                 int       nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);

// TODO: Place code here.
MSG     msg;
HACCEL  hAccelTable;
int     i;
DWORD   dwThreadIdArray[NUM_THREADS]; //edited after first post
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
PARAM_PASSED *paramPassed = NULL;
std::ostringstream ss;
std::wstring str;

// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_LSP3, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);

// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
    return FALSE;
}

hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LSP3));

// Initialize GDI+
GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL);

// Create event in order to let the other threads know
// when they can start posting message
hStartEvent = CreateEvent(  NULL,                   // default security attributes
                            TRUE,                   // manual-reset event
                            FALSE,                  // initial state is nonsignaled
                            TEXT("StartEvent"));    // object name

if(hStartEvent == NULL)
{
    ss << "_tWinMain: CreateEvent failed" << std::endl;
    str = string2wideString(ss.str().c_str());
    OutputDebugString(str.c_str());
    return 1;
}

// Create threads
for(i = 0; i < NUM_THREADS; i++)
{
    paramPassed = NULL;
    threadHandles[i] = CreateThread(NULL,                   // security context is default
                                    0,                      // stack size is default
                                    rectAnalyzer,           // start routine is rectAnalyzer
                                    paramPassed,            // parameter pointer is paramPassed
                                    0,                      // thread active
                                    &dwThreadIdArray[i]);   // variable used to store thread id
    if(threadHandles[i] == NULL)
    {
        ss << "_tWinMain: error CreateThread " << i << std::endl;
        str = string2wideString(ss.str().c_str());
        OutputDebugString(str.c_str());
    }
    else
    {
        ss << "_tWinMain: created thread " << i << std::endl;
        str = string2wideString(ss.str().c_str());
        OutputDebugString(str.c_str());
    }
}

// Let other threads start
SetEvent(hStartEvent);

// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
    if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

// Wait for all threads
WaitForMultipleObjects(NUM_THREADS, threadHandles, TRUE, INFINITE);

for(i = 0; i < NUM_THREADS; i++)
{
    CloseHandle(threadHandles[i]);
}

//Releases GDI+
Gdiplus::GdiplusShutdown(gdiplusToken);

return (int) msg.wParam;
}
</code>```

and I get this output:

```<code>_tWinMain: created thread 0
_tWinMain: created thread 0
_tWinMain: created thread 1
_tWinMain: created thread 0
_tWinMain: created thread 1
_tWinMain: created thread 2
_tWinMain: created thread 0
_tWinMain: created thread 1
_tWinMain: created thread 2
_tWinMain: created thread 3
The thread 'Win32 Thread' (0x159c) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x12bc) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x102c) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x1594) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x107c) has exited with code 1 (0x1).
The program '[2308] lsp3.exe: Native' has exited with code 0 (0x0).
</code>```

Why am I getting multiple output for thread 0...2 ? I don't know if I am creating 4 threads or 10 threads.. Moreover in the end it seems I created 4 threads plus primary thread..

答:
You are not clearing the stringstream ss in the loop, so the output just accumulates:

thread 0

  thread 0 1

  thread 0 1 2

  thread 0 1 2 3

Add a ss.str("") after doing each output.

Body:
I have this function

int APIENTRY _tWinMain(HINSTANCE hInstance,
                 HINSTANCE hPrevInstance,
                 LPTSTR    lpCmdLine,
                 int       nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);

// TODO: Place code here.
MSG     msg;
HACCEL  hAccelTable;
int     i;
DWORD   dwThreadIdArray[NUM_THREADS]; //edited after first post
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
PARAM_PASSED *paramPassed = NULL;
std::ostringstream ss;
std::wstring str;

// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_LSP3, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);

// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
    return FALSE;
}

hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LSP3));

// Initialize GDI+
GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL);

// Create event in order to let the other threads know
// when they can start posting message
hStartEvent = CreateEvent(  NULL,                   // default security attributes
                            TRUE,                   // manual-reset event
                            FALSE,                  // initial state is nonsignaled
                            TEXT("StartEvent"));    // object name

if(hStartEvent == NULL)
{
    ss << "_tWinMain: CreateEvent failed" << std::endl;
    str = string2wideString(ss.str().c_str());
    OutputDebugString(str.c_str());
    return 1;
}

// Create threads
for(i = 0; i < NUM_THREADS; i++)
{
    paramPassed = NULL;
    threadHandles[i] = CreateThread(NULL,                   // security context is default
                                    0,                      // stack size is default
                                    rectAnalyzer,           // start routine is rectAnalyzer
                                    paramPassed,            // parameter pointer is paramPassed
                                    0,                      // thread active
                                    &dwThreadIdArray[i]);   // variable used to store thread id
    if(threadHandles[i] == NULL)
    {
        ss << "_tWinMain: error CreateThread " << i << std::endl;
        str = string2wideString(ss.str().c_str());
        OutputDebugString(str.c_str());
    }
    else
    {
        ss << "_tWinMain: created thread " << i << std::endl;
        str = string2wideString(ss.str().c_str());
        OutputDebugString(str.c_str());
    }
}

// Let other threads start
SetEvent(hStartEvent);

// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
    if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

// Wait for all threads
WaitForMultipleObjects(NUM_THREADS, threadHandles, TRUE, INFINITE);

for(i = 0; i < NUM_THREADS; i++)
{
    CloseHandle(threadHandles[i]);
}

//Releases GDI+
Gdiplus::GdiplusShutdown(gdiplusToken);

return (int) msg.wParam;
}

and I get this output:

_tWinMain: created thread 0
_tWinMain: created thread 0
_tWinMain: created thread 1
_tWinMain: created thread 0
_tWinMain: created thread 1
_tWinMain: created thread 2
_tWinMain: created thread 0
_tWinMain: created thread 1
_tWinMain: created thread 2
_tWinMain: created thread 3
The thread 'Win32 Thread' (0x159c) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x12bc) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x102c) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x1594) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x107c) has exited with code 1 (0x1).
The program '[2308] lsp3.exe: Native' has exited with code 0 (0x0).

Why am I getting multiple output for thread 0...2 ? I don't know if I am creating 4 threads or 10 threads.. Moreover in the end it seems I created 4 threads plus primary thread..


问:
How can I iterate through the result of itertools.product()?
I am trying to implement a Q-Learning algorithm, my state-space contains all possible combinations of numbers 0,1,2 in a vector of a given length.

Now I am trying to initialize a Q-Table full of zeros which would have the same amount of rows as my state-space. And then I want to in each step to run through the state space and check which of all possible state vector is right now. But that means I have to subscript an itertools.product()
How can I do that? because when I try to print it n-th vector from the product it shows an error that product is not subscriptable

I tried this:

```<code>import itertools
NUMBER_OF_SECTORS = 6
state_space = itertools.product(*[[0, 1, 2]] * NUMBER_OF_SECTORS)
length = len(list(state_space)) # 729
       for obs in range(length):
            print(list(state_space[obs]))
</code>```

Also, is there a possibility, how can I rid the length variable? Because when I define the for loop as: for obs in range(len(list(state_space))) it is not executed at all.

Thank you very much

答:
You can only iterate over an instance of product once: after that, it is consumed. list iterates over the instance in order to produce a list whose length you compute. Once you do that, the state space is gone; all you have left is the length.

You don't need to convert the state space to a list or compute its length; you can just iterate over it directly:

```<code>state_space = itertools.product([0,1,2], repeat=NUMBER_OF_SECTORS)
for state in state_space:
    print(state)
</code>```

Body:
I am trying to implement a Q-Learning algorithm, my state-space contains all possible combinations of numbers 0,1,2 in a vector of a given length.

Now I am trying to initialize a Q-Table full of zeros which would have the same amount of rows as my state-space. And then I want to in each step to run through the state space and check which of all possible state vector is right now. But that means I have to subscript an itertools.product()
How can I do that? because when I try to print it n-th vector from the product it shows an error that product is not subscriptable

I tried this:

import itertools
NUMBER_OF_SECTORS = 6
state_space = itertools.product(*[[0, 1, 2]] * NUMBER_OF_SECTORS)
length = len(list(state_space)) # 729
       for obs in range(length):
            print(list(state_space[obs]))

Also, is there a possibility, how can I rid the length variable? Because when I define the for loop as: for obs in range(len(list(state_space))) it is not executed at all.

Thank you very much

Body:
You can only iterate over an instance of product once: after that, it is consumed. list iterates over the instance in order to produce a list whose length you compute. Once you do that, the state space is gone; all you have left is the length.

You don't need to convert the state space to a list or compute its length; you can just iterate over it directly:

state_space = itertools.product([0,1,2], repeat=NUMBER_OF_SECTORS)
for state in state_space:
    print(state)


问:
Python how to fix year out of range error
I am trying to convert timezones in a csv file, and the code that I am using for this used to work fine but for some reason it is giving me the error dateutil.parser._parser.ParserError: year 20200320 is out of range: 20200320.0 21:43:00. This is weird because this error did not happen before with this code.

When I try to reproduce the error with the following code:

```<code>import pandas as pd

#Creating sample dataframe
lst1 = [['Bananas', 'Bali', '20200108', '15:30:00', 1.58, 1.85, 1.50, 1.50],
['Bananas', 'Bali', '20200108', '22:00:00', 1.68, 1.78, 1.40, 1.60],
['Bananas', 'Bali', '20200109', '15:30:00', 1.88, 1.95, 1.70, 1.86],
['Bananas', 'Bali', '20200109', '22:00:00', 1.78, 1.88, 1.60, 1.65],
['Coconut', 'Bahamas', '20200110', '15:30:00', 2.58, 2.85, 2.50, 2.50],
['Coconut', 'Bahamas', '20200110', '22:00:00', 2.68, 2.78, 2.40, 2.60],
['Coconut', 'Bahamas', '20200111', '15:30:00', 2.88, 2.95, 2.70, 2.86],
['Coconut', 'Bahamas', '20200111', '22:00:00', 2.78, 2.88, 2.60, 2.65]]

df1 = pd.DataFrame(lst1, columns =['Name', 'Origin', 'Date', 'Time', 'Open', 'High', 'Low', 'Close'])
print('Second Dataframe')
print(df1)

df1["Datetime"] = df1["Date"].astype(str) + ' ' + df1["Time"].astype(str)
df1["Datetime"] = pd.to_datetime(df1["Datetime"])
df1["Datetime"] = df1["Datetime"].dt.tz_localize('Europe/Paris').dt.tz_convert('US/Eastern')
df1["Datetime"] = df1["Datetime"].dt.tz_localize(None)
df1["Datetime"] = df1["Datetime"].astype(str)

print(df1)
</code>```

it does not give me the error, eventhough it is the same code and data. I am verry confused by this and I hope that someone here is able to help me out.

I tried to divide the date by 1000.0, which was an answer here on SO, but then it gives me an error that I cant do calculations with strings, but I also cannot convert the date to datetime64. I hope someone here knows how to fix this issue.

EDIT:
Here is a sample of the actual .csv file I am using. As you can see, it has lots of whitespaces, which i remove within the script.

```<code>Ticker;Exchange;Date;None;Time;Open; High;  Low;    Close;   Volume;   VWAP;      Trades
AAPL ; NASDAQ ; 20200128; ; 10:00:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 10 ; 0.67 ; 3
AAPL ; NASDAQ ; 20200128; ; 10:01:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 0 ; 0.67 ; 0
AAPL ; NASDAQ ; 20200128; ; 10:02:00 ; 0.66 ; 0.66 ; 0.66 ; 0.66 ; 4 ; 0.66 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:03:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 3 ; 0.67 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:04:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 4 ; 0.67 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:05:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 0 ; 0.67 ; 0
AAPL ; NASDAQ ; 20200128; ; 10:06:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 0 ; 0.67 ; 0
AAPL ; NASDAQ ; 20200128; ; 10:07:00 ; 0.65 ; 0.65 ; 0.65 ; 0.65 ; 4 ; 0.65 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:08:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 2 ; 0.67 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:09:00 ; 0.7 ; 0.7 ; 0.6422 ; 0.6422 ; 16 ; 0.67157 ; 4
AAPL ; NASDAQ ; 20200128; ; 10:10:00 ; 0.7 ; 0.7 ; 0.7 ; 0.7 ; 1 ; 0.7 ; 1
</code>```

The whole code I am using for this:

```<code>import pandas as pd
import os

print("Converting Timezone")

TEMP = pd.read_csv("Temp\\data.csv", sep=";")

#Removing Whitespaces
TEMP.rename(columns=lambda x: x.strip(), inplace=True)
TEMP['Ticker'] = TEMP["Ticker"].astype(str).str.strip()
TEMP['Exchange'] = TEMP["Exchange"].astype(str).str.strip()
TEMP['Date'] = TEMP["Date"].astype(str).str.strip()
TEMP['Time'] = TEMP["Time"].astype(str).str.strip()
TEMP['Open'] = TEMP["Open"].astype(str).str.strip()
TEMP['Open'] = TEMP["Open"].astype(float)
TEMP['High'] = TEMP["High"].astype(str).str.strip()
TEMP['High'] = TEMP["High"].astype(float)
TEMP['Low'] = TEMP["Low"].astype(str).str.strip()
TEMP['Low'] = TEMP["Low"].astype(float)
TEMP['Close'] = TEMP["Close"].astype(str).str.strip()
TEMP['Close'] = TEMP["Close"].astype(float)
TEMP['Volume'] = TEMP["Volume"].astype(str).str.strip()
TEMP['Volume'] = TEMP["Volume"].astype(float)
TEMP['VWAP'] = TEMP["VWAP"].astype(str).str.strip()
TEMP['VWAP'] = TEMP["VWAP"].astype(float)
TEMP['Trades'] = TEMP["Trades"].astype(str).str.strip()
TEMP['Trades'] = TEMP["Trades"].astype(float)
TEMP.drop(columns = ['None'], inplace=True)

#converting dates, here is where I get the error (after print(TEMP))
TEMP["Datetime"] = TEMP["Date"].astype(str) + ' ' + TEMP["Time"].astype(str)
print(TEMP)
TEMP["Datetime"] = pd.to_datetime(TEMP["Datetime"])
TEMP["Datetime"] = TEMP["Datetime"].dt.tz_localize('Europe/Paris').dt.tz_convert('US/Eastern')
TEMP["Datetime"] = TEMP["Datetime"].dt.tz_localize(None)
TEMP["Datetime"] = TEMP["Datetime"].astype(str)
new = TEMP["Datetime"].str.split(" ", n=1, expand=True)
TEMP["Date"] = new[0]
TEMP["Time"] = new[1]
TEMP.drop(columns =["Datetime"], inplace = True)
TEMP["Date"] = pd.to_datetime(TEMP["Date"])
TEMP['Date'] = TEMP.Date.dt.strftime('%Y%m%d')
TEMP["Date"] = TEMP["Date"].astype(str)
TEMP.drop_duplicates(subset=['Ticker', 'Exchange', 'Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'VWAP', 'Trades'], keep='first')
TEMP.sort_values(by=['Date', 'Time'])

print("Dataframe")
print(TEMP)
</code>```

EDIT:

Alright so making the following changes to the code seemed to fix the issue, which I think is verry weird but ill go with it.

```<code>TEMP["Datetime"] = pd.to_datetime(TEMP["Datetime"], errors='coerce')
</code>```

adding errors='coerce' to this line fixed me not getting the error. This however should return NaT values for each line that had an error, but I'm not getting any, so all my data gets converted and no errors are found (atleast thats what I think this means), eventhough it previously said it had errors. I'm happy that the issue is resolved, but still flabbergasted about the solution.

also setting `dtype='object' seemed to help here, probably because I have a large data set.

答:
Well, there's a lot to say.

First, pandas automatically detects the type for each columns. With your csv data, everything was correctly imported, to the exception of the column Date which was imported as int64. The whole paragraph called # removing white spaces is then not necessary. Note that the code is 100% functionnal, if you keep this paragraph.

Also consider the option dtype='object' in the read_csv function. So every column will be set as object data.

Second, regarding your question, when I remove the 1st paragraph and run merely this batch of code, I do manage to get a Datetime column of type datetime64[ns]:

TEMP = pd.read_csv(file, sep=";")
TEMP.drop(columns = ['None'], inplace=True)
TEMP["Datetime"] = TEMP["Date"].astype(str) + ' ' + TEMP["Time"].astype(str)
TEMP["Datetime"] = pd.to_datetime(TEMP["Datetime"])
print(TEMP)
print(TEMP.dtypes)
```

Body:
I am trying to convert timezones in a csv file, and the code that I am using for this used to work fine but for some reason it is giving me the error dateutil.parser._parser.ParserError: year 20200320 is out of range: 20200320.0 21:43:00. This is weird because this error did not happen before with this code.

When I try to reproduce the error with the following code:

import pandas as pd

#Creating sample dataframe
lst1 = [['Bananas', 'Bali', '20200108', '15:30:00', 1.58, 1.85, 1.50, 1.50],
['Bananas', 'Bali', '20200108', '22:00:00', 1.68, 1.78, 1.40, 1.60],
['Bananas', 'Bali', '20200109', '15:30:00', 1.88, 1.95, 1.70, 1.86],
['Bananas', 'Bali', '20200109', '22:00:00', 1.78, 1.88, 1.60, 1.65],
['Coconut', 'Bahamas', '20200110', '15:30:00', 2.58, 2.85, 2.50, 2.50],
['Coconut', 'Bahamas', '20200110', '22:00:00', 2.68, 2.78, 2.40, 2.60],
['Coconut', 'Bahamas', '20200111', '15:30:00', 2.88, 2.95, 2.70, 2.86],
['Coconut', 'Bahamas', '20200111', '22:00:00', 2.78, 2.88, 2.60, 2.65]]

df1 = pd.DataFrame(lst1, columns =['Name', 'Origin', 'Date', 'Time', 'Open', 'High', 'Low', 'Close'])
print('Second Dataframe')
print(df1)

df1["Datetime"] = df1["Date"].astype(str) + ' ' + df1["Time"].astype(str)
df1["Datetime"] = pd.to_datetime(df1["Datetime"])
df1["Datetime"] = df1["Datetime"].dt.tz_localize('Europe/Paris').dt.tz_convert('US/Eastern')
df1["Datetime"] = df1["Datetime"].dt.tz_localize(None)
df1["Datetime"] = df1["Datetime"].astype(str)

print(df1)

it does not give me the error, eventhough it is the same code and data. I am verry confused by this and I hope that someone here is able to help me out.

I tried to divide the date by 1000.0, which was an answer here on SO, but then it gives me an error that I cant do calculations with strings, but I also cannot convert the date to datetime64. I hope someone here knows how to fix this issue.

EDIT:
Here is a sample of the actual .csv file I am using. As you can see, it has lots of whitespaces, which i remove within the script.

Ticker;Exchange;Date;None;Time;Open; High;  Low;    Close;   Volume;   VWAP;      Trades
AAPL ; NASDAQ ; 20200128; ; 10:00:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 10 ; 0.67 ; 3
AAPL ; NASDAQ ; 20200128; ; 10:01:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 0 ; 0.67 ; 0
AAPL ; NASDAQ ; 20200128; ; 10:02:00 ; 0.66 ; 0.66 ; 0.66 ; 0.66 ; 4 ; 0.66 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:03:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 3 ; 0.67 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:04:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 4 ; 0.67 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:05:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 0 ; 0.67 ; 0
AAPL ; NASDAQ ; 20200128; ; 10:06:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 0 ; 0.67 ; 0
AAPL ; NASDAQ ; 20200128; ; 10:07:00 ; 0.65 ; 0.65 ; 0.65 ; 0.65 ; 4 ; 0.65 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:08:00 ; 0.67 ; 0.67 ; 0.67 ; 0.67 ; 2 ; 0.67 ; 1
AAPL ; NASDAQ ; 20200128; ; 10:09:00 ; 0.7 ; 0.7 ; 0.6422 ; 0.6422 ; 16 ; 0.67157 ; 4
AAPL ; NASDAQ ; 20200128; ; 10:10:00 ; 0.7 ; 0.7 ; 0.7 ; 0.7 ; 1 ; 0.7 ; 1

The whole code I am using for this:

import pandas as pd
import os

print("Converting Timezone")

TEMP = pd.read_csv("Temp\\data.csv", sep=";")

#Removing Whitespaces
TEMP.rename(columns=lambda x: x.strip(), inplace=True)
TEMP['Ticker'] = TEMP["Ticker"].astype(str).str.strip()
TEMP['Exchange'] = TEMP["Exchange"].astype(str).str.strip()
TEMP['Date'] = TEMP["Date"].astype(str).str.strip()
TEMP['Time'] = TEMP["Time"].astype(str).str.strip()
TEMP['Open'] = TEMP["Open"].astype(str).str.strip()
TEMP['Open'] = TEMP["Open"].astype(float)
TEMP['High'] = TEMP["High"].astype(str).str.strip()
TEMP['High'] = TEMP["High"].astype(float)
TEMP['Low'] = TEMP["Low"].astype(str).str.strip()
TEMP['Low'] = TEMP["Low"].astype(float)
TEMP['Close'] = TEMP["Close"].astype(str).str.strip()
TEMP['Close'] = TEMP["Close"].astype(float)
TEMP['Volume'] = TEMP["Volume"].astype(str).str.strip()
TEMP['Volume'] = TEMP["Volume"].astype(float)
TEMP['VWAP'] = TEMP["VWAP"].astype(str).str.strip()
TEMP['VWAP'] = TEMP["VWAP"].astype(float)
TEMP['Trades'] = TEMP["Trades"].astype(str).str.strip()
TEMP['Trades'] = TEMP["Trades"].astype(float)
TEMP.drop(columns = ['None'], inplace=True)

#converting dates, here is where I get the error (after print(TEMP))
TEMP["Datetime"] = TEMP["Date"].astype(str) + ' ' + TEMP["Time"].astype(str)
print(TEMP)
TEMP["Datetime"] = pd.to_datetime(TEMP["Datetime"])
TEMP["Datetime"] = TEMP["Datetime"].dt.tz_localize('Europe/Paris').dt.tz_convert('US/Eastern')
TEMP["Datetime"] = TEMP["Datetime"].dt.tz_localize(None)
TEMP["Datetime"] = TEMP["Datetime"].astype(str)
new = TEMP["Datetime"].str.split(" ", n=1, expand=True)
TEMP["Date"] = new[0]
TEMP["Time"] = new[1]
TEMP.drop(columns =["Datetime"], inplace = True)
TEMP["Date"] = pd.to_datetime(TEMP["Date"])
TEMP['Date'] = TEMP.Date.dt.strftime('%Y%m%d')
TEMP["Date"] = TEMP["Date"].astype(str)
TEMP.drop_duplicates(subset=['Ticker', 'Exchange', 'Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'VWAP', 'Trades'], keep='first')
TEMP.sort_values(by=['Date', 'Time'])

print("Dataframe")
print(TEMP)

EDIT:

Alright so making the following changes to the code seemed to fix the issue, which I think is verry weird but ill go with it.

TEMP["Datetime"] = pd.to_datetime(TEMP["Datetime"], errors='coerce')

adding errors='coerce' to this line fixed me not getting the error. This however should return NaT values for each line that had an error, but I'm not getting any, so all my data gets converted and no errors are found (atleast thats what I think this means), eventhough it previously said it had errors. I'm happy that the issue is resolved, but still flabbergasted about the solution.

also setting `dtype='object' seemed to help here, probably because I have a large data set.


问:
Python3 Qt5 MainWindow
I have an application flow which looks like this. At startup a MainWindow is shown and asks the user to choose a project or create a new one. After a project is created or chosen from the list, I want to close this MainWindow and open another MainWindow.

In my main.py the code looks like this:

```<code>app = QApplication([])

ui_project_list_view = ProjectListView()
ui_project_list_view.show()

app.exec_()
</code>```

Now I want to close the first main window (ui_project_list_view) and open the other main window (ui_project_view). This code is called from within ui_project_list_view.

```<code>ui_project_view = ProjectView()
ui_project_view.show()
main_view.close()
</code>```

No matter in which order I show or close, the application quits. How should I design my "window-flow" ?

Thanks for your help.

答:
If you open most programs like Word or Excel- or QtDesigner for example- you'll see a blank main window initialize, and then a popup will appear asking you to choose your project.

If you wanted to apply this to your code, the ProjectView should be the main window and the ProjectListView would be the popup. The ProjectView would call this after initializing, in a setup function perhaps. After ProjectListView finishes, then ProjectView would just need to update the screen with the information that ProjectListView has.

Title: Python3 Qt5 MainWindow

Body:
I have an application flow which looks like this. At startup a MainWindow is shown and asks the user to choose a project or create a new one. After a project is created or chosen from the list, I want to close this MainWindow and open another MainWindow.

In my main.py the code looks like this:

app = QApplication([])

ui_project_list_view = ProjectListView()
ui_project_list_view.show()

app.exec_()

Now I want to close the first main window (ui_project_list_view) and open the other main window (ui_project_view). This code is called from within ui_project_list_view.

ui_project_view = ProjectView()
ui_project_view.show()
main_view.close()

No matter in which order I show or close, the application quits. How should I design my "window-flow" ?

Thanks for your help.