问:
DEPRECATION: c_args in the [properties] section of the machine file is deprecated, use the [built-in options] section
Here is cross-file example I use for cross compiling with meson build system. It is passed to meson with --cross-file option.

```<code>[host_machine]
system     = 'linux'
cpu_family = 'arm'
cpu        = ''
endian     = 'little'

[binaries]
c         = 'arm-linux-gnueabihf-cc'
cpp       = 'arm-linux-gnueabihf-g++'
ld        = 'arm-linux-gnueabihf-ld'
ar        = 'arm-linux-gnueabihf-ar'
strip     = 'arm-linux-gnueabihf-strip'
pkgconfig = 'pkg-config'

[properties]
c_args        = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-I/sysroot/usr/include']
cpp_args      = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-I/sysroot/usr/include']
c_link_args   = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-L/sysroot/lib', '-Wl,-rpath-link=/sysroot/staging/lib', '-L/sysroot/usr/lib', '-Wl,-rpath-link=/sysroot/usr/lib']
cpp_link_args = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-L/sysroot/lib', '-Wl,-rpath-link=/sysroot/staging/lib', '-L/sysroot/usr/lib', '-Wl,-rpath-link=/sysroot/usr/lib']
</code>```

It worked fine. But after upgrading meson to the newest version, I get the following warnings:

```<code>DEPRECATION: c_args in the [properties] section of the machine file is deprecated, use the [built-in options] section.
DEPRECATION: cpp_args in the [properties] section of the machine file is deprecated, use the [built-in options] section.
DEPRECATION: c_link_args in the [properties] section of the machine file is deprecated, use the [built-in options] section.
DEPRECATION: cpp_link_args in the [properties] section of the machine file is deprecated, use the [built-in options] section.
</code>```

How can I fix this?

答:
Just rename [properties] section to [built-in options]:

```<code>[built-in options]
c_args        = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-I/sysroot/usr/include']
cpp_args      = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-I/sysroot/usr/include']
c_link_args   = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-L/sysroot/lib', '-Wl,-rpath-link=/sysroot/staging/lib', '-L/sysroot/usr/lib', '-Wl,-rpath-link=/sysroot/usr/lib']
cpp_link_args = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-L/sysroot/lib', '-Wl,-rpath-link=/sysroot/staging/lib', '-L/sysroot/usr/lib', '-Wl,-rpath-link=/sysroot/usr/lib']
</code>```

https://mesonbuild.com/Machine-files.html

Changed in 0.56.0 putting <lang>_args and <lang>_link_args in the properties section has been deprecated, and should be put in the built-in options section.

Before 0.56.0, <lang>_args and <lang>_link_args must be put in the properties section instead, else they will be ignored.

Meson built-in options can be set the same way:

```<code>[built-in options]
c_std = 'c99'
</code>```

Body:
Here is cross-file example I use for cross compiling with meson build system. It is passed to meson with --cross-file option.

[host_machine]
system     = 'linux'
cpu_family = 'arm'
cpu        = ''
endian     = 'little'

[binaries]
c         = 'arm-linux-gnueabihf-cc'
cpp       = 'arm-linux-gnueabihf-g++'
ld        = 'arm-linux-gnueabihf-ld'
ar        = 'arm-linux-gnueabihf-ar'
strip     = 'arm-linux-gnueabihf-strip'
pkgconfig = 'pkg-config'

[properties]
c_args        = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-I/sysroot/usr/include']
cpp_args      = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-I/sysroot/usr/include']
c_link_args   = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-L/sysroot/lib', '-Wl,-rpath-link=/sysroot/staging/lib', '-L/sysroot/usr/lib', '-Wl,-rpath-link=/sysroot/usr/lib']
cpp_link_args = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-L/sysroot/lib', '-Wl,-rpath-link=/sysroot/staging/lib', '-L/sysroot/usr/lib', '-Wl,-rpath-link=/sysroot/usr/lib']

It worked fine. But after upgrading meson to the newest version, I get the following warnings:

DEPRECATION: c_args in the [properties] section of the machine file is deprecated, use the [built-in options] section.
DEPRECATION: cpp_args in the [properties] section of the machine file is deprecated, use the [built-in options] section.
DEPRECATION: c_link_args in the [properties] section of the machine file is deprecated, use the [built-in options] section.
DEPRECATION: cpp_link_args in the [properties] section of the machine file is deprecated, use the [built-in options] section.

How can I fix this?

Body:
Just rename [properties] section to [built-in options]:

[built-in options]
c_args        = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-I/sysroot/usr/include']
cpp_args      = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-I/sysroot/usr/include']
c_link_args   = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-L/sysroot/lib', '-Wl,-rpath-link=/sysroot/staging/lib', '-L/sysroot/usr/lib', '-Wl,-rpath-link=/sysroot/usr/lib']
cpp_link_args = ['-march=armv7-a', '-mtune=cortex-a9', '-mlittle-endian', '-L/sysroot/lib', '-Wl,-rpath-link=/sysroot/staging/lib', '-L/sysroot/usr/lib', '-Wl,-rpath-link=/sysroot/usr/lib']

https://mesonbuild.com/Machine-files.html

Changed in 0.56.0 putting <lang>_args and <lang>_link_args in the properties section has been deprecated, and should be put in the built-in options section.

Before 0.56.0, <lang>_args and <lang>_link_args must be put in the properties section instead, else they will be ignored.

Meson built-in options can be set the same way:

[built-in options]
c_std = 'c99'


来源: stackexchange

问:
Should I use a Prometheus Kubernetes SD config of Pod or Endpoint?
Prometheus supports multiple roles in its Kubernetes SD config

I'm confused about whether I should use a Pod config or a endpoints role for my Deployment + Service.

The service I am monitoring is a Deployment

apiVersion: apps/v1
kind: Deployment
spec:
 replicas: ~10
 strategy:
    rollingUpdate:
      maxSurge: 5
      maxUnavailable: 0
    type: RollingUpdate
 template:
  containers:
  - name: web-app
    ports:
    - containerPort: 3182
      name: http
    - containerPort: 6060
      name: metrics
```
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: Service
metadata:
  name: web-app
spec:
  ports:
  - name: http
    port: 3182
    targetPort: http
  selector:
    app: web-app
  type: ClusterIP
</code>```

The number of pods can vary in the deployment. The deployment is continuously being updated with new images.

I can add annotations or labels as needed to either of these YAML files.

Is there a reason to prefer either a Pod role or an Endpoints role?

答:
In short, there are two major differences:

an endpoints role gives you more data in labels (to which service a pod belongs, for example);

a pod role targets any pod out there and not just those belonging to a service.

What's best for you is for you to decide, but I suppose that an endpoints role would fit well for your production applications (all these usually have a corresponding service), and a pod role for everything else. Or you may do with just one pod role job  for everything and bring that extra information with the kube-state-metrics exporter.

ContentLicense: CC BY-SA 4.0

Body:
Prometheus supports multiple roles in its Kubernetes SD config

I'm confused about whether I should use a Pod config or a endpoints role for my Deployment + Service.

The service I am monitoring is a Deployment

apiVersion: apps/v1
kind: Deployment
spec:
 replicas: ~10
 strategy:
    rollingUpdate:
      maxSurge: 5
      maxUnavailable: 0
    type: RollingUpdate
 template:
  containers:
  - name: web-app
    ports:
    - containerPort: 3182
      name: http
    - containerPort: 6060
      name: metrics

apiVersion: v1
kind: Service
metadata:
  name: web-app
spec:
  ports:
  - name: http
    port: 3182
    targetPort: http
  selector:
    app: web-app
  type: ClusterIP

The number of pods can vary in the deployment. The deployment is continuously being updated with new images.

I can add annotations or labels as needed to either of these YAML files.

Is there a reason to prefer either a Pod role or an Endpoints role?


问:
Mysql order column by 2 values
i have the ff table

id
type
title

1
private
page 1

1
public
page 1

2
private
page 2

3
public
page 3

i want to group them by id and prioritize type "public" over "private"
so the output would be like this

id
type
title

1
public
page 1

2
private
page 2

3
public
page 3

答:
You can try to use condition aggregate function to make it, writing high prioritize type in the front which you want.

Query #1

```<code>SELECT id,title,MAX(CASE WHEN type = 'public' THEN 'public' ELSE 'private' END) type
FROM T
GROUP BY id,title;
</code>```

id
title
type

1
page 1
public

2
page 2
private

3
page 3
public

View on DB Fiddle

Title: Mysql order column by 2 values

Body:
You can try to use condition aggregate function to make it, writing high prioritize type in the front which you want.

Query #1

SELECT id,title,MAX(CASE WHEN type = 'public' THEN 'public' ELSE 'private' END) type
FROM T
GROUP BY id,title;

id
title
type

1
page 1
public

2
page 2
private

3
page 3
public

View on DB Fiddle


问:
How can I carry out a fit with errors on both axis with lmfit module in Python?
```<code>import lmfit
import numpy as np
import pandas as pd

def test_func(x, a, b):
   model = a* np.exp(-b*np.array(x))
   return model

df = pd.read_excel("esti.xlsx", usecols=["altezza", "err_altezza", "Icorrente", "err_I"])
x_var = df["altezza"].tolist()
x_err = df["err_altezza"].tolist()
y_var = df["Icorrente"].tolist()
y_err = df["err_I"].tolist()

mod = lmfit.Model(test_func)
pars = lmfit.Parameters()
pars.add('a', value=200)
pars.add('b', value=0)
result = mod.fit(y_var, x=x_var, params=pars, weights=y_err)
</code>```

Idk how to include the noise on the x-axis. Lmfit give me the opportunity only to add the errors on the y-axis with the command "weights=".
Do you know a way to work with noises on both axes using lmfit?

答:
lmfit does not directly support uncertainties in the independent variable.
Here's a long-winded explanation, then a suggested alternative:

Non-linear fitting problems don't necessarily have a single, well-defined "independent variable", but are thought of as a series of observations (say "y") that can be modelled, and seek to find a set of parameters for a model to match the data, most typically in the least-squares sense:

Find a set of values for parameters p in order to minimize

```<code>  Sum_i [(y_i - model(p, i))/eps_y_i]^2
</code>```

where i is the index of the observation, y_i is the observation, eps_y_i its uncertainty, and model is the function that models the observation in terms of the parameters p.

There sort of is not an x (or at least not always a single, well-defined x) there.  Indeed, the fitting algorithms typically do not require an x value.  When they take one, it is only to help the model function calculate the observation.  So, you could pass in an eps_x array along with x to your model function, and calculate a weighted model to best describe the observation at index i, but that is left as an exercise for the reader ;).

Anyway, that is why uncertainties in x are typically not handled, and in fact,  None of the codes in scipy. optimize or lmfit handle uncertainties in x.

Suggested Alternative:

However: there is scipy.odr which is sort of oddly in a separate module and with a sort of unusual interface.  This ODR approach can include uncertainties in x.  So, that might be worth looking into.  ODR is not supported in lmfit. That would take some real effort, but might be doable if someone was so motivated.

Body:
import lmfit
import numpy as np
import pandas as pd

def test_func(x, a, b):
   model = a* np.exp(-b*np.array(x))
   return model

df = pd.read_excel("esti.xlsx", usecols=["altezza", "err_altezza", "Icorrente", "err_I"])
x_var = df["altezza"].tolist()
x_err = df["err_altezza"].tolist()
y_var = df["Icorrente"].tolist()
y_err = df["err_I"].tolist()

mod = lmfit.Model(test_func)
pars = lmfit.Parameters()
pars.add('a', value=200)
pars.add('b', value=0)
result = mod.fit(y_var, x=x_var, params=pars, weights=y_err)

Idk how to include the noise on the x-axis. Lmfit give me the opportunity only to add the errors on the y-axis with the command "weights=".
Do you know a way to work with noises on both axes using lmfit?

Body:
lmfit does not directly support uncertainties in the independent variable.
Here's a long-winded explanation, then a suggested alternative:

Non-linear fitting problems don't necessarily have a single, well-defined "independent variable", but are thought of as a series of observations (say "y") that can be modelled, and seek to find a set of parameters for a model to match the data, most typically in the least-squares sense:

Find a set of values for parameters p in order to minimize

  Sum_i [(y_i - model(p, i))/eps_y_i]^2

where i is the index of the observation, y_i is the observation, eps_y_i its uncertainty, and model is the function that models the observation in terms of the parameters p.

There sort of is not an x (or at least not always a single, well-defined x) there.  Indeed, the fitting algorithms typically do not require an x value.  When they take one, it is only to help the model function calculate the observation.  So, you could pass in an eps_x array along with x to your model function, and calculate a weighted model to best describe the observation at index i, but that is left as an exercise for the reader ;).

Anyway, that is why uncertainties in x are typically not handled, and in fact,  None of the codes in scipy. optimize or lmfit handle uncertainties in x.

Suggested Alternative:

However: there is scipy.odr which is sort of oddly in a separate module and with a sort of unusual interface.  This ODR approach can include uncertainties in x.  So, that might be worth looking into.  ODR is not supported in lmfit. That would take some real effort, but might be doable if someone was so motivated.


问:
Live_helpers function usage in liveview app "live_beats" by chrismccord
There is a function sidebar_account_dropdown/1 in lib/live_beats_web/views/layout_view.ex

```<code>def sidebar_account_dropdown(assigns) do
    ~H"""
    <.dropdown id={@id}>
      <:img src={@current_user.avatar_url}/>
      <:title><%= @current_user.name %></:title>
      <:subtitle>@<%= @current_user.username %></:subtitle>

      <:link navigate={profile_path(@current_user)}>View Profile</:link>
      <:link navigate={Routes.settings_path(Endpoint, :edit)}>Settings</:link>
      <:link href={Routes.o_auth_callback_path(Endpoint, :sign_out)} method={:delete}>Sign out</:link>
    </.dropdown>
    """
end
</code>```

And in its template part dropdown function from lib/live_beats_web/live/live_helpers.ex

```<code>def dropdown(assigns) do
    assigns =
      assigns
      |> assign_new(:img, fn -> nil end)
      |> assign_new(:title, fn -> nil end)
      |> assign_new(:subtitle, fn -> nil end)

    ~H"""
    <!-- User account dropdown -->
    <div class="px-3 mt-6 relative inline-block text-left">
</code>```

just not to elongate things I cutted the long dropdown function
dropdown/1

I would like to know how the html tags are replaced with atoms.
Is it used as a means for assigning value to the :img, :title, :subtitle,  etc that exist in our assigns as nil or something.
I would love to understand this clearly

答:
Phoenix Liveview defines its own engine for sigil_H/1.

The engine has its own tokenizer which understands <. opening, treats is as a slot and processes further.

Body:
There is a function sidebar_account_dropdown/1 in lib/live_beats_web/views/layout_view.ex

def sidebar_account_dropdown(assigns) do
    ~H"""
    <.dropdown id={@id}>
      <:img src={@current_user.avatar_url}/>
      <:title><%= @current_user.name %></:title>
      <:subtitle>@<%= @current_user.username %></:subtitle>

      <:link navigate={profile_path(@current_user)}>View Profile</:link>
      <:link navigate={Routes.settings_path(Endpoint, :edit)}>Settings</:link>
      <:link href={Routes.o_auth_callback_path(Endpoint, :sign_out)} method={:delete}>Sign out</:link>
    </.dropdown>
    """
end

And in its template part dropdown function from lib/live_beats_web/live/live_helpers.ex

def dropdown(assigns) do
    assigns =
      assigns
      |> assign_new(:img, fn -> nil end)
      |> assign_new(:title, fn -> nil end)
      |> assign_new(:subtitle, fn -> nil end)

    ~H"""

just not to elongate things I cutted the long dropdown function
dropdown/1

I would like to know how the html tags are replaced with atoms.
Is it used as a means for assigning value to the :img, :title, :subtitle,  etc that exist in our assigns as nil or something.
I would love to understand this clearly


问:
how to get value of more than one text box in a loop
I have some text boxes in my page. I want to get all text box values in an array and insert in to table of database.

Is there any option to work by loop

答:
```<code>public IEnumerable<string> AllTextsFromTextboxes()
{
    foreach (var control in Page.Controls.OfType<TextBox>())
    {
        yield return control.Text;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0


问:
Unable to fetch data from third party api in NestJs showing Error 412
I am trying to post data to some third party API I have added authkey correctly in my request headers but when I am making request its showing below error:

```<code> ERROR [ExceptionsHandler] Request failed with status code 412
</code>```

Below is my Postman configuration for making Postman request:

Below is my code:

subscribe.controller.ts

```<code>@Controller()
export class SubscribeController {
constructor(private subscribeService:SubscribeService){}

@Post('location')
async getLocation(@Body('phoneNumber') phoneNumber:string){

    const loc = await this.subscribeService.getLocation(phoneNumber);
    return loc;
  }
}
</code>```

subscribe.service.ts

```<code>@Injectable()
export class SubscribeService {
constructor(@InjectModel('Subscribe') private readonly model:Model<Subscribe>,
            private httpService: HttpService){}

    async getLocation(phoneNumber:string){

    const data = {phoneNumber};

    const url = 'https://example.com';
    const headersRequest = {
      'Content-Type': 'application/json',
      'authkey': 'xxxxxxxxxxxx'
    };

      const resp = await this.httpService.post(url,data,{ headers: headersRequest }).pipe(
        map((response) => {
          return response.data;
        })
      );

      return resp;
   }
}
</code>```

What am I doing wrong?

答:
Also I would suggest you send body like this
Create following DTO class

```<code>    export class PhoneNumber
    {
    phoneNumber:string
    }
</code>```

Then, type with your API/controlloer

```<code>  @Post('location')
async getLocation(@Body() phoneNumberBody:PhoneNumber,
 @Headers('authkey') authkey:string)){

    const loc = await this.subscribeService.getLocation(phoneNumberBody,authkey);
    return loc;
  }
}
</code>```

Update the service to send body,

```<code>@Injectable()
export class SubscribeService {
    constructor(@InjectModel('Subscribe') private readonly model:Model<Subscribe>,
                private httpService: HttpService){}

    async getLocation(phoneNumber:PhoneNumber,authkey:string){

        const url = 'https://example.com';
        const headersRequest = {
            'Content-Type': 'application/json',
            'authkey': authkey
        };

        const resp = await this.httpService.post(url,phoneNumber,{ headers: headersRequest }).pipe(
            map((response) => {
                return response.data;
            })
        );

        return resp;
    }
}
</code>```

To make sure you are sending body in correct format, try to console.log(phoneNumber); in service call

Another thing we can try ot use axios request if that does not work

```<code>  const resp = await axios.post('https:<your-url>',phoneNumber,{headers:{
            'Content-Type': 'application/json',
            'authkey': authkey
        }});

        console.log(resp.data);
     }
     catch(err){
         console.log(err);
     }
</code>```

Body:
I am trying to post data to some third party API I have added authkey correctly in my request headers but when I am making request its showing below error:

 ERROR [ExceptionsHandler] Request failed with status code 412

Below is my Postman configuration for making Postman request:

Below is my code:

subscribe.controller.ts

@Controller()
export class SubscribeController {
constructor(private subscribeService:SubscribeService){}

@Post('location')
async getLocation(@Body('phoneNumber') phoneNumber:string){

    const loc = await this.subscribeService.getLocation(phoneNumber);
    return loc;
  }
}

subscribe.service.ts

@Injectable()
export class SubscribeService {
constructor(@InjectModel('Subscribe') private readonly model:Model<Subscribe>,
            private httpService: HttpService){}

    async getLocation(phoneNumber:string){

    const data = {phoneNumber};

    const url = 'https://example.com';
    const headersRequest = {
      'Content-Type': 'application/json',
      'authkey': 'xxxxxxxxxxxx'
    };

      const resp = await this.httpService.post(url,data,{ headers: headersRequest }).pipe(
        map((response) => {
          return response.data;
        })
      );

      return resp;
   }
}

What am I doing wrong?

Body:
Also I would suggest you send body like this
Create following DTO class

    export class PhoneNumber
    {
    phoneNumber:string
    }

Then, type with your API/controlloer

  @Post('location')
async getLocation(@Body() phoneNumberBody:PhoneNumber,
 @Headers('authkey') authkey:string)){

    const loc = await this.subscribeService.getLocation(phoneNumberBody,authkey);
    return loc;
  }
}

Update the service to send body,

@Injectable()
export class SubscribeService {
    constructor(@InjectModel('Subscribe') private readonly model:Model<Subscribe>,
                private httpService: HttpService){}

    async getLocation(phoneNumber:PhoneNumber,authkey:string){

        const url = 'https://example.com';
        const headersRequest = {
            'Content-Type': 'application/json',
            'authkey': authkey
        };

        const resp = await this.httpService.post(url,phoneNumber,{ headers: headersRequest }).pipe(
            map((response) => {
                return response.data;
            })
        );

        return resp;
    }
}

To make sure you are sending body in correct format, try to console.log(phoneNumber); in service call

Another thing we can try ot use axios request if that does not work

  const resp = await axios.post('https:<your-url>',phoneNumber,{headers:{
            'Content-Type': 'application/json',
            'authkey': authkey
        }});

        console.log(resp.data);
     }
     catch(err){
         console.log(err);
     }


问:
How do I add a URL to R markdown?
I want to refer a URL link to the R markdown and I already tried the input such as "addlink"
or "address <- ...."
Both of them do not work.
How can I add a link in R markdown?

Thanks!

EDIT: op's code from comment was

```<code>   {r} [linked phrase] (www.bit.ly/1EqAdIp)
</code>```

答:
You can try this code to add a url which represent the topic.

```<code>[ggrepel](https://github.com/slowkow/ggrepel)
</code>```

That is:

```<code>[topic](url)
</code>```

Title: How do I add a URL to R markdown?

Body:
I want to refer a URL link to the R markdown and I already tried the input such as "addlink"
or "address <- ...."
Both of them do not work.
How can I add a link in R markdown?

Thanks!

EDIT: op's code from comment was

   {r} [linked phrase] (www.bit.ly/1EqAdIp)

Body:
You can try this code to add a url which represent the topic.

[ggrepel](https://github.com/slowkow/ggrepel)

That is:

[topic](url)


问:
#Error in SQL while updating table using join
I got an error while updating the table with the join query. The error message is:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from employee details join employeedept on employee details.emp_dept=employeedept.' at line 3

Can anyone help me to resolve this error?

```<code>update employeeDetails
set employeeDetails.emp_age = employeeDetails.emp_age+20, employeeDetails.emp_salary = employeeDetails.emp_salary-500
from employeeDetails
join employeedept on employeeDetails.emp_dept = employeedept.dept_name
where employeedept.dept_name = 'CSE';
select * from employeeDetails;
</code>```

List item

答:
Have you tried using MySQL's UPDATE JOIN syntax yet? e.g.:

update employeeDetails
join employeeDept on employeeDetails.emp_dept = employeeDept.dept_name
set
  employeeDetails.emp_age = employeeDetails.emp_age+20,
  employeeDetails.emp_salary = employeeDetails.emp_salary-500
where employeeDept.dept_name = 'CSE';

select * from employeeDetails;
```

Body:
I got an error while updating the table with the join query. The error message is:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from employee details join employeedept on employee details.emp_dept=employeedept.' at line 3

Can anyone help me to resolve this error?

update employeeDetails
set employeeDetails.emp_age = employeeDetails.emp_age+20, employeeDetails.emp_salary = employeeDetails.emp_salary-500
from employeeDetails
join employeedept on employeeDetails.emp_dept = employeedept.dept_name
where employeedept.dept_name = 'CSE';
select * from employeeDetails;

List item


问:
How to show utf-8 decoded value in vuejs?
Requirement:
To decode data of utf8  K& #2446;Ler which is possible by v-html attribute in vuejs

Problem:
Don't know how to pass displayFullUserName to data-tooltip which holds value Armin K& #2446;Ler so that it will reflect Armin Koler in grey layout.

Finding
The below image shows gibberish data K& #2446;Ler, since it is not rendered by v-html.
I have a data-tooltip property which shown below as grey over tooltip view.
Now, I don't know how to fix this as actual text rendered above was by v-html tag.

```<code> <label
   v-bind:data-tooltip="displayFullUserName"
   v-html="displayFullUserName"
 />

computed() {
return this.displayFullUserName;
}
</code>```

答:
It worked with below solution

```<code>htmlEntity2utf8(s) {
 const t= document.createElement('span'); t.innerHTML = s;
 return t.textContent
}
</code>```

thanks @Bravo for this.

Body:
Requirement:
To decode data of utf8  K& #2446;Ler which is possible by v-html attribute in vuejs

Problem:
Don't know how to pass displayFullUserName to data-tooltip which holds value Armin K& #2446;Ler so that it will reflect Armin Koler in grey layout.

Finding
The below image shows gibberish data K& #2446;Ler, since it is not rendered by v-html.
I have a data-tooltip property which shown below as grey over tooltip view.
Now, I don't know how to fix this as actual text rendered above was by v-html tag.

computed() {
return this.displayFullUserName;
}

Body:
It worked with below solution

htmlEntity2utf8(s) {
 const t= document.createElement('span'); t.innerHTML = s;
 return t.textContent
}

thanks @Bravo for this.


问:
Accent insensitive in filter backend to datatable in ASP.NET MVC 5
I made a method on the back-end side to handle the filter of my datatable.

On the other hand, this one does not manage the accents of the French language, so if I have "école" and I write "ecole" it cannot find it.

I found this method on another question on stackoverflow

```<code>public static String RemoveDiacritics(this String s)
{
    String normalizedString = s.Normalize(NormalizationForm.FormD);
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < normalizedString.Length; i++)
    {
        Char c = normalizedString[i];

        if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
</code>```

and it works, but only for part of my problem. It works on the letter or the word that is written in the search, but I am not able to apply it in my linq query, so with the .RemoveDiacritics() method my "école" becomes "ecole", but I don't am not able to apply it in the column of my table and it always looks for "école".

Here the code for the search:

```<code>if (search != null)
{
    int n;
    search = search.Trim();

    var isNumeric = int.TryParse(search, out n);

    if (isNumeric)
    {
        IdFilter = n;
        query = query.Where(x => x.UsagerId == IdFilter || x.Niveau == IdFilter);
    }
    else if (search != "")
    {
        // this line work
        textFilter = search.ToLower().RemoveDiacritics();
        // This is the full line, but absolutely takes the accents out to get the right information out
        // query = query.Where(x => x.Nom.ToLower().Contains(textFilter) || x.Prenom.ToLower().Contains(textFilter) || x.Username.ToLower().Contains(textFilter) || x.Email.ToLower().Contains(textFilter) || x.EtabNom.ToLower().Contains(textFilter) || x.ActifStatut.ToLower().Contains(textFilter));

        // This is the line that will replace the line above, which I try and it doesn't work ( this part: x.Prenom.ToLower().RemoveDiacritics())
        query = query.Where(x => x.Prenom.ToLower().RemoveDiacritics().Contains(textFilter));
    }
}
</code>```

This is the basic query:

```<code>IQueryable<ListeUsagers> query = (from u in db.USAGERs
                             join e in db.ETABLISSEMENTs on u.USAGER_INST equals e.ETAB_CODE
                             where u.USAGER_INST == instId && u.USAGER_NIVEAU > 3 && u.USAGER_NIVEAU < 5 //&& u.USAGER_ACTIF == 1
                             select new ListeUsagers()
                             {
                                 UsagerId = u.USAGER_id,
                                 Nom = u.USAGER_NOM,
                                 Prenom = u.USAGER_PRENOM,
                                 EtabCode = e.ETAB_CODE,
                                 EtabNom = e.ETAB_NOM_COURT,
                                 EtabType = e.ETAB_TYPE,
                                 Niveau = u.USAGER_NIVEAU,
                                 Username = u.USAGER_USERNAME,
                                 UserPassword = u.USAGER_MP,
                                 DateCreation = u.USAGER_DATE_INSC,
                                 Sexe = u.USAGER_SEXE,
                                 Lang = u.USAGER_LANGUE,
                                 Telephone = u.USAGER_TELEPHONE,
                                 Email = u.USAGER_EMAIL,
                                 FonctionTravail = u.USAGER_FONCTION,
                                 LieuTravail = u.USAGER_LIEUTRAVAIL,
                                 Note = u.USAGER_NOTE,
                                 Actif = u.USAGER_ACTIF,
                                 ActifStatut = u.USAGER_ACTIF == 0 ? "Inactif" : "Actif"
                             });
</code>```

This is the error:

LINQ to Entities does not recognize the method 'System.String RemoveDiacritics(System.String)' method, and this method cannot be translated into a store expression.

答:
There's built-in functionality to do this in entityframework: https://learn.microsoft.com/en-us/ef/core/miscellaneous/collations-and-case-sensitivity if you're using EF 5+

You'll want an accent insensitive collation  ("AI", not "AS" in the examples on that page.)

Body:
I made a method on the back-end side to handle the filter of my datatable.

On the other hand, this one does not manage the accents of the French language, so if I have "école" and I write "ecole" it cannot find it.

I found this method on another question on stackoverflow

public static String RemoveDiacritics(this String s)
{
    String normalizedString = s.Normalize(NormalizationForm.FormD);
    StringBuilder stringBuilder = new StringBuilder();

    for (int i = 0; i < normalizedString.Length; i++)
    {
        Char c = normalizedString[i];

        if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}

and it works, but only for part of my problem. It works on the letter or the word that is written in the search, but I am not able to apply it in my linq query, so with the .RemoveDiacritics() method my "école" becomes "ecole", but I don't am not able to apply it in the column of my table and it always looks for "école".

Here the code for the search:

if (search != null)
{
    int n;
    search = search.Trim();

    var isNumeric = int.TryParse(search, out n);

    if (isNumeric)
    {
        IdFilter = n;
        query = query.Where(x => x.UsagerId == IdFilter || x.Niveau == IdFilter);
    }
    else if (search != "")
    {
        // this line work
        textFilter = search.ToLower().RemoveDiacritics();
        // This is the full line, but absolutely takes the accents out to get the right information out
        // query = query.Where(x => x.Nom.ToLower().Contains(textFilter) || x.Prenom.ToLower().Contains(textFilter) || x.Username.ToLower().Contains(textFilter) || x.Email.ToLower().Contains(textFilter) || x.EtabNom.ToLower().Contains(textFilter) || x.ActifStatut.ToLower().Contains(textFilter));

        // This is the line that will replace the line above, which I try and it doesn't work ( this part: x.Prenom.ToLower().RemoveDiacritics())
        query = query.Where(x => x.Prenom.ToLower().RemoveDiacritics().Contains(textFilter));
    }
}

This is the basic query:

IQueryable<ListeUsagers> query = (from u in db.USAGERs
                             join e in db.ETABLISSEMENTs on u.USAGER_INST equals e.ETAB_CODE
                             where u.USAGER_INST == instId && u.USAGER_NIVEAU > 3 && u.USAGER_NIVEAU < 5 //&& u.USAGER_ACTIF == 1
                             select new ListeUsagers()
                             {
                                 UsagerId = u.USAGER_id,
                                 Nom = u.USAGER_NOM,
                                 Prenom = u.USAGER_PRENOM,
                                 EtabCode = e.ETAB_CODE,
                                 EtabNom = e.ETAB_NOM_COURT,
                                 EtabType = e.ETAB_TYPE,
                                 Niveau = u.USAGER_NIVEAU,
                                 Username = u.USAGER_USERNAME,
                                 UserPassword = u.USAGER_MP,
                                 DateCreation = u.USAGER_DATE_INSC,
                                 Sexe = u.USAGER_SEXE,
                                 Lang = u.USAGER_LANGUE,
                                 Telephone = u.USAGER_TELEPHONE,
                                 Email = u.USAGER_EMAIL,
                                 FonctionTravail = u.USAGER_FONCTION,
                                 LieuTravail = u.USAGER_LIEUTRAVAIL,
                                 Note = u.USAGER_NOTE,
                                 Actif = u.USAGER_ACTIF,
                                 ActifStatut = u.USAGER_ACTIF == 0 ? "Inactif" : "Actif"
                             });

This is the error:

LINQ to Entities does not recognize the method 'System.String RemoveDiacritics(System.String)' method, and this method cannot be translated into a store expression.


问:
C++ signal to QML slot in Qt
I want to send a Signal from C++ to a Slot in my QML File.
I already got it working without and primitive type parameters, although if I want to send a QString to my QML Slot I get an error whilst connecting.

I connect in main.cpp

```<code>QObject *contentView = rootObject->findChild<QObject*>(QString("contentView"));
QObject::connect(&myObj,      SIGNAL(finishedGatheringDataForItem(QString)),
                 contentView, SLOT(updateViewWithItem(QString)));
</code>```

the relavant part of my qml File

```<code>Rectangle {
        objectName: "contentView"
        function updateViewWithItem(string) { console.log('got some Items'); }  // slot
}
</code>```

Error:

```<code>Object::connect: No such slot QDeclarativeRectangle_QML_2::updateViewWithItem(QString)
</code>```

答:
For those who also stumbled upon this question, I want to say that Everything is much simpler. You just need the signal from C++ to have QVariant arguments. For example:

```<code>QObject::connect(&recipient, SIGNAL(resTalk(QVariant)), engine.rootObjects().at(0)->findChild<QObject*>("winSettings"),
                     SLOT(showWithErrorNetwork(QVariant)));
</code>```

My signal is declared like this:

```<code>signals:
    void resTalk(QVariant res);
</code>```

So I'm calling the signal:

```<code>emit resTalk(true); //For more complex types, use  'emit yourSignal(QVariant(yourArg))'
</code>```

And here is the slot I have in QML:

```<code>    function showWithErrorNetwork(isNoError=false) {
        if(!isNoError) {
            visible = true
            warningText.text = "Network error. Check the data."
            warningText.visible = true
        }
    }
</code>```

Title: C++ signal to QML slot in Qt

Body:
I want to send a Signal from C++ to a Slot in my QML File.
I already got it working without and primitive type parameters, although if I want to send a QString to my QML Slot I get an error whilst connecting.

I connect in main.cpp

QObject *contentView = rootObject->findChild<QObject*>(QString("contentView"));
QObject::connect(&myObj,      SIGNAL(finishedGatheringDataForItem(QString)),
                 contentView, SLOT(updateViewWithItem(QString)));

the relavant part of my qml File

Rectangle {
        objectName: "contentView"
        function updateViewWithItem(string) { console.log('got some Items'); }  // slot
}

Error:

Object::connect: No such slot QDeclarativeRectangle_QML_2::updateViewWithItem(QString)

Body:
For those who also stumbled upon this question, I want to say that Everything is much simpler. You just need the signal from C++ to have QVariant arguments. For example:

QObject::connect(&recipient, SIGNAL(resTalk(QVariant)), engine.rootObjects().at(0)->findChild<QObject*>("winSettings"),
                     SLOT(showWithErrorNetwork(QVariant)));

My signal is declared like this:

signals:
    void resTalk(QVariant res);

So I'm calling the signal:

emit resTalk(true); //For more complex types, use  'emit yourSignal(QVariant(yourArg))'

And here is the slot I have in QML:

    function showWithErrorNetwork(isNoError=false) {
        if(!isNoError) {
            visible = true
            warningText.text = "Network error. Check the data."
            warningText.visible = true
        }
    }


问:
How to get relative path of a file in visual studio?
I am trying to get the path of an image file which I added in solution explorer in Visual Studio, but I couldn't get the relative path of that image. H is the file structure of my project:

```
/BulutDepoProject
    /FolderIcon
        Folder.ico
        Main.cs
```

I can get the image like this :

```<code>"C:\\Users\\Tolga\\Desktop\\BulutDepo\\BulutDepoProject\\FolderIcon\\Folder.ico"
</code>```

But I should be able to get it with something like :

```<code>"~\\FolderIcon\\Folder.ico"
</code>```

I guess I don't know the exact syntax of it so I cant fetch the image. :(

答:
My folder was at the root of my project and I used this:</p>
```<code>string sCurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

string sFile = System.IO.Path.Combine(sCurrentDirectory, @"libs\cat");

string sFilePath = Path.GetFullPath(sFile);
</code>```

Body:
I am trying to get the path of an image file which I added in solution explorer in Visual Studio, but I couldn't get the relative path of that image. H is the file structure of my project:

/BulutDepoProject
    /FolderIcon
        Folder.ico
        Main.cs

I can get the image like this :

"C:\\Users\\Tolga\\Desktop\\BulutDepo\\BulutDepoProject\\FolderIcon\\Folder.ico"

But I should be able to get it with something like :

"~\\FolderIcon\\Folder.ico"

I guess I don't know the exact syntax of it so I cant fetch the image. :(

Body:
My folder was at the root of my project and I used this:

string sCurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

string sFile = System.IO.Path.Combine(sCurrentDirectory, @"libs\cat");

string sFilePath = Path.GetFullPath(sFile);


问:
Is there a better dependency injection pattern in golang?
Given this code:

```<code>package main

import (
    "fmt"
)

type datstr string

type Guy interface {
   SomeDumbGuy() string
}

func (d *datstr) SomeDumbGuy() string {
  return "some guy"
}

func someConsumer(g Guy) {
  fmt.Println("Hello, " + g.SomeDumbGuy())
}

func main() {
    var d datstr
    someConsumer(&d)
}
</code>```

Is the wiring of components together that's done in main the right way to wire a dependency together?  It seems like I'm over using this a bit in my code.  Is there a common pattern better than this, or am I overthinking it?

答:
You can also check Uber's fx for a more general application framework. It uses Uber's dig under the hood as  @yndolok has already mentioned.

fx github link: https://github.com/uber-go/fx

Body:
Given this code:

package main

import (
    "fmt"
)

type datstr string

type Guy interface {
   SomeDumbGuy() string
}

func (d *datstr) SomeDumbGuy() string {
  return "some guy"
}

func someConsumer(g Guy) {
  fmt.Println("Hello, " + g.SomeDumbGuy())
}

func main() {
    var d datstr
    someConsumer(&d)
}

Is the wiring of components together that's done in main the right way to wire a dependency together?  It seems like I'm over using this a bit in my code.  Is there a common pattern better than this, or am I overthinking it?


问:
Terraform create multiple ec2 instances in multiple subnets
I am trying to create multiple ec2 instances with access to multiple subnets.

I've found questions and answers on doing these things individually, but not combined.

First, I create a private and a public subnet, then I setup a local to store the IDs once they are created:

```<code>locals {
  subnets =  [ aws_subnet.public_subnet.id, aws_subnet.private_subnet.id ]
}
</code>```

Next, I can create a variable number of servers in the private_subnet using for_each and the below:

```<code>servers = [ "s1", "s2" ]
resource "aws_instance" "system" {
  for_each                    = var.servers
  ami                         = var.aws_ami
  instance_type               = var.instance_type
  #subnet_id                  = aws_subnet.private_subnet.id
  count = 2
  subnet_id                   = element(local.subs, count.index)
}
</code>```

What I want to have, is that the server can access both subnets (it doesn't exist as far as I can tell, but the equivalent of subnet_ids = [aws_subnet.public_subnet.id, aws_subnet.private_subnet.id]).

I found a nice answer which works for a specific instance by creating two NICs (Terraform one EC2 instance with two subnets), however I need to do this var.servers times so it's difficult to hardcode the var.servers * 2 NICs with my current aws_instance setup (and I trip up when combining for_each and count).

Can someone please point me in the right direction?

答:
Two create multiple servers (in your case 4 in total) in private (two servers) and public (two servers) subnets you can use count:

```<code>resource "aws_instance" "system" {
  count                    = length(var.servers) * length(local.subnets)
  ami                         = var.aws_ami
  instance_type               = var.instance_type
  subnet_id                   = element(local.subnets, count.index)
}
</code>```

Body:
I am trying to create multiple ec2 instances with access to multiple subnets.

I've found questions and answers on doing these things individually, but not combined.

First, I create a private and a public subnet, then I setup a local to store the IDs once they are created:

locals {
  subnets =  [ aws_subnet.public_subnet.id, aws_subnet.private_subnet.id ]
}

Next, I can create a variable number of servers in the private_subnet using for_each and the below:

servers = [ "s1", "s2" ]
resource "aws_instance" "system" {
  for_each                    = var.servers
  ami                         = var.aws_ami
  instance_type               = var.instance_type
  #subnet_id                  = aws_subnet.private_subnet.id
  count = 2
  subnet_id                   = element(local.subs, count.index)
}

What I want to have, is that the server can access both subnets (it doesn't exist as far as I can tell, but the equivalent of subnet_ids = [aws_subnet.public_subnet.id, aws_subnet.private_subnet.id]).

I found a nice answer which works for a specific instance by creating two NICs (Terraform one EC2 instance with two subnets), however I need to do this var.servers times so it's difficult to hardcode the var.servers * 2 NICs with my current aws_instance setup (and I trip up when combining for_each and count).

Can someone please point me in the right direction?

Body:
Two create multiple servers (in your case 4 in total) in private (two servers) and public (two servers) subnets you can use count:

resource "aws_instance" "system" {
  count                    = length(var.servers) * length(local.subnets)
  ami                         = var.aws_ami
  instance_type               = var.instance_type
  subnet_id                   = element(local.subnets, count.index)
}


问:
how to share instance variable between class methods in objective c
So I was building a flutter native plugin. I have two method (in xyzPlugin.m) which looks like this

```<code>+ (void)registerWithRegistrar:(nonnull NSObject<FlutterPluginRegistrar> *)registrar {
</code>```

and

```<code>- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
</code>```

Now, I want to share instance variable between both of them.

Suppose. I initialize meetingView like this inside registerWithRegistrar

```<code> MeetingView *meetingView = [MeetingView new];
</code>```

How can I use the same in handleMethodCall?

What have I tried?

```<code>@implementation xyzPlugin {
    MeetingView *_view;
}
</code>```

and then in

```<code>- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    _view = [MeetingView new];
</code>```

but this gives following error

Instance variable '_view' accessed in class method

答:
Maybe you need a global variable, so you can claim your object with a static keyword like:

```<code>static MeetingView *_meetingView = ...
</code>```

then you can access this object in between class methods in Objective-C.

Body:
So I was building a flutter native plugin. I have two method (in xyzPlugin.m) which looks like this

+ (void)registerWithRegistrar:(nonnull NSObject<FlutterPluginRegistrar> *)registrar {

and

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {

Now, I want to share instance variable between both of them.

Suppose. I initialize meetingView like this inside registerWithRegistrar

 MeetingView *meetingView = [MeetingView new];

How can I use the same in handleMethodCall?

What have I tried?

@implementation xyzPlugin {
    MeetingView *_view;
}

and then in

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    _view = [MeetingView new];

but this gives following error

Instance variable '_view' accessed in class method

Body:
Maybe you need a global variable, so you can claim your object with a static keyword like:

static MeetingView *_meetingView = ...

then you can access this object in between class methods in Objective-C.


问:
How to create a modal bottomsheet with circular corners in Flutter?
showModalBottomSheet does not provide any styling or decorations. I want to create something like the Google Tasks bottomsheet.

答:
```<code>showModalBottomSheet(
  context:context
  shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(20),
        ),
      ),
  clipBehavior: Clip.hardEdge,
)
</code>```

It will be much better to use Clip.hardEdge. As it is faster than other clipping modes but slower than [none].

Body:
showModalBottomSheet(
  context:context
  shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(20),
        ),
      ),
  clipBehavior: Clip.hardEdge,
)

It will be much better to use Clip.hardEdge. As it is faster than other clipping modes but slower than [none].


问:
When is a class template depending on a incomplete type as a template argument instantiated?
```<code>class I;

template<class T>
struct P
{
    T t;
};

template<class T>
struct F
{
    operator bool() {return false;}
};

int main()
{
    int a = F<P<I>>();
    int b = !F<P<I>>();
    int c = int(F<P<I>>());
    int d = !int(F<P<I>>());
}
</code>```

Are the evaluations in the initializers above well-formed? Why or why not? Which rules in the standard mandate the behavior?

答:
Specializations are instantiated only if a complete type is required or affects the semantics in the given context. [temp.inst]/2

So the default behavior is not to do any implicit instantiation if not necessary.

In all the cases you have shown, the specializations of F need to be instantiated because T() requires T to be complete. However, nothing in the instantiation of F<P> requires P to be complete, so it will not be instantiated with it.

None of the conversions to int require P to be complete either and so the initializations of a, c and d don't cause any instantiation of P at all and they are well-formed.

However, for b the situation is a bit different. In order to determine which operator! overload to call, unqualified name lookup and argument-dependent name lookup of operator! is done.

Argument-dependent lookup looks for operator! declarations in multiple scopes related to the type F<P>.

First, for F itself, it includes F's class scope and the enclosing namespace scope, meaning the global scope. However, secondly, it also includes the class- and enclosing namespace scope of types in the template arguments of the type, meaning that it includes P's class scope as well.

In order to determine whether there is an operator! overload in P, it must be instantiated. While instantiating P the declaration T t; is also instantiated as I t;, which requires I to be complete, but which it isn't, making the initialization of b ill-formed.

However [temp.inst]/9 allows, but doesn't require, the instantiation to be skipped if it isn't needed to determine the result of overload resolution. I am not sure how wide this permission is supposed to be interpreted, but if it does apply here, then it is unspecified whether instantiation of P for the initialization of b happens.

Body:
class I;

template<class T>
struct P
{
    T t;
};

template<class T>
struct F
{
    operator bool() {return false;}
};

int main()
{
    int a = F<P>();
    int b = !F<P>();
    int c = int(F<P>());
    int d = !int(F<P>());
}

Are the evaluations in the initializers above well-formed? Why or why not? Which rules in the standard mandate the behavior?

Body:
Specializations are instantiated only if a complete type is required or affects the semantics in the given context. [temp.inst]/2

So the default behavior is not to do any implicit instantiation if not necessary.

In all the cases you have shown, the specializations of F need to be instantiated because T() requires T to be complete. However, nothing in the instantiation of F<P<I>> requires P<I> to be complete, so it will not be instantiated with it.

None of the conversions to int require P<I> to be complete either and so the initializations of a, c and d don't cause any instantiation of P<I> at all and they are well-formed.

However, for b the situation is a bit different. In order to determine which operator! overload to call, unqualified name lookup and argument-dependent name lookup of operator! is done.

Argument-dependent lookup looks for operator! declarations in multiple scopes related to the type F<P<I>>.

First, for F itself, it includes F's class scope and the enclosing namespace scope, meaning the global scope. However, secondly, it also includes the class- and enclosing namespace scope of types in the template arguments of the type, meaning that it includes P<I>'s class scope as well.

In order to determine whether there is an operator! overload in P<I>, it must be instantiated. While instantiating P<I> the declaration T t; is also instantiated as I t;, which requires I to be complete, but which it isn't, making the initialization of b ill-formed.

However [temp.inst]/9 allows, but doesn't require, the instantiation to be skipped if it isn't needed to determine the result of overload resolution. I am not sure how wide this permission is supposed to be interpreted, but if it does apply here, then it is unspecified whether instantiation of P<I> for the initialization of b happens.


问:
Calling powershell function in batch script
Hoping someone can point me in the right direction. Have a working remote PC info scanning tool that collects computer name, serial number and model. Been trying to get the monitor info added for so time and found this Powershell script and have been trying to get intergraded without success.

Powershell function;

```<code>      $Monitors = Get-WmiObject WmiMonitorID -Namespace root\wmi
 $LogFile = ".\MonInfo.csv"

 function Decode {
     If ($args[0] -is [System.Array]) {
         [System.Text.Encoding]::ASCII.GetString($args[0])
     }
     Else {
         "Not Found"
     }
 }

 ForEach ($Monitor in $Monitors) {
     $Manufacturer = Decode $Monitor.ManufacturerName -notmatch 0
     $Name = Decode $Monitor.UserFriendlyName -notmatch 0
     $Serial = Decode $Monitor.SerialNumberID -notmatch 0

     echo  $Manufacturer, $Name, $Serial" >> $LogFile
 }
</code>```

Here's the network scan batch script I been using. (Basic info scan via ping and get info from remoter systems via WMI)

```<code>    @echo off
cls
color 5f

setlocal EnableDelayedExpansion

net session >nul 2>&1
if %errorlevel% neq 0 set errormsg=This program must be run as Administrator& goto ERRORDISP

set "ip="
for /f "tokens=2 delims=:" %%a in ('ipconfig ^| findstr /c:"IPv4 Address"') do set ip=%%a
if not defined ip (set errormsg=No IP address detected - check network cable& goto ERRORDISP)
set ip=%ip: =%
for /f "tokens=1,2,3,4 delims=." %%a in ("%ip%") do set oct1=%%a& set oct2=%%b& set oct3=%%c& set oct4=%%d
set subnet=%oct1%.%oct2%.%oct3%

set scan=0
set found=0
set foundsv=0
set ipstart=51
set ipend=170

:SCAN
set /a totalip=ipend-ipstart+1

set "_d=%date%"
set "_t=%time%"
set "log=scanLog%-d%-%_t%.csv"

echo IP,Name,Serial,Model > %log%

echo.
for /l %%a in (%ipstart%,1,%ipend%) do (
 set "ip=%subnet%.%%a"
 set /a scan=scan+1
 set /a pct=scan*100/totalip

 echo  Scanning !ip!...
 call :BAR !pct! 40 progbar
 title Simple Scanner ^| !totalip!/!scan!/!found!/!foundsv! ^| [!progbar!] !pct!%%%

 ping -n 1 -w 200 !ip! | find "TTL" >nul
 if !errorlevel! equ 0 (
  set "output="
  set /a found=found+1

  call :GETWMI !ip! "bios get serialnumber" serial
  call :GETWMI !ip! "computersystem get model" model
  call :GETWMI !ip! "computersystem get name" name

    REM *** DO "SV WORKSTATION" THINGS HERE

    set "output=!ip!,!name!,!serial!,!model! !MonSN!"
   ) else (

    REM *** DO "NON-SV WORKSTATION" THINGS HERE

    set "output=!ip!,!name!,!serial!,!model! !MonSN!"
  )
  echo !output! >> %log%
 ) else (

    REM *** DO "WORKSTATION NOT DETECTED" THINGS HERE

 )
)
:END

cls
color 2f
echo.
echo  SCAN COMPLETE
echo  ______________________________________________________________________
echo.
echo
echo        Range: %subnet%.%ipstart% - %ipend%
echo      Scanned: %scan%
echo  Found total: %found%
echo     Found SV: %foundsv%
echo  ______________________________________________________________________
echo.
echo  Opening log file %log%...
echo.

start /max %log%

echo
echo  Press any key to exit...
pause>nul
exit

:GETWMI
set "_s="
set _r=%2
set _r=%_r:"=%
(for /f "tokens=2 delims==" %%b in ('wmic /failfast:on /node:%1 %_r% /value') do set _s=%%b) 2>nul
if not defined _s set "_s=ERROR"
set "%~3=%_s%"
goto :eof

:BAR
if not defined xbar call :initBAR %2
for /l %%b in (1,1,%2) do (
 set /a bars=%2*%1/100
 set /a spcs=%2-bars
 set "obar="
 for %%c in (!bars!) do set "obar=!obar!!xbar:~0,%%c!"
 for %%c in (!spcs!) do set "obar=!obar!!xspc:~0,%%c!"
 set %3=!obar!
)
goto :eof

:initBAR
set "xbar=" & for /l %%b in (1,1,%1) do set "xbar=!xbar!l"
set "xspc=" & for /l %%b in (1,1,%1) do set "xspc=!xspc! "
goto :eof

:ERRORDISP
cls
color cf
echo.
echo  ^>^>^> ERROR ^<^<^<
echo.
echo  %errormsg%
echo
echo  Press any key to exit...
pause>nul
exit
</code>```

I have also tried calling for the .ps1 yet the variables are always empty and the corp network requires Powershell scripts to have sign cert to run by them selves.

答:
Long time ago I wrote the script to get monitor serial number from registry.
It takes only first monitor value. But you can change this script or convert to Powershell. Anyway you can see script logic: get EDID-number, then parse it.</p>
```<code>@for /f %%i in ('@wmic path win32_desktopmonitor get pnpdeviceid ^|@find "DISPLAY"') do @set val="HKLM\SYSTEM\CurrentControlSet\Enum\%%i\Device Parameters"

@reg query %val% /v EDID>NUL
@if %errorlevel% GTR 0 @echo BAD EDID&EXIT
@for /f "skip=2 tokens=1,2,3*" %%a in ('@reg query %val% /v EDID') do @set edid=%%c

@set /A Y=%edid:~34,1%*16+%edid:~35,1%+1990
@echo.Manufactured: %Y%

@set id=%edid:000000FC00=#%
@for /f "tokens=1,2* delims=#" %%a in ("%id%") do @set id=%%b
@set id=%id:~0,22%

@setlocal enableextensions enabledelayedexpansion
@echo off
@for /L %%i in (0,2,20) do (
@set p=!id:~%%i,2!
@if !p!==0A @goto nxt
@set m=!m!0x!p!
)
@echo on
:nxt
@forfiles /p %windir%\system32 /m shell32.dll /c "cmd /c @echo.Model       : !m!"
@endlocal

@set edid=%edid:000000FF00=#%
@for /f "tokens=1,2* delims=#" %%a in ("%edid%") do @set id=%%b
@set id=%id:~0,20%

@setlocal enableextensions enabledelayedexpansion
@for /L %%i in (0,2,18) do @set sn=!sn!0x!id:~%%i,2!
@forfiles /p %windir%\system32 /m shell32.dll /c "cmd /c @echo.S.N.        : !sn!"
@endlocal
</code>```

Body:
Hoping someone can point me in the right direction. Have a working remote PC info scanning tool that collects computer name, serial number and model. Been trying to get the monitor info added for so time and found this Powershell script and have been trying to get intergraded without success.

Powershell function;

      $Monitors = Get-WmiObject WmiMonitorID -Namespace root\wmi
 $LogFile = ".\MonInfo.csv"

 function Decode {
     If ($args[0] -is [System.Array]) {
         [System.Text.Encoding]::ASCII.GetString($args[0])
     }
     Else {
         "Not Found"
     }
 }

 ForEach ($Monitor in $Monitors) {
     $Manufacturer = Decode $Monitor.ManufacturerName -notmatch 0
     $Name = Decode $Monitor.UserFriendlyName -notmatch 0
     $Serial = Decode $Monitor.SerialNumberID -notmatch 0

     echo  $Manufacturer, $Name, $Serial" >> $LogFile
 }

Here's the network scan batch script I been using. (Basic info scan via ping and get info from remoter systems via WMI)

    @echo off
cls
color 5f

setlocal EnableDelayedExpansion

net session >nul 2>&1
if %errorlevel% neq 0 set errormsg=This program must be run as Administrator& goto ERRORDISP

set "ip="
for /f "tokens=2 delims=:" %%a in ('ipconfig ^| findstr /c:"IPv4 Address"') do set ip=%%a
if not defined ip (set errormsg=No IP address detected - check network cable& goto ERRORDISP)
set ip=%ip: =%
for /f "tokens=1,2,3,4 delims=." %%a in ("%ip%") do set oct1=%%a& set oct2=%%b& set oct3=%%c& set oct4=%%d
set subnet=%oct1%.%oct2%.%oct3%

set scan=0
set found=0
set foundsv=0
set ipstart=51
set ipend=170

:SCAN
set /a totalip=ipend-ipstart+1

set "_d=%date%"
set "_t=%time%"
set "log=scanLog%-d%-%_t%.csv"

echo IP,Name,Serial,Model > %log%

echo.
for /l %%a in (%ipstart%,1,%ipend%) do (
 set "ip=%subnet%.%%a"
 set /a scan=scan+1
 set /a pct=scan*100/totalip

 echo  Scanning !ip!...
 call :BAR !pct! 40 progbar
 title Simple Scanner ^| !totalip!/!scan!/!found!/!foundsv! ^| [!progbar!] !pct!%%%

 ping -n 1 -w 200 !ip! | find "TTL" >nul
 if !errorlevel! equ 0 (
  set "output="
  set /a found=found+1

  call :GETWMI !ip! "bios get serialnumber" serial
  call :GETWMI !ip! "computersystem get model" model
  call :GETWMI !ip! "computersystem get name" name

    REM *** DO "SV WORKSTATION" THINGS HERE

    set "output=!ip!,!name!,!serial!,!model! !MonSN!"
   ) else (

    REM *** DO "NON-SV WORKSTATION" THINGS HERE

    set "output=!ip!,!name!,!serial!,!model! !MonSN!"
  )
  echo !output! >> %log%
 ) else (

    REM *** DO "WORKSTATION NOT DETECTED" THINGS HERE

 )
)
:END

cls
color 2f
echo.
echo  SCAN COMPLETE
echo  ______________________________________________________________________
echo.
echo
echo        Range: %subnet%.%ipstart% - %ipend%
echo      Scanned: %scan%
echo  Found total: %found%
echo     Found SV: %foundsv%
echo  ______________________________________________________________________
echo.
echo  Opening log file %log%...
echo.

start /max %log%

echo
echo  Press any key to exit...
pause>nul
exit

:GETWMI
set "_s="
set _r=%2
set _r=%_r:"=%
(for /f "tokens=2 delims==" %%b in ('wmic /failfast:on /node:%1 %_r% /value') do set _s=%%b) 2>nul
if not defined _s set "_s=ERROR"
set "%~3=%_s%"
goto :eof

:BAR
if not defined xbar call :initBAR %2
for /l %%b in (1,1,%2) do (
 set /a bars=%2*%1/100
 set /a spcs=%2-bars
 set "obar="
 for %%c in (!bars!) do set "obar=!obar!!xbar:~0,%%c!"
 for %%c in (!spcs!) do set "obar=!obar!!xspc:~0,%%c!"
 set %3=!obar!
)
goto :eof

:initBAR
set "xbar=" & for /l %%b in (1,1,%1) do set "xbar=!xbar!l"
set "xspc=" & for /l %%b in (1,1,%1) do set "xspc=!xspc! "
goto :eof

:ERRORDISP
cls
color cf
echo.
echo  ^>^>^> ERROR ^<^<^<
echo.
echo  %errormsg%
echo
echo  Press any key to exit...
pause>nul
exit

I have also tried calling for the .ps1 yet the variables are always empty and the corp network requires Powershell scripts to have sign cert to run by them selves.

Body:
Long time ago I wrote the script to get monitor serial number from registry.
It takes only first monitor value. But you can change this script or convert to Powershell. Anyway you can see script logic: get EDID-number, then parse it.

@for /f %%i in ('@wmic path win32_desktopmonitor get pnpdeviceid ^|@find "DISPLAY"') do @set val="HKLM\SYSTEM\CurrentControlSet\Enum\%%i\Device Parameters"

@reg query %val% /v EDID>NUL
@if %errorlevel% GTR 0 @echo BAD EDID&EXIT
@for /f "skip=2 tokens=1,2,3*" %%a in ('@reg query %val% /v EDID') do @set edid=%%c

@set /A Y=%edid:~34,1%*16+%edid:~35,1%+1990
@echo.Manufactured: %Y%

@set id=%edid:000000FC00=#%
@for /f "tokens=1,2* delims=#" %%a in ("%id%") do @set id=%%b
@set id=%id:~0,22%

@setlocal enableextensions enabledelayedexpansion
@echo off
@for /L %%i in (0,2,20) do (
@set p=!id:~%%i,2!
@if !p!==0A @goto nxt
@set m=!m!0x!p!
)
@echo on
:nxt
@forfiles /p %windir%\system32 /m shell32.dll /c "cmd /c @echo.Model       : !m!"
@endlocal

@set edid=%edid:000000FF00=#%
@for /f "tokens=1,2* delims=#" %%a in ("%edid%") do @set id=%%b
@set id=%id:~0,20%

@setlocal enableextensions enabledelayedexpansion
@for /L %%i in (0,2,18) do @set sn=!sn!0x!id:~%%i,2!
@forfiles /p %windir%\system32 /m shell32.dll /c "cmd /c @echo.S.N.        : !sn!"
@endlocal


问:
Where to add/remove interceptors while different components are calling apis using an axiosinstance
I have axios instance initialized at the start of application. Under Login.js I am able to get the token and want to add it to the header using interceptors, for most subsequent api calls e.g. when using under AddSampleTable.js . (A few of them will require to go without Authorization header too e.g. ForgotPassword.js)

Currently I have to do this for every single api call in each component. My current code is as follows

axios.js

```<code>import axios from 'axios';

 const baseURL = process.env.REACT_APP_BASE_URL;

 let headers = {};

//this never executes since we havent logged in yet

//if(localStorage.token) {
  //headers.Authorization = `Bearer ${localStorage.token}`;
//}
const token = localStorage.getItem('token');

const axiosInstance = axios.create({

    baseURL: baseURL,
    headers: {'Authorization': token? `Bearer ${token}`: null},
});

export default axiosInstance;
</code>```

Login.js

```<code> import axiosInstance from '../../helpers/axios';

  const printValues = e =>{
  e.preventDefault();
 axiosInstance.post('/auth', data)
 .then(res =>{
  console.log("writing token");
  dispatch(jwtTokenRecieved(res.data.token));
  localStorage.setItem('token',res.data.token);

  const config = {
    headers:{
      Authorization:'Bearer '+res.data.token
    }
  }
  axiosInstance.get('/User/GetUserByID/0', config)
.then(res =>{
    dispatch(isLoggedUser(res.data));
  })
  .catch(err =>{
    console.log(err);
  })
</code>```

AddSampleTable.js

This is where I want to use the instance and token should be present by default but currently I am extracting for each api call from localstorage

```<code>import axiosInstance from '../../helpers/axios';
export default function AddSamplesTable(){
const jwtToken = useSelector(state => state?.token?.data || '');

const retrieveSampleData = () =>{

const config = {
  headers:{
    Authorization:'Bearer '+ jwtToken,
    'Content-Type': 'application/json'
  }
}
axiosInstance.get('/batch/'+CoCData.id, config)
    .then(function (response) {
      setSamples(response.data.samples);
    })
    .catch(function (error) {
      console.log(error);
    });
}

}
</code>```

Note I am also using reducers and actions to set token into the localStorage as you see in (in addition to saving it via setItem)

```<code>dispatch(jwtTokenRecieved(res.data.token));
</code>```

Update: I have tried using interceptors in axios.js after create function as follows

```<code>axiosInstance.interceptors.request.use(
config => {
console.log(config)
  const token = JSON.parse(localStorage.getItem('token'));
  config.headers.Authorization =  token ? `Bearer ${token}`: null;

  return config;
    }
);
</code>```

but when a new user logs in, the existing token value does not get updated with the new token and I get

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'status')

答:
Use Distinct Axios instances for Secure API and Guest API

Follow below steps:

Define baseURL for secure and guest APIs

Create distinct Axios instances

Define request, response and error handlers for secure API Axios instance

Using request handler, put the token in request headers

Bind above handlers as interceptors to the secure Axios instance

Export both axios instances and use as required

Clear the token upon logout or using timers

Sample code for axios.js

```<code>// /userLibrary/axios.js
import axios from 'axios';

// Step 1
const baseURL = process.env.REACT_APP_BASE_URL;

// Step 2
const guestAxios = axios.create({ baseURL })
const secureAxios = axios.create({ baseURL })

// Step 3: Define handlers
const errorHandler = ()=>{
   ...
}

const secureAPIRequest= (config)=>{

    // Step 4: Put token in header
    const token = JSON.parse(localStorage.getItem('token'));
    config.headers.Authorization =  token ? `Bearer ${token}`: null;
    return config
}

const secureAPIResponse= ()=>{
   ...
}

// Step 5: Add interceptors for secure axios instance
secureAxios.interceptors.request.use(secureAPIRequest, errorHandler)
secureAxios.interceptors.response.use(secureAPIResponse, errorHandler)

// Step 6
export {
    guestAxios,
    secureAxios
}
</code>```

Sample code for Login.js

```<code>import { guestAxios } from '/userLibrary/axios.js'
...
</code>```

Sample code for AddSampleTable.js

```<code>import { secureAxios } from '/userLibrary/axios.js'
...
</code>```

Body:
I have axios instance initialized at the start of application. Under Login.js I am able to get the token and want to add it to the header using interceptors, for most subsequent api calls e.g. when using under AddSampleTable.js . (A few of them will require to go without Authorization header too e.g. ForgotPassword.js)

Currently I have to do this for every single api call in each component. My current code is as follows

axios.js

import axios from 'axios';

 const baseURL = process.env.REACT_APP_BASE_URL;

 let headers = {};

//this never executes since we havent logged in yet

//if(localStorage.token) {
  //headers.Authorization = `Bearer ${localStorage.token}`;
//}
const token = localStorage.getItem('token');

const axiosInstance = axios.create({

    baseURL: baseURL,
    headers: {'Authorization': token? `Bearer ${token}`: null},
});

export default axiosInstance;

Login.js

 import axiosInstance from '../../helpers/axios';

  const printValues = e =>{
  e.preventDefault();
 axiosInstance.post('/auth', data)
 .then(res =>{
  console.log("writing token");
  dispatch(jwtTokenRecieved(res.data.token));
  localStorage.setItem('token',res.data.token);

  const config = {
    headers:{
      Authorization:'Bearer '+res.data.token
    }
  }
  axiosInstance.get('/User/GetUserByID/0', config)
.then(res =>{
    dispatch(isLoggedUser(res.data));
  })
  .catch(err =>{
    console.log(err);
  })

AddSampleTable.js

This is where I want to use the instance and token should be present by default but currently I am extracting for each api call from localstorage

import axiosInstance from '../../helpers/axios';
export default function AddSamplesTable(){
const jwtToken = useSelector(state => state?.token?.data || '');

const retrieveSampleData = () =>{

const config = {
  headers:{
    Authorization:'Bearer '+ jwtToken,
    'Content-Type': 'application/json'
  }
}
axiosInstance.get('/batch/'+CoCData.id, config)
    .then(function (response) {
      setSamples(response.data.samples);
    })
    .catch(function (error) {
      console.log(error);
    });
}

}

Note I am also using reducers and actions to set token into the localStorage as you see in (in addition to saving it via setItem)

dispatch(jwtTokenRecieved(res.data.token));

Update: I have tried using interceptors in axios.js after create function as follows

axiosInstance.interceptors.request.use(
config => {
console.log(config)
  const token = JSON.parse(localStorage.getItem('token'));
  config.headers.Authorization =  token ? `Bearer ${token}`: null;

  return config;
    }
);

but when a new user logs in, the existing token value does not get updated with the new token and I get

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'status')

Body:
Use Distinct Axios instances for Secure API and Guest API

Follow below steps:

Define baseURL for secure and guest APIs

Create distinct Axios instances

Define request, response and error handlers for secure API Axios instance

Using request handler, put the token in request headers

Bind above handlers as interceptors to the secure Axios instance

Export both axios instances and use as required

Clear the token upon logout or using timers

Sample code for axios.js

// /userLibrary/axios.js
import axios from 'axios';

// Step 1
const baseURL = process.env.REACT_APP_BASE_URL;

// Step 2
const guestAxios = axios.create({ baseURL })
const secureAxios = axios.create({ baseURL })

// Step 3: Define handlers
const errorHandler = ()=>{
   ...
}

const secureAPIRequest= (config)=>{

    // Step 4: Put token in header
    const token = JSON.parse(localStorage.getItem('token'));
    config.headers.Authorization =  token ? `Bearer ${token}`: null;
    return config
}

const secureAPIResponse= ()=>{
   ...
}

// Step 5: Add interceptors for secure axios instance
secureAxios.interceptors.request.use(secureAPIRequest, errorHandler)
secureAxios.interceptors.response.use(secureAPIResponse, errorHandler)

// Step 6
export {
    guestAxios,
    secureAxios
}

Sample code for Login.js

import { guestAxios } from '/userLibrary/axios.js'
...

Sample code for AddSampleTable.js

import { secureAxios } from '/userLibrary/axios.js'
...


问:
Inserting data right after create table in SqlAlchemy
I'm creating my tables with SqlAlchemy and have a table called UserTypes

id | type

0  | Owner

1  | Customer

In my User table i take usertype id as foreign key. And whenever i want to create a user, i want to assign usertype default 0. But my usertype table is empty, so i want to fill this table right after its created with SqlAlchemy, and locked for further insertions. Question is can i insert

Here is my User and UserType modals.

```<code>class User(Model):

    id = Column(db.Integer, primary_key=True)
    email = Column(db.String(64), unique=True, index=True)
    username = Column(db.String(15), unique=True, index=True)
    name = Column(db.String(64))
    password_hash = Column(db.String(128))
    usertype_id = Column(db.Integer, db.ForeignKey('user_types.id'), default=DEFAULT_USERTYPE)
</code>```

and

```<code>class UserType(db.Model):

   __tablename__ = 'user_types'
   id = db.Column(db.Integer, primary_key=True)
   name = db.Column(db.String(64), index=True, unique=True)
   users = db.relationship('User', backref='user_types', lazy='dynamic')

</code>```

答:
You could add those UserTypes in your app/__init__.py. You would have to check under which key the table gets saved, I'm not sure if it would be 'usertype' or 'user_types'.</p>
```<code>if 'user_types' not in db.metadata.tables.keys():
    db.create_all()
    t1 = UserType()
    t1.id = 0
    t1.name = 'Owner'
    db.session.add(t1)
    t2 = UserType()
    t2.id = 1
    t2.name = 'Customer'
    db.session.add(t2)
    db.session.commit()
</code>```

Body:
I'm creating my tables with SqlAlchemy and have a table called UserTypes

id | type

0  | Owner

1  | Customer

In my User table i take usertype id as foreign key. And whenever i want to create a user, i want to assign usertype default 0. But my usertype table is empty, so i want to fill this table right after its created with SqlAlchemy, and locked for further insertions. Question is can i insert

Here is my User and UserType modals.

class User(Model):

    id = Column(db.Integer, primary_key=True)
    email = Column(db.String(64), unique=True, index=True)
    username = Column(db.String(15), unique=True, index=True)
    name = Column(db.String(64))
    password_hash = Column(db.String(128))
    usertype_id = Column(db.Integer, db.ForeignKey('user_types.id'), default=DEFAULT_USERTYPE)

and

class UserType(db.Model):

   __tablename__ = 'user_types'
   id = db.Column(db.Integer, primary_key=True)
   name = db.Column(db.String(64), index=True, unique=True)
   users = db.relationship('User', backref='user_types', lazy='dynamic')

Body:
You could add those UserTypes in your app/__init__.py. You would have to check under which key the table gets saved, I'm not sure if it would be 'usertype' or 'user_types'.

if 'user_types' not in db.metadata.tables.keys():
    db.create_all()
    t1 = UserType()
    t1.id = 0
    t1.name = 'Owner'
    db.session.add(t1)
    t2 = UserType()
    t2.id = 1
    t2.name = 'Customer'
    db.session.add(t2)
    db.session.commit()


问:
Should I leave small values in my rotation matrix?

My matrix

```<code>6.12303176911189E-17 1 0
-1 6.12303176911189E-17 0
0 0 1
</code>```

Rotation matrix calculated here

```<code>0       1       0
-1      0       0
0       0       1
</code>```

Question

Should I leave my matrix as it is, or should I set the small values to zero?

The function I use to generate rotation matrices

```<code>public void SetRotate(Vector axis, double angle)
{
    double angleSin = Math.Sin(angle);
    double angleCos = Math.Cos(angle);

    double a = 1.0 - angleCos;
    double ax = a * axis.X;
    double ay = a * axis.Y;
    double az = a * axis.Z;

    _m11 = ax * axis.X + angleCos;
    _m12 = ax * axis.Y + axis.Z * angleSin;
    _m13 = ax * axis.Z - axis.Y * angleSin;

    _m21 = ay * axis.X - axis.Z * angleSin;
    _m22 = ay * axis.Y + angleCos;
    _m23 = ay * axis.Z + axis.X * angleSin;

    _m31 = az * axis.X + axis.Y * angleSin;
    _m32 = az * axis.Y - axis.X * angleSin;
    _m33 = az * axis.Z + angleCos;
}
</code>```

答:
Leave it, just because you can verify that the matrix computed for 90 degrees is different ever so slightly from the ideal result doesn't justify fixing the function for this single case.

If you add a fix for this you might as well add fixes for all other possible values as well...

Body:
My matrix

6.12303176911189E-17 1 0
-1 6.12303176911189E-17 0
0 0 1

Rotation matrix calculated here

0       1       0
-1      0       0
0       0       1

Question

Should I leave my matrix as it is, or should I set the small values to zero?

The function I use to generate rotation matrices

public void SetRotate(Vector axis, double angle)
{
    double angleSin = Math.Sin(angle);
    double angleCos = Math.Cos(angle);

    double a = 1.0 - angleCos;
    double ax = a * axis.X;
    double ay = a * axis.Y;
    double az = a * axis.Z;

    _m11 = ax * axis.X + angleCos;
    _m12 = ax * axis.Y + axis.Z * angleSin;
    _m13 = ax * axis.Z - axis.Y * angleSin;

    _m21 = ay * axis.X - axis.Z * angleSin;
    _m22 = ay * axis.Y + angleCos;
    _m23 = ay * axis.Z + axis.X * angleSin;

    _m31 = az * axis.X + axis.Y * angleSin;
    _m32 = az * axis.Y - axis.X * angleSin;
    _m33 = az * axis.Z + angleCos;
}


问:
Using a hyper-link in a manual validation task - Azure DevOps (Yaml)
I have a url in a manual validation task like below :

```<code> - task: ManualValidation@0
      displayName: Export the Power Platform Solution
      timeoutInMinutes: 1440 # task times out in 1 day
      inputs:
        notifyUsers: |
          bob@bob.com
        instructions: |
          'Please follow this link for instructions'
          'https://dev.azure.com/BobsOFfice/ASR/_wiki/wikis/ASR.wiki/1002/Application-Deployment?anchor=export-the-solution'
        onTimeout: 'reject'
</code>```

It looks terrible on the screen and you have hightlight the url and paste it into IE. Is it possible to make this a hyper-link ? I cannot see any docs on this.

答:
I'm afraid the manual validation task doesn't support this feature yet.

The instructions field will be displayed in plain text and cannot be displayed as a hyperlink for the time being.

I can fully understand your requirement. Here is a suggestion ticket with the same requirements: Azure devops Manual Validation Task's instruction is not showing the hyperlink.

You can vote it and add comment in this suggestion ticket.

Body:
I have a url in a manual validation task like below :

 - task: ManualValidation@0
      displayName: Export the Power Platform Solution
      timeoutInMinutes: 1440 # task times out in 1 day
      inputs:
        notifyUsers: |
          bob@bob.com
        instructions: |
          'Please follow this link for instructions'
          'https://dev.azure.com/BobsOFfice/ASR/_wiki/wikis/ASR.wiki/1002/Application-Deployment?anchor=export-the-solution'
        onTimeout: 'reject'

It looks terrible on the screen and you have hightlight the url and paste it into IE. Is it possible to make this a hyper-link ? I cannot see any docs on this.


问:
Sitecore content editor redirects to Page not foud
Due to some publishing issues i corrupted my local enviroment. Luckily i had backup which i restored and my local site was functioning well but, when i login to sitecore and choose any option from main page like Content Editor or Desktop it redirects to page not found.

I've tried to disable exceptions which redirect to page but they were of no use. And no logs are being created. Should i replace the entire wwwroot folder but, my wwwroot backup is 2 months old.

Or should i start from scratch and create a new sitecore site for same solution. I've compared my web.config,connection strings files they don't seem o have any problem.

Suggest what to do.

答:
You are able to login but seems due to some permission issue you are not able to Content Editor/Desktop. Check permission on folders like identityserver(used for login)/your website(content editor and other CMS work), to start with you can try to give permission to your IIS User/Everyone (as shown in image), once it starts working you can be selective and change permission as per your need
enter image description here</p>


问:
React doesn't display images placed in public folder when I install gh-pages but when I push the code it displays in gh-pages?
I have changed the images path from this src={../images/${props.data.coverImg}}

To this
src={images/${props.data.coverImg}}

and the interesting thing is that when I install gh-pages, images are broken on local host-3000 but it displays on gh-pages.

I have stored images folder in public folder.

答:
Try to add ./ before the img src:

```<code> src={./images/${props.data.coverImg}}
</code>```

I think there is a differnets in the way your browser rendering the url of the images, between localhost and a real environment.

Body:
Try to add ./ before the img src:

 src={./images/${props.data.coverImg}}

I think there is a differnets in the way your browser rendering the url of the images, between localhost and a real environment.


问:
Extracting substring with awk if the string includes regular expressions
I have many strings like this

```<code>i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt
</code>```

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!

答:
Bash allows you to split a string into an array.

# starting value
str=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt

# split string on / delimiter into the split array
IFS=/ read -ra split <<<"$str"

# get M1 and FCT elements at their respective indexes
M1=${split[1]}
FCT=${split[5]}

# dump M1 and FCT variables for demo purpose
declare -p M1 FCT
```

Body:
I have many strings like this

i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!


问:
Brownie does not export .env variables
I'm following a tutorial that uses brownie in python to deploy a contract.
If the contract is to be deployed onto a testnet (rinkeby in this case), the program is supposed to get the private key from the environment variables, but when trying to run the deploy.py script as:

```<code>brownie run scripts/deploy.py --network rinkeby
</code>```

I get the following error:

```<code>Running 'scripts/deploy.py::main'...
  File "brownie/_cli/run.py", line 50, in main
    return_value, frame = run(
  File "brownie/project/scripts.py", line 103, in run
    return_value = f_locals[method_name](*args, **kwargs)
  File "./scripts/deploy.py", line 10, in main
    deploy_fund_me()
  File "./scripts/deploy.py", line 5, in deploy_fund_me
    account = get_account()
  File "./scripts/helpful_scripts.py", line 19, in get_account
    return accounts.add(config["wallets"]["from_key"])
  File "brownie/network/account.py", line 142, in add
    w3account = web3.eth.account.from_key(private_key)
  File "eth_utils/decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "eth_account/account.py", line 250, in from_key
    key = self._parsePrivateKey(private_key)
  File "eth_utils/decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "eth_account/account.py", line 776, in _parsePrivateKey
    raise ValueError(
ValueError: The private key must be exactly 32 bytes long, instead of 0 bytes.
</code>```

Some background on this error:
I have a .env file in the same directory as my brownie-config.yml, containing the following:

```<code>export PRIVATE_KEY={my_private_key}
</code>```

where {my_private_key} is a my actual private key in hex.

The brownie-config.yml looks like this:

```<code>dependencies:
  # - <organization/repo>@<version>
  - smartcontractkit/chainlink-brownie-contracts@1.1.1
compiler:
  solc:
    remappings:
      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1'

dotenv: .env

wallets:
    from_key: ${PRIVATE_KEY}
</code>```

From my understanding, brownie should use the .env file to export the key as an environment variable and then put it into some brownie config file (probably when the code gets compiled?), where brownie will look for it when the contract gets deployed.
It also does not change anything if I export this environment variable manually before executing the code.

P.S: The function that seems to cause the error:

```<code>def get_account():
    if network.show_active() == "development":
        return accounts[0]
    else:
        return accounts.add(config["wallets"]["from_key"])
</code>```

答:
I am also getting the same error
I tried to directly give the private key 0x.... inside brownie-config.yaml file and it work, but I think this is not the secure way to get the private key.

dotenv: .env
wallets:
from_key: 0x....

Title: Brownie does not export .env variables

Body:
I'm following a tutorial that uses brownie in python to deploy a contract.
If the contract is to be deployed onto a testnet (rinkeby in this case), the program is supposed to get the private key from the environment variables, but when trying to run the deploy.py script as:

brownie run scripts/deploy.py --network rinkeby

I get the following error:

Running 'scripts/deploy.py::main'...
  File "brownie/_cli/run.py", line 50, in main
    return_value, frame = run(
  File "brownie/project/scripts.py", line 103, in run
    return_value = f_locals[method_name](*args, **kwargs)
  File "./scripts/deploy.py", line 10, in main
    deploy_fund_me()
  File "./scripts/deploy.py", line 5, in deploy_fund_me
    account = get_account()
  File "./scripts/helpful_scripts.py", line 19, in get_account
    return accounts.add(config["wallets"]["from_key"])
  File "brownie/network/account.py", line 142, in add
    w3account = web3.eth.account.from_key(private_key)
  File "eth_utils/decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "eth_account/account.py", line 250, in from_key
    key = self._parsePrivateKey(private_key)
  File "eth_utils/decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "eth_account/account.py", line 776, in _parsePrivateKey
    raise ValueError(
ValueError: The private key must be exactly 32 bytes long, instead of 0 bytes.

Some background on this error:
I have a .env file in the same directory as my brownie-config.yml, containing the following:

export PRIVATE_KEY={my_private_key}

where {my_private_key} is a my actual private key in hex.

The brownie-config.yml looks like this:

dependencies:
  # - <organization/repo>@<version>
  - smartcontractkit/chainlink-brownie-contracts@1.1.1
compiler:
  solc:
    remappings:
      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1'

dotenv: .env

wallets:
    from_key: ${PRIVATE_KEY}

From my understanding, brownie should use the .env file to export the key as an environment variable and then put it into some brownie config file (probably when the code gets compiled?), where brownie will look for it when the contract gets deployed.
It also does not change anything if I export this environment variable manually before executing the code.

P.S: The function that seems to cause the error:

def get_account():
    if network.show_active() == "development":
        return accounts[0]
    else:
        return accounts.add(config["wallets"]["from_key"])


问:
CircleCI: Use nodejs version 12
My CircleCI file is provided:

```<code>version: 2.1
orbs:
  node: circleci/node@4.1.0
  aws-cli: circleci/aws-cli@2.0.3
  eb: circleci/aws-elastic-beanstalk@2.0.1
jobs:
  build:
    docker:
      - image: "cimg/base:stable"
    steps:
      - node/install
      - checkout
      - aws-cli/setup
      - eb/setup
      - run:
          name: Check current version of node
          command: node -v
      - run:
          name: Get and install node version manager.
          command: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
      - run:
          name: Install Node version 12 using NVM
          command: nvm install 12
      - run:
          name: Use Node version 12
          command: nvm use 12
      - run:
          name: Back-End Install
          command: |
            npm run backend:install
      - run:
          name: Front-End Install
          command: |
            npm run frontend:install
      - run:
          name: Back-End Build
          command: |
            npm run backend:build
      - run:
          name: Front-End Build
          command: |
            npm run frontend:build
      - run:
          name: Back-End Deploy
          command: |
            npm run backend:deploy
      - run:
          name: Front-End Deploy
          command: |
            npm run frontend:deploy
</code>```

During the setup, the CircleCI install node version of v16.9.0 and I need to use v12. So, I run additional command to use v12 using NVM.

Is there easier way to use specific version of the Node during the time of setup?

答:
Using cimg with node version as a docker image should work. You don't have to manually install using nvm.

```<code>jobs:
  build:
    docker:
      - image: cimg/node:12.16
</code>```

https://hub.docker.com/r/cimg/node

I'm using cimg/node:16.13.2 and it works fine.

Title: CircleCI: Use nodejs version 12

Body:
My CircleCI file is provided:

version: 2.1
orbs:
  node: circleci/node@4.1.0
  aws-cli: circleci/aws-cli@2.0.3
  eb: circleci/aws-elastic-beanstalk@2.0.1
jobs:
  build:
    docker:
      - image: "cimg/base:stable"
    steps:
      - node/install
      - checkout
      - aws-cli/setup
      - eb/setup
      - run:
          name: Check current version of node
          command: node -v
      - run:
          name: Get and install node version manager.
          command: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
      - run:
          name: Install Node version 12 using NVM
          command: nvm install 12
      - run:
          name: Use Node version 12
          command: nvm use 12
      - run:
          name: Back-End Install
          command: |
            npm run backend:install
      - run:
          name: Front-End Install
          command: |
            npm run frontend:install
      - run:
          name: Back-End Build
          command: |
            npm run backend:build
      - run:
          name: Front-End Build
          command: |
            npm run frontend:build
      - run:
          name: Back-End Deploy
          command: |
            npm run backend:deploy
      - run:
          name: Front-End Deploy
          command: |
            npm run frontend:deploy

During the setup, the CircleCI install node version of v16.9.0 and I need to use v12. So, I run additional command to use v12 using NVM.

Is there easier way to use specific version of the Node during the time of setup?

Body:
Using cimg with node version as a docker image should work. You don't have to manually install using nvm.

jobs:
  build:
    docker:
      - image: cimg/node:12.16

https://hub.docker.com/r/cimg/node

I'm using cimg/node:16.13.2 and it works fine.


问:
Flutter: upgrade the version code for play store
I have published an application on the play store with flutter, now I want to upload a new version of the application. I am trying to change the version code with:

flutter build apk --build-name=1.0.2 --build-number=3

or changing the local.properties like this

```<code> flutter.versionName=2.0.0
 flutter.versionCode=2
 flutter.buildMode=release
</code>```

but every time I get an error on the play store

You must use a different version code for your APK or your Android App Bundle because code 1 is already assigned to another APK or Android App Bundle.

答:
I have been doing it like this in the 'app/build.gradle' file</p>
```<code>def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}else {
    flutterVersionCode = '4'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}else {
    flutterVersionName = '1.3'
}
</code>```

Body:
I have published an application on the play store with flutter, now I want to upload a new version of the application. I am trying to change the version code with:

flutter build apk --build-name=1.0.2 --build-number=3

or changing the local.properties like this

 flutter.versionName=2.0.0
 flutter.versionCode=2
 flutter.buildMode=release

but every time I get an error on the play store

You must use a different version code for your APK or your Android App Bundle because code 1 is already assigned to another APK or Android App Bundle.

Body:
I have been doing it like this in the 'app/build.gradle' file

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}else {
    flutterVersionCode = '4'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}else {
    flutterVersionName = '1.3'
}


问:
Find first file in directory with Java
I have some sort of batch program that should pick up a file from a directory and process it.

Since this program is supposed to:

run on JDK 5,

be small (no external libraries)

and fast! (with a bang)

...what is the best way to only pick one file from the directory - without using File.list() (might be hundreds of files)?

答: It seems from what you said that you want to process every file in the directory once (including files that get added to the directory). You can do the following: set a monitor on the directory that generates notifications when files are added. you then process each file that you get notified about. Since you use JDK 5 , i suggest using jpathwatch . note that you need to make sure the file writing has finished before trying to process it. after starting the monitor to insure you will be processing every new file, make a one time usage of  file listing to process the current content. </p>

Title: Find first file in directory with Java