问:
How ansible sets variables ('required_pkgs')?
I'm working on Kubespray 2.16

At roles/kubernetes/preinstall/tasks/0070-system-packages.yml, there is a task "Install packages requirements"

- name: Install packages requirements
  package:
    name: "{{ required_pkgs | default([]) | union(common_required_pkgs|default([])) }}"
    state: present
  register: pkgs_task_result
  until: pkgs_task_result is succeeded
  retries: "{{ pkg_install_retries }}"
  delay: "{{ retry_stagger | random + 3 }}"
  when: not (ansible_os_family in ["Flatcar Container Linux by Kinvolk", "ClearLinux"] or is_fedora_coreos)
  tags:
    - bootstrap-os
```
<p>According to the code, the package <code>{{ required_pkgs | default([]) | union(common_required_pkgs|default([])) }}</code> will be installed.</p>
<p>And I found the required_pkgs in <code>roles/kubernetes/preinstall/vars/*.yml</code></p>
<p>In <code>redhat.yml</code>,</p>
<pre class="lang-yaml prettyprint-override"><code>required_pkgs:
  - "{{ ( (ansible_distribution_major_version | int) < 8) | ternary('libselinux-python','python3-libselinux') }}"
  - device-mapper-libs
  - nss
  - conntrack
</code>```

In centos.yml,

required_pkgs:
  - "{{ ( (ansible_distribution_major_version | int) < 8) | ternary('libselinux-python','python3-libselinux') }}"
  - device-mapper-libs
  - nss
  - conntrack
```

I think there is no process for Ansible to check my OS in "this task". Then how the Ansible set required_pkgs among a lot of YML files?

p.s. My OS is RedHat.

答:
By default, when Ansible first starts executing a play it will implicitly run the setup module on all the remote hosts involved in the play. This is called the "fact gathering" step, and is controlled by the gather_facts option in the play or the gathering option in ansible.cfg.

The facts gathered in this step include things like operating system flavor, release, information about interfaces and disks, and a variety of other host metadata. The variables are all all in the ansible_* namespace (e.g., ansible_distribution_major_version).

Kubespray is taking advantage of these automatically gathered facts to load the appropriate vars files.

For more information:

Discovering variables: facts and magic variables (from the Ansible documentation)

An introduction to Ansible facts

Etc.

Body:
I'm working on Kubespray 2.16

At roles/kubernetes/preinstall/tasks/0070-system-packages.yml, there is a task "Install packages requirements"

- name: Install packages requirements
  package:
    name: "{{ required_pkgs | default([]) | union(common_required_pkgs|default([])) }}"
    state: present
  register: pkgs_task_result
  until: pkgs_task_result is succeeded
  retries: "{{ pkg_install_retries }}"
  delay: "{{ retry_stagger | random + 3 }}"
  when: not (ansible_os_family in ["Flatcar Container Linux by Kinvolk", "ClearLinux"] or is_fedora_coreos)
  tags:
    - bootstrap-os

According to the code, the package {{ required_pkgs | default([]) | union(common_required_pkgs|default([])) }} will be installed.

And I found the required_pkgs in roles/kubernetes/preinstall/vars/*.yml

In redhat.yml,

required_pkgs:
  - "{{ ( (ansible_distribution_major_version | int) < 8) | ternary('libselinux-python','python3-libselinux') }}"
  - device-mapper-libs
  - nss
  - conntrack

In centos.yml,

required_pkgs:
  - "{{ ( (ansible_distribution_major_version | int) < 8) | ternary('libselinux-python','python3-libselinux') }}"
  - device-mapper-libs
  - nss
  - conntrack

I think there is no process for Ansible to check my OS in "this task". Then how the Ansible set required_pkgs among a lot of YML files?

p.s. My OS is RedHat.


来源: stackexchange

问:
Python: Can a parent class initialiser know about child class class-attributes?
Sorry if the whole python code is not good. I am still learning.

What I am trying to do is that I have a few classes which share a lot of methods. Basically, the classes only differ in some fields. When I create an object of one of these classes, I want the data used for creation to be used in an assertion to see if the created object has the expected data. The expected data is different for each class but it's the same for all objects of each class (IE it's a class attribute).

I see that the following code is marked as wrong in the IDE (""):

```<code>class OperatingSystem:
    def __init__(self, my_param):
        my_os = my_param["os"]
        assert my_os == self.os_name

class Win11(OperatingSystem):
    os_name = "Windows 11"

class Win10(OperatingSystem):
    os_name = "Windows 10"
</code>```

What I think the IDE is trying to tell me by "unresolved attribute reference (os_name)" is that the parent class __init__ is called before the class variable is set. Therefore, at the time I am trying to get the class variable (init method of parent), that data is not there yet and this will certainly fail.

However, logically, the data is known already. So, there should be a way for me to make it available at ANY time. Of course, I can just put constants in the parent class or above that - but I want to give classes their own attributes and do things somewhat more OO :)

For example: Win11.os_name works fine even inside init of parent class...

Tried self.__class__.os_name - still unresolved

答:
You're almost there. The problem is that the base class OperatingSystem doesn't set os_name, so code like this:

```<code>os = OperatingSystem({'os': 'Windows'})
</code>```

will fail when it tries to read self.os_name.

Two ways to fix this:

Tell Python that OperatingSystem is an abstract base class, which means it cannot create direct instances; only its subclasses can create instances:

```<code>from abc import ABC

class OperatingSystem(ABC):
    ...
</code>```

Set os_name in the base class:

```<code>class OperatingSystem(ABC):
    os_name = "A Generic OS"
    ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Sorry if the whole python code is not good. I am still learning.

What I am trying to do is that I have a few classes which share a lot of methods. Basically, the classes only differ in some fields. When I create an object of one of these classes, I want the data used for creation to be used in an assertion to see if the created object has the expected data. The expected data is different for each class but it's the same for all objects of each class (IE it's a class attribute).

I see that the following code is marked as wrong in the IDE (""):

class OperatingSystem:
    def __init__(self, my_param):
        my_os = my_param["os"]
        assert my_os == self.os_name

class Win11(OperatingSystem):
    os_name = "Windows 11"

class Win10(OperatingSystem):
    os_name = "Windows 10"

What I think the IDE is trying to tell me by "unresolved attribute reference (os_name)" is that the parent class __init__ is called before the class variable is set. Therefore, at the time I am trying to get the class variable (init method of parent), that data is not there yet and this will certainly fail.

However, logically, the data is known already. So, there should be a way for me to make it available at ANY time. Of course, I can just put constants in the parent class or above that - but I want to give classes their own attributes and do things somewhat more OO :)

For example: Win11.os_name works fine even inside init of parent class...

Tried self.__class__.os_name - still unresolved

Body:
You're almost there. The problem is that the base class OperatingSystem doesn't set os_name, so code like this:

os = OperatingSystem({'os': 'Windows'})

will fail when it tries to read self.os_name.

Two ways to fix this:

Tell Python that OperatingSystem is an abstract base class, which means it cannot create direct instances; only its subclasses can create instances:

from abc import ABC

class OperatingSystem(ABC):
    ...

Set os_name in the base class:

class OperatingSystem(ABC):
    os_name = "A Generic OS"
    ...


问:
Programmatically localize a String?
Asp.net 4 and C#.

I have a string in my Code Behind. I would like assign a value depending on the User's Browser region.

I'm trying with this code, no error, but does not work (no value to a String has been assigned).

Any idea how to solve it? Thanks

```<code>   string textPrevious = "<%$ Resources:Global, CategoryListSubCategories %>";
</code>```

答:
You can do like...</p>

```<code>string textPrevious = Resources.Global.CategoryListSubCategories;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Programmatically localize a String?

Body:
Asp.net 4 and C#.

I have a string in my Code Behind. I would like assign a value depending on the User's Browser region.

I'm trying with this code, no error, but does not work (no value to a String has been assigned).

Any idea how to solve it? Thanks

   string textPrevious = "<%$ Resources:Global, CategoryListSubCategories %>";

Body:
You can do like...

string textPrevious = Resources.Global.CategoryListSubCategories;


问:
CMake CPack NSIS How to pass install location to project?
I have a project written in C. Currently it's using UNIX makefiles to compile itself for Linux, but recently I've been looking into CMake, to be more portable.

The executable, when running, needs to access some asset files that are part of the project. When using makefiles, I would just compile the project with:

```<code>make prefix=/usr
make prefix=/usr install
</code>```

So while the project is compiled, it knows that it will end up in /usr, and when running, it searching for its own project files there (in something like /usr/share/my-project/).

I created a very basic CMakeLists.txt, that compiles the .exe file, and installs it together with one other asset file in the install directory. I then run the following commands to create an NSIS installer for Windows:

```<code>cmake.exe --build --config Release .
cpack.exe
</code>```

Which succesfully gives me the NSIS installer. When run, it shows the user a few steps, one of them is to decide where the project will be installed, which the user can modify.

So my question is, at that point the project has already been compiled, so how can I pass to my project its own install location, so it can access files included in the project? How do other projects do this? I couldn't find much information online about it, which makes me think I might be taking the wrong approach.

答:
For anyone stuck in a similar problem, I found one solution.

Upon looking online, this seems to be something not recommended for Unix systems, and setting the install location during compilation is pretty standard.

For windows, however, I found the function GetModuleFileNameW (GetModuleFileNameW function (libloaderapi.h)).

It returns the path to the current executable (something like C:\Program Files\<my-app>\bin\my-app.exe). I've confirmed it returns the right path, even when I install the project on different directories. It returns the result using wchar_t, so unicode directories are also supported.

Here is a small example of how it can be used:

```<code>// to keep the example simple, this is assuming maximum 1000 characters in the path
wchar_t dynamicProjectLocationW[1000];
GetModuleFileNameW(NULL, dynamicProjectLocationW, 999);
dynamicProjectLocationW[999] = L'\0';

// given a path like "C:\X\Y\bin\myapp.exe" find the second to last slash
// so we can get the path "C:\X\Y\"
wchar_t *pointer = dynamicProjectLocationW;
wchar_t *secondToLastSlash = 0;
wchar_t *lastSlash = 0;
while (pointer[0] != L'\0') {
    if (pointer[0] == L'\\') {
        secondToLastSlash = lastSlash;
        lastSlash = pointer;
    }
    pointer++;
}

// cut the path short, so we can use the project path to find other files
if (secondToLastSlash) {
    secondToLastSlash++;
    secondToLastSlash[0] = L'\0';
}
</code>```

This is solving my problem for now, so I'll be using this until a better solution is found.

Body:
I have a project written in C. Currently it's using UNIX makefiles to compile itself for Linux, but recently I've been looking into CMake, to be more portable.

The executable, when running, needs to access some asset files that are part of the project. When using makefiles, I would just compile the project with:

make prefix=/usr
make prefix=/usr install

So while the project is compiled, it knows that it will end up in /usr, and when running, it searching for its own project files there (in something like /usr/share/my-project/).

I created a very basic CMakeLists.txt, that compiles the .exe file, and installs it together with one other asset file in the install directory. I then run the following commands to create an NSIS installer for Windows:

cmake.exe --build --config Release .
cpack.exe

Which succesfully gives me the NSIS installer. When run, it shows the user a few steps, one of them is to decide where the project will be installed, which the user can modify.

So my question is, at that point the project has already been compiled, so how can I pass to my project its own install location, so it can access files included in the project? How do other projects do this? I couldn't find much information online about it, which makes me think I might be taking the wrong approach.

Body:
For anyone stuck in a similar problem, I found one solution.

Upon looking online, this seems to be something not recommended for Unix systems, and setting the install location during compilation is pretty standard.

For windows, however, I found the function GetModuleFileNameW (GetModuleFileNameW function (libloaderapi.h)).

It returns the path to the current executable (something like C:\Program Files\<my-app>\bin\my-app.exe). I've confirmed it returns the right path, even when I install the project on different directories. It returns the result using wchar_t, so unicode directories are also supported.

Here is a small example of how it can be used:

// to keep the example simple, this is assuming maximum 1000 characters in the path
wchar_t dynamicProjectLocationW[1000];
GetModuleFileNameW(NULL, dynamicProjectLocationW, 999);
dynamicProjectLocationW[999] = L'\0';

// given a path like "C:\X\Y\bin\myapp.exe" find the second to last slash
// so we can get the path "C:\X\Y\"
wchar_t *pointer = dynamicProjectLocationW;
wchar_t *secondToLastSlash = 0;
wchar_t *lastSlash = 0;
while (pointer[0] != L'\0') {
    if (pointer[0] == L'\\') {
        secondToLastSlash = lastSlash;
        lastSlash = pointer;
    }
    pointer++;
}

// cut the path short, so we can use the project path to find other files
if (secondToLastSlash) {
    secondToLastSlash++;
    secondToLastSlash[0] = L'\0';
}

This is solving my problem for now, so I'll be using this until a better solution is found.


问:
Change ggplot bar chart fill colors
With this data:

```<code>df <- data.frame(value =c(20, 50, 90),
                 group = c(1, 2,3))
</code>```

I can get a bar chart:

```<code>df %>% ggplot(aes(x = group, y = value, fill = value)) +
  geom_col() +
  coord_flip()+
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")
</code>```

But I would like to have the colors of those bars to vary according to their corresponding values in value.

I have managed to change them using geom_raster:

```<code>ggplot() +
  geom_raster(aes(x = c(0:20), y = .9, fill = c(0:20)),
              interpolate = TRUE) +
  geom_raster(aes(x = c(0:50), y = 2, fill = c(0:50)),
              interpolate = TRUE) +
  geom_raster(aes(x = c(0:90), y = 3.1, fill = c(0:90)),
              interpolate = TRUE) +
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")
</code>```

This approach is not efficient when I have many groups in real data. Any suggestions to get it done more efficiently would be appreciated.

I found the accepted answer to a previous similar question, but "These numbers needs to be adjusted depending on the number of x values and range of y". I was looking for an approach that I do not have to adjust numbers based on data. David Gibson's answer fits my purpose.

答:
It does not look like this is supported natively in ggplot. I was able to get something close by adding additional rows, ranging from 0 to value) to the data. Then use geom_tile and separating the tiles by specifying width.

```<code>library(tidyverse)

df <- data.frame(value = c(20, 50, 90),
                 group = c(1, 2, 3))

df_expanded <- df %>%
  rowwise() %>%
  summarise(group = group,
            value = list(0:value)) %>%
  unnest(cols = value)

df_expanded %>%
  ggplot() +
  geom_tile(aes(
    x = group,
    y = value,
    fill = value,
    width = 0.9
  )) +
  coord_flip() +
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")
</code>```

If this is too pixilated you can increase the number of rows generated by replacing list(0:value) with seq(0, value, by = 0.1).

Title: Change ggplot bar chart fill colors

Body:
With this data:

df <- data.frame(value =c(20, 50, 90),
                 group = c(1, 2,3))

I can get a bar chart:

df %>% ggplot(aes(x = group, y = value, fill = value)) +
  geom_col() +
  coord_flip()+
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")

But I would like to have the colors of those bars to vary according to their corresponding values in value.

I have managed to change them using geom_raster:

ggplot() +
  geom_raster(aes(x = c(0:20), y = .9, fill = c(0:20)),
              interpolate = TRUE) +
  geom_raster(aes(x = c(0:50), y = 2, fill = c(0:50)),
              interpolate = TRUE) +
  geom_raster(aes(x = c(0:90), y = 3.1, fill = c(0:90)),
              interpolate = TRUE) +
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")

This approach is not efficient when I have many groups in real data. Any suggestions to get it done more efficiently would be appreciated.

I found the accepted answer to a previous similar question, but "These numbers needs to be adjusted depending on the number of x values and range of y". I was looking for an approach that I do not have to adjust numbers based on data. David Gibson's answer fits my purpose.

Body:
It does not look like this is supported natively in ggplot. I was able to get something close by adding additional rows, ranging from 0 to value) to the data. Then use geom_tile and separating the tiles by specifying width.

library(tidyverse)

df <- data.frame(value = c(20, 50, 90),
                 group = c(1, 2, 3))

df_expanded <- df %>%
  rowwise() %>%
  summarise(group = group,
            value = list(0:value)) %>%
  unnest(cols = value)

df_expanded %>%
  ggplot() +
  geom_tile(aes(
    x = group,
    y = value,
    fill = value,
    width = 0.9
  )) +
  coord_flip() +
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")

If this is too pixilated you can increase the number of rows generated by replacing list(0:value) with seq(0, value, by = 0.1).


问:
I want to add active class on the button that got clicked and remove from the another button, vice versa in vue js
I want to add an active class while the first button is clicked and remove the active class if it's there in the second button same condition for the second button how can I achieve it.</p>
```<code><button
            :class="{ active: isActiveAc, sortas: true }"
            @click="sortUp()"
          >
            Price low to Hight
          </button>
          <button
            :class="{ active: isActiveDc, sortas: true }"
            @click="sortDown()"
          >
            Price Hight to Low
          </button>
</code>```

答:
I would like to give you a basic idea which might help you.

```<code><button :class="{ active: isActiveAc, sortas: true }"@click="sortUp(),setFalse(1)>Price low to Hight</button>
<button:class="{ active: isActiveDc, sortas: true }"@click="sortDown(),setFalse(1)">Price Hight to Low</button>

</code>```

and add the following function in a method.

```<code>setFalse(c) {
      if (c == 1) {
        this.isActiveAc = true;
        this.isActiveDc = !this.isActiveAc;
      } else if (c == 2) {
        this.isActiveDc = true;
        this.isActiveAc = !this.isActiveDc;
      }
    },
</code>```

Body:
I want to add an active class while the first button is clicked and remove the active class if it's there in the second button same condition for the second button how can I achieve it.

<button
            :class="{ active: isActiveAc, sortas: true }"
            @click="sortUp()"
          >
            Price low to Hight
          </button>
          <button
            :class="{ active: isActiveDc, sortas: true }"
            @click="sortDown()"
          >
            Price Hight to Low
          </button>

Body:
I would like to give you a basic idea which might help you.

<button :class="{ active: isActiveAc, sortas: true }"@click="sortUp(),setFalse(1)>Price low to Hight</button>
<button:class="{ active: isActiveDc, sortas: true }"@click="sortDown(),setFalse(1)">Price Hight to Low</button>

and add the following function in a method.

setFalse(c) {
      if (c == 1) {
        this.isActiveAc = true;
        this.isActiveDc = !this.isActiveAc;
      } else if (c == 2) {
        this.isActiveDc = true;
        this.isActiveAc = !this.isActiveDc;
      }
    },


问:
(Javascript) i want to reduce every duplicate values in 2 Dimensional Array but i don't know how
my English is not good but i really need your help.

I want to reduce all same values in this 2 Dimensional Array but it doesn't work.

```<code>let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

 function removeDup(edge) {
      for (let i = 0; i < edge.length; i++) {
        if (edge.some((item) => item > 1)) {
          edge.splice(i, 1);
        }
      }
      return edge;
    }
</code>```

i want to change array like this.

```<code> [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]]

to

[[0,1,4],[1,2,4],[2,3,4],[3,0,4]]
</code>```

答:
This may be one possible solution to achieve the desired result:

Copying from the question:

```<code>[[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]]
</code>```

to

```<code>[[0,1,4],[1,2,4],[2,3,4],[3,0,4]]
</code>```

Note: The desired target array has no [0, 2, 4].

Code Sample

```<code>const removeDupes = arr => (
  Object.entries(
    arr.reduce(
      (fin, itm) =>
        ({...fin, [itm]: (fin[itm] || 0) + 1})
      ,{}
    )
  ).filter(
    ([k ,v]) => v === 1
  ).map(x => x[0])
);
</code>```

Explanation

Iterate over the array using .reduce to generate an object

The key of the resulting object will be each inner array (such as [0, 1, 4]

The value will be a count (number of times the inner array is found in edge)

Once the object is generated, iterate over its entries to filter only those which have a count of exactly 1

Now, use .map to pull only the keys of the object.

Code Snippet

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

const removeDupes = arr => (
  Object.entries(
    arr.reduce(
      (fin, itm) =>
        ({...fin, [itm]: (fin[itm] || 0) + 1})
      ,{}
    )
  ).filter(
    ([k ,v]) => v === 1
  ).map(x => x[0])
);

console.log(removeDupes(edge));```

Body:
my English is not good but i really need your help.

I want to reduce all same values in this 2 Dimensional Array but it doesn't work.

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

 function removeDup(edge) {
      for (let i = 0; i < edge.length; i++) {
        if (edge.some((item) => item > 1)) {
          edge.splice(i, 1);
        }
      }
      return edge;
    }

i want to change array like this.

 [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]]

to

[[0,1,4],[1,2,4],[2,3,4],[3,0,4]]

Body:
This may be one possible solution to achieve the desired result:

Copying from the question:

[[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]]

to

[[0,1,4],[1,2,4],[2,3,4],[3,0,4]]

Note: The desired target array has no [0, 2, 4].

Code Sample

const removeDupes = arr => (
  Object.entries(
    arr.reduce(
      (fin, itm) =>
        ({...fin, [itm]: (fin[itm] || 0) + 1})
      ,{}
    )
  ).filter(
    ([k ,v]) => v === 1
  ).map(x => x[0])
);

Explanation

Iterate over the array using .reduce to generate an object

The key of the resulting object will be each inner array (such as [0, 1, 4]

The value will be a count (number of times the inner array is found in edge)

Once the object is generated, iterate over its entries to filter only those which have a count of exactly 1

Now, use .map to pull only the keys of the object.

Code Snippet

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

const removeDupes = arr => (
  Object.entries(
    arr.reduce(
      (fin, itm) =>
        ({...fin, [itm]: (fin[itm] || 0) + 1})
      ,{}
    )
  ).filter(
    ([k ,v]) => v === 1
  ).map(x => x[0])
);

console.log(removeDupes(edge));


问:
vimscript autocmd passing a argument to a function
I'm trying to run tags upon file save. But I can't get the current buffers name inside the function, I need this after the write, since I want ctags to process the new amendments. Ideally I want to pass the . argument into the function from the autocmd

```<code> 23 function! UpdateTagsIfHasTags()
 24     echom "adsfsdf"
 25     return
 26     let tagsPath = printf('%s/tags', expand("%:h"))
 27     if !empty(glob(tagsPath))
 28         system(printf('/usr/local/bin/phpctags %s', filepath))
 29     endif
 30 endfunction
 31 augroup tags
 32     autocmd!
 33     autocmd BufEnter *.tex silent! !start /min ctags *.tex
 34     autocmd BufEnter *.php :call UpdateTagsIfHasTags()
 35 augroup END
</code>```

How can I pass the current file path to the function?

答:
You can get autocmd file name with special variables <afile> or <amatch>. See :h expand, :h <afile>, :h <amatch> for details.

```<code>function! Update()
  echom expand('<afile>')
  echom expand('<amatch>')
endfunction

autocmd BufEnter *.vim :call Update()
</code>```

Body:
I'm trying to run tags upon file save. But I can't get the current buffers name inside the function, I need this after the write, since I want ctags to process the new amendments. Ideally I want to pass the . argument into the function from the autocmd

 23 function! UpdateTagsIfHasTags()
 24     echom "adsfsdf"
 25     return
 26     let tagsPath = printf('%s/tags', expand("%:h"))
 27     if !empty(glob(tagsPath))
 28         system(printf('/usr/local/bin/phpctags %s', filepath))
 29     endif
 30 endfunction
 31 augroup tags
 32     autocmd!
 33     autocmd BufEnter *.tex silent! !start /min ctags *.tex
 34     autocmd BufEnter *.php :call UpdateTagsIfHasTags()
 35 augroup END

How can I pass the current file path to the function?

Body:
You can get autocmd file name with special variables <afile> or <amatch>. See :h expand, :h <afile>, :h <amatch> for details.

function! Update()
  echom expand('<afile>')
  echom expand('<amatch>')
endfunction

autocmd BufEnter *.vim :call Update()


问:
multiple expectations/assertions to verify test result
I have read in several book and articles about TDD and BDD that one should avoid multiple assertions or expectations in a single unit test or specification. And I can understand the reasons for doing so. Still I am not sure what would be a good way to verify a complex result.

Assuming a method under test returns a complex object as a result (e.g. deserialization or database read) how do I verify the result correctly?

1.Asserting on each property:

```<code>  Assert.AreEqual(result.Property1, 1);
  Assert.AreEqual(result.Property2, "2");
  Assert.AreEqual(result.Property3, null);
  Assert.AreEqual(result.Property4, 4.0);
</code>```

2.Relying on a correctly implemented .Equals():

```<code>Assert.AreEqual(result, expectedResult);
</code>```

The disadvantage  of 1. is that if the first assert fails all the following asserts are not run, which might have contained valuable information to find the problem. Maintainability might also be a problem as Properties come and go.

The disatvantage of 2. is that I seem to be testing more than one thing with this test. I might get false positives or negatives if .Equals() is not implemented correctly. Also with 2. I do not see, what properties are actually different if the test fails but I assume that can often be addressed with a decent .ToString() override. In any case I think I should avoid to be forced to throw the debugger at the failing tests to see the difference. I should see it right away.

The next problem with 2. is that it compares the whole object even though for some tests only some properties might be significant.

What would be a decent way or best practise for this in TDD and BDD.

答:
Try "one aspect of behavior per test" rather than "one assertion per test". If you need more than one assertion to illustrate the behavior you're interested in, do that.

For instance, your example might be ShouldHaveSensibleDefaults. Splitting that up into ShouldHaveADefaultNameAsEmptyString, ShouldHaveNullAddress, ShouldHaveAQuantityOfZero etc. won't read as clearly. Nor will it help to hide the sensible defaults in another object then do a comparison.

However, I would separate examples where the values had defaults with any properties derived from some logic somewhere, for instance, ShouldCalculateTheTotalQuantity. Moving small examples like this into their own method makes it more readable.

You might also find that different properties on your object are changed by different contexts. Calling out each of these contexts and looking at those properties separately helps me to see how the context relates to the outcome.

Dave Astels, who came up with the "one assertion per test", now uses the phrase "one aspect of behavior" too, though he still finds it useful to separate that behavior. I tend to err on the side of readability and maintainability, so if it makes pragmatic sense to have more than one assertion, I'll do that.

Body:
I have read in several book and articles about TDD and BDD that one should avoid multiple assertions or expectations in a single unit test or specification. And I can understand the reasons for doing so. Still I am not sure what would be a good way to verify a complex result.

Assuming a method under test returns a complex object as a result (e.g. deserialization or database read) how do I verify the result correctly?

1.Asserting on each property:

  Assert.AreEqual(result.Property1, 1);
  Assert.AreEqual(result.Property2, "2");
  Assert.AreEqual(result.Property3, null);
  Assert.AreEqual(result.Property4, 4.0);

2.Relying on a correctly implemented .Equals():

Assert.AreEqual(result, expectedResult);

The disadvantage  of 1. is that if the first assert fails all the following asserts are not run, which might have contained valuable information to find the problem. Maintainability might also be a problem as Properties come and go.

The disatvantage of 2. is that I seem to be testing more than one thing with this test. I might get false positives or negatives if .Equals() is not implemented correctly. Also with 2. I do not see, what properties are actually different if the test fails but I assume that can often be addressed with a decent .ToString() override. In any case I think I should avoid to be forced to throw the debugger at the failing tests to see the difference. I should see it right away.

The next problem with 2. is that it compares the whole object even though for some tests only some properties might be significant.

What would be a decent way or best practise for this in TDD and BDD.


问:
Propensity score for a multinomial treatment to be used in a propensity score adjusted glm
I have never used propensity scores for mulitnomial variables, and so I am unfamiliar with how the predicted probabilities are handled. I have a factor variable for treatment with 5 categories and I calculated a propensity score using multinom()

PSmod<- multinom(Treat~Age+BMI+Gender+Smoking+HIV,data =df)

df$PS <- predict(PSmod, type = 'probs')

This gives me a variable of which the class is "matrix" "array" and I am not sure how to work with this. How can I obtain a single probability from this matrix array for each subject so that I can model a glm adjusting for their propensity score?
Thanks

答:
Don't do this. Adjusting for the propensity score is very complicated with multicategory treatments. Instead, use the propensity to form inverse probability weights and fit an outcome regression model to the weighted sample. To estimate the ATE, you compute each unit's weight as the inverse of the probability of being in the group they are in. The way you would create these weights in R is the following:

```<code>for (i in 1:nlevels(df$Treat)) {
  in_i <- which(df$Treat == levels(df$Treat)[i])
  df$weight[in_i] <- 1/PS_mat[in_i, i]
}
</code>```

Or, you can just use the WeightIt package. WeightIt offers the function get_w_from_ps(), which takes in the PS matrix and the treatment vector and returns the weights. Even better would be to use weightit() to estimate the weights in a single step using one of a variety of methods, including but not limited to multinomial logistic regression. Other available methods include machine learning-based methods, optimization-based methods, and other generalized linear models beyond logistic. See my answer here for an example.

Body:
Don't do this. Adjusting for the propensity score is very complicated with multicategory treatments. Instead, use the propensity to form inverse probability weights and fit an outcome regression model to the weighted sample. To estimate the ATE, you compute each unit's weight as the inverse of the probability of being in the group they are in. The way you would create these weights in R is the following:

for (i in 1:nlevels(df$Treat)) {
  in_i <- which(df$Treat == levels(df$Treat)[i])
  df$weight[in_i] <- 1/PS_mat[in_i, i]
}

Or, you can just use the WeightIt package. WeightIt offers the function get_w_from_ps(), which takes in the PS matrix and the treatment vector and returns the weights. Even better would be to use weightit() to estimate the weights in a single step using one of a variety of methods, including but not limited to multinomial logistic regression. Other available methods include machine learning-based methods, optimization-based methods, and other generalized linear models beyond logistic. See my answer here for an example.


问:
How to understand the requirement of `std::lower_bound`?
As per the document about std::lower_bound, which says that:

The range [first, last) must be partitioned with respect to the expression element < value or comp(element, value), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets this criterion.

I have a little difficulty to fully understand it.

1.What's element < value? It seems that element (or value) is never mentioned before this paragraph in the aforementioned document. Does the said element mean the elements before the current element, and the said value means the value of the current element?

UPDATED:

2.Since whether a specific sequence is valid(i.e. suits the requirement) or not depends the value, the requirement for a specific sequence could not be always be guaranteed when the value is different. I think it's meaningless to define such a requirement. It's seems that a fully sorted seuqence is more reliable and practical.

答:
Partitions

A list of values may be partitioned, or grouped according to some criterion. For example:

```<code>┌────┬────┬────┬────┬────┬────┬────┬────┐
|  2 |  7 |  3 | -5 | 11 | 94 | 15 | 12 |
└────┴────┴────┴────┴────┴────┴────┴────┘
        x < 10      |       x ≥ 10
</code>```

In this list we have two partitions:

elements where x < 10

elements where x is not < 10

Further, the criterion implies an order:

all xs such that (x < 10) come —before— all xs such that !(x < 10)

(In C++ we tend to use a “comparator” or “comparison function” to specify the criterion.)

Notice that it does not matter what order the elements are relative to each other in each partition! That said, it is also noteworthy that if the list were sorted, it would still have the exact same two partitions:

```<code>┌────┬────┬────┬────┬────┬────┬────┬────┐
| -5 |  2 |  3 |  7 | 11 | 12 | 15 | 94 |
└────┴────┴────┴────┴────┴────┴────┴────┘
        x < 10      |       x ≥ 10
</code>```

(My example here has two equal-sized partitions. That is not necessarily the case. A partition may have zero or more elements, and each partition may have a different size than the others.)

Lower bound → index of start of partition

What the lower_bound algorithm does is find the first element of an existing partition.

The only caveat that the algorithm requires is that the sequence must already be partitioned in a way that the sort criterion makes sense. (Because the algorithm only finds partitions, it does not sort stuff!)

For example, our original sequence does not support a criterion that separates elements into (x < 7) and (x ≥ 7), because the elements are not partitioned in that way — it would not make sense to try to find the “first” element of a partition that doesn’t exist.

This is the meaning of the language used by cppreference.com.

Body:
Partitions

A list of values may be partitioned, or grouped according to some criterion. For example:

┌────┬────┬────┬────┬────┬────┬────┬────┐
|  2 |  7 |  3 | -5 | 11 | 94 | 15 | 12 |
└────┴────┴────┴────┴────┴────┴────┴────┘
        x < 10      |       x ≥ 10

In this list we have two partitions:

elements where x < 10

elements where x is not < 10

Further, the criterion implies an order:

all xs such that (x < 10) come —before— all xs such that !(x < 10)

(In C++ we tend to use a “comparator” or “comparison function” to specify the criterion.)

Notice that it does not matter what order the elements are relative to each other in each partition! That said, it is also noteworthy that if the list were sorted, it would still have the exact same two partitions:

┌────┬────┬────┬────┬────┬────┬────┬────┐
| -5 |  2 |  3 |  7 | 11 | 12 | 15 | 94 |
└────┴────┴────┴────┴────┴────┴────┴────┘
        x < 10      |       x ≥ 10

(My example here has two equal-sized partitions. That is not necessarily the case. A partition may have zero or more elements, and each partition may have a different size than the others.)

Lower bound → index of start of partition

What the lower_bound algorithm does is find the first element of an existing partition.

The only caveat that the algorithm requires is that the sequence must already be partitioned in a way that the sort criterion makes sense. (Because the algorithm only finds partitions, it does not sort stuff!)

For example, our original sequence does not support a criterion that separates elements into (x < 7) and (x ≥ 7), because the elements are not partitioned in that way — it would not make sense to try to find the “first” element of a partition that doesn’t exist.

This is the meaning of the language used by cppreference.com.


答:
This is a real hack using ggforce. This package has a geom that can take color gradients but it is for a line segment. I've just increased the size to make the line segment look like a bar. I made all the bars the same length to get the correct gradient, then covered a portion of each bar over with the same color as the background color to make them appear to be the correct length.  Had to hide the grid lines, however. :-)

```<code>df %>%
    ggplot() +
    geom_link(aes(x = 0, xend = max(value), y = group, yend = group, color = stat(index)), size = 30) +
    geom_link(aes(x = value, xend = max(value), y = group, yend = group), color = "grey", size = 31) +
    scale_color_viridis_c(option = "C") +
    theme(legend.position = "none", panel.background = element_rect(fill = "grey"),
          panel.grid = element_blank()) +
    ylim(0.5, max(df$group)+0.5 )
</code>```

Title: Change ggplot bar chart fill colors

Body:
This is a real hack using ggforce. This package has a geom that can take color gradients but it is for a line segment. I've just increased the size to make the line segment look like a bar. I made all the bars the same length to get the correct gradient, then covered a portion of each bar over with the same color as the background color to make them appear to be the correct length.  Had to hide the grid lines, however. :-)

df %>%
    ggplot() +
    geom_link(aes(x = 0, xend = max(value), y = group, yend = group, color = stat(index)), size = 30) +
    geom_link(aes(x = value, xend = max(value), y = group, yend = group), color = "grey", size = 31) +
    scale_color_viridis_c(option = "C") +
    theme(legend.position = "none", panel.background = element_rect(fill = "grey"),
          panel.grid = element_blank()) +
    ylim(0.5, max(df$group)+0.5 )


问:
How to set the process title without 3rd library in Python?
A lot of implementations employ 3rd library, such as setproctitle. So can we implement the functionality manually?</p>

答:
Of course, this functionality can be implemented by the Python raw approach. As we all know, Python has the standard library ctypes. By using this library, we can do the syscall. Meanwhile, other implementations are the same as to call system function to achieve the objective.

As the code below shows:

        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        progname = ctypes.c_char_p.in_dll(libc, '__progname_full')  # refer to the source code of glibc
        with open('/proc/self/cmdline') as fp:
            old_progname_len = len(fp.readline())
        if old_progname_len > len(new_name):
            # padding blank chars
            new_name += b' ' * (old_progname_len - len(new_name))

        # for `ps` command:
        # Environment variables are already copied to the Python program zone.
        # We can get environment variables by using `os.environ`,
        # hence we can ignore both reallocation and movement.
        libc.strcpy(progname, ctypes.c_char_p(new_name))
        # for `top` command and `/proc/self/comm`:
        buff = ctypes.create_string_buffer(len(new_name) + 1)
        buff.value = new_name
        libc.prctl(15, ctypes.byref(buff), 0, 0, 0)
```


问:
window.location.href with React.js
I need help.

If I use JSON.stringify(window.location.href), is there any way to show that URL without "" (quotes / as a string)? So showing it like a link and not a string.

If not... Is there a way to use window.location.href in React without having to use JSON.stringify()?

Or maybe use something to replace window.location.href but same result?

Basically need to show / use that url as a link (html   tag) not as a string.

New images!

code

useStickyState function

--- Ignore the key: URL_HREF its MY_URL instead ---

with JSON.stringify

without JSON.stringify

Any help is appreciated!

答:
The problem seems to be with your custom hook. Here's a variation that should work:

TypeScript Playground link

If you aren't using or can't use TypeScript in your React project, you can navigate to the playground link above and copy the transpiled JavaScript code (it's on the right side of the page).

import {
  default as React,
  useCallback,
  useEffect,
  useState,
  type Dispatch,
  type SetStateAction,
} from 'react';

// useLSState: This is a modified version of your "useStickyState"

export type Result <T = void, E extends Error = Error> = T | E;

export function getError (exception: unknown): Error {
  return exception instanceof Error ? exception : new Error(String(exception));
}

export type Json = boolean | null | number | string | Json[] | { [key: string]: Json };
export type JsonValidator = (data: Json) => boolean;

export function safeParse <T extends Json = Json>(json: string, validate: JsonValidator = () => true): Result<T> {
  try {
    const data = JSON.parse(json) as T;
    if (validate(data)) return data;
    throw new Error('Parsed JSON failed validation');
  }
  catch (ex) { return getError(ex); }
}

export function safeLSGet <T extends Json = Json>(key: string, validate: JsonValidator = () => true): Result<T> {
  const json = localStorage.getItem(key) ?? new Error(`localStorage item at "${key}" was null`);
  return json instanceof Error ? json : safeParse(json, validate);
}

export function safeLSSet <T extends Json = Json>(key: string, value: T): Result {
  try {
    const json = JSON.stringify(value);
    localStorage.setItem(key, json);
  }
  catch (ex) { return getError(ex); }
}

export function useLSState <T extends Json>(
  initalState: T,
  key: string,
  validate?: JsonValidator,
): [state: T, setState: Dispatch<SetStateAction<T>>] {
  const [value, setValue] = useState(initalState);

  useEffect(() => {
    const parsed = safeLSGet<T>(key, validate);
    if (parsed instanceof Error) {/* the localStorage value was null */}
    else setValue(parsed);
  }, [key, validate]);

  const setLSValue = useCallback<Dispatch<SetStateAction<T>>>(action => {
    if (typeof action === 'function') {
      setValue(prev => {
        const value = action(prev);
        const err = safeLSSet(key, value); // potentially useful for debugging
        return value;
      });
      return;
    }

    const value = action;
    setValue(value);
    const err = safeLSSet(key, value); // potentially useful for debugging
  }, [key, setValue]);

  return [value, setLSValue];
}

// Example usage:

const lsKey = 'MY_URL';

function Example (props: { item_url: string }) {
  const [previouslyClickedUrl, setPreviouslyClickedUrl] = useLSState(window.location.href, lsKey);

  const handleClick: React.MouseEventHandler<HTMLAnchorElement> = ev => {
    // Prevent native navigation on click
    ev.preventDefault();

    // Update the localStorage item
    setPreviouslyClickedUrl(window.location.href);

    // Navigate to the new URL
    window.location.href = props.item_url;
  };

  return (

Previous URL: {previouslyClickedUrl}

      {props.item_url}

  );
}

```

Title: window.location.href with React.js


问:
How can I put variable of one function into another function?
I am getting the error 'NameError: name 'card_dealer_1' is not defined' while it is defined in function (Blackjack_loop) that runs before the function (Blackjack) which gives the error.

I have used the globe function and I have tried to put 'card_dealer_1' as input into the second function. Both didn't work.

To show a bit of my coding,

```<code>def Blackjack_loop():
    wallet = 1000
    while play == True:
        if wallet <= 0:
            print("\nMy apologies. You have run out of cash and cannot continue the game. Please restart if you want to have a rematch.")
            break
        deck = [A, A, A, A, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5,5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,9, 10, 10, 10, 10, J, J, J, J, Q, Q, Q, Q, K, K, K, K]
        random.shuffle(deck)
        bet = input("\nHi! The dealer here is speaking. May I know how much money you want to bet?\n$")
        card_dealer_1 = random.randint(0, 51)
        card_dealer_1 = deck[card_dealer_1]
        deck.remove(card_dealer_1)

        card_dealer_2 = random.randint(0, 50)
        card_dealer_2 = deck[card_dealer_2]
        deck.remove(card_dealer_2)
</code>```

and function two

```<code>def Blackjack():
    dealer = [card_dealer_1, card_dealer_2]
    player = [card_player_1, card_player_2]
    if input("\nDo you want another card? Type 'y' or 'no'\n") == 'y':
        card_player = random.randint(0, X)
        card_player = deck[card_player]
        if card_player == 11:
            A = int(input("You have drawn an A. Do you want the value to be 11 or 1? An invalid input automatically results into 11.\n"))
            if A == 1:
                A = 1
            else:
                A = 11
        deck.remove(card_player)
        card_player.append(player)
        X -= 1
</code>```

Any help would be greatly appreciated.

edit: I can't use the return function as I need it to run the rest of the coding. Obviously, if there is no other way, I will have to adjust it and use the return function.

答:
You can use classes in this case like this:

```<code>class name:

def Blackjack_loop(self):
    wallet = 1000
    while play == True:
        if wallet <= 0:
            print("\nMy apologies. You have run out of cash and cannot continue the game. Please restart if you want to have a rematch.")
            break
        deck = [A, A, A, A, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5,5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,9, 10, 10, 10, 10, J, J, J, J, Q, Q, Q, Q, K, K, K, K]
        random.shuffle(deck)
        bet = input("\nHi! The dealer here is speaking. May I know how much money you want to bet?\n$")
        self.card_dealer_1 = random.randint(0, 51)
        self.card_dealer_1 = deck[card_dealer_1]
        deck.remove(card_dealer_1)

        card_dealer_2 = random.randint(0, 50)
        card_dealer_2 = deck[card_dealer_2]
        deck.remove(card_dealer_2)

def Blackjack(self):
    dealer = [self.card_dealer_1, card_dealer_2]
    player = [card_player_1, card_player_2]
    if input("\nDo you want another card? Type 'y' or 'no'\n") == 'y':
        card_player = random.randint(0, X)
        card_player = deck[card_player]
        if card_player == 11:
            A = int(input("You have drawn an A. Do you want the value to be 11 or 1? An invalid input automatically results into 11.\n"))
            if A == 1:
                A = 1
            else:
                A = 11
        deck.remove(card_player)
        card_player.append(player)
        X -= 1
</code>```

Body:
I am getting the error 'NameError: name 'card_dealer_1' is not defined' while it is defined in function (Blackjack_loop) that runs before the function (Blackjack) which gives the error.

I have used the globe function and I have tried to put 'card_dealer_1' as input into the second function. Both didn't work.

To show a bit of my coding,

def Blackjack_loop():
    wallet = 1000
    while play == True:
        if wallet <= 0:
            print("\nMy apologies. You have run out of cash and cannot continue the game. Please restart if you want to have a rematch.")
            break
        deck = [A, A, A, A, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5,5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,9, 10, 10, 10, 10, J, J, J, J, Q, Q, Q, Q, K, K, K, K]
        random.shuffle(deck)
        bet = input("\nHi! The dealer here is speaking. May I know how much money you want to bet?\n$")
        card_dealer_1 = random.randint(0, 51)
        card_dealer_1 = deck[card_dealer_1]
        deck.remove(card_dealer_1)

        card_dealer_2 = random.randint(0, 50)
        card_dealer_2 = deck[card_dealer_2]
        deck.remove(card_dealer_2)

and function two

def Blackjack():
    dealer = [card_dealer_1, card_dealer_2]
    player = [card_player_1, card_player_2]
    if input("\nDo you want another card? Type 'y' or 'no'\n") == 'y':
        card_player = random.randint(0, X)
        card_player = deck[card_player]
        if card_player == 11:
            A = int(input("You have drawn an A. Do you want the value to be 11 or 1? An invalid input automatically results into 11.\n"))
            if A == 1:
                A = 1
            else:
                A = 11
        deck.remove(card_player)
        card_player.append(player)
        X -= 1

Any help would be greatly appreciated.

edit: I can't use the return function as I need it to run the rest of the coding. Obviously, if there is no other way, I will have to adjust it and use the return function.

Body:
You can use classes in this case like this:

class name:

def Blackjack_loop(self):
    wallet = 1000
    while play == True:
        if wallet <= 0:
            print("\nMy apologies. You have run out of cash and cannot continue the game. Please restart if you want to have a rematch.")
            break
        deck = [A, A, A, A, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5,5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,9, 10, 10, 10, 10, J, J, J, J, Q, Q, Q, Q, K, K, K, K]
        random.shuffle(deck)
        bet = input("\nHi! The dealer here is speaking. May I know how much money you want to bet?\n$")
        self.card_dealer_1 = random.randint(0, 51)
        self.card_dealer_1 = deck[card_dealer_1]
        deck.remove(card_dealer_1)

        card_dealer_2 = random.randint(0, 50)
        card_dealer_2 = deck[card_dealer_2]
        deck.remove(card_dealer_2)

def Blackjack(self):
    dealer = [self.card_dealer_1, card_dealer_2]
    player = [card_player_1, card_player_2]
    if input("\nDo you want another card? Type 'y' or 'no'\n") == 'y':
        card_player = random.randint(0, X)
        card_player = deck[card_player]
        if card_player == 11:
            A = int(input("You have drawn an A. Do you want the value to be 11 or 1? An invalid input automatically results into 11.\n"))
            if A == 1:
                A = 1
            else:
                A = 11
        deck.remove(card_player)
        card_player.append(player)
        X -= 1


问:
.NET Core backwards compatibly issue
I have an ASP.NET core website that is targeting .NET 5.  I have installed the lastest hosting bundle and from what I read, this should work, but I have the following error in the event log:</p>
```<code>Could not find 'aspnetcorev2_inprocess.dll'. Exception message:
It was not possible to find any compatible framework version
The framework 'Microsoft.AspNetCore.App', version '5.0.0' (x64) was not found.
  - The following frameworks were found:
      2.1.18 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
      2.1.30 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
      3.1.4 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
      3.1.22 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
      6.0.1 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
</code>```

答:
There is incompatibility between major versions of .net core. For example .net 5 and .net 6.

I haven't found the official relevant documentation for the time being, but it's not difficult to understand this problem. If it is compatible, existing projects do not need to be migrated. Project migration solves the compatibility problem.

Migration from Asp.Net Core 5.0 to 6.0 — Real project

Recommendation

Install the special version sdk will solve your issue.

Title: .NET Core backwards compatibly issue

Body:
I have an ASP.NET core website that is targeting .NET 5.  I have installed the lastest hosting bundle and from what I read, this should work, but I have the following error in the event log:

Could not find 'aspnetcorev2_inprocess.dll'. Exception message:
It was not possible to find any compatible framework version
The framework 'Microsoft.AspNetCore.App', version '5.0.0' (x64) was not found.
  - The following frameworks were found:
      2.1.18 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
      2.1.30 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
      3.1.4 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
      3.1.22 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
      6.0.1 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]


问:
Double every other element of list from right in Haskell
I have a list and I want to double every other element in this list from the right.

There is another related question that solves this problem but it doubles from the left, not the right: Haskell: Double every 2nd element in list

For example, in my scenario, [1,2,3,4] would become [2,2,6,4], and in that question, [1,2,3,4] would become [1,4,3,8].

How would I implement this?

答:
We can also do it like this:</p>
```<code>doubleEveryOther = reverse . zipWith (*) value . reverse
    where
    value = 1 : 2 : value
</code>```

Body:
We can also do it like this:

doubleEveryOther = reverse . zipWith (*) value . reverse
    where
    value = 1 : 2 : value


问:
Initializing the Date Picker with Date Other Than Today
I need help with dates. How do you initialize the DatePicker with a stored date? Say, for example, that the user entered an entry with a date. He then determines the date is wrong and would like to change the date. But currently the DatePicker in this code will always default to today's date instead of the stored date.

The state parameter startDate can't be initialized with a stored date above the body. It appears that I need to set startDate in the body.

```<code>import SwiftUI
import Combine

struct GetDate: View {

    @ObservedObject var userData : UserData = UserData()
    @State private var startDate = Date()

    var body: some View {

        //let startDate = userData.startDate

        VStack (alignment: .leading) {

            Form {

                Text("startdate 1 = \(startDate)")

                // enter start date
                Section(header: Text("Enter Start Date")) {
                    HStack {
                        Image(systemName: "calendar.badge.clock")
                            .resizable()
                            .foregroundColor(Color(.systemRed))
                            .frame(width: 35, height: 35)

                        Spacer()

                        DatePicker("", selection: $startDate, in: ...Date(), displayedComponents: .date)
                            .datePickerStyle(CompactDatePickerStyle())
                    }
                }

                Button ( action: {
                    userData.saveDates(startDate: startDate)
                }) {

                    HStack {
                        Spacer()
                        Text("Save Dates?")
                        Spacer()
                    }
                }
            }
            .font(.body)
            .navigationBarTitle("Get Date", displayMode: .inline)
        }
    }
}

class UserData:  ObservableObject {

    @Published var startDate: Date = Date()  {
        didSet {
            UserDefaults.standard.set(startDate, forKey: "startDate")  // save
        }
    }

    init() {
        // save / retrieve trip dates
        if let sdate = UserDefaults.standard.object(forKey: "startDate") as? Date {
            startDate = sdate
            print("startDate 2 = \(startDate)")
        } else {
            UserDefaults.standard.set(Date(), forKey: "startDate")
        }
    }

    func saveDates(startDate: Date) -> () {

        self.startDate = startDate
        UserDefaults.standard.set(self.startDate, forKey: "startDate")

        print("startDate 3 = \(self.startDate)")
    }
}
</code>```

答:
Just reset startDate to userData.startDate in .onAppear().

```<code>    .onAppear {
        startDate = userData.startDate
    }
</code>```

Body:
I need help with dates. How do you initialize the DatePicker with a stored date? Say, for example, that the user entered an entry with a date. He then determines the date is wrong and would like to change the date. But currently the DatePicker in this code will always default to today's date instead of the stored date.

The state parameter startDate can't be initialized with a stored date above the body. It appears that I need to set startDate in the body.

import SwiftUI
import Combine

struct GetDate: View {

    @ObservedObject var userData : UserData = UserData()
    @State private var startDate = Date()

    var body: some View {

        //let startDate = userData.startDate

        VStack (alignment: .leading) {

            Form {

                Text("startdate 1 = \(startDate)")

                // enter start date
                Section(header: Text("Enter Start Date")) {
                    HStack {
                        Image(systemName: "calendar.badge.clock")
                            .resizable()
                            .foregroundColor(Color(.systemRed))
                            .frame(width: 35, height: 35)

                        Spacer()

                        DatePicker("", selection: $startDate, in: ...Date(), displayedComponents: .date)
                            .datePickerStyle(CompactDatePickerStyle())
                    }
                }

                Button ( action: {
                    userData.saveDates(startDate: startDate)
                }) {

                    HStack {
                        Spacer()
                        Text("Save Dates?")
                        Spacer()
                    }
                }
            }
            .font(.body)
            .navigationBarTitle("Get Date", displayMode: .inline)
        }
    }
}

class UserData:  ObservableObject {

    @Published var startDate: Date = Date()  {
        didSet {
            UserDefaults.standard.set(startDate, forKey: "startDate")  // save
        }
    }

    init() {
        // save / retrieve trip dates
        if let sdate = UserDefaults.standard.object(forKey: "startDate") as? Date {
            startDate = sdate
            print("startDate 2 = \(startDate)")
        } else {
            UserDefaults.standard.set(Date(), forKey: "startDate")
        }
    }

    func saveDates(startDate: Date) -> () {

        self.startDate = startDate
        UserDefaults.standard.set(self.startDate, forKey: "startDate")

        print("startDate 3 = \(self.startDate)")
    }
}

Body:
Just reset startDate to userData.startDate in .onAppear().

    .onAppear {
        startDate = userData.startDate
    }


问:
Filter dataframe based on matching values from two columns
I have a dataframe like as shown below

```<code>cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,2,3,0,0]})
</code>```

I would like to filter the dataframe based on the below criteria

```<code>cdf['Id']==cdf['Label']  # first 3 rows are matching for both columns in cdf
</code>```

I tried the below

```<code>flag = np.where[cdf['Id'].eq(cdf['Label'])==True,1,0]
final_df = cdf[cdf['flag']==1]
</code>```

but I got the below error

TypeError: 'function' object is not subscriptable

I expect my output to be like as shown below

```<code>     Id Label
0    1   1
1    2   2
2    3   3
</code>```

答:
Also you can check query

```<code>cdf.query('Id == Label')
Out[248]:
   Id  Label
0   1      1
1   2      2
2   3      3
</code>```

Body:
I have a dataframe like as shown below

cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,2,3,0,0]})

I would like to filter the dataframe based on the below criteria

cdf['Id']==cdf['Label']  # first 3 rows are matching for both columns in cdf

I tried the below

flag = np.where[cdf['Id'].eq(cdf['Label'])==True,1,0]
final_df = cdf[cdf['flag']==1]

but I got the below error

TypeError: 'function' object is not subscriptable

I expect my output to be like as shown below

     Id Label
0    1   1
1    2   2
2    3   3

Body:
Also you can check query

cdf.query('Id == Label')
Out[248]:
   Id  Label
0   1      1
1   2      2
2   3      3


问:
Is there a way to have a constructor return an object that == null in Java?
I have a feeling the answer is "no" but thought I'd ask just in case...

pseudo code:

```<code>Foo foo = new Foo();

if(foo != null){
    foo.useMe();
}else{
   System.out.println("foo failed to initialize");
}
</code>```

What would I have to do in Foo to make this a reality?

答:
11 years later and we still have the issue. To summarize the valid responses and add an idea as well:

Idea 1: Create a wrapper class to work like a factory. This wrapper class will create new instances of the inner class if the data is valid. (by user975484)
//Idea 1 is great if you are working solo, but if you are creating an object for a school or company project then you may not be allowed to use a factory.

Idea 2: Throw an exception if data is invalid in the constructor. (by CamelSlack)
//Idea 2 is great as well if the user catches and handles the error. However, you may not be allowed to use this method for school or company rules. I believe that this may be the best solution if you can use it.

Idea 3: return null or default data from functions in the object after verifying data. In essence, run your data verification before running functions.
//Idea 3 might be the only option for students and employees who are forced to follow an overly strict set of requirements. Really isn't useful unless idea 1 and 2 cannot be used.

Body:
I have a feeling the answer is "no" but thought I'd ask just in case...

pseudo code:

Foo foo = new Foo();

if(foo != null){
    foo.useMe();
}else{
   System.out.println("foo failed to initialize");
}

What would I have to do in Foo to make this a reality?


问:
Getting 401 error when using API Key to Retrieve Gmail inbox contents via list endpoint
I am trying to add some API tests for our application that validate that a message is sent out and eventually received in Gmail. I went ahead and added an API key for my email in the Google Cloud Services developer console and created the following code.

The Client.cs class is just an example I found online that I tweaked and made work with our endpoints (maybe this type of strategy wont work with Gmail API?)

Enpoints.cs is just the class to return the URL. Im also including the key as an optional parameter

Test.cs just contains a segment of how I am calling the endpoint and getting the 401 Unauthorized error

Are we able to use the list endpoint to get the contents of a gmail inbox by using an API Key?

Client.cs

```<code>public enum Command {
    GET,
    POST,
    PUT,
    DELETE }

namespace Project{
    public class Client
    {

        public string endPoint { get; set; }
        public Command execute { get; set; }
        public string contentType { get; set; }
        public string postData { get; set; }
        public string encoded = "";

        // Basic Client
        public Client()
        {
            endPoint = "";
            execute = Command.GET;
            contentType = "application/JSON";
            postData = "";
            encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("email@gmail.com"
+ ":" + "mypass"));
        }

        // Basic Request
        public string Request(string parameters)
        {
            var request = (HttpWebRequest)WebRequest.Create(parameters);
            request.Headers.Add("Authorization", "Basic " + encoded);
            request.Method = execute.ToString();
            request.ContentLength = 0;
            request.ContentType = contentType;

            if (postData != "")
            {
                request.SendChunked = true;
                request.ContentType = "application/json";

                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    string json = postData;

                    streamWriter.Write(json);
                }
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var responseValue = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Failed: Received HTTP {0}", response.StatusCode);
                    Console.WriteLine(message);
                    //throw new ApplicationException(message);
                }

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                }

                return responseValue;
            }
        }
    }

}
</code>```

Endpoints.cs

```<code>namespace Project
{
    class Endpoints
    {

        // Class to store URLs for Gmail Integrations
        public static class Gmail
        {
            // Class to interface with Gmail Messages
            public static class Messages
            {
                // Retrieve Messsages (List)
                public static string List(string userId)
                {
                    return "https://gmail.googleapis.com/gmail/v1/users/" + userId + "/messages?key=mykey";
                }
            }
        }

    }
}
</code>```

Test.cs

```<code>// Prepare the Client
Client client = new Client();

// Get the Response
client.execute = Command.GET;
var response = client.Request(Endpoints.Gmail.Messages.List("email@gmail.com"));

// Print Response
Console.WriteLine(response);
</code>```

答:
For anyone else who might stumble upon this, it turns out there really is no easy way to do this with GMail. This post does describe a way to do it, however with the OAuth2 authentication, you will need to login using a browser popup which means no headless API tests..

https://www.swtestacademy.com/gmail-api-test-automation/

I ended up using this product, https://testmail.app/, which is super affordable and lightweight and works great if you are just trying to do some simple email validations.

Body:
I am trying to add some API tests for our application that validate that a message is sent out and eventually received in Gmail. I went ahead and added an API key for my email in the Google Cloud Services developer console and created the following code.

The Client.cs class is just an example I found online that I tweaked and made work with our endpoints (maybe this type of strategy wont work with Gmail API?)

Enpoints.cs is just the class to return the URL. Im also including the key as an optional parameter

Test.cs just contains a segment of how I am calling the endpoint and getting the 401 Unauthorized error

Are we able to use the list endpoint to get the contents of a gmail inbox by using an API Key?

Client.cs

public enum Command {
    GET,
    POST,
    PUT,
    DELETE }

namespace Project{
    public class Client
    {

        public string endPoint { get; set; }
        public Command execute { get; set; }
        public string contentType { get; set; }
        public string postData { get; set; }
        public string encoded = "";

        // Basic Client
        public Client()
        {
            endPoint = "";
            execute = Command.GET;
            contentType = "application/JSON";
            postData = "";
            encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("email@gmail.com"
+ ":" + "mypass"));
        }

        // Basic Request
        public string Request(string parameters)
        {
            var request = (HttpWebRequest)WebRequest.Create(parameters);
            request.Headers.Add("Authorization", "Basic " + encoded);
            request.Method = execute.ToString();
            request.ContentLength = 0;
            request.ContentType = contentType;

            if (postData != "")
            {
                request.SendChunked = true;
                request.ContentType = "application/json";

                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    string json = postData;

                    streamWriter.Write(json);
                }
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var responseValue = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Failed: Received HTTP {0}", response.StatusCode);
                    Console.WriteLine(message);
                    //throw new ApplicationException(message);
                }

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                }

                return responseValue;
            }
        }
    }

}

Endpoints.cs

namespace Project
{
    class Endpoints
    {

        // Class to store URLs for Gmail Integrations
        public static class Gmail
        {
            // Class to interface with Gmail Messages
            public static class Messages
            {
                // Retrieve Messsages (List)
                public static string List(string userId)
                {
                    return "https://gmail.googleapis.com/gmail/v1/users/" + userId + "/messages?key=mykey";
                }
            }
        }

    }
}

Test.cs

// Prepare the Client
Client client = new Client();

// Get the Response
client.execute = Command.GET;
var response = client.Request(Endpoints.Gmail.Messages.List("email@gmail.com"));

// Print Response
Console.WriteLine(response);


问:
how to add space between textbox and browse button for input file type
Can we add space between the browse button and textbox for input type file ?Is that possible? Aslo can i add border color for the same  textbox ?

thanks,

michaeld

答:
Increasing spacing is not possible. Generally speaking, styling an input type="file" is extremely difficult. If you check cross-browser, you can see that different browsers render it differently. The only way to style it is to fake another element as input type="file"

Example: http://www.quirksmode.org/dom/inputfile.html


问:
Pylint check in `src` directory not finding errors in `src/collect/` directory
When I run the command pylint src in my project, I expect it to go through all of the folders and files within src and find the errors. However, I run it and get:

```<code>(.venv) kasparpoland@kasparMac server % pylint src

--------------------------------------------------------------------
Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)
</code>```

However, when I run pylint src/collect, I get hundreds of errors:

```<code>(.venv) kasparpoland@kasparMac server % pylint src/collect
************* Module src.collect.collect
src/collect/collect.py:36:0: C0301: Line too long (147/100) (line-too-long)
src/collect/collect.py:72:0: C0301: Line too long (126/100) (line-too-long)
src/collect/collect.py:81:0: C0301: Line too long (107/100) (line-too-long)
src/collect/collect.py:105:0: C0301: Line too long (104/100) (line-too-long)
src/collect/collect.py:116:0: C0301: Line too long (146/100) (line-too-long)
src/collect/collect.py:127:0: C0301: Line too long (155/100) (line-too-long)
src/collect/collect.py:161:0: C0301: Line too long (140/100) (line-too-long)
src/collect/collect.py:177:0: C0301: Line too long (108/100) (line-too-long)
src/collect/collect.py:200:0: C0301: Line too long (110/100) (line-too-long)
src/collect/collect.py:233:0: C0301: Line too long (132/100) (line-too-long)
src/collect/collect.py:236:0: C0301: Line too long (101/100) (line-too-long)
src/collect/collect.py:258:0: C0301: Line too long (108/100) (line-too-long)
... AND MANY MORE
</code>```

Why is this happening?

答: The pylint command only searches the immediate directory, or python files within it. A command like pylint *.py **/*.py will search recursively for python files, beginning at the root.

Body:
When I run the command pylint src in my project, I expect it to go through all of the folders and files within src and find the errors. However, I run it and get:

(.venv) kasparpoland@kasparMac server % pylint src

--------------------------------------------------------------------
Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)

However, when I run pylint src/collect, I get hundreds of errors:

(.venv) kasparpoland@kasparMac server % pylint src/collect
************* Module src.collect.collect
src/collect/collect.py:36:0: C0301: Line too long (147/100) (line-too-long)
src/collect/collect.py:72:0: C0301: Line too long (126/100) (line-too-long)
src/collect/collect.py:81:0: C0301: Line too long (107/100) (line-too-long)
src/collect/collect.py:105:0: C0301: Line too long (104/100) (line-too-long)
src/collect/collect.py:116:0: C0301: Line too long (146/100) (line-too-long)
src/collect/collect.py:127:0: C0301: Line too long (155/100) (line-too-long)
src/collect/collect.py:161:0: C0301: Line too long (140/100) (line-too-long)
src/collect/collect.py:177:0: C0301: Line too long (108/100) (line-too-long)
src/collect/collect.py:200:0: C0301: Line too long (110/100) (line-too-long)
src/collect/collect.py:233:0: C0301: Line too long (132/100) (line-too-long)
src/collect/collect.py:236:0: C0301: Line too long (101/100) (line-too-long)
src/collect/collect.py:258:0: C0301: Line too long (108/100) (line-too-long)
... AND MANY MORE

Why is this happening?


问:
Error MSB3541: Files has invalid value
I just deployed an asp.net mvc 3 web application to AppHarbor but it failed:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(3932,5): error MSB3541: Files has invalid value "<<<<<<< HEAD". Illegal characters in path. [D:\temp\q5cmde4m.uk1\input\MyProject\MyProject.csproj]

This happened after I opened the project with Visual Studio 2012 (the application was created with VS2010).

答:
Ok this might be helpful to someone else.

in my case my .vbproj file and some form files somehow had the last lines of its code truncated, I fixed this by restoring this missing part of the code (around the last 10 lines were missing) from a previous backup of the same project.

The other files got corrupted in a simillar way and were fixed by restoring the missing parts of the files from the backed up ones on a text editor (notepad)

After getting this the project loaded without issue.

Title: Error MSB3541: Files has invalid value


问:
How to get difference in years from current date and Ecto.Date instance
Let's say I have a Person model and each person has a birthday field set as an Ecto.Date column.

So if I retrieve a record from the database which represents an instance of this model, what is the best way to get this person's age from his birthday column?

答:
I know this is a bit old but I just ran into this and wrote my own function which I think is a bit easier to understand, using Date from Elixir which has since replaced Ecto.Date:

```<code>def get_person_age(%Person{} = person) do
  today = Date.utc_today()
  {:ok, today_in_birthday_year} = Date.new(person.birthday.year, today.month, today.day)
  years_diff = today.year - person.birthday.year

  if Date.compare(today_in_birthday_year, person.birthday) == :lt do
    years_diff - 1
  else
    years_diff
  end
end
</code>```

Body:
I know this is a bit old but I just ran into this and wrote my own function which I think is a bit easier to understand, using Date from Elixir which has since replaced Ecto.Date:

def get_person_age(%Person{} = person) do
  today = Date.utc_today()
  {:ok, today_in_birthday_year} = Date.new(person.birthday.year, today.month, today.day)
  years_diff = today.year - person.birthday.year

  if Date.compare(today_in_birthday_year, person.birthday) == :lt do
    years_diff - 1
  else
    years_diff
  end
end


问:
IntersectionObserver not updating in React
The following code will trigger a state change as soon as the element enters or leaves the viewport by scrolling

```<code>const dialog = useRef(),
[visible, set] = useState(false)

useEffect(() => {
        const observer = new IntersectionObserver((e) => {
            set(e[0].isIntersecting ? true : false)
        }, {root: null, rootMargin: '0px', threshold: 0})
        observer.observe(dialog.current)
        return () => observer.disconnect()
    }, [dialog.current])

return <div ref={dialog}>my dialog</div>
</code>```

but if I try something like this

```<code>const observer = new IntersectionObserver((e) => {
            set(e[0].boundingClientRect.y <= 0 ? true : false)
        }, {root: null, rootMargin: '0px', threshold: 0})
</code>```

the state gets updated only if a re-render is triggered, while I want it to trigger when I scroll the viewport, based on the boundingClientRect.y value of the observed element.
the only way I found to make this work is by using window.onscroll event inside useEffect and putting the observer inside it but it doesn't look too good to me. Is there a different (and better) way than using window.onscroll ?

答:
This is to do with the DOM content not fully loading by the time the IntersectionObserver is instantiated in the useEffect hook.

A way around this, without using window.onscroll, is to run the hook in a component and pass your setter as a prop.

Something like this

```<code>function MyObserver({ selector, callback }){
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => callback(entries),
      { root: null, rootMargin: '0px', threshold: 0 });

    const element = document.querySelector(selector);

    observer.observe(element);

    return () => {
      observer.disconnect();
    };

  }, []);

  return null;
}

function Main() {
  [visible, set] = useState(false);

  return <>
    <div className="myDialog">my dialog</div>
    <MyObserver selector=".myDialog"
      callback={ (e) => { set(e[0].isIntersecting ? true : false); } } />
  </>;
}
</code>```

Now the observer logic is part of the render flow, taking place after the dialog, so it should update correctly.

This worked for me when faced with this exact issue.

Body:
The following code will trigger a state change as soon as the element enters or leaves the viewport by scrolling

const dialog = useRef(),
[visible, set] = useState(false)

useEffect(() => {
        const observer = new IntersectionObserver((e) => {
            set(e[0].isIntersecting ? true : false)
        }, {root: null, rootMargin: '0px', threshold: 0})
        observer.observe(dialog.current)
        return () => observer.disconnect()
    }, [dialog.current])

return
my dialog

but if I try something like this

const observer = new IntersectionObserver((e) => {
            set(e[0].boundingClientRect.y <= 0 ? true : false)
        }, {root: null, rootMargin: '0px', threshold: 0})

the state gets updated only if a re-render is triggered, while I want it to trigger when I scroll the viewport, based on the boundingClientRect.y value of the observed element.
the only way I found to make this work is by using window.onscroll event inside useEffect and putting the observer inside it but it doesn't look too good to me. Is there a different (and better) way than using window.onscroll ?

Body:
This is to do with the DOM content not fully loading by the time the IntersectionObserver is instantiated in the useEffect hook.

A way around this, without using window.onscroll, is to run the hook in a component and pass your setter as a prop.

Something like this

function MyObserver({ selector, callback }){
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => callback(entries),
      { root: null, rootMargin: '0px', threshold: 0 });

    const element = document.querySelector(selector);

    observer.observe(element);

    return () => {
      observer.disconnect();
    };

  }, []);

  return null;
}

function Main() {
  [visible, set] = useState(false);

  return <>
    <div className="myDialog">my dialog</div>
    <MyObserver selector=".myDialog"
      callback={ (e) => { set(e[0].isIntersecting ? true : false); } } />
  </>;
}

Now the observer logic is part of the render flow, taking place after the dialog, so it should update correctly.

This worked for me when faced with this exact issue.


问:
Multiple conditions in Regex_Replace
I want to replace special characters from two different words as shown in the image below. From the first word, I want to replace a special character with "I" and from the second word, I want to replace a special character with "U".
My query is like below: It works for the first word. Can you pls assist?

```<code>SELECT
   distinct ABC REGEXP_REPLACE(REGEXP_REPLACE(ABC, r'([^\p{ASCII}]+)', 'I') ,r'\&', 'U')
FROM Table
where ABC like '%B??RD%' or ABC like '%M??D%';
</code>```

答:
Instead of using REGEX, you can use CASE for this scenario:

```<code>WITH CTE as (
SELECT  'B��RD'as ABC,
UNION ALL SELECT 'M��D'as ABC)

SELECT
   ABC,
   CASE ABC
    WHEN 'B��RD' THEN 'BIRD'
    WHEN 'M��D' THEN 'MUD'
   END AS output

FROM CTE
</code>```

Output:

Title: Multiple conditions in Regex_Replace

Body:
I want to replace special characters from two different words as shown in the image below. From the first word, I want to replace a special character with "I" and from the second word, I want to replace a special character with "U".
My query is like below: It works for the first word. Can you pls assist?

SELECT
   distinct ABC REGEXP_REPLACE(REGEXP_REPLACE(ABC, r'([^\p{ASCII}]+)', 'I') ,r'\&', 'U')
FROM Table
where ABC like '%B??RD%' or ABC like '%M??D%';

Body:
Instead of using REGEX, you can use CASE for this scenario:

WITH CTE as (
SELECT  'B��RD'as ABC,
UNION ALL SELECT 'M��D'as ABC)

SELECT
   ABC,
   CASE ABC
    WHEN 'B��RD' THEN 'BIRD'
    WHEN 'M��D' THEN 'MUD'
   END AS output

FROM CTE

Output:


问:
Restrict Windows shell extension to folder/drive
I'm working on a shell extension that is supposed to display extended properties of files (mostly .jpgs) stored on a virtual drive (think of it as an external harddrive).

Is it possible to register the shell extension in a way that it only kicks in for files of a specific folder/drive (in my case the external harddrive) and leaves the handling of jpgs in other folder to the Windows default shell extension?

Regards,

Sebastian

答:
Place Your app infos in:
HKEY_CLASSES_ROOT\Directory\shell\</p>

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: anon


问:
invalid api key
I am investigating using the services module in Drupal 6 to get data from some custom views in JSON format.  I followed an article at http://drupal.org/node/308629 and created a vb version of this project (pushed up to https://sharpred@github.com/sharpred/ConsoleApplicationDrupal.git)

The first time I run my code I get "Invalid API Key", subsequent runs return "token has been used previously for a request.  Re-try with another nonce key".  The second error is a bit spurious IMO as my code creates a new random nonce each time it is run.

I also noticed that the first run creates an entry in services_timestamp_nonce table that contains just the timestamp but no nonce or domain value.  If I delete this record, it goes back to the "invalid api key" message.

The code works unauthenticated and the method call from /admin/build/services/browse/views.get on the site works also.

Any ideas as to why this does not work?

Searching google, the most common source of "invalid api key" seems to be either the timestamp one uses is wrong or the api key does not match the domain used in creating the hash.  Neither are true in my case as far as I can see.  I created a gist of my code used to create the timestamp and hash at https://gist.github.com/1151222

Can anyone help on getting this process to work?

答: I figured this out after trawling through the code for the services module.  Some of the values in my multipart form were not enclosed with quotes, so were being processed as nulls by the services_key_auth module.  This meant that on the first pass, only the timestamp was being written to the nonce table and the computed hash did not match my hash because of the quotes.  On subsequent updates, the module was effectively doing a search for a nonce value of null and  on finding one in the database, returning the result that one had been used before.  If anyone else gets this issue, pull my github project linked above and look at my code.</p>

Title: invalid api key


问:
Is there a way to find out which array the image belongs to, after loading it into an array in preload() function? - Javascript
I am trying to load multiple images from multiple folders in three different arrays like so:

```<code>function preload()
{

for (let num=0; num<10; num++){

    array1[num] = loadImage('first/img'+ num +'.png');
  }

  for (let num1=0; num1<18; num1++){

    array2[num1] = loadImage('second/img'+ num1 +'.png');
  }

  for (let num2=0; num2<25; num2++){

    array3[num2] = loadImage('third/img'+ num2 +'.png');
  }
}
</code>```

Now I want to pick a random image from a random folder. If the image belongs to array1, I want to print 'first folder'. If second, it should print 'second folder' and so on.

Is there any easier way to get this task done?

答:
You can pick a random folder first, then pick a random image from it.
This is the pseudo code.

const getRand = (num) => parseInt(Math.random() * num);

const folder1 = Array.from(Array(10).keys());
const folder2 = Array.from(Array(18).keys());
const folder3 = Array.from(Array(25).keys());
const allItems = [folder1, folder2, folder3];

const randInt1 = getRand(allItems.length);
const randomFolder = allItems[randInt1];
const randInt2 = getRand(randomFolder.length);
const randomImage = randomFolder[randInt2];
```

Body:
I am trying to load multiple images from multiple folders in three different arrays like so:

function preload()
{

for (let num=0; num<10; num++){

    array1[num] = loadImage('first/img'+ num +'.png');
  }

  for (let num1=0; num1<18; num1++){

    array2[num1] = loadImage('second/img'+ num1 +'.png');
  }

  for (let num2=0; num2<25; num2++){

    array3[num2] = loadImage('third/img'+ num2 +'.png');
  }
}

Now I want to pick a random image from a random folder. If the image belongs to array1, I want to print 'first folder'. If second, it should print 'second folder' and so on.

Is there any easier way to get this task done?


问:
How do I loop a piece of code (have tried for, doesn't seem to work for me)
I'm looking for a way to loop the code below... so that it'll go through and print the first sentence, then the second sentence over and over until one entity's health drops to zero.

From my research (bearing in mind I'm a knucklehead) the 'for' function seems to only work with single words/numbers... but perhaps I'm wrong.

CODE:

```<code>if sentence == 1:
  print ("The" + " " + enemy_1 + " " + random.choice(attack_verb) + " " + main_character + " " + "with its" + " " + random.choice(enemy_1_weapon))
  enemy_1_health -= 20
  print (enemy_1_health)
  sentence = 0

if sentence == 0:
  print (main_character + " " + random.choice(attack_verb) + " " + "the" + " " + enemy_1 + " " + "with his" + " " + random.choice(main_character_weapon))
  enemy_1_health -= 20
  print (enemy_1_health)
  sentence = 1

#And then repeat and repeat over and over :)
</code>```

答:
you could do something like this</p>
```<code>while enemy_1_health > 0:
    if sentence == 1:
        print ("The" + " " + enemy_1 + " " + random.choice(attack_verb) + " " + main_character + " " + "with its" + " " + random.choice(enemy_1_weapon))
        enemy_1_health -= 20
        print(enemy_1_health)
        sentence = 0

    if sentence == 0:
        print (main_character + " " + random.choice(attack_verb) + " " + "the" + " " + enemy_1 + " " + "with his" + " " + random.choice(main_character_weapon))
        enemy_1_health -= 20
        print(enemy_1_health)
        sentence = 1

</code>```

Body:
I'm looking for a way to loop the code below... so that it'll go through and print the first sentence, then the second sentence over and over until one entity's health drops to zero.

From my research (bearing in mind I'm a knucklehead) the 'for' function seems to only work with single words/numbers... but perhaps I'm wrong.

CODE:

if sentence == 1:
  print ("The" + " " + enemy_1 + " " + random.choice(attack_verb) + " " + main_character + " " + "with its" + " " + random.choice(enemy_1_weapon))
  enemy_1_health -= 20
  print (enemy_1_health)
  sentence = 0

if sentence == 0:
  print (main_character + " " + random.choice(attack_verb) + " " + "the" + " " + enemy_1 + " " + "with his" + " " + random.choice(main_character_weapon))
  enemy_1_health -= 20
  print (enemy_1_health)
  sentence = 1

#And then repeat and repeat over and over :)

Body:
you could do something like this

while enemy_1_health > 0:
    if sentence == 1:
        print ("The" + " " + enemy_1 + " " + random.choice(attack_verb) + " " + main_character + " " + "with its" + " " + random.choice(enemy_1_weapon))
        enemy_1_health -= 20
        print(enemy_1_health)
        sentence = 0

    if sentence == 0:
        print (main_character + " " + random.choice(attack_verb) + " " + "the" + " " + enemy_1 + " " + "with his" + " " + random.choice(main_character_weapon))
        enemy_1_health -= 20
        print(enemy_1_health)
        sentence = 1


问:
adding item in to react state at certain position related to the item at hand?
How to update state array to add a value after related position rather than at the end of the array ? in the example below for example I want rice to go after rice rather than after bananas ? , this current logic is making thing really mixed when I want to render items according to what the user has selected to be the first item.

let stateArr = [{item : cucumber}, {item : rice }, {item: bannan }, {item : rice }]

// current state logic

[...stateArr, newItem ]```

答:
If you want to keep things immutable, you can slice your array at the point you want to insert the new item, and spread those two slices around your new value.

let stateArr = [
    { item: "cucumber" },
    { item: "rice" },
    { item: "bannan" },
    { item: "fish" },
];

// First, find the location of the item you want to insert _after_
const riceIndex = stateArr.findIndex(({ item }) => item === "rice");

const newItem = { item: "crab" };

// Next, slice _right after_ that item (+ 1)
const newState = [
    ...stateArr.slice(0, riceIndex + 1),
    newItem,
    ...stateArr.slice(riceIndex + 1),
];

console.log(newState);```


问:
Why sometimes snackbar is failing
Please help to explain why sometimes my SnackBar is showing an error. I don't understand at which circumstance the issue will come. I just want to point also that even though it is showing the error, in the app itself, it is working fine.

Here's my code:

```<code>void showFailedSnackBar(String s) {
    SnackBar snackBar = SnackBar(
      content: Text(s),
      duration: Duration(seconds: 3),
      backgroundColor: Theme.of(context).primaryColor,
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }
</code>```

Here's the error:

```<code>E/flutter ( 7879): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter ( 7879): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
</code>```

答:
https://velog.io/@namtaehyun/Flutter-This-widget-has-been-unmounted-so-the-State-no-longer-has-a-context

define global navigator context in main.dart, and use it everywhere

```<code>// main.dart

final navigatorKey = GlobalKey<NavigatorState>(); // define global key

void main() => runApp(
  MaterialApp(
    ...
    navigatorKey: navigatorKey, // propagate to all descendant contexts
  ),
);

// other.dart

void showMyDialog() {
  showDialog(
    context: navigatorKey.currentContext, // reference global context
    builder: (context) => ...
  );
}
</code>```

Title: Why sometimes snackbar is failing

Body:
Please help to explain why sometimes my SnackBar is showing an error. I don't understand at which circumstance the issue will come. I just want to point also that even though it is showing the error, in the app itself, it is working fine.

Here's my code:

void showFailedSnackBar(String s) {
    SnackBar snackBar = SnackBar(
      content: Text(s),
      duration: Duration(seconds: 3),
      backgroundColor: Theme.of(context).primaryColor,
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

Here's the error:

E/flutter ( 7879): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter ( 7879): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.

Body:
https://velog.io/@namtaehyun/Flutter-This-widget-has-been-unmounted-so-the-State-no-longer-has-a-context

define global navigator context in main.dart, and use it everywhere

// main.dart

final navigatorKey = GlobalKey<NavigatorState>(); // define global key

void main() => runApp(
  MaterialApp(
    ...
    navigatorKey: navigatorKey, // propagate to all descendant contexts
  ),
);

// other.dart

void showMyDialog() {
  showDialog(
    context: navigatorKey.currentContext, // reference global context
    builder: (context) => ...
  );
}