问:
Material UI 5 class name styles
I migrated from Mui 4 to 5 and wonder how to use class names. If I want to apply certain styles to just one component there is the SX property. However, I'm struggling with using the same class for multiple components. In v4 my code looked like this:

export const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      padding: theme.spacing(1),
      margin: 'auto',
    },
  })
)
```
<p>I could import this <code>useStyles</code> hook in any component and use it like this:</p>
<pre class="lang-jsx prettyprint-override"><code>const classes = useStyles()
...
<div className={classes.root}>...</div>
</code>```

This docs say, that I can 'override styles with class names', but they don't tell how to do it:
https://mui.com/customization/how-to-customize/#overriding-styles-with-class-names

Do I have to put these styles in an external CSS file?

.Button {
  color: black;
}
```
<p>I would rather define the styles in my ts file.</p>
<p>I also found this migration guide:
https://next.material-ui.com/guides/migration-v4/#migrate-makestyles-to-emotion</p>
<p>I don't like approach one, because using this Root wrapper, it is inconvenient to apply a class conditionally. (Especially for typescript there is some overhead) Approach two comes with an external dependency and some boilerplate code.</p>
<p>Ideally I would use styles like this, perhaps with one rapper function around the styles object:</p>
<pre class="lang-js prettyprint-override"><code>export const root = {
  padding: theme.spacing(1),
  margin: 'auto',
}

<div className={root}>...</div>
</code>```

Of course, the last approach doesn't work, because className wants a string as input. Does anybody know an alternative with little boilerplate code?

答:
Answering your exact question, there are use cases (I think yours is not one of them and you should use styled components) however for those like me who stumble upon it and want a "exact answer to this question" and not a "do this instead", this is how you achieve to retrieve the class names.

This is so far undocumented.

For functional components, using emotion, here an use case where you have a 3rd party component that expects, not one, but many class names, or where the className property is not where you are meant to pass the property.

import { css, Theme, useTheme } from "@mui/material/styles";
import { css as emotionCss } from "@emotion/css";

const myStyles = {
  basicClass: {
    marginLeft: "1rem",
    marginRight: "1rem",
    paddingLeft: "1rem",
    paddingRight: "1rem",
  },
  optionClass: (theme: Theme) => ({
    [theme.breakpoints.down(theme.breakpoints.values.md)]: {
      display: "none",
    }
  })
}

function MyComponent() {
  cons theme = useTheme();

  // first we need to convert to something emotion can understand
  const basicClass = css(myStyles.basicClass);
  const optionClass = css(myStyles.optionClass(theme));

  // now we can pass to emotion
  const basicClassName = emotionCss(basicClass.styles);
  const optionClassName = emotionCss(optionClass.styles);

  return (
    <ThirdPartyComponent basicClassName={basicClassName} optionClassName={optionClassName} />
  )
}
```
<p>When you have a Class Component, you need to use the also undocumented <code>withTheme</code> from <code>@mui/material/styles</code> and wrap your class, if you use the theme.</p>
<p><strong>WHEN IT IS NOT AN USE CASE</strong></p>
<ol>
<li>When your component uses a single className property just use styled components.</li>
</ol>
```import { styled } from "@mui/material/styles";

const ThrirdPartyStyled = styled(ThirdPartyComponent)(({theme}) => ({
  color: theme.palette.success.contrastText
}))
```
<ol start="2">
<li>Even if you have dynamic styles</li>
</ol>
```import { styled } from "@mui/material/styles";

interface IThrirdPartyStyledExtraProps {
  fullWidth?: boolean;
}

const ThrirdPartyStyled = styled(ThirdPartyComponent, {
  shouldForwardProp: (prop) => prop !== "fullWidth"
})<IThrirdPartyStyledExtraProps>(({theme, fullWidth}) => ({
  color: theme.palette.success.contrastText,
  width: fullWidth ? "100%" : "auto",
}))
```
<p>Even if each one has some form of custom color, you just would use "sx" on your new ThrirdPartyStyled.</p>
<ol start="3">
<li>When you are just trying to reuse a style around (your use case)</li>
</ol>
<pre class="lang-js prettyprint-override"><code>const myReusableStyle = {
  color: "red",
}

// better
const MyStyledDiv = styled("div")(myReusableStyle);
// questionable
const MySpanWithoutStyles = styled("span")();

// better
const MyDrawerStyled = styled(Drawer)(myReusableStyle);

function MyComponent() {
  return (
    <MyStyledDiv>
      questionable usage because it is less clean:
      <MySpanWithoutStyles sx={myReusableStyle}>hello</MySpanWithoutStyles>
      <MySpanWithoutStyles sx={myReusableStyle}>world</MySpanWithoutStyles>

      these two are equivalent:
      <MyDrawerStyled />
      <Drawer sx={myReusableStyle} />
    </MyStyledDiv>
  )
}
</code>```

Now what is "presumably" cool about this is that your style, is just an object now, and you can just import it and use it everywhere without makeStyles or withStyles, supposedly an advantage, even when to be honest, I have never used that of exporting/importing around; the code seems a bit cleaner nevertheless.

You seem to want to use it so all you do is.

```<code>export const myStyles {
  // your styles here
}
</code>```

because this object is equivalent in memory, and it is always the same object, something that is easier to mess up with styles, it should be as effective or even more than your hook, theoretically (if it re-renders often even when setup may be longer), which stores the same function in memory but returns a new object every time.

Now you can use those myStyles everywhere you deem reasonable, either with styled components or by assigning to sx.

You can further optimize, say if it's always a div that you use that is styled the same way, then the styled component MyStyledDiv should be faster, because it is the same and done each time. How much faster is this? According to some sources 55% faster, to me, it is taking 4 weeks of refactor and the JSS compatibility with emotion is bad, all mixed with SSR is making everything unusable and slow and broken, so let's see until then when the whole is refactored.

Title: Material UI 5 class name styles

Body:
I migrated from Mui 4 to 5 and wonder how to use class names. If I want to apply certain styles to just one component there is the SX property. However, I'm struggling with using the same class for multiple components. In v4 my code looked like this:

export const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      padding: theme.spacing(1),
      margin: 'auto',
    },
  })
)

I could import this useStyles hook in any component and use it like this:

const classes = useStyles()
...

...

This docs say, that I can 'override styles with class names', but they don't tell how to do it:
https://mui.com/customization/how-to-customize/#overriding-styles-with-class-names

Do I have to put these styles in an external CSS file?

.Button {
  color: black;
}

I would rather define the styles in my ts file.

I also found this migration guide:
https://next.material-ui.com/guides/migration-v4/#migrate-makestyles-to-emotion

I don't like approach one, because using this Root wrapper, it is inconvenient to apply a class conditionally. (Especially for typescript there is some overhead) Approach two comes with an external dependency and some boilerplate code.

Ideally I would use styles like this, perhaps with one rapper function around the styles object:

export const root = {
  padding: theme.spacing(1),
  margin: 'auto',
}

...

Of course, the last approach doesn't work, because className wants a string as input. Does anybody know an alternative with little boilerplate code?

Body:
Answering your exact question, there are use cases (I think yours is not one of them and you should use styled components) however for those like me who stumble upon it and want a "exact answer to this question" and not a "do this instead", this is how you achieve to retrieve the class names.

This is so far undocumented.

For functional components, using emotion, here an use case where you have a 3rd party component that expects, not one, but many class names, or where the className property is not where you are meant to pass the property.

import { css, Theme, useTheme } from "@mui/material/styles";
import { css as emotionCss } from "@emotion/css";

const myStyles = {
  basicClass: {
    marginLeft: "1rem",
    marginRight: "1rem",
    paddingLeft: "1rem",
    paddingRight: "1rem",
  },
  optionClass: (theme: Theme) => ({
    [theme.breakpoints.down(theme.breakpoints.values.md)]: {
      display: "none",
    }
  })
}

function MyComponent() {
  cons theme = useTheme();

  // first we need to convert to something emotion can understand
  const basicClass = css(myStyles.basicClass);
  const optionClass = css(myStyles.optionClass(theme));

  // now we can pass to emotion
  const basicClassName = emotionCss(basicClass.styles);
  const optionClassName = emotionCss(optionClass.styles);

  return (
    <ThirdPartyComponent basicClassName={basicClassName} optionClassName={optionClassName} />
  )
}

When you have a Class Component, you need to use the also undocumented withTheme from @mui/material/styles and wrap your class, if you use the theme.

WHEN IT IS NOT AN USE CASE

When your component uses a single className property just use styled components.

import { styled } from "@mui/material/styles";

const ThrirdPartyStyled = styled(ThirdPartyComponent)(({theme}) => ({
  color: theme.palette.success.contrastText
}))

Even if you have dynamic styles

import { styled } from "@mui/material/styles";

interface IThrirdPartyStyledExtraProps {
  fullWidth?: boolean;
}

const ThrirdPartyStyled = styled(ThirdPartyComponent, {
  shouldForwardProp: (prop) => prop !== "fullWidth"
})<IThrirdPartyStyledExtraProps>(({theme, fullWidth}) => ({
  color: theme.palette.success.contrastText,
  width: fullWidth ? "100%" : "auto",
}))

Even if each one has some form of custom color, you just would use "sx" on your new ThrirdPartyStyled.

When you are just trying to reuse a style around (your use case)

const myReusableStyle = {
  color: "red",
}

// better
const MyStyledDiv = styled("div")(myReusableStyle);
// questionable
const MySpanWithoutStyles = styled("span")();

// better
const MyDrawerStyled = styled(Drawer)(myReusableStyle);

function MyComponent() {
  return (
    <MyStyledDiv>
      questionable usage because it is less clean:
      <MySpanWithoutStyles sx={myReusableStyle}>hello</MySpanWithoutStyles>
      <MySpanWithoutStyles sx={myReusableStyle}>world</MySpanWithoutStyles>

      these two are equivalent:
      <MyDrawerStyled />
      <Drawer sx={myReusableStyle} />
    </MyStyledDiv>
  )
}

Now what is "presumably" cool about this is that your style, is just an object now, and you can just import it and use it everywhere without makeStyles or withStyles, supposedly an advantage, even when to be honest, I have never used that of exporting/importing around; the code seems a bit cleaner nevertheless.

You seem to want to use it so all you do is.

export const myStyles {
  // your styles here
}

because this object is equivalent in memory, and it is always the same object, something that is easier to mess up with styles, it should be as effective or even more than your hook, theoretically (if it re-renders often even when setup may be longer), which stores the same function in memory but returns a new object every time.

Now you can use those myStyles everywhere you deem reasonable, either with styled components or by assigning to sx.

You can further optimize, say if it's always a div that you use that is styled the same way, then the styled component MyStyledDiv should be faster, because it is the same and done each time. How much faster is this? According to some sources 55% faster, to me, it is taking 4 weeks of refactor and the JSS compatibility with emotion is bad, all mixed with SSR is making everything unusable and slow and broken, so let's see until then when the whole is refactored.


来源: stackexchange

问:
Excel INDEX MATCH COUNTIF
I know this is very simple, but I'm quite stuck on that. I have a very simple file with the following columns:

I need to count how many people have chosen the fruit specified in column C.
I tried to do something like

```<code>=INDEX($B$1:$B$8,MATCH("*"&$C1&"*",$A$1:$A$8,0))
</code>```

And it correctly finds the first person corresponding to a given fruit, but how to make it count the total number of people?
I've tried using countif, but I'm missing something...

答:
If you want to be sure to not match a substring, like count "apple" in "pineapple", you'll have to cover several cases:

when the word occurs at the start of the list

when the word occurs at the end of the list

when the list only has that word

when the word occurs anywhere else in the list

So then the formula for cell C1 becomes:

```<code>=COUNTIF(A:A,"*, "&C1&",*") +COUNTIF(A:A,C1&",*")+COUNTIF(A:A,"*, "&C1)+COUNTIF(A:A,C1)
</code>```

This assumes the comma separated list always has exactly one space after the comma, and none before it.

ContentLicense: CC BY-SA 4.0

Title: Excel INDEX MATCH COUNTIF

Body:
I know this is very simple, but I'm quite stuck on that. I have a very simple file with the following columns:

I need to count how many people have chosen the fruit specified in column C.
I tried to do something like

=INDEX($B$1:$B$8,MATCH("*"&$C1&"*",$A$1:$A$8,0))

And it correctly finds the first person corresponding to a given fruit, but how to make it count the total number of people?
I've tried using countif, but I'm missing something...

Body:
If you want to be sure to not match a substring, like count "apple" in "pineapple", you'll have to cover several cases:

when the word occurs at the start of the list

when the word occurs at the end of the list

when the list only has that word

when the word occurs anywhere else in the list

So then the formula for cell C1 becomes:

=COUNTIF(A:A,"*, "&C1&",*") +COUNTIF(A:A,C1&",*")+COUNTIF(A:A,"*, "&C1)+COUNTIF(A:A,C1)

This assumes the comma separated list always has exactly one space after the comma, and none before it.


问:
How to set up Netbeans 12 with CCLS for C/C++ programming on Ubuntu 21.04
How do I set up Netbeans 12.3 on Ubuntu 21.04 for C/C++ programming?
In Netbeans the plugin is marked as Temporary, and says it uses CCLS (CC Language Server).
I can install that native with "apt install ccls"
In Netbeans under Tools/Options/C/C++ the path /usr/bin/ccls is set.
In Project Properties there are two options, Editor and Build
For Editor I can guess I write, "gcc hello.c -o hello.out"
For Build, there are Build, Clean and Run data entry textboxes, which I can write:-
Build: "gcc hello.c -o hello.out"
Run: "hello.out"

But nothing works properly.
CCLS search gets me to "https://github.com/MaskRay/ccls", but there is nothing in the Editor Configuration for Netbeans.

Anyone?

答:
Which plugin do you use? CPPLite Kit or C/C++ from NetBeans 8.2 Plugin Portal.
You can try C/C++: Open Plugins (Tools >> Plugins) window and switch to tab Settings and select NetBeans 8.2 Plugin Portal. Then go to tab Available Plugins and click Check for Newest and search for C/C++.

If you want to use CPPLite Kit you must have .ccls file in your project directory. Right click on your project select Properities and in the
Editor section set path of Compile Commands to .ccls file in your project folder.

.ccls file can contain this:

```<code>g++
-xc++
-Iinclude
-std=c++17
</code>```

.ccls is whole name of the file, not like something.ccls.

Body:
Which plugin do you use? CPPLite Kit or C/C++ from NetBeans 8.2 Plugin Portal.
You can try C/C++: Open Plugins (Tools >> Plugins) window and switch to tab Settings and select NetBeans 8.2 Plugin Portal. Then go to tab Available Plugins and click Check for Newest and search for C/C++.

If you want to use CPPLite Kit you must have .ccls file in your project directory. Right click on your project select Properities and in the
Editor section set path of Compile Commands to .ccls file in your project folder.

.ccls file can contain this:

g++
-xc++
-Iinclude
-std=c++17

.ccls is whole name of the file, not like something.ccls.


问:
Ansible include_tasks will not run when tags are specified
I am including some tasks like shown below in my main.yml (as one of the tasks in a list of several other tasks)

```<code>- name          : remove swarm
  include_tasks : swarm.undo.yml
  tags          : [ 'never', 'debug' ]
</code>```

when I run the playbook specifying the --tags never It just don't run, but shows the output below.

```<code>PLAY [all] *****************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************
ok: [node2]
ok: [node4]
ok: [node3]
ok: [node5]
ok: [node1]
ok: [node6]

TASK [swarm : remove swarm] ************************************************************************************************************************************
included: /home/xbox/Work/Infra/roles/swarm/tasks/swarm.undo.yml for node1, node2, node3, node4, node5, node6

PLAY RECAP *****************************************************************************************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node2                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node3                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node4                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node5                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node6                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
</code>```

If I do not specify and comment out the other tasks in that group (plus remove the never tag). It runs as it should.

Why is this behavior? What should I do to make it run correctly?

答:
You should use "apply" keyword, this doesn't work if you write without that one.
The correct syntax (from documentation) is

```<code>- name: Apply tags to tasks within included file
  include_tasks:
    file: install.yml
    apply:
      tags:
        - install
</code>```

If you want to run all tasks using one tags there is the best way below:

```<code>- name: Include and run an inner and an outer task
  include_tasks:
    file: install.yml
    apply:
      tags: install
  tags: install
</code>```

Body:
I am including some tasks like shown below in my main.yml (as one of the tasks in a list of several other tasks)

- name          : remove swarm
  include_tasks : swarm.undo.yml
  tags          : [ 'never', 'debug' ]

when I run the playbook specifying the --tags never It just don't run, but shows the output below.

PLAY [all] *****************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************
ok: [node2]
ok: [node4]
ok: [node3]
ok: [node5]
ok: [node1]
ok: [node6]

TASK [swarm : remove swarm] ************************************************************************************************************************************
included: /home/xbox/Work/Infra/roles/swarm/tasks/swarm.undo.yml for node1, node2, node3, node4, node5, node6

PLAY RECAP *****************************************************************************************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node2                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node3                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node4                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node5                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node6                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

If I do not specify and comment out the other tasks in that group (plus remove the never tag). It runs as it should.

Why is this behavior? What should I do to make it run correctly?

Body:
You should use "apply" keyword, this doesn't work if you write without that one.
The correct syntax (from documentation) is

- name: Apply tags to tasks within included file
  include_tasks:
    file: install.yml
    apply:
      tags:
        - install

If you want to run all tasks using one tags there is the best way below:

- name: Include and run an inner and an outer task
  include_tasks:
    file: install.yml
    apply:
      tags: install
  tags: install


问:
CakePHP hasMany - belongsTo - hasMany relationship
I have a bit more complex system...
I have

users model - hasMany Ads

ads model - hasMany "placads"

placads model - belongsTo Ads and Places

places model - hasMany placads

Now I run query like this:

```<code>    $this->set(
        'ad',
        $this->User->Ad->find(
            'all',
            array(
                'conditions' => array('Ad.user_id' => $this->Auth->user('id'))
            )
        )
    );
</code>```

and I am getting this without "Place" in * mark

```<code>[0] => Array
    (
        [Ad] => Array
            (
                [id] => 1
                [user_id] => 1
                [name] => bota
            )

        [Placad] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [ad_id] => 1
                        [place_id] => 1
                        [count] => 10
                        *[Place] => Array
                        (
                            info about place
                        )*
                    )

                [1] => Array
                    (
                        [id] => 2
                        [ad_id] => 1
                        [place_id] => 2
                        [count] => 20
                        *[Place] => Array
                        (
                            info about place
                        )*
                    )

            )

    )
</code>```

What should I do to get something like I wrote into the * mark?

Thanks in advance!

答:
use recursive:

http://book.cakephp.org/view/1063/recursive

```<code>$this->User->Ad->recursive = 2; // before find
</code>```

alternatively:

```<code>$this->User->Ad->find( 'all',
    array(
        'recursive' => 2,
        'conditions' => array('Ad.user_id' => $this->Auth->user('id'))
    )
)
</code>```

number 2 is an example, but should do in your case

2nd alternative:

use Containable

http://book.cakephp.org/view/1323/Containable

ContentLicense: CC BY-SA 3.0

Body:
I have a bit more complex system...
I have

users model - hasMany Ads

ads model - hasMany "placads"

placads model - belongsTo Ads and Places

places model - hasMany placads

Now I run query like this:

    $this->set(
        'ad',
        $this->User->Ad->find(
            'all',
            array(
                'conditions' => array('Ad.user_id' => $this->Auth->user('id'))
            )
        )
    );

and I am getting this without "Place" in * mark

[0] => Array
    (
        [Ad] => Array
            (
                [id] => 1
                [user_id] => 1
                [name] => bota
            )

        [Placad] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [ad_id] => 1
                        [place_id] => 1
                        [count] => 10
                        *[Place] => Array
                        (
                            info about place
                        )*
                    )

                [1] => Array
                    (
                        [id] => 2
                        [ad_id] => 1
                        [place_id] => 2
                        [count] => 20
                        *[Place] => Array
                        (
                            info about place
                        )*
                    )

            )

    )

What should I do to get something like I wrote into the * mark?

Thanks in advance!

Body:
use recursive:

http://book.cakephp.org/view/1063/recursive

$this->User->Ad->recursive = 2; // before find

alternatively:

$this->User->Ad->find( 'all',
    array(
        'recursive' => 2,
        'conditions' => array('Ad.user_id' => $this->Auth->user('id'))
    )
)

number 2 is an example, but should do in your case

2nd alternative:

use Containable

http://book.cakephp.org/view/1323/Containable


问:
Generated boolean list cannot be changed its value
I need to create an authentication page. It has locations. I have gathered the info from api with future and i assigned them with generated bool list but i cannot change their values. Here is my code examples...

```<code>ListView.builder(
   padding: EdgeInsets.fromLTRB(0,12,0,0),
   shrinkWrap: true,
   primary: false,
   itemCount: snapshot.data!.locationList!.length,
   itemBuilder:
      (context, index) {
         final locations = snapshot.data!.locationList!;
         List<bool>? x = List<bool>.generate(locations.length, (index) => false);
         debugPrint(x[0].toString()); //false
         debugPrint(locations[0].id.toString()); //1
         return Padding(
                   padding: const EdgeInsets.fromLTRB(12,6,12,6),
                   child: Row(
                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
                             children: <Widget>[
                             Text('${locations[index].name}', style: TextStyle(fontSize: 20),),
                             FlutterSwitch(
                                 width: width*.2,
                                 height: 50.0,
                                 activeColor: col.mostDarkPurpleAccent,
                                 toggleSize: width*.06,
                                 value: LoginApi.distinctLocation.contains(index+1) ? !x[index] : x[index],
                                 borderRadius: 30.0,
                                 padding: 8.0,
                                 onToggle: (bool val) {
                                          debugPrint(val.toString()); //false
                                          setState(() {
                                            debugPrint('setState başı: '+x[index].toString()); //false
                                            if (LoginApi.distinctLocation.contains(index+1)) {
                                              debugPrint('if başı: '+x[index].toString()); //false
                                              x[index] = !val;
                                              debugPrint('if sonu: '+x[index].toString()); //true
                                            } else {
                                              debugPrint('else başı: '+x[index].toString()); //not in
                                              x[index] = !val;
                                              debugPrint('else sonu: '+x[index].toString()); //not in
                                            }
                                            debugPrint('setState sonu: '+x[index].toString()); //true
                                          });
                             },
                       ),
                   ],
               ),
         );
    },
),
</code>```

Here are codes, but i cannot toggle it. What is the problem? Could you help me, pls?

答: If you are setting a value to x[index] in your onToggle: (bool val){} and call setState() then your value is already changed and affects to your view. So you dont need to do that: value:LoginApi.distinctLocation.contains(index+1) ? !x[index] : x[index], use instead only: value: x[index],

Body:
I need to create an authentication page. It has locations. I have gathered the info from api with future and i assigned them with generated bool list but i cannot change their values. Here is my code examples...

ListView.builder(
   padding: EdgeInsets.fromLTRB(0,12,0,0),
   shrinkWrap: true,
   primary: false,
   itemCount: snapshot.data!.locationList!.length,
   itemBuilder:
      (context, index) {
         final locations = snapshot.data!.locationList!;
         List<bool>? x = List<bool>.generate(locations.length, (index) => false);
         debugPrint(x[0].toString()); //false
         debugPrint(locations[0].id.toString()); //1
         return Padding(
                   padding: const EdgeInsets.fromLTRB(12,6,12,6),
                   child: Row(
                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
                             children: <Widget>[
                             Text('${locations[index].name}', style: TextStyle(fontSize: 20),),
                             FlutterSwitch(
                                 width: width*.2,
                                 height: 50.0,
                                 activeColor: col.mostDarkPurpleAccent,
                                 toggleSize: width*.06,
                                 value: LoginApi.distinctLocation.contains(index+1) ? !x[index] : x[index],
                                 borderRadius: 30.0,
                                 padding: 8.0,
                                 onToggle: (bool val) {
                                          debugPrint(val.toString()); //false
                                          setState(() {
                                            debugPrint('setState başı: '+x[index].toString()); //false
                                            if (LoginApi.distinctLocation.contains(index+1)) {
                                              debugPrint('if başı: '+x[index].toString()); //false
                                              x[index] = !val;
                                              debugPrint('if sonu: '+x[index].toString()); //true
                                            } else {
                                              debugPrint('else başı: '+x[index].toString()); //not in
                                              x[index] = !val;
                                              debugPrint('else sonu: '+x[index].toString()); //not in
                                            }
                                            debugPrint('setState sonu: '+x[index].toString()); //true
                                          });
                             },
                       ),
                   ],
               ),
         );
    },
),

Here are codes, but i cannot toggle it. What is the problem? Could you help me, pls?


问:
Web accessibility language detection with Voiceover
How does Voiceover detect language and how can I make it "speak" the same language throughout a website?

My computer is in English, I am working on a website that offers various localizations.
Voiceover can very well read
 or  elements in that current local (not English) but when I focus on a <button> element, it doesn't detect the language and reads everything in English, which doesn't make sense because the text is not in English. I have the lang attribute set in  but it doesn't seem to help. I've even added the lang attribute to the button, but still nothing.

I have tried adding a
 element inside of a <button> but it still does the same thing.

Is that just how Voiceover works or am I doing something wrong?

答:
Have you tried to add the language manually in the System Settings?

Go to System Settings > Accessibility > Voice Over > "Open Voice Over Utility" > Speech > Click "+" button on the bottom to add a new language.


问:
'HTTP Error 401: Unauthorized' Unable to use Deta Base
I am using Deta Base to create a API using the Fast API framework.
I was able deploy my API using deta micros, it worked like a dream.

However, when I am trying to use the 'Deta Base' feature, It is giving me the following error:

```<code>urllib.error.HTTPError: HTTP Error 401: Unauthorized
</code>```

I have logged in in the terminal already, this was the result.

```<code>deta login
Logged in successfully.
</code>```

I have checked that my project key is correct, I also made a new project and copied and pasted the id directly in, so I am sure that my project key is linked to a Deta project.

This is my code.

```<code># python-decouple
from decouple import config
DETA_PROJECT_KEY = config('DETA-PROJECT-KEY')
DETA_PROJECT_ID = config('DETA-PROJECT-ID')
DETA_BASE_NAME = config('DETA-BASE-NAME')

# Deta Base
from deta import Deta
deta = Deta('DETA-PROJECT-KEY')
locations_of_interest = deta.Base('locations_of_interest')

locations_of_interest.insert({"hello":"world"})
new_home = next(locations_of_interest.fetch({"hello":"world"}))
</code>```

How can I fix this?

Thank you for your help!!

答:
from looking at your code, I could identify the issue that you are passing a string instead of the actual project key, try fixing that by replacing 'DETA-PROJECT-KEY' with DETA_PROJECT_KEY as follows:

deta = Deta(DETA_PROJECT_KEY)
```

If this issue persists, feel free to reach out to us (the Deta team) on Discord/Slack/Intercom, we're happy to help.

Body:
I am using Deta Base to create a API using the Fast API framework.
I was able deploy my API using deta micros, it worked like a dream.

However, when I am trying to use the 'Deta Base' feature, It is giving me the following error:

urllib.error.HTTPError: HTTP Error 401: Unauthorized

I have logged in in the terminal already, this was the result.

deta login
Logged in successfully.

I have checked that my project key is correct, I also made a new project and copied and pasted the id directly in, so I am sure that my project key is linked to a Deta project.

This is my code.

# python-decouple
from decouple import config
DETA_PROJECT_KEY = config('DETA-PROJECT-KEY')
DETA_PROJECT_ID = config('DETA-PROJECT-ID')
DETA_BASE_NAME = config('DETA-BASE-NAME')

# Deta Base
from deta import Deta
deta = Deta('DETA-PROJECT-KEY')
locations_of_interest = deta.Base('locations_of_interest')

locations_of_interest.insert({"hello":"world"})
new_home = next(locations_of_interest.fetch({"hello":"world"}))

How can I fix this?

Thank you for your help!!

Body:
from looking at your code, I could identify the issue that you are passing a string instead of the actual project key, try fixing that by replacing 'DETA-PROJECT-KEY' with DETA_PROJECT_KEY as follows:

deta = Deta(DETA_PROJECT_KEY)

If this issue persists, feel free to reach out to us (the Deta team) on Discord/Slack/Intercom, we're happy to help.


问:
Make sure, pipelines run sequential in gitlab
of course I am aware, that single jobs run in sequence FIFO if these jobs are pointing to a single runner, so they have to wait.

That is fine.

For a test environment, where we can only deploy & test one version at a time, we need not only single jobs to be queryed, but whole pipelines.

To be clear: If we have Job_Deploy & Job_Test which are Part of a Pipeline Pipeline, we need to wait for the whole pipeline to be done.

By now we have the scenario, that the sequence can possible not be in order:

Job_Deploy1, Job_Deploy2, Job_Test2, Job_Test1 may be the case.

But we need it strict FIFO

Pipeline1(Job_Deploy1, Job_Test1), Pipeline(Job_Deploy2, Job_Test2)

How can we achieve this?

Why do we seem to be alone with this requirement? Do we have any wrong perceptions here? Is it best practice? If not: why?

Best regards

答:
It seems like i misread the question and my initial answer is not applicable, i leave it at the end.

Right answer:

Use resource_group to create a resource group that ensures a job is mutually exclusive across different pipelines for the same project.

There are are so called resource_groups which you can use to force a certain order. and which ensures that jobs only run after each other even if they are in separate pipelines.

https://docs.gitlab.com/ee/ci/yaml/#resource_group

Wrong answer:

What you are looking for is the needs directive.

It offers you the possibility to express job dependencies within your ci file.

Something like

deploy1:
  script: echo "deploy 1"

test1:
  script: echo "test 1"
  needs:
    - deploy1
```

This means that test1 even if it is in the same stage, will not start as long as deploy1 has finished. Furthermore, you could also add needs: [] to deploy1 to start it immediately even if it is in a later stage. needs is powerful and allows you to work outside the stage boundaries.

Take a look at https://docs.gitlab.com/ee/ci/yaml/#needs

Body:
It seems like i misread the question and my initial answer is not applicable, i leave it at the end.

Right answer:

Use resource_group to create a resource group that ensures a job is mutually exclusive across different pipelines for the same project.

There are are so called resource_groups which you can use to force a certain order. and which ensures that jobs only run after each other even if they are in separate pipelines.

https://docs.gitlab.com/ee/ci/yaml/#resource_group

Wrong answer:

What you are looking for is the needs directive.

It offers you the possibility to express job dependencies within your ci file.

Something like

deploy1:
  script: echo "deploy 1"

test1:
  script: echo "test 1"
  needs:
    - deploy1

This means that test1 even if it is in the same stage, will not start as long as deploy1 has finished. Furthermore, you could also add needs: [] to deploy1 to start it immediately even if it is in a later stage. needs is powerful and allows you to work outside the stage boundaries.

Take a look at https://docs.gitlab.com/ee/ci/yaml/#needs


问:
Progressbar for long running function WP7 C#
I am writing a sudoku solver app. The calculation time of the solver in certain cases can exceed 3 seconds, which would require a progress bar.

so my code:

```<code>private void solveButton_Click(object sender, RoutedEventArgs e)
{
    progressBar1.Visibility = Visibility.Visible;
    progressBar1.IsIndeterminate = true;
    mySolver.Solve(initialValue)
    progressBar1.Visilibity=Visilibity.collapsed;
    progressBar1.IsIndeterminate = false;
}
</code>```

The code here is a condensed version of my actual code. This code doesn't work, as the progress bar does not appear at all. It seems to me that the UI updates only after event is finised executed. If I didn't hide the progressbar after the solver step, the progressBar appears after the sudoku is solved. Replacing the solver with thread.sleep(1000) also results in the same UI update.

thanks for your help.

答: If you still want to run it on the UI Thread (which i wouldn't recommend!!) you can use the progressbar from the WP7 Toolkit that was released yesterday. It contains a progressbar that will work while your UI Thread is blocked.</p>

Body:
I am writing a sudoku solver app. The calculation time of the solver in certain cases can exceed 3 seconds, which would require a progress bar.

so my code:

private void solveButton_Click(object sender, RoutedEventArgs e)
{
    progressBar1.Visibility = Visibility.Visible;
    progressBar1.IsIndeterminate = true;
    mySolver.Solve(initialValue)
    progressBar1.Visilibity=Visilibity.collapsed;
    progressBar1.IsIndeterminate = false;
}

The code here is a condensed version of my actual code. This code doesn't work, as the progress bar does not appear at all. It seems to me that the UI updates only after event is finised executed. If I didn't hide the progressbar after the solver step, the progressBar appears after the sudoku is solved. Replacing the solver with thread.sleep(1000) also results in the same UI update.

thanks for your help.


问:
Wrong version number error on *some* websites during handshake with Asio and OpenSSL
I'm trying to send https web requests with Asio and OpenSSL. My code is working fine on most of the sites I tried it on, but on some others, I get an error during the handshake handshake: wrong version number (SSL routines, ssl3_get_record).

I've found some people having this issue because they were behind proxies or because they tried to connect to port 80 instead of port 443, but this is not the case here (as far as I know) because the exact same code (see below for minimal example) works for most of the sites I tried it on.

I've tried to check with wireshark to see if I could spot the difference between a case with and one without the error. Here what I found:

when it works, TLSv1.2 or 1.3 is used, when it doesn't, it's TLSv1

when it doesn't work, the DNS query shows a cloudfront cname redirection, but the endpoint used for the socket matches the redirection

Based on these observations, I know my code is capable of using TLSv1.3, and I thought that using TLSv1 was the issue. So I tried to force asio to use a version > 1 for TLS with asio::ssl::context::tlsv13_client when creating the context, or by adding asio::ssl::context::no_tlsv1 to set_options, but wireshark still showed that a TLSv1 protocol was used.

For the second point, I'm not too familiar with web stuff, so I'm not sure what conclusion I can make about that, or even if it's relevant to the issue.

Minimal working example:

#include <asio.hpp>
#include <asio/ssl.hpp>

#include <iostream>

int main(int argc, char* argv[])
{
    try
    {
        asio::io_context io_context;
        asio::ip::tcp::resolver resolver(io_context);
        asio::ip::tcp::resolver::results_type endpoints = resolver.resolve("google.com", "https"); //not working with "api.minecraftservices.com" for example

        asio::ssl::context ctx(asio::ssl::context::sslv23); // also tried tlsv13_client to force v1.3, without success
        ctx.set_default_verify_paths();
        ctx.set_options(asio::ssl::context::default_workarounds | asio::ssl::context::verify_none);

        asio::ssl::stream<asio::ip::tcp::socket> socket(io_context, ctx);
        socket.set_verify_mode(asio::ssl::verify_none);
        socket.set_verify_callback([](bool, asio::ssl::verify_context&) {return true; });
        asio::connect(socket.lowest_layer(), endpoints);
        socket.handshake(socket.client);
    }
    catch (const std::exception& e)
    {
        std::cout << e.what() << std::endl;
        return -1;
    }

    return 0;
}
```

答:
You need to be more specific about the server you are trying to connect to:

Live On Coliru

```<code>#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <iostream>

namespace ssl = boost::asio::ssl;
using boost::asio::ip::tcp;

int main() {
    try {
        boost::asio::io_context io_context;
        tcp::resolver           resolver(io_context);

        ssl::context ctx(ssl::context::sslv23); // also tried tlsv13_client to
                                                // force v1.3, without success
        ctx.set_default_verify_paths();
        ctx.set_options(ssl::context::default_workarounds |
                        ssl::context::verify_none);

        ssl::stream<tcp::socket> socket(io_context, ctx);
        socket.set_verify_mode(ssl::verify_none);
        socket.set_verify_callback([](auto&&...) { return true; });

#ifndef COLIRU
        connect(socket.lowest_layer(), resolver.resolve("d7uri8nf7uskq.cloudfront.net", "https"));
#else
        socket.lowest_layer().connect({boost::asio::ip::address_v4::from_string("65.9.84.220"), 443});
#endif
        std::cout << "Connected to " << socket.lowest_layer().remote_endpoint() << "\n";
        socket.handshake(socket.client);
    } catch (std::exception const& e) {
        std::cout << e.what() << std::endl;
        return -1;
    }
}
</code>```

Prints

```<code>Connected to 65.9.84.220:443
</code>```

UPDATE

Indeed, using api.minecraftservices.com:443 does print

```<code>Connected to 65.9.78.95:443
handshake: wrong version number (SSL routines, ssl3_get_record) [asio.ssl:336130315]
</code>```

It turns out you need SNI:

```<code>SSL_set_tlsext_host_name(socket.native_handle(), "api.minecraftservices.com");
</code>```

And then it works (with varying IP resolutions)

```<code>Connected to 65.9.78.23:443
</code>```

Body:
You need to be more specific about the server you are trying to connect to:

Live On Coliru

#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <iostream>

namespace ssl = boost::asio::ssl;
using boost::asio::ip::tcp;

int main() {
    try {
        boost::asio::io_context io_context;
        tcp::resolver           resolver(io_context);

        ssl::context ctx(ssl::context::sslv23); // also tried tlsv13_client to
                                                // force v1.3, without success
        ctx.set_default_verify_paths();
        ctx.set_options(ssl::context::default_workarounds |
                        ssl::context::verify_none);

        ssl::stream<tcp::socket> socket(io_context, ctx);
        socket.set_verify_mode(ssl::verify_none);
        socket.set_verify_callback([](auto&&...) { return true; });

#ifndef COLIRU
        connect(socket.lowest_layer(), resolver.resolve("d7uri8nf7uskq.cloudfront.net", "https"));
#else
        socket.lowest_layer().connect({boost::asio::ip::address_v4::from_string("65.9.84.220"), 443});
#endif
        std::cout << "Connected to " << socket.lowest_layer().remote_endpoint() << "\n";
        socket.handshake(socket.client);
    } catch (std::exception const& e) {
        std::cout << e.what() << std::endl;
        return -1;
    }
}

Prints

Connected to 65.9.84.220:443

UPDATE

Indeed, using api.minecraftservices.com:443 does print

Connected to 65.9.78.95:443
handshake: wrong version number (SSL routines, ssl3_get_record) [asio.ssl:336130315]

It turns out you need SNI:

SSL_set_tlsext_host_name(socket.native_handle(), "api.minecraftservices.com");

And then it works (with varying IP resolutions)

Connected to 65.9.78.23:443


问:
How to grow a popover controller
I have a popover controller in my app for iPad and Mac (using mac catalyst) and I'm trying to figure out how to grow the height of the popover when it's already presented. I've been searching everywhere on how to do this but everything I find is about setting the size before presenting but not after.

While the pop-up is presenting, there's a button in it that should grow the height by 100-150 pixels, but I can not figure out how

Can anyone please help me with this? Thank you in advance!

Here's my popover presenting code:

```<code>func openView(sourceView: UIView?, sourceRect: CGRect?) {
    let vc = ViewControllerA()

    //Try popover
    if let sourceView = sourceView,
        let sourceRect = sourceRect {
            vc.modalPresentationStyle = .popover

            if let popover = vc.popoverPresentationController {
                vc.preferredContentSize = return CGSize(width: 390, height: 390)
                vc.presentationController?.delegate = self

                popover.sourceView = sourceView
                popover.sourceRect = sourceRect
                popover.permittedArrowDirections = [.up, .left]

                self.present(vc, animated: true, completion: nil)
                return
            }
        }

    //present it normally if there's no source view
    vc.modalPresentationStyle = .overCurrentContext
    vc.modalTransitionStyle = .crossDissolve

    self.present(vc, animated: true, completion: nil)
}

</code>```

答:
To change a size of your presented controller in popover view you should modify its preferredContentSize property:

@IBAction func showPopover(_ sender: UIButton) {
    // Create controller
    guard let controller = storyboard?.instantiateViewController(withIdentifier: "Popover") else {
        return
    }
    controller.modalPresentationStyle = .popover
    controller.preferredContentSize = CGSize(width: 200, height: 200)

    // Configure popover
    guard let popover = controller.popoverPresentationController else {
        return
    }
    popover.permittedArrowDirections = .up
    popover.sourceView = self.view
    popover.sourceRect = sender.frame
    popover.delegate = self
    present(controller, animated: true, completion: nil)

    // Change height after 3 secs
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
        controller.preferredContentSize = CGSize(width: 200, height: 400)
    }
}
```

Title: How to grow a popover controller

Body:
I have a popover controller in my app for iPad and Mac (using mac catalyst) and I'm trying to figure out how to grow the height of the popover when it's already presented. I've been searching everywhere on how to do this but everything I find is about setting the size before presenting but not after.

While the pop-up is presenting, there's a button in it that should grow the height by 100-150 pixels, but I can not figure out how

Can anyone please help me with this? Thank you in advance!

Here's my popover presenting code:

func openView(sourceView: UIView?, sourceRect: CGRect?) {
    let vc = ViewControllerA()

    //Try popover
    if let sourceView = sourceView,
        let sourceRect = sourceRect {
            vc.modalPresentationStyle = .popover

            if let popover = vc.popoverPresentationController {
                vc.preferredContentSize = return CGSize(width: 390, height: 390)
                vc.presentationController?.delegate = self

                popover.sourceView = sourceView
                popover.sourceRect = sourceRect
                popover.permittedArrowDirections = [.up, .left]

                self.present(vc, animated: true, completion: nil)
                return
            }
        }

    //present it normally if there's no source view
    vc.modalPresentationStyle = .overCurrentContext
    vc.modalTransitionStyle = .crossDissolve

    self.present(vc, animated: true, completion: nil)
}


问:
Remove entire table when there is no input in searchbox?
I have been twisting my head around on this and I can't seem to fix it.

I have not coded much, but wanting to learn. However, I am trying to make a table in which when there is no input the entire table vanishes.

As of now I have managed to get it so that it starts as vanished, and that when information is inserted into the search box the non-relevant lines dissapear. However, when all text in the search box is removed the entire table is showing. I want the table to stay hidden when there is no text that matches.

Would love to get any feedback on what I am doing wrong here.

    function performSearch() {

  // Declare search string
  var filter = searchBox.value.toUpperCase();

  // Loop through first tbody's rows
  for (var rowI = 0; rowI < trs.length; rowI++) {

    // define the row's cells
    var tds = trs[rowI].getElementsByTagName("td");

    // hide the row
    trs[rowI].style.display = "none";

    // loop through row cells
    for (var cellI = 0; cellI < tds.length; cellI++) {

      // if there's a match
      if (tds[cellI].innerHTML.toUpperCase().indexOf(filter) > -1)
        {

        // show the row
            myTable.style.display = "table";
        trs[rowI].style.display = "";

        // skip to the next row
        continue;

      }

    }
  }

}

// declare elements
const searchBox = document.getElementById('searchBox');
const table = document.getElementById("myTable");
const trs = table.tBodies[0].getElementsByTagName("tr");

// add event listener to search box
searchBox.addEventListener('keyup', performSearch);

      ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  * {
  box-sizing: border-box;
}

#searchBox {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 30%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
position: relative;
 top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);

}

#myTable {
  border-collapse: collapse;
  width: 80%;
  border: 1px solid #ddd;
  font-size: 18px;
    position: relative;
left: 10%;
    display: none;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}

    #Overskrift {
    width: 100%;
 text-align-last: center;
  font-size: 40px;
}</code>```

<input class="form-control" type="text" id="searchBox" placeholder="Search ..." onkeyup="searchTableColumns()">

      Fagnavn
    LK20
    LK06
       R94

       Pika
    Chu
    Poke
 Mon

       Temporary
    Text
    Fields
       Here

```

答:
There is a simple solution for this. Just add a check to the end your performSearch function:

```<code>  if (searchBox.value === ''){
    table.style.display='none';
  }
  else {
    table.style.display='table';
  }
</code>```

You can also check it here:
https://codepen.io/serazoltan/pen/dyZRprb

Body:
I have been twisting my head around on this and I can't seem to fix it.

I have not coded much, but wanting to learn. However, I am trying to make a table in which when there is no input the entire table vanishes.

As of now I have managed to get it so that it starts as vanished, and that when information is inserted into the search box the non-relevant lines dissapear. However, when all text in the search box is removed the entire table is showing. I want the table to stay hidden when there is no text that matches.

Would love to get any feedback on what I am doing wrong here.

    function performSearch() {

  // Declare search string
  var filter = searchBox.value.toUpperCase();

  // Loop through first tbody's rows
  for (var rowI = 0; rowI < trs.length; rowI++) {

    // define the row's cells
    var tds = trs[rowI].getElementsByTagName("td");

    // hide the row
    trs[rowI].style.display = "none";

    // loop through row cells
    for (var cellI = 0; cellI < tds.length; cellI++) {

      // if there's a match
      if (tds[cellI].innerHTML.toUpperCase().indexOf(filter) > -1)
        {

        // show the row
            myTable.style.display = "table";
        trs[rowI].style.display = "";

        // skip to the next row
        continue;

      }

    }
  }

}

// declare elements
const searchBox = document.getElementById('searchBox');
const table = document.getElementById("myTable");
const trs = table.tBodies[0].getElementsByTagName("tr");

// add event listener to search box
searchBox.addEventListener('keyup', performSearch);

  * {
  box-sizing: border-box;
}

#searchBox {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 30%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
position: relative;
 top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);

}

#myTable {
  border-collapse: collapse;
  width: 80%;
  border: 1px solid #ddd;
  font-size: 18px;
    position: relative;
left: 10%;
    display: none;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}

    #Overskrift {
    width: 100%;
 text-align-last: center;
  font-size: 40px;
}

<input class="form-control" type="text" id="searchBox" placeholder="Search ..." onkeyup="searchTableColumns()">

      Fagnavn
    LK20
    LK06
       R94

       Pika
    Chu
    Poke
 Mon

       Temporary
    Text
    Fields
       Here

Body:
There is a simple solution for this. Just add a check to the end your performSearch function:

  if (searchBox.value === ''){
    table.style.display='none';
  }
  else {
    table.style.display='table';
  }

You can also check it here:
https://codepen.io/serazoltan/pen/dyZRprb


问:
How do I index an item in a JSON array from Python
I was thinking to myself how one would find the position of a JSON object in a JSON array through python

for example

```<code>{
    "users": [
        {
            "person1": [
                {
                    "money": 769967967456795806758905768494685798974560,
                    "name": "person1"
                }
            ]
        },
        {
            "person2": [
                {
                    "money": 696969696969969696969696969,
                    "name": "person2"
                }
            ]
        }
    ]
}
</code>```

For instance let's say I wanted to get the position of person 2 from the array in python so position 2

(I looked through websites and previous questions but couldn't figure it out)

(hello people from my last post :) )

If you need any extra materials posted please request it here

答:
a better way would be to use enumerate

# not a great way of doing it
>>> index = 0

>>> for value in values:
...     print(index, value)
...     index += 1
...
0 a
1 b
2 c
```
<pre class="lang-py prettyprint-override"><code># a better more efficient way of doing it using enumerate()
>>> for i, value in enumerate(json["names]):
...     print(i, value)
...
0 a
1 b
2 c
</code>```

Soltution:

data = {
    "users": [
        {
            "person1": [
                {
                    "money": 769967967456795806758905768494685798974560,
                    "name": "person1"
                }
            ]
        },
        {
            "person2": [
                {
                    "money": 696969696969969696969696969,
                    "name": "person2"
                }
            ]
        }
    ]
}

for i, name in enumerate(data['users']):
    print(i,name)
```
<h2>Output</h2>
```0 {'person1': [{'money': 769967967456795806758905768494685798974560, 'name': 'person1'}]}
1 {'person2': [{'money': 696969696969969696969696969, 'name': 'person2'}]}
```

with enumerate, there is much less code.

Then you could do something like person2 = data['users'][1]

Body:
I was thinking to myself how one would find the position of a JSON object in a JSON array through python

for example

{
    "users": [
        {
            "person1": [
                {
                    "money": 769967967456795806758905768494685798974560,
                    "name": "person1"
                }
            ]
        },
        {
            "person2": [
                {
                    "money": 696969696969969696969696969,
                    "name": "person2"
                }
            ]
        }
    ]
}

For instance let's say I wanted to get the position of person 2 from the array in python so position 2

(I looked through websites and previous questions but couldn't figure it out)

(hello people from my last post :) )

If you need any extra materials posted please request it here

Body:
a better way would be to use enumerate

# not a great way of doing it
>>> index = 0

>>> for value in values:
...     print(index, value)
...     index += 1
...
0 a
1 b
2 c

# a better more efficient way of doing it using enumerate()
>>> for i, value in enumerate(json["names]):
...     print(i, value)
...
0 a
1 b
2 c

Soltution:

data = {
    "users": [
        {
            "person1": [
                {
                    "money": 769967967456795806758905768494685798974560,
                    "name": "person1"
                }
            ]
        },
        {
            "person2": [
                {
                    "money": 696969696969969696969696969,
                    "name": "person2"
                }
            ]
        }
    ]
}

for i, name in enumerate(data['users']):
    print(i,name)

Output

0 {'person1': [{'money': 769967967456795806758905768494685798974560, 'name': 'person1'}]}
1 {'person2': [{'money': 696969696969969696969696969, 'name': 'person2'}]}

with enumerate, there is much less code.

Then you could do something like person2 = data['users'][1]


问:
Cannot Run PowerShell Scripts in Azure Functions v4 but works in console app
I am trying to execute PowerShell scripts in azure functions but it just ignores it, doesn't throw any errors, and I know the lines are not being really executed because it's just instant, and when running from ConsoleApp (same lines of code) it takes like 5 to 10 seconds and then brings the information well.

I looked into it and what I found is that I have to MANUALLY insert dll files to the output of the build. The thing is that I tried that and didn't have luck either.

```<code>        using (PowerShell ps = PowerShell.Create())
        {
            foreach (var line in query)
            {
                ps.AddScript(line);
                ps.AddParameters(prms);
                var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);
                foreach (var item in pipelineObjects)
                {
                    if (item != null) { } // it's always null here
                }
         }
</code>```

The line that should bring information is this one:

```<code>Get-AdminPowerAppEnvironment
</code>```

It works on Console App well, but not in Azure Function.

```<code><TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</code>```

答:
I've not used this module but just checking over the contents of the module on the PowerShell gallery it suggests that it users WinForms for authentication

https://www.powershellgallery.com/packages/Microsoft.PowerApps.Administration.PowerShell/2.0.27/Content/Microsoft.PowerApps.Administration.PowerShell.psd1

If this is the case then WinForms is not supported in PowerShell 7 within Azure Functions. You could create a PowerShell FunctionApp and call that from your C# function and see if you can workaround the Winforms issue by importing the PowerApps module with:

Import-Module Microsoft.PowerApps.Administration.PowerShell -UseWindowsPowerShell

Not sure if this would work but most of the O365 type modules aren't properly supported in PowerShell 7 and take some hacking around the limitations to get them to work.

Here is an example of one I created for importing the AzureAD module.

https://github.com/brettmillerb/azureadFunction/blob/main/addUser/run.ps1

Body:
I am trying to execute PowerShell scripts in azure functions but it just ignores it, doesn't throw any errors, and I know the lines are not being really executed because it's just instant, and when running from ConsoleApp (same lines of code) it takes like 5 to 10 seconds and then brings the information well.

I looked into it and what I found is that I have to MANUALLY insert dll files to the output of the build. The thing is that I tried that and didn't have luck either.

        using (PowerShell ps = PowerShell.Create())
        {
            foreach (var line in query)
            {
                ps.AddScript(line);
                ps.AddParameters(prms);
                var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);
                foreach (var item in pipelineObjects)
                {
                    if (item != null) { } // it's always null here
                }
         }

The line that should bring information is this one:

Get-AdminPowerAppEnvironment

It works on Console App well, but not in Azure Function.

<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>


问:
Video memory and android applications
I would like to know if the video memory (VRAM) that an android OpenGL application can use is limited ? If so, would you know what the limit is?</p>

答: The limit depends on how much the device has. On many devices, the VRAM is actually part of the general purpose RAM. I don't think there is a way to find how much there is at runtime. The total RAM on current devices will vary between about 256 MB and up. However, you may have problems allocating more than a certain limit (16MB, 24MB, 28MB etc.) that is fixed per device. See VM Limit in Android 2.0 for details.</p>

Title: Video memory and android applications


问:
How to change Jest module version for node.js 14?
I just started using JEST, I can't figure out what's wrong.
I've tried reinstalling all packages and clearing the cache.

```<code>  ● Test suite failed to run

    The module '/Users/dan_kos/Documents/Work/Authorization project/admin_service/server/node_modules/nodegit/build/Release/nodegit.node'
    was compiled against a different Node.js version using
    NODE_MODULE_VERSION 83. This version of Node.js requires
    NODE_MODULE_VERSION 102. Please try re-compiling or re-installing
    the module (for instance, using `npm rebuild` or `npm install`).

      at Runtime._loadModule (node_modules/jest-runtime/build/index.js:893:29)
      at Object.<anonymous> (node_modules/nodegit/dist/nodegit.js:12:12)

</code>```

Jest config:

```<code>"jest": {
    "preset": "ts-jest",
    "testEnvironment": "node",
    "transform": {
      "node_modules/variables/.+\\.(j|t)sx?$": "ts-jest"
    },
    "transformIgnorePatterns": [
      "node_modules/(?!variables/.*)"
    ]
  }```
```

答: It was an absolutely stupid mistake, I forgot to change the version of node.js in the WebStrom settings and it ran everything in version 17 instead of 14</p>

Body:
I just started using JEST, I can't figure out what's wrong.
I've tried reinstalling all packages and clearing the cache.

  ● Test suite failed to run

    The module '/Users/dan_kos/Documents/Work/Authorization project/admin_service/server/node_modules/nodegit/build/Release/nodegit.node'
    was compiled against a different Node.js version using
    NODE_MODULE_VERSION 83. This version of Node.js requires
    NODE_MODULE_VERSION 102. Please try re-compiling or re-installing
    the module (for instance, using `npm rebuild` or `npm install`).

      at Runtime._loadModule (node_modules/jest-runtime/build/index.js:893:29)
      at Object.<anonymous> (node_modules/nodegit/dist/nodegit.js:12:12)

Jest config:

"jest": {
    "preset": "ts-jest",
    "testEnvironment": "node",
    "transform": {
      "node_modules/variables/.+\\.(j|t)sx?$": "ts-jest"
    },
    "transformIgnorePatterns": [
      "node_modules/(?!variables/.*)"
    ]
  }```


问:
Rails creates many objects for has_one relationship
I've got two models in my Rails 5 app - User and Login with below association:

```<code>class User < ApplicationRecord
  belongs_to :login, optional: true
end

class Login < ApplicationRecord
  has_one :user
end
</code>```

I thought such an association would prevent the Login from having more than one User but it turns out that in a case when the Login.last already has associated user object:

```<code>2.4.5 :108 > Login.last.user
 => #<User id: 1, type: "Registrant", login_id: 43, first_name: "test", last_name: "test", created_at: "2022-02-11 11:22:25", updated_at: "2022-02-11 11:22:25">
</code>```

You can still create a new user with the same Login:

```<code>User.create(first_name: 'test2', last_name: 'test2', login_id: 43
 => #<User id: 2, login_id: 43, first_name: "test2", last_name: "test2", created_at: "2022-02-11 12:03:36", updated_at: "2022-02-11 12:03:36">
</code>```

But when you are trying to fetch last login user you will get the first created user:

```<code>Login.last.user
=> #<User id: 1, type: "Registrant", login_id: 43, first_name: "test", last_name: "test", created_at: "2022-02-11 11:22:25", updated_at: "2022-02-11 11:22:25">
</code>```

How to prevent creating a new user with a login that has already been used once?

答:
You can use validation to say that a login just can be use by one user.
This will look like this in model User:</p>
```<code>validates :login_id, uniqueness: true
</code>```

Body:
I've got two models in my Rails 5 app - User and Login with below association:

class User < ApplicationRecord
  belongs_to :login, optional: true
end

class Login < ApplicationRecord
  has_one :user
end

I thought such an association would prevent the Login from having more than one User but it turns out that in a case when the Login.last already has associated user object:

2.4.5 :108 > Login.last.user
 => #<User id: 1, type: "Registrant", login_id: 43, first_name: "test", last_name: "test", created_at: "2022-02-11 11:22:25", updated_at: "2022-02-11 11:22:25">

You can still create a new user with the same Login:

User.create(first_name: 'test2', last_name: 'test2', login_id: 43
 => #<User id: 2, login_id: 43, first_name: "test2", last_name: "test2", created_at: "2022-02-11 12:03:36", updated_at: "2022-02-11 12:03:36">

But when you are trying to fetch last login user you will get the first created user:

Login.last.user
=> #<User id: 1, type: "Registrant", login_id: 43, first_name: "test", last_name: "test", created_at: "2022-02-11 11:22:25", updated_at: "2022-02-11 11:22:25">

How to prevent creating a new user with a login that has already been used once?

Body:
You can use validation to say that a login just can be use by one user.
This will look like this in model User:

validates :login_id, uniqueness: true


问:
MySQL stored procedure BEGIN / END statements throwing errors
I'm trying to run a stored procedure and having real issues debugging.

I've tried cutting everything out to try and track down the issue, and even down to this I'm getting errors:

```<code>DROP PROCEDURE IF EXISTS sp_transpose_tickets;
CREATE PROCEDURE sp_transpose_tickets ()
BEGIN
select 1;
END
</code>```

errors are:

```<code>> Error : 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 '' at line 2
>
> Error : 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 'END' at line 1
</code>```

This is on my local machine, under root user so all privileges are granted and I am running mySQL 5.5.20.

答: I was having the same issue using Dbeaver. All I need to do was select my query from the beginning to the end and run the query. If I put my cursor only in the beginning without selecting all the code the same error was shown for me.</p>

Body:
I'm trying to run a stored procedure and having real issues debugging.

I've tried cutting everything out to try and track down the issue, and even down to this I'm getting errors:

DROP PROCEDURE IF EXISTS sp_transpose_tickets;
CREATE PROCEDURE sp_transpose_tickets ()
BEGIN
select 1;
END

errors are:

> Error : 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 '' at line 2
>
> Error : 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 'END' at line 1

This is on my local machine, under root user so all privileges are granted and I am running mySQL 5.5.20.


问:
python - json , how to make a json flat
so i have a nested json that contains two groups , each group has a field that contains more sub groups
i would like to pop all the sub groups out to flatten the json
and remove the sub groups field

What is the correct way to do it

JSON :

```<code>[
    {
        "groupId": "a_group",
        "version": "2.0.1",
        "type": "jar",
        "sub_group": [
            {
                "groupId": "a_1",
                "version": "2.0.0",
                "type": "jar",
                "sub_group": []
            },
            {
                "groupId": "a_2",
                "version": "2.0.1",
                "type": "jar",
                "sub_group": [
                                {
                                "groupId": "a_1",
                                "version": "2.0.0",
                                "type": "jar",
                                "sub_group": []
                                },
                ],
            }
        ],
    },
    {
        "groupId": "c_group",
        "version": "1.9.1",
        "type": "jar",
        "sub_group": [
                    {
                "groupId": "a_1",
                "version": "2.0.0",
                "type": "jar",
                "sub_group": []
            },
        ],
    },
}
</code>```

This is the expected result:
I need to pop all the sub groups and make them appear as a flat json like this

```<code>[{
        "groupId": "a_group",
        "version": "2.0.1",
        "type": "jar",
        "sub_group": []
    },
    {
        "groupId": "a_1",
        "version": "2.0.0",
        "type": "txt",
        "sub_group": []
    },
    {
        "groupId": "a_2",
        "version": "2.0.1",
        "type": "jar",
        "sub_group": []
    },
    {
        "groupId": "c_group",
        "version": "1.9.1",
        "type": "jar",
        "sub_group": []
    },
]
</code>```

答:
Well , i had an interview question very similar to your question

This is my answer:

```<code>def flatten_json(self,json_data) ->json:
    '''
    :param json_data: The json file to work on
    :return: A json
    '''

    out = []
    def flatten(key):
        if isinstance(key, dict):
            if key['sub_group']:
                flatten(key['sub_group'])
                key['sub_group'] = []
                out.append(key)
            else:
                out.append(key)

        # in case we have multiple items in the list[]
        elif isinstance(key, list):
            for val in key:
                flatten(val)

    flatten(json_data)
    return json.dumps(out)
</code>```

This is not the nicest solution but it works pretty good
I took the liberty of assuming the name of the sub_group is always subgroup
I used a recursion and i am handling moving into the dictionaries with the isinstance method to check if i am looking at a dictionary , if not then it means i have a list containing something else
I handle that in the elif part and i iterate over each item in the list

Title: python - json , how to make a json flat

Body:
so i have a nested json that contains two groups , each group has a field that contains more sub groups
i would like to pop all the sub groups out to flatten the json
and remove the sub groups field

What is the correct way to do it

JSON :

[
    {
        "groupId": "a_group",
        "version": "2.0.1",
        "type": "jar",
        "sub_group": [
            {
                "groupId": "a_1",
                "version": "2.0.0",
                "type": "jar",
                "sub_group": []
            },
            {
                "groupId": "a_2",
                "version": "2.0.1",
                "type": "jar",
                "sub_group": [
                                {
                                "groupId": "a_1",
                                "version": "2.0.0",
                                "type": "jar",
                                "sub_group": []
                                },
                ],
            }
        ],
    },
    {
        "groupId": "c_group",
        "version": "1.9.1",
        "type": "jar",
        "sub_group": [
                    {
                "groupId": "a_1",
                "version": "2.0.0",
                "type": "jar",
                "sub_group": []
            },
        ],
    },
}

This is the expected result:
I need to pop all the sub groups and make them appear as a flat json like this

[{
        "groupId": "a_group",
        "version": "2.0.1",
        "type": "jar",
        "sub_group": []
    },
    {
        "groupId": "a_1",
        "version": "2.0.0",
        "type": "txt",
        "sub_group": []
    },
    {
        "groupId": "a_2",
        "version": "2.0.1",
        "type": "jar",
        "sub_group": []
    },
    {
        "groupId": "c_group",
        "version": "1.9.1",
        "type": "jar",
        "sub_group": []
    },
]

Body:
Well , i had an interview question very similar to your question

This is my answer:

def flatten_json(self,json_data) ->json:
    '''
    :param json_data: The json file to work on
    :return: A json
    '''

    out = []
    def flatten(key):
        if isinstance(key, dict):
            if key['sub_group']:
                flatten(key['sub_group'])
                key['sub_group'] = []
                out.append(key)
            else:
                out.append(key)

        # in case we have multiple items in the list[]
        elif isinstance(key, list):
            for val in key:
                flatten(val)

    flatten(json_data)
    return json.dumps(out)

This is not the nicest solution but it works pretty good
I took the liberty of assuming the name of the sub_group is always subgroup
I used a recursion and i am handling moving into the dictionaries with the isinstance method to check if i am looking at a dictionary , if not then it means i have a list containing something else
I handle that in the elif part and i iterate over each item in the list


问:
Custom configuration section in app.config cannot read xml data as collection in C# application
I have following class extended ApplicationSettingsBase as below

```<code>public class SMTPServerConfig : ApplicationSettingsBase
{
    private static SMTPServerConfig instance = (SMTPServerConfig)Synchronized(new SMTPServerConfig());

    public static SMTPServerConfig Instance { get { return instance; } }

    [ApplicationScopedSetting]
    [DefaultSettingValue("")]
    [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Xml)]
    public List<SMTPServerConfigItem> SMTPServers
    {
        get
        {
            return ((List<SMTPServerConfigItem>)(this["SMTPServers"]));
        }
    }

    [ApplicationScopedSetting]
    [DefaultSettingValue("")]
    [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.String)]
    public string TestProp
    {
        get
        {
            return ((string)(this["TestProp"]));
        }
    }
}

[Serializable]
public class SMTPServerConfigItem
{

    public string SMTPHost { get; set; }
    public string SMTPPort { get; set; }
    public string SMTPAccount { get; set; }
    public string SMTPPassword { get; set; }
}
</code>```

Here is my App.config

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="Example.Config.SMTPServerConfig" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>

  </configSections>

  <applicationSettings>
    <Example.Config.SMTPServerConfig>
      <setting name="TestProp" serializeAs="String">
        <value>123123</value>
      </setting>
      <setting name="SMTPServers" serializeAs="Xml">
        <value>
          <SMTPServerConfigItem>
            <SMTPHost>smtp.example.com</SMTPHost>
            <SMTPPort>123</SMTPPort>
            <SMTPAccount>admin@example.com</SMTPAccount>
            <SMTPPassword>123456</SMTPPassword>
          </SMTPServerConfigItem>

          <SMTPServerConfigItem>
            <SMTPHost>smtp.example.com</SMTPHost>
            <SMTPPort>123</SMTPPort>
            <SMTPAccount>admin@example.com</SMTPAccount>
            <SMTPPassword>123456</SMTPPassword>
          </SMTPServerConfigItem>

        </value>

      </setting>
    </Example.Config.SMTPServerConfig>
  </applicationSettings>

</configuration>
</code>```

When i use SMTPServerConfig.Instance.TestProp it will show result is "123123" (it's true value, it mean i have correct config's schema for it), but SMTPServerConfig.Instance.SMTPServers.Count always zero. Where i'm wrong in code or config file ?

答:
After a hours of research, i found a question in stackoverflow then i know where i'm wrong. I was missing a xml tag in app.config file.
Question:
Trying to create a custom partial settings file

Then now i will correct my App.config file

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="Example.Config.SMTPServerConfig" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>

  </configSections>

  <applicationSettings>
    <Example.Config.SMTPServerConfig>
      <setting name="TestProp" serializeAs="String">
        <value>123123</value>
      </setting>
      <setting name="SMTPServers" serializeAs="Xml">
        <value>
          <ArrayOfSMTPServerConfigItem>
            <SMTPServerConfigItem>
              <SMTPHost>smtp.example.com</SMTPHost>
              <SMTPPort>123</SMTPPort>
              <SMTPAccount>admin@example.com</SMTPAccount>
              <SMTPPassword>123456</SMTPPassword>
            </SMTPServerConfigItem>

            <SMTPServerConfigItem>
              <SMTPHost>smtp.example.com</SMTPHost>
              <SMTPPort>123</SMTPPort>
              <SMTPAccount>admin@example.com</SMTPAccount>
              <SMTPPassword>123456</SMTPPassword>
            </SMTPServerConfigItem>
          </ArrayOfSMTPServerConfigItem>

        </value>

      </setting>
    </Example.Config.SMTPServerConfig>
  </applicationSettings>

</configuration>
</code>```

After add ArrayOfSMTPServerConfigItem tag, it will solve this problem.

Body:
I have following class extended ApplicationSettingsBase as below

public class SMTPServerConfig : ApplicationSettingsBase
{
    private static SMTPServerConfig instance = (SMTPServerConfig)Synchronized(new SMTPServerConfig());

    public static SMTPServerConfig Instance { get { return instance; } }

    [ApplicationScopedSetting]
    [DefaultSettingValue("")]
    [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Xml)]
    public List<SMTPServerConfigItem> SMTPServers
    {
        get
        {
            return ((List<SMTPServerConfigItem>)(this["SMTPServers"]));
        }
    }

    [ApplicationScopedSetting]
    [DefaultSettingValue("")]
    [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.String)]
    public string TestProp
    {
        get
        {
            return ((string)(this["TestProp"]));
        }
    }
}

[Serializable]
public class SMTPServerConfigItem
{

    public string SMTPHost { get; set; }
    public string SMTPPort { get; set; }
    public string SMTPAccount { get; set; }
    public string SMTPPassword { get; set; }
}

Here is my App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>

  </configSections>

  <applicationSettings>
    <Example.Config.SMTPServerConfig>
      <setting name="TestProp" serializeAs="String">
        <value>123123</value>
      </setting>
      <setting name="SMTPServers" serializeAs="Xml">
        <value>
          <SMTPServerConfigItem>
            <SMTPHost>smtp.example.com</SMTPHost>
            <SMTPPort>123</SMTPPort>
            <SMTPAccount>admin@example.com</SMTPAccount>
            <SMTPPassword>123456</SMTPPassword>
          </SMTPServerConfigItem>

          <SMTPServerConfigItem>
            <SMTPHost>smtp.example.com</SMTPHost>
            <SMTPPort>123</SMTPPort>
            <SMTPAccount>admin@example.com</SMTPAccount>
            <SMTPPassword>123456</SMTPPassword>
          </SMTPServerConfigItem>

        </value>

      </setting>
    </Example.Config.SMTPServerConfig>
  </applicationSettings>

</configuration>

When i use SMTPServerConfig.Instance.TestProp it will show result is "123123" (it's true value, it mean i have correct config's schema for it), but SMTPServerConfig.Instance.SMTPServers.Count always zero. Where i'm wrong in code or config file ?

Body:
After a hours of research, i found a question in stackoverflow then i know where i'm wrong. I was missing a xml tag in app.config file.
Question:
Trying to create a custom partial settings file

Then now i will correct my App.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="Example.Config.SMTPServerConfig" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>

  </configSections>

  <applicationSettings>
    <Example.Config.SMTPServerConfig>
      <setting name="TestProp" serializeAs="String">
        <value>123123</value>
      </setting>
      <setting name="SMTPServers" serializeAs="Xml">
        <value>
          <ArrayOfSMTPServerConfigItem>
            <SMTPServerConfigItem>
              <SMTPHost>smtp.example.com</SMTPHost>
              <SMTPPort>123</SMTPPort>
              <SMTPAccount>admin@example.com</SMTPAccount>
              <SMTPPassword>123456</SMTPPassword>
            </SMTPServerConfigItem>

            <SMTPServerConfigItem>
              <SMTPHost>smtp.example.com</SMTPHost>
              <SMTPPort>123</SMTPPort>
              <SMTPAccount>admin@example.com</SMTPAccount>
              <SMTPPassword>123456</SMTPPassword>
            </SMTPServerConfigItem>
          </ArrayOfSMTPServerConfigItem>

        </value>

      </setting>
    </Example.Config.SMTPServerConfig>
  </applicationSettings>

</configuration>

After add ArrayOfSMTPServerConfigItem tag, it will solve this problem.


问:
How to iterate through the all the body objects
I want to assert if my response.body does not contain some provided value. The body has let's assume 10 objects. All the objects have "id" field. How to use some kind of each or forEach on the request response? I know that I can use e.g.

```<code>expect(response.body[0].requestId).not.eq(value);
expect(response.body[1].requestId).not.eq(value);
expect(response.body[2].requestId).not.eq(value);
expect(response.body[3].requestId).not.eq(value);
</code>```

but I don't know how to code it in a more optimized way.

I prepared the array with:

```<code>    const bodyObjects = [
      'body[0]',
      'body[1]',
      'body[2]',
      'body[3]',
      'body[4]',
    ];

</code>```

My code

```<code>it.only("Something "A" should not see something "B"", () => {
    const bodyObjects = [
      'body[0]',
      'body[1]',
      'body[2]',
      'body[3]',
      'body[4]',
    ];
    cy.request({
      method: "POST",
      url: Cypress.env("URL",
      auth: {
        bearer: token,
      },
      body: {
        id: someId,
      },
    }).then((response, $bodyObjects) => {
      responseId = response.body.id;
      expect(response.status).to.eq(201);
      **MY POTENTIAL ASSERTION**
    })
  });
</code>```

答:
You can apply a forEach like this:

it.only('Something "A" should not see something "B""', () => {
  const bodyObjects = ['body[0]', 'body[1]', 'body[2]', 'body[3]', 'body[4]']
  cy.request({
    method: 'POST',
    url: Cypress.env('URL'),
    auth: {
      bearer: token,
    },
    body: {
      id: someId,
    },
  }).then((response, $bodyObjects) => {
    responseId = response.body.id
    expect(response.status).to.eq(201)
    bodyObjects.forEach((bodyObject) => {
      expect(response[bodyObject].requestId).not.eq(value)
    })
  })
})
```

Body:
I want to assert if my response.body does not contain some provided value. The body has let's assume 10 objects. All the objects have "id" field. How to use some kind of each or forEach on the request response? I know that I can use e.g.

expect(response.body[0].requestId).not.eq(value);
expect(response.body[1].requestId).not.eq(value);
expect(response.body[2].requestId).not.eq(value);
expect(response.body[3].requestId).not.eq(value);

but I don't know how to code it in a more optimized way.

I prepared the array with:

    const bodyObjects = [
      'body[0]',
      'body[1]',
      'body[2]',
      'body[3]',
      'body[4]',
    ];

My code

it.only("Something "A" should not see something "B"", () => {
    const bodyObjects = [
      'body[0]',
      'body[1]',
      'body[2]',
      'body[3]',
      'body[4]',
    ];
    cy.request({
      method: "POST",
      url: Cypress.env("URL",
      auth: {
        bearer: token,
      },
      body: {
        id: someId,
      },
    }).then((response, $bodyObjects) => {
      responseId = response.body.id;
      expect(response.status).to.eq(201);
      **MY POTENTIAL ASSERTION**
    })
  });


问:
Javascript in ASP.NET is not working
I'm back at coding som .NET stuff and I thought I'd play with Javascripts / jQuery.

I've added my /js/myscript.js file and it loads when the pages has loaded.

In my js file I only have one call alert('TEST').

Why isn't the alert triggered?

I'm on ASP.NET 4.0  - but I don' think that has anything to do with it.

Is there a way to detect if there is any conflict with other scripts?

This goes in the header:

```<code><script type="text/javascript" src="js/myscript.js" ></script>
</code>```

After page is loaded, I can use Firebug and exapnd the script and see it's content. So the script is loaded.

Embarrassing update

```<code>jQuery(document).ready(function() {
    // Alert if jQuery is loaded
    alert('Test1');
}

alert('Test 2');
</code>```

As you can see in the above code, I'd forgotten to add the ); and the end of the  jQuery(document).ready() function.

After a long day, even the simplest things can go unnoticed.

答:
What does your myscript.js look like?

```<code>function x(){
  alert('TEST');
}
</code>```

or just (which will execute on load):

```<code>alert('TEST');
</code>```

Title: Javascript in ASP.NET is not working

Body:
I'm back at coding som .NET stuff and I thought I'd play with Javascripts / jQuery.

I've added my /js/myscript.js file and it loads when the pages has loaded.

In my js file I only have one call alert('TEST').

Why isn't the alert triggered?

I'm on ASP.NET 4.0  - but I don' think that has anything to do with it.

Is there a way to detect if there is any conflict with other scripts?

This goes in the header:

After page is loaded, I can use Firebug and exapnd the script and see it's content. So the script is loaded.

Embarrassing update

jQuery(document).ready(function() {
    // Alert if jQuery is loaded
    alert('Test1');
}

alert('Test 2');

As you can see in the above code, I'd forgotten to add the ); and the end of the  jQuery(document).ready() function.

After a long day, even the simplest things can go unnoticed.

Body:
What does your myscript.js look like?

function x(){
  alert('TEST');
}

or just (which will execute on load):

alert('TEST');


答:
Considering response.body is an array, you can use a forEach loop to iterate through them:

responde.body.forEach(res => {
  expect(res.requestId).not.eq(value)
})
```

Title: How to iterate through the all the body objects


问:
how to convert pdf to image in react native?
I want to make pdf to image converter in react native. I tried using some packages but they are not working.so is there any way to convert pdf to image?
thanks in advance.</p>

答:
We can achieve the PDF to thumbnail using the npm package called react-native-pdf-thumbnail

Have a try with this npm package


问:
Updating table based on same table with a max value
Have a table data structure like below:

id
regid
docid
archived

1
1000
1
0

2
1000
2
0

3
1000
3
0

4
2000
1
0

5
2000
2
0

6
3000
1
0

7
3000
2
0

8
3000
3
0

9
3000
4
0

What I'm trying to do update the archived column to 1 where the docid is less than the max docid, by each regid group.

So I should end up with id's 3, 5 & 9 not being set to 1

Have tried:

```<code>update table t1
join (select max(docid) as maxdocid, regid from table) t2 on t1.docid < t2.maxdocid and t1.regid = t2.regid
set t1.archived = 1
</code>```

But doesn't work, only does the first regid group.

答:
You could try:

```<code>update test_tbl t1
set t1.archived = 1
where t1.archived = 0
and t1.id not in ( select t2.id
                   from (select max(id) as id,
                                regid,
                                max(docid)
                         from test_tbl
                         group by regid
                         ) as t2
                   ) ;
</code>```

Result:

```<code>id  regid    docid  archived
1   1000       1    1
2   1000       2    1
3   1000       3    0
4   2000       1    1
5   2000       2    0
6   3000       1    1
7   3000       2    1
8   3000       3    1
9   3000       4    0
</code>```

Demo

Or you can use a LEFT JOIN

```<code>update test_tbl t1
left join ( select max(id) as id,
                   regid,
                   max(docid) as docid
                   from test_tbl
                    group by regid
          ) as t2 on t1.id=t2.id
set t1.archived = 1
where t1.archived = 0
and  t2.id IS NULL
</code>```

Demo

Body:
Have a table data structure like below:

id
regid
docid
archived

1
1000
1
0

2
1000
2
0

3
1000
3
0

4
2000
1
0

5
2000
2
0

6
3000
1
0

7
3000
2
0

8
3000
3
0

9
3000
4
0

What I'm trying to do update the archived column to 1 where the docid is less than the max docid, by each regid group.

So I should end up with id's 3, 5 & 9 not being set to 1

Have tried:

update table t1
join (select max(docid) as maxdocid, regid from table) t2 on t1.docid < t2.maxdocid and t1.regid = t2.regid
set t1.archived = 1

But doesn't work, only does the first regid group.

Body:
You could try:

update test_tbl t1
set t1.archived = 1
where t1.archived = 0
and t1.id not in ( select t2.id
                   from (select max(id) as id,
                                regid,
                                max(docid)
                         from test_tbl
                         group by regid
                         ) as t2
                   ) ;

Result:

id  regid    docid  archived
1   1000       1    1
2   1000       2    1
3   1000       3    0
4   2000       1    1
5   2000       2    0
6   3000       1    1
7   3000       2    1
8   3000       3    1
9   3000       4    0

Demo

Or you can use a LEFT JOIN

update test_tbl t1
left join ( select max(id) as id,
                   regid,
                   max(docid) as docid
                   from test_tbl
                    group by regid
          ) as t2 on t1.id=t2.id
set t1.archived = 1
where t1.archived = 0
and  t2.id IS NULL

Demo


问:
want to put \' in my json object
I am having trouble using JObject.Parse(string) to get this result:

```<code>'apos\'trophe'
</code>```

But...

```<code>"apos\'trophe"    turns into    'apos'trophe'
"apos\\\'trophe"  turns into    'apos\\\'trophe'
"apos\\'trophe"   turns into    'apos\\'trophe'
"apos/\'trophe"   turns into    'apos/'trophe'
</code>```

答: "apos\\\'trophe" works for me.

Title: want to put \' in my json object

Body:
I am having trouble using JObject.Parse(string) to get this result:

'apos\'trophe'

But...

"apos\'trophe"    turns into    'apos'trophe'
"apos\\\'trophe"  turns into    'apos\\\'trophe'
"apos\\'trophe"   turns into    'apos\\'trophe'
"apos/\'trophe"   turns into    'apos/'trophe'

Body: "apos\\\'trophe" works for me.