问:
Handle warning like an exception and read csv file accordingly
When I read_csv the following df, it raises the warning:

```<code>              TIME                       col_A     col_B
0        yyyy-MM-dd"T"HH:mm:ss.fffzzz      t         m
1       2022-12-10T00:00:00.000-06:00  0.000     0.000
2       2022-12-10T00:00:05.000-06:00  0.000     0.000
</code>```

```<code>> DtypeWarning: Columns (1,2,3) have mixed types. Specify dtype option
> on import or set low_memory=False. csv_file =
> pd.read_csv(self.surf_path + '/' + file)
</code>```

I understand the warning, when I have these sorts of csv files (with units on the zeroth index) I have to manually drop the index 0 in order to be able to process further. I would like to write a function, which catches this warning and drops the zeroth index if necessary. See example of code I have in mind:

```<code>def read_file():
  for file in os.listdir(file_path):
    if file.endswith('.csv'):
      try:
        csv_file = pd.read_csv(self.surf_path + '/' + file)
      except DtypeWarning:
        csv_file = pd.read_csv(self.surf_path + '/' + file)
        csv_file.drop(index=csv_file.index[0], axis=0, inplace=True)
        csv_file.reset_index(drop=True, inplace=True)
  return csv_file
</code>```

I know in python I can catch only exception in this way, not the warnings, but I couldn't fiigure out how to catch the warning for my case from other posts.

Body:
When I read_csv the following df, it raises the warning:

              TIME                       col_A     col_B
0        yyyy-MM-dd"T"HH:mm:ss.fffzzz      t         m
1       2022-12-10T00:00:00.000-06:00  0.000     0.000
2       2022-12-10T00:00:05.000-06:00  0.000     0.000

> DtypeWarning: Columns (1,2,3) have mixed types. Specify dtype option
> on import or set low_memory=False. csv_file =
> pd.read_csv(self.surf_path + '/' + file)

I understand the warning, when I have these sorts of csv files (with units on the zeroth index) I have to manually drop the index 0 in order to be able to process further. I would like to write a function, which catches this warning and drops the zeroth index if necessary. See example of code I have in mind:

def read_file():
  for file in os.listdir(file_path):
    if file.endswith('.csv'):
      try:
        csv_file = pd.read_csv(self.surf_path + '/' + file)
      except DtypeWarning:
        csv_file = pd.read_csv(self.surf_path + '/' + file)
        csv_file.drop(index=csv_file.index[0], axis=0, inplace=True)
        csv_file.reset_index(drop=True, inplace=True)
  return csv_file

I know in python I can catch only exception in this way, not the warnings, but I couldn't fiigure out how to catch the warning for my case from other posts.


来源: stackexchange

问:
R-score total in neural network
How is the total R-score factor calculated in the neural network?
For example, for test data, it is between the test output and the actual output.
For validation, it is between the validation data and the actual output.

What criteria is considered for the total** R-score total **that is reported in MATLAB?

How is the total R-score factor calculated in the neural network?
For example, for test data, it is between the test output and the actual output.
For validation, it is between the validation data and the actual output.

What criteria is considered for the **total R-SCORE totall **that is reported in MATLAB?

ContentLicense: CC BY-SA 4.0

Title: R-score total in neural network


问:
Multiple patterns matching on Chinese/Japanese in one pass?
Suppose:

source strings are 10 ~ 1000 length in Chinese, Japanese or Korea,
that's means the character set are 5000~10000

the regular pattens may reach 1000,

so how can we use one pass against the multi patterns?

and how to do if add the substitution

one pass against the multi patterns


问:
Add a new "addopts" by default in pytest plugin?
I want to disable capture by default in a pytest plugin I'm working on. This can be done using an "ini" file normally as below:

```<code>[pytest]
addopts = -s
</code>```

In the pytest docs they discuss "addini", and this works for other values I've tried but not addopts.

https://docs.pytest.org/en/latest/reference/reference.html#pytest.Parser.addini

https://docs.pytest.org/en/latest/reference/reference.html#pytest.hookspec.pytest_addoption

An alternative way to approach is to override the argument directly like so:

def pytest_addoption(parser):
    parser.addoption(
        "--capture",
        dest="capture",
        help="Capture the output",
        default='no'
    )
```

...but this complains that there is an argument conflict with the existing capture argument.

Is there some other better practice for default values of addopts that I haven't thought of?

Body:
I want to disable capture by default in a pytest plugin I'm working on. This can be done using an "ini" file normally as below:

[pytest]
addopts = -s

In the pytest docs they discuss "addini", and this works for other values I've tried but not addopts.

https://docs.pytest.org/en/latest/reference/reference.html#pytest.Parser.addini

https://docs.pytest.org/en/latest/reference/reference.html#pytest.hookspec.pytest_addoption

An alternative way to approach is to override the argument directly like so:

def pytest_addoption(parser):
    parser.addoption(
        "--capture",
        dest="capture",
        help="Capture the output",
        default='no'
    )

...but this complains that there is an argument conflict with the existing capture argument.

Is there some other better practice for default values of addopts that I haven't thought of?


问:
I saved an image in local database. whenever i try to open using glide. i get the following log
enter image description here

fail to get the list and getting null pointer exception.

whenever i add the product into cart then it proceed into cart but image is not loaded and getting error of null pointer exception

```<code>class CartFragment : Fragment() {

    private lateinit var binding: FragmentCartBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentCartBinding.inflate(layoutInflater)

        val preference = requireContext().getSharedPreferences("info", AppCompatActivity.MODE_PRIVATE)
        val editor = preference.edit()
        editor.putBoolean("isCart",false)
        editor.apply()

        val dao = AppDatabase.getInstance(requireContext()).productDao()
        dao.getAllProducts().observe(requireActivity()){
            binding.cartRecycler.adapter = CartAdapter(requireContext(),it)

            totalCost(it)
        }

        return binding.root
    }

    private fun totalCost(data: List<ProductModel>) {
        var total = "0"
        for (item in data){
            total += item.productSp!!.toString()

        }
        binding.textView12.text = "Total item in cart is ${data.size}"
        binding.textView13.text = "Total Cost $total"

        binding.checkout.setOnClickListener {
            val intent = Intent(context, AddressActivity::class.java)
            intent.putExtra("totalCost",total)
            startActivity(intent)
        }

    }
}
</code>```

Body:
enter image description here

fail to get the list and getting null pointer exception.

whenever i add the product into cart then it proceed into cart but image is not loaded and getting error of null pointer exception

class CartFragment : Fragment() {

    private lateinit var binding: FragmentCartBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentCartBinding.inflate(layoutInflater)

        val preference = requireContext().getSharedPreferences("info", AppCompatActivity.MODE_PRIVATE)
        val editor = preference.edit()
        editor.putBoolean("isCart",false)
        editor.apply()

        val dao = AppDatabase.getInstance(requireContext()).productDao()
        dao.getAllProducts().observe(requireActivity()){
            binding.cartRecycler.adapter = CartAdapter(requireContext(),it)

            totalCost(it)
        }

        return binding.root
    }

    private fun totalCost(data: List<ProductModel>) {
        var total = "0"
        for (item in data){
            total += item.productSp!!.toString()

        }
        binding.textView12.text = "Total item in cart is ${data.size}"
        binding.textView13.text = "Total Cost $total"

        binding.checkout.setOnClickListener {
            val intent = Intent(context, AddressActivity::class.java)
            intent.putExtra("totalCost",total)
            startActivity(intent)
        }

    }
}


问:
I want to develop application for windows with flutter and I want to prevent screen recording can I do that with flutter
I want to develop an application for windows with flutter and I want to prevent screen recording can I do that flutter can someone help me to do that it is an E-learning application so I want to avoid students from screen recording or in that case make the screen black can I do that or not</p>


问:
Use CMake build system for Fortran simulation on CodeBlocks
I downloaded a Fortran simulation from github and wanted to run the main_prog.f90 on CodeBlocks. I'm not sure what the This project uses the CMake build system means in the readme file, so if I try to compile, I get an error:

Fatal Error: Can't open module file 'asteroid_module.mod' for reading at (1): No such file or directory

Does this mean that CodeBlocks can't locate the module files? If so how do I fix it and does it involve using CMake in CodeBlocks? I looked at relevant posts like this older question but it wasn't helpful.

Edit: I had to add MinGW to the environment variables (see eg. this post, and note for Win10 you go to Control Panel > System > Advanced System Settings > System properties > Advanced > Environment variables). It seems to work now.


问:
Preprocess and data transformation in machine learning
I have a  problem where I have to predict a buyer using machine learning (created a dummy dataset). I need to transform the data first before I can use it for machine learning. I am aggregating information per id,visit level which gives me a list of food and cloths bought. This list needs to be one hot encoded before applying classifier model.

import pandas as pd
import numpy as np
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import GradientBoostingClassifier

def preprocess(df):
    # Only keep rows till buyer=1
    df = df.groupby(["id1", "visit"], group_keys=False).apply(
        lambda g: g.loc[: g["Buyer"].idxmax()]
    )

    # Form lists on each id1,visit level
    df1 = df.groupby(["id1", "visit"], as_index=False).agg(
        is_Pax=("Buyer", "max"),
        fruits=("fruits", lambda x: x.dropna().unique().tolist()),
        cloths=("cloths", lambda x: x.dropna().unique().tolist()),
    )
    col = ["fruits", "cloths"]
    df_transformed = onehot(df1, col)
    return df_transformed

def onehot(df, col):
    """
    This function does one hot encoding of a list column.
    """

    onehot_list_encoder = MultiLabelBinarizer()
    for cl in col:
        print("One hot encoding ", cl)
        newd = pd.DataFrame(
            onehot_list_encoder.fit_transform(df[cl]),
            columns=onehot_list_encoder.classes_,
        ).add_prefix(cl + "_")
        df = df.join(newd)
    return df

df = pd.DataFrame(np.array([['a', 'a', 'b', 'b','a','a'], [1, 2, 2, 2,1,1],
                            ['Apple', 'Apple', 'Banana', None,'Orange','Pear'],[1,2,1,3,4,5],
                           [0, 0, 1, 0,1,0]]).T,
                  columns=['id1', 'visit', 'fruits','cloths','Buyer'])
df['Buyer'] = df['Buyer'].astype('int')

```
<p>How to create a simple ML model now that does this preprocessing to data (both fit and predict) since in test data, I want the same transformation (i.e. 0 for all columns not present in the test rows), Can pipeline solve this? I am not so good with writing pipelines and am getting errors.</p>
<pre class="lang-py prettyprint-override"><code>droplist=['id1', 'visit', 'fruits','cloths']
pipe=Pipeline(steps=[
    ("preprocess",preprocess(df)),
    ("coltrans",ColumnTransformer([("drop",'drop',droplist)])),
    ("model",GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)),
    ])
</code>```

Can someone help?

Body:
I have a  problem where I have to predict a buyer using machine learning (created a dummy dataset). I need to transform the data first before I can use it for machine learning. I am aggregating information per id,visit level which gives me a list of food and cloths bought. This list needs to be one hot encoded before applying classifier model.

import pandas as pd
import numpy as np
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import GradientBoostingClassifier

def preprocess(df):
    # Only keep rows till buyer=1
    df = df.groupby(["id1", "visit"], group_keys=False).apply(
        lambda g: g.loc[: g["Buyer"].idxmax()]
    )

    # Form lists on each id1,visit level
    df1 = df.groupby(["id1", "visit"], as_index=False).agg(
        is_Pax=("Buyer", "max"),
        fruits=("fruits", lambda x: x.dropna().unique().tolist()),
        cloths=("cloths", lambda x: x.dropna().unique().tolist()),
    )
    col = ["fruits", "cloths"]
    df_transformed = onehot(df1, col)
    return df_transformed

def onehot(df, col):
    """
    This function does one hot encoding of a list column.
    """

    onehot_list_encoder = MultiLabelBinarizer()
    for cl in col:
        print("One hot encoding ", cl)
        newd = pd.DataFrame(
            onehot_list_encoder.fit_transform(df[cl]),
            columns=onehot_list_encoder.classes_,
        ).add_prefix(cl + "_")
        df = df.join(newd)
    return df

df = pd.DataFrame(np.array([['a', 'a', 'b', 'b','a','a'], [1, 2, 2, 2,1,1],
                            ['Apple', 'Apple', 'Banana', None,'Orange','Pear'],[1,2,1,3,4,5],
                           [0, 0, 1, 0,1,0]]).T,
                  columns=['id1', 'visit', 'fruits','cloths','Buyer'])
df['Buyer'] = df['Buyer'].astype('int')

How to create a simple ML model now that does this preprocessing to data (both fit and predict) since in test data, I want the same transformation (i.e. 0 for all columns not present in the test rows), Can pipeline solve this? I am not so good with writing pipelines and am getting errors.

droplist=['id1', 'visit', 'fruits','cloths']
pipe=Pipeline(steps=[
    ("preprocess",preprocess(df)),
    ("coltrans",ColumnTransformer([("drop",'drop',droplist)])),
    ("model",GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)),
    ])

Can someone help?


问:
Vue.js 2 / Webpack Part disable Prefetch - Cannot call .tap() on a plugin that has not yet been defined. Call plugin('prefetch').use(<Plugin>) first
I have a piece of config in my vue.config.js file which is intended to prevent Vue from prefetching files that are dynamically loaded.

The code looks like this...

    chainWebpack: config => {
        // stop webpack from prefetching all possible themes
        config
            .plugin('prefetch')
            .tap(args => {
                args[0].fileBlacklist = [ /\/scheme-.*\./ ]
                return args
            })
    }
```

After doing an npm package update to resolve security vulnerabilities this does not work anymore and I get this error when trying to execute the app...

Error: Cannot call .tap() on a plugin that has not yet been defined.
Call plugin('prefetch').use() first.

I'm not sure what to do from here.

Body:
I have a piece of config in my vue.config.js file which is intended to prevent Vue from prefetching files that are dynamically loaded.

The code looks like this...

    chainWebpack: config => {
        // stop webpack from prefetching all possible themes
        config
            .plugin('prefetch')
            .tap(args => {
                args[0].fileBlacklist = [ /\/scheme-.*\./ ]
                return args
            })
    }

After doing an npm package update to resolve security vulnerabilities this does not work anymore and I get this error when trying to execute the app...

Error: Cannot call .tap() on a plugin that has not yet been defined.
Call plugin('prefetch').use() first.

I'm not sure what to do from here.


问:
Why my ciphered text string is longer than expected?
I'm facing the CS50's substitution problem.
It works, even though the code is not very optimized.

The problem is that i had to add this line of code at the end to make it work:
`

```<code>cipher_text[strlen(plain_text)] = '\0';
</code>```

`

otherwise the lenght of the cipher_text is longer than expected.

Can you tell me why?

this is the code i've written.

`

```<code>#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, string argv[])
{
    // check if there's 1 argument, if there are > 1 or < 0 print error message and return 1
    if (argc != 2)
    {
        printf("Error, type 1 command\n");
        return 1;
    }

    string key = argv[1];
    long lenght = strlen(key);

    // check if the key is valid (26 characters) or not, if not return 1 and print error
    if (lenght != 26)
    {
        printf("Key must contain 26 characters.\n");
        return 1;
    }

    // iterate throughout the key, element after element whith the 1st for loop
        //check if contains letters or something else in the 1st if
        //make the key all lower in order to compare letter repetition in the else if
        //check for double letters (compare every letter (key[i]) with all the other letters) in the second for loop
    for (int i = 0 ; i < lenght ; i++)
    {
        if (isalpha(key[i]) == 0) //(key[i] < 65 || key[i] > 90) && (key[i] < 97 || key[i] > 122))
        {
            printf("Key must contain only letters\n");
            return 1;
        }
        else if (isupper(key[i]))
        {
            key[i] = tolower(key[i]);
        }
        for (int j = 0 ; j < lenght ; j++)
        {
            if (j != i && key[j] == key[i])
            {
                printf("You can't repeat letters in key (you've repeated the letter %c)\n", key[j]);
                return 1;
            }
        }
    }

    //ask user for the text to cipher
    string plain_text = get_string("plaintext:  ");

    char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    char ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    char cipher_text[strlen(plain_text)];

    // iterate through every index in plain_text
        //if it is not alphabetical, add it to cipher text
        //otherwise, check if it is lower or upper, and add to cipher_text
        //
    for (int j = 0; j < strlen(plain_text) ; j++)
    {
        if (isalpha(plain_text[j]) == 0)
        {
            cipher_text[j] = plain_text[j];
        }

        for (int x = 0 ; x < lenght ; x++)
        {
            if(islower(plain_text[j]))
            {
                if (plain_text[j] == alphabet[x])
                {
                cipher_text[j] = key[x];
                }
            }
            else if (isupper(plain_text[j]))
            {
                if (plain_text[j] == ALPHABET[x])
                {
                cipher_text[j] = toupper(key[x]);
                }
            }

        }

    }

    cipher_text[strlen(plain_text)] = '\0';

    printf("ciphertext: %s\n", cipher_text);

    return 0;

}
</code>```

`

Body:
I'm facing the CS50's substitution problem.
It works, even though the code is not very optimized.

The problem is that i had to add this line of code at the end to make it work:
`

cipher_text[strlen(plain_text)] = '\0';

`

otherwise the lenght of the cipher_text is longer than expected.

Can you tell me why?

this is the code i've written.

`

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, string argv[])
{
    // check if there's 1 argument, if there are > 1 or < 0 print error message and return 1
    if (argc != 2)
    {
        printf("Error, type 1 command\n");
        return 1;
    }

    string key = argv[1];
    long lenght = strlen(key);

    // check if the key is valid (26 characters) or not, if not return 1 and print error
    if (lenght != 26)
    {
        printf("Key must contain 26 characters.\n");
        return 1;
    }

    // iterate throughout the key, element after element whith the 1st for loop
        //check if contains letters or something else in the 1st if
        //make the key all lower in order to compare letter repetition in the else if
        //check for double letters (compare every letter (key[i]) with all the other letters) in the second for loop
    for (int i = 0 ; i < lenght ; i++)
    {
        if (isalpha(key[i]) == 0) //(key[i] < 65 || key[i] > 90) && (key[i] < 97 || key[i] > 122))
        {
            printf("Key must contain only letters\n");
            return 1;
        }
        else if (isupper(key[i]))
        {
            key[i] = tolower(key[i]);
        }
        for (int j = 0 ; j < lenght ; j++)
        {
            if (j != i && key[j] == key[i])
            {
                printf("You can't repeat letters in key (you've repeated the letter %c)\n", key[j]);
                return 1;
            }
        }
    }

    //ask user for the text to cipher
    string plain_text = get_string("plaintext:  ");

    char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    char ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    char cipher_text[strlen(plain_text)];

    // iterate through every index in plain_text
        //if it is not alphabetical, add it to cipher text
        //otherwise, check if it is lower or upper, and add to cipher_text
        //
    for (int j = 0; j < strlen(plain_text) ; j++)
    {
        if (isalpha(plain_text[j]) == 0)
        {
            cipher_text[j] = plain_text[j];
        }

        for (int x = 0 ; x < lenght ; x++)
        {
            if(islower(plain_text[j]))
            {
                if (plain_text[j] == alphabet[x])
                {
                cipher_text[j] = key[x];
                }
            }
            else if (isupper(plain_text[j]))
            {
                if (plain_text[j] == ALPHABET[x])
                {
                cipher_text[j] = toupper(key[x]);
                }
            }

        }

    }

    cipher_text[strlen(plain_text)] = '\0';

    printf("ciphertext: %s\n", cipher_text);

    return 0;

}

`


问:
eclipse configuration build output location reacts differently after restart of ecplise
My eclipse with Version: 2022-12 (4.26.0) and Build id: 20221201-1913 reacts strangely when it comes to the build output location.
I have a small C/C++ Projekt with a single makefile and use gtkmm3. Under "Edit Configuration" - "Build Settings" - "Build Output Location" I can chose between "1. Build in project directory" and "2. Build in configuration specific directory". I set this to 1. Build in project directory.
It works. I get some error logs of this kind: "Indexed 'HausRegelung' (2 sources, 176 headers) in 8.68 sec: 13,582 declarations; 21,405 references; 6 unresolved inclusions; 0 syntax errors; 53 unresolved names (0.15%)" but can run my program anyhow. I can make changes - rebuild - and it works.
If I restart eclipse and perform a rebuild, I get this message:

Building in: /home/bejo/eclipse-workspace/HausRegelung/build/default
make -f ../../Makefile
find: ‘./src’: No such file or directory
g++  pkg-config --libs gtkmm-3.0 -o build/HausRegelung
find: ‘./src’: No such file or directory
/usr/bin/ld: cannot open output file build/HausRegelung: No such file or directory
collect2: error: ld returned 1 exit status
make: *** [../../Makefile:32: build/HausRegelung] Error 1
Build complete (2 errors, 0 warnings): /home/bejo/eclipse-workspace/HausRegelung/build/default

The project directory is "/home/bejo/eclipse-workspace/HausRegelung" and not "/home/bejo/eclipse-workspace/HausRegelung/build/default". The curious thing is, that when I enter the "Build Output Location" and change it - hit save - reenter the "Build Output Location" and change it back to what it was before (Build in project directory) - save it and then go for a rebuild everything works fine. Basically, I effectively do not change anything. But it has an effect.

What do I have to set, to not have to do this "Build Output Location Dance" every time and only once, eclipse is started?


问:
Is greyscale closing equivalent to binary closing on a binary image?
I have several binary images (geotiff) that i want to perform binary closing on.
Because there are atleast 2600 images, i want to shorten the execution time for each operation.

I'm using Python and have found several packages which include this operation. Among these are scipy and scikit-image:

from scipy.ndimage import binary_closing
from scipy.ndimage import grey_closing
import skimage.morphology as sm

....
        arr = some_binary_image_as_numpy_array

        start = time.time()
        disk = sm.disk(5)
        opened_arr = sm.binary_closing(arr, disk )
        end = time.time()
        print(end - start)

        start = time.time()
        opened_arr = binary_closing(arr, structure=np.ones((10, 10)) )
        end = time.time()
        print(end - start)

```
<p>output:</p>
```8.373806715011597
9.53745985031128
```
<p>I know the scikit-image disk isnt the same as the np.ones ((10,10)), so they are not completely the same.</p>
<p>However, when i run scipy's greyscale closing (grey_closing) i get this result:</p>
```        start = time.time()
        opened_arr = grey_closing(arr, size=(10, 10))
        end = time.time()
        print(end - start)
```
<p>output:</p>
```4.35299277305603
```

On 10 out of 11 images i tried, the number of pixels with 1 in grey_closing and binary_closing were the same.

I know scipy's grey_closing also has the argument structure, but when i use this, the execution time increased to 30 seconds.

So my question is: would scipy's grey_closing using the argument size, be the same as
using scipy's binary_closing with argument structure?

Body:
I have several binary images (geotiff) that i want to perform binary closing on.
Because there are atleast 2600 images, i want to shorten the execution time for each operation.

I'm using Python and have found several packages which include this operation. Among these are scipy and scikit-image:

from scipy.ndimage import binary_closing
from scipy.ndimage import grey_closing
import skimage.morphology as sm

....
        arr = some_binary_image_as_numpy_array

        start = time.time()
        disk = sm.disk(5)
        opened_arr = sm.binary_closing(arr, disk )
        end = time.time()
        print(end - start)

        start = time.time()
        opened_arr = binary_closing(arr, structure=np.ones((10, 10)) )
        end = time.time()
        print(end - start)

output:

8.373806715011597
9.53745985031128

I know the scikit-image disk isnt the same as the np.ones ((10,10)), so they are not completely the same.

However, when i run scipy's greyscale closing (grey_closing) i get this result:

        start = time.time()
        opened_arr = grey_closing(arr, size=(10, 10))
        end = time.time()
        print(end - start)

output:

4.35299277305603

On 10 out of 11 images i tried, the number of pixels with 1 in grey_closing and binary_closing were the same.

I know scipy's grey_closing also has the argument structure, but when i use this, the execution time increased to 30 seconds.

So my question is: would scipy's grey_closing using the argument size, be the same as
using scipy's binary_closing with argument structure?


问:
Plotting boxplots in one graph of rasterlayers of different extents
I have 4 rasterstacks of different zones containing each 12 layers (one for every month) containing data on atmospheric NO2 concentration. I made a layer for each rasterstack containing the mean values for the 12 layers. Now I created a boxplot for each of these mean layers but now I want to combine these boxplots in one plot to easily compare.

I tried to stack the different mean layers but that was not possible because they have a different extent. Here is the code

```<code>#import rasters
NS <- stack("north_seca_2019_stack.tiff")
BY <- stack("Biscay_2019_stack.tiff")
BP <- stack("BQPZJR_2019_stack.tiff")
EC <- stack("EngChan_2019_stack.tiff")

# mean of year

meanIgnoringZeroes <- function(x) {
  mean(x[x>0],na.rm=T)
}

meanBY<- overlay(BY,fun=meanIgnoringZeroes)
meanNS<- overlay(NS,fun=meanIgnoringZeroes)
meanBP<- overlay(BP,fun=meanIgnoringZeroes)
meanEC<- overlay(EC,fun=meanIgnoringZeroes)

t<- stack(meanBY,meanNS,meanBP,meanEC)

> t<- stack(meanBY,meanNS)
Error in compareRaster(x) : different extent

B<-boxplot(meanBY)
N<-boxplot(meanNS)
BZ<- boxplot(meanBP)
E<-boxplot(meanEC)
</code>```

This creates boxplots for each zone but I can't find a way to plot them all together in one plot.

Body:
I have 4 rasterstacks of different zones containing each 12 layers (one for every month) containing data on atmospheric NO2 concentration. I made a layer for each rasterstack containing the mean values for the 12 layers. Now I created a boxplot for each of these mean layers but now I want to combine these boxplots in one plot to easily compare.

I tried to stack the different mean layers but that was not possible because they have a different extent. Here is the code

#import rasters
NS <- stack("north_seca_2019_stack.tiff")
BY <- stack("Biscay_2019_stack.tiff")
BP <- stack("BQPZJR_2019_stack.tiff")
EC <- stack("EngChan_2019_stack.tiff")

# mean of year

meanIgnoringZeroes <- function(x) {
  mean(x[x>0],na.rm=T)
}

meanBY<- overlay(BY,fun=meanIgnoringZeroes)
meanNS<- overlay(NS,fun=meanIgnoringZeroes)
meanBP<- overlay(BP,fun=meanIgnoringZeroes)
meanEC<- overlay(EC,fun=meanIgnoringZeroes)

t<- stack(meanBY,meanNS,meanBP,meanEC)

> t<- stack(meanBY,meanNS)
Error in compareRaster(x) : different extent

B<-boxplot(meanBY)
N<-boxplot(meanNS)
BZ<- boxplot(meanBP)
E<-boxplot(meanEC)

This creates boxplots for each zone but I can't find a way to plot them all together in one plot.


问:
How to send an e-mail if a particular word is present in subject using Python
I have sent an automated e-mail using python with the following subject: "Daily Test Results are completed and please find the Test Results". Once this is done, I should wait and search for the reply for this email with the following subject: "Daily Test Results are completed and please find the Test Results - CHECK OK/VERIFIED/SEND/PASS_SEND"
Once I receive the mail with the new subject, then through python I must share the original mail with the first subject to multiple users.

I am not sure on two points:

For subject ending with CHECK OK/VERIFIED/SEND/PASS_SEND, I am not able to give a list and instead give only one keyword

If I give one keyword and search, I am able to get the mail, but I am not sure how to share the original mail to remaining participants

Can some one please help me with this

Code:

```<code>import win32com.client as win32
from datetime import date
def mail_check():
    Outlook = win32.Dispatch('Outlook.Application').GetNameSpace('MAPI')
    inbox = Outlook.GetDefaultFolder(6)
    sub = [message for message in inbox.Items if 'CHECK OK' in message.Subject]
    for mssg in sub:
        print(mssg)
if __name__ == '__main__':
    mail_check()
</code>```

Body:
I have sent an automated e-mail using python with the following subject: "Daily Test Results are completed and please find the Test Results". Once this is done, I should wait and search for the reply for this email with the following subject: "Daily Test Results are completed and please find the Test Results - CHECK OK/VERIFIED/SEND/PASS_SEND"
Once I receive the mail with the new subject, then through python I must share the original mail with the first subject to multiple users.

I am not sure on two points:

For subject ending with CHECK OK/VERIFIED/SEND/PASS_SEND, I am not able to give a list and instead give only one keyword

If I give one keyword and search, I am able to get the mail, but I am not sure how to share the original mail to remaining participants

Can some one please help me with this

Code:

import win32com.client as win32
from datetime import date
def mail_check():
    Outlook = win32.Dispatch('Outlook.Application').GetNameSpace('MAPI')
    inbox = Outlook.GetDefaultFolder(6)
    sub = [message for message in inbox.Items if 'CHECK OK' in message.Subject]
    for mssg in sub:
        print(mssg)
if __name__ == '__main__':
    mail_check()


问:
Identical x-axis on two different plot in grid.arrange() /ggplot function
I have attempted to create two distributions of age using the following lines of code:

```<code>library(ggplot2)
library(gridExtra)
f <- ggplot(Opportunities) +geom_density(aes(x = Age))
a <- ggplot(Transactions) +geom_density(aes(x = Age))
grid.arrange(a,f, nrow = 2)
</code>```

However, the output produces two different x-axises, Because the data point with the lowest value in "age" is different between the two variables. I would like both axis'es to start at 0, any tips on how to solve this?

Body:
I have attempted to create two distributions of age using the following lines of code:

library(ggplot2)
library(gridExtra)
f <- ggplot(Opportunities) +geom_density(aes(x = Age))
a <- ggplot(Transactions) +geom_density(aes(x = Age))
grid.arrange(a,f, nrow = 2)

However, the output produces two different x-axises, Because the data point with the lowest value in "age" is different between the two variables. I would like both axis'es to start at 0, any tips on how to solve this?


问:
docker build cannot find file secret file outside home directory
I'm building a docker image as follows:

```<code>TEMP_FILE="/home/username/any/directory/temp"
touch $TEMP_FILE

<secrets> > $TEMP_FILE

export DOCKER_BUILDKIT=1
pushd $PROJECT_ROOT
  docker build -t $DOCKER_IMAGE_NAME \
               --secret id=netrc,src=$TEMP_FILE \
               --build-arg=<...> \
               -f Dockerfile .
  rm $TEMP_FILE
</code>```

Currently this works.

I'd now like to use $(mktemp) to create the TEMP_FILE in the /tmp directory. However, when I point TEMP_FILE outside of /home, I get the following error:

```<code>could not parse secrets: [id=netrc,src=/tmp/temp-file-name]: failed to stat /tmp/temp-file-name: stat /tmp/temp-file-name: no such file or directory
</code>```

The script itself has no issue, I can easily find and view the temporary file for example with cat $TEMP_FILE.

How do I give docker build access to /tmp?

Body:
I'm building a docker image as follows:

TEMP_FILE="/home/username/any/directory/temp"
touch $TEMP_FILE

<secrets> > $TEMP_FILE

export DOCKER_BUILDKIT=1
pushd $PROJECT_ROOT
  docker build -t $DOCKER_IMAGE_NAME \
               --secret id=netrc,src=$TEMP_FILE \
               --build-arg=<...> \
               -f Dockerfile .
  rm $TEMP_FILE

Currently this works.

I'd now like to use $(mktemp) to create the TEMP_FILE in the /tmp directory. However, when I point TEMP_FILE outside of /home, I get the following error:

could not parse secrets: [id=netrc,src=/tmp/temp-file-name]: failed to stat /tmp/temp-file-name: stat /tmp/temp-file-name: no such file or directory

The script itself has no issue, I can easily find and view the temporary file for example with cat $TEMP_FILE.

How do I give docker build access to /tmp?


问:
The terminal in visual studio code is only 20 characters long
As I said in the title, for some reason when I run something in the terminal the result appears in 20 characters. This is how the terminal looks like.
Don't mind the text itself, I'm still learning how to use Cucumber with Javascript, but don't have a lot of luck.

I tried reinstalling VS Code, but didn't help.


问:
Connection closed before full header was received on http post in flutter
I'm trying to do a http post with the picture the user selects, when trying to make the http call, I get the error 'Connection closed before full header was received', I don't know how to fix it, the same error is happening on a real device.

This is also the documentation for the api, the body is form data.

```<code>class UploadVideoServices {
  static Future<http.StreamedResponse> postProf({
    required String imagePath,
    required String title,
    required bool isPayPerView,
    required bool isDeleted,
    required bool show,
    required List<String> tags,
    required String description,
  }) async {
    var headers = {'Authorization': 'Bearer ${prefs!.getString('token')}'};
    var request = http.MultipartRequest(
        'POST',
        Uri.parse(
            "http url/v1/postpic/634d0ebd2be78793c9474ae0/$title/$description/$show/$isPayPerView/$isDeleted/$tags"));
    request.fields.addAll({
      'file': imagePath,
    });

    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();

    return response;
  }
}

=====
using the services
=====

postProf() async {
    try {
      var result = await UploadVideoServices.postProf(
        imagePath: selectedImagePath.value,
        title: 'ajanvideo',
        isPayPerView: false,
        isDeleted: false,
        show: true,
        tags: ['ajan', 'app'],
        description: 'hey',
      );
      successSnackBar('Done', 'Posted prof');
      return result;
    } catch (e) {
      errorSnackBar('Opps', e.toString());
      print(e.toString());
    }
  }

======

void getImage(ImageSource imageSource) async {
    try {
      final pickedFile = await ImagePicker().pickImage(source: imageSource);

      if (pickedFile != null) {
        selectedImagePath.value = pickedFile.path;
      }
      print(selectedImagePath.value);
      await postProf(); // using the method after getting image
    } catch (e) {
      errorSnackBar('Opps', 'Failed to get image');
    }
  }
</code>```

Body:
I'm trying to do a http post with the picture the user selects, when trying to make the http call, I get the error 'Connection closed before full header was received', I don't know how to fix it, the same error is happening on a real device.

This is also the documentation for the api, the body is form data.

class UploadVideoServices {
  static Future<http.StreamedResponse> postProf({
    required String imagePath,
    required String title,
    required bool isPayPerView,
    required bool isDeleted,
    required bool show,
    required List<String> tags,
    required String description,
  }) async {
    var headers = {'Authorization': 'Bearer ${prefs!.getString('token')}'};
    var request = http.MultipartRequest(
        'POST',
        Uri.parse(
            "http url/v1/postpic/634d0ebd2be78793c9474ae0/$title/$description/$show/$isPayPerView/$isDeleted/$tags"));
    request.fields.addAll({
      'file': imagePath,
    });

    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();

    return response;
  }
}

=====
using the services
=====

postProf() async {
    try {
      var result = await UploadVideoServices.postProf(
        imagePath: selectedImagePath.value,
        title: 'ajanvideo',
        isPayPerView: false,
        isDeleted: false,
        show: true,
        tags: ['ajan', 'app'],
        description: 'hey',
      );
      successSnackBar('Done', 'Posted prof');
      return result;
    } catch (e) {
      errorSnackBar('Opps', e.toString());
      print(e.toString());
    }
  }

======

void getImage(ImageSource imageSource) async {
    try {
      final pickedFile = await ImagePicker().pickImage(source: imageSource);

      if (pickedFile != null) {
        selectedImagePath.value = pickedFile.path;
      }
      print(selectedImagePath.value);
      await postProf(); // using the method after getting image
    } catch (e) {
      errorSnackBar('Opps', 'Failed to get image');
    }
  }


问:
Wndow is not being created in Eclipse c++
I use the Eclipse IDE and the glfw, glew, and glm libraries. I want to create a window, but when I run the code nothing happens. Earlier, when I tried to launch it, it was written in the console "Info: Do not build anything", but now this phrase appears for a moment and disappears. And if I erase the contents of int main(), and write for example: cout << "hello world<<endl;, then the text will be output to the console, but for some reason, the code for creating the window does not work.

I tried reinstalling Eclipse, but nothing changes. I am new to programming in Eclipse, I had to spend about 10 hours fixing other errors that did not even allow me to run the code.

```<code>#include <iostream>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

using namespace std;

int WIDTH = 1280;
int HEIGHT = 720;

int main() {
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Window", nullptr, nullptr);
    if(window == nullptr) {
        cerr << "Failed to create GLFW Window" << endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    if(glewInit() != GLEW_OK) {
        cerr << "Failed to initialize GLEW" << endl;
        return -1;
    }

    glViewport(0,0, WIDTH, HEIGHT);

    while(!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    return 0;
}
</code>```

Body:
I use the Eclipse IDE and the glfw, glew, and glm libraries. I want to create a window, but when I run the code nothing happens. Earlier, when I tried to launch it, it was written in the console "Info: Do not build anything", but now this phrase appears for a moment and disappears. And if I erase the contents of int main(), and write for example: cout << "hello world<<endl;, then the text will be output to the console, but for some reason, the code for creating the window does not work.

I tried reinstalling Eclipse, but nothing changes. I am new to programming in Eclipse, I had to spend about 10 hours fixing other errors that did not even allow me to run the code.

#include <iostream>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

using namespace std;

int WIDTH = 1280;
int HEIGHT = 720;

int main() {
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Window", nullptr, nullptr);
    if(window == nullptr) {
        cerr << "Failed to create GLFW Window" << endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    if(glewInit() != GLEW_OK) {
        cerr << "Failed to initialize GLEW" << endl;
        return -1;
    }

    glViewport(0,0, WIDTH, HEIGHT);

    while(!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    return 0;
}


问:
Android Developement: Trying to Understand Nested Classes in RecyclerView Implementation
Trying to understand recycler view adapter implementation as described in the android developers website (link: Android Dev Website)

Implementation of the custom adapter continues to puzzle me, per the following screenshot and code.

```<code>class CustomAdapter(private val dataSet: Array<String>) :
        RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder)
     */
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val textView: TextView

        init {
            // Define click listener for the ViewHolder's View
            textView = view.findViewById(R.id.textView)
        }
    }

...

}
</code>```

I understand that when implementing a CustomAdapter, we created a nested class, ViewHolder, that is to be exclusively used by the CustomAdapter.

If I understand correctly, the CustomAdapter extends the RecyclerView.Adapter of type RecyclerView.ViewHolder, which in the example above, is the ViewHolder that we've defined in the nested class.

How can we provide the "ViewHolder" in the CustomAdapter constructor if it's defined "after" "inside" the CustomAdapter class?

I think there is a gap in my understanding regarding the order in which things compile. Does a nested class, ViewHolder, compile first before the "outer" class, CustomAdapter, allowing it to be passed in the constructor?

Any help would be appreciated!

The Android Developers website is not clear to me on how this works. I want to understand why this is vs simply memorizing the implementation.

Body:
Trying to understand recycler view adapter implementation as described in the android developers website (link: Android Dev Website)

Implementation of the custom adapter continues to puzzle me, per the following screenshot and code.

class CustomAdapter(private val dataSet: Array<String>) :
        RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder)
     */
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val textView: TextView

        init {
            // Define click listener for the ViewHolder's View
            textView = view.findViewById(R.id.textView)
        }
    }

...

}

I understand that when implementing a CustomAdapter, we created a nested class, ViewHolder, that is to be exclusively used by the CustomAdapter.

If I understand correctly, the CustomAdapter extends the RecyclerView.Adapter of type RecyclerView.ViewHolder, which in the example above, is the ViewHolder that we've defined in the nested class.

How can we provide the "ViewHolder" in the CustomAdapter constructor if it's defined "after" "inside" the CustomAdapter class?

I think there is a gap in my understanding regarding the order in which things compile. Does a nested class, ViewHolder, compile first before the "outer" class, CustomAdapter, allowing it to be passed in the constructor?

Any help would be appreciated!

The Android Developers website is not clear to me on how this works. I want to understand why this is vs simply memorizing the implementation.


问:
how to use uwb devices in xamarin native
Im working on an xamarin native app, where we now want to make use of ultra wideband devices.
I have some trouble finding good resources and tutorials on that.

What is the best approach here? Can you provide any good knowledge, links, tutorials on this?

This is what I have found, but its very limited:

https://aniltaskiran.medium.com/nearby-interaction-ios-14-wwdc20-e4ad9bcb3826

https://github.com/android/connectivity-samples/tree/main/UwbRanging

Would be really helpful with more info.


问:
calculate if hour it´s in labor time
I´m trying to create script to compare any ours from json and function difference hours to extract if actual time it´s minor that hour in json or higher that time json. to do this i´m buildg a function with DateTime() php and pass to this function two arguments:

```<code>$diferencia = $this->diferenciaFechas($hora_actual, $value["hora_inicio"]);

function diferenciaFechas($horaInicio, $horaFin) {
    $hora_inicio = new Datetime($horaInicio);
    $hora_fin = new Datetime($horaFin);

    $tiempo = $hora_inicio->diff($hora_fin);

    return $tiempo;
}
</code>```

and i´m checking my results with:

```<code>if($provincia == $value["localidad"] && $diferencia->h < 0 || $provincia == $value["localidad"] && $diferencia->h > 0){
    $fuera_horario = true;
    $rama = "fuera horario";
}else{
    echo $value["localidad"];
    echo $value["hora_inicio"] . "<br>";
}
</code>```

always my script go to else block:

this: $value["localidad"] its value from my foreach:

```<code>foreach ($festivos as $value) {

    if($viernes == "Friday"){
        if($hora_actual < $value["hora_inicio_viernes"] || $hora_actual >= $value["hora_fin_viernes"]){
            $fuera_horario = true;
        }
    }else{
        $diferencia = $this->diferenciaFechas($hora_actual, $value["hora_inicio"]);

        //echo $diferencia->h;

        if($provincia == $value["localidad"] && $diferencia->h < 0 || $provincia == $value["localidad"] && $diferencia->h > 0){
            $fuera_horario = true;
            $rama = "fuera horario";
        }else{
            echo $value["localidad"];
            echo $value["hora_inicio"] . "<br>";
        }
    }
}
</code>```

and $festivos it´s json_decode() from file_get_contents('include/festivos.json');

any data from to this json its:

```<code>{
    "cp": "17",
    "localidad": "Gerona",
    "fecha": "2022-12-26",
    "hora_inicio": "09:00:00",
    "hora_fin": "14:00:00",
    "hora_inicio_viernes": "09:00:00",
    "hora_fin_viernes": "14:00:00"
},
{
    "cp": "18",
    "localidad": "Granada",
    "fecha": "2022-12-15",
    "hora_inicio": "12:01:00",
    "hora_fin": "12:00:00",
    "hora_inicio_viernes": "09:00:00",
    "hora_fin_viernes": "14:00:00"
},
{
    "cp": "18",
    "localidad": "Granada",
    "fecha": "2023-01-01",
    "hora_inicio": "09:00:00",
    "hora_fin": "14:00:00",
    "hora_inicio_viernes": "09:00:00",
    "hora_fin_viernes": "14:00:00"
},
{
    "cp": "19",
    "localidad": "Guadalajara",
    "fecha": "2022-12-26",
    "hora_inicio": "09:00:00",
    "hora_fin": "14:00:00",
    "hora_inicio_viernes": "09:00:00",
    "hora_fin_viernes": "14:00:00"
},
</code>```

i need get if $hora_inicio from my json it´s minor or bigger than actual time to know if i´m in labor time or not.

I´m sorry for my bad english.

Thanks for help me

Title: calculate if hour it´s in labor time

Body:
I´m trying to create script to compare any ours from json and function difference hours to extract if actual time it´s minor that hour in json or higher that time json. to do this i´m buildg a function with DateTime() php and pass to this function two arguments:

$diferencia = $this->diferenciaFechas($hora_actual, $value["hora_inicio"]);

function diferenciaFechas($horaInicio, $horaFin) {
    $hora_inicio = new Datetime($horaInicio);
    $hora_fin = new Datetime($horaFin);

    $tiempo = $hora_inicio->diff($hora_fin);

    return $tiempo;
}

and i´m checking my results with:

if($provincia == $value["localidad"] && $diferencia->h < 0 || $provincia == $value["localidad"] && $diferencia->h > 0){
    $fuera_horario = true;
    $rama = "fuera horario";
}else{
    echo $value["localidad"];
    echo $value["hora_inicio"] . "
";
}

always my script go to else block:

this: $value["localidad"] its value from my foreach:

foreach ($festivos as $value) {

    if($viernes == "Friday"){
        if($hora_actual < $value["hora_inicio_viernes"] || $hora_actual >= $value["hora_fin_viernes"]){
            $fuera_horario = true;
        }
    }else{
        $diferencia = $this->diferenciaFechas($hora_actual, $value["hora_inicio"]);

        //echo $diferencia->h;

        if($provincia == $value["localidad"] && $diferencia->h < 0 || $provincia == $value["localidad"] && $diferencia->h > 0){
            $fuera_horario = true;
            $rama = "fuera horario";
        }else{
            echo $value["localidad"];
            echo $value["hora_inicio"] . "
";
        }
    }
}

and $festivos it´s json_decode() from file_get_contents('include/festivos.json');

any data from to this json its:

{
    "cp": "17",
    "localidad": "Gerona",
    "fecha": "2022-12-26",
    "hora_inicio": "09:00:00",
    "hora_fin": "14:00:00",
    "hora_inicio_viernes": "09:00:00",
    "hora_fin_viernes": "14:00:00"
},
{
    "cp": "18",
    "localidad": "Granada",
    "fecha": "2022-12-15",
    "hora_inicio": "12:01:00",
    "hora_fin": "12:00:00",
    "hora_inicio_viernes": "09:00:00",
    "hora_fin_viernes": "14:00:00"
},
{
    "cp": "18",
    "localidad": "Granada",
    "fecha": "2023-01-01",
    "hora_inicio": "09:00:00",
    "hora_fin": "14:00:00",
    "hora_inicio_viernes": "09:00:00",
    "hora_fin_viernes": "14:00:00"
},
{
    "cp": "19",
    "localidad": "Guadalajara",
    "fecha": "2022-12-26",
    "hora_inicio": "09:00:00",
    "hora_fin": "14:00:00",
    "hora_inicio_viernes": "09:00:00",
    "hora_fin_viernes": "14:00:00"
},

i need get if $hora_inicio from my json it´s minor or bigger than actual time to know if i´m in labor time or not.

I´m sorry for my bad english.

Thanks for help me


问:
is there a way to count the number of files in a folder via google sheet?
I'm doing a log for files at work and I need a formula or a way to "get" the amount of files in a folder (that i've on pc not in gdrive).
es: in A1 I want the number of files in the *XXXXX *folder on the pc...I hope I was clear.
thank you

number file on folder ->  i've ...    A1  .pdf file in my folder


问:
Set the audio on a variable
How can I access to the audio of the pc and set it to a variable in C++ or python? I'd like to do a wallpaper that changes with the music (like in wallpaper engine but on my own).

I searched in many websites but I didn't find anything useful

Title: Set the audio on a variable


问:
How to move rect in pygame through the for loop?
I'm trying to create my rect through the for loop in each cell position in my path array, but the rect appears only in last cell position. Could somebody explain me why it's happens and how to sort it out? I've tryed to use pygame.time.delay, pygame.time.wait and clock with events as well but it doesent help.

So, I'm getting mouse position and if click on ground cell I've getting cell that pressed on, then I'm creating path from current player position to choosen cell. And, I want to show, how player actually moving to target position. I've decide to make it like creating new rect on next in path array cell and rect disappear from previous one, and do it till the end of array.

Here's the function that create new rect and "delete" previous one:

```<code>def draw_path(self, path):
    for index, i in enumerate(path):
        print(i)
        self.create_rect(colors['dark_red'], colors['red'], i[0] * TILE_SIZE, i[1] * TILE_SIZE, TILE_SIZE,TILE_SIZE)
        if index != 0:
            self.create_rect(colors['black'], colors['dark_gray'], path[index-1][0] * TILE_SIZE, path[index-1][1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
        self.player.position = (i[0], i[1])
</code>```

Here's I'm calling the function:

```<code>if event.type == pygame.MOUSEBUTTONUP:
    for cell in self.groundcells:
        if cell.collidepoint(pygame.mouse.get_pos()):
            current_path = self.pathfinder.make_path(self.player.position, (int(cell[0] / TILE_SIZE), int(cell[1] / TILE_SIZE)), self.map)
            self.player.path = current_path
            self.draw_path(self.player.path)
</code>```

Here's the whole code (if neccesary):

```<code>import sys, pygame
from settings import *
from maps import testing_map
from pathfindinder import Pathfind
from character import Character

class Game:
    def __init__(self):
        pygame.init()
        self.map = testing_map.test_map
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption(GAME_NAME + ' ' + CURR_VER)
        self.clock = pygame.time.Clock()
        self.pathfinder = Pathfind()
        self.groundcells = []
        self.start_pos = (2, 1)
        self.player = Character(self.start_pos)
        self.player.position = self.start_pos

    def create_rect(self, border_color, fill_color, x_pos, y_pos, size_x, size_y, cells_list=[]):
        rect = pygame.draw.rect(self.screen, fill_color, (x_pos, y_pos, size_x, size_y))
        pygame.draw.rect(self.screen, border_color, (x_pos, y_pos, size_x - 1, size_y - 1))
        cells_list.append(rect)
        return pygame.rect.Rect(rect)

    def generate_map(self):
        for row_i, row in enumerate(self.map):
            for cell_i, cell in enumerate(row):
                if cell == 0:
                    self.create_rect(colors['blue'], colors['navy_blue'], cell_i * TILE_SIZE, row_i * TILE_SIZE, TILE_SIZE, TILE_SIZE)
                if cell == 1:
                    self.create_rect(colors['black'], colors['dark_gray'], cell_i * TILE_SIZE, row_i * TILE_SIZE, TILE_SIZE, TILE_SIZE, self.groundcells)

    def draw_path(self, path):
        for index, i in enumerate(path):
            print(i)
            self.create_rect(colors['dark_red'], colors['red'], i[0] * TILE_SIZE, i[1] * TILE_SIZE, TILE_SIZE,TILE_SIZE)
            if index != 0:
                self.create_rect(colors['black'], colors['dark_gray'], path[index-1][0] * TILE_SIZE, path[index-1][1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
            self.player.position = (i[0], i[1])

    def run(self):
        self.generate_map()

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.QUIT
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONUP:
                    for cell in self.groundcells:
                        if cell.collidepoint(pygame.mouse.get_pos()):
                            current_path = self.pathfinder.make_path(self.player.position, (int(cell[0] / TILE_SIZE), int(cell[1] / TILE_SIZE)), self.map)
                            self.player.path = current_path
                            self.draw_path(self.player.path)
            self.player.draw(self.screen)
            pygame.display.update()
            self.clock.tick(FPS)

if __name__ == '__main__':
    game = Game()
    game.run()
</code>```

Body:
I'm trying to create my rect through the for loop in each cell position in my path array, but the rect appears only in last cell position. Could somebody explain me why it's happens and how to sort it out? I've tryed to use pygame.time.delay, pygame.time.wait and clock with events as well but it doesent help.

So, I'm getting mouse position and if click on ground cell I've getting cell that pressed on, then I'm creating path from current player position to choosen cell. And, I want to show, how player actually moving to target position. I've decide to make it like creating new rect on next in path array cell and rect disappear from previous one, and do it till the end of array.

Here's the function that create new rect and "delete" previous one:

def draw_path(self, path):
    for index, i in enumerate(path):
        print(i)
        self.create_rect(colors['dark_red'], colors['red'], i[0] * TILE_SIZE, i[1] * TILE_SIZE, TILE_SIZE,TILE_SIZE)
        if index != 0:
            self.create_rect(colors['black'], colors['dark_gray'], path[index-1][0] * TILE_SIZE, path[index-1][1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
        self.player.position = (i[0], i[1])

Here's I'm calling the function:

if event.type == pygame.MOUSEBUTTONUP:
    for cell in self.groundcells:
        if cell.collidepoint(pygame.mouse.get_pos()):
            current_path = self.pathfinder.make_path(self.player.position, (int(cell[0] / TILE_SIZE), int(cell[1] / TILE_SIZE)), self.map)
            self.player.path = current_path
            self.draw_path(self.player.path)

Here's the whole code (if neccesary):

import sys, pygame
from settings import *
from maps import testing_map
from pathfindinder import Pathfind
from character import Character

class Game:
    def __init__(self):
        pygame.init()
        self.map = testing_map.test_map
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption(GAME_NAME + ' ' + CURR_VER)
        self.clock = pygame.time.Clock()
        self.pathfinder = Pathfind()
        self.groundcells = []
        self.start_pos = (2, 1)
        self.player = Character(self.start_pos)
        self.player.position = self.start_pos

    def create_rect(self, border_color, fill_color, x_pos, y_pos, size_x, size_y, cells_list=[]):
        rect = pygame.draw.rect(self.screen, fill_color, (x_pos, y_pos, size_x, size_y))
        pygame.draw.rect(self.screen, border_color, (x_pos, y_pos, size_x - 1, size_y - 1))
        cells_list.append(rect)
        return pygame.rect.Rect(rect)

    def generate_map(self):
        for row_i, row in enumerate(self.map):
            for cell_i, cell in enumerate(row):
                if cell == 0:
                    self.create_rect(colors['blue'], colors['navy_blue'], cell_i * TILE_SIZE, row_i * TILE_SIZE, TILE_SIZE, TILE_SIZE)
                if cell == 1:
                    self.create_rect(colors['black'], colors['dark_gray'], cell_i * TILE_SIZE, row_i * TILE_SIZE, TILE_SIZE, TILE_SIZE, self.groundcells)

    def draw_path(self, path):
        for index, i in enumerate(path):
            print(i)
            self.create_rect(colors['dark_red'], colors['red'], i[0] * TILE_SIZE, i[1] * TILE_SIZE, TILE_SIZE,TILE_SIZE)
            if index != 0:
                self.create_rect(colors['black'], colors['dark_gray'], path[index-1][0] * TILE_SIZE, path[index-1][1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
            self.player.position = (i[0], i[1])

    def run(self):
        self.generate_map()

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.QUIT
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONUP:
                    for cell in self.groundcells:
                        if cell.collidepoint(pygame.mouse.get_pos()):
                            current_path = self.pathfinder.make_path(self.player.position, (int(cell[0] / TILE_SIZE), int(cell[1] / TILE_SIZE)), self.map)
                            self.player.path = current_path
                            self.draw_path(self.player.path)
            self.player.draw(self.screen)
            pygame.display.update()
            self.clock.tick(FPS)

if __name__ == '__main__':
    game = Game()
    game.run()


问:
why is 'dependency:copy-dependencies' executed unexpectedly during tycho build?
I want to add JARs to a plugin. Previously, I added them by hand but thought it would be a good idea to add them via dependency definitions.

I created a pom.xml in the bundle and added an execution:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>3.4.0</version>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>process-sources</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.basedir}/lib</outputDirectory>
                <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

As soon as I save the file the dependency JARs are all copied to the lib folder. So far so good...

When I start a tycho build, such as mvn install, the build succeeds but the lib folder now contains a new folder lib/myplugin-1.0.0.qualifier-lib and this folder contains copies of all the JARs in lib but they all have the extension .jar.jar.

If I remove the copy-dependencies execution before starting the tycho build then this folder is not created.

Can anyone explain why this is happening and what I should do to avoid this behaviour?

Body:
I want to add JARs to a plugin. Previously, I added them by hand but thought it would be a good idea to add them via dependency definitions.

I created a pom.xml in the bundle and added an execution:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>3.4.0</version>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>process-sources</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.basedir}/lib</outputDirectory>
                <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
        </execution>
    </executions>
</plugin>

As soon as I save the file the dependency JARs are all copied to the lib folder. So far so good...

When I start a tycho build, such as mvn install, the build succeeds but the lib folder now contains a new folder lib/myplugin-1.0.0.qualifier-lib and this folder contains copies of all the JARs in lib but they all have the extension .jar.jar.

If I remove the copy-dependencies execution before starting the tycho build then this folder is not created.

Can anyone explain why this is happening and what I should do to avoid this behaviour?


问:
Calculate percentages with 2 fields in the GROUP BY clause - SQL
I have the following results that list different departments within different offices. Each departments hours and cost has been calculated for each office.

```<code>OfficeCode    Department     Total Hours     Total Costs
---------------------------------------------------------
OFC-UK        Buying         44              50850
OFC-UK        Design         42              30008
OFC-UK        R&D            28              70600
OFC-AZ        Buying         52              30801
OFC-AZ        Design         34              50080
OFC-BG        Buying         25              40030
OFC-BG        Design         37              10020
</code>```

The above results come from the following query:

```<code>SELECT office.office_code,
       department.department_description,
       CAST(SUM(timesheet_entry.timesheet_entry_hour) + (SUM(timesheet_entry.timesheet_entry_minute)/60) as float) as total_hours,
       SUM((timesheet_entry.timesheet_entry_hour + ((timesheet_entry.timesheet_entry_minute)/60)) * person.person_rate) as 'total_cost'
       FROM timesheet_entry

INNER JOIN user
        ON user.user_obj = timesheet_entry.user_obj
INNER JOIN person
    ON person.person_obj = user.person_obj
INNER JOIN department
        ON department.department_obj = user.department_id
INNER JOIN office
        ON office.office_id = timesheet_entry.office_id

GROUP BY timesheet_entry.office_code, department.department_description
ORDER BY office.office_code, department.department_description;
</code>```

I need to calculate the percentages of the total_hours and total_cost fields, per department, per office. Such as an example of the desired results:

```<code>OfficeCode    Department     Total Hours     HoursPercentage     Total Costs     CostPercentage
-----------------------------------------------------------------------------------------------
OFC-UK        Buying         44              38.59               50850           33.57
OFC-UK        Design         42              36.84               30008           19.81
OFC-UK        R&D            28              24.56               70600           46.61
OFC-AZ        Buying         52              etc                 etc             etc
OFC-AZ        Design         34              etc                 etc             etc
OFC-BG        Buying         25              etc                 etc             etc
OFC-BG        Design         37              etc                 etc             etc
</code>```

I tried to put the results into a temp-table, and then calculate the percentages ontop of that with the GROUP BY, but it seems it doesnt take the groups into consideration. Is there a better, and accurate, way to do this?

```<code>CREATE TEMPORARY TABLE OfficeDepartmentTotalsTbl

SELECT office.office_code,
       department.department_description,
       CAST(SUM(timesheet_entry.timesheet_entry_hour) + (SUM(timesheet_entry.timesheet_entry_minute)/60) as float) as total_hours,
       SUM((timesheet_entry.timesheet_entry_hour + ((timesheet_entry.timesheet_entry_minute)/60)) * person.person_rate) as 'total_cost'
       FROM timesheet_entry

INNER JOIN user
        ON user.user_obj = timesheet_entry.user_obj
INNER JOIN person
    ON person.person_obj = user.person_obj
INNER JOIN department
        ON department.department_obj = user.department_id
INNER JOIN office
        ON office.office_id = timesheet_entry.office_id

GROUP BY timesheet_entry.office_code, department.department_description
ORDER BY office.office_code, department.department_description;

SELECT
    OfficeDepartmentTotalsTbl.office_code,
    OfficeDepartmentTotalsTbl.department_description,
    OfficeDepartmentTotalsTbl.total_hours,
    OfficeDepartmentTotalsTbl.total_hours * 100 /
        (SELECT SUM(OfficeDepartmentTotalsTbl.total_hours) FROM OfficeDepartmentTotalsTbl) AS 'department_percentage_of_total_hours',
    OfficeDepartmentTotalsTbl.total_cost,
    OfficeDepartmentTotalsTbl.total_cost * 100 / (SELECT
            SUM(OfficeDepartmentTotalsTbl.total_cost)
        FROM
            OfficeDepartmentTotalsTbl) AS 'department_percentage_of_total_cost'
FROM
    OfficeDepartmentTotalsTbl
GROUP BY OfficeDepartmentTotalsTbl.office_code, OfficeDepartmentTotalsTbl.department_description;

DROP TEMPORARY TABLE OfficeDepartmentTotalsTbl;
</code>```

Body:
I have the following results that list different departments within different offices. Each departments hours and cost has been calculated for each office.

OfficeCode    Department     Total Hours     Total Costs
---------------------------------------------------------
OFC-UK        Buying         44              50850
OFC-UK        Design         42              30008
OFC-UK        R&D            28              70600
OFC-AZ        Buying         52              30801
OFC-AZ        Design         34              50080
OFC-BG        Buying         25              40030
OFC-BG        Design         37              10020

The above results come from the following query:

SELECT office.office_code,
       department.department_description,
       CAST(SUM(timesheet_entry.timesheet_entry_hour) + (SUM(timesheet_entry.timesheet_entry_minute)/60) as float) as total_hours,
       SUM((timesheet_entry.timesheet_entry_hour + ((timesheet_entry.timesheet_entry_minute)/60)) * person.person_rate) as 'total_cost'
       FROM timesheet_entry

INNER JOIN user
        ON user.user_obj = timesheet_entry.user_obj
INNER JOIN person
    ON person.person_obj = user.person_obj
INNER JOIN department
        ON department.department_obj = user.department_id
INNER JOIN office
        ON office.office_id = timesheet_entry.office_id

GROUP BY timesheet_entry.office_code, department.department_description
ORDER BY office.office_code, department.department_description;

I need to calculate the percentages of the total_hours and total_cost fields, per department, per office. Such as an example of the desired results:

OfficeCode    Department     Total Hours     HoursPercentage     Total Costs     CostPercentage
-----------------------------------------------------------------------------------------------
OFC-UK        Buying         44              38.59               50850           33.57
OFC-UK        Design         42              36.84               30008           19.81
OFC-UK        R&D            28              24.56               70600           46.61
OFC-AZ        Buying         52              etc                 etc             etc
OFC-AZ        Design         34              etc                 etc             etc
OFC-BG        Buying         25              etc                 etc             etc
OFC-BG        Design         37              etc                 etc             etc

I tried to put the results into a temp-table, and then calculate the percentages ontop of that with the GROUP BY, but it seems it doesnt take the groups into consideration. Is there a better, and accurate, way to do this?

CREATE TEMPORARY TABLE OfficeDepartmentTotalsTbl

SELECT office.office_code,
       department.department_description,
       CAST(SUM(timesheet_entry.timesheet_entry_hour) + (SUM(timesheet_entry.timesheet_entry_minute)/60) as float) as total_hours,
       SUM((timesheet_entry.timesheet_entry_hour + ((timesheet_entry.timesheet_entry_minute)/60)) * person.person_rate) as 'total_cost'
       FROM timesheet_entry

INNER JOIN user
        ON user.user_obj = timesheet_entry.user_obj
INNER JOIN person
    ON person.person_obj = user.person_obj
INNER JOIN department
        ON department.department_obj = user.department_id
INNER JOIN office
        ON office.office_id = timesheet_entry.office_id

GROUP BY timesheet_entry.office_code, department.department_description
ORDER BY office.office_code, department.department_description;

SELECT
    OfficeDepartmentTotalsTbl.office_code,
    OfficeDepartmentTotalsTbl.department_description,
    OfficeDepartmentTotalsTbl.total_hours,
    OfficeDepartmentTotalsTbl.total_hours * 100 /
        (SELECT SUM(OfficeDepartmentTotalsTbl.total_hours) FROM OfficeDepartmentTotalsTbl) AS 'department_percentage_of_total_hours',
    OfficeDepartmentTotalsTbl.total_cost,
    OfficeDepartmentTotalsTbl.total_cost * 100 / (SELECT
            SUM(OfficeDepartmentTotalsTbl.total_cost)
        FROM
            OfficeDepartmentTotalsTbl) AS 'department_percentage_of_total_cost'
FROM
    OfficeDepartmentTotalsTbl
GROUP BY OfficeDepartmentTotalsTbl.office_code, OfficeDepartmentTotalsTbl.department_description;

DROP TEMPORARY TABLE OfficeDepartmentTotalsTbl;


问:
How to get IDs of selected options when using bootsrap-select and multiple?
I'm using bootsrap-select.

I have 3 dropdowns. I need to filter the options (hide them) of descendant dropdowns based on the selected options in the parent dropdown.

For that I added IDs and classes to each option. So the class represent the ID of the parent option.

Example of parent-child relationship (only 2 dropdowns for the example):

```<code><select id="parent">
    <option id="parent_id_1"></option>
</select>

<select id="child_1">
    <option id="child_id_1" class="parent_id_1"></option>
    <option id="child_id_2" class="parent_id_1"></option>
</select>
</code>```

I need to get the IDs of the selected options, and then iterate each of them to hide any option that does not have their class that corresponds to their IDs.

But bootsrap-select wraps everything in other elements so I just couldn't find a way to do it

Body:
I'm using bootsrap-select.

I have 3 dropdowns. I need to filter the options (hide them) of descendant dropdowns based on the selected options in the parent dropdown.

For that I added IDs and classes to each option. So the class represent the ID of the parent option.

Example of parent-child relationship (only 2 dropdowns for the example):

<select id="parent">
    <option id="parent_id_1"></option>
</select>

<select id="child_1">
    <option id="child_id_1" class="parent_id_1"></option>
    <option id="child_id_2" class="parent_id_1"></option>
</select>

I need to get the IDs of the selected options, and then iterate each of them to hide any option that does not have their class that corresponds to their IDs.

But bootsrap-select wraps everything in other elements so I just couldn't find a way to do it


问:
How can I change Kivymd DataTable icon height?
My code is there, I want to define a constant table icon size ("alert", [255 / 256, 165 / 256, 0, 1], "[size=12]No Signal"). I can arrange only text size with brackets in front of any text but, for icon size could not find anything.

```<code>  class Example(MDApp):
       def build(self):
        return Builder.load_string(kv)

    def on_start(self):
        data_tables = MDDataTable(
            size_hint=(None, None),
            size=(200,400),
            pos=(10, 20),
            column_data=[
                ("Column 1", dp(20)),
                ("Column 2", dp(30)),
                ("Column 3", dp(50), self.sort_on_col_3),
                ("Column 4", dp(30)),
                ("Column 5", dp(30)),
                ("Column 6", dp(30)),
                ("Column 7", dp(30), self.sort_on_col_2),
            ],
            row_data=[
                # The number of elements must match the length
                # of the `column_data` list.
                (
                    "1",
                    ("alert", [255 / 256, 165 / 256, 0, 1], "[size=24]No Signal"),
                    "Astrid: NE shared managed",
                    "Medium",
                    "Triaged",
                    "0:33",
                    "Chase Nguyen",
                )

            ],
        )
        self.root.add_widget(data_tables)

   Example().run()
</code>```

Body:
My code is there, I want to define a constant table icon size ("alert", [255 / 256, 165 / 256, 0, 1], "[size=12]No Signal"). I can arrange only text size with brackets in front of any text but, for icon size could not find anything.

  class Example(MDApp):
       def build(self):
        return Builder.load_string(kv)

    def on_start(self):
        data_tables = MDDataTable(
            size_hint=(None, None),
            size=(200,400),
            pos=(10, 20),
            column_data=[
                ("Column 1", dp(20)),
                ("Column 2", dp(30)),
                ("Column 3", dp(50), self.sort_on_col_3),
                ("Column 4", dp(30)),
                ("Column 5", dp(30)),
                ("Column 6", dp(30)),
                ("Column 7", dp(30), self.sort_on_col_2),
            ],
            row_data=[
                # The number of elements must match the length
                # of the `column_data` list.
                (
                    "1",
                    ("alert", [255 / 256, 165 / 256, 0, 1], "[size=24]No Signal"),
                    "Astrid: NE shared managed",
                    "Medium",
                    "Triaged",
                    "0:33",
                    "Chase Nguyen",
                )

            ],
        )
        self.root.add_widget(data_tables)

   Example().run()


问:
Why does it not execute my func using apply_async? - multiprocessing python
```<code>
from multiprocessing import Pool

def function1(var1, var2):

    print("function1 executing")
    var3 = var1 + var2

    return var3

if __name__ == "__main__":

    pool = Pool()

    pool.apply_async(function1, args=(7, 5))

    pool.close()
    pool.join()
</code>```

When I run this I don't get anything in the console. It shows:

In [1]:

In [2]:

I tryed it with several different functions but I don't get anything printed in the console. Sorry for the nooby question :DD

Body:
from multiprocessing import Pool

def function1(var1, var2):

    print("function1 executing")
    var3 = var1 + var2

    return var3

if __name__ == "__main__":

    pool = Pool()

    pool.apply_async(function1, args=(7, 5))

    pool.close()
    pool.join()

When I run this I don't get anything in the console. It shows:

In [1]:

In [2]:

I tryed it with several different functions but I don't get anything printed in the console. Sorry for the nooby question :DD


问:
EXCEL: Remove blanks from Dropdown List & make Dropdown List inactive if no options are returned?
I use a Unique Filter formula to obtain a list. I do not want any blanks in my Dropdown List at all.

Problem,
1: How can I remove the blanks?
2: If the list returns no options can I make the Dropdown List inactive?
3: How can I have the first or all dropdown list options displayed in the cell, before clicking on it with a mouse?

I tried selecting REMOVE BLANKS in Data Validation but the blanks still show up.

IMAGE[1]: https://i.stack.imgur.com/8JbGQ.png


问:
React.version stating older version than is in package.json
I am attempting to use the React devtools to produce a flamegraph profile of my app, but I was greeted with the message:

After checking my package.json version number, I saw it was set to "^16.4.1".

I performed an update to both the React and React-Dom versions: npm i --save react@16.5 && npm i --save react-dom@16.5, which updated both versions in the package json to "^16.5.2". I also cleared my node_modules and deleted the package.lock before doing an npm install once again.

However, when I run both my local instance of the app and push changes to my staging environment, it is outputting 16.14.0 as the version number that I have specified to log out in at the start of the App.jsx...

This is puzzling also as the logged out a version earlier than my package.json originally stated...

Is there somewhere that I am missing to update versions that could be causing this?

I have done a global search in my project for 16.14 to see if there is anything and it seems that some of my dependencies have mentioned this version, but I wouldn't think that it would be an issue?

```<code>package.lock
------------
"dependencies": {
    ...
    "react": {
      "version": "16.14.0",
      ...
    },
    ...
    "react-dom": {
      "version": "16.14.0",
      ...
    },
    ...
}
</code>```

I don't understand what is going wrong here?

Body:
I am attempting to use the React devtools to produce a flamegraph profile of my app, but I was greeted with the message:

After checking my package.json version number, I saw it was set to "^16.4.1".

I performed an update to both the React and React-Dom versions: npm i --save react@16.5 && npm i --save react-dom@16.5, which updated both versions in the package json to "^16.5.2". I also cleared my node_modules and deleted the package.lock before doing an npm install once again.

However, when I run both my local instance of the app and push changes to my staging environment, it is outputting 16.14.0 as the version number that I have specified to log out in at the start of the App.jsx...

This is puzzling also as the logged out a version earlier than my package.json originally stated...

Is there somewhere that I am missing to update versions that could be causing this?

I have done a global search in my project for 16.14 to see if there is anything and it seems that some of my dependencies have mentioned this version, but I wouldn't think that it would be an issue?

package.lock
------------
"dependencies": {
    ...
    "react": {
      "version": "16.14.0",
      ...
    },
    ...
    "react-dom": {
      "version": "16.14.0",
      ...
    },
    ...
}

I don't understand what is going wrong here?


问:
/usr/bin/python3.8: can't open file 'app.py': [Errno 13] Permission denied
I am creating an app with Python which I am going to execute it in gramine when I run the command gramine-sgx ./python app.py I get error: /usr/bin/python3.8: can't open file 'app.py': [Errno 13] Permission denied
and my python.manifest.template is:

```<code>loader.entrypoint = "file:{{ gramine.libos }}"
libos.entrypoint = "{{ entrypoint }}"

loader.log_level = "{{ log_level }}"

loader.env.LD_LIBRARY_PATH = "{{ python.stdlib }}/lib:/lib:{{ arch_libdir }}:/usr/lib:/usr/{{ arch_libdir }}"

loader.insecure__use_cmdline_argv = true

sys.enable_sigterm_injection = true

fs.mounts = [
  { path = "/lib", uri = "file:{{ gramine.runtimedir() }}" },
  { path = "{{ arch_libdir }}", uri = "file:{{ arch_libdir }}" },
  { path = "/usr", uri = "file:/usr" },
  { path = "{{ python.stdlib }}", uri = "file:{{ python.stdlib }}" },
  { path = "{{ python.distlib }}", uri = "file:{{ python.distlib }}" },
  { path = "/etc", uri = "file:/etc" },

  { type = "tmpfs", path = "/tmp" },
]

sys.stack.size = "2M"
sys.enable_extra_runtime_domain_names_conf = true

sgx.debug = true
sgx.nonpie_binary = true
sgx.enclave_size = "512M"
sgx.thread_num = 32

sgx.remote_attestation = "{{ ra_type }}"
sgx.ra_client_spid = "{{ ra_client_spid }}"
sgx.ra_client_linkable = {{ 'true' if ra_client_linkable == '1' else 'false' }}

sgx.trusted_files = [
  "file:{{ gramine.libos }}",
  "file:{{ entrypoint }}",
  "file:{{ gramine.runtimedir() }}/",
  "file:{{ arch_libdir }}/",
  "file:/usr/{{ arch_libdir }}/",
  "file:{{ python.stdlib }}/",
  "file:{{ python.distlib }}/",
  "file:app.py",
  "file:/etc/mime.types",
  "file:/etc/default/apport",
]

sgx.allowed_files = [
  "file:/etc/nsswitch.conf",
  "file:/etc/ethers",
  "file:/etc/hosts",
  "file:/etc/group",
  "file:/etc/passwd",
  "file:/etc/gai.conf",
  "file:/etc/host.conf",
]
</code>```

I have no idea why this error occurs. I have installed Python on my system, besides, I can run samples of gramine which are written in Python using make SGX=1 for building them.

Body:
I am creating an app with Python which I am going to execute it in gramine when I run the command gramine-sgx ./python app.py I get error: /usr/bin/python3.8: can't open file 'app.py': [Errno 13] Permission denied
and my python.manifest.template is:

loader.entrypoint = "file:{{ gramine.libos }}"
libos.entrypoint = "{{ entrypoint }}"

loader.log_level = "{{ log_level }}"

loader.env.LD_LIBRARY_PATH = "{{ python.stdlib }}/lib:/lib:{{ arch_libdir }}:/usr/lib:/usr/{{ arch_libdir }}"

loader.insecure__use_cmdline_argv = true

sys.enable_sigterm_injection = true

fs.mounts = [
  { path = "/lib", uri = "file:{{ gramine.runtimedir() }}" },
  { path = "{{ arch_libdir }}", uri = "file:{{ arch_libdir }}" },
  { path = "/usr", uri = "file:/usr" },
  { path = "{{ python.stdlib }}", uri = "file:{{ python.stdlib }}" },
  { path = "{{ python.distlib }}", uri = "file:{{ python.distlib }}" },
  { path = "/etc", uri = "file:/etc" },

  { type = "tmpfs", path = "/tmp" },
]

sys.stack.size = "2M"
sys.enable_extra_runtime_domain_names_conf = true

sgx.debug = true
sgx.nonpie_binary = true
sgx.enclave_size = "512M"
sgx.thread_num = 32

sgx.remote_attestation = "{{ ra_type }}"
sgx.ra_client_spid = "{{ ra_client_spid }}"
sgx.ra_client_linkable = {{ 'true' if ra_client_linkable == '1' else 'false' }}

sgx.trusted_files = [
  "file:{{ gramine.libos }}",
  "file:{{ entrypoint }}",
  "file:{{ gramine.runtimedir() }}/",
  "file:{{ arch_libdir }}/",
  "file:/usr/{{ arch_libdir }}/",
  "file:{{ python.stdlib }}/",
  "file:{{ python.distlib }}/",
  "file:app.py",
  "file:/etc/mime.types",
  "file:/etc/default/apport",
]

sgx.allowed_files = [
  "file:/etc/nsswitch.conf",
  "file:/etc/ethers",
  "file:/etc/hosts",
  "file:/etc/group",
  "file:/etc/passwd",
  "file:/etc/gai.conf",
  "file:/etc/host.conf",
]

I have no idea why this error occurs. I have installed Python on my system, besides, I can run samples of gramine which are written in Python using make SGX=1 for building them.


问:
How to create framework file from existing sdk codes by xcode
I am completely new to ios , mac and xcode.
Basically I am a xamarin developer which is based on .net,at the moment
our client have a requirement to use an existing sdk in their xamarin ios project.
To create a native binding for xamarin ios,we need to create a .framework file.

So how to create a .framework file from existing SDK Codes,for example lets say this one

https://github.com/facebook/facebook-ios-sdk

This is just an example...I know libraries for Facebook already exists in .Net


问:
on MySQL Workbench 8.0 CE - Server tab in empty, how can I fix it?
a screen shot of the server tab when I'm trying to use it
any idea what is the source of the problem and how can I fix it?

Workbench is up to date (checked)
tried to restart
server works fine


问:
Correlation and clustering of data with mixed type variables
I want to do statistical analysis on data that are integer, float, categorical (both with single value i.e. 0 or 1 and with multiple values).I want to omit the non important data. Is it possible to use the correlation function corr on non numerical data? If not, what is the alternative? Also, which method in sklearn can be used for clustering of mixed data?</p>


问:
tomcat context file get removed when auto deploy war
Application is spring boot package as WAR.

I have 2 context file in following path

```<code>C:\Program Files\Apache Software Foundation\Tomcat 9.0\conf\Catalina\localhost
</code>```

Each context has Parameter in it, with use to define the parameter that is used by the application, example I have different environment one is appname and appname-dev for development environement.

The problem is the context file get removed if I auto deploy the war file.

```<code><Context reloadable="false"> does not work.
</code>```

Body:
Application is spring boot package as WAR.

I have 2 context file in following path

C:\Program Files\Apache Software Foundation\Tomcat 9.0\conf\Catalina\localhost

Each context has Parameter in it, with use to define the parameter that is used by the application, example I have different environment one is appname and appname-dev for development environement.

The problem is the context file get removed if I auto deploy the war file.

<Context reloadable="false"> does not work.


问:
Re-using an API key for several different APIs
My AWS solution has several different APIs, each implemented using an API Gateway.
Now I want to introduce usage plans with throttling, and I want to use the fact that API keys can be assigned by an authorizer lambda.
However, I'm very confused regarding the relations between API keys, APIs, stages and usage plans.

A usage plan is associated with 1-N API+stage tuples. That's fine, so I can define a plan once with throttling of X requests per day, and apply that same constraint to 3 different APIs.

A UsagePlanKey ties 1 API key to 1 usage plan. Nothing strange.

With this in mind I thought about creating one single API key SharedApiKey, and then for each API set up a usage plan for that API only, and associate each usage plan with the same API key SharedApiKey:

Resources:

```<code>Shared:
SharedApiKey (AWS:ApiGateway::Key)

For API 1:
Api1 (AWS::ApiGateway::RestApi)
Api1Stage (AWS::ApiGateway::Stage)
Api1UsagePlan (AWS::ApiGateway::UsagePlan) - connect to Api1+Api1Stage
Api1UsagePlanKey - connect Api1UsagePlan with SharedApiKey

etc for API 2, 3, 4...
</code>```

I thought this would mean that I could create the shared API key in its own CF stack, and then have each API CF stack associate its usage plan with it.

However, then I found that the API key resources themselves also have an array of associations to API+stage tuples. Why is that? It seems redundant to have keys connected to N API stages, and usage plans connected to N API stages, and UsagePlanKeys connecting 1 UsagePlan to 1 key?

I then found that StageKeys on ApiKey is optional, so perhaps this is simply a legacy attribute? Or what is the consequence of not associating a key with any APIs or stages, and only connect keys to usage plans the other way around?

Will my intended setup work at all?

Body:
My AWS solution has several different APIs, each implemented using an API Gateway.
Now I want to introduce usage plans with throttling, and I want to use the fact that API keys can be assigned by an authorizer lambda.
However, I'm very confused regarding the relations between API keys, APIs, stages and usage plans.

A usage plan is associated with 1-N API+stage tuples. That's fine, so I can define a plan once with throttling of X requests per day, and apply that same constraint to 3 different APIs.

A UsagePlanKey ties 1 API key to 1 usage plan. Nothing strange.

With this in mind I thought about creating one single API key SharedApiKey, and then for each API set up a usage plan for that API only, and associate each usage plan with the same API key SharedApiKey:

Resources:

Shared:
SharedApiKey (AWS:ApiGateway::Key)

For API 1:
Api1 (AWS::ApiGateway::RestApi)
Api1Stage (AWS::ApiGateway::Stage)
Api1UsagePlan (AWS::ApiGateway::UsagePlan) - connect to Api1+Api1Stage
Api1UsagePlanKey - connect Api1UsagePlan with SharedApiKey

etc for API 2, 3, 4...

I thought this would mean that I could create the shared API key in its own CF stack, and then have each API CF stack associate its usage plan with it.

However, then I found that the API key resources themselves also have an array of associations to API+stage tuples. Why is that? It seems redundant to have keys connected to N API stages, and usage plans connected to N API stages, and UsagePlanKeys connecting 1 UsagePlan to 1 key?

I then found that StageKeys on ApiKey is optional, so perhaps this is simply a legacy attribute? Or what is the consequence of not associating a key with any APIs or stages, and only connect keys to usage plans the other way around?

Will my intended setup work at all?


问:
Getting org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session for SauceLab using selenium 3.4.0
Getting org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session for SauceLab using selenium 3.4.0 only in case of "APAC Southeast" datacenter.
And same is working using selenium 4.7.0 jar.
and other datacenter are working fine with 3.4.0

```<code>  public static void main(String[] args) throws MalformedURLException {
    String sauceUrl = "https://{username}:{accesskey}@ondemand.apac-southeast-1.saucelabs.com/wd/hub";
    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setCapability("browserName", "chrome");
    cap.setCapability("platformName", "windows 10");
    cap.setCapability("browserVersion", "latest");
    RemoteWebDriver driver = new RemoteWebDriver(new URL(sauceUrl), cap);
    driver.get("https://x.github.io/sample-todo-app/");
    System.out.println("working");
  }
</code>```

error : org.openqa.selenium.SessionNotCreatedException: Unable to
create new remote session desired capabilities = Capabilities
[{securityToken=null, acceptSslCerts=true, marionette=true, build=X
Test Run 2022-12-15 17:10:56 IST, acceptInsecureCerts=true,
name=test.testcase, browserName=chrome, version=106.0,
platform=WIN10,
firefox_profile=org.openqa.selenium.chrome.ChromeProfile@1595c99e}],
required capabilities = Capabilities [{}]

#selenium #saucelab

It should work for all data centers

Body:
Getting org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session for SauceLab using selenium 3.4.0 only in case of "APAC Southeast" datacenter.
And same is working using selenium 4.7.0 jar.
and other datacenter are working fine with 3.4.0

  public static void main(String[] args) throws MalformedURLException {
    String sauceUrl = "https://{username}:{accesskey}@ondemand.apac-southeast-1.saucelabs.com/wd/hub";
    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setCapability("browserName", "chrome");
    cap.setCapability("platformName", "windows 10");
    cap.setCapability("browserVersion", "latest");
    RemoteWebDriver driver = new RemoteWebDriver(new URL(sauceUrl), cap);
    driver.get("https://x.github.io/sample-todo-app/");
    System.out.println("working");
  }

error : org.openqa.selenium.SessionNotCreatedException: Unable to
create new remote session desired capabilities = Capabilities
[{securityToken=null, acceptSslCerts=true, marionette=true, build=X
Test Run 2022-12-15 17:10:56 IST, acceptInsecureCerts=true,
name=test.testcase, browserName=chrome, version=106.0,
platform=WIN10,
firefox_profile=org.openqa.selenium.chrome.ChromeProfile@1595c99e}],
required capabilities = Capabilities [{}]

#selenium #saucelab

It should work for all data centers


问:
C: Check expected format string length at compile-time
Assume a call like this exists in a C program:

```<code>char buffer[3];
sprintf(buffer, "%d,%d,%d", 1, 2, 3);
</code>```

If this is compiled with gcc -Wall -Wextra then it will show some warnings:

```<code>...
<source>:16:8: note: 'sprintf' output 6 bytes into a destination of size 3
   16 | sprintf(buffer, "%d,%d,%d", 1, 2, 3);
      | ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
</code>```

It seems gcc uses some fancy functions to check this (e.g. __builtin___sprintf_chk).

My question is now:
Is there a builtin-function to obtain a compile-time known value with an upperbound (if one exists) for the given format?
E.g. for format_upperbound("%d,%d", 12) it would return the maximum size of the resulting format. If there is no known upperbound at compile-time upperbound (e.g. %s) it could return -1 or something.

For sure something like this exists in gcc, because sometimes it produces errors which include some bounds, but I'm not sure if it is somehow exported.

Thanks:)

Body:
Assume a call like this exists in a C program:

char buffer[3];
sprintf(buffer, "%d,%d,%d", 1, 2, 3);

If this is compiled with gcc -Wall -Wextra then it will show some warnings:

...
<source>:16:8: note: 'sprintf' output 6 bytes into a destination of size 3
   16 | sprintf(buffer, "%d,%d,%d", 1, 2, 3);
      | ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...

It seems gcc uses some fancy functions to check this (e.g. __builtin___sprintf_chk).

My question is now:
Is there a builtin-function to obtain a compile-time known value with an upperbound (if one exists) for the given format?
E.g. for format_upperbound("%d,%d", 12) it would return the maximum size of the resulting format. If there is no known upperbound at compile-time upperbound (e.g. %s) it could return -1 or something.

For sure something like this exists in gcc, because sometimes it produces errors which include some bounds, but I'm not sure if it is somehow exported.

Thanks:)