问:
how can I fix "build failed" after I run react-native run-android in windows 10
I have created the project very well and I have also installed the android studio and all the required sdks. but still I am still facing a problem of the emulator not starting. below is error in the terminal.

'$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier"
flag.
(node:8368) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)
Jetifier found 866 file(s) to forward-jetify. Using 6 workers...
info Starting JS server...
'adb' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon, 3 stopped Daemons could not be reused, use --status for details

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

```<code>at makeError (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:174:9)
at C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:278:16
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async runOnAllDevices (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:192:9)
</code>```

info Run CLI with --verbose flag for more details.`

答: Check Your SDK path and you have installed correct sdk according to version.</p>

Body:
I have created the project very well and I have also installed the android studio and all the required sdks. but still I am still facing a problem of the emulator not starting. below is error in the terminal.

'$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier"
flag.
(node:8368) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)
Jetifier found 866 file(s) to forward-jetify. Using 6 workers...
info Starting JS server...
'adb' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon, 3 stopped Daemons could not be reused, use --status for details

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

at makeError (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:174:9)
at C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:278:16
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async runOnAllDevices (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:192:9)

info Run CLI with --verbose flag for more details.`


来源: stackexchange

问:
DB2 to Snowflake Migration - SQL: Deriving a result table using 'values' clause
We are migrating off DB2 to Snowflake, and we have run into an issue with a lack of scope when using the 'values' clause.  DB2 scope extends to all tables within the select query; while Snowflake is limited to that within the clause:

Valid in DB2:

```<code>select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2
</code>```

Not valid in Snowflake (slightly different syntax - remove 'table'):

```<code>select * from
t_1
join

(values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2
</code>```

This throws an error saying "...t_1 is undefined".

Does anyone know of an equivalent capability in Snowflake?

For some context:  This construct sits behind a well embedded process for our business, and to rework it would mean significant investment.

It forms the basis for a dynamic ETL query which is passed into an ADF pipeline.  There is a frontend which deploys components into this query - this deployable piece needs to be kept as simple as possible.  It is the equivalent to the "(t_1.c1, ‘foo’)" line, so ideally any solution would keep this piece the same.

EDIT:

For some additional context...

In the example above, we have a placeholder which identifies the insert point of newly deployed items from the front end, like this:

```<code>select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
/*client_X_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

union

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
,(t_1.c2, 'barfoo')
/*client_Y_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2
</code>```

We are pulling a series of metrics associated with clients, where the label is t_2.c2 and the result is t2.c1.  This is still highly simplified relative to the real world.  We need a simple way to update the placeholder with a new metric and its calculation - t2.c1 may be wrapped in a pile of functions and/or reside inside case statements, etc.

答:
I have no idea whether this works in snowflake, but SQL requires you to declare t_2 as LATERAL if you want to reference t_1 inside of it. Db2 uses tables as a synonym for lateral (which works as well). So you could try:

```<code>select *
from t_1
join LATERAL (
    values (t_1.c1, ‘foo’)
         , (t_1.c1, ‘bar’)
    ) as t_2 (c1, c2)
  on t_1.c5 = t_2.c2
</code>```

Lateral was introduced in SQL99 and is supported by many DBMS including Db2.

In Db2, TABLE is typically used when selecting from a function returning a table:

```<code>SELECT * FROM TABLE ( myfun() )
</code>```

which is somewhat similar so I guess that is why TABLE can act as a synonym for LATERAL (just guessing).

I did some googling and LATERAL is described in the docs for snowflake: join-lateral

EDIT:

Apparently, there is a limitation when it comes to joining the values clause in the derived table. The answer by Simeon Pilgrim contains a fix for this

ContentLicense: CC BY-SA 4.0

Body:
We are migrating off DB2 to Snowflake, and we have run into an issue with a lack of scope when using the 'values' clause.  DB2 scope extends to all tables within the select query; while Snowflake is limited to that within the clause:

Valid in DB2:

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

Not valid in Snowflake (slightly different syntax - remove 'table'):

select * from
t_1
join

(values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

This throws an error saying "...t_1 is undefined".

Does anyone know of an equivalent capability in Snowflake?

For some context:  This construct sits behind a well embedded process for our business, and to rework it would mean significant investment.

It forms the basis for a dynamic ETL query which is passed into an ADF pipeline.  There is a frontend which deploys components into this query - this deployable piece needs to be kept as simple as possible.  It is the equivalent to the "(t_1.c1, ‘foo’)" line, so ideally any solution would keep this piece the same.

EDIT:

For some additional context...

In the example above, we have a placeholder which identifies the insert point of newly deployed items from the front end, like this:

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
/*client_X_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

union

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
,(t_1.c2, 'barfoo')
/*client_Y_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

We are pulling a series of metrics associated with clients, where the label is t_2.c2 and the result is t2.c1.  This is still highly simplified relative to the real world.  We need a simple way to update the placeholder with a new metric and its calculation - t2.c1 may be wrapped in a pile of functions and/or reside inside case statements, etc.

Body:
I have no idea whether this works in snowflake, but SQL requires you to declare t_2 as LATERAL if you want to reference t_1 inside of it. Db2 uses tables as a synonym for lateral (which works as well). So you could try:

select *
from t_1
join LATERAL (
    values (t_1.c1, ‘foo’)
         , (t_1.c1, ‘bar’)
    ) as t_2 (c1, c2)
  on t_1.c5 = t_2.c2

Lateral was introduced in SQL99 and is supported by many DBMS including Db2.

In Db2, TABLE is typically used when selecting from a function returning a table:

SELECT * FROM TABLE ( myfun() )

which is somewhat similar so I guess that is why TABLE can act as a synonym for LATERAL (just guessing).

I did some googling and LATERAL is described in the docs for snowflake: join-lateral

EDIT:

Apparently, there is a limitation when it comes to joining the values clause in the derived table. The answer by Simeon Pilgrim contains a fix for this


问:
Cypress - get value that is inside a component (into a variable)
I'm a new developer and I am trying to build a certain test using cypress. the client has a dynamic grid, and I'd like to see which row in the grid contains the data I want. I cannot change the HTML file.

At the moment I am trying to iterate over all rows using each() cypress command. So I have two questions:

is this a correct approach?

assuming it is correct, how do I get the value out of the component? for example, how do I get the value of "aaaaaaaa" out of here (and into a variable):
html structure

thanks!

答:
Using each is a pretty good approach, select the rows and make use of the index parameter to find which one.

cy.get('[role="row"]').each(($row, index) => {

  if ($row.find('span').text() === 'aaaa') {
    cy.wrap(index).as('rowIndex')
})

cy.get('@rowIndex')
  .then(rowIndex => {
    // use the row index here
  })
```
<p>There's also this method Cypress get index of th element to use it later.</p>
<p>If it works (the jQuery docs don't show this usage) the code for your HTML would be</p>
<pre class="lang-js prettyprint-override"><code>cy.contains('[role="row"]', 'aaaa').invoke('index').as('rowIndex')

cy.get('@rowIndex')
  .then(rowIndex => {
    // use the row index here
  })
</code>```

Body:
Using each is a pretty good approach, select the rows and make use of the index parameter to find which one.

cy.get('[role="row"]').each(($row, index) => {

  if ($row.find('span').text() === 'aaaa') {
    cy.wrap(index).as('rowIndex')
})

cy.get('@rowIndex')
  .then(rowIndex => {
    // use the row index here
  })

There's also this method Cypress get index of th element to use it later.

If it works (the jQuery docs don't show this usage) the code for your HTML would be

cy.contains('[role="row"]', 'aaaa').invoke('index').as('rowIndex')

cy.get('@rowIndex')
  .then(rowIndex => {
    // use the row index here
  })


问:
How to create grid structure in react native map function?
I want to create a grid structure 4*5. creating this I can wrap a view with flexDirection:"row" with every 4 views. But I am rendering this through map function.

```<code><View style={{ alignItems: "center" }}>
  {this.props.color.primary.map((color) => {
    return <View key={color.key} style={[styles.color, { backgroundColor: color.code }]} />
  })}
</View>
</code>```

I need to wrap inner view with View style={{flexDirection:"row"}} after every 4 View. How to achieve this. Or else is there any other solution to achieve this?

答:
Create this component file separately

```<code>import React from 'react'
import { View } from 'react-native'

export function CTMapList({
  data,
  renderItem,
  ListHeaderComponent,
  ListHeaderComponentStyle,
  ListFooterComponent,
  ListFooterComponentStyle,
  ListEmptyComponent,
  style,
  horizontal,
  ItemSeparatorComponent,
  numColumns
}) {
  const createGroup = () => {
    const dataGroup = []
    let groupCount = 0
    let group = []
    // eslint-disable-next-line array-callback-return
    data.map((item, index) => {
      if (groupCount === 0 && index !== 0) {
        dataGroup.push(group)
        group = []
      }
      group.push(item)
      groupCount++
      if (groupCount === numColumns) groupCount = 0
      if (data.length - 1 === index) dataGroup.push(group)
    })
    return dataGroup
  }

  return (
    <View style={style}>
      <View style={ListHeaderComponentStyle}>{ListHeaderComponent && ListHeaderComponent}</View>
      {(!data || data.length === 0) && ListEmptyComponent && ListEmptyComponent}
      {((numColumns && numColumns === 1) || !numColumns) && (
        <View style={{ flexDirection: horizontal ? 'row' : 'column' }}>
          {data &&
            data.map((item, index) => (
              <View key={String(index)}>
                <View>{renderItem && renderItem({ item, index })}</View>
                {data.length - 1 !== index && ItemSeparatorComponent}
              </View>
            ))}
        </View>
      )}
      {numColumns && numColumns !== 1 && (
        <View>
          {createGroup() &&
            createGroup().map((item, index) => (
              <View key={String(index)} style={{ flexDirection: 'row' }}>
                {item.map((item2, index2) => (
                  <View key={String(index2)} style={{ flex: 1 }}>
                    <View style={{ flex: 1 }}>{renderItem && renderItem({ item: item2, index: index2 })}</View>
                    {data.length - 1 !== index && ItemSeparatorComponent}
                  </View>
                ))}
              </View>
            ))}
        </View>
      )}

      <View style={ListFooterComponentStyle}>{ListFooterComponent && ListFooterComponent}</View>
    </View>
  )
}
</code>```

and then use it like flatlist by doing this you can avoid nested visualised list warning you need to wrap this component with scrollview

```<code>    <ScrollView
       bounces={false}
       overScrollMode="never"
       showsVerticalScrollIndicator={false}
       style={{ flex: 1 }}
    >
         <CTMapList
            data={sortedPackages}
            style={{ paddingHorizontal: 30, zIndex: -1 }}
            numColumns={2}
            keyExtractor={(item) => String(item.id)}
            renderItem={this.renderPackeges}
         />
    </ScrollView>
</code>```

Body:
I want to create a grid structure 4*5. creating this I can wrap a view with flexDirection:"row" with every 4 views. But I am rendering this through map function.

<View style={{ alignItems: "center" }}>
  {this.props.color.primary.map((color) => {
    return <View key={color.key} style={[styles.color, { backgroundColor: color.code }]} />
  })}
</View>

I need to wrap inner view with View style={{flexDirection:"row"}} after every 4 View. How to achieve this. Or else is there any other solution to achieve this?

Body:
Create this component file separately

import React from 'react'
import { View } from 'react-native'

export function CTMapList({
  data,
  renderItem,
  ListHeaderComponent,
  ListHeaderComponentStyle,
  ListFooterComponent,
  ListFooterComponentStyle,
  ListEmptyComponent,
  style,
  horizontal,
  ItemSeparatorComponent,
  numColumns
}) {
  const createGroup = () => {
    const dataGroup = []
    let groupCount = 0
    let group = []
    // eslint-disable-next-line array-callback-return
    data.map((item, index) => {
      if (groupCount === 0 && index !== 0) {
        dataGroup.push(group)
        group = []
      }
      group.push(item)
      groupCount++
      if (groupCount === numColumns) groupCount = 0
      if (data.length - 1 === index) dataGroup.push(group)
    })
    return dataGroup
  }

  return (
    <View style={style}>
      <View style={ListHeaderComponentStyle}>{ListHeaderComponent && ListHeaderComponent}</View>
      {(!data || data.length === 0) && ListEmptyComponent && ListEmptyComponent}
      {((numColumns && numColumns === 1) || !numColumns) && (
        <View style={{ flexDirection: horizontal ? 'row' : 'column' }}>
          {data &&
            data.map((item, index) => (
              <View key={String(index)}>
                <View>{renderItem && renderItem({ item, index })}</View>
                {data.length - 1 !== index && ItemSeparatorComponent}
              </View>
            ))}
        </View>
      )}
      {numColumns && numColumns !== 1 && (
        <View>
          {createGroup() &&
            createGroup().map((item, index) => (
              <View key={String(index)} style={{ flexDirection: 'row' }}>
                {item.map((item2, index2) => (
                  <View key={String(index2)} style={{ flex: 1 }}>
                    <View style={{ flex: 1 }}>{renderItem && renderItem({ item: item2, index: index2 })}</View>
                    {data.length - 1 !== index && ItemSeparatorComponent}
                  </View>
                ))}
              </View>
            ))}
        </View>
      )}

      <View style={ListFooterComponentStyle}>{ListFooterComponent && ListFooterComponent}</View>
    </View>
  )
}

and then use it like flatlist by doing this you can avoid nested visualised list warning you need to wrap this component with scrollview

    <ScrollView
       bounces={false}
       overScrollMode="never"
       showsVerticalScrollIndicator={false}
       style={{ flex: 1 }}
    >
         <CTMapList
            data={sortedPackages}
            style={{ paddingHorizontal: 30, zIndex: -1 }}
            numColumns={2}
            keyExtractor={(item) => String(item.id)}
            renderItem={this.renderPackeges}
         />
    </ScrollView>


问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
The compiler is keeping track of what is and what is not const.  Getting them right can be tricky at first.

For your first point, you're passing in const Dict *dict, which means you're promising that you aren't going to modify anything through dict.  Then you assign it to Dict * currptr.  Since currptr isn't const, you could change things through *currptr.  The compiler has to warn you at some point that you're trying to modify something even though it's const, and the right place is when you're assigning a const pointer to a non-const pointer.

For your second point, you're missing exactly what's const.  If you have const Dict * currptr, you're describing currptr as a pointer to const Dict, meaning you can change currptr but not *currptr.  You can make currptr const with Dict * const currptr, or make it a const pointer to a const value with const Dick * const currptr.

I don't actually understand your third point.  You should get a compiler warning from del() as you've posted it, since you're assigning a pointer to const value to pointer to value.  You need to have prevptr non-const, since you're using it to modify a value.  The function signature should be Dict *del(Dict *dict, int key), since as it is you're promising not to modify anything dict is pointing to, and doing it anyway.

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

OwnerDisplayName: David Thornley


问:
DJANGO TESTS: TypeError: test_suit_row_attributes() missing 1 required positional argument: 'request'
I want to resolve this error and finish the test:

admin.py

```<code>def suit_row_attributes(self, obj, request):
    """Add colours to the rows according to the status"""

    type_error = 'notSent'
    status_colours = {Transaction.STATUS_REJECTED: 'error', Transaction.STATUS_RECEIVED: 'received',
                      Transaction.STATUS_PENDING: 'warning', Transaction.STATUS_ACCEPTED: 'success',
                      type_error: 'notSent'}
    try:
        tt_status = Transaction.objects.get(txid=obj.numero).last_status
    except Transaction.DoesNotExist:
        tt_status = type_error
    return {'class': status_colours.get(tt_status, 'success')}
</code>```

in tests.py

```<code>def test_suit_row_attributes(self):
    self.assertEqual(self.admin_instance.suit_row_attributes(self.errortr_obj), {'class': 'notSent'})
</code>```

Can someone help me, please?

答:
```<code>from django.contrib.admin import ModelAdmin

class CountryAdmin(ModelAdmin):
    ...

    def suit_row_attributes(self, obj, request):
        return {'class': 'type-%s' % obj.type}

    # Or bit more advanced example
    def suit_row_attributes(self, obj, request):
        css_class = {
            1: 'success',
            0: 'warning',
            -1: 'error',
        }.get(obj.status)
        if css_class:
            return {'class': css_class, 'data': obj.name}
</code>```

For more :- https://django-suit.readthedocs.io/en/develop/list_attributes.html

Body:
I want to resolve this error and finish the test:

admin.py

def suit_row_attributes(self, obj, request):
    """Add colours to the rows according to the status"""

    type_error = 'notSent'
    status_colours = {Transaction.STATUS_REJECTED: 'error', Transaction.STATUS_RECEIVED: 'received',
                      Transaction.STATUS_PENDING: 'warning', Transaction.STATUS_ACCEPTED: 'success',
                      type_error: 'notSent'}
    try:
        tt_status = Transaction.objects.get(txid=obj.numero).last_status
    except Transaction.DoesNotExist:
        tt_status = type_error
    return {'class': status_colours.get(tt_status, 'success')}

in tests.py

def test_suit_row_attributes(self):
    self.assertEqual(self.admin_instance.suit_row_attributes(self.errortr_obj), {'class': 'notSent'})

Can someone help me, please?

Body:
from django.contrib.admin import ModelAdmin

class CountryAdmin(ModelAdmin):
    ...

    def suit_row_attributes(self, obj, request):
        return {'class': 'type-%s' % obj.type}

    # Or bit more advanced example
    def suit_row_attributes(self, obj, request):
        css_class = {
            1: 'success',
            0: 'warning',
            -1: 'error',
        }.get(obj.status)
        if css_class:
            return {'class': css_class, 'data': obj.name}

For more :- https://django-suit.readthedocs.io/en/develop/list_attributes.html


问:
How to rewrite code into one using javascript and react?
i have two methods like below.

```<code> const handleRowClick = React.useMemo(() =>
     !isRunning
         ? (itemId: string) => {
             startRun({items: [itemId] });
         }
         : undefined,
     [startRun]
 );

  const handleSelectedItemsClick = React.useMemo(() =>
      !isRunning
          ? (items: string[]) => startRun({ items: items })
          : undefined,
          startRun]
  );

  handleRowClick(itemId);
  handleSelectedItemsClick(itemIds);
</code>```

as seen from above handleRowClick takes a string as an argument whereas handleSelectedItemsClick takes an array of strings as an argument.

how can I rewrite the above methods into one such that it can handle either a string or array of strings as input?

could someone help me with this? thanks.

答:
at function param set the the type string | string[]

the inside a function

(itemId: string | string[]) => {startRun({items: Array.isArray(itemId)?itemId:[itemId] });}

Body:
i have two methods like below.

 const handleRowClick = React.useMemo(() =>
     !isRunning
         ? (itemId: string) => {
             startRun({items: [itemId] });
         }
         : undefined,
     [startRun]
 );

  const handleSelectedItemsClick = React.useMemo(() =>
      !isRunning
          ? (items: string[]) => startRun({ items: items })
          : undefined,
          startRun]
  );

  handleRowClick(itemId);
  handleSelectedItemsClick(itemIds);

as seen from above handleRowClick takes a string as an argument whereas handleSelectedItemsClick takes an array of strings as an argument.

how can I rewrite the above methods into one such that it can handle either a string or array of strings as input?

could someone help me with this? thanks.


问:
Sudden "No hosted parallelism has been purchased or granted. To request a free parallelism grant" error on old organisation
I suddenly got this error on a pull request so it cannot build.

We have 1 parallel job in our self-hosted project on Azure DevOps and NONE is running currently so not sure why would this error appear at all?

Also according to the info  they "have temporarily disabled the free grant of parallel jobs for public projects and for certain private projects in new organizations".

Our organisation is not new, we've been on Azure for years.

Any thoughts?

答:
We have received several feedback recently. Some customers' free parallel job were banned after February 8th.

As jessehouwing said, I suggest that you re-apply for free parallel job through this form first. Also, you can contact Microsoft Support by Azure DevOps Services support or Developer Community. They may help you speed up your application progress.


问:
Unit testing iOS 10 notifications
In my app I wish to assert that notifications have been added in the correct format. I'd normally do this with dependency injection, but I can't think of a way to test the new UNUserNotificationCenter API.

I started to create a mock object which would capture the notification request:

```<code>import Foundation
import UserNotifications

class NotificationCenterMock: UNUserNotificationCenter {
    var request: UNNotificationRequest? = nil
    override func add(_ request: UNNotificationRequest, withCompletionHandler completionHandler: ((Error?) -> Void)? = nil) {
        self.request = request
    }
}
</code>```

However, UNUserNotificationCenter has no accessible initializers I can't instantiate the mock.

I'm not even sure I can test by adding the notification request and fetching the current notifications, as the tests would need to request permission on the Simulator which would stall the tests. Currently I've refactored the notification logic into a wrapper, so I can at least mock that throughout my application and manually test.

Do I have any better options than manual testing?

答:
I managed to mock UNNotificationSettings using below

```<code>let object = UIView()
let data = try! NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
let coder = try! NSKeyedUnarchiver(forReadingFrom: data)
let setting = UNNotificationSettings(coder: coder)
setting?.setValue(UNAuthorizationStatus.notDetermined.rawValue, forKey: "authorizationStatus")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Unit testing iOS 10 notifications

Body:
In my app I wish to assert that notifications have been added in the correct format. I'd normally do this with dependency injection, but I can't think of a way to test the new UNUserNotificationCenter API.

I started to create a mock object which would capture the notification request:

import Foundation
import UserNotifications

class NotificationCenterMock: UNUserNotificationCenter {
    var request: UNNotificationRequest? = nil
    override func add(_ request: UNNotificationRequest, withCompletionHandler completionHandler: ((Error?) -> Void)? = nil) {
        self.request = request
    }
}

However, UNUserNotificationCenter has no accessible initializers I can't instantiate the mock.

I'm not even sure I can test by adding the notification request and fetching the current notifications, as the tests would need to request permission on the Simulator which would stall the tests. Currently I've refactored the notification logic into a wrapper, so I can at least mock that throughout my application and manually test.

Do I have any better options than manual testing?

Body:
I managed to mock UNNotificationSettings using below

let object = UIView()
let data = try! NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
let coder = try! NSKeyedUnarchiver(forReadingFrom: data)
let setting = UNNotificationSettings(coder: coder)
setting?.setValue(UNAuthorizationStatus.notDetermined.rawValue, forKey: "authorizationStatus")


问:
How to rewrite the code using conditional rendering in react and javascript?
i have code like below

```<code>const mode = isActiveMode;

{!isActiveMode && runId && !isEmpty(items) && (
    <>
        <Flex>
            //more jsx similar
            <Icon onClick={() =>
                setItemState((previous: any) => ({
                    ...previous,
                    items: undefined,
                }))
            }
        />
        <TabPanel>
            <Table />
        </TabPanel>
    </>
)}

{isActiveMode && runId && !isEmpty(items) && isTableOpen && (
    <>
        <Flex>
            //more jsx similar
            <Icon onClick={() =>
                setItemState((previous: any) => ({
                    ...previous,
                    items: undefined,
                }))
            }
        />
        <TabPanel>
            {selections.length === 1 ? (
                <Table/> ): ( <div>hello</div>)
            }
        </TabPanel>

    </>
)}
</code>```

i have two renderings based on different conditions. the code inside is almost same in both cases. how can i reuse the code in this case. could someone please help me with this.

How can i rewrite above code into one with conditions using reusable code. thanks.

答:
From what I can see your jsx is pretty similar how about that one condition which was different you put it in ternary operator because table was rendering

```<code>const mode = isActiveMode;

{!isActiveMode && runId && !isEmpty(items) && (
    <>
    <Flex>
        //more jsx similar
        <Icon onClick={() =>
            setItemState((previous: any) => ({
                ...previous,
                items: undefined,
            }))
        }
     />
     <TabPanel>
         {isTableOpen===false || selections.length === 1 ? (
             <Table/> ): ( <div>hello</div>)
         }
     </TabPanel>

    </>
)}
</code>```

Tell me if this isn't what you were looking for I'll try something different then

Body:
i have code like below

const mode = isActiveMode;

{!isActiveMode && runId && !isEmpty(items) && (
    <>
        <Flex>
            //more jsx similar
            <Icon onClick={() =>
                setItemState((previous: any) => ({
                    ...previous,
                    items: undefined,
                }))
            }
        />
        <TabPanel>

        </TabPanel>
    </>
)}

{isActiveMode && runId && !isEmpty(items) && isTableOpen && (
    <>
        <Flex>
            //more jsx similar
            <Icon onClick={() =>
                setItemState((previous: any) => ({
                    ...previous,
                    items: undefined,
                }))
            }
        />
        <TabPanel>
            {selections.length === 1 ? (

 ): (
hello
)
            }
        </TabPanel>

    </>
)}

i have two renderings based on different conditions. the code inside is almost same in both cases. how can i reuse the code in this case. could someone please help me with this.

How can i rewrite above code into one with conditions using reusable code. thanks.

Body:
From what I can see your jsx is pretty similar how about that one condition which was different you put it in ternary operator because table was rendering

const mode = isActiveMode;

{!isActiveMode && runId && !isEmpty(items) && (
    <>
    <Flex>
        //more jsx similar
        <Icon onClick={() =>
            setItemState((previous: any) => ({
                ...previous,
                items: undefined,
            }))
        }
     />
     <TabPanel>
         {isTableOpen===false || selections.length === 1 ? (
             <Table/> ): ( <div>hello</div>)
         }
     </TabPanel>

    </>
)}

Tell me if this isn't what you were looking for I'll try something different then


问:
Is there a way to get my program to start at the very beginning of a do while loop if an exception occurs?
I want it to start again at the most outer for loop, so that if a user messes up the input, they can sign in again and everything work just like if the program started all over again. I tried using continue statements and break statements and using the nicknames for the loops. Like

```<code>outer: do {
//loop code
}
then break outer;
</code>```

The problem is when I do that, it messes up my controlling of the loop. The end statement that asks the user if they want to go back to the main menu. Right now I just have the app exit, if an exception is encountered, using return statement, but If I'm just gonna exit, I might as well just let the app crash. I want to actually resolve the situation and ask the user for valid input.

```<code>package main;

import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Scanner;

import model.BankAccount;

public class app {

    static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {

        HashMap<String, BankAccount> accounts = new HashMap<>();
        BankAccount sallyAccount = new BankAccount(1000);
        BankAccount bobAccount = new BankAccount(2000);
        BankAccount naomiAccount = new BankAccount();
        accounts.put("Sally", sallyAccount);
        accounts.put("Bob", bobAccount);
        accounts.put("Naomi", naomiAccount);
        String name;
        BankAccount account;
        int userInput;
        double amount;
        boolean again;

        do
        {
            again = true;
            System.out.println("Login: Enter your name.");
            name = console.next();
            account = accounts.get(name);
            if(account == null)
            {
                System.out.println("Please enter a valid name.");
                return;
            }

            do
            {
                System.out.println("1 - Deposit");
                System.out.println("2 - Withdraw");
                System.out.println("3 - View Balance");
                System.out.println("4 - Logout");
                userInput = console.nextInt();
                switch(userInput)
                {
                case 1:
                    System.out.println("Enter amount to deposit: ");
                    try
                    {
                        amount = console.nextDouble();
                    }
                    catch(InputMismatchException e)
                    {
                        System.out.println("Please enter a numeric amount.");
                        return;
                    }
                    if(amount < 0)
                    {
                        System.out.println("You can't withdraw a negative amount");
                        return;
                    }
                    account.deposit(amount);
                    break;
                case 2:
                    System.out.println("Enter amount to withdraw: ");
                    try
                    {
                        amount = console.nextDouble();
                    }
                    catch(InputMismatchException e)
                    {
                        System.out.println("Please enter a numeric amount.");
                        return;
                    }
                    if(amount < 0)
                    {
                        System.out.println("You can't withdraw a negative amount");
                        return;
                    }
                    account.withdraw(amount);
                    break;
                case 3:
                    System.out.println(account.getBalance());
                    break;
                case 4:
                    again = false;
                    break;
                default:
                    System.out.println("Enter a valid option.");
                }
            }
            while(again);
            System.out.println("Back to main menu? 1 - Yes, 2 - No");
            try
            {
                userInput = console.nextInt();
            }
            catch(InputMismatchException e)
            {
                System.out.println("Please enter a number");
                return;
            }
        }
        while(userInput == 1);
    }
}
</code>```
```<code>package model;

public class BankAccount {

    private double balance = 0;

    public BankAccount() {}

    public BankAccount(double balance)
    {
        this.balance = balance;
    }

    public void deposit(double amount)
    {
        balance = balance + amount;
    }

    public void withdraw(double amount)
    {
        if((balance - amount) < 0)
        {
            System.out.println("Transaction Failed: You can't withdraw more than you have.");
        }
        else
        {
            balance = balance - amount;
        }
    }

    public double getBalance()
    {
        return balance;
    }
}
</code>```

答:
You'll be best served by breaking up your main function in multiple functions that handle different parts of the control logic. A good rule of thumb (for beginning programmers) is a function over ~10-15 lines should probably be multiple functions, though it's not an ironclad rule.

I rewrote your program to be multiple functions, but since this seems like a homework problem I won't post the whole thing. Rather, a general strategy with some snippets.

For example, when the user enters an amount to deposit or withdraw. What your programs wants in that moment is a single double, so you could request a single double, and let another method figure out how to get it:

```<code>switch (getMenuChoice()) {
    case 1:
        account.deposit(getDepositOrWithdrawAmount("deposit"));
        break;
    case 2:
        account.withdraw(getDepositOrWithdrawAmount("withdraw"));
        break;
    // etc.
}
</code>```

Then, that function is responsible for looping infinitely until the user provides a valid value:

```<code>static double getDepositOrWithdrawAmount(String depositOrWithdraw) {
    // loop infinitely until we get a valid value
    while (true) {
      System.out.println("Enter amount to " + depositOrWithdraw);
      try {
        double amount = console.nextDouble();
        if (amount < 0) {
          System.out.println("You can't " + depositOrWithdraw + " a negative amount.");
        } else {
          // valid value! return for deposit / withdraw to use
          // , ending the infinite loop
          return amount;
        }
      } catch (InputMismatchException e) {
        System.out.println("Please enter a numeric amount.");

        // clear the bad token from the stream
        // if you don't do this, each time you
        // call `nextDouble`, the same value will
        // be returned, causing an infinite loop
        console.next();
      }
    }
  }
</code>```

The nice thing about this function is it works in isolation:

```<code>public static void main(String[] args) {
  System.out.println("Test: " + getDepositOrWithdrawal("test!"));
}
</code>```

Gives this result:

```<code>Enter amount to test!
abc
Please enter a numeric amount.
Enter amount to test!
not-a-number
Please enter a numeric amount.
Enter amount to test!
-5
You can't test! a negative amount.
Enter amount to test!
1000
Test: 1000.0
</code>```

This lets you test that pieces of your program are working on their own, instead of trying to debug one big program.

You can write other parts of your program as functions as well, but I'll leave that to you.

Body:
I want it to start again at the most outer for loop, so that if a user messes up the input, they can sign in again and everything work just like if the program started all over again. I tried using continue statements and break statements and using the nicknames for the loops. Like

outer: do {
//loop code
}
then break outer;

The problem is when I do that, it messes up my controlling of the loop. The end statement that asks the user if they want to go back to the main menu. Right now I just have the app exit, if an exception is encountered, using return statement, but If I'm just gonna exit, I might as well just let the app crash. I want to actually resolve the situation and ask the user for valid input.

package main;

import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Scanner;

import model.BankAccount;

public class app {

    static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {

        HashMap<String, BankAccount> accounts = new HashMap<>();
        BankAccount sallyAccount = new BankAccount(1000);
        BankAccount bobAccount = new BankAccount(2000);
        BankAccount naomiAccount = new BankAccount();
        accounts.put("Sally", sallyAccount);
        accounts.put("Bob", bobAccount);
        accounts.put("Naomi", naomiAccount);
        String name;
        BankAccount account;
        int userInput;
        double amount;
        boolean again;

        do
        {
            again = true;
            System.out.println("Login: Enter your name.");
            name = console.next();
            account = accounts.get(name);
            if(account == null)
            {
                System.out.println("Please enter a valid name.");
                return;
            }

            do
            {
                System.out.println("1 - Deposit");
                System.out.println("2 - Withdraw");
                System.out.println("3 - View Balance");
                System.out.println("4 - Logout");
                userInput = console.nextInt();
                switch(userInput)
                {
                case 1:
                    System.out.println("Enter amount to deposit: ");
                    try
                    {
                        amount = console.nextDouble();
                    }
                    catch(InputMismatchException e)
                    {
                        System.out.println("Please enter a numeric amount.");
                        return;
                    }
                    if(amount < 0)
                    {
                        System.out.println("You can't withdraw a negative amount");
                        return;
                    }
                    account.deposit(amount);
                    break;
                case 2:
                    System.out.println("Enter amount to withdraw: ");
                    try
                    {
                        amount = console.nextDouble();
                    }
                    catch(InputMismatchException e)
                    {
                        System.out.println("Please enter a numeric amount.");
                        return;
                    }
                    if(amount < 0)
                    {
                        System.out.println("You can't withdraw a negative amount");
                        return;
                    }
                    account.withdraw(amount);
                    break;
                case 3:
                    System.out.println(account.getBalance());
                    break;
                case 4:
                    again = false;
                    break;
                default:
                    System.out.println("Enter a valid option.");
                }
            }
            while(again);
            System.out.println("Back to main menu? 1 - Yes, 2 - No");
            try
            {
                userInput = console.nextInt();
            }
            catch(InputMismatchException e)
            {
                System.out.println("Please enter a number");
                return;
            }
        }
        while(userInput == 1);
    }
}

package model;

public class BankAccount {

    private double balance = 0;

    public BankAccount() {}

    public BankAccount(double balance)
    {
        this.balance = balance;
    }

    public void deposit(double amount)
    {
        balance = balance + amount;
    }

    public void withdraw(double amount)
    {
        if((balance - amount) < 0)
        {
            System.out.println("Transaction Failed: You can't withdraw more than you have.");
        }
        else
        {
            balance = balance - amount;
        }
    }

    public double getBalance()
    {
        return balance;
    }
}

Body:
You'll be best served by breaking up your main function in multiple functions that handle different parts of the control logic. A good rule of thumb (for beginning programmers) is a function over ~10-15 lines should probably be multiple functions, though it's not an ironclad rule.

I rewrote your program to be multiple functions, but since this seems like a homework problem I won't post the whole thing. Rather, a general strategy with some snippets.

For example, when the user enters an amount to deposit or withdraw. What your programs wants in that moment is a single double, so you could request a single double, and let another method figure out how to get it:

switch (getMenuChoice()) {
    case 1:
        account.deposit(getDepositOrWithdrawAmount("deposit"));
        break;
    case 2:
        account.withdraw(getDepositOrWithdrawAmount("withdraw"));
        break;
    // etc.
}

Then, that function is responsible for looping infinitely until the user provides a valid value:

static double getDepositOrWithdrawAmount(String depositOrWithdraw) {
    // loop infinitely until we get a valid value
    while (true) {
      System.out.println("Enter amount to " + depositOrWithdraw);
      try {
        double amount = console.nextDouble();
        if (amount < 0) {
          System.out.println("You can't " + depositOrWithdraw + " a negative amount.");
        } else {
          // valid value! return for deposit / withdraw to use
          // , ending the infinite loop
          return amount;
        }
      } catch (InputMismatchException e) {
        System.out.println("Please enter a numeric amount.");

        // clear the bad token from the stream
        // if you don't do this, each time you
        // call `nextDouble`, the same value will
        // be returned, causing an infinite loop
        console.next();
      }
    }
  }

The nice thing about this function is it works in isolation:

public static void main(String[] args) {
  System.out.println("Test: " + getDepositOrWithdrawal("test!"));
}

Gives this result:

Enter amount to test!
abc
Please enter a numeric amount.
Enter amount to test!
not-a-number
Please enter a numeric amount.
Enter amount to test!
-5
You can't test! a negative amount.
Enter amount to test!
1000
Test: 1000.0

This lets you test that pieces of your program are working on their own, instead of trying to debug one big program.

You can write other parts of your program as functions as well, but I'll leave that to you.


问:
Session in ASP.NET Core MVC
I am migrating an ASP.NET MVC application to ASP.NET Core MVC.

In ASP.NET MVC, I am using some Session variables to store or get values like:

```<code>Session["UserID"] = user.UserName;
Session["Role"] = role[0].ROLE_DESCRIPTION;
ViewData["LEVEL"] = Session["LEVEL"];
</code>```

But after converting, I get an error:

The name 'Session' does not exist in the current context

Also, I need to have replacement for this as well in the .cshtml file:

```<code>var UserName = "@Session["Name"]";
</code>```

Is there any other method in ASP.NET Core MVC to store or get values on those variables without changing the behavior?

答:
You need to add session middleware in your configuration file

```<code>public void ConfigureServices(IServiceCollection services)
{
     //........
    services.AddDistributedMemoryCache();
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(1);//You can set Time
    });
    services.AddMvc();
}

public void ConfigureServices(IServiceCollection services)
{
    //......
    app.UseSession();
    //......
}
</code>```

Then in your controller, you can

```<code>//set session

HttpContext.Session.SetString(SessionName, "Jarvik");
HttpContext.Session.SetInt32(SessionAge, 24);

//get session

ViewBag.Name = HttpContext.Session.GetString(SessionName);
ViewBag.Age = HttpContext.Session.GetInt32(SessionAge);

</code>```

Title: Session in ASP.NET Core MVC

Body:
I am migrating an ASP.NET MVC application to ASP.NET Core MVC.

In ASP.NET MVC, I am using some Session variables to store or get values like:

Session["UserID"] = user.UserName;
Session["Role"] = role[0].ROLE_DESCRIPTION;
ViewData["LEVEL"] = Session["LEVEL"];

But after converting, I get an error:

The name 'Session' does not exist in the current context

Also, I need to have replacement for this as well in the .cshtml file:

var UserName = "@Session["Name"]";

Is there any other method in ASP.NET Core MVC to store or get values on those variables without changing the behavior?

Body:
You need to add session middleware in your configuration file

public void ConfigureServices(IServiceCollection services)
{
     //........
    services.AddDistributedMemoryCache();
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(1);//You can set Time
    });
    services.AddMvc();
}

public void ConfigureServices(IServiceCollection services)
{
    //......
    app.UseSession();
    //......
}

Then in your controller, you can

//set session

HttpContext.Session.SetString(SessionName, "Jarvik");
HttpContext.Session.SetInt32(SessionAge, 24);

//get session

ViewBag.Name = HttpContext.Session.GetString(SessionName);
ViewBag.Age = HttpContext.Session.GetInt32(SessionAge);


问:
IndexError:Index 10 is out of bounds for axis 1 with size 10
I am classifying images into 30 different classes using CNN and on running the CNN ,I am getting the following traceback-

```<code>Traceback (most recent call last):
File "thapar.py", line 165, in <module>
Y = np_utils.to_categorical(labels, num_classes)
File "/home/rishav/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/utils/np_utils.py", line 31, in to_categorical
categorical[np.arange(n), y] = 1
IndexError: index 10 is out of bounds for axis 1 with size 10
</code>```

Python 3.6
Keras 2.1.5 using tensorflow backend
Ubuntu 16.04

I have explored other similar questions but unable to find the similarity in issue.

How to resolve this issue?

Edit:

```<code>num_classes = 30
num_of_samples = img_data.shape[0]
labels = np.ones((num_of_samples,),dtype='int64')
labels[0:20]=0
labels[20:40]=1
labels[40:60]=2
labels[60:80]=3
labels[80:100]=4
labels[100:120]=5
labels[120:140]=6
labels[140:160]=7
labels[160:180]=8
labels[180:200]=9
labels[200:220]=10
labels[220:240]=11
labels[240:260]=12
labels[260:280]=13
labels[280:300]=14
labels[300:320]=15
labels[320:340]=16
labels[340:360]=17
labels[360:380]=18
labels[380:400]=19
labels[400:420]=20
labels[420:440]=21
labels[440:460]=22
labels[460:480]=23
labels[480:500]=24
labels[500:520]=25
labels[520:540]=26
labels[540:560]=27
labels[560:580]=28
labels[580:600]=29

names =
</code>```

['bent','bowl','claw','fist','good','thumbs_up','A','B','C','D','E','F','G','H','I','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y']

```<code>Y = np_utils.to_categorical(labels, num_classes)
</code>```

答: Recently, I have faced the same problem, then I got to know it was giving error with some images only, I remove those images and it worked perfectly for me then.</p>

Body:
I am classifying images into 30 different classes using CNN and on running the CNN ,I am getting the following traceback-

Traceback (most recent call last):
File "thapar.py", line 165, in <module>
Y = np_utils.to_categorical(labels, num_classes)
File "/home/rishav/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras/utils/np_utils.py", line 31, in to_categorical
categorical[np.arange(n), y] = 1
IndexError: index 10 is out of bounds for axis 1 with size 10

Python 3.6
Keras 2.1.5 using tensorflow backend
Ubuntu 16.04

I have explored other similar questions but unable to find the similarity in issue.

How to resolve this issue?

Edit:

num_classes = 30
num_of_samples = img_data.shape[0]
labels = np.ones((num_of_samples,),dtype='int64')
labels[0:20]=0
labels[20:40]=1
labels[40:60]=2
labels[60:80]=3
labels[80:100]=4
labels[100:120]=5
labels[120:140]=6
labels[140:160]=7
labels[160:180]=8
labels[180:200]=9
labels[200:220]=10
labels[220:240]=11
labels[240:260]=12
labels[260:280]=13
labels[280:300]=14
labels[300:320]=15
labels[320:340]=16
labels[340:360]=17
labels[360:380]=18
labels[380:400]=19
labels[400:420]=20
labels[420:440]=21
labels[440:460]=22
labels[460:480]=23
labels[480:500]=24
labels[500:520]=25
labels[520:540]=26
labels[540:560]=27
labels[560:580]=28
labels[580:600]=29

names =

['bent','bowl','claw','fist','good','thumbs_up','A','B','C','D','E','F','G','H','I','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y']

Y = np_utils.to_categorical(labels, num_classes)


问:
Bind to CollectionViewSource in xaml
I have a ViewModel with 2 properties:

IsReadOnly

SomeCollectionViewSource

This is a simple working view example:

```<code><StackPanel DataContext="{Binding SomeCollectionViewSource}">
  <DatePicker SelectedDate="{Binding Path=Date}" IsEnabled="False" />
</StackPanel>
</code>```

Now I want to bind the IsEnabled property:

```<code><StackPanel DataContext="{Binding}">
  <DatePicker SelectedDate="{Binding Path=?}" IsEnabled="{Binding IsReadOnly}" />
</StackPanel>
</code>```

How should the binding look like in this example? (I think I'm mising something simple)

I would prefer a short and easy binding since I have a lot of controls to bind.

Is there a better/easier way to make all controls on one CollectionViewSource read-only?

答:
Under the assumption that the above binding targets the current item this should be equivalent:

```<code>{Binding SomeCollectionViewSource.View/Date}
</code>```

Also see the references for Binding.Path and the PropertyPath syntax if you have not read them already, there's a lot to it.

The above binding (of your two bindings) is equivalent to:

```<code>{Binding Path=/Date}
</code>```

The slash can be omitted and if the property is not found on the collection the binding looks for the property on the current item. so...

```<code>{Binding Date} binds to: CurrentItem -> Date
{Binding Count} binds to: Count
</code>```

For clarity i would suggest always explicity writing the slash.

(Setting any DataContext to {Binding} is really pointless by the way)

Title: Bind to CollectionViewSource in xaml

Body:
I have a ViewModel with 2 properties:

IsReadOnly

SomeCollectionViewSource

This is a simple working view example:

<StackPanel DataContext="{Binding SomeCollectionViewSource}">
  <DatePicker SelectedDate="{Binding Path=Date}" IsEnabled="False" />
</StackPanel>

Now I want to bind the IsEnabled property:

<StackPanel DataContext="{Binding}">
  <DatePicker SelectedDate="{Binding Path=?}" IsEnabled="{Binding IsReadOnly}" />
</StackPanel>

How should the binding look like in this example? (I think I'm mising something simple)

I would prefer a short and easy binding since I have a lot of controls to bind.

Is there a better/easier way to make all controls on one CollectionViewSource read-only?

Body:
Under the assumption that the above binding targets the current item this should be equivalent:

{Binding SomeCollectionViewSource.View/Date}

Also see the references for Binding.Path and the PropertyPath syntax if you have not read them already, there's a lot to it.

The above binding (of your two bindings) is equivalent to:

{Binding Path=/Date}

The slash can be omitted and if the property is not found on the collection the binding looks for the property on the current item. so...

{Binding Date} binds to: CurrentItem -> Date
{Binding Count} binds to: Count

For clarity i would suggest always explicity writing the slash.

(Setting any DataContext to {Binding} is really pointless by the way)


问:
RetroFit: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY in MVVM kotlin app
I was developing an app which make some networks call using Retrofit, and then load into a local database which Room.

My problem comes, when I try to implement the flow of the service which give all the reservations I made in the app, that throws me the title above error:

Regaring to the json which I would like to recover is this:

```<code>{
  "reservations": [
    {
      "id": "6204d5e99b251509d20d3e57",
      "garageSpotNumber": "91",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204d5e99b251509d20d3e58",
          "date": 1644451200000
        }
      ],
      "dateFrom": 1644451200000,
      "dateTo": 1644451200000
    },
    {
      "id": "6204e0ad9b251509d20d3e59",
      "garageSpotNumber": "41",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e0ad9b251509d20d3e5a",
          "date": 1644537600000
        }
      ],
      "dateFrom": 1644537600000,
      "dateTo": 1644537600000
    },
    {
      "id": "6204e16c9b251509d20d3e5b",
      "garageSpotNumber": "43",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e16c9b251509d20d3e5c",
          "date": 1644796800000
        }
      ],
      "dateFrom": 1644796800000,
      "dateTo": 1644796800000
    },
    {
      "id": "6204e9dc9b251509d20d3e61",
      "garageSpotNumber": "60",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e9dc9b251509d20d3e62",
          "date": 1644883200000
        }
      ],
      "dateFrom": 1644883200000,
      "dateTo": 1644883200000
    },
    {
      "id": "6204e89b9b251509d20d3e5d",
      "garageSpotNumber": "47",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e89b9b251509d20d3e5e",
          "date": 1645056000000
        }
      ],
      "dateFrom": 1645056000000,
      "dateTo": 1645056000000
    },
    {
      "id": "6204e9929b251509d20d3e5f",
      "garageSpotNumber": "102",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e9929b251509d20d3e60",
          "date": 1645142400000
        }
      ],
      "dateFrom": 1645142400000,
      "dateTo": 1645142400000
    },
    {
      "id": "620519299b251509d20d3e63",
      "garageSpotNumber": "65",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "620519299b251509d20d3e64",
          "date": 1645401600000
        }
      ],
      "dateFrom": 1645401600000,
      "dateTo": 1645401600000
    },
    {
      "id": "6205231a9b251509d20d3e65",
      "garageSpotNumber": "88",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6205231a9b251509d20d3e66",
          "date": 1645660800000
        }
      ],
      "dateFrom": 1645660800000,
      "dateTo": 1645660800000
    }
  ]
}
</code>```

So my models and response are like this:

```<code>data class QueryGarageResponse(
    @SerializedName("reservations") var reservations: List<GarageBooking> = emptyList(),
    @SerializedName("error") var error: ErrorCall? = null
):Serializable

data class GarageBooking (
    @SerializedName("id") var id: String,
    @SerializedName("garageSpotNumber") var seatNumber : String,
    @SerializedName("area") var area:SeatArea,
    @SerializedName("employee") var employee: ReservedEmployee,
    @SerializedName("detail") var detail: BookingDetail,
    @SerializedName("dateFrom") var dateFrom: Long,
    @SerializedName("dateTo") var dateTo: Long
    ):Serializable
</code>```

Regarding to my api services:

```<code> @GET("api/v1/garageReservation")
    fun getAllGarageReservations(
        @Header("tokenGraph")token:String,
        @Query("startdate")startDate:Long,
        @Query("finishDate")finishDate:Long,
        @Query("employee")employee:String
    ):Call<QueryGarageResponse>
</code>```

my repository:

SeatRepository.kt

```<code>fun getAllGarageReservations(
        token:String,
        startDate: Long,
        finishDate:Long,
        employee:String
    ): LiveData<QueryGarageResponse>{
        var responseData = MutableLiveData<QueryGarageResponse>()

        api.getAllGarageReservations(token, startDate, finishDate, employee)
            .enqueue(object: Callback<QueryGarageResponse> {
                override fun onResponse(
                    call: Call<QueryGarageResponse>,
                    response: Response<QueryGarageResponse>
                ) {
                    Log.d("garage", "resp getAllGarageReservation repository: $response")
                    if(response.isSuccessful){
                        Log.d("garage", "resp repository: ${response.body()}")
                        responseData.value = response.body()
                    }else{
                        try {
                            val apiError = getErrorApi(response.errorBody()!!, ApiError::class.java)

                            apiError.error.let {
                                responseData.value =
                                    QueryGarageResponse(
                                        reservations = ArrayList(),
                                        error = ErrorCall(
                                            status = it.status,
                                            payload = it.payload.seat
                                        )
                                    )
                            }

                        } catch (ex: Exception) {
                            responseData.value =
                                QueryGarageResponse(
                                    reservations = ArrayList(),
                                    error = ErrorCall(
                                       message = ex.message!!
                                    )
                                )
                        }
                    }

                }

                override fun onFailure(call: Call<QueryGarageResponse>, t: Throwable) {
                    responseData.value =
                        QueryGarageResponse(
                           reservations = arrayListOf(),
                           error = ErrorCall(message = t.message!!)
                        )
                    }
            })
        return responseData
    }
</code>```

My viewModel

CheckGarageViewModel.kt

```<code>class CheckGarageViewModel(
    private val repository : SeatsRepository
    ): ViewModel() {

    fun getGarageBookings(): LiveData<QueryGarageResponse>{
        //1296000000 = millisegundos equivalentes a 15 dias.
        return repository.getAllGarageReservations(token = UserPreferences.prefs.token!!, System.currentTimeMillis(), System.currentTimeMillis() + 1296000000, UserPreferences.prefs.email!!)
    }

}

</code>```

I don't know why this error happens when I really expect an Array instead of an object.

So if you can help take thanks in advance !

答:
You are facing an error because you are parsing the wrong data type.

```<code>data class GarageBooking (
    @SerializedName("id") var id: String,
    @SerializedName("garageSpotNumber") var seatNumber : String,
    @SerializedName("area") var area:SeatArea,
    @SerializedName("employee") var employee: ReservedEmployee,
    @SerializedName("detail") var detail: BookingDetail,
    @SerializedName("dateFrom") var dateFrom: Long,
    @SerializedName("dateTo") var dateTo: Long
):Serializable
</code>```

According to this model class, detail variable should be Object in API response. But have a look at the API response you have added.

```<code>{
  "id": "6204e89b9b251509d20d3e5d",
  "garageSpotNumber": "47",
  "area": null,
  "employee": {
    "username": "luismanuel.lucas@vass.es",
    "preferredName": "Luis Manuel Lucas Amate"
  },
  "detail": [
    {
      "id": "6204e89b9b251509d20d3e5e",
      "date": 1645056000000
    }
  ],
  "dateFrom": 1645056000000,
  "dateTo": 1645056000000
}
</code>```

detail variable is Array type. So you need to define detail variable as a list in your model class like below,

```<code>    @SerializedName("detail") var detail: List<BookingDetail>?,
</code>```

After making this change, your app will run without error.

Body:
I was developing an app which make some networks call using Retrofit, and then load into a local database which Room.

My problem comes, when I try to implement the flow of the service which give all the reservations I made in the app, that throws me the title above error:

Regaring to the json which I would like to recover is this:

{
  "reservations": [
    {
      "id": "6204d5e99b251509d20d3e57",
      "garageSpotNumber": "91",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204d5e99b251509d20d3e58",
          "date": 1644451200000
        }
      ],
      "dateFrom": 1644451200000,
      "dateTo": 1644451200000
    },
    {
      "id": "6204e0ad9b251509d20d3e59",
      "garageSpotNumber": "41",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e0ad9b251509d20d3e5a",
          "date": 1644537600000
        }
      ],
      "dateFrom": 1644537600000,
      "dateTo": 1644537600000
    },
    {
      "id": "6204e16c9b251509d20d3e5b",
      "garageSpotNumber": "43",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e16c9b251509d20d3e5c",
          "date": 1644796800000
        }
      ],
      "dateFrom": 1644796800000,
      "dateTo": 1644796800000
    },
    {
      "id": "6204e9dc9b251509d20d3e61",
      "garageSpotNumber": "60",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e9dc9b251509d20d3e62",
          "date": 1644883200000
        }
      ],
      "dateFrom": 1644883200000,
      "dateTo": 1644883200000
    },
    {
      "id": "6204e89b9b251509d20d3e5d",
      "garageSpotNumber": "47",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e89b9b251509d20d3e5e",
          "date": 1645056000000
        }
      ],
      "dateFrom": 1645056000000,
      "dateTo": 1645056000000
    },
    {
      "id": "6204e9929b251509d20d3e5f",
      "garageSpotNumber": "102",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6204e9929b251509d20d3e60",
          "date": 1645142400000
        }
      ],
      "dateFrom": 1645142400000,
      "dateTo": 1645142400000
    },
    {
      "id": "620519299b251509d20d3e63",
      "garageSpotNumber": "65",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "620519299b251509d20d3e64",
          "date": 1645401600000
        }
      ],
      "dateFrom": 1645401600000,
      "dateTo": 1645401600000
    },
    {
      "id": "6205231a9b251509d20d3e65",
      "garageSpotNumber": "88",
      "area": null,
      "employee": {
        "username": "luismanuel.lucas@vass.es",
        "preferredName": "Luis Manuel Lucas Amate"
      },
      "detail": [
        {
          "id": "6205231a9b251509d20d3e66",
          "date": 1645660800000
        }
      ],
      "dateFrom": 1645660800000,
      "dateTo": 1645660800000
    }
  ]
}

So my models and response are like this:

data class QueryGarageResponse(
    @SerializedName("reservations") var reservations: List<GarageBooking> = emptyList(),
    @SerializedName("error") var error: ErrorCall? = null
):Serializable

data class GarageBooking (
    @SerializedName("id") var id: String,
    @SerializedName("garageSpotNumber") var seatNumber : String,
    @SerializedName("area") var area:SeatArea,
    @SerializedName("employee") var employee: ReservedEmployee,
    @SerializedName("detail") var detail: BookingDetail,
    @SerializedName("dateFrom") var dateFrom: Long,
    @SerializedName("dateTo") var dateTo: Long
    ):Serializable

Regarding to my api services:

 @GET("api/v1/garageReservation")
    fun getAllGarageReservations(
        @Header("tokenGraph")token:String,
        @Query("startdate")startDate:Long,
        @Query("finishDate")finishDate:Long,
        @Query("employee")employee:String
    ):Call<QueryGarageResponse>

my repository:

SeatRepository.kt

fun getAllGarageReservations(
        token:String,
        startDate: Long,
        finishDate:Long,
        employee:String
    ): LiveData<QueryGarageResponse>{
        var responseData = MutableLiveData<QueryGarageResponse>()

        api.getAllGarageReservations(token, startDate, finishDate, employee)
            .enqueue(object: Callback<QueryGarageResponse> {
                override fun onResponse(
                    call: Call<QueryGarageResponse>,
                    response: Response<QueryGarageResponse>
                ) {
                    Log.d("garage", "resp getAllGarageReservation repository: $response")
                    if(response.isSuccessful){
                        Log.d("garage", "resp repository: ${response.body()}")
                        responseData.value = response.body()
                    }else{
                        try {
                            val apiError = getErrorApi(response.errorBody()!!, ApiError::class.java)

                            apiError.error.let {
                                responseData.value =
                                    QueryGarageResponse(
                                        reservations = ArrayList(),
                                        error = ErrorCall(
                                            status = it.status,
                                            payload = it.payload.seat
                                        )
                                    )
                            }

                        } catch (ex: Exception) {
                            responseData.value =
                                QueryGarageResponse(
                                    reservations = ArrayList(),
                                    error = ErrorCall(
                                       message = ex.message!!
                                    )
                                )
                        }
                    }

                }

                override fun onFailure(call: Call<QueryGarageResponse>, t: Throwable) {
                    responseData.value =
                        QueryGarageResponse(
                           reservations = arrayListOf(),
                           error = ErrorCall(message = t.message!!)
                        )
                    }
            })
        return responseData
    }

My viewModel

CheckGarageViewModel.kt

class CheckGarageViewModel(
    private val repository : SeatsRepository
    ): ViewModel() {

    fun getGarageBookings(): LiveData<QueryGarageResponse>{
        //1296000000 = millisegundos equivalentes a 15 dias.
        return repository.getAllGarageReservations(token = UserPreferences.prefs.token!!, System.currentTimeMillis(), System.currentTimeMillis() + 1296000000, UserPreferences.prefs.email!!)
    }

}

I don't know why this error happens when I really expect an Array instead of an object.

So if you can help take thanks in advance !

Body:
You are facing an error because you are parsing the wrong data type.

data class GarageBooking (
    @SerializedName("id") var id: String,
    @SerializedName("garageSpotNumber") var seatNumber : String,
    @SerializedName("area") var area:SeatArea,
    @SerializedName("employee") var employee: ReservedEmployee,
    @SerializedName("detail") var detail: BookingDetail,
    @SerializedName("dateFrom") var dateFrom: Long,
    @SerializedName("dateTo") var dateTo: Long
):Serializable

According to this model class, detail variable should be Object in API response. But have a look at the API response you have added.

{
  "id": "6204e89b9b251509d20d3e5d",
  "garageSpotNumber": "47",
  "area": null,
  "employee": {
    "username": "luismanuel.lucas@vass.es",
    "preferredName": "Luis Manuel Lucas Amate"
  },
  "detail": [
    {
      "id": "6204e89b9b251509d20d3e5e",
      "date": 1645056000000
    }
  ],
  "dateFrom": 1645056000000,
  "dateTo": 1645056000000
}

detail variable is Array type. So you need to define detail variable as a list in your model class like below,

    @SerializedName("detail") var detail: List<BookingDetail>?,

After making this change, your app will run without error.


答:
```<code>const handleSelectedItemsClick = React.useMemo(() =>
    !isRunning
    ? (items: string[]) => startRun({ items: items })
    : undefined,
    [startRun]
);

const handleRowClick = (itemId) => {
    handleSelectedItemsClick([itemId]);
}

handleRowClick(itemId);
handleSelectedItemsClick(itemIds);
</code>```

Title: How to rewrite code into one using javascript and react?


问:
Ansible Loop & Array
I need to loop a list of names to use it in the query itself. Upon looping, I want to gather the information from the query itself and store it in an array. I manage to store it in an array but whenever I re-run the program, it will keep adding the same value again and again.

My data:

    priv: [admin, monitor]
    data:
      - {name: admin, locked: 'no', uid: 0}
      - {name: monitor, locked: 'no', uid: 102}
```
<p>This is my code:</p>
<pre class="lang-yaml prettyprint-override"><code>    - name: Test Informationk
      set_fact:
        info2: "{{ data|json_query(jmesquery) + info2|default([]) }}"
        cacheable: yes
      vars:
        jmesquery: "[?name=='{{ item }}'].[name,locked,uid]"
      loop: "{{ priv }}"
</code>```

This is my output:

    - - monitor
        'no'
        102
    - - admin
        'no'
        0
    - - monitor
        'no'
        102
    - - admin
        'no'
        0
    - - monitor
        'no'
        102
    - - admin
        'no'
        0
```

It will keep adding and adding every time I re-run the program. The existing data is supposed to be only 2 items.

答:
Q: "Whenever I re-run the program, it will keep adding the same value again and again."

A: You set cacheable: yes. Quoting from cacheable:

This actually creates 2 copies of the variable, a normal 'set_fact' host variable with high precedence and a lower 'ansible_fact' one that is available for persistence via the facts cache plugin.

If you don't want to cache the variable disable it. If you want to see in detail what's going on put a debug in front of the set_fact, for example, the playbook below

- hosts: localhost
  vars:
    priv: [admin, monitor]
    data:
      - {name: admin, locked: 'no', uid: 0}
      - {name: monitor, locked: 'no', uid: 102}
  tasks:
    - debug:
        var: info2
    - set_fact:
        info2: "{{ data|json_query(jmesquery) + info2|default([]) }}"
        cacheable: false
      vars:
        jmesquery: "[?name=='{{ item }}'].[name,locked,uid]"
      loop: "{{ priv }}"
    - debug:
        var: info2
```
<p>gives</p>
<pre class="lang-yaml prettyprint-override"><code>TASK [debug] *******************************************************
ok: [localhost] =>
  info2: VARIABLE IS NOT DEFINED!

TASK [set_fact] ****************************************************
ok: [localhost] => (item=admin)
ok: [localhost] => (item=monitor)

TASK [debug] *******************************************************
ok: [localhost] =>
  info2:
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0
</code>```

If you set both cacheable: true in set_fact and the configuration below (you must have already set the caching, I guess)

```<code>shell> cat ansible.cfg
[defaults]
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_cache.json

...
</code>```

then you'll see the list incremented on each consecutive run of the playbook

TASK [debug] ***************************************************
ok: [localhost] =>
  info2:
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0

TASK [set_fact] ***********************************************
ok: [localhost] => (item=admin)
ok: [localhost] => (item=monitor)

TASK [debug] **************************************************
ok: [localhost] =>
  info2:
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0
```
<hr>
<p>See the cache</p>
<pre class="lang-yaml prettyprint-override"><code>shell> cat /tmp/ansible_cache.json/localhost
{
    "info2": [
        [
            "monitor",
            "no",
            102
        ],
        [
            "admin",
            "no",
            0
        ]
    ]
}
</code>```

Title: Ansible Loop & Array

Body:
I need to loop a list of names to use it in the query itself. Upon looping, I want to gather the information from the query itself and store it in an array. I manage to store it in an array but whenever I re-run the program, it will keep adding the same value again and again.

My data:

    priv: [admin, monitor]
    data:
      - {name: admin, locked: 'no', uid: 0}
      - {name: monitor, locked: 'no', uid: 102}

This is my code:

    - name: Test Informationk
      set_fact:
        info2: "{{ data|json_query(jmesquery) + info2|default([]) }}"
        cacheable: yes
      vars:
        jmesquery: "[?name=='{{ item }}'].[name,locked,uid]"
      loop: "{{ priv }}"

This is my output:

    - - monitor
        'no'
        102
    - - admin
        'no'
        0
    - - monitor
        'no'
        102
    - - admin
        'no'
        0
    - - monitor
        'no'
        102
    - - admin
        'no'
        0

It will keep adding and adding every time I re-run the program. The existing data is supposed to be only 2 items.

Body:
Q: "Whenever I re-run the program, it will keep adding the same value again and again."

A: You set cacheable: yes. Quoting from cacheable:

This actually creates 2 copies of the variable, a normal 'set_fact' host variable with high precedence and a lower 'ansible_fact' one that is available for persistence via the facts cache plugin.

If you don't want to cache the variable disable it. If you want to see in detail what's going on put a debug in front of the set_fact, for example, the playbook below

- hosts: localhost
  vars:
    priv: [admin, monitor]
    data:
      - {name: admin, locked: 'no', uid: 0}
      - {name: monitor, locked: 'no', uid: 102}
  tasks:
    - debug:
        var: info2
    - set_fact:
        info2: "{{ data|json_query(jmesquery) + info2|default([]) }}"
        cacheable: false
      vars:
        jmesquery: "[?name=='{{ item }}'].[name,locked,uid]"
      loop: "{{ priv }}"
    - debug:
        var: info2

gives

TASK [debug] *******************************************************
ok: [localhost] =>
  info2: VARIABLE IS NOT DEFINED!

TASK [set_fact] ****************************************************
ok: [localhost] => (item=admin)
ok: [localhost] => (item=monitor)

TASK [debug] *******************************************************
ok: [localhost] =>
  info2:
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0

If you set both cacheable: true in set_fact and the configuration below (you must have already set the caching, I guess)

shell> cat ansible.cfg
[defaults]
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_cache.json

...

then you'll see the list incremented on each consecutive run of the playbook

TASK [debug] ***************************************************
ok: [localhost] =>
  info2:
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0

TASK [set_fact] ***********************************************
ok: [localhost] => (item=admin)
ok: [localhost] => (item=monitor)

TASK [debug] **************************************************
ok: [localhost] =>
  info2:
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0

See the cache

shell> cat /tmp/ansible_cache.json/localhost
{
    "info2": [
        [
            "monitor",
            "no",
            102
        ],
        [
            "admin",
            "no",
            0
        ]
    ]
}


问:
how to remove special characters/numbers from cucumber console?
I'm new for Cucumber. While I'm writing a basic feature file I have used tables. and printed the same table values to see how they will display on console. But while printing the values I could see some special characters. What are they and how to remove them? any idea?
 I googled to get a solution, but couldn't make it. Can anyone please help me?

Here is my feature file:
    Feature: Addding two values
 Addding two values

```<code>Scenario: tesing sum values
  Given input and output
  When inputs <inputx> and <inputy> is given
 |22|33|
 |33|55|
 Then output must be <output>
 |55|
 |88|
</code>```

And the below is my Ruby File

```<code>Given(/^input and output$/) do
  puts "Given block"
end

When(/^inputs <inputx> and <inputy> is given$/) do |table|
  # table is a Cucumber::Core::Ast::DataTable
  puts table
end

Then(/^output must be <output>$/) do |table|
   # table is a Cucumber::Core::Ast::DataTable
   puts table
end
</code>```

And the below is the output on the console

```<code>*** WARNING: You must use ANSICON 1.31 or higher (https://github.com/adoxa/ansicon/) to get coloured output on Windows
C:/Ruby193/bin/ruby -S bundle exec cucumber  --profile default
Using the default profile...
Feature: Addding two values
  Addding two values

  Scenario: tesing sum values
    [32mGiven input and output[0m
      [36mGiven block[0m
[32mWhen inputs <inputx> and <inputy> is given[0m
  [36m[0m
  [36m  | [32m    22[0m[0m |[0m [32m    33[0m[0m |[0m[0m
  [36m  | [32m    33[0m[0m |[0m [32m    55[0m[0m |[0m[0m
  | [36m22[0m[0m |[0m [36m33[0m[0m |[0m
  | [36m33[0m[0m |[0m [36m55[0m[0m |[0m
[32mThen output must be <output>[0m
  [36m[0m
  [36m  | [32m    55[0m[0m |[0m[0m
  [36m  | [32m    88[0m[0m |[0m[0m
  | [36m55[0m[0m |[0m
  | [36m88[0m[0m |[0m

1 scenario ([32m1 passed[0m)
3 steps ([32m3 passed[0m)
0m6.555s
</code>```

答:
You are getting this error because cucumber is trying to print the coloured output into the terminal, but your terminal is not able to do so. As a result these symbols are visible.
 To resolve this issue just add monochrome = true in the Runner (Step Definition) file where you are gluing this cucumber feature file.
Sample Code:

```<code>@CucumberOptions(features = {"src/test/resources/FeatureFiles/RegisterUser.feature", "src/test/resources/FeatureFiles/RegisterUserVerifyError.feature"},
glue = "com/assignment2/userreg/stepdefinations/",
tags = {"@multipleverify"}, monochrome = true, plugin = {"pretty", "html:target/cucumber-reports/cucumber-pretty"})
</code>```

Body:
I'm new for Cucumber. While I'm writing a basic feature file I have used tables. and printed the same table values to see how they will display on console. But while printing the values I could see some special characters. What are they and how to remove them? any idea?
 I googled to get a solution, but couldn't make it. Can anyone please help me?

Here is my feature file:
    Feature: Addding two values
 Addding two values

Scenario: tesing sum values
  Given input and output
  When inputs <inputx> and <inputy> is given
 |22|33|
 |33|55|
 Then output must be <output>
 |55|
 |88|

And the below is my Ruby File

Given(/^input and output$/) do
  puts "Given block"
end

When(/^inputs <inputx> and <inputy> is given$/) do |table|
  # table is a Cucumber::Core::Ast::DataTable
  puts table
end

Then(/^output must be <output>$/) do |table|
   # table is a Cucumber::Core::Ast::DataTable
   puts table
end

And the below is the output on the console

*** WARNING: You must use ANSICON 1.31 or higher (https://github.com/adoxa/ansicon/) to get coloured output on Windows
C:/Ruby193/bin/ruby -S bundle exec cucumber  --profile default
Using the default profile...
Feature: Addding two values
  Addding two values

  Scenario: tesing sum values
    [32mGiven input and output[0m
      [36mGiven block[0m
[32mWhen inputs <inputx> and <inputy> is given[0m
  [36m[0m
  [36m  | [32m    22[0m[0m |[0m [32m    33[0m[0m |[0m[0m
  [36m  | [32m    33[0m[0m |[0m [32m    55[0m[0m |[0m[0m
  | [36m22[0m[0m |[0m [36m33[0m[0m |[0m
  | [36m33[0m[0m |[0m [36m55[0m[0m |[0m
[32mThen output must be <output>[0m
  [36m[0m
  [36m  | [32m    55[0m[0m |[0m[0m
  [36m  | [32m    88[0m[0m |[0m[0m
  | [36m55[0m[0m |[0m
  | [36m88[0m[0m |[0m

1 scenario ([32m1 passed[0m)
3 steps ([32m3 passed[0m)
0m6.555s

Body:
You are getting this error because cucumber is trying to print the coloured output into the terminal, but your terminal is not able to do so. As a result these symbols are visible.
 To resolve this issue just add monochrome = true in the Runner (Step Definition) file where you are gluing this cucumber feature file.
Sample Code:

@CucumberOptions(features = {"src/test/resources/FeatureFiles/RegisterUser.feature", "src/test/resources/FeatureFiles/RegisterUserVerifyError.feature"},
glue = "com/assignment2/userreg/stepdefinations/",
tags = {"@multipleverify"}, monochrome = true, plugin = {"pretty", "html:target/cucumber-reports/cucumber-pretty"})


问:
JQuery script not firing on main page but same JQuery fires in separate php page variable inserted
I have a PHP app  that works perfectly except for my hyperlinked jQuery call to another PHP page.  It is a dead link but it is underlined. The jQuery code is correct, because it is the same code on a separate PHP page that I call that uses the same logic... and it works on that embedded PHP page within this challenged page. Think I'm using PHP 5.x.

const friendReqURL = 'domain.com';
const thisRandNum = Math.random();

function deny_friend(x, a, b) {
  $.post(friendReqURL, {
      request: "denyFrd",
      reqID: x,
      id1: a,
      id2: b,
      thisWipit: thisRandNum
    },
    function(data) {
      $("#request" + x).html(data).show();
    });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td bgcolor="#CCCCCC">
  <div align="center" class="style2">
    <span id="request' . $id2 . '">Withdraw Interest?
  Yes </span></div>
</td></code>```

Page link is just inactive as if it isn't a hyperlink (yet it is).

答:
I duplicated the sql query of reqID: in my code... just found the duplication. Somehow that duplication was disabling the jquery code. Deleted it, it works now. –
Vets
Jun 10 2019 at 1:40   Delete</p>

Body:
I have a PHP app  that works perfectly except for my hyperlinked jQuery call to another PHP page.  It is a dead link but it is underlined. The jQuery code is correct, because it is the same code on a separate PHP page that I call that uses the same logic... and it works on that embedded PHP page within this challenged page. Think I'm using PHP 5.x.

const friendReqURL = 'domain.com';
const thisRandNum = Math.random();

function deny_friend(x, a, b) {
  $.post(friendReqURL, {
      request: "denyFrd",
      reqID: x,
      id1: a,
      id2: b,
      thisWipit: thisRandNum
    },
    function(data) {
      $("#request" + x).html(data).show();
    });
}

    Withdraw Interest?
  Yes

Page link is just inactive as if it isn't a hyperlink (yet it is).