问:
why I'm getting a error "withScriptjs is not exported from 'react-google-maps" in react js while using google map api?
I'm working on a specific project, where I asked user to a pick location using a movable marker in google map.
I tested this code from stackoverflow which is given on the first answer here and demolink and paste it in my computer but im getting this error continuesly.

export 'withScriptjs' (imported as 'withScriptjs') was not found in 'react-google-maps' (possible exports: Circle, DirectionsRenderer, FusionTablesLayer, GoogleMap, InfoWindow, KmlLayer, Marker, OverlayView, Polygon, Polyline, Rectangle, StreetViewPanorama, TrafficLayer, __esModule, withGoogleMap)

MyParentComponentWrapper.js code:-

import React from "react";
import { compose, withProps, lifecycle } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from "react-google-maps";

const MyMapComponent = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=AIzaSyAWKZtBo8JUsVdNUCAl5EZ2Rg4rstzPjlw=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  lifecycle({
    componentWillMount() {
      const refs = {};

      this.setState({
        position: null,
        onMarkerMounted: (ref) => {
          refs.marker = ref;
        },

        onPositionChanged: () => {
          const position = refs.marker.getPosition();
          console.log(position.toString());
        },
      });
    },
  }),
  withScriptjs,
  withGoogleMap
)((props) => (
  <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
    {props.isMarkerShown && (
      <Marker
        position={{ lat: -34.397, lng: 150.644 }}
        draggable={true}
        ref={props.onMarkerMounted}
        onPositionChanged={props.onPositionChanged}
      />
    )}
  </GoogleMap>
));

class MyParentComponentWrapper extends React.PureComponent {
  state = {
    isMarkerShown: false,
  };

  render() {
    return (

        <MyMapComponent isMarkerShown={true} />

    );
  }
}

export default MyParentComponentWrapper;
```
<p>App.js code:-</p>
<pre class="lang-jsx prettyprint-override"><code>// import logo from './logo.svg';
import "./App.css";
import MyParentComponentWrapper from "./MyParentComponentWrapper";

function App() {
  return (
    <>
      <MyParentComponentWrapper />
    </>
  );
}

export default App;
</code>```

index.js code:-

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>

    You need to enable JavaScript to run this app.

```
<p>package json</p>
```{
  "name": "map",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@react-google-maps/api": "^2.17.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
```

i just started learning react js and cannot figure out why im getting this error.

Body:
I'm working on a specific project, where I asked user to a pick location using a movable marker in google map.
I tested this code from stackoverflow which is given on the first answer here and demolink and paste it in my computer but im getting this error continuesly.

export 'withScriptjs' (imported as 'withScriptjs') was not found in 'react-google-maps' (possible exports: Circle, DirectionsRenderer, FusionTablesLayer, GoogleMap, InfoWindow, KmlLayer, Marker, OverlayView, Polygon, Polyline, Rectangle, StreetViewPanorama, TrafficLayer, __esModule, withGoogleMap)

MyParentComponentWrapper.js code:-

import React from "react";
import { compose, withProps, lifecycle } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from "react-google-maps";

const MyMapComponent = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=AIzaSyAWKZtBo8JUsVdNUCAl5EZ2Rg4rstzPjlw=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  lifecycle({
    componentWillMount() {
      const refs = {};

      this.setState({
        position: null,
        onMarkerMounted: (ref) => {
          refs.marker = ref;
        },

        onPositionChanged: () => {
          const position = refs.marker.getPosition();
          console.log(position.toString());
        },
      });
    },
  }),
  withScriptjs,
  withGoogleMap
)((props) => (
  <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
    {props.isMarkerShown && (
      <Marker
        position={{ lat: -34.397, lng: 150.644 }}
        draggable={true}
        ref={props.onMarkerMounted}
        onPositionChanged={props.onPositionChanged}
      />
    )}
  </GoogleMap>
));

class MyParentComponentWrapper extends React.PureComponent {
  state = {
    isMarkerShown: false,
  };

  render() {
    return (

        <MyMapComponent isMarkerShown={true} />

    );
  }
}

export default MyParentComponentWrapper;

App.js code:-

// import logo from './logo.svg';
import "./App.css";
import MyParentComponentWrapper from "./MyParentComponentWrapper";

function App() {
  return (
    <>
      <MyParentComponentWrapper />
    </>
  );
}

export default App;

index.js code:-

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>

    You need to enable JavaScript to run this app.

package json

{
  "name": "map",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@react-google-maps/api": "^2.17.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

i just started learning react js and cannot figure out why im getting this error.


来源: stackexchange

问:
Plot in excel with dates that do not overlap
I have two data series with dates that do not overlap. How do I plot them separately using different colours under the same graph and date axis?
Thanks

ContentLicense: CC BY-SA 4.0


问:
Shiny for Python: Button Kwargs?

Where is a documented list of kwargs I can pass to buttons (download, inputs, etc.) in Python shiny?

That's really all I need to get my first shiny app where I want it to be.

A "What's the Magic Words?" Situation

My app's workflow looks something like...

a user uploads a file

the user commands the app to do some work

the app enables a button for to download the results

I would like to do things like use icons for buttons and disable the download button until after the user commanded the app to do work. The issue is that I cannot figure out what the kwargs are (or if they are in the correct form: a dict, list of tuples, etc.)

What I Have Tried

From the documentation and this useful tutorial, I have gathered that I can use ui.update_select() to toggle the button's state, but I just don't know (and can't find) the magical keyword! The kwargs for the buttons do not show up in the documentation.

Normally I would resort to finding an example, but only the pure R Shiny shows up. Their attributes don't seem to work as kwargs in Python Shiny or I am phrasing these wrong. (A dict seems to make the most sense here...)

Title: Shiny for Python: Button Kwargs?


问:
How to improve sequential promises execution and force fulfillment
This code is being used in a Sveltekit web application.

In the first step I get a user jwt token from an api like : dashboard.example.com/auth/local

and in the second step I'm using the response of the first api call to get full information from an api endpoint like this : example.com/api/users/token

This is an endpoint in an Sveltekit application:

```<code>import { json as json$1, error } from '@sveltejs/kit';
import axios from 'axios';
import md5 from 'md5';
import { SITE_ADDRESS } from '$lib/Env';
let userToken;

/** @type {import('@sveltejs/kit').RequestHandler} */
export async function POST({ request }) {
    const bodyData = await request.json();
    let identifier = bodyData.data.identifier;
    let password = bodyData.data.password;
    let loginToken = bodyData.data.loginToken;

    let newLoginToken = md5(identifier + password + process.env.SECURE_HASH_TOKEN);

    let dataResult = await axios
        .post(`${import.meta.env.VITE_SITE_API}/auth/local`, {
            identifier: identifier,
            password: password
        })
        .then((response) => {
            return response.data;
        })
        .then((response) => {
            let userSummaryData = response;

            userToken = md5(
                userSummaryData.user.username + userSummaryData.user.id + process.env.SECURE_HASH_TOKEN
            );

            let userCompleteData = axios
                .post(`${SITE_ADDRESS}/api/users/${userToken}`, {
                    data: {
                        userID: userSummaryData.user.id,
                        username: userSummaryData.user.username
                    }
                })
                .then((response) => {
                    return {
                        userJWT: userSummaryData.jwt,
                        userSummary: userSummaryData.user,
                        userFullSummary: response.data.userFullSummary
                    };
                });
            return userCompleteData;
        })
        .catch((error) => {
            // console.log(' ---- Err ----');
        });

    if (dataResult && newLoginToken == loginToken) {
        return json$1(
            {
                userJWT: dataResult.userJWT,
                userSummary: dataResult.userSummary,
                userFullSummary: dataResult.userFullSummary
            },
            {
                headers: {
                    'cache-control': 'private, max-age=0, no-store'
                }
            }
        );
    } else if (dataResult && newLoginToken != loginToken) {
        throw error(400, 'Something wrong happened');
    }
    throw error(401, 'Something wrong happened');
}

</code>```

This code is work perfectly in localhost. But when I test it on host I get error 401.

and the question is :

Why this works on localhost but doesn't work on the server?

How can I improve this kind of promises (I'd like to use the response of the first api call in the second api call and return both
as a result)

Body:
This code is being used in a Sveltekit web application.

In the first step I get a user jwt token from an api like : dashboard.example.com/auth/local

and in the second step I'm using the response of the first api call to get full information from an api endpoint like this : example.com/api/users/token

This is an endpoint in an Sveltekit application:

import { json as json$1, error } from '@sveltejs/kit';
import axios from 'axios';
import md5 from 'md5';
import { SITE_ADDRESS } from '$lib/Env';
let userToken;

/** @type {import('@sveltejs/kit').RequestHandler} */
export async function POST({ request }) {
    const bodyData = await request.json();
    let identifier = bodyData.data.identifier;
    let password = bodyData.data.password;
    let loginToken = bodyData.data.loginToken;

    let newLoginToken = md5(identifier + password + process.env.SECURE_HASH_TOKEN);

    let dataResult = await axios
        .post(`${import.meta.env.VITE_SITE_API}/auth/local`, {
            identifier: identifier,
            password: password
        })
        .then((response) => {
            return response.data;
        })
        .then((response) => {
            let userSummaryData = response;

            userToken = md5(
                userSummaryData.user.username + userSummaryData.user.id + process.env.SECURE_HASH_TOKEN
            );

            let userCompleteData = axios
                .post(`${SITE_ADDRESS}/api/users/${userToken}`, {
                    data: {
                        userID: userSummaryData.user.id,
                        username: userSummaryData.user.username
                    }
                })
                .then((response) => {
                    return {
                        userJWT: userSummaryData.jwt,
                        userSummary: userSummaryData.user,
                        userFullSummary: response.data.userFullSummary
                    };
                });
            return userCompleteData;
        })
        .catch((error) => {
            // console.log(' ---- Err ----');
        });

    if (dataResult && newLoginToken == loginToken) {
        return json$1(
            {
                userJWT: dataResult.userJWT,
                userSummary: dataResult.userSummary,
                userFullSummary: dataResult.userFullSummary
            },
            {
                headers: {
                    'cache-control': 'private, max-age=0, no-store'
                }
            }
        );
    } else if (dataResult && newLoginToken != loginToken) {
        throw error(400, 'Something wrong happened');
    }
    throw error(401, 'Something wrong happened');
}

This code is work perfectly in localhost. But when I test it on host I get error 401.

and the question is :

Why this works on localhost but doesn't work on the server?

How can I improve this kind of promises (I'd like to use the response of the first api call in the second api call and return both
as a result)


问:
CLARANS pyclustering implementation - is there a mistake in the code?
I know my question is a bit weird but I am trying to implement my own version of CLARANS algorithm for sake of learning. To understand it better, I tried to get through the CLARANS code of pyclustering library (which is outdated but still seems popular and I've seen it used in some places). Here it is:
https://github.com/annoviko/pyclustering/blob/master/pyclustering/cluster/clarans.py

I understood everything (or thought so), until the line 210, so just before the cost calculation takes place.

```<code>distance_nearest = float('inf')
if ( (point_medoid_index != candidate_medoid_index) and (point_medoid_index != current_medoid_cluster_index) ):
    distance_nearest = euclidean_distance_square(self.__pointer_data[point_index], self.__pointer_data[point_medoid_index])
</code>```

Is there a bug inside the library? Let's say we have 1000 data points and 3 clusters (so 3 medoids of course).
Why would we say the distance_nearest = float('inf') for any of the points (especially since we're adding the distance_nearest later in the code)? And what is more, why would we compare the index of analyzed point's medoid (so could be equal to 400) to the current_medoid_cluster_index (which could only take values from 0 to 2)? What's the point of that?

I'm sorry if it's a bit chaotic, but I'm honestly looking for someone either interested in going through the code or someone who understands the code already - I am willing to elaborate further if needed.

If someone understands it and knows there is no bug, could you please explain the cost calculation part?

Body:
I know my question is a bit weird but I am trying to implement my own version of CLARANS algorithm for sake of learning. To understand it better, I tried to get through the CLARANS code of pyclustering library (which is outdated but still seems popular and I've seen it used in some places). Here it is:
https://github.com/annoviko/pyclustering/blob/master/pyclustering/cluster/clarans.py

I understood everything (or thought so), until the line 210, so just before the cost calculation takes place.

distance_nearest = float('inf')
if ( (point_medoid_index != candidate_medoid_index) and (point_medoid_index != current_medoid_cluster_index) ):
    distance_nearest = euclidean_distance_square(self.__pointer_data[point_index], self.__pointer_data[point_medoid_index])

Is there a bug inside the library? Let's say we have 1000 data points and 3 clusters (so 3 medoids of course).
Why would we say the distance_nearest = float('inf') for any of the points (especially since we're adding the distance_nearest later in the code)? And what is more, why would we compare the index of analyzed point's medoid (so could be equal to 400) to the current_medoid_cluster_index (which could only take values from 0 to 2)? What's the point of that?

I'm sorry if it's a bit chaotic, but I'm honestly looking for someone either interested in going through the code or someone who understands the code already - I am willing to elaborate further if needed.

If someone understands it and knows there is no bug, could you please explain the cost calculation part?


问:
Configuring both http basic and Form based authentication in latest Spring security 6.0
I'm trying to configure REST and Form based authentication in new Spring boot and spring secuirty latest. I went through following post Combining basic authentication and form login for the same REST Api and new spring configuration using SecurityFilterChain and created the following. As I learnt that WebSecurityConfigurerAdapter method in the above post is deprecated.

```<code>@Configuration
@Order(2)
@EnableWebSecurity
public class RESTBasedConfigurationAdapter {

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Bean
    public BCryptPasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http.antMatcher("/api/**")
                .authorizeRequests().anyRequest().hasAnyRole(...)
                .and().httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint());
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        return http.build();
    }

}
</code>```

and

```<code>@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableWebSecurity
public class FormBasedConfigurationAdapter {

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers(...)
                .permitAll().anyRequest().authenticated()
                .and().formLogin().loginPage("/login").successHandler(authenticationSuccessHandler)
                .permitAll().and().logout().permitAll();

        return http.build();
    }
</code>```

}

But the configure method FormBasedConfigurationAdapter's is never called. Please explain how to configure so that both http Basic and Form based Authentication can be done.

As far I under I want two flows.

One flow REST which uses the following AuthenticationProvider for logging STATELESS

```<code>@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    @Lazy
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        String userName = authentication.getName();
        String password = authentication.getCredentials().toString();
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        if (passwordEncoder.matches(password, userDetails.getPassword())) {
            return new UsernamePasswordAuthenticationToken(userName, password, userDetails.getAuthorities());
        } else {
            throw new BadCredentialsException(" Bad Credentials ");
        }
    }

    @Override
    public boolean supports(Class<?> authenticationType) {
        return authenticationType.equals(UsernamePasswordAuthenticationToken.class);
    }
}
</code>```

and for other FormBased authentication, I would like to go through controller as below.

```<code>@PostMapping("/login")
    public String login(@ModelAttribute("loginForm") LoginForm loginForm,
                        BindingResult bindingResult,
                        Model model) {
        loginValidator.validate(loginForm, bindingResult);
        securityService.login(loginForm.getUserName(), loginForm.getPasswd());
        if (bindingResult.hasErrors()) {
            return "login";
        }
        return "...";
    }
</code>```

to facilitate Validation for Authenticate using Service as below.

```<code>@Override
    public void login(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
        if (passwordEncoder.matches(password, userDetails.getPassword())) {
            if (usernamePasswordAuthenticationToken.isAuthenticated()) {
                SecurityContextHolder.getContext()
                        .setAuthentication(usernamePasswordAuthenticationToken);
                logger.debug(String.format("Auto login %s successfully!", username));
            }

        } else {
            throw new BadCredentialsException(" Bad Credentials ");
        }

    }
</code>```

Please explain how to achieve this. I also tried doing both HttpSecurity mapping in the same class but it is not working due to various reasons.

Body:
I'm trying to configure REST and Form based authentication in new Spring boot and spring secuirty latest. I went through following post Combining basic authentication and form login for the same REST Api and new spring configuration using SecurityFilterChain and created the following. As I learnt that WebSecurityConfigurerAdapter method in the above post is deprecated.

@Configuration
@Order(2)
@EnableWebSecurity
public class RESTBasedConfigurationAdapter {

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Bean
    public BCryptPasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http.antMatcher("/api/**")
                .authorizeRequests().anyRequest().hasAnyRole(...)
                .and().httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint());
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        return http.build();
    }

}

and

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableWebSecurity
public class FormBasedConfigurationAdapter {

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers(...)
                .permitAll().anyRequest().authenticated()
                .and().formLogin().loginPage("/login").successHandler(authenticationSuccessHandler)
                .permitAll().and().logout().permitAll();

        return http.build();
    }

}

But the configure method FormBasedConfigurationAdapter's is never called. Please explain how to configure so that both http Basic and Form based Authentication can be done.

As far I under I want two flows.

One flow REST which uses the following AuthenticationProvider for logging STATELESS

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    @Lazy
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        String userName = authentication.getName();
        String password = authentication.getCredentials().toString();
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        if (passwordEncoder.matches(password, userDetails.getPassword())) {
            return new UsernamePasswordAuthenticationToken(userName, password, userDetails.getAuthorities());
        } else {
            throw new BadCredentialsException(" Bad Credentials ");
        }
    }

    @Override
    public boolean supports(Class<?> authenticationType) {
        return authenticationType.equals(UsernamePasswordAuthenticationToken.class);
    }
}

and for other FormBased authentication, I would like to go through controller as below.

@PostMapping("/login")
    public String login(@ModelAttribute("loginForm") LoginForm loginForm,
                        BindingResult bindingResult,
                        Model model) {
        loginValidator.validate(loginForm, bindingResult);
        securityService.login(loginForm.getUserName(), loginForm.getPasswd());
        if (bindingResult.hasErrors()) {
            return "login";
        }
        return "...";
    }

to facilitate Validation for Authenticate using Service as below.

@Override
    public void login(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
        if (passwordEncoder.matches(password, userDetails.getPassword())) {
            if (usernamePasswordAuthenticationToken.isAuthenticated()) {
                SecurityContextHolder.getContext()
                        .setAuthentication(usernamePasswordAuthenticationToken);
                logger.debug(String.format("Auto login %s successfully!", username));
            }

        } else {
            throw new BadCredentialsException(" Bad Credentials ");
        }

    }

Please explain how to achieve this. I also tried doing both HttpSecurity mapping in the same class but it is not working due to various reasons.


问:
Modify drop down value with preset value
I'm designing a form that can both used to create and edit something.

The form has a dropdown, which isn't initialized when created, but is set with a value when used for editing.

I want to be able to modify the value of the drop down, both for creating & updating, yet is only working when the mode is CREATE.

Here's my template:

```<code><template>
    <v-row justify="center">
        <v-form ref="form" v-model="valid" lazy-validation>
            <v-text-field v-model="title" label="Title*" :rules="rules.fieldRules" prepend-icon="mdi-text">
            </v-text-field>
            <v-text-field v-model="website_link" label="URL" prepend-icon="mdi-web">
            </v-text-field>
            <h3>Description</h3>
            <text-editor @update:modelValue="getValue" :rules="rules.fieldRules" :modelValue="description">
            </text-editor>
            <br />
            <v-select v-model="selectedState" :readonly="false" :items="items" filled label="Which state?*" prepend-icon="mdi-help"></v-select>
            <v-file-input v-model="files" prepend-icon="mdi-camera" multiple label="File input"></v-file-input>
            <v-layout v-for="file of files" :key="file">
                <v-img :src="generateUrl(file)" max-width="10%" max-height="10%">
                </v-img>
            </v-layout>
            <v-combobox v-model="tags" prepend-icon="mdi-lightbulb" label="Tags" chips clearable multiple filled
                rounded></v-combobox>
            <v-btn :disabled="mode == 'EDIT' ? false : !valid" color="success" class="mr-4" @click="validate">
                Validate
            </v-btn>
            <v-btn color="blue" class="mr-4" @click="backToProfile">
                Back
            </v-btn>
        </v-form>
    </v-row>
</template>
</code>```

selectedState is a computed method described as below here:

selectedState: {
            get() {
                if (this.mode == 'CREATE') {
                    return this.state
                } else {
                    const state = this.items.filter((item) => item.value = this.currentConcept.state)[0].title;
                    this.setState(state);
                    return this.state;
                }
            },
            set(value) {
                console.log(`value: ${value}`)
                this.state = value;
            }
        }
```

Am I missing something?

TIA

Body:
I'm designing a form that can both used to create and edit something.

The form has a dropdown, which isn't initialized when created, but is set with a value when used for editing.

I want to be able to modify the value of the drop down, both for creating & updating, yet is only working when the mode is CREATE.

Here's my template:

<template>
    <v-row justify="center">
        <v-form ref="form" v-model="valid" lazy-validation>
            <v-text-field v-model="title" label="Title*" :rules="rules.fieldRules" prepend-icon="mdi-text">
            </v-text-field>
            <v-text-field v-model="website_link" label="URL" prepend-icon="mdi-web">
            </v-text-field>

Description

            <text-editor @update:modelValue="getValue" :rules="rules.fieldRules" :modelValue="description">
            </text-editor>

            <v-select v-model="selectedState" :readonly="false" :items="items" filled label="Which state?*" prepend-icon="mdi-help"></v-select>
            <v-file-input v-model="files" prepend-icon="mdi-camera" multiple label="File input"></v-file-input>
            <v-layout v-for="file of files" :key="file">
                <v-img :src="generateUrl(file)" max-width="10%" max-height="10%">
                </v-img>
            </v-layout>
            <v-combobox v-model="tags" prepend-icon="mdi-lightbulb" label="Tags" chips clearable multiple filled
                rounded></v-combobox>
            <v-btn :disabled="mode == 'EDIT' ? false : !valid" color="success" class="mr-4" @click="validate">
                Validate
            </v-btn>
            <v-btn color="blue" class="mr-4" @click="backToProfile">
                Back
            </v-btn>
        </v-form>
    </v-row>
</template>

selectedState is a computed method described as below here:

selectedState: {
            get() {
                if (this.mode == 'CREATE') {
                    return this.state
                } else {
                    const state = this.items.filter((item) => item.value = this.currentConcept.state)[0].title;
                    this.setState(state);
                    return this.state;
                }
            },
            set(value) {
                console.log(`value: ${value}`)
                this.state = value;
            }
        }

Am I missing something?

TIA


问:
Internet Explorer unsupported get request
I got a big problem in IE (only IE, FF etc works great).

I got a canvas page: xyz.de/gewinnspiel.php?register=1.
In IE I get the following error:

FacebookApiException: Unsupported get request. in Facebook->_graph()

Does anybody have an idea?

IE8

```<code>$facebook = new Facebook(array(
    'appId' => $app_id,
    'secret' => $app_secret,
    'cookie' => true
    ));

$loginuser = $facebook->getUser();

$userInfo           = $facebook->api("/$loginuser");
</code>```

the $userInfo triggers the error...

ContentLicense: CC BY-SA 3.0

Body:
I got a big problem in IE (only IE, FF etc works great).

I got a canvas page: xyz.de/gewinnspiel.php?register=1.
In IE I get the following error:

FacebookApiException: Unsupported get request. in Facebook->_graph()

Does anybody have an idea?

IE8

$facebook = new Facebook(array(
    'appId' => $app_id,
    'secret' => $app_secret,
    'cookie' => true
    ));

$loginuser = $facebook->getUser();

$userInfo           = $facebook->api("/$loginuser");

the $userInfo triggers the error...


问:
Django Rest Framework no read multiple records
I have tried everything on the blogs. I even consume the service with postman and multiple records are not inserted. Can you help me understand what is happening? There are no errors thrown by the code. Only one record is inserted.

My code in DJANGO

```<code>class ProviderListSerializer(serializers.ListSerializer):
    def do_stuff(data):
        return data

    def create(self, validated_data):
        some_data = self.do_stuff()
        return Provider.objects.bulk_create(some_data, ignore_conflicts=True)
class ProviderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Provider
        fields = '__all__'
        list_serializer_class = ProviderListSerializer

class ProviderViewSet(viewsets.ModelViewSet):
    queryset = Provider.objects.all()
    serializer_class = ProviderSerializer

    def create(self, request, *args, **kwargs):
        many = isinstance(request.data, list)
        serializer = self.get_serializer(data=request.data, many=many)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, headers=headers)
</code>```

My code in POSTMAN:

```<code>curl --location --request POST 'http://127.0.0.1:8000/api-auth/providers/' \
--header 'Authorization: Basic YRtaW46SklFTTkzMDYMQ==' \
--form 'name="Proveedor09"' \
--form 'representante="Proveedor09"' \
--form 'alias="Proveedor09"' \
--form 'ruc="isuioasuio92"' \
--form 'mobile="48489948"' \
--form 'address="shds"' \
--form 'telefono="45546546654"' \
--form 'email="Proveedor09@mail.com"' \
--form 'activo="true"' \
--form 'name="Proveedor091"' \
--form 'representante="Proveedor091"' \
--form 'alias="Proveedor091"' \
--form 'ruc="isuioasuio921"' \
--form 'mobile="48489948"' \
--form 'address="shds"' \
--form 'telefono="45546546654"' \
--form 'email="Proveedor109@mail.com"' \
--form 'activo="true"'
</code>```

I just expect to insert multiple records. As I said, I've tried everything I've seen on the web. Maybe I'm sending the form-data wrong, but I see that in many cases, they send the data just like me.

Body:
I have tried everything on the blogs. I even consume the service with postman and multiple records are not inserted. Can you help me understand what is happening? There are no errors thrown by the code. Only one record is inserted.

My code in DJANGO

class ProviderListSerializer(serializers.ListSerializer):
    def do_stuff(data):
        return data

    def create(self, validated_data):
        some_data = self.do_stuff()
        return Provider.objects.bulk_create(some_data, ignore_conflicts=True)
class ProviderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Provider
        fields = '__all__'
        list_serializer_class = ProviderListSerializer

class ProviderViewSet(viewsets.ModelViewSet):
    queryset = Provider.objects.all()
    serializer_class = ProviderSerializer

    def create(self, request, *args, **kwargs):
        many = isinstance(request.data, list)
        serializer = self.get_serializer(data=request.data, many=many)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, headers=headers)

My code in POSTMAN:

curl --location --request POST 'http://127.0.0.1:8000/api-auth/providers/' \
--header 'Authorization: Basic YRtaW46SklFTTkzMDYMQ==' \
--form 'name="Proveedor09"' \
--form 'representante="Proveedor09"' \
--form 'alias="Proveedor09"' \
--form 'ruc="isuioasuio92"' \
--form 'mobile="48489948"' \
--form 'address="shds"' \
--form 'telefono="45546546654"' \
--form 'email="Proveedor09@mail.com"' \
--form 'activo="true"' \
--form 'name="Proveedor091"' \
--form 'representante="Proveedor091"' \
--form 'alias="Proveedor091"' \
--form 'ruc="isuioasuio921"' \
--form 'mobile="48489948"' \
--form 'address="shds"' \
--form 'telefono="45546546654"' \
--form 'email="Proveedor109@mail.com"' \
--form 'activo="true"'

I just expect to insert multiple records. As I said, I've tried everything I've seen on the web. Maybe I'm sending the form-data wrong, but I see that in many cases, they send the data just like me.


问:
Microsoft Signin to Nuget
I am trying to signin to Nuget.
The only signin option appears to be with Microsoft.
However, after authenticating me it says "unable to save" and I cant go any further.
I have tried using the phone and sms options and they both authenticate positively.
Screenshot of page after I have authorised.

Is microsoft signin broken ?

Title: Microsoft Signin to Nuget


问:
Make SQLAlchemy "or_" operator return only the 1st match
guys! I have this one query, written with SQLAlchemy:

```<code>query = query.filter(
    CollectionCardLink.collection_id == card_id,
    CollectionCardLink.position.in_([0, count-1]),
    or_(CardStyle.user_id == referrer_id, CardStyle.user_id == ANYONE_USER_ID)
).all()
</code>```

My issue is: this => or_(PostStyle.user_id == current_user_id, PostStyle.user_id == DEFAULT_USER_ID) returns me two records, cause there are records for current_user_id and for DEFAULT_USER_ID in table too.
But I want or_ to work like it works in Python: stop checking after 1st True. So, I need to get PostStyle for DEFAULT_USER_ID only if there's no PostStyle for current_user_id.
Can someone help, please, with that issue?

Also I tried to code: (PostStyle.user_id == current_user_id or PostStyle.user_id == DEFAULT_USER_ID) but it gives me a record for DEFAULT_USER_ID firstly and that's incorrect

Body:
guys! I have this one query, written with SQLAlchemy:

query = query.filter(
    CollectionCardLink.collection_id == card_id,
    CollectionCardLink.position.in_([0, count-1]),
    or_(CardStyle.user_id == referrer_id, CardStyle.user_id == ANYONE_USER_ID)
).all()

My issue is: this => or_(PostStyle.user_id == current_user_id, PostStyle.user_id == DEFAULT_USER_ID) returns me two records, cause there are records for current_user_id and for DEFAULT_USER_ID in table too.
But I want or_ to work like it works in Python: stop checking after 1st True. So, I need to get PostStyle for DEFAULT_USER_ID only if there's no PostStyle for current_user_id.
Can someone help, please, with that issue?

Also I tried to code: (PostStyle.user_id == current_user_id or PostStyle.user_id == DEFAULT_USER_ID) but it gives me a record for DEFAULT_USER_ID firstly and that's incorrect


问:
aws-ec2 OVA to AMI import-image error: ClientError: Unable to find an etc directory with fstab
My goal is to convert an OVA into AMI for deploying EC2 instances with. The OVA is a standard SLES 12, SP5 image with proprietary software installed on it. SLES 12 is supported for EC2 Image import: https://docs.aws.amazon.com/vm-import/latest/userguide/prerequisites.html

The OVA is uploaded to S3 bucket. I have closely followed this very well documented wiki on VM Imports on AWS: https://docs.aws.amazon.com/vm-import/latest/userguide/vmimport-image-import.html, which works great, until the conversion fails (error below).

Image import begins:

```<code>MAC-LT: ~/aws $ aws ec2 import-image --description "SLES 12 OVA" --disk-containers file://containers.json --region us-east-2
{
    "Description": "SLES 12 OVA",
    "ImportTaskId": "import-ami-<redacted>",
    "Progress": "1",
    "SnapshotDetails": [
        {
            "Description": "SLES 12 OVA",
            "DiskImageSize": 0.0,
            "Format": "OVA",
            "UserBucket": {
                "S3Bucket": "<redacted>",
                "S3Key": "<redacted>.ova"
            }
        }
    ],
    "Status": "active",
    "StatusMessage": "pending"
}
</code>```

Conversion starts:

```<code>MAC-LT: ~/aws $ aws ec2 describe-import-image-tasks --import-task-ids import-ami-<redacted> --region <redacted>
{
    "ImportImageTasks": [
        {
            "Description": "SLES 12 OVA",
            "ImportTaskId": "import-ami-<redacted>",
            "Progress": "19",
            "SnapshotDetails": [
                {
                    "DiskImageSize": 5130945536.0,
                    "Format": "VMDK",
                    "Status": "active",
                    "UserBucket": {
                        "S3Bucket": "<redacted>",
                        "S3Key": "<redacted>.ova"
                    }
                }
            ],
            "Status": "active",
            "StatusMessage": "converting",
            "Tags": []
        }
    ]
}
</code>```

But eventually fails after ~30mins with:

```<code>MAC-LT: ~/aws $ aws ec2 describe-import-image-tasks --import-task-ids import-ami-<redacted> --region <redacted>
{
    "ImportImageTasks": [
        {
            "Description": "SLES 12 OVA",
            "ImportTaskId": "import-ami-<redacted>",
            "SnapshotDetails": [
                {
                    "DeviceName": "/dev/sde",
                    "DiskImageSize": 5130945536.0,
                    "Format": "VMDK",
                    "Status": "completed",
                    "UserBucket": {
                        "S3Bucket": "<redacted>",
                        "S3Key": "<redacted>.ova"
                    }
                }
            ],
            "Status": "deleted",
            "StatusMessage": "ClientError: Unable to find an etc directory with fstab.",
            "Tags": []
        }
    ]
}
</code>```

Has anyone seen this? Are there any customizations to the OVA that are required to make this work?

Body:
My goal is to convert an OVA into AMI for deploying EC2 instances with. The OVA is a standard SLES 12, SP5 image with proprietary software installed on it. SLES 12 is supported for EC2 Image import: https://docs.aws.amazon.com/vm-import/latest/userguide/prerequisites.html

The OVA is uploaded to S3 bucket. I have closely followed this very well documented wiki on VM Imports on AWS: https://docs.aws.amazon.com/vm-import/latest/userguide/vmimport-image-import.html, which works great, until the conversion fails (error below).

Image import begins:

MAC-LT: ~/aws $ aws ec2 import-image --description "SLES 12 OVA" --disk-containers file://containers.json --region us-east-2
{
    "Description": "SLES 12 OVA",
    "ImportTaskId": "import-ami-<redacted>",
    "Progress": "1",
    "SnapshotDetails": [
        {
            "Description": "SLES 12 OVA",
            "DiskImageSize": 0.0,
            "Format": "OVA",
            "UserBucket": {
                "S3Bucket": "<redacted>",
                "S3Key": "<redacted>.ova"
            }
        }
    ],
    "Status": "active",
    "StatusMessage": "pending"
}

Conversion starts:

MAC-LT: ~/aws $ aws ec2 describe-import-image-tasks --import-task-ids import-ami-<redacted> --region <redacted>
{
    "ImportImageTasks": [
        {
            "Description": "SLES 12 OVA",
            "ImportTaskId": "import-ami-<redacted>",
            "Progress": "19",
            "SnapshotDetails": [
                {
                    "DiskImageSize": 5130945536.0,
                    "Format": "VMDK",
                    "Status": "active",
                    "UserBucket": {
                        "S3Bucket": "<redacted>",
                        "S3Key": "<redacted>.ova"
                    }
                }
            ],
            "Status": "active",
            "StatusMessage": "converting",
            "Tags": []
        }
    ]
}

But eventually fails after ~30mins with:

MAC-LT: ~/aws $ aws ec2 describe-import-image-tasks --import-task-ids import-ami-<redacted> --region <redacted>
{
    "ImportImageTasks": [
        {
            "Description": "SLES 12 OVA",
            "ImportTaskId": "import-ami-<redacted>",
            "SnapshotDetails": [
                {
                    "DeviceName": "/dev/sde",
                    "DiskImageSize": 5130945536.0,
                    "Format": "VMDK",
                    "Status": "completed",
                    "UserBucket": {
                        "S3Bucket": "<redacted>",
                        "S3Key": "<redacted>.ova"
                    }
                }
            ],
            "Status": "deleted",
            "StatusMessage": "ClientError: Unable to find an etc directory with fstab.",
            "Tags": []
        }
    ]
}

Has anyone seen this? Are there any customizations to the OVA that are required to make this work?


问:
Android - How to catch when another app shares data to my app?
I have an app that accepts shared data from other apps.

So in my onCreate(...) function, I have

```<code>intent.extras?.getString("android.intent.extra.TEXT")?.let{query -> someCallback(query)}
</code>```

This works fine if my app has not been started yet.  However, I also want to call someCallback when data is shared after my Activity has already been created?  How do I hook into the event of receiving shared data from another app?

Body:
I have an app that accepts shared data from other apps.

So in my onCreate(...) function, I have

intent.extras?.getString("android.intent.extra.TEXT")?.let{query -> someCallback(query)}

This works fine if my app has not been started yet.  However, I also want to call someCallback when data is shared after my Activity has already been created?  How do I hook into the event of receiving shared data from another app?


问:
python queue from multiprocessing is empty
So I'm trying to assign values to a Queue from the module multiprocessing.

My code is:

```<code>from multiprocessing import Queue

fileBlocks = Queue()
filesDic = dict()
cont = 0

def eDiv(files, k):
    global fileBlocks
    listLinesAllWithIdx = []
    index = 0
    bytesCount = 0
    blockLines = []
    blockLinesAll = []
    allBytes = 0
    n = 0
    lineCount = 0
    for file in files:
        with open(file) as f:
            filesDic[file] = index
            for line in f:
                listLinesAllWithIdx.append((index,line, utf8len(line)))
                allBytes += utf8len(line)
        index += 1

    while n < allBytes:
        bytesCount = 0
        blockLines = []
        while bytesCount <= k and lineCount < len(listLinesAllWithIdx):
            blockLines.append(listLinesAllWithIdx[lineCount])
            bytesCount += listLinesAllWithIdx[lineCount][2]
            lineCount += 1
        n += bytesCount
        blockLinesAll.append(blockLines)

    for i in blockLinesAll:
        fileBlocks.put(i)

    print(fileBlocks.empty())

def utf8len(s):
    return len(s.encode('utf-8'))

eDiv(["file1.txt","file2.txt"], 10)
</code>```

I'm expecting fileBlocks.empty() = True but I'm getting False, and I don't understand why this is happening.

Body:
So I'm trying to assign values to a Queue from the module multiprocessing.

My code is:

from multiprocessing import Queue

fileBlocks = Queue()
filesDic = dict()
cont = 0

def eDiv(files, k):
    global fileBlocks
    listLinesAllWithIdx = []
    index = 0
    bytesCount = 0
    blockLines = []
    blockLinesAll = []
    allBytes = 0
    n = 0
    lineCount = 0
    for file in files:
        with open(file) as f:
            filesDic[file] = index
            for line in f:
                listLinesAllWithIdx.append((index,line, utf8len(line)))
                allBytes += utf8len(line)
        index += 1

    while n < allBytes:
        bytesCount = 0
        blockLines = []
        while bytesCount <= k and lineCount < len(listLinesAllWithIdx):
            blockLines.append(listLinesAllWithIdx[lineCount])
            bytesCount += listLinesAllWithIdx[lineCount][2]
            lineCount += 1
        n += bytesCount
        blockLinesAll.append(blockLines)

    for i in blockLinesAll:
        fileBlocks.put(i)

    print(fileBlocks.empty())

def utf8len(s):
    return len(s.encode('utf-8'))

eDiv(["file1.txt","file2.txt"], 10)

I'm expecting fileBlocks.empty() = True but I'm getting False, and I don't understand why this is happening.


问:
What do I have to do to comply with encryption compliance with app that encrypts chat messages?
I am developing a flutter app which encrypts and decripts chat messages held on a server.
I use the following library: https://pub.dev/packages/encrypt
My code is as follows:
`

```<code>import 'package:encrypt/encrypt.dart' as encrypt;

class Environment {
  static const ekey = String.fromEnvironment('ENCRYPT_KEY');
  static const ivkey = String.fromEnvironment('IV_KEY');
}

final key = encrypt.Key.fromBase64(Environment.ekey);
final iv = encrypt.IV.fromBase64(Environment.ivkey);

final encrypter = encrypt.Encrypter(encrypt.AES(key));

String Encrypt(input) {
  final encryptedText = encrypter.encrypt(input, iv: iv);
  return encryptedText.base64;
}
String Decrypt(input){
  final fb64 = encrypt.Encrypted.fromBase64(input);
  final decryptedText = encrypter.decrypt(fb64, iv: iv);
  return decryptedText;
}
</code>```

The app will be held on apple and google stores, and I am planning to allow users in countries outside the US to download the app.

I have looked online but this seems like a minefield.

I would just like to know what I need to do to not fall foul of the law.

Body:
I am developing a flutter app which encrypts and decripts chat messages held on a server.
I use the following library: https://pub.dev/packages/encrypt
My code is as follows:
`

import 'package:encrypt/encrypt.dart' as encrypt;

class Environment {
  static const ekey = String.fromEnvironment('ENCRYPT_KEY');
  static const ivkey = String.fromEnvironment('IV_KEY');
}

final key = encrypt.Key.fromBase64(Environment.ekey);
final iv = encrypt.IV.fromBase64(Environment.ivkey);

final encrypter = encrypt.Encrypter(encrypt.AES(key));

String Encrypt(input) {
  final encryptedText = encrypter.encrypt(input, iv: iv);
  return encryptedText.base64;
}
String Decrypt(input){
  final fb64 = encrypt.Encrypted.fromBase64(input);
  final decryptedText = encrypter.decrypt(fb64, iv: iv);
  return decryptedText;
}

The app will be held on apple and google stores, and I am planning to allow users in countries outside the US to download the app.

I have looked online but this seems like a minefield.

I would just like to know what I need to do to not fall foul of the law.


问:
How to use SQL query in QueryRunner for NestJS?
I want to update an existing column in a table with a value. but I'm not sure how to translate sql to nestjs on the queryRunner. I can't find update examples with this QueryRunner

```<code>import {MigrationInterface, QueryRunner} from "TypeORM";

export class Student12345 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
       await queryRunner.query(`UPDATE "students"("status") SET "Active"`);
   }

   public async down(queryRunner: QueryRunner): Promise<void> {
       await queryRunner.query(`UPDATE COLUMN "status" SET NULL`);
   }
}
</code>```

Can anyone help?

Body:
I want to update an existing column in a table with a value. but I'm not sure how to translate sql to nestjs on the queryRunner. I can't find update examples with this QueryRunner

import {MigrationInterface, QueryRunner} from "TypeORM";

export class Student12345 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
       await queryRunner.query(`UPDATE "students"("status") SET "Active"`);
   }

   public async down(queryRunner: QueryRunner): Promise<void> {
       await queryRunner.query(`UPDATE COLUMN "status" SET NULL`);
   }
}

Can anyone help?


问:
django DenseRank annotation based on another annotate
I want to annotate rank queryset based on avg of points.

annotate(avg=Avg('point'), rank=Window(expression=DenseRank(), order_by=Value("avg").desc())

but rank is 1 for all data.

When I check query straight in database result is true! but in django all rank is 1.

When I use F("avg") instead of Value("avg"), result is true but query is not optimal . With F() in query once calculate average of points for avg and calculate avg again for rank avg:

query 1:

```<code>SELECT AVG(point) AS avg,
    DENSE_RANK() OVER (
        ORDER BY AVG(point) DESC
    ) rank,
</code>```

but I want below query:
query 2:

```<code>SELECT AVG(point) AS avg,
    DENSE_RANK() OVER (
        ORDER BY avg DESC
    ) rank,
</code>```

when I user Value('avg') query 2 generate but all rank is 1 and when I use F('avg'), result is true but query 1 generate which is not optimal and calculate 'avg' twice(twice AVG(point) in query).

Body:
I want to annotate rank queryset based on avg of points.

annotate(avg=Avg('point'), rank=Window(expression=DenseRank(), order_by=Value("avg").desc())

but rank is 1 for all data.

When I check query straight in database result is true! but in django all rank is 1.

When I use F("avg") instead of Value("avg"), result is true but query is not optimal . With F() in query once calculate average of points for avg and calculate avg again for rank avg:

query 1:

SELECT AVG(point) AS avg,
    DENSE_RANK() OVER (
        ORDER BY AVG(point) DESC
    ) rank,

but I want below query:
query 2:

SELECT AVG(point) AS avg,
    DENSE_RANK() OVER (
        ORDER BY avg DESC
    ) rank,

when I user Value('avg') query 2 generate but all rank is 1 and when I use F('avg'), result is true but query 1 generate which is not optimal and calculate 'avg' twice(twice AVG(point) in query).


问:
Objective-C: local notification not showing action buttons
Here is what I added in my iOS app:

```<code>- (void) schedule:(CDVInvokedUrlCommand*)command
{
    NSArray* notifications = command.arguments;

    [self.commandDelegate runInBackground:^{
        for (NSDictionary* options in notifications) {
            APPNotificationContent* notification;

            notification = [[APPNotificationContent alloc]
                            initWithOptions:options];
            notification.title = @"This is title2";
            notification.subtitle = @"This is subtitle";
            notification.body = @"This is body";
            notification.categoryIdentifier = @"demoCategory";
            NSLog(@"categoryIdentifier: %@", notification.categoryIdentifier);
            NSString* found;
            found = [_center hasActionGroup:notification.categoryIdentifier] ? @"yes" : @"no";
            NSLog(@"category existance: %@", found);

            [self scheduleNotification:notification];
        }

        [self check:command];
    }];
}

</code>```

And here is what I received when it was triggered:

```<code>2022-12-09 13:11:12.595804+1300 MyApp[71182:11636137] NotificationCenter Handle push from foreground
2022-12-09 13:11:12.595994+1300 MyApp[71182:11636137] Notification received
2022-12-09 13:11:12.596147+1300 MyApp[71182:11636137] Push Plugin key: alert
2022-12-09 13:11:12.626052+1300 MyApp[71182:11637337] categoryIdentifier: demoCategory
2022-12-09 13:11:12.627402+1300 MyApp[71182:11637337] category existance: yes
</code>```

I added two buttons in that category, but I ended up receiving a notification without any action button.

Is the categoryIdentifier not working? Or should I somehow check if the category is applied correctly?

Body:
Here is what I added in my iOS app:

- (void) schedule:(CDVInvokedUrlCommand*)command
{
    NSArray* notifications = command.arguments;

    [self.commandDelegate runInBackground:^{
        for (NSDictionary* options in notifications) {
            APPNotificationContent* notification;

            notification = [[APPNotificationContent alloc]
                            initWithOptions:options];
            notification.title = @"This is title2";
            notification.subtitle = @"This is subtitle";
            notification.body = @"This is body";
            notification.categoryIdentifier = @"demoCategory";
            NSLog(@"categoryIdentifier: %@", notification.categoryIdentifier);
            NSString* found;
            found = [_center hasActionGroup:notification.categoryIdentifier] ? @"yes" : @"no";
            NSLog(@"category existance: %@", found);

            [self scheduleNotification:notification];
        }

        [self check:command];
    }];
}

And here is what I received when it was triggered:

2022-12-09 13:11:12.595804+1300 MyApp[71182:11636137] NotificationCenter Handle push from foreground
2022-12-09 13:11:12.595994+1300 MyApp[71182:11636137] Notification received
2022-12-09 13:11:12.596147+1300 MyApp[71182:11636137] Push Plugin key: alert
2022-12-09 13:11:12.626052+1300 MyApp[71182:11637337] categoryIdentifier: demoCategory
2022-12-09 13:11:12.627402+1300 MyApp[71182:11637337] category existance: yes

I added two buttons in that category, but I ended up receiving a notification without any action button.

Is the categoryIdentifier not working? Or should I somehow check if the category is applied correctly?


问:
How to include a file for importing objects in aws lambda that is a custom resource for cdk v2?
I am using python 3.8 as the lambda runtime for my lambda function which I am trying to deploy using cdk v2. This is a lambda as a custom resource that runs every time the stack deploys.

This is the folder structure

```<code> /Dynamics/cust_resource/__init__.py
 /Dynamics/cust_resource/data_objects.py
 /Dynamics/cust_resource/lambda.py
 /Dynamics/cust_resource/requirements.txt
 /Dynamics/__init__.py
 /Dynamics/dyna_stack.py
 app.py
</code>```

This is the lambda code

```<code>import os
import boto3
import sys

print('before lambda import')

from data_objects import poco_data
</code>```

This is how I am creating the function in the stack

```<code>cust_res_lambda = _lambda.Function(
    self, 'crLambda',
    runtime=_lambda.Runtime.PYTHON_3_8,
    code=_lambda.Code.from_asset('Dynamics/cust_resource',
                                 bundling=BundlingOptions(
                                        image=_lambda.Runtime.PYTHON_3_8.bundling_image,
                                        command=["bash", "-c", "pip install -r requirements.txt -t /asset-output && cp -au . /asset-output"]
                                     )),
    handler='lambda.lambda_handler',
    function_name='crlambdaFn',

)
</code>```

The lambda executes and I see the line before lambda import in cloudwatch logs followed by.

```<code>[ERROR] RuntimeError: generator didn't stop after throw()
Traceback (most recent call last):
  File "/var/lang/lib/python3.8/imp.py", line 234, in load_module
    return load_source(name, filename, file)
  File "/var/lang/lib/python3.8/imp.py", line 171, in load_source
    module = _load(spec)
  File "<frozen importlib._bootstrap>", line 702, in _load
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 843, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/var/task/lambda.py", line 12, in <module>
    from data_objects import poco_data
  File "/var/task/data_objects.py", line 1, in <module>
    from aws_cdk import (
  File "/var/task/aws_cdk/__init__.py", line 1257, in <module>
    from ._jsii import *
  File "/var/task/aws_cdk/_jsii/__init__.py", line 13, in <module>
    import constructs._jsii
  File "/var/task/constructs/__init__.py", line 43, in <module>
    from ._jsii import *
  File "/var/task/constructs/_jsii/__init__.py", line 13, in <module>
    __jsii_assembly__ = jsii.JSIIAssembly.load(
  File "/var/task/jsii/_runtime.py", line 54, in load
    _kernel.load(assembly.name, assembly.version, os.fspath(assembly_path))
  File "/var/lang/lib/python3.8/contextlib.py", line 162, in __exit__
    raise RuntimeError("generator didn't stop after throw()")
[ERROR] RuntimeError: generator didn't stop after throw() Traceback (most recent call last):   File "/var/lang/lib/python3.8/imp.py", line 234, in load_module     return load_source(name, filename, file)   File "/var/lang/lib/python3.8/imp.py", line 171, in load_source     module = _load(spec)   File "<frozen importlib._bootstrap>", line 702, in _load   File "<frozen importlib._bootstrap>", line 671, in _load_unlocked   File "<frozen importlib._bootstrap_external>", line 843, in exec_module   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed   File "/var/task/lambda.py", line 12, in <module>     from data_objects import poco_data   File "/var/task/data_objects.py", line 1, in <module>     from aws_cdk import (   File "/var/task/aws_cdk/__init__.py", line 1257, in <module>     from ._jsii import *   File "/var/task/aws_cdk/_jsii/__init__.py", line 13, in <module>     import constructs._jsii   File "/var/task/constructs/__init__.py", line 43, in <module>     from ._jsii import *   File "/var/task/constructs/_jsii/__init__.py", line 13, in <module>     __jsii_assembly__ = jsii.JSIIAssembly.load(   File "/var/task/jsii/_runtime.py", line 54, in load     _kernel.load(assembly.name, assembly.version, os.fspath(assembly_path))   File "/var/lang/lib/python3.8/contextlib.py", line 162, in __exit__     raise RuntimeError("generator didn't stop after throw()")
</code>```

What does this error mean and how to fix it?

Body:
I am using python 3.8 as the lambda runtime for my lambda function which I am trying to deploy using cdk v2. This is a lambda as a custom resource that runs every time the stack deploys.

This is the folder structure

 /Dynamics/cust_resource/__init__.py
 /Dynamics/cust_resource/data_objects.py
 /Dynamics/cust_resource/lambda.py
 /Dynamics/cust_resource/requirements.txt
 /Dynamics/__init__.py
 /Dynamics/dyna_stack.py
 app.py

This is the lambda code

import os
import boto3
import sys

print('before lambda import')

from data_objects import poco_data

This is how I am creating the function in the stack

cust_res_lambda = _lambda.Function(
    self, 'crLambda',
    runtime=_lambda.Runtime.PYTHON_3_8,
    code=_lambda.Code.from_asset('Dynamics/cust_resource',
                                 bundling=BundlingOptions(
                                        image=_lambda.Runtime.PYTHON_3_8.bundling_image,
                                        command=["bash", "-c", "pip install -r requirements.txt -t /asset-output && cp -au . /asset-output"]
                                     )),
    handler='lambda.lambda_handler',
    function_name='crlambdaFn',

)

The lambda executes and I see the line before lambda import in cloudwatch logs followed by.

[ERROR] RuntimeError: generator didn't stop after throw()
Traceback (most recent call last):
  File "/var/lang/lib/python3.8/imp.py", line 234, in load_module
    return load_source(name, filename, file)
  File "/var/lang/lib/python3.8/imp.py", line 171, in load_source
    module = _load(spec)
  File "<frozen importlib._bootstrap>", line 702, in _load
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 843, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/var/task/lambda.py", line 12, in <module>
    from data_objects import poco_data
  File "/var/task/data_objects.py", line 1, in <module>
    from aws_cdk import (
  File "/var/task/aws_cdk/__init__.py", line 1257, in <module>
    from ._jsii import *
  File "/var/task/aws_cdk/_jsii/__init__.py", line 13, in <module>
    import constructs._jsii
  File "/var/task/constructs/__init__.py", line 43, in <module>
    from ._jsii import *
  File "/var/task/constructs/_jsii/__init__.py", line 13, in <module>
    __jsii_assembly__ = jsii.JSIIAssembly.load(
  File "/var/task/jsii/_runtime.py", line 54, in load
    _kernel.load(assembly.name, assembly.version, os.fspath(assembly_path))
  File "/var/lang/lib/python3.8/contextlib.py", line 162, in __exit__
    raise RuntimeError("generator didn't stop after throw()")
[ERROR] RuntimeError: generator didn't stop after throw() Traceback (most recent call last):   File "/var/lang/lib/python3.8/imp.py", line 234, in load_module     return load_source(name, filename, file)   File "/var/lang/lib/python3.8/imp.py", line 171, in load_source     module = _load(spec)   File "<frozen importlib._bootstrap>", line 702, in _load   File "<frozen importlib._bootstrap>", line 671, in _load_unlocked   File "<frozen importlib._bootstrap_external>", line 843, in exec_module   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed   File "/var/task/lambda.py", line 12, in <module>     from data_objects import poco_data   File "/var/task/data_objects.py", line 1, in <module>     from aws_cdk import (   File "/var/task/aws_cdk/__init__.py", line 1257, in <module>     from ._jsii import *   File "/var/task/aws_cdk/_jsii/__init__.py", line 13, in <module>     import constructs._jsii   File "/var/task/constructs/__init__.py", line 43, in <module>     from ._jsii import *   File "/var/task/constructs/_jsii/__init__.py", line 13, in <module>     __jsii_assembly__ = jsii.JSIIAssembly.load(   File "/var/task/jsii/_runtime.py", line 54, in load     _kernel.load(assembly.name, assembly.version, os.fspath(assembly_path))   File "/var/lang/lib/python3.8/contextlib.py", line 162, in __exit__     raise RuntimeError("generator didn't stop after throw()")

What does this error mean and how to fix it?


问:
error when running any .ipynb file in vscode
I already have jupyter notebook, and wanted to be able to run it in vs code.
I installed pip

```<code>PS C:\Users\ninet> py --version
Python 3.11.0
PS C:\Users\ninet> py -m pip --version
pip 22.3 from C:\Users\ninet\AppData\Local\Programs\Python\Python311\Lib\site-packages\pip (python 3.11)
</code>```

and also jupyter extension, but whenever i try to run a simple .ipynb at vscode there's an error

```<code>python: can't open file 'C:\\Users\\ninet\\AppData\\Local\\Programs\\Microsoft VS Code\\Untitled-1.ipynb': [Errno 2] No such file or directory
</code>```

I think I need to fix the path somehow , how can i fix it?

I tried to set the name by

```<code>
python -m ipykernel install --user --name conda --display-name

</code>```

but it doesn't run

Body:
I already have jupyter notebook, and wanted to be able to run it in vs code.
I installed pip

PS C:\Users\ninet> py --version
Python 3.11.0
PS C:\Users\ninet> py -m pip --version
pip 22.3 from C:\Users\ninet\AppData\Local\Programs\Python\Python311\Lib\site-packages\pip (python 3.11)

and also jupyter extension, but whenever i try to run a simple .ipynb at vscode there's an error

python: can't open file 'C:\\Users\\ninet\\AppData\\Local\\Programs\\Microsoft VS Code\\Untitled-1.ipynb': [Errno 2] No such file or directory

I think I need to fix the path somehow , how can i fix it?

I tried to set the name by

python -m ipykernel install --user --name conda --display-name

but it doesn't run


问:
Trying to get Amazon reviews to go left and right of a picture
everyone. First time poster and I'm gonna go ahead and consider myself a novice when it comes to coding.

So I have a few Amazon reviews that I am wanting to go left and right of a picture that's in the middle of the page. That way I don't have a senseless empty/white space on the page. I am using external CSS and JS with my HTML.

let data = [
    {
        review: 'I finished this book in three days because I COULD NOT PUT IT DOWN! I read page one, and I was a goner! If you enjoy romance, but also appreciate unpredictability, plot twists, with a side steam, look no further. Very much looking forward to the next book!'
    },
    {
        review: 'A great romance! The plot is very interesting and keeps you turning the pages. More and more romance today is all about lust and spice, but grateful for authors who still believe plot is important. This is a quick read. Very refreshing and clean (it does have 2 spicey scenes). Can\'t wait for the next book!'
    },
    {
        review: 'Finished the book in under 24 hours. It\'s absolutely riveting. Apparently it\'s the author\'s first book - and honestly I see a lot of talent in this young writer. There\'s lots of twists and turns that leaves me in suspense. I can also appreciate the military references so that it also has an appeal to the male audience. My wife absolutely loves this book and is fully immersed into the storyline - she describes it as a masterpiece and the fact that she got a sneak peek of the next book at the very end leaves her in high suspense and anxious for the next one to get published.'
    },
    {
        review: 'Good quick read with twists and a good ending!'
    },
    {
        review: 'A great romance! The plot is very interesting and keeps you turning the pages. More and more romance today is all about lust and spice, but grateful for authors who still believe plot is important. This is a quick read. Very refreshing and clean (it does have 2 spicey scenes). Can\'t wait for the next book!'
    }
];

const info = document.querySelector('#info')

let details = data.map(function(item) {
    return ('
' + item.review + '
')
})

info.innerHTML = details.join('\n') ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    /* display: flex; */
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100hv;
}

#topBanner {
    background-color: #424347;
    color: white;
    text-align: center;
    padding: 25px 0 25px;
    font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    text-transform: uppercase;
    width: auto;
    margin: auto;
}

.title {
    font-family: X Typewriter;
    font-size: x-large;
    letter-spacing: 2em;
    text-indent: 2em;
}

.subTitle {
    font-family: X Typewriter;
}

img {
    display: block;
    margin-left: auto;
    margin-right: auto;
    /* width: 50%; */
}

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

#info {
    display: grid;
    grid-template-columns: 1fr 1fr;

}

#info div {
    padding: 3rem;
    background: lightgrey;
    margin: 0.5rem;
    border-radius: 10px;
    font-size: 1.2rem;
    text-align: center;
}</code>```

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Uncovered: A Novel</title>
        <link rel="stylesheet" href="styles.css">

Uncovered

A Novel

```

Body:
everyone. First time poster and I'm gonna go ahead and consider myself a novice when it comes to coding.

So I have a few Amazon reviews that I am wanting to go left and right of a picture that's in the middle of the page. That way I don't have a senseless empty/white space on the page. I am using external CSS and JS with my HTML.

let data = [
    {
        review: 'I finished this book in three days because I COULD NOT PUT IT DOWN! I read page one, and I was a goner! If you enjoy romance, but also appreciate unpredictability, plot twists, with a side steam, look no further. Very much looking forward to the next book!'
    },
    {
        review: 'A great romance! The plot is very interesting and keeps you turning the pages. More and more romance today is all about lust and spice, but grateful for authors who still believe plot is important. This is a quick read. Very refreshing and clean (it does have 2 spicey scenes). Can\'t wait for the next book!'
    },
    {
        review: 'Finished the book in under 24 hours. It\'s absolutely riveting. Apparently it\'s the author\'s first book - and honestly I see a lot of talent in this young writer. There\'s lots of twists and turns that leaves me in suspense. I can also appreciate the military references so that it also has an appeal to the male audience. My wife absolutely loves this book and is fully immersed into the storyline - she describes it as a masterpiece and the fact that she got a sneak peek of the next book at the very end leaves her in high suspense and anxious for the next one to get published.'
    },
    {
        review: 'Good quick read with twists and a good ending!'
    },
    {
        review: 'A great romance! The plot is very interesting and keeps you turning the pages. More and more romance today is all about lust and spice, but grateful for authors who still believe plot is important. This is a quick read. Very refreshing and clean (it does have 2 spicey scenes). Can\'t wait for the next book!'
    }
];

const info = document.querySelector('#info')

let details = data.map(function(item) {
    return ('
' + item.review + '
')
})

info.innerHTML = details.join('\n')

body {
    /* display: flex; */
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100hv;
}

#topBanner {
    background-color: #424347;
    color: white;
    text-align: center;
    padding: 25px 0 25px;
    font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    text-transform: uppercase;
    width: auto;
    margin: auto;
}

.title {
    font-family: X Typewriter;
    font-size: x-large;
    letter-spacing: 2em;
    text-indent: 2em;
}

.subTitle {
    font-family: X Typewriter;
}

img {
    display: block;
    margin-left: auto;
    margin-right: auto;
    /* width: 50%; */
}

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

#info {
    display: grid;
    grid-template-columns: 1fr 1fr;

}

#info div {
    padding: 3rem;
    background: lightgrey;
    margin: 0.5rem;
    border-radius: 10px;
    font-size: 1.2rem;
    text-align: center;
}

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Uncovered: A Novel</title>
        <link rel="stylesheet" href="styles.css">

Uncovered

A Novel


问:
Update table with data after value selected from the dropdownlist (asp.net mvc)
I am just  starting to work with asp.net mvc and I am trying to understand the logic between views and controllers.
I have the table with the data that I am getting from the db shown on my page and I am also have the dropdown on my page. I would like to update my table according to the value selected from the dropdown (for example if user selects T3) the data for T3 shows in the table.
I can't quite understand how I can pass the value selected from the dropdown and how to the controller and how to update my sql query with this new value. Is it suppose to be in the same index method or it should be the different one. I would appreciate any help and ideas. Thank you in advance.

Here is my model:

```<code>    public class TestModel
    {
        public int id { get; set; }
        public string name { get; set; }
        public string serial{ get; set; }
        public string pr { get; set; }
    }
</code>```

Here is my Controller: First sql string I am using to get data for the dropdown and the second one to get data for the table itself.

```<code>    public class TestController : Controller
    {
     public List<TestModel> Test = new List<TestModel>();
     public List<TableModel> Table = new List<TableModel>();

        public IActionResult Index()
        {
            try
            {

                String connectionString = "bbbb";
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    String sql2 = "SELECT * FROM db WHERE detail = 1";
                    using (SqlCommand command = new SqlCommand(sql2, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                TestModel test= new TestModel();
                                test.id = Convert.ToInt32("" + reader[0]);
                                test.name = "" + reader[1];
                                test.serial = "" + reader[3];
                                test.pr = "" + reader[4];
                                Test.Add(test);
                            }
                        }
                    }

                    String sql = "SELECT * FROM bb1";
                    using (SqlCommand command1 = new SqlCommand(sql, connection)) {
                    using(SqlDataReader reader1 = command1.ExecuteReader())
                    {
                        while (reader1.Read())
                        {
                            TableModel tablemod = new TableModel();
                            tablemod.id = Convert.ToInt32("" + reader1[0]);
                            tablemod.tr = "" + reader1[2];
                            tablemod.pr = "" + reader1[4];
                            tablemod.req = "" + reader1[5];
                            tablemod.test = "" + reader1[6];
                            tablemod.method = "" + reader1[7];
                            tablemod.sport = "" + reader1[8];
                            tablemod.timer = "" + reader1[9];
                            tablemod.ra = "" + reader1[10];
                            tablemod.calib = "" + reader1[12];
                            Table.Add(tablemod);
                            }
                    }
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("exception:" + ex.ToString());
            }

            ViewData["dropdown"] = TestCell;
            ViewData["table"] = Table;

            return View();
        }
    }
</code>```

And here is the view:

```<code><!doctype html>
<html lang="eng">
<head>
some styles go there
</head>

<body>
    <div class="table">

                <div>
                    <select asp-for="@Model.id" asp-items="(@ViewData["dropdown"] as IEnumerable<SelectListItem>)"  id="UserId" class="form-control " >
                        <span asp-validation-for="@Model.id"></span>
                        @foreach (var item in @ViewData["dropdown"] as IEnumerable<TestModel>)
                        {
                            <option class="others" value="@item.id&&@item.serial&&@item.pr">@item.fname</option>

                        }
                    </select>
                </div>
                <div><input id="serial" type="text"/></div>
                <div><input id="pr" type="text"/></div>

            </div>

        </div>

        <table class="table ">
            <thead>
            <th data-field="tr" data-sortable="true">TR</th>
            <th data-field="pr" data-sortable="true">Priority</th>
            <th data-field="req" data-sortable="true">Requestor</th>
            <th data-field="test" data-sortable="true">Test Name</th>
            <th data-field="method" data-sortable="true">Description</th>
            <th data-field="sport" data-sortable="true">Failed Part</th>
            <th data-field="timer" data-sortable="true">Emission</th>
            <th data-field="ra" data-sortable="true">Rating</th>
            <th data-field="calib" data-sortable="true">Calibration</th>
            </thead>

             <tbody>
                @foreach (var item in @ViewData["table"] as IEnumerable<TableModel>)
                {
                    <tr>
                        <td>@item.trnum</td>
                        <td>@item.priority</td>
                        <td>@item.requestor</td>
                        <td>@item.testname</td>
                        <td>@item.description</td>
                        <td>@item.failed</td>
                        <td>@item.emission</td>
                        <td>@item.rating</td>
                        <td>@item.calibration</td>
                        <td>@item.eas</td>
                        <td>@item.recorder</td>

                    </tr>
                }

            </tbody>
        </table>
    </div>

</body>
</html>

<script type="text/javascript">
    var $table = $('#fresh-table')
    var $alertBtn = $('#alertBtn')

    $(function () {
        $table.bootstrapTable({
            classes: 'table table-hover table-striped',
            toolbar: '.toolbar',

            search: true,
            showRefresh: true,
            showToggle: true,
            showColumns: true,
            pagination: true,
            height: $(window).height(),
            striped: true,
            sortable: true,
            pageSize: 10,
            pageList: [8, 10, 25, 50, 100],

            formatShowingRows: function (pageFrom, pageTo, totalRows) {
                return ''
            },
            formatRecordsPerPage: function (pageNumber) {
                return pageNumber + ' rows visible'
            }
        })

        $(window).resize(function () {
            $table.bootstrapTable('resetView', {
                height: $(window).height(),

            })
        })

    })

    $(function () {
        $('#fresh-table').bootstrapTable()
    })
    $("#UserId").change(function () {
        var selectedid = $("#UserId option:selected").val().split("&&");
        var serialNumber = selectedid[1];
        var projectNumber = selectedid[2];
        $('#serialNumber').val(serialNumber);
        $('#projectNumber').val(projectNumber);
    });

</script>
</code>```

Body:
I am just  starting to work with asp.net mvc and I am trying to understand the logic between views and controllers.
I have the table with the data that I am getting from the db shown on my page and I am also have the dropdown on my page. I would like to update my table according to the value selected from the dropdown (for example if user selects T3) the data for T3 shows in the table.
I can't quite understand how I can pass the value selected from the dropdown and how to the controller and how to update my sql query with this new value. Is it suppose to be in the same index method or it should be the different one. I would appreciate any help and ideas. Thank you in advance.

Here is my model:

    public class TestModel
    {
        public int id { get; set; }
        public string name { get; set; }
        public string serial{ get; set; }
        public string pr { get; set; }
    }

Here is my Controller: First sql string I am using to get data for the dropdown and the second one to get data for the table itself.

    public class TestController : Controller
    {
     public List<TestModel> Test = new List<TestModel>();
     public List<TableModel> Table = new List<TableModel>();

        public IActionResult Index()
        {
            try
            {

                String connectionString = "bbbb";
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    String sql2 = "SELECT * FROM db WHERE detail = 1";
                    using (SqlCommand command = new SqlCommand(sql2, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                TestModel test= new TestModel();
                                test.id = Convert.ToInt32("" + reader[0]);
                                test.name = "" + reader[1];
                                test.serial = "" + reader[3];
                                test.pr = "" + reader[4];
                                Test.Add(test);
                            }
                        }
                    }

                    String sql = "SELECT * FROM bb1";
                    using (SqlCommand command1 = new SqlCommand(sql, connection)) {
                    using(SqlDataReader reader1 = command1.ExecuteReader())
                    {
                        while (reader1.Read())
                        {
                            TableModel tablemod = new TableModel();
                            tablemod.id = Convert.ToInt32("" + reader1[0]);
                            tablemod.tr = "" + reader1[2];
                            tablemod.pr = "" + reader1[4];
                            tablemod.req = "" + reader1[5];
                            tablemod.test = "" + reader1[6];
                            tablemod.method = "" + reader1[7];
                            tablemod.sport = "" + reader1[8];
                            tablemod.timer = "" + reader1[9];
                            tablemod.ra = "" + reader1[10];
                            tablemod.calib = "" + reader1[12];
                            Table.Add(tablemod);
                            }
                    }
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("exception:" + ex.ToString());
            }

            ViewData["dropdown"] = TestCell;
            ViewData["table"] = Table;

            return View();
        }
    }

And here is the view:

<!doctype html>

some styles go there

                    <select asp-for="@Model.id" asp-items="(@ViewData["dropdown"] as IEnumerable<SelectListItem>)"  id="UserId" class="form-control " >

                        @foreach (var item in @ViewData["dropdown"] as IEnumerable<TestModel>)
                        {
                            <option class="others" value="@item.id&&@item.serial&&@item.pr">@item.fname</option>

                        }
                    </select>

<input id="serial" type="text"/>

<input id="pr" type="text"/>

            TR
            Priority
            Requestor
            Test Name
            Description
            Failed Part
            Emission
            Rating
            Calibration

                @foreach (var item in @ViewData["table"] as IEnumerable<TableModel>)
                {

                        @item.trnum
                        @item.priority
                        @item.requestor
                        @item.testname
                        @item.description
                        @item.failed
                        @item.emission
                        @item.rating
                        @item.calibration
                        @item.eas
                        @item.recorder

                }


问:
Strange OpenXML corruption issue when populating a newly-saved template
We have a template we reflected the code (with the OpenXML Productivity Tool v2.5) for in 2018 and the population of its data goes smoothly.  The resultant document does not contain corrupted data.

We need to make changes to the template, so we expected to be able to use the OpenXML Productivity Tool to reflect the code for our mutated template back into the project.

This failed, however, in that the document was partially corrupted by the same code that we used to modify the old template.

Inspecting further, I found that generating the old template out of the reflected code from 2018, opening it in Excel, and doing nothing to the document except saving it again causes the corruption to the document when it is attempted to be populated.

What follows is the code to mutate our cells (populate them with data).  I am at a loss for other "bad" chars to remove from the cell's value (check out the safeValueBuilder StringBuilder at the end).

Is the OpenXML Productivity Tool past EOL?  The only other solution I can think of would be to store the templates directly instead of storing reflected code from the Productivity Tool.

Any help with this would be greatly, greatly appreciated.  Perhaps there are other invalid chars in the Excel data besides the 0 bytes?  What other chars are invalid data for OpenXML?

```<code>        public virtual void ChangeCell(
            SpreadsheetDocument document,
            string cellReference,
            string newValue)
        {
            if (document == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(newValue))
            {
                return;
            }

            var workbook = document.WorkbookPart;
            var worksheet = EH.FirstOrNull(
                    workbook?.WorksheetParts)
                ?.Worksheet;
            if (worksheet == null)
            {
                return;
            }

            var r = this.runner;
            r?.Run<CellLocator>(locator =>
            {
                var sheetData = worksheet.GetFirstChild<SheetData>();
                if (sheetData == null)
                {
                    return;
                }

                byte columnIndex;
                short rowIndex;
                locator.Locate(
                    cellReference,
                    out columnIndex,
                    out rowIndex);
                var row = EH.ElementAt(
                    sheetData.Elements<Row>(),
                    rowIndex);
                if (row == null)
                {
                    return;
                }

                var cell = EH.FirstOrNull(
                    row.Elements<Cell>(),
                    c => c?.CellReference == cellReference);
                if (cell == null)
                {
                    cell = new Cell { CellReference = cellReference };
                    row.InsertAt(cell, columnIndex);
                }

                if (double.TryParse(newValue, out _))
                {
                    cell.DataType = new EnumValue<CellValues>(
                        CellValues.Number);
                    goto setCellValue;
                }

                cell.DataType = new EnumValue<CellValues>(
                    CellValues.String);

                setCellValue:
                var safeValueBuilder = new StringBuilder();
                foreach (var c in newValue)
                {
                    if (c == (char)InvalidCharByte)
                    {
                        continue;
                    }

                    safeValueBuilder.Append(c);
                }

                cell.CellValue = new CellValue(
                    safeValueBuilder.ToString());
            });
        }

public const byte InvalidCharByte = 0x00;
</code>```

Body:
We have a template we reflected the code (with the OpenXML Productivity Tool v2.5) for in 2018 and the population of its data goes smoothly.  The resultant document does not contain corrupted data.

We need to make changes to the template, so we expected to be able to use the OpenXML Productivity Tool to reflect the code for our mutated template back into the project.

This failed, however, in that the document was partially corrupted by the same code that we used to modify the old template.

Inspecting further, I found that generating the old template out of the reflected code from 2018, opening it in Excel, and doing nothing to the document except saving it again causes the corruption to the document when it is attempted to be populated.

What follows is the code to mutate our cells (populate them with data).  I am at a loss for other "bad" chars to remove from the cell's value (check out the safeValueBuilder StringBuilder at the end).

Is the OpenXML Productivity Tool past EOL?  The only other solution I can think of would be to store the templates directly instead of storing reflected code from the Productivity Tool.

Any help with this would be greatly, greatly appreciated.  Perhaps there are other invalid chars in the Excel data besides the 0 bytes?  What other chars are invalid data for OpenXML?

        public virtual void ChangeCell(
            SpreadsheetDocument document,
            string cellReference,
            string newValue)
        {
            if (document == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(newValue))
            {
                return;
            }

            var workbook = document.WorkbookPart;
            var worksheet = EH.FirstOrNull(
                    workbook?.WorksheetParts)
                ?.Worksheet;
            if (worksheet == null)
            {
                return;
            }

            var r = this.runner;
            r?.Run<CellLocator>(locator =>
            {
                var sheetData = worksheet.GetFirstChild<SheetData>();
                if (sheetData == null)
                {
                    return;
                }

                byte columnIndex;
                short rowIndex;
                locator.Locate(
                    cellReference,
                    out columnIndex,
                    out rowIndex);
                var row = EH.ElementAt(
                    sheetData.Elements<Row>(),
                    rowIndex);
                if (row == null)
                {
                    return;
                }

                var cell = EH.FirstOrNull(
                    row.Elements<Cell>(),
                    c => c?.CellReference == cellReference);
                if (cell == null)
                {
                    cell = new Cell { CellReference = cellReference };
                    row.InsertAt(cell, columnIndex);
                }

                if (double.TryParse(newValue, out _))
                {
                    cell.DataType = new EnumValue<CellValues>(
                        CellValues.Number);
                    goto setCellValue;
                }

                cell.DataType = new EnumValue<CellValues>(
                    CellValues.String);

                setCellValue:
                var safeValueBuilder = new StringBuilder();
                foreach (var c in newValue)
                {
                    if (c == (char)InvalidCharByte)
                    {
                        continue;
                    }

                    safeValueBuilder.Append(c);
                }

                cell.CellValue = new CellValue(
                    safeValueBuilder.ToString());
            });
        }

public const byte InvalidCharByte = 0x00;


问:
Apex Test - Instantiate new Controller
I am trying to instantiate a new controller. But every syntax I have tried shows an error.

Here is my code:

Class:

```<code>public  class MyNewCaseController {

    public string filterId {get; set;}

    public MyNewCaseController(ApexPages.StandardController  ctrl){
        string filter = ApexPages.currentPage().getParameters().get('filterId');
        if (filter != null)
            filterId = filter;
    }
}
</code>```

Test:

```<code>@isTest
public without sharing class MyNewCaseListControllerTest {

    @isTest
    public static void testMyNewCaseController (){
        // Instantiate a new controller with all parameters in the page
        MyNewCaseListController controller = new MyNewCaseListController.MyNewCaseListController(ApexPages.StandardController ctrl);

    // Do something
    }
}
</code>```

I get the error “Invalid type: CommunitiesCaseListController.CommunitiesCaseListController”.

If I try just

```<code>MyNewCaseListController controller = new MyNewCaseListController();
</code>```

I get Constructor not defined: [MyNewCaseListController].()

If I try

```<code>MyNewCaseListController.MyNewCaseListController();
</code>```

I get “Invalid type: MyNewCaseListController.MyNewCaseListController”

If I try

```<code>MyNewCaseListController controller = new MyNewCaseListController.MyNewCaseListController(ApexPages.ctrl);
</code>```

I get “Invalid type: MyNewCaseListController.MyNewCaseListController”

What am I doing wrong?

Title: Apex Test - Instantiate new Controller

Body:
I am trying to instantiate a new controller. But every syntax I have tried shows an error.

Here is my code:

Class:

public  class MyNewCaseController {

    public string filterId {get; set;}

    public MyNewCaseController(ApexPages.StandardController  ctrl){
        string filter = ApexPages.currentPage().getParameters().get('filterId');
        if (filter != null)
            filterId = filter;
    }
}

Test:

@isTest
public without sharing class MyNewCaseListControllerTest {

    @isTest
    public static void testMyNewCaseController (){
        // Instantiate a new controller with all parameters in the page
        MyNewCaseListController controller = new MyNewCaseListController.MyNewCaseListController(ApexPages.StandardController ctrl);

    // Do something
    }
}

I get the error “Invalid type: CommunitiesCaseListController.CommunitiesCaseListController”.

If I try just

MyNewCaseListController controller = new MyNewCaseListController();

I get Constructor not defined: [MyNewCaseListController].()

If I try

MyNewCaseListController.MyNewCaseListController();

I get “Invalid type: MyNewCaseListController.MyNewCaseListController”

If I try

MyNewCaseListController controller = new MyNewCaseListController.MyNewCaseListController(ApexPages.ctrl);

I get “Invalid type: MyNewCaseListController.MyNewCaseListController”

What am I doing wrong?