问:
Make manual servervalidation and color textfield if failed
I am trying to change the color of a textfield to red if a serverside validation fails.

If result is True or False nothing happens

JQuery

```<code>        $('.datein').change(function () {
        //send servervalidering ajax
        var data = { dateOut: $('#resource_dateout').val(), dateHourOut: $('#resource_hourout').val(), dateMinuteOut: $('#resource_minuteout').val(),
            dateIn: $('#resource_datein').val(), dateHourIn: $('#resource_hourin').val(), dateMinuteIn: $('#resource_minutein').val()
        };
        $.post("Resource/isDateValid", data, ajaxsuccess);
    });

function ajaxsuccess(result) {
    if ($('.datein').hasClass('.resourceerror')) {
        if (result == "True") {
            $('.datein').removeClass('.resourceerror');
        }
    }
    else if (result == "False") {
        $('.datein').addClass('.resourceerror');
    }
}
</code>```

Html

```<code>                <span class="editor-field">
                    @Html.TextBoxFor(m => m.DateIn.Date, new { @Id = "resource_datein", @class = "datepicker datein", maxlength = "10" })
                    @Html.TextBoxFor(m => m.DateIn.Hour, new { @Id = "resource_hourin", @class = "datein", maxlength = "2" })
                    :
                    @Html.TextBoxFor(m => m.DateIn.Minute, new { @Id = "resource_minutein", @class = "datein", maxlength = "2" })
                </span>
                <span>
                    @Html.ValidationMessageFor(m => m.DateIn.Date)
                    @Html.ValidationMessageFor(m => m.DateIn.Hour)
                    @Html.ValidationMessageFor(m => m.DateIn.Minute)
                </span>
</code>```

Is there a way I can just toggle a validation instead? My code dont work, I am 100% sure the Ajax call either returns "True" or "False"

Edit: When accessing the css classes I wrote hasClass('.classname') instead of hasClass('classname')

答: Change the if(result) to if(result == "True"). Since result is the AJAX response, it is a string, and if(result) just tests to see if it has non-zero value, not if it the text of the string is "True". This MIGHT help, since if server validation fails and returns "False", your current code removes the .resourceerror class from the inputs</p>

Body:
I am trying to change the color of a textfield to red if a serverside validation fails.

If result is True or False nothing happens

JQuery

        $('.datein').change(function () {
        //send servervalidering ajax
        var data = { dateOut: $('#resource_dateout').val(), dateHourOut: $('#resource_hourout').val(), dateMinuteOut: $('#resource_minuteout').val(),
            dateIn: $('#resource_datein').val(), dateHourIn: $('#resource_hourin').val(), dateMinuteIn: $('#resource_minutein').val()
        };
        $.post("Resource/isDateValid", data, ajaxsuccess);
    });

function ajaxsuccess(result) {
    if ($('.datein').hasClass('.resourceerror')) {
        if (result == "True") {
            $('.datein').removeClass('.resourceerror');
        }
    }
    else if (result == "False") {
        $('.datein').addClass('.resourceerror');
    }
}

Html

                    @Html.TextBoxFor(m => m.DateIn.Date, new { @Id = "resource_datein", @class = "datepicker datein", maxlength = "10" })
                    @Html.TextBoxFor(m => m.DateIn.Hour, new { @Id = "resource_hourin", @class = "datein", maxlength = "2" })
                    :
                    @Html.TextBoxFor(m => m.DateIn.Minute, new { @Id = "resource_minutein", @class = "datein", maxlength = "2" })

                    @Html.ValidationMessageFor(m => m.DateIn.Date)
                    @Html.ValidationMessageFor(m => m.DateIn.Hour)
                    @Html.ValidationMessageFor(m => m.DateIn.Minute)

Is there a way I can just toggle a validation instead? My code dont work, I am 100% sure the Ajax call either returns "True" or "False"

Edit: When accessing the css classes I wrote hasClass('.classname') instead of hasClass('classname')


来源: stackexchange

问:
How do I use the pipe operator or something related to break a pipeline into two steps?
Is there a way to break this into two steps so that the ml_logistic_regression() can be applied separately to flights_pipeline?

Below is working code for the pipeline:

```<code>flights_pipeline <- ml_pipeline(sc) %>%
  ft_dplyr_transformer(
    tbl = df
    ) %>%
  ft_binarizer(
    input_col = "dep_delay",
    output_col = "delayed",
    threshold = 15
  ) %>%
  ft_bucketizer(
    input_col = "sched_dep_time",
    output_col = "hours",
    splits = c(400, 800, 1200, 1600, 2000, 2400)
  )  %>%
  ft_r_formula(delayed ~ month + day + hours + distance) %>%
  ml_logistic_regression()
</code>```

This is my attempt, I'd like to break it into two steps - something like this:

```<code>flights_pipeline <- ml_pipeline(sc) %>%
  ft_dplyr_transformer(
    tbl = df
    ) %>%
  ft_binarizer(
    input_col = "dep_delay",
    output_col = "delayed",
    threshold = 15
  ) %>%
  ft_bucketizer(
    input_col = "sched_dep_time",
    output_col = "hours",
    splits = c(400, 800, 1200, 1600, 2000, 2400)
  )  %>%
  ft_r_formula(delayed ~ month + day + hours + distance)

flights_pipeline_with_model <- flights_pipeline %>%
  ml_logistic_regression()

</code>```

答:
Not clear based on the description and the OP's second code block.  If the intention is to create an object within the pipe and continue with the pipe, perhaps pipeR could help

```<code>library(pipeR)
ml_pipeline(sc) %>%
  ft_dplyr_transformer(
    tbl = df
    ) %>%
  ft_binarizer(
    input_col = "dep_delay",
    output_col = "delayed",
    threshold = 15
  ) %>%
  ft_bucketizer(
    input_col = "sched_dep_time",
    output_col = "hours",
    splits = c(400, 800, 1200, 1600, 2000, 2400)
  )  %>%
  ft_r_formula(delayed ~ month + day + hours + distance) %>%
  (~flights_pipeline) %>>%
  ml_logistic_regression()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to break this into two steps so that the ml_logistic_regression() can be applied separately to flights_pipeline?

Below is working code for the pipeline:

flights_pipeline <- ml_pipeline(sc) %>%
  ft_dplyr_transformer(
    tbl = df
    ) %>%
  ft_binarizer(
    input_col = "dep_delay",
    output_col = "delayed",
    threshold = 15
  ) %>%
  ft_bucketizer(
    input_col = "sched_dep_time",
    output_col = "hours",
    splits = c(400, 800, 1200, 1600, 2000, 2400)
  )  %>%
  ft_r_formula(delayed ~ month + day + hours + distance) %>%
  ml_logistic_regression()

This is my attempt, I'd like to break it into two steps - something like this:

flights_pipeline <- ml_pipeline(sc) %>%
  ft_dplyr_transformer(
    tbl = df
    ) %>%
  ft_binarizer(
    input_col = "dep_delay",
    output_col = "delayed",
    threshold = 15
  ) %>%
  ft_bucketizer(
    input_col = "sched_dep_time",
    output_col = "hours",
    splits = c(400, 800, 1200, 1600, 2000, 2400)
  )  %>%
  ft_r_formula(delayed ~ month + day + hours + distance)

flights_pipeline_with_model <- flights_pipeline %>%
  ml_logistic_regression()

Body:
Not clear based on the description and the OP's second code block.  If the intention is to create an object within the pipe and continue with the pipe, perhaps pipeR could help

library(pipeR)
ml_pipeline(sc) %>%
  ft_dplyr_transformer(
    tbl = df
    ) %>%
  ft_binarizer(
    input_col = "dep_delay",
    output_col = "delayed",
    threshold = 15
  ) %>%
  ft_bucketizer(
    input_col = "sched_dep_time",
    output_col = "hours",
    splits = c(400, 800, 1200, 1600, 2000, 2400)
  )  %>%
  ft_r_formula(delayed ~ month + day + hours + distance) %>%
  (~flights_pipeline) %>>%
  ml_logistic_regression()


问:
stop processes in batch files with python
I am new to programming and I want to make a python tool to automate a process. I want to end a running batch file without killing it, is this even possible?
I don't want to kill it, because it scans for IP packages in running time and when stopped, creates a file with the data, and I want to work with this file.
Thanks for your help</p>

答:
```<code>subprocess.call("taskkill /F /im process.exe")
</code>```


问:
New Web Dev person and need help on GitHub
I am new to GitHub and having issues uploading a website.....

When I upload to GitHub, it separates folders (Here is the image of what I am seeing GitHub) and thus website doesn't display properly.

Here is the image of the file on my computer Here is what I am seeing on computer

I attached screenshots, any help would be great....

I am confused af at this point in time

答:
Try To push changes correctly as it doesn't happen usually. Read this:
Open your Command prompt first then move to the particular which here contains your whole website.
Start with

git init (it will initialize your folder to be pushed up or pulled
to git Controls)

then git add . (To add All the files create your
.gitignore file carefully)

git commit -m "Whatever you want to write
us a note about the changes"

then git push -u origin main

Hope Your problem will be solved or maybe something you can only diagnose because you are there sitting and functioning
**Note If there is any folder containing called .git, delete that. Before proceeding the way I mentioned **


问:
Dealing with object return from axios
Someone could please point me what I need do to get the nuxt axios return which works inside vuetify v-for?

I'm using the following code:

```<code>async asyncData() {
    let res = await axios.get('https://jsonplaceholder.typicode.com/posts')
        console.log(res)
        let objectPosts = {}
        objectPosts = res.data
        return (posts: objectPosts)
},
</code>```

My componnent data is:

```<code>data() {
    return {
        posts: {}
    }
},
</code>```

My v-for is:

```<code><article v-for="(post, index) in posts" :key="index">
</code>```

And the error I'm getting is:

```<code>[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'length')"
</code>```

If I fill my componnent data with the json as object manually works fine, example:

```<code>data() {
    return {
        posts: [
            {
            "userId": 1,
            "id": 1,
            "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
            "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
            },
            {
            "userId": 1,
            "id": 2,
            "title": "qui est esse",
            "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
            }
        ]
    }
},
</code>```

Console log show the array from axios too.

The application is using SSR, my initial guess was on be an issue with async, page get rendered first and object don't exists triggering this error.

答: You need to change the type of your posts to Array []

Title: Dealing with object return from axios

Body:
Someone could please point me what I need do to get the nuxt axios return which works inside vuetify v-for?

I'm using the following code:

async asyncData() {
    let res = await axios.get('https://jsonplaceholder.typicode.com/posts')
        console.log(res)
        let objectPosts = {}
        objectPosts = res.data
        return (posts: objectPosts)
},

My componnent data is:

data() {
    return {
        posts: {}
    }
},

My v-for is:

And the error I'm getting is:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'length')"

If I fill my componnent data with the json as object manually works fine, example:

data() {
    return {
        posts: [
            {
            "userId": 1,
            "id": 1,
            "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
            "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
            },
            {
            "userId": 1,
            "id": 2,
            "title": "qui est esse",
            "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
            }
        ]
    }
},

Console log show the array from axios too.

The application is using SSR, my initial guess was on be an issue with async, page get rendered first and object don't exists triggering this error.


问:
how to check if a php file is obfuscated?
is there any way we can check if a php file has been obfuscated, using php? I was thinking regex maybe (for instance ioncube's encoded file contains a very long alphabet string, etc.</p>

答: I think you can use token_get_all() to parse the file - then compute some statistics. For example check for number of function calls(in calse obfuscator uses some eval() string and nothing else) and calculate average function length - for obfuscators it will usually be about 3-5 chars, for normal PHP code it should be much bigger. You can also use dictionary lookup for function/variable names, check for comments etc. I think if you know all obfuscator formats that you want to detect - it will be easy.</p>

ContentLicense: CC BY-SA 3.0


问:
Are Fn() + 'static and FnMut() + 'static equivalent?
I have what I think to be a simple question, but not much luck finding an answer for it.

Background

I understand the difference between Fn and FnMut in Rust, but I see quite often the need to accept closures that require a 'static lifetime bound.

The Question

Is an Fn() + 'static equivalent to FnMut() + 'static?

My Opinion

In my opinion, I seem to believe they are, because an Fn allows for capturing immutable references to its environment, whereas FnMut, mutable references, however, due to the 'static lifetime bound, the only references they can have, are owned ones, and therefore will almost always have move semantics associated with the closure. Since only owned values, or special &'static references can have 'static lifetime, it seems to me pointless to want to have or need an FnMut() in this case, since there is no mutable reference one might be able to get to the closures environment.

Am I wrong with this conclusion? My guess is yes, otherwise there would probably be a Clippy lint for this.

答:
Any closure type can capture any kind of data. The difference is how the closure can access the captured data while it is executed. An Fn closure receives a shared reference to its captured data. An FnMut closure receives a mutable reference to its captured data, so it can mutate it. And finally, an FnOnce closure receives ownership of the captrued data, which is why you can call it only once.

The 'static trait bound means that the captured data has static lifetime. This is completely orthogonal to the question what a closure can do with its captured data while it is called.


问:
Recoding rare categories of a variable to category -"other" based on condition
Need to transform variable below, based on category quantity in the dataset

so that categories that appear less than two times are re-named to category "other"

Data example

Desirable output

I used to use below chunk of code for such transformation but since I moved to R 4.05 it throws me an error.

```<code>levels(data$Country_of_origin) <-ifelse(table(data&Country_of_origin)>2,"OTHER",levels(data&Country_of_origin))
</code>```

答:
Here is another option:

Packages

```<code>library(dplyr)
library(tibble)
library(magrittr)
</code>```

Input

```<code>data <- tibble( country = c('USA', 'USA', 'Germany', 'Japan', 'USA', 'USA'))
</code>```

data

```<code># A tibble: 6 x 1
  country
  <chr>
1 USA
2 USA
3 Germany
4 Japan
5 USA
6 USA
</code>```

Solution

```<code>few_country <- data %>% count(country) %>% filter(n<=2)

data %>%
   mutate(new_country = case_when(country %in% few_country$country ~ "OTHER",
                                     TRUE ~ country))
</code>```

Output

```<code># A tibble: 6 x 2
  country new_country
  <chr>   <chr>
1 USA     USA
2 USA     USA
3 Germany OTHER
4 Japan   OTHER
5 USA     USA
6 USA     USA

</code>```

Body:
Need to transform variable below, based on category quantity in the dataset

so that categories that appear less than two times are re-named to category "other"

Data example

Desirable output

I used to use below chunk of code for such transformation but since I moved to R 4.05 it throws me an error.

levels(data$Country_of_origin) <-ifelse(table(data&Country_of_origin)>2,"OTHER",levels(data&Country_of_origin))

Body:
Here is another option:

Packages

library(dplyr)
library(tibble)
library(magrittr)

Input

data <- tibble( country = c('USA', 'USA', 'Germany', 'Japan', 'USA', 'USA'))

data

# A tibble: 6 x 1
  country
  <chr>
1 USA
2 USA
3 Germany
4 Japan
5 USA
6 USA

Solution

few_country <- data %>% count(country) %>% filter(n<=2)

data %>%
   mutate(new_country = case_when(country %in% few_country$country ~ "OTHER",
                                     TRUE ~ country))

Output

# A tibble: 6 x 2
  country new_country
  <chr>   <chr>
1 USA     USA
2 USA     USA
3 Germany OTHER
4 Japan   OTHER
5 USA     USA
6 USA     USA


问:
update Spring BOOT-INF/lib jars
I am trying to update a jar in rest-xxxx.jar, this rest jar is basically a SpringBoot Jar and has the folder structure of BOOT-INF/lib/<dependencies.jars> when you unpack it.

Now I want to replace a dependency jar within this rest-xxxx.jar, so I used the command:

```<code>jar uf rest-xxxx.jar BOOT-INF/lib/new-version-jar-same-name.jar
</code>```

How ever I got errors during booting process:

Exception in thread "main" java.lang.IllegalStateException: Unable to open nested entry 'BOOT-INF/lib/new-version-jar-same-name.jar'. It has been compressed and nested jar files must be stored without compression. Please check the mechanism used to create your executable jar file

I noticed that there's a 0 option for jar command to avoid compression, so I did:

```<code>jar u0f rest-xxxx.jar BOOT-INF/lib/new-version-jar-same-name.jar
</code>```

But then I got a similar compression issue like below:

Exception in thread "main" java.lang.IllegalStateException: Unable to open nested entry 'BOOT-INF/lib/new-version-jar-same-name.jar/META-INF/MANIFEST.MF'. It has been compressed and nested jar files must be stored without compression. Please check the mechanism used to create your executable jar file

What should I do when I need to replace the dependency jars within a given springboot jar?

please note: I understand the best practise is to build from updated pom.xml, the limitations we have is that we cannot get the right version source code at the moment, hence we are trying to patch the existing springboot jar instead of rebuilding it.

答:
My initial answer was deleted, so I'm following recommendations and updating my answer.

Regarding comments, sometimes it's faster to cut corners and just patch jar/zip file directly instead of rebuilding the whole thing that can take a lot of time on large projects.

There is nothing wrong with the Spring Boot file layout unless jar names and compression methods are retained, the nested .jars are only "indexed" by their names, and OP means replacing .jar with the same name.

I've faced the very same question as OP and haven't found a solution, so this is my attempt to solve it with utility https://github.com/denizk0/cpzip

This utility 1. Updates a file in the zip/jar, if it's a nested archive, it's expanded to a temp file, then GOTO 1. Nesting may be of any depth. Eventually, all nested archives are wrapped back together, temp files are cleaned. Compression methods are preserved.

Here's an example:

cpzip ~/.m2/repository/joda-time/joda-time/2.9.9/joda-time-2.9.9.jar camunda-bpm-run-7.16.0.zip internal/camunda-bpm-run-core.jar/BOOT-INF/lib -v

will copy or replace joda-time-2.9.9.jar from local maven repo in camunda-bpm-run-7.16.0.zip from current directory in nested internal/camunda-bpm-run-core.jar

PS: It is even possible to replace .js files in webjars

Title: update Spring BOOT-INF/lib jars

Body:
I am trying to update a jar in rest-xxxx.jar, this rest jar is basically a SpringBoot Jar and has the folder structure of BOOT-INF/lib/<dependencies.jars> when you unpack it.

Now I want to replace a dependency jar within this rest-xxxx.jar, so I used the command:

jar uf rest-xxxx.jar BOOT-INF/lib/new-version-jar-same-name.jar

How ever I got errors during booting process:

Exception in thread "main" java.lang.IllegalStateException: Unable to open nested entry 'BOOT-INF/lib/new-version-jar-same-name.jar'. It has been compressed and nested jar files must be stored without compression. Please check the mechanism used to create your executable jar file

I noticed that there's a 0 option for jar command to avoid compression, so I did:

jar u0f rest-xxxx.jar BOOT-INF/lib/new-version-jar-same-name.jar

But then I got a similar compression issue like below:

Exception in thread "main" java.lang.IllegalStateException: Unable to open nested entry 'BOOT-INF/lib/new-version-jar-same-name.jar/META-INF/MANIFEST.MF'. It has been compressed and nested jar files must be stored without compression. Please check the mechanism used to create your executable jar file

What should I do when I need to replace the dependency jars within a given springboot jar?

please note: I understand the best practise is to build from updated pom.xml, the limitations we have is that we cannot get the right version source code at the moment, hence we are trying to patch the existing springboot jar instead of rebuilding it.


问:
How to set C++ version with Bazel in a cross platform way?
I would like my Bazel project to use c++17. There is a similar question (How to set C++ standard version when build with Bazel?) but the accepted answer does not port to MSCV.

MSCV needs --cxxopt='/std:c++17' while gcc needs --cxxopt='--std=c++17'.

Does anyone have a minimal example configuration that builds on the most popular Windows and Linux compilers (gcc, MSCV, clang) that sets the version to c++17? I am having a real hard time understanding the toolchain documentation.

The following did not work.

```<code># .bazelrc

build --cxxopt=select({
    "@bazel_tools//src/conditions:windows": "/std:c++17",
    "//conditions:default": "--std=c++17",
})
</code>```

答:
You can do something like this in your .bazelrc:

```<code># GCC 9.3
build:gcc9 --cxxopt=-std=c++2a
build:gcc9 --cxxopt=-Wall
build:gcc9 --cxxopt=-Werror
##build:gcc9 --cxxopt=-Wextra
build:gcc9 --define compiler=gcc9_3_0

build:macos --cxxopt=-std=c++2a
build:macos --cxxopt=-Wall
#build:macos --cxxopt=-Werror
##build:macos --cxxopt=-Wextra
build:macos --define compiler=clang12

# Clang 13.0.0
build:clang13 --cxxopt=-std=c++17
#build:clang13 --cxxopt=-mavx
#build:clang13 --cxxopt=-mavx2
#build:clang13 --cxxopt=-msse4.2
#build:clang13 --cxxopt=-Werror
build:clang13 --define compiler=clang13
build:clang13 --incompatible_enable_cc_toolchain_resolution
build:clang13 --cxxopt=-mwaitpkg

# Mingw
build:mingw --cxxopt=-std=c++2a
#build:mingw --cxxopt=-Wall
#build:mingw --cxxopt=-Werror
#build:mingw --cxxopt=-Wextra
build:mingw --compiler=mingw-gcc

# Visual Studio 2019
build:vs2019 --cxxopt=/std:c++17
build:vs2019 --enable_runfiles # https://github.com/bazelbuild/bazel/issues/8843
build:vs2019 --define compiler=vs2019
build:vs2019 --copt=-DWIN32_LEAN_AND_MEAN
build:vs2019 --copt=-DNOGDI
build:vs2019 --host_copt=-DWIN32_LEAN_AND_MEAN
build:vs2019 --host_copt=-DNOGDI

# Visual Studio 2022
build:vs2022 --config=vs2019
</code>```

And then select a config when you do a build e.g. bazel --config=vs2022 //...

When you are too lazy to type every time the config you can create in your home directory (e.g. ~/.bazelrc a file that contains build --config=config_for_the_machine.

Config switches are costly. Bazel needs to rerun a lot of stuff if you switch the config. If you switch on one machine often between different configs (e.g. GCC and Clang) then use a Bazel Remote Cache server. I use one on my local machine - this makes config switches cheap since the Bazel Remote Cache server is able to store artifacts for different configs whereas Bazel seems only to store artifacts for the latest config.

Body:
I would like my Bazel project to use c++17. There is a similar question (How to set C++ standard version when build with Bazel?) but the accepted answer does not port to MSCV.

MSCV needs --cxxopt='/std:c++17' while gcc needs --cxxopt='--std=c++17'.

Does anyone have a minimal example configuration that builds on the most popular Windows and Linux compilers (gcc, MSCV, clang) that sets the version to c++17? I am having a real hard time understanding the toolchain documentation.

The following did not work.

# .bazelrc

build --cxxopt=select({
    "@bazel_tools//src/conditions:windows": "/std:c++17",
    "//conditions:default": "--std=c++17",
})

Body:
You can do something like this in your .bazelrc:

# GCC 9.3
build:gcc9 --cxxopt=-std=c++2a
build:gcc9 --cxxopt=-Wall
build:gcc9 --cxxopt=-Werror
##build:gcc9 --cxxopt=-Wextra
build:gcc9 --define compiler=gcc9_3_0

build:macos --cxxopt=-std=c++2a
build:macos --cxxopt=-Wall
#build:macos --cxxopt=-Werror
##build:macos --cxxopt=-Wextra
build:macos --define compiler=clang12

# Clang 13.0.0
build:clang13 --cxxopt=-std=c++17
#build:clang13 --cxxopt=-mavx
#build:clang13 --cxxopt=-mavx2
#build:clang13 --cxxopt=-msse4.2
#build:clang13 --cxxopt=-Werror
build:clang13 --define compiler=clang13
build:clang13 --incompatible_enable_cc_toolchain_resolution
build:clang13 --cxxopt=-mwaitpkg

# Mingw
build:mingw --cxxopt=-std=c++2a
#build:mingw --cxxopt=-Wall
#build:mingw --cxxopt=-Werror
#build:mingw --cxxopt=-Wextra
build:mingw --compiler=mingw-gcc

# Visual Studio 2019
build:vs2019 --cxxopt=/std:c++17
build:vs2019 --enable_runfiles # https://github.com/bazelbuild/bazel/issues/8843
build:vs2019 --define compiler=vs2019
build:vs2019 --copt=-DWIN32_LEAN_AND_MEAN
build:vs2019 --copt=-DNOGDI
build:vs2019 --host_copt=-DWIN32_LEAN_AND_MEAN
build:vs2019 --host_copt=-DNOGDI

# Visual Studio 2022
build:vs2022 --config=vs2019

And then select a config when you do a build e.g. bazel --config=vs2022 //...

When you are too lazy to type every time the config you can create in your home directory (e.g. ~/.bazelrc a file that contains build --config=config_for_the_machine.

Config switches are costly. Bazel needs to rerun a lot of stuff if you switch the config. If you switch on one machine often between different configs (e.g. GCC and Clang) then use a Bazel Remote Cache server. I use one on my local machine - this makes config switches cheap since the Bazel Remote Cache server is able to store artifacts for different configs whereas Bazel seems only to store artifacts for the latest config.


问:
Erlang: Supervisor start_child succeeds but no child is added
I'm working on building a supervisor in Erlang that looks like this:

```<code>-module(a_sup).
-behaviour(supervisor).

%% API
-export([start_link/0, init/1]).

start_link() ->
  {ok, supervisor:start_link({local,?MODULE}, ?MODULE, [])}.

init(_Args) ->
  RestartStrategy = {simple_one_for_one, 5, 3600},
  ChildSpec = {
    a_gen_server,
    {a_gen_server, start_link, []},
    permanent,
    brutal_kill,
    worker,
    [a_gen_server]
  },
  {ok, {RestartStrategy,[ChildSpec]}}.
</code>```

And this is how my gen_server looks:

```<code>-module(a_gen_server).
-behavior(gen_server).

%% API
-export([start_link/2, init/1]).

start_link(Name, {X, Y}) ->
  gen_server:start_link({local, Name}, ?MODULE, [Name, {X,Y}], []),
  ok.

init([Name, {X,Y}]) ->
  process_flag(trap_exit, true),
  io:format("~p: position {~p,~p}~n",[Name, X, Y]),
  {ok, {X,Y}}.
</code>```

My gen_server works completely fine. When I run the supervisor as:

```<code>1> c(a_sup).
{ok,a_sup}
2> Pid = a_sup:start_link().
{ok,{ok,<0.85.0>}}
3> supervisor:start_child(a_sup, [Hello, {4,3}]).
Hello: position {4,3}
{error,ok}
</code>```

I couldn't understand where the {error, ok} is coming from, and if there is an error, then what is causing it. So this is what I get when I check the status of the children:

```<code>> supervisor:count_children(a_sup).
[{specs,1},{active,0},{supervisors,0},{workers,0}]
</code>```

This means that there are no children registered with the supervisor yet despite it calling the init method of the gen_server and spawning a process? Clearly there is some error preventing the method to complete successfully but I can't seem to gather any hints to figure it out.

答:
The problem is that a_gen_server:start_link (since that's the function used to in the child spec) is expected to return {ok, Pid}, not just ok.

As the docs put it:

The start function must create and link to the child process, and must
return {ok,Child} or {ok,Child,Info}, where Child is the pid of the
child process and Info any term that is ignored by the supervisor.

The start function can also return ignore if the child process for
some reason cannot be started, in which case the child specification
is kept by the supervisor (unless it is a temporary child) but the
non-existing child process is ignored.

If something goes wrong, the function can also return an error tuple
{error,Error}.

Body:
I'm working on building a supervisor in Erlang that looks like this:

-module(a_sup).
-behaviour(supervisor).

%% API
-export([start_link/0, init/1]).

start_link() ->
  {ok, supervisor:start_link({local,?MODULE}, ?MODULE, [])}.

init(_Args) ->
  RestartStrategy = {simple_one_for_one, 5, 3600},
  ChildSpec = {
    a_gen_server,
    {a_gen_server, start_link, []},
    permanent,
    brutal_kill,
    worker,
    [a_gen_server]
  },
  {ok, {RestartStrategy,[ChildSpec]}}.

And this is how my gen_server looks:

-module(a_gen_server).
-behavior(gen_server).

%% API
-export([start_link/2, init/1]).

start_link(Name, {X, Y}) ->
  gen_server:start_link({local, Name}, ?MODULE, [Name, {X,Y}], []),
  ok.

init([Name, {X,Y}]) ->
  process_flag(trap_exit, true),
  io:format("~p: position {~p,~p}~n",[Name, X, Y]),
  {ok, {X,Y}}.

My gen_server works completely fine. When I run the supervisor as:

1> c(a_sup).
{ok,a_sup}
2> Pid = a_sup:start_link().
{ok,{ok,<0.85.0>}}
3> supervisor:start_child(a_sup, [Hello, {4,3}]).
Hello: position {4,3}
{error,ok}

I couldn't understand where the {error, ok} is coming from, and if there is an error, then what is causing it. So this is what I get when I check the status of the children:

> supervisor:count_children(a_sup).
[{specs,1},{active,0},{supervisors,0},{workers,0}]

This means that there are no children registered with the supervisor yet despite it calling the init method of the gen_server and spawning a process? Clearly there is some error preventing the method to complete successfully but I can't seem to gather any hints to figure it out.


问:
Is there any way to optimise this code?
I have a piece of code which will invert all the checkboxes on my form. I have multiple elements (not just checkboxes but also  <input type='text'>'s) in it. The reason I need it to be optimised is because it takes about two to three seconds to select all the checkboxes (275 right now).

Here's my code:

```<code>function FormInverse() {
    var iCheckbox = 1; // Because there are multiple input elements, we need to distinquish the input element ID and the row id
    var FormLength = document.FormFacturen.elements.length;
    for (i=0; i < FormLength; i++) {
        var FormElementType = document.FormFacturen.elements[i].type;
        if (FormElementType == "checkbox") {
            var Elements = document.getElementsByClassName('row' + iCheckbox); // Alle elementen in de array zetten
            var iNumElements = Elements.length;
            for (iElement=0; iElement < iNumElements; iElement++) {
                if (document.FormFacturen[i].checked == true) {
                    Elements[iElement].className = "invoice-tr-standard row" + iCheckbox;
                } else {
                    Elements[iElement].className = "invoice-tr-clicked row" + iCheckbox;
                }
            }
            iCheckbox++;
            document.FormFacturen[i].checked = !document.FormFacturen[i].checked;
        }
    }
}
</code>```

And here is the document.getElementsByClassName function:

```<code>document.getElementsByClassName = function(cl) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = document.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};
</code>```

答:
I would suggest using jQuery as well.

Try this:

Add a reference to jQuery:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript" language="JavaScript"></script>
</code>```

Use this code:

```<code>$(':checkbox').each( function() {
  $(this).attr('checked', !$(this).attr('checked'));
});
</code>```

Edited:
Or use this to change the classes as well:

```<code>$(':checkbox').each(function() {
    var checked = $(this).attr('checked');
    if (checked) {
        $(this).attr('checked', false);
        $(this).addClass('invoice-tr-clicked');
        $(this).removeClass('invoice-tr-standard');
    }
    else {
        $(this).attr('checked', true);
        $(this).addClass('invoice-tr-standard');
        $(this).removeClass('invoice-tr-clicked');
    }
});
</code>```

Final version:

```<code>$('#FormFacturen :checkbox').each(function() {
    var checked = $(this).attr('checked');
    if (checked) {
        $(this).attr('checked', false);
        $(this).parents('tr').addClass('invoice-tr-clicked');
        $(this).parents('tr').removeClass('invoice-tr-standard');
    }
    else {
        $(this).attr('checked', true);
        $(this).parents('tr').addClass('invoice-tr-standard');
        $(this).parents('tr').removeClass('invoice-tr-clicked');
    }
});
</code>```

Title: Is there any way to optimise this code?

Body:
I have a piece of code which will invert all the checkboxes on my form. I have multiple elements (not just checkboxes but also  <input type='text'>'s) in it. The reason I need it to be optimised is because it takes about two to three seconds to select all the checkboxes (275 right now).

Here's my code:

function FormInverse() {
    var iCheckbox = 1; // Because there are multiple input elements, we need to distinquish the input element ID and the row id
    var FormLength = document.FormFacturen.elements.length;
    for (i=0; i < FormLength; i++) {
        var FormElementType = document.FormFacturen.elements[i].type;
        if (FormElementType == "checkbox") {
            var Elements = document.getElementsByClassName('row' + iCheckbox); // Alle elementen in de array zetten
            var iNumElements = Elements.length;
            for (iElement=0; iElement < iNumElements; iElement++) {
                if (document.FormFacturen[i].checked == true) {
                    Elements[iElement].className = "invoice-tr-standard row" + iCheckbox;
                } else {
                    Elements[iElement].className = "invoice-tr-clicked row" + iCheckbox;
                }
            }
            iCheckbox++;
            document.FormFacturen[i].checked = !document.FormFacturen[i].checked;
        }
    }
}

And here is the document.getElementsByClassName function:

document.getElementsByClassName = function(cl) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = document.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};

Body:
I would suggest using jQuery as well.

Try this:

Add a reference to jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript" language="JavaScript"></script>

Use this code:

$(':checkbox').each( function() {
  $(this).attr('checked', !$(this).attr('checked'));
});

Edited:
Or use this to change the classes as well:

$(':checkbox').each(function() {
    var checked = $(this).attr('checked');
    if (checked) {
        $(this).attr('checked', false);
        $(this).addClass('invoice-tr-clicked');
        $(this).removeClass('invoice-tr-standard');
    }
    else {
        $(this).attr('checked', true);
        $(this).addClass('invoice-tr-standard');
        $(this).removeClass('invoice-tr-clicked');
    }
});

Final version:

$('#FormFacturen :checkbox').each(function() {
    var checked = $(this).attr('checked');
    if (checked) {
        $(this).attr('checked', false);
        $(this).parents('tr').addClass('invoice-tr-clicked');
        $(this).parents('tr').removeClass('invoice-tr-standard');
    }
    else {
        $(this).attr('checked', true);
        $(this).parents('tr').addClass('invoice-tr-standard');
        $(this).parents('tr').removeClass('invoice-tr-clicked');
    }
});


问:
Merge two lists into dynamic list in Python
I have a scenario where have lists List1 and List2 which has below values

List1 = [1,2,3]

List2 = [(11,22,33),(44,55,66),(77,88,99)]

Expected List3 = [(1,11,22,33),(2,44,55,66),(3,77,88,99)]

I need to populate this List3 in Python.Any help is appriciated.

i tried using multiple for loops but didnt work somehing like this

```<code>list = []
        for id in tIDs:
            tIDy = id["ID"]
            for row in PlanDf[["Owner","SP","rep"]].itertuples(index=False):
                list.append((tIDy ,tuple(row)[0],tuple(row)[1],tuple(row)[2]))
                break
</code>```

答:
A short one:

```<code>List3 = [*zip(List1, *zip(*List2))]
</code>```

A fast one:

```<code>List3 = [(a,) + b for a, b in zip(List1, List2)]
</code>```

Benchmark of some solutions with lists 1000 times longer:

```<code>311 us  [*zip(List1, *zip(*List2))]
281 us  [(a,) + b for a, b in zip(List1, List2)]
424 us  [(a, *b) for a, b in zip(List1, List2)]
</code>```

Code (Try it online!):

```<code>from timeit import repeat

setup = '''
List1 = [1,2,3] * 1000
List2 = [(11,22,33),(44,55,66),(77,88,99)] * 1000
'''

es = [
    '[*zip(List1, *zip(*List2))]',
    '[(a,) + b for a, b in zip(List1, List2)]',
    '[(a, *b) for a, b in zip(List1, List2)]',
]

for e in es * 3:
    number = 100
    t = min(repeat(e, setup, number=number, repeat=10)) / number
    print('%3d us ' % (t * 1e6), e)
</code>```

Body:
I have a scenario where have lists List1 and List2 which has below values

List1 = [1,2,3]

List2 = [(11,22,33),(44,55,66),(77,88,99)]

Expected List3 = [(1,11,22,33),(2,44,55,66),(3,77,88,99)]

I need to populate this List3 in Python.Any help is appriciated.

i tried using multiple for loops but didnt work somehing like this

list = []
        for id in tIDs:
            tIDy = id["ID"]
            for row in PlanDf[["Owner","SP","rep"]].itertuples(index=False):
                list.append((tIDy ,tuple(row)[0],tuple(row)[1],tuple(row)[2]))
                break

Body:
A short one:

List3 = [*zip(List1, *zip(*List2))]

A fast one:

List3 = [(a,) + b for a, b in zip(List1, List2)]

Benchmark of some solutions with lists 1000 times longer:

311 us  [*zip(List1, *zip(*List2))]
281 us  [(a,) + b for a, b in zip(List1, List2)]
424 us  [(a, *b) for a, b in zip(List1, List2)]

Code (Try it online!):

from timeit import repeat

setup = '''
List1 = [1,2,3] * 1000
List2 = [(11,22,33),(44,55,66),(77,88,99)] * 1000
'''

es = [
    '[*zip(List1, *zip(*List2))]',
    '[(a,) + b for a, b in zip(List1, List2)]',
    '[(a, *b) for a, b in zip(List1, List2)]',
]

for e in es * 3:
    number = 100
    t = min(repeat(e, setup, number=number, repeat=10)) / number
    print('%3d us ' % (t * 1e6), e)


问:
How to use `ccache -s` to show hit rates for different CCACHE_DIR
When I use ccache -s, I get like this.

```<code>root@iZwz98um4r4f2aucz24e1yZ:~# ccache -s
cache directory                     /root/.ccache
primary config                      /root/.ccache/ccache.conf
secondary config      (readonly)    /etc/ccache.conf
</code>```

But when I set different environment CCACHE_DIR for my different C++ projects, how can I get my CCACHE_DIR statistics? Is there parameters can do this?

答:
As per the documentation:

-d, --dir PATH

Let the command line options operate on cache directory PATH instead of the default. For example, to show statistics for a cache directory at /shared/ccache you can run ccache -d /shared/ccache -s. Using this option has the same effect as setting the environment variable CCACHE_DIR temporarily.

Available from Ccache version 4.0 onwards.

Body:
When I use ccache -s, I get like this.

root@iZwz98um4r4f2aucz24e1yZ:~# ccache -s
cache directory                     /root/.ccache
primary config                      /root/.ccache/ccache.conf
secondary config      (readonly)    /etc/ccache.conf

But when I set different environment CCACHE_DIR for my different C++ projects, how can I get my CCACHE_DIR statistics? Is there parameters can do this?


问:
Flex LineChart advanced horiztonal axis?
I want to make a line chart that allows the user to select a date range for the data. For example if the date range span is more than 1 month, I want to to have a bar that shows the months, also if the date range is around 30 days or less I want it to show the dates for each day as well. Something like that.

Does anyone have any suggestions?

Thanks!

答:
I would suggest using a DateTimeAxis, and setting the labelUnits property to "days" or "months" as appropriate.  The axis will then do all the hard work of grouping your data accordingly.

In your particular case, when the user makes a choice from the combo box, you should have a handler that computes how granular to make the x-axis based on the user's date selections.

OwnerDisplayName: John Isaacks

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Matt Dillard


问:
Problem in getting all urls in a page using regex ?
I have a webpage source code stored in $page and I need to extract all urls from it

the problem that some urls which are not in  tag, but in javascript codes.

for example, I have this source code that I want to extract all urls from

```<code>    Click <a style="vertical-align:middle;cursor:pointer;text-decoration:underline;color:red;" onClick="return downme('http://www.AAAAA.com/atnbc1i7b/part1.html')">

            Here</a> to go to download page

<a href="http://www.UUUU.com/register">Hi all</a>
</code>```

and I use this regex code

```<code>$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
    if(preg_match_all("/$regexp/siU", $page, $matches, PREG_SET_ORDER))
               {
                 foreach($matches as $match)
                   {
                      print_r($match)
                   }

               }
</code>```

the output will print to me just

```<code>http://www.UUUU.com/register
</code>```

but the other link

```<code>http://www.AAAAA.com/atnbc1i7b/part1.htm
</code>```

will not appear !!

Help please

thanks

答:
In first example you have:

```<code><a href="http://www.UUUU.com/register">
</code>```

so this regexp working

but in second:

```<code><a style="vertical-align:middle;cursor:pointer;text-decoration:underline;color:red;" onClick="return downme('http://www.AAAAA.com/atnbc1i7b/part1.html')">
</code>```

so this not working because:

```<code>$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
</code>```

as you see you have href= in regexp

change href= to onClick= and try, this tip should be resolve this problem.

if you need href and onClick use (href|onClick)

Body:
I have a webpage source code stored in $page and I need to extract all urls from it

the problem that some urls which are not in  tag, but in javascript codes.

for example, I have this source code that I want to extract all urls from

    Click

            Here to go to download page

Hi all

and I use this regex code

$regexp = "]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
    if(preg_match_all("/$regexp/siU", $page, $matches, PREG_SET_ORDER))
               {
                 foreach($matches as $match)
                   {
                      print_r($match)
                   }

               }

the output will print to me just

http://www.UUUU.com/register

but the other link

http://www.AAAAA.com/atnbc1i7b/part1.htm

will not appear !!

Help please

thanks

Body:
In first example you have:

<a href="http://www.UUUU.com/register">

so this regexp working

but in second:

<a style="vertical-align:middle;cursor:pointer;text-decoration:underline;color:red;" onClick="return downme('http://www.AAAAA.com/atnbc1i7b/part1.html')">

so this not working because:

$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";

as you see you have href= in regexp

change href= to onClick= and try, this tip should be resolve this problem.

if you need href and onClick use (href|onClick)


问:
How to use wildcard in AWS Principal?
Currently I have policy role like:

```<code>{
"Version": "2008-10-17",
"Statement": [
   {
   "Effect": "Allow",
   "Principal": {
      "AWS": [
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v2",
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v1"
      ],
     "Service": [
        "elasticmapreduce.amazonaws.com",
        "glue.amazonaws.com",
        "comprehend.amazonaws.com",
        "sagemaker.amazonaws.com"
      ]
    },
   "Action": [
       "sts:AssumeRole",
       "sts:TagSession"
    ]
   }
 ]
}
</code>```

So I want to replace V1 and V2 with V*(wildcard) because I want to have multiple resources.
How can I achieve this? Tried using Condition but it didn't work out.

I.E
Instead of

```<code>"AWS": [
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v2",
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v1"
      ],
</code>```

I want something like this:

```<code>"AWS": [
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v*""
      ],
</code>```

答:
According to the doc:

You cannot use a wildcard to match part of a principal name or ARN.

You would have to explicitly list out all of your versions:

```<code>"AWS": [
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v3",
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v2",
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v1"
      ],
</code>```

Title: How to use wildcard in AWS Principal?

Body:
Currently I have policy role like:

{
"Version": "2008-10-17",
"Statement": [
   {
   "Effect": "Allow",
   "Principal": {
      "AWS": [
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v2",
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v1"
      ],
     "Service": [
        "elasticmapreduce.amazonaws.com",
        "glue.amazonaws.com",
        "comprehend.amazonaws.com",
        "sagemaker.amazonaws.com"
      ]
    },
   "Action": [
       "sts:AssumeRole",
       "sts:TagSession"
    ]
   }
 ]
}

So I want to replace V1 and V2 with V*(wildcard) because I want to have multiple resources.
How can I achieve this? Tried using Condition but it didn't work out.

I.E
Instead of

"AWS": [
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v2",
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v1"
      ],

I want something like this:

"AWS": [
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v*""
      ],

Body:
According to the doc:

You cannot use a wildcard to match part of a principal name or ARN.

You would have to explicitly list out all of your versions:

"AWS": [
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v3",
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v2",
         "arn:aws:sts::AccountID:assumed-role/a111-ml-role/some-api-v1"
      ],


问:
Can't find where preempt count in the stack is declared for a percpu variable access. (linux kernel)
I was debugging linux boot and tried to understand how these percpu variables work in arm64. For test, I added a function called read_pkcontext1 which returns the percpu variable printk_context. (This value is used for printk) And I found something I can't understand.

(this is from linux 5.4.21)

```<code>==== kernel/printk/printk_safe.c ====

int read_pkcontext1(void)   /* function I added for test */
{
    return this_cpu_read(printk_context);
}

==== include/linux/percpu-defs.h ====
/*
 * Operations with implied preemption/interrupt protection.  These
 * operations can be used without worrying about preemption or interrupt.
 */
#define this_cpu_read(pcp)      __pcpu_size_call_return(this_cpu_read_, pcp)

==== include/linux/percpu-defs.h ====
#define __pcpu_size_call_return(stem, variable)             \
({                                  \
    typeof(variable) pscr_ret__;                    \
    __verify_pcpu_ptr(&(variable));                 \
    switch(sizeof(variable)) {                  \
    case 1: pscr_ret__ = stem##1(variable); break;          \
    case 2: pscr_ret__ = stem##2(variable); break;          \
    case 4: pscr_ret__ = stem##4(variable); break;          \
    case 8: pscr_ret__ = stem##8(variable); break;          \
    default:                            \
        __bad_size_call_parameter(); break;         \
    }                               \
    pscr_ret__;                         \
})
</code>```

This is result of aarch64-none-elf-objdump -S vmlinux for read_pkcontext1 function and the used funtions inside (with optimization off).

```<code>ffffffc0100f0dc0 <read_pkcontext1>:
void write_pkcontext(void);

#pragma GCC push_options
#pragma GCC optimize ("O0")
int read_pkcontext1(void)
{
ffffffc0100f0dc0:   a9bd7bfd    stp x29, x30, [sp, #-48]!
ffffffc0100f0dc4:   910003fd    mov x29, sp
    return this_cpu_read(printk_context);
ffffffc0100f0dc8:   f9000fff    str xzr, [sp, #24]
ffffffc0100f0dcc:   52800020    mov w0, #0x1                    // #1
ffffffc0100f0dd0:   94000018    bl  ffffffc0100f0e30 <__preempt_count_add>

... skip ...

ffffffc0100f0e30 <__preempt_count_add>:
ffffffc0100f0e30:   d5384101    mrs x1, sp_el0
ffffffc0100f0e34:   b9401022    ldr w2, [x1, #16]
    pc += val;
ffffffc0100f0e38:   0b020000    add w0, w0, w2
    case 4: *(volatile __u32 *)p = *(__u32 *)res; break;
ffffffc0100f0e3c:   b9001020    str w0, [x1, #16]
}
ffffffc0100f0e40:   d65f03c0    ret
</code>```

In the code above, it calls __preempt_count_add with w0 = #1 (incrementing preemption count), and __preempt_count_add functions is adding the value (w0) to a variable at sp + #16 and writes it back. So this variable in stack looks like the preemption count. (I guess this prevents preemption). My quetion is : when was this value in stack defined and initialized? I couldn't find it in the linux source. (using qemu, I see this value is seen to be 1 and incremented to 2 after the __preempt_count_add. Of course it is decrement back to 1 after the percpu variable access.)

答:
this_cpu_read(printk_context) expands to:

⇒ __pcpu_size_call_return(this_cpu_read_, printk_context)

⇒

({
    typeof(printk_context) pscr_ret__;
    __verify_pcpu_ptr(&(printk_context));
    switch(sizeof(printk_context)) {
    case 1: pscr_ret__ = this_cpu_read_1(printk_context); break;
    case 2: pscr_ret__ = this_cpu_read_2(printk_context); break;
    case 4: pscr_ret__ = this_cpu_read_4(printk_context); break;
    case 8: pscr_ret__ = this_cpu_read_8(printk_context); break;
    default:
        __bad_size_call_parameter(); break;
    }
    pscr_ret__;
})
```
<p><code>sizeof(printk_context)</code> is 4, so <code>pscr_ret__ = this_cpu_read_4(printk_context);</code>.</p>
<p>The <code>this_cpu_read_4()</code> macro is defined by <code>#include <asm/percpu.h></code>:</p>
<p><strong>==== arch/arm64/include/asm/percpu.h ====</strong></p>
<pre class="lang-c prettyprint-override"><code>#define this_cpu_read_4(pcp)        \
    _pcp_protect_return(__percpu_read_32, pcp)
</code>```

#define _pcp_protect_return(op, pcp, args...)               \
({                                  \
    typeof(pcp) __retval;                       \
    preempt_disable_notrace();                  \
    __retval = (typeof(pcp))op(raw_cpu_ptr(&(pcp)), ##args);    \
    preempt_enable_notrace();                   \
    __retval;                           \
})
```
<p>That is where the preempt count manipulation occurs.</p>
<p>The <code>preempt_disable_notrace()</code> and <code>preempt_enable_notrace()</code> macros are defined by <code>#include <linux/preempt.h></code>.</p>
<p><strong>==== include/linux/preempt.h ====</strong></p>
<pre class="lang-c prettyprint-override"><code>#define preempt_enable_notrace() \
do { \
    barrier(); \
    __preempt_count_dec(); \
} while (0)
</code>```

#define preempt_disable_notrace() \
do { \
    __preempt_count_inc(); \
    barrier(); \
} while (0)
```
<pre class="lang-c prettyprint-override"><code>#define __preempt_count_inc() __preempt_count_add(1)
#define __preempt_count_dec() __preempt_count_sub(1)
</code>```

__preempt_count_add() and __preempt_count_sub() are defined by #include <asm/preempt.h>.

==== arch/arm64/include/asm/preempt.h ====

static inline void __preempt_count_add(int val)
{
    u32 pc = READ_ONCE(current_thread_info()->preempt.count);
    pc += val;
    WRITE_ONCE(current_thread_info()->preempt.count, pc);
}

static inline void __preempt_count_sub(int val)
{
    u32 pc = READ_ONCE(current_thread_info()->preempt.count);
    pc -= val;
    WRITE_ONCE(current_thread_info()->preempt.count, pc);
}
```
<p>For arm64, <code>CONFIG_THREAD_INFO_IN_TASK</code> is enabled so <code>current_thread_info()</code> is defined as a macro by <code>#include <linux/thread_info.h></code>.</p>
<p><strong>==== include/linux/thread_info.h ====</strong></p>
<pre class="lang-c prettyprint-override"><code>#ifdef CONFIG_THREAD_INFO_IN_TASK
/*
 * For CONFIG_THREAD_INFO_IN_TASK kernels we need <asm/current.h> for the
 * definition of current, but for !CONFIG_THREAD_INFO_IN_TASK kernels,
 * including <asm/current.h> can cause a circular dependency on some platforms.
 */
#include <asm/current.h>
#define current_thread_info() ((struct thread_info *)current)
#endif
</code>```

The current macro is defined by #include <asm/current.h>.

==== arch/arm64/include/asm/current.h ====

#define current get_current()
```
<pre class="lang-c prettyprint-override"><code>/*
 * We don't use read_sysreg() as we want the compiler to cache the value where
 * possible.
 */
static __always_inline struct task_struct *get_current(void)
{
    unsigned long sp_el0;

    asm ("mrs %0, sp_el0" : "=r" (sp_el0));

    return (struct task_struct *)sp_el0;
}
</code>```

There is some magic in arch/arm64/kernel/entry.S relating to the use of the sp_el0 stack pointer to point to the current thread_info / task_struct. Sorry, I do not have time to study the gory details, but it was introduced by commit     6cdf9c7ca687 ("arm64: Store struct thread_info in sp_el0").

The key thing is that sp_el0 register is not the same as sp. The kernel does not run in EL0 mode so sp_el0 is available as a "scratch" register. The kernel uses it to point to the current thread_info / task_struct.

struct task_struct is defined by #include <linux/sched.h>.

==== include/linux/sched.h ====

struct task_struct {
#ifdef CONFIG_THREAD_INFO_IN_TASK
    /*
     * For reasons of header soup (see current_thread_info()), this
     * must be the first element of task_struct.
     */
    struct thread_info      thread_info;
#endif
    /* -1 unrunnable, 0 runnable, >0 stopped: */
    volatile long           state;
```
<p>Since <code>CONFIG_THREAD_INFO_IN_TASK</code> is selected, the first member is <code>struct thread_info thread_info</code>.  <code>current_thread_info()</code> points to that member in the current task.</p>
<p><code>struct thread_info</code> is defined by <code>#include <asm/thread_info.h></code>.</p>
<p><strong>==== arch/arm64/include/asm/thread_info.h ====</strong></p>
<pre class="lang-c prettyprint-override"><code>/*
 * low level task data that entry.S needs immediate access to.
 */
struct thread_info {
    unsigned long       flags;      /* low level flags */
    mm_segment_t        addr_limit; /* address limit */
#ifdef CONFIG_ARM64_SW_TTBR0_PAN
    u64         ttbr0;      /* saved TTBR0_EL1 */
#endif
    union {
        u64     preempt_count;  /* 0 => preemptible, <0 => bug */
        struct {
#ifdef CONFIG_CPU_BIG_ENDIAN
            u32 need_resched;
            u32 count;
#else
            u32 count;
            u32 need_resched;
#endif
        } preempt;
    };
};
</code>```

When CONFIG_ARM64_SW_TTBR0_PAN is not selected and the CPU is little-endian, the preempt.count member will be at offset 16 from the start of the structure.

Body:
I was debugging linux boot and tried to understand how these percpu variables work in arm64. For test, I added a function called read_pkcontext1 which returns the percpu variable printk_context. (This value is used for printk) And I found something I can't understand.

(this is from linux 5.4.21)

==== kernel/printk/printk_safe.c ====

int read_pkcontext1(void)   /* function I added for test */
{
    return this_cpu_read(printk_context);
}

==== include/linux/percpu-defs.h ====
/*
 * Operations with implied preemption/interrupt protection.  These
 * operations can be used without worrying about preemption or interrupt.
 */
#define this_cpu_read(pcp)      __pcpu_size_call_return(this_cpu_read_, pcp)

==== include/linux/percpu-defs.h ====
#define __pcpu_size_call_return(stem, variable)             \
({                                  \
    typeof(variable) pscr_ret__;                    \
    __verify_pcpu_ptr(&(variable));                 \
    switch(sizeof(variable)) {                  \
    case 1: pscr_ret__ = stem##1(variable); break;          \
    case 2: pscr_ret__ = stem##2(variable); break;          \
    case 4: pscr_ret__ = stem##4(variable); break;          \
    case 8: pscr_ret__ = stem##8(variable); break;          \
    default:                            \
        __bad_size_call_parameter(); break;         \
    }                               \
    pscr_ret__;                         \
})

This is result of aarch64-none-elf-objdump -S vmlinux for read_pkcontext1 function and the used funtions inside (with optimization off).

ffffffc0100f0dc0 <read_pkcontext1>:
void write_pkcontext(void);

#pragma GCC push_options
#pragma GCC optimize ("O0")
int read_pkcontext1(void)
{
ffffffc0100f0dc0:   a9bd7bfd    stp x29, x30, [sp, #-48]!
ffffffc0100f0dc4:   910003fd    mov x29, sp
    return this_cpu_read(printk_context);
ffffffc0100f0dc8:   f9000fff    str xzr, [sp, #24]
ffffffc0100f0dcc:   52800020    mov w0, #0x1                    // #1
ffffffc0100f0dd0:   94000018    bl  ffffffc0100f0e30 <__preempt_count_add>

... skip ...

ffffffc0100f0e30 <__preempt_count_add>:
ffffffc0100f0e30:   d5384101    mrs x1, sp_el0
ffffffc0100f0e34:   b9401022    ldr w2, [x1, #16]
    pc += val;
ffffffc0100f0e38:   0b020000    add w0, w0, w2
    case 4: *(volatile __u32 *)p = *(__u32 *)res; break;
ffffffc0100f0e3c:   b9001020    str w0, [x1, #16]
}
ffffffc0100f0e40:   d65f03c0    ret

In the code above, it calls __preempt_count_add with w0 = #1 (incrementing preemption count), and __preempt_count_add functions is adding the value (w0) to a variable at sp + #16 and writes it back. So this variable in stack looks like the preemption count. (I guess this prevents preemption). My quetion is : when was this value in stack defined and initialized? I couldn't find it in the linux source. (using qemu, I see this value is seen to be 1 and incremented to 2 after the __preempt_count_add. Of course it is decrement back to 1 after the percpu variable access.)

Body:
this_cpu_read(printk_context) expands to:

⇒ __pcpu_size_call_return(this_cpu_read_, printk_context)

⇒

({
    typeof(printk_context) pscr_ret__;
    __verify_pcpu_ptr(&(printk_context));
    switch(sizeof(printk_context)) {
    case 1: pscr_ret__ = this_cpu_read_1(printk_context); break;
    case 2: pscr_ret__ = this_cpu_read_2(printk_context); break;
    case 4: pscr_ret__ = this_cpu_read_4(printk_context); break;
    case 8: pscr_ret__ = this_cpu_read_8(printk_context); break;
    default:
        __bad_size_call_parameter(); break;
    }
    pscr_ret__;
})

sizeof(printk_context) is 4, so pscr_ret__ = this_cpu_read_4(printk_context);.

The this_cpu_read_4() macro is defined by #include <asm/percpu.h>:

==== arch/arm64/include/asm/percpu.h ====

#define this_cpu_read_4(pcp)        \
    _pcp_protect_return(__percpu_read_32, pcp)

#define _pcp_protect_return(op, pcp, args...)               \
({                                  \
    typeof(pcp) __retval;                       \
    preempt_disable_notrace();                  \
    __retval = (typeof(pcp))op(raw_cpu_ptr(&(pcp)), ##args);    \
    preempt_enable_notrace();                   \
    __retval;                           \
})

That is where the preempt count manipulation occurs.

The preempt_disable_notrace() and preempt_enable_notrace() macros are defined by #include <linux/preempt.h>.

==== include/linux/preempt.h ====

#define preempt_enable_notrace() \
do { \
    barrier(); \
    __preempt_count_dec(); \
} while (0)

#define preempt_disable_notrace() \
do { \
    __preempt_count_inc(); \
    barrier(); \
} while (0)

#define __preempt_count_inc() __preempt_count_add(1)
#define __preempt_count_dec() __preempt_count_sub(1)

__preempt_count_add() and __preempt_count_sub() are defined by #include <asm/preempt.h>.

==== arch/arm64/include/asm/preempt.h ====

static inline void __preempt_count_add(int val)
{
    u32 pc = READ_ONCE(current_thread_info()->preempt.count);
    pc += val;
    WRITE_ONCE(current_thread_info()->preempt.count, pc);
}

static inline void __preempt_count_sub(int val)
{
    u32 pc = READ_ONCE(current_thread_info()->preempt.count);
    pc -= val;
    WRITE_ONCE(current_thread_info()->preempt.count, pc);
}

For arm64, CONFIG_THREAD_INFO_IN_TASK is enabled so current_thread_info() is defined as a macro by #include <linux/thread_info.h>.

==== include/linux/thread_info.h ====

#ifdef CONFIG_THREAD_INFO_IN_TASK
/*
 * For CONFIG_THREAD_INFO_IN_TASK kernels we need <asm/current.h> for the
 * definition of current, but for !CONFIG_THREAD_INFO_IN_TASK kernels,
 * including <asm/current.h> can cause a circular dependency on some platforms.
 */
#include <asm/current.h>
#define current_thread_info() ((struct thread_info *)current)
#endif

The current macro is defined by #include <asm/current.h>.

==== arch/arm64/include/asm/current.h ====

#define current get_current()

/*
 * We don't use read_sysreg() as we want the compiler to cache the value where
 * possible.
 */
static __always_inline struct task_struct *get_current(void)
{
    unsigned long sp_el0;

    asm ("mrs %0, sp_el0" : "=r" (sp_el0));

    return (struct task_struct *)sp_el0;
}

There is some magic in arch/arm64/kernel/entry.S relating to the use of the sp_el0 stack pointer to point to the current thread_info / task_struct. Sorry, I do not have time to study the gory details, but it was introduced by commit     6cdf9c7ca687 ("arm64: Store struct thread_info in sp_el0").

The key thing is that sp_el0 register is not the same as sp. The kernel does not run in EL0 mode so sp_el0 is available as a "scratch" register. The kernel uses it to point to the current thread_info / task_struct.

struct task_struct is defined by #include <linux/sched.h>.

==== include/linux/sched.h ====

struct task_struct {
#ifdef CONFIG_THREAD_INFO_IN_TASK
    /*
     * For reasons of header soup (see current_thread_info()), this
     * must be the first element of task_struct.
     */
    struct thread_info      thread_info;
#endif
    /* -1 unrunnable, 0 runnable, >0 stopped: */
    volatile long           state;

Since CONFIG_THREAD_INFO_IN_TASK is selected, the first member is struct thread_info thread_info.  current_thread_info() points to that member in the current task.

struct thread_info is defined by #include <asm/thread_info.h>.

==== arch/arm64/include/asm/thread_info.h ====

/*
 * low level task data that entry.S needs immediate access to.
 */
struct thread_info {
    unsigned long       flags;      /* low level flags */
    mm_segment_t        addr_limit; /* address limit */
#ifdef CONFIG_ARM64_SW_TTBR0_PAN
    u64         ttbr0;      /* saved TTBR0_EL1 */
#endif
    union {
        u64     preempt_count;  /* 0 => preemptible, <0 => bug */
        struct {
#ifdef CONFIG_CPU_BIG_ENDIAN
            u32 need_resched;
            u32 count;
#else
            u32 count;
            u32 need_resched;
#endif
        } preempt;
    };
};

When CONFIG_ARM64_SW_TTBR0_PAN is not selected and the CPU is little-endian, the preempt.count member will be at offset 16 from the start of the structure.


问:
Angular lazy loading external styles and scripts on specific component causes layout glitch for brief second
as I already described in the title, I have some styles and script that I only want to load on one specific component but this causes a glitch in the view, looks like the page is displayed before the css is loaded. Is there a way to adjust this code such a way that first all the css is loaded and then the page is displayed, preventing the glitch to happen ?

https://stackblitz.com/edit/angular-ivy-sjspyx?file=src/app/app.component.ts

I would really appreciate a fix for this.

Thank you.

答:
Since those styles aren't included when the app is compiled and are added only when the component is initialized, i.e, in the constructor, I think your best bet would be to add a loading indicator (or progress spinner) that is then dismissed when the loadExternalScript function is completed:

```<code>constructor(){
// activate loading indicator

// rest of your code

}
private loadExternalScript(scriptUrl: Array<any>) {
    scriptUrl.forEach(function (item) {
      const scriptElement = document.createElement('script');
      scriptElement.src = item;
      scriptElement.async = false;
      scriptElement.defer = true;
      document.body.appendChild(scriptElement);
    });

    // dismiss loading indicator
}
</code>```

Body:
Since those styles aren't included when the app is compiled and are added only when the component is initialized, i.e, in the constructor, I think your best bet would be to add a loading indicator (or progress spinner) that is then dismissed when the loadExternalScript function is completed:

constructor(){
// activate loading indicator

// rest of your code

}
private loadExternalScript(scriptUrl: Array<any>) {
    scriptUrl.forEach(function (item) {
      const scriptElement = document.createElement('script');
      scriptElement.src = item;
      scriptElement.async = false;
      scriptElement.defer = true;
      document.body.appendChild(scriptElement);
    });

    // dismiss loading indicator
}


问:
OpenAL Soft 40964 in alcOpenDevice: AL_INVALID_OPERATION
When running my audio application, ported from Windows, on Ubuntu Virtualbox, it reports the following:

```<code>Devices found:
OpenAL Soft

OpenAL Soft 40964 in alcOpenDevice: AL_INVALID_OPERATION
</code>```

The line it runs on:

```<code>ALCdevice device = alcOpenDevice( NULL ); // Also tried "OpenAL Soft"
</code>```

Ubuntu audio is working properly. What am I missing?

CMakeLists:

```<code>target_link_libraries( ${PROJECT_NAME}
    "myengine"
    "openal"
)
</code>```

I installed libopenal1 on the target VM

答:
Apparently, the alGetError() will return this error before a context is created. Starting from alcMakeContextCurrent() I can use this function to check for errors.

It now plays audio!

So for alcOpenDevice() and alcCreateContext() I had to comment out the alGetError() error checking. Though I could still check whether the device was opened successfully using if( !device )

Body:
When running my audio application, ported from Windows, on Ubuntu Virtualbox, it reports the following:

Devices found:
OpenAL Soft

OpenAL Soft 40964 in alcOpenDevice: AL_INVALID_OPERATION

The line it runs on:

ALCdevice device = alcOpenDevice( NULL ); // Also tried "OpenAL Soft"

Ubuntu audio is working properly. What am I missing?

CMakeLists:

target_link_libraries( ${PROJECT_NAME}
    "myengine"
    "openal"
)

I installed libopenal1 on the target VM


问:
Automate the Boring Stuff - Coin Flip Streaks - How to optimize my answer?
I've been going through automate the boring stuff, and am trying the practice problems.
I came up with this solution to the project on the lists chapter - Coin Flip Streaks.

The objective of the problem is the following:
''For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.''
And this is my code.

```<code>numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    experimentNumber = experimentNumber + 1
    for test in range(100):
        selector = random.randint(0,1)
        if selector == 0:
            experiment = experiment + ['H']
        elif selector == 1:
            experiment = experiment + ['T']

    for n in range(94):
        if experiment[n:n+6] == ['T', 'T', 'T', 'T', 'T', 'T']:
            numberOfStreaks = numberOfStreaks + 1
        elif experiment[n:n+6] == ['H', 'H', 'H', 'H', 'H', 'H']:
            numberOfStreaks = numberOfStreaks + 1
        else:
            numberOfStreaks = numberOfStreaks
print((numberOfStreaks / 100000) * 100)
</code>```

I can only run this solution efficiently for 1000 experiments, and the book says to run for 10000, but it takes too long.
I think this derives from the inneficiency of the algorithm I came up with.

How do I make this algorithm more efficient?

答:
We should first wonder what is the actual quantity that we want to establish. Here the text says (emphasize mine):

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row.

As we want a percentage computed on 10000 experiment, it means that each experiment shall be true if it contains at least a streak, and false if it does not.

Applying minimum changes to the code proposed by @JeffUK, it could be

```<code>import random

numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    heads=0
    tails=0

    for test in range(100):

        if random.randint(0,1):
            heads += 1
            tails = 0
        else:
            tails += 1
            heads = 0

        if heads == 6 or tails == 6:
            numberOfStreaks +=1
            break   # stop after first match!

print((numberOfStreaks / 100000) * 100)
</code>```

And the result should be around 80, meaning that the probability of having at least one sequence of 6 identical flip when we launch it 100 time is close to 80%

Body:
I've been going through automate the boring stuff, and am trying the practice problems.
I came up with this solution to the project on the lists chapter - Coin Flip Streaks.

The objective of the problem is the following:
''For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.''
And this is my code.

numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    experimentNumber = experimentNumber + 1
    for test in range(100):
        selector = random.randint(0,1)
        if selector == 0:
            experiment = experiment + ['H']
        elif selector == 1:
            experiment = experiment + ['T']

    for n in range(94):
        if experiment[n:n+6] == ['T', 'T', 'T', 'T', 'T', 'T']:
            numberOfStreaks = numberOfStreaks + 1
        elif experiment[n:n+6] == ['H', 'H', 'H', 'H', 'H', 'H']:
            numberOfStreaks = numberOfStreaks + 1
        else:
            numberOfStreaks = numberOfStreaks
print((numberOfStreaks / 100000) * 100)

I can only run this solution efficiently for 1000 experiments, and the book says to run for 10000, but it takes too long.
I think this derives from the inneficiency of the algorithm I came up with.

How do I make this algorithm more efficient?

Body:
We should first wonder what is the actual quantity that we want to establish. Here the text says (emphasize mine):

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row.

As we want a percentage computed on 10000 experiment, it means that each experiment shall be true if it contains at least a streak, and false if it does not.

Applying minimum changes to the code proposed by @JeffUK, it could be

import random

numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    heads=0
    tails=0

    for test in range(100):

        if random.randint(0,1):
            heads += 1
            tails = 0
        else:
            tails += 1
            heads = 0

        if heads == 6 or tails == 6:
            numberOfStreaks +=1
            break   # stop after first match!

print((numberOfStreaks / 100000) * 100)

And the result should be around 80, meaning that the probability of having at least one sequence of 6 identical flip when we launch it 100 time is close to 80%


问:
is there a way to filter devices list
i'm using android management api and i can limit fields returned but i do not find a way to filter query results.

for example, is there a way with enterprises.devices.list method to get only devices matching one specific policy or hardware brand?

https://developers.google.com/android/management/reference/rest/v1/enterprises.devices/list

答: Currently there is no way to filter the result when using enterprises.devices.list as it will list all devices assigned on the given enterprise.</p>

Title: is there a way to filter devices list


问:
How can i use query in mongoose array object Schema?
enter image description here

this is my Schema

enter image description here

i want to use tag.id

this is code doesnt work....
help me

答:
You should be using positional operator in this case.</p>
```<code>Todo.find({ 'tag.$._id': id });
</code>```

Body:
You should be using positional operator in this case.

Todo.find({ 'tag.$._id': id });


问:
Deploying react apps to custom domain name (Ubuntu)
My react app is installed on a ubuntu server. I want to add a custom domain to it. When I pointed the domain to the server. It points to xx.xx.xx.xx but the react app is installed on xx.xx.xx.xx:3000

How can I install the react app on xx:xx:xx:xx:80 ?

答:
Does your app still works with example.com:3000? I believe it should.

Your web server's port needs to be on 80 to serve with http://example.com/ or http://xx.xx.xx.xx/. Either change the port to 80, or use a web server such as Nginx to proxy 80 to your 3000.


问:
How to copy dtype when doing numpy array assignment or when appending to a numpy array
I'm pretty illiterate in using Python/numpy.

I have the following piece of code:

```<code>data = np.array([])

for i in range(10):
    data = np.append(data, GetData())

return data
</code>```

GetData() returns a numpy array with a custom dtype. However when executing the above piece of code, the numbers convert to float64 which I suspect is the culprit for other issues I'm having. How can I copy/append the output of the functions while preserving the dtype as well?

答:
Given the comments stating that you will only know the type of data once you run GetData(), and that multiple types are expected, you could do it like so:

# [...]

dataByType = {} # dictionary to store the dtypes encountered and the arrays with given dtype

for i in range(10):
    newData = GetData()
    if newData.dtype not in dataByType:
        # If the dtype has not been encountered yet,
        # create an empty array with that dtype and store it in the dict
        dataByType[newData.dtype] = np.array([], dtype=newData.dtype)
    # Append the new data to the corresponding array in dict, depending on dtype
    dataByType[newData.dtype] = np.append(dataByType[newData.dtype], newData)
```
<hr />
<p>Taking into account hpaulj's answer, if you wish to conserve the different types you might encounter without creating a new array at each iteration you can adapt the above to:</p>
<pre class="lang-py prettyprint-override"><code># [...]

dataByType = {} # dictionary to store the dtypes encountered and the list storing data with given dtype

for i in range(10):
    newData = GetData()
    if newData.dtype not in dataByType:
        # If the dtype has not been encountered yet,
        # create an empty list with that dtype and store it in the dict
        dataByType[newData.dtype] = []
    # Append the new data to the corresponding list in dict, depending on dtype
    dataByType[newData.dtype].append(newData)

# At this point, you have all your data pieces stored according to their original dtype inside the dataByType dictionary.
# Now if you wish you can convert them to numpy arrays as well

# Either by concatenation, updating what is stored in the dict
for dataType in dataByType:
    dataByType[dataType] = np.concatenate(dataByType[dataType])
    # No need to specify the dtype in concatenate here, since previous step ensures all data pieces are the same type

# Or by creating array directly, to store each data piece at a different index
for dataType in dataByType:
    dataByType[dataType] = np.array(dataByType[dataType])
    # As for concatenate, no need to specify the dtype here
</code>```

A little example:

import numpy as np

# to get something similar to GetData in the example structure:
getData = [
    np.array([1.,2.], dtype=np.float64),
    np.array([1,2], dtype=np.int64),
    np.array([3,4], dtype=np.int64),
    np.array([3.,4.], dtype=np.float64)
    ] # dtype precised here for clarity, but not needed

dataByType = {}

for i in range(len(getData)):
    newData = getData[i]
    if newData.dtype not in dataByType:
        dataByType[newData.dtype] = []
    dataByType[newData.dtype].append(newData)

print(dataByType) # output formatted below for clarity
# {dtype('float64'):
#     [array([1., 2.]), array([3., 4.])],
#  dtype('int64'):
#     [array([1, 2], dtype=int64), array([3, 4], dtype=int64)]}
```
<p>Now if we use concatenate on that dataset, we get 1D arrays, conserving the original type (dtype=float64 not precised in the output since it is the default type for floating point values):</p>
<pre class="lang-py prettyprint-override"><code>for dataType in dataByType:
    dataByType[dataType] = np.concatenate(dataByType[dataType])

print(dataByType) # once again output formatted for clarity
# {dtype('float64'):
#      array([1., 2., 3., 4.]),
#  dtype('int64'):
#      array([1, 2, 3, 4], dtype=int64)}
</code>```

And if we use array, we get 2D arrays:

for dataType in dataByType:
    dataByType[dataType] = np.array(dataByType[dataType])

print(dataByType)
# {dtype('float64'):
#      array([[1., 2.],
#             [3., 4.]]),
#  dtype('int64'):
#      array([[1, 2],
#             [3, 4]], dtype=int64)}
```
<p><strong>Important thing to note</strong>: using <code>array</code> will not work as intended if all the arrays to combine don't have the same shape:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np

print(repr(np.array([
                np.array([1,2,3]),
                np.array([4,5])])])))
# array([array([1, 2, 3]), array([4, 5])], dtype=object)
</code>```

You get an array of dtype object, which are all in this case arrays of different lengths.

Body:
I'm pretty illiterate in using Python/numpy.

I have the following piece of code:

data = np.array([])

for i in range(10):
    data = np.append(data, GetData())

return data

GetData() returns a numpy array with a custom dtype. However when executing the above piece of code, the numbers convert to float64 which I suspect is the culprit for other issues I'm having. How can I copy/append the output of the functions while preserving the dtype as well?

Body:
Given the comments stating that you will only know the type of data once you run GetData(), and that multiple types are expected, you could do it like so:

# [...]

dataByType = {} # dictionary to store the dtypes encountered and the arrays with given dtype

for i in range(10):
    newData = GetData()
    if newData.dtype not in dataByType:
        # If the dtype has not been encountered yet,
        # create an empty array with that dtype and store it in the dict
        dataByType[newData.dtype] = np.array([], dtype=newData.dtype)
    # Append the new data to the corresponding array in dict, depending on dtype
    dataByType[newData.dtype] = np.append(dataByType[newData.dtype], newData)

Taking into account hpaulj's answer, if you wish to conserve the different types you might encounter without creating a new array at each iteration you can adapt the above to:

# [...]

dataByType = {} # dictionary to store the dtypes encountered and the list storing data with given dtype

for i in range(10):
    newData = GetData()
    if newData.dtype not in dataByType:
        # If the dtype has not been encountered yet,
        # create an empty list with that dtype and store it in the dict
        dataByType[newData.dtype] = []
    # Append the new data to the corresponding list in dict, depending on dtype
    dataByType[newData.dtype].append(newData)

# At this point, you have all your data pieces stored according to their original dtype inside the dataByType dictionary.
# Now if you wish you can convert them to numpy arrays as well

# Either by concatenation, updating what is stored in the dict
for dataType in dataByType:
    dataByType[dataType] = np.concatenate(dataByType[dataType])
    # No need to specify the dtype in concatenate here, since previous step ensures all data pieces are the same type

# Or by creating array directly, to store each data piece at a different index
for dataType in dataByType:
    dataByType[dataType] = np.array(dataByType[dataType])
    # As for concatenate, no need to specify the dtype here

A little example:

import numpy as np

# to get something similar to GetData in the example structure:
getData = [
    np.array([1.,2.], dtype=np.float64),
    np.array([1,2], dtype=np.int64),
    np.array([3,4], dtype=np.int64),
    np.array([3.,4.], dtype=np.float64)
    ] # dtype precised here for clarity, but not needed

dataByType = {}

for i in range(len(getData)):
    newData = getData[i]
    if newData.dtype not in dataByType:
        dataByType[newData.dtype] = []
    dataByType[newData.dtype].append(newData)

print(dataByType) # output formatted below for clarity
# {dtype('float64'):
#     [array([1., 2.]), array([3., 4.])],
#  dtype('int64'):
#     [array([1, 2], dtype=int64), array([3, 4], dtype=int64)]}

Now if we use concatenate on that dataset, we get 1D arrays, conserving the original type (dtype=float64 not precised in the output since it is the default type for floating point values):

for dataType in dataByType:
    dataByType[dataType] = np.concatenate(dataByType[dataType])

print(dataByType) # once again output formatted for clarity
# {dtype('float64'):
#      array([1., 2., 3., 4.]),
#  dtype('int64'):
#      array([1, 2, 3, 4], dtype=int64)}

And if we use array, we get 2D arrays:

for dataType in dataByType:
    dataByType[dataType] = np.array(dataByType[dataType])

print(dataByType)
# {dtype('float64'):
#      array([[1., 2.],
#             [3., 4.]]),
#  dtype('int64'):
#      array([[1, 2],
#             [3, 4]], dtype=int64)}

Important thing to note: using array will not work as intended if all the arrays to combine don't have the same shape:

import numpy as np

print(repr(np.array([
                np.array([1,2,3]),
                np.array([4,5])])])))
# array([array([1, 2, 3]), array([4, 5])], dtype=object)

You get an array of dtype object, which are all in this case arrays of different lengths.


问:
How to get the length of a string field in Mongoose?
I am new to MongoDB and Mongoose.

I am practicing some of the queries with the following Schema and Model:

```<code>const articleSchema = mongoose.Schema({
  title: String,
  content: String,
});

const Article = mongoose.model('article', articleSchema);

</code>```

Let's say I added the following two documents:

```<code>{title: "One", content: "Content One"}
{title: "LongerTitleThanOne", content: "Content Two"}
</code>```

Which query can I use to find all documents where the "title" length is greater than 3?

I tried the following query but it only works with numbers:

```<code>Article.find({title:{$gt:3}}, (err,foundItems)=>{});
</code>```

Many thanks in advance for your help here.

答:
This is not the best way to do this but it works

I advise you to not use this in production.

First get all your data from you database and store it in a variable then use JavaScript filter function to accomplish your task

For Example

```<code>     let data = model.find({});
     let filter_data = data.filter(data.title.length>8);
</code>```

Body:
I am new to MongoDB and Mongoose.

I am practicing some of the queries with the following Schema and Model:

const articleSchema = mongoose.Schema({
  title: String,
  content: String,
});

const Article = mongoose.model('article', articleSchema);

Let's say I added the following two documents:

{title: "One", content: "Content One"}
{title: "LongerTitleThanOne", content: "Content Two"}

Which query can I use to find all documents where the "title" length is greater than 3?

I tried the following query but it only works with numbers:

Article.find({title:{$gt:3}}, (err,foundItems)=>{});

Many thanks in advance for your help here.

Body:
This is not the best way to do this but it works

I advise you to not use this in production.

First get all your data from you database and store it in a variable then use JavaScript filter function to accomplish your task

For Example

     let data = model.find({});
     let filter_data = data.filter(data.title.length>8);


问:
ORA-01000: maximum open cursors exceeded using oracle instant client and C#
Our C# application is generating ORA-01000 error. We were using ODP.Net and the application was running just perfect without any ORA-01000 error.

We removed the ODP.Net and installed the instant client instead (we are now connecting from C# to Oracle using 7 dll files which are oci.dll, ociw32.dll, Oracle.DataAccess.dll, orannzsbb11.dll, oraocci11.dll, oraociicus11.dll and OraOps11w.dll).

Since then we are getting the ORA-01000 upon executing a long process with multiple queries. Noting that we are closing/disposing the OracleDataReader object.

What could be the reason behind the ORA-01000 with instant client?

答:
Got the same problem and solved it by doing

OracleConnection.ClearPool(oraConn);

between your multiple requests


问:
Json parsing problem android
If the response of a request is a json response how to handle it and decode it.I have tried the following abnd get an error @     JSONArray json = new JSONArray(r1);

```<code>HttpPost post = new HttpPost(postURL);
MultipartEntity reqEntity = new MultipartEntity();

HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();

String r1 = EntityUtils.toString(resEntity);
System.out.println("printing response now "+r1);
JSONArray json = new JSONArray(r1);

//Toast.makeText(getApplicationContext(), "data received"+r1, Toast.LENGTH_LONG).show();
//  JSONObject json = new JSONObject(r1);
JSONArray venues = json.getJSONObject("data")
          .getJSONArray("url")
          .getJSONObject(0)
          .getJSONArray("url");
</code>```

Json structure is given below

```<code> [
 {"data":
  {"url":
   {
     "url": "http://www.xxxxxx.com/story.html", "title":"some data","source_url": "www.somesite.com", "summary": "\n \n \n \n \n somedata again"
   }
  }
 }
 ]
</code>```

Error:

```<code>   08-18 16:30:22.907: INFO/System.out(1178): Exceptionorg.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray
</code>```

答:
I've this following code taking your json and it works for me...
May be you've to check if your orginal json string is ok ... byte per byte may be .. invisible character may disturb the parsing</p>

```<code>  String r1 = "[{\"data\": {\"url\": { \"url\": \"http://www.xxxxxx.com/story.html\",  \"title\":\"some data\",\"source_url\": \"www.somesite.com\", \"summary\": \"\\n \\n \\n \\n \\n somedata again\"}}}]";
try {
   JSONArray json = new JSONArray(r1);

   Object url = json.getJSONObject(0)
            .getJSONObject("data")
            .getJSONObject("url")
            .get("url");
   Toast.makeText(getApplicationContext(), "url="+url.toString(), Toast.LENGTH_LONG).show();
   Log.i("TESTJSON","All Is Ok");

} catch (Exception e) {
   Log.d("TESTJSON","Something wrong..",e);
   Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
</code>```

Title: Json parsing problem android

Body:
If the response of a request is a json response how to handle it and decode it.I have tried the following abnd get an error @     JSONArray json = new JSONArray(r1);

HttpPost post = new HttpPost(postURL);
MultipartEntity reqEntity = new MultipartEntity();

HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();

String r1 = EntityUtils.toString(resEntity);
System.out.println("printing response now "+r1);
JSONArray json = new JSONArray(r1);

//Toast.makeText(getApplicationContext(), "data received"+r1, Toast.LENGTH_LONG).show();
//  JSONObject json = new JSONObject(r1);
JSONArray venues = json.getJSONObject("data")
          .getJSONArray("url")
          .getJSONObject(0)
          .getJSONArray("url");

Json structure is given below

 [
 {"data":
  {"url":
   {
     "url": "http://www.xxxxxx.com/story.html", "title":"some data","source_url": "www.somesite.com", "summary": "\n \n \n \n \n somedata again"
   }
  }
 }
 ]

Error:

   08-18 16:30:22.907: INFO/System.out(1178): Exceptionorg.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray

Body:
I've this following code taking your json and it works for me...
May be you've to check if your orginal json string is ok ... byte per byte may be .. invisible character may disturb the parsing

  String r1 = "[{\"data\": {\"url\": { \"url\": \"http://www.xxxxxx.com/story.html\",  \"title\":\"some data\",\"source_url\": \"www.somesite.com\", \"summary\": \"\\n \\n \\n \\n \\n somedata again\"}}}]";
try {
   JSONArray json = new JSONArray(r1);

   Object url = json.getJSONObject(0)
            .getJSONObject("data")
            .getJSONObject("url")
            .get("url");
   Toast.makeText(getApplicationContext(), "url="+url.toString(), Toast.LENGTH_LONG).show();
   Log.i("TESTJSON","All Is Ok");

} catch (Exception e) {
   Log.d("TESTJSON","Something wrong..",e);
   Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}


问:
Add key:value to dictionary if variable is not None
I have a function clans(), that accepts 8 arguments. I need to add key and value pair to dictionary if argument is not None. There is my solution:

```<code>def clans(self, name: str = None, warFrequency: str = None, location: str = None,
            minMembers: int = None, maxMembers: int = None,
            minClanPoints: int = None, minClanLevel: int = None,
            labels: list[str] = None):
    params = {} # <- the dictionary to add to

    # very much if-conditions
    if name is not None:
        params['name'] = name
    if warFrequency is not None:
        params['warFrequency'] = warFrequency
    ... # <- other function arguments and if conditions
    if labels is not None:
        params['labels'] = labels

    return params
</code>```

I think it is not the most optimal solution due to the large amount of code and poor readability, how can I improve that code? I have an idea like (but I dont know how to realize it):

```<code>params = {}
for arg in args: # <- args is list of function arguments
    if arg is not None:
        params[arg.key()] = arg.value() # <- arg.key() is argument name, arg.value() is value
</code>```

答:
I have found an answer, based on @RJ Adriaansen solution, there it is (this will also check if argument is not self):

```<code>def clans(self, name: str = None, warFrequency: str = None, location: str = None,
                minMembers: int = None, maxMembers: int = None,
                minClanPoints: int = None, minClanLevel: int = None,
                labels: list[str] = None):
        params = {k: v for k, v in locals().items() if v is not None and v != self}
        #                                                            ^^^^^^^^^^^^^
        #                                                            small change
        return params

</code>```

Body:
I have a function clans(), that accepts 8 arguments. I need to add key and value pair to dictionary if argument is not None. There is my solution:

def clans(self, name: str = None, warFrequency: str = None, location: str = None,
            minMembers: int = None, maxMembers: int = None,
            minClanPoints: int = None, minClanLevel: int = None,
            labels: list[str] = None):
    params = {} # <- the dictionary to add to

    # very much if-conditions
    if name is not None:
        params['name'] = name
    if warFrequency is not None:
        params['warFrequency'] = warFrequency
    ... # <- other function arguments and if conditions
    if labels is not None:
        params['labels'] = labels

    return params

I think it is not the most optimal solution due to the large amount of code and poor readability, how can I improve that code? I have an idea like (but I dont know how to realize it):

params = {}
for arg in args: # <- args is list of function arguments
    if arg is not None:
        params[arg.key()] = arg.value() # <- arg.key() is argument name, arg.value() is value

Body:
I have found an answer, based on @RJ Adriaansen solution, there it is (this will also check if argument is not self):

def clans(self, name: str = None, warFrequency: str = None, location: str = None,
                minMembers: int = None, maxMembers: int = None,
                minClanPoints: int = None, minClanLevel: int = None,
                labels: list[str] = None):
        params = {k: v for k, v in locals().items() if v is not None and v != self}
        #                                                            ^^^^^^^^^^^^^
        #                                                            small change
        return params


问:
How to Redirect From Backend To FrontEnd after Authentication
I Have My Backend (nodejs) running on another Port And My Frontend (React) Running On Another Port...So After After Sending Credentials To Backend And Authentication...How Can I Redirect To Front End ?</p>

答:
in my case, I was handling the verifyEmail on the backend of a nest.js server.

How I was able to redirect to the frontend after handling the request, was to use the res.redirect from express.

```<code>
  @Get('verify/:token')
  async verifyUser(@Param('token') token, @Res() response: Response): Promise<any> {
    const redirectUrl = await  this.authService.verifyUserEmail(token);
    response.redirect(redirectUrl);
    return {redirectUrl};
  }
</code>```

And, it worked like a charm.

Body:
in my case, I was handling the verifyEmail on the backend of a nest.js server.

How I was able to redirect to the frontend after handling the request, was to use the res.redirect from express.

  @Get('verify/:token')
  async verifyUser(@Param('token') token, @Res() response: Response): Promise<any> {
    const redirectUrl = await  this.authService.verifyUserEmail(token);
    response.redirect(redirectUrl);
    return {redirectUrl};
  }

And, it worked like a charm.


问:
Is their SDK library to create Github Bot in python
I was moving towards creating Bot(Github App). I googled a lot but could not find it.
Is their any SDK, library to create Github bots in python as Slack-bolt, slack SDK for python to listen for web events?
There is probot which is for Node Development. Any thoughts?</p>

答: It seems that this conversation happened here, and the consensus was to use this though it's not official GitHub, and looks under active development as of Feb 2022.</p>