问:
Powershell script: get multiple properties from "Get-Childitem" in a loop
i am absolutely not a programmer, so please excuse my ignorance and clumsy code.

My task is to change one value per file with 1.25*value in a number of xml-files in a folder.

I have come up with the following code which seems to go through all files and changes each value correctly, then writes the new changed files to a new subfolder "DD1". My test code so far only wrote to a single file test.xml all the time, overwriting it per each loop.

I want the altered files to be named exactly like the original ones, so i am trying to grab each filename within the loop but so far to no avail. Maybe you can tell me, what to put instead of the "????????"

```<code>New-Item '.\DD1'  -ItemType Directory

Get-ChildItem -Path .\ -Filter *.pws |

Foreach-Object {
[xml]$myXML = Get-Content $_.FullName
$valueString = $myXML.settings.TuningMenu.FF
$valueInt = [int]$valueString
$newValueInt = $valueInt*1.25
$newValueString = [string]$newValueInt
$myXML.settings.TuningMenu.FF = $newValueString
[string]$path = $PWD
[string]$file = ????????
$fullName = $path+"\DD1\"+$file
$myXML.Save("$fullName")
}
</code>```

Body:
i am absolutely not a programmer, so please excuse my ignorance and clumsy code.

My task is to change one value per file with 1.25*value in a number of xml-files in a folder.

I have come up with the following code which seems to go through all files and changes each value correctly, then writes the new changed files to a new subfolder "DD1". My test code so far only wrote to a single file test.xml all the time, overwriting it per each loop.

I want the altered files to be named exactly like the original ones, so i am trying to grab each filename within the loop but so far to no avail. Maybe you can tell me, what to put instead of the "????????"

New-Item '.\DD1'  -ItemType Directory

Get-ChildItem -Path .\ -Filter *.pws |

Foreach-Object {
[xml]$myXML = Get-Content $_.FullName
$valueString = $myXML.settings.TuningMenu.FF
$valueInt = [int]$valueString
$newValueInt = $valueInt*1.25
$newValueString = [string]$newValueInt
$myXML.settings.TuningMenu.FF = $newValueString
[string]$path = $PWD
[string]$file = ????????
$fullName = $path+"\DD1\"+$file
$myXML.Save("$fullName")
}


来源: stackexchange

问:
In google calendar get only the Microsoft Team Addon event's list using API
I have added the Microsoft team as an add-on in google calendar. Now I want to get only those events that are added as Microsoft team events in the event list using API. How can I achieve this?

to get an event list of only Microsoft team events.

ContentLicense: CC BY-SA 4.0


问:
Why doesn't it let me choose settings?
There is a simple application that should download a file to the watch at the click of a button. The first problem is that it downloads it every other time!
enter image description here

Even if it downloaded it and I try to open it
enter image description here

I have a settings window pop up so that I can give permissions
but when I click on the settings button, my application returns to the original window.

Main activity.java

```<code>public class MainActivity extends Activity {

    private Button download;
    private ActivityMainBinding binding;
    private static final String URL = "https://xmonitoring.ru/load/auto_load.php";
    private static final String FILE_NAME = "wearOs.apk";
    private static final int DOWNLOAD_FILE = 100;
    private static final int INSTALL_APK = 200;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        binding.download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                        downloadApk(URL, FILE_NAME);
                    } else {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE);
                    }
                } else {
                    downloadApk(URL, FILE_NAME);
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == DOWNLOAD_FILE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                binding.download.performClick();
            }
        }
    }

    private void downloadApk(String url, String file) {
        String fileName = URLUtil.guessFileName(file, null, "application/vnd.android.package-archive");
        String folder = Environment.getExternalStorageDirectory() + "/Download/";
        File newFile = new File(folder, fileName);
        try {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.allowScanningByMediaScanner();
            request.setDescription(fileName)
                    .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI)
                    .setDestinationUri(Uri.fromFile(newFile))
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                    .setVisibleInDownloadsUi(true)
                    .setTitle(file);
            DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            assert manager != null;
            long downloadID = manager.enqueue(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Title: Why doesn't it let me choose settings?

Body:
There is a simple application that should download a file to the watch at the click of a button. The first problem is that it downloads it every other time!
enter image description here

Even if it downloaded it and I try to open it
enter image description here

I have a settings window pop up so that I can give permissions
but when I click on the settings button, my application returns to the original window.

Main activity.java

public class MainActivity extends Activity {

    private Button download;
    private ActivityMainBinding binding;
    private static final String URL = "https://xmonitoring.ru/load/auto_load.php";
    private static final String FILE_NAME = "wearOs.apk";
    private static final int DOWNLOAD_FILE = 100;
    private static final int INSTALL_APK = 200;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        binding.download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                        downloadApk(URL, FILE_NAME);
                    } else {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE);
                    }
                } else {
                    downloadApk(URL, FILE_NAME);
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == DOWNLOAD_FILE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                binding.download.performClick();
            }
        }
    }

    private void downloadApk(String url, String file) {
        String fileName = URLUtil.guessFileName(file, null, "application/vnd.android.package-archive");
        String folder = Environment.getExternalStorageDirectory() + "/Download/";
        File newFile = new File(folder, fileName);
        try {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.allowScanningByMediaScanner();
            request.setDescription(fileName)
                    .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI)
                    .setDestinationUri(Uri.fromFile(newFile))
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                    .setVisibleInDownloadsUi(true)
                    .setTitle(file);
            DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            assert manager != null;
            long downloadID = manager.enqueue(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


问:
How to improve Google Recaptchav3 score as it returns 0.1 for genuine users
Recaptchav3 score is random for a set of users

It returns 0.1 as score for logged in Safari browser request
0.3 for firefox and chrome

Any suggestions to improve the score as the recommended threshold is 0.5

```<code>    request = recaptchaenterprise_v1.CreateAssessmentRequest()
    request.assessment = assessment
    request.parent = project_name

    response = client.create_assessment(request)
</code>```

Body:
Recaptchav3 score is random for a set of users

It returns 0.1 as score for logged in Safari browser request
0.3 for firefox and chrome

Any suggestions to improve the score as the recommended threshold is 0.5

    request = recaptchaenterprise_v1.CreateAssessmentRequest()
    request.assessment = assessment
    request.parent = project_name

    response = client.create_assessment(request)


问:
trying to build 3d/2d cycle configurator web application on top of react. Which stack/tool/lib/plugin I should use
Hi I am trying build a web application, which is a cycle configurator. The requirement is, there will be a page where a cycle wireframe will display with dimensions. There will be a configurator panel where user can select the value to change the length of cycle, tire height and width, handle width, total length and height, color of the cycle. I have to create the wireframe (2d/3d) as per user input dynamically and at the end send the response as json to server. Could you please guide me which tool I should use to build an interactive (2d/3d) wireframe on top of React

I am trying to create SVG file which can be modified by js code. Could you please suggest which library I should use to draw and manipulate complex drawing


问:
error: cannot find symbol on React Native
I want to build a VPN app with React Native and cloned a repository from this GitHub.
When I run the project with yarn android, it throws me error like this:

```<code>Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
/Users/rurjaf/React-Native/FourthVPN/node_modules/react-native-ip-sec-vpn/android/src/main/java/org/strongswan/android/logic/CharonVpnService.java:374: error: cannot find symbol
                .setSmallIcon(androidx.appcompat.R.drawable.abc_ic_star_black_48dp)
                                                           ^
  symbol:   variable abc_ic_star_black_48dp
  location: class drawable
/Users/rurjaf/React-Native/FourthVPN/node_modules/react-native-ip-sec-vpn/android/src/main/java/org/strongswan/android/logic/CharonVpnService.java:382: error: cannot find symbol
            builder.setSmallIcon(androidx.appcompat.R.drawable.abc_ic_star_black_48dp);
                                                              ^
  symbol:   variable abc_ic_star_black_48dp
  location: class drawable
/Users/rurjaf/React-Native/FourthVPN/node_modules/react-native-ip-sec-vpn/android/src/main/java/org/strongswan/android/logic/CharonVpnService.java:409: error: cannot find symbol
                    builder.setSmallIcon(androidx.appcompat.R.drawable.abc_ic_star_black_48dp);
                                                                      ^
  symbol:   variable abc_ic_star_black_48dp
  location: class drawable
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
</code>```

I deleted the node_modules and installed it again with yarn add but I am still facing the same issue. Also I run ./gradlew clean, but still facing the same issue.

Thanks in advance for any help.

Body:
I want to build a VPN app with React Native and cloned a repository from this GitHub.
When I run the project with yarn android, it throws me error like this:

Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
/Users/rurjaf/React-Native/FourthVPN/node_modules/react-native-ip-sec-vpn/android/src/main/java/org/strongswan/android/logic/CharonVpnService.java:374: error: cannot find symbol
                .setSmallIcon(androidx.appcompat.R.drawable.abc_ic_star_black_48dp)
                                                           ^
  symbol:   variable abc_ic_star_black_48dp
  location: class drawable
/Users/rurjaf/React-Native/FourthVPN/node_modules/react-native-ip-sec-vpn/android/src/main/java/org/strongswan/android/logic/CharonVpnService.java:382: error: cannot find symbol
            builder.setSmallIcon(androidx.appcompat.R.drawable.abc_ic_star_black_48dp);
                                                              ^
  symbol:   variable abc_ic_star_black_48dp
  location: class drawable
/Users/rurjaf/React-Native/FourthVPN/node_modules/react-native-ip-sec-vpn/android/src/main/java/org/strongswan/android/logic/CharonVpnService.java:409: error: cannot find symbol
                    builder.setSmallIcon(androidx.appcompat.R.drawable.abc_ic_star_black_48dp);
                                                                      ^
  symbol:   variable abc_ic_star_black_48dp
  location: class drawable
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

I deleted the node_modules and installed it again with yarn add but I am still facing the same issue. Also I run ./gradlew clean, but still facing the same issue.

Thanks in advance for any help.


问:
How to configure Oracle Column's DefaultValue And Collate Value
In Oracle 19c, I want to specify the default value of a column and the collate property at the same time.

create table id_table(
     name varchar2(64) collate binary_ai,
     id varchar2(8) collate binary_ci
);

insert into id_table values('Christopher', 'ABCD1234');

SELECT collation(name), collation(id) from id_table;
```
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>COLLATION(NAME)</th>
<th>COLLATION(ID)</th>
</tr>
</thead>
<tbody>
<tr>
<td>BINARY_AI</td>
<td>BINARY_CI</td>
</tr>
</tbody>
</table>
</div>
<p>It was well specified as intended.</p>
<p>but,</p>
<pre class="lang-sql prettyprint-override"><code>create table id_table2(
     name char default 'Y' collate binary_ai,
     id varchar2(8)
);

insert into id_table2 values('c', 'ABCD1234');

SELECT collation(name), collation(id) from id_table2;
</code>```

COLLATION(NAME)
COLLATION(ID)

USING_NLS_COMP
USING_NLS_COMP

If you specify the default value and collate together, an unintended value is specified.

The intent was to expect the same values as in the first example.

Are DEFAULT VALUE and COLLATE mutually exclusive?

Body:
In Oracle 19c, I want to specify the default value of a column and the collate property at the same time.

create table id_table(
     name varchar2(64) collate binary_ai,
     id varchar2(8) collate binary_ci
);

insert into id_table values('Christopher', 'ABCD1234');

SELECT collation(name), collation(id) from id_table;

COLLATION(NAME)
COLLATION(ID)

BINARY_AI
BINARY_CI

It was well specified as intended.

but,

create table id_table2(
     name char default 'Y' collate binary_ai,
     id varchar2(8)
);

insert into id_table2 values('c', 'ABCD1234');

SELECT collation(name), collation(id) from id_table2;

COLLATION(NAME)
COLLATION(ID)

USING_NLS_COMP
USING_NLS_COMP

If you specify the default value and collate together, an unintended value is specified.

The intent was to expect the same values as in the first example.

Are DEFAULT VALUE and COLLATE mutually exclusive?


问:
Can't Resolve NoReverseMatch Error "NoReverseMatch at /accounts/signup/"
I have been working on an archiving web app in django. I needed to create an email verification for users at signup (registration). But I'm encountering a problem with URL redirection of the email html. Here are my codes below. Kindly requesting help?????

views.py

urls.py

account_activation_email.html

Error page

I was expecting an email to be sent and when the activation link clicked, a login page appears telling the user has been successfully activated


问:
When I try to override a core function in converse.js I get an error
I am using converse.js 7.0.6 version. I am trying to set the subject topic button to be by default hidden, currently, it is visible by default. I have investigated I need to override this function toggleSubjectHiddenState, when I try to use _converse.api.user. I get an error TypeError: Cannot read properties of undefined (reading 'user')

This is how I tried, maybe I am doing wrong something.

```<code>export const addModifyHideTopicPlugin = () => {
  window.converse.plugins.add('modify-hide-topic', {
    overrides: {
      ChatRoom: {
        toggleSubjectHiddenState: async function () {
          const _converse: any = this;
          //   const muc_jid = this.get('jid');
          const jids = await _converse.api.user.settings.get(
            'mucs_with_hidden_subject',
            [],
          );

          return _converse.toggleSubjectHiddenState
            .apply(_converse, arguments)
            .then((response: any) => {
              console.log(response, 'response');

              return response;
            });
        },
      },
    },
  });
};

</code>```

This is the toggleSubjectHiddenState function I am trying to override because this function is handleing the show topic or hide topic.

```<code>            async toggleSubjectHiddenState () {
                const muc_jid = this.get('jid');
                const jids = await api.user.settings.get('mucs_with_hidden_subject', []);
                if (jids.includes(this.get('jid'))) {
                    api.user.settings.set('mucs_with_hidden_subject', jids.filter(jid => jid !== muc_jid));
                } else {
                    api.user.settings.set('mucs_with_hidden_subject', [...jids, muc_jid]);
                }
            },
</code>```

Body:
I am using converse.js 7.0.6 version. I am trying to set the subject topic button to be by default hidden, currently, it is visible by default. I have investigated I need to override this function toggleSubjectHiddenState, when I try to use _converse.api.user. I get an error TypeError: Cannot read properties of undefined (reading 'user')

This is how I tried, maybe I am doing wrong something.

export const addModifyHideTopicPlugin = () => {
  window.converse.plugins.add('modify-hide-topic', {
    overrides: {
      ChatRoom: {
        toggleSubjectHiddenState: async function () {
          const _converse: any = this;
          //   const muc_jid = this.get('jid');
          const jids = await _converse.api.user.settings.get(
            'mucs_with_hidden_subject',
            [],
          );

          return _converse.toggleSubjectHiddenState
            .apply(_converse, arguments)
            .then((response: any) => {
              console.log(response, 'response');

              return response;
            });
        },
      },
    },
  });
};

This is the toggleSubjectHiddenState function I am trying to override because this function is handleing the show topic or hide topic.

            async toggleSubjectHiddenState () {
                const muc_jid = this.get('jid');
                const jids = await api.user.settings.get('mucs_with_hidden_subject', []);
                if (jids.includes(this.get('jid'))) {
                    api.user.settings.set('mucs_with_hidden_subject', jids.filter(jid => jid !== muc_jid));
                } else {
                    api.user.settings.set('mucs_with_hidden_subject', [...jids, muc_jid]);
                }
            },


问:
Anonymous Role in springboot project after autenticated
I have a spring boot project

When authenticating in project, after authenticating with the admin account, I encountered an anonymous role.

Can you please advise what is the reason and how to solve it?

Meanwhile, I use Angular as the front end of the project

This is my webSecurityConfig

```<code>
public class WebSecurityConfig {
    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().antMatchers("/api2/auth/**").permitAll()
                .anyRequest().authenticated();

        http.authenticationProvider(authenticationProvider());

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

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

Auth Controller:

```<code>
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping("/api2/auth")
public class AuthController {
        @Autowired
        AuthenticationManager authenticationManager;
        @Autowired
        UserRepository userRepository;
        @Autowired
        RoleRepository roleRepository;
        @Autowired
        PasswordEncoder encoder;
        @Autowired
        JwtUtils jwtUtils;

        @PostMapping("/signin")
        public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
            Authentication authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);

            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(userDetails);
            List<String> roles = userDetails.getAuthorities().stream()
                    .map(item -> item.getAuthority())
                    .collect(Collectors.toList());
            return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
                    .body(new UserInfoResponse(userDetails.getId(),
                            userDetails.getUsername(),
                            userDetails.getPassword(),
                            roles));
        }

        @PostMapping("/signup")
        public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
            if (userRepository.existsByUsername(signUpRequest.getUsername())) {
                return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
            }

            // Create new user's account
            User user = new User(signUpRequest.getUsername(),
                    encoder.encode(signUpRequest.getPassword()));
            Set<String> strRoles =  signUpRequest.getRole();
            Set<Role> roles = new HashSet<>();
            if (strRoles == null) {
                Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                        .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                roles.add(userRole);
            } else {
                strRoles.forEach(role -> {
                    if ("admin".equals(role)) {
                        Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(adminRole);

                    } else if ("user".equals(role)) {
                        Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(userRole);
                    }
                });
            }
            user.setRoles(roles);
            userRepository.save(user);
            return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
        }

        @PostMapping("/signout")
        public ResponseEntity<?> logoutUser() {
            ResponseCookie cookie = jwtUtils.getCleanJwtCookie();
            return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString())
                    .body(new MessageResponse("You've been signed out!"));
        }
    }
</code>```

result of trace:

ERROR 2540 ---  c.s.e.security.jwt.AuthEntryPointJwt     : Unauthorized error: Full authentication is required to access this resource

TRACE 2540 ---  o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match request to [Is Secure]

DEBUG 2540 ---  s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

TRACE 2540 --- o.s.security.web.FilterChainProxy        : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter...]

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking WebAsyncManagerIntegrationFilter (2/13)

TRACE 2540 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking SecurityContextPersistenceFilter (3/13)

DEBUG 2540 --- s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext

TRACE 2540 --- o.s.security.web.FilterChainProxy        : Invoking HeaderWriterFilter (4/13)

TRACE 2540 --- o.s.security.web.FilterChainProxy        : Invoking CorsFilter (5/13)

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking LogoutFilter (6/13)

TRACE 2540 ---  o.s.s.w.a.logout.LogoutFilter            : Did not match request to Or [Ant [pattern='/logout', GET], Ant [pattern='/logout', POST], Ant [pattern='/logout', PUT], Ant [pattern='/logout', DELETE]]

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking AuthTokenFilter (7/13)

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking RequestCacheAwareFilter (8/13)

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking SecurityContextHolderAwareRequestFilter (9/13)

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking AnonymousAuthenticationFilter (10/13)

TRACE 2540 ---[ o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]]

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking SessionManagementFilter (11/13)

TRACE 2540 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking ExceptionTranslationFilter (12/13)

TRACE 2540 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking FilterSecurityInterceptor (13/13)

TRACE 2540 --- [nio-8080-exec-2] edFilterInvocationSecurityMetadataSource : Did not match request to Ant [pattern='/api2/auth/**'] - [permitAll] (1/2)

TRACE 2540 ---o.s.s.w.a.i.FilterSecurityInterceptor    : Did not re-authenticate AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]] before authorizing

TRACE 2540 ---  o.s.s.w.a.expression.WebExpressionVoter  : Voted to deny authorization

TRACE 2540 ---  o.s.s.w.a.i.FilterSecurityInterceptor    : Failed to authorize filter invocation [GET /product/slider] with attributes [authenticated] using AffirmativeBased [DecisionVoters=[org.springframework.security.web.access.expression.WebExpressionVoter@1dcad16f], AllowIfAllAbstainDecisions=false]

TRACE 2540 ---  o.s.s.w.a.ExceptionTranslationFilter     : Sending AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]] to authentication entry point since access is denied

Added

ERROR 8184 ---  c.s.e.security.jwt.AuthEntryPointJwt     : Unauthorized error: Full authentication is required to access this resource >

TRACE 8184 --- o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match request to [Is Secure] >

DEBUG 8184 --- s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

Project classes:

Thank you for your time

I tried many ways from stackoverflow and other places to solve this problem, but I didn't get any results.

Body:
I have a spring boot project

When authenticating in project, after authenticating with the admin account, I encountered an anonymous role.

Can you please advise what is the reason and how to solve it?

Meanwhile, I use Angular as the front end of the project

This is my webSecurityConfig

public class WebSecurityConfig {
    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().antMatchers("/api2/auth/**").permitAll()
                .anyRequest().authenticated();

        http.authenticationProvider(authenticationProvider());

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

Auth Controller:

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping("/api2/auth")
public class AuthController {
        @Autowired
        AuthenticationManager authenticationManager;
        @Autowired
        UserRepository userRepository;
        @Autowired
        RoleRepository roleRepository;
        @Autowired
        PasswordEncoder encoder;
        @Autowired
        JwtUtils jwtUtils;

        @PostMapping("/signin")
        public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
            Authentication authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);

            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(userDetails);
            List<String> roles = userDetails.getAuthorities().stream()
                    .map(item -> item.getAuthority())
                    .collect(Collectors.toList());
            return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
                    .body(new UserInfoResponse(userDetails.getId(),
                            userDetails.getUsername(),
                            userDetails.getPassword(),
                            roles));
        }

        @PostMapping("/signup")
        public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
            if (userRepository.existsByUsername(signUpRequest.getUsername())) {
                return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
            }

            // Create new user's account
            User user = new User(signUpRequest.getUsername(),
                    encoder.encode(signUpRequest.getPassword()));
            Set<String> strRoles =  signUpRequest.getRole();
            Set<Role> roles = new HashSet<>();
            if (strRoles == null) {
                Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                        .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                roles.add(userRole);
            } else {
                strRoles.forEach(role -> {
                    if ("admin".equals(role)) {
                        Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(adminRole);

                    } else if ("user".equals(role)) {
                        Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(userRole);
                    }
                });
            }
            user.setRoles(roles);
            userRepository.save(user);
            return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
        }

        @PostMapping("/signout")
        public ResponseEntity<?> logoutUser() {
            ResponseCookie cookie = jwtUtils.getCleanJwtCookie();
            return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString())
                    .body(new MessageResponse("You've been signed out!"));
        }
    }

result of trace:

ERROR 2540 ---  c.s.e.security.jwt.AuthEntryPointJwt     : Unauthorized error: Full authentication is required to access this resource

TRACE 2540 ---  o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match request to [Is Secure]

DEBUG 2540 ---  s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

TRACE 2540 --- o.s.security.web.FilterChainProxy        : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter...]

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking WebAsyncManagerIntegrationFilter (2/13)

TRACE 2540 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking SecurityContextPersistenceFilter (3/13)

DEBUG 2540 --- s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext

TRACE 2540 --- o.s.security.web.FilterChainProxy        : Invoking HeaderWriterFilter (4/13)

TRACE 2540 --- o.s.security.web.FilterChainProxy        : Invoking CorsFilter (5/13)

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking LogoutFilter (6/13)

TRACE 2540 ---  o.s.s.w.a.logout.LogoutFilter            : Did not match request to Or [Ant [pattern='/logout', GET], Ant [pattern='/logout', POST], Ant [pattern='/logout', PUT], Ant [pattern='/logout', DELETE]]

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking AuthTokenFilter (7/13)

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking RequestCacheAwareFilter (8/13)

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking SecurityContextHolderAwareRequestFilter (9/13)

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking AnonymousAuthenticationFilter (10/13)

TRACE 2540 ---[ o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]]

TRACE 2540 ---  o.s.security.web.FilterChainProxy        : Invoking SessionManagementFilter (11/13)

TRACE 2540 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking ExceptionTranslationFilter (12/13)

TRACE 2540 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking FilterSecurityInterceptor (13/13)

TRACE 2540 --- [nio-8080-exec-2] edFilterInvocationSecurityMetadataSource : Did not match request to Ant [pattern='/api2/auth/**'] - [permitAll] (1/2)

TRACE 2540 ---o.s.s.w.a.i.FilterSecurityInterceptor    : Did not re-authenticate AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]] before authorizing

TRACE 2540 ---  o.s.s.w.a.expression.WebExpressionVoter  : Voted to deny authorization

TRACE 2540 ---  o.s.s.w.a.i.FilterSecurityInterceptor    : Failed to authorize filter invocation [GET /product/slider] with attributes [authenticated] using AffirmativeBased [DecisionVoters=[org.springframework.security.web.access.expression.WebExpressionVoter@1dcad16f], AllowIfAllAbstainDecisions=false]

TRACE 2540 ---  o.s.s.w.a.ExceptionTranslationFilter     : Sending AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]] to authentication entry point since access is denied

Added

ERROR 8184 ---  c.s.e.security.jwt.AuthEntryPointJwt     : Unauthorized error: Full authentication is required to access this resource >

TRACE 8184 --- o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match request to [Is Secure] >

DEBUG 8184 --- s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

Project classes:

Thank you for your time

I tried many ways from stackoverflow and other places to solve this problem, but I didn't get any results.


问:
Inotifywait not showing all events
I have this simple python program in script.py.

```<code>import os

os.mkdir('abc')

with open('abc/readme.txt', 'w') as f:
  f.write('Sample text file')

os.rename('abc', 'new_folder')
</code>```

Now, on a separate terminal, I ran this inotifywait command. This monitors the current directory recursively.
inotifywait -qrme modify,attrib,move,create,delete,access .

Then while monitoring, I ran the python program above which gives me these events:

```<code>./ ACCESS script.py
./ ACCESS script.py
./ ACCESS,ISDIR
./ CREATE,ISDIR abc
./ MOVED_FROM,ISDIR abc
./ MOVED_TO,ISDIR new_folder
./ ACCESS,ISDIR new_folder
./ ACCESS,ISDIR
./ ACCESS,ISDIR new_folder
./new_folder/ ACCESS,ISDIR
./ ACCESS,ISDIR new_folder
./new_folder/ ACCESS,ISDIR
./ ACCESS,ISDIR
./ ACCESS,ISDIR
./ ACCESS,ISDIR
</code>```

As you have observed, the create and modify events for abc/readme.txt did not show up.

Now, I understand that this is due to race conditions as stated in their docs. However, my question is, is there a workaround for this?

Assumptions and constraints in this problem:

Strictly, only one level of directories from the root directory are created. Meaning, /folder1/folder2/ is not possible.

I cannot modify the program.

I know what directories are going to be created in the root directory.

Title: Inotifywait not showing all events

Body:
I have this simple python program in script.py.

import os

os.mkdir('abc')

with open('abc/readme.txt', 'w') as f:
  f.write('Sample text file')

os.rename('abc', 'new_folder')

Now, on a separate terminal, I ran this inotifywait command. This monitors the current directory recursively.
inotifywait -qrme modify,attrib,move,create,delete,access .

Then while monitoring, I ran the python program above which gives me these events:

./ ACCESS script.py
./ ACCESS script.py
./ ACCESS,ISDIR
./ CREATE,ISDIR abc
./ MOVED_FROM,ISDIR abc
./ MOVED_TO,ISDIR new_folder
./ ACCESS,ISDIR new_folder
./ ACCESS,ISDIR
./ ACCESS,ISDIR new_folder
./new_folder/ ACCESS,ISDIR
./ ACCESS,ISDIR new_folder
./new_folder/ ACCESS,ISDIR
./ ACCESS,ISDIR
./ ACCESS,ISDIR
./ ACCESS,ISDIR

As you have observed, the create and modify events for abc/readme.txt did not show up.

Now, I understand that this is due to race conditions as stated in their docs. However, my question is, is there a workaround for this?

Assumptions and constraints in this problem:

Strictly, only one level of directories from the root directory are created. Meaning, /folder1/folder2/ is not possible.

I cannot modify the program.

I know what directories are going to be created in the root directory.


问:
linearize if then implication with system of inequations in the condition
While working on some linear program I had the following problem:

t is time index
s is a time decision variable
p is a time decision variable
q is a Boolean decision variable
x[t] is a Boolean decision variable

I want to make sure x[t] = 1 while q = 1 and t is in the interval of [s, s+p]

I am expecting to have this condition in a linear programming form. Summing x over the interval and making sure it is equal to p is not helpful since not linear.

so what I tried is the following:

if q>=1 and t>=s and t<= s + p then x=1  is equivalent to (q < 1 or t < s or t> p + s) and x >= 1

I would like to know if it is correct what I stated and if there is another way to linearize it such as I avoid inserting boolean variables and constants.


问:
React-Native-Geolocation-Service not giving appropiate latitude and longitude
The latitude and longitude provided by React-native-geolocation-service is not changing even changing location from Noida to Ghaziabad.

I have create two different Alerts one in getlocation method and another in watchposition method. The current Alert (that is in getLocation method) and changed alert (that is present in watchposition method) I get to know that the latitude and longitude provided by React-native-geolocation-service is not as per accuracy.
Here is the method that are working for geolocation to getCurrentPosition and to watchPosition whenever user changes position.

```<code>const getOneTimeLocation = () => {
    setLocationStatus("Getting Location ...");
    Geolocation.getCurrentPosition(
      (position) => {
        setLocationStatus("You are Here");
        Alert.alert("current"," latitude "+ JSON.stringify(position.coords.latitude)+ " Longitude "+ JSON.stringify(position.coords.longitude))
        setCurrentLatitude(JSON.stringify(position.coords.latitude));
        setCurrentLongitude(JSON.stringify(position.coords.longitude));
        // weather(false,position.coords.latitude,position.coords.longitude)
        console.log(currentLatitude,currentLongitude,"dekhooooo")
        // setCurrentLatitude(currentLatitude);
      },
      (error) => {
        setLocationStatus(error.message);
        Alert.alert(error.message);
      },
      {
        enableHighAccuracy: true,
        timeout: 30000,
        maximumAge: 1000,
      }
    );
  };

``````````````````````````````````````````````````````````````````````````````````````````````````````````
  const watchPositionMethod = () => {
    watchID = Geolocation.watchPosition(
      (position) => {
        setLocationStatus("You are Here");
        console.log(position);
        Alert.alert("Changed"," latitude "+ JSON.stringify(position.coords.latitude)+" Longitude "+ JSON.stringify(position.coords.longitude))
        setCurrentLatitude(JSON.stringify(position.coords.latitude));
        setCurrentLongitude(JSON.stringify(position.coords.longitude));
        // Alert.alert()
      },
      (error) => {
        setLocationStatus(error.message);
        Alert.alert(error.message);
      },
      {
        enableHighAccuracy: true,
        maximumAge: 1000,
      }
    );
  };
`````````````````````````````````````````````````````````````````````````````````````````````````````````
</code>```

Body:
The latitude and longitude provided by React-native-geolocation-service is not changing even changing location from Noida to Ghaziabad.

I have create two different Alerts one in getlocation method and another in watchposition method. The current Alert (that is in getLocation method) and changed alert (that is present in watchposition method) I get to know that the latitude and longitude provided by React-native-geolocation-service is not as per accuracy.
Here is the method that are working for geolocation to getCurrentPosition and to watchPosition whenever user changes position.

const getOneTimeLocation = () => {
    setLocationStatus("Getting Location ...");
    Geolocation.getCurrentPosition(
      (position) => {
        setLocationStatus("You are Here");
        Alert.alert("current"," latitude "+ JSON.stringify(position.coords.latitude)+ " Longitude "+ JSON.stringify(position.coords.longitude))
        setCurrentLatitude(JSON.stringify(position.coords.latitude));
        setCurrentLongitude(JSON.stringify(position.coords.longitude));
        // weather(false,position.coords.latitude,position.coords.longitude)
        console.log(currentLatitude,currentLongitude,"dekhooooo")
        // setCurrentLatitude(currentLatitude);
      },
      (error) => {
        setLocationStatus(error.message);
        Alert.alert(error.message);
      },
      {
        enableHighAccuracy: true,
        timeout: 30000,
        maximumAge: 1000,
      }
    );
  };

``````````````````````````````````````````````````````````````````````````````````````````````````````````
  const watchPositionMethod = () => {
    watchID = Geolocation.watchPosition(
      (position) => {
        setLocationStatus("You are Here");
        console.log(position);
        Alert.alert("Changed"," latitude "+ JSON.stringify(position.coords.latitude)+" Longitude "+ JSON.stringify(position.coords.longitude))
        setCurrentLatitude(JSON.stringify(position.coords.latitude));
        setCurrentLongitude(JSON.stringify(position.coords.longitude));
        // Alert.alert()
      },
      (error) => {
        setLocationStatus(error.message);
        Alert.alert(error.message);
      },
      {
        enableHighAccuracy: true,
        maximumAge: 1000,
      }
    );
  };
`````````````````````````````````````````````````````````````````````````````````````````````````````````


问:
Unity gameobject turns black while adding point light
hello guys i have problem, while i set the value of exposure to zero then as usual everything turns black but then i added the point light and all the gameobjects works fine but the table turns black and i used the Lit shadergraph. Now when i change from opaque to transparent then it doesn't works in this point light but when i change it back to opaque in shader graph it works fine also in point light but i need the table glass to be alpha therefore i used alpha in shader graph.

before and after transparent in shader graph images and changing the exposure of skybox to 1 are given below and before and after changing.

Shader Graph:

Table Before:

Table after:

SkyBox after:

SkyBox before:


问:
how can i add the data to database after select the data? How to make the handleCategory and handleChange together?
i have 2 select box and both are related, how can i add the data to database after select the data? How to make the handleCategory and handleChange together ?</p>
```<code>const handleCategory = (id) => {
    const dt = optionsSubCategory.filter(x => x.categoryId === id);
    setSubcategory(dt);
  }const handleChange = (e) => {
    setProduct((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };
</code>```

Body:
i have 2 select box and both are related, how can i add the data to database after select the data? How to make the handleCategory and handleChange together ?

const handleCategory = (id) => {
    const dt = optionsSubCategory.filter(x => x.categoryId === id);
    setSubcategory(dt);
  }const handleChange = (e) => {
    setProduct((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };


问:
VS code SCM and Explorer not showing the green color , U , M keywords related to Git
For my project , I installed Git . and entered git init actually to the parent folder.then suddenly all my files in Project explorer Tabs changed to green color. So to undo it i entered this cmd rm -rf .git in my terminal.
So after refreshing the green color went away, Then I went to my project folder and then typed git init it created a repository but the green color in file explorer is not showing .

Even I edit SCM section , It is not showing any changes or commits .

Please provide solution for making these green indicators to be visible

I was expecting to get the green color indication on my explorer.


问:
Display nodes in swagger whose values are returning null
I have following JSON format and data, and in few nodes I am getting null values. Check below JSON data. In Swagger that nodes are not displaying whose values are null in get request.

For example below, IsTest1 and IsTest2 are not displaying in Get request in swagger response. But I like to display it in JSON response, so any one know how can I do that.

```<code>{
    "IsTest1": null,
    "IsTest2": null,
    "Client3": "client-data",
    "Status": 3
}
</code>```

In swagger it is returning only below data but I want all nodes also whose values are null.

```<code>{
  "data": {
    "client3" : "client-data"
      }
    "status": 3
  },
  "statusCode": 200,
  "successMessage": "Successful"
}
</code>```

I am using .Net-Core

Body:
I have following JSON format and data, and in few nodes I am getting null values. Check below JSON data. In Swagger that nodes are not displaying whose values are null in get request.

For example below, IsTest1 and IsTest2 are not displaying in Get request in swagger response. But I like to display it in JSON response, so any one know how can I do that.

{
    "IsTest1": null,
    "IsTest2": null,
    "Client3": "client-data",
    "Status": 3
}

In swagger it is returning only below data but I want all nodes also whose values are null.

{
  "data": {
    "client3" : "client-data"
      }
    "status": 3
  },
  "statusCode": 200,
  "successMessage": "Successful"
}

I am using .Net-Core


问:
when gradle testNG groups cmd is triggered it shows null pointer
when gradle clean test -P testGroups="test" cmd is used to run tests which has test in groups. I get null pointer exception not sure what is wrong,  can someone help here i am stuck for days here

```<code>FAILED: BotAttributesTest
java.lang.NullPointerException
    at sanityTests.BotAttributesTest.BotAttributesTest(BotAttributesTest.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

it fails at logger line not sure why?

logger declaration below

  public ExtentSparkReporter htmlReporter;
     public static ExtentReports extent;
     public  ExtentTest logger;
     public static WebDriver  wd;

    @BeforeMethod
    public void logger(Method testMethod){
        logger = extent.createTest(testMethod.getName());

        WebDriverManager.chromedriver().setup();
</code>```

Body:
when gradle clean test -P testGroups="test" cmd is used to run tests which has test in groups. I get null pointer exception not sure what is wrong,  can someone help here i am stuck for days here

FAILED: BotAttributesTest
java.lang.NullPointerException
    at sanityTests.BotAttributesTest.BotAttributesTest(BotAttributesTest.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

it fails at logger line not sure why?

logger declaration below

  public ExtentSparkReporter htmlReporter;
     public static ExtentReports extent;
     public  ExtentTest logger;
     public static WebDriver  wd;

    @BeforeMethod
    public void logger(Method testMethod){
        logger = extent.createTest(testMethod.getName());

        WebDriverManager.chromedriver().setup();


问:
Why are different numbers all ending on .225 rounded differently in python?

>>> print('result:%9.2f' % 1111.225)
result:  1111.22
>>> print('result:%9.2f' % 11111.225)
result: 11111.23
>>> print('result:%9.2f' % 111.225)
result:   111.22
>>> print('result:%9.2f' % 11.225)
result:    11.22
>>> print('result:%9.2f' % 1.225)
result:     1.23
```

In the above example, you can see that 111.225 and 11.225 are rounded downwards, while the others are rounded upwards. As they all end on .225, one would expect them all to be rounded upwards to .23. Why does the rounding of the numbers differ?

Body:
>>> print('result:%9.2f' % 1111.225)
result:  1111.22
>>> print('result:%9.2f' % 11111.225)
result: 11111.23
>>> print('result:%9.2f' % 111.225)
result:   111.22
>>> print('result:%9.2f' % 11.225)
result:    11.22
>>> print('result:%9.2f' % 1.225)
result:     1.23

In the above example, you can see that 111.225 and 11.225 are rounded downwards, while the others are rounded upwards. As they all end on .225, one would expect them all to be rounded upwards to .23. Why does the rounding of the numbers differ?


问:
SSRS Lookup is not returning all matching Records
I have 2 Datasets in my SSRS report
DS1 is getting data from MSSQL with column ID(varchar)
DS2 is getting data from PGSQL with column ID(uuid)
I have type cast the datatype in my data set and trimmed the extra space as well.
Sample Data from DS1 of type varchar
9be8bf09-927b-4e04-af74-9d523f125d87
6058eb2e-7884-4220-a719-a5262744f34b

Sample Data from DS2 of type uuid
b3e2c869-7569-4b6e-95e4-f42a0e99f5cf
I have all the records from DS1 in DS2

in the attached image, the blank rows coming where match is not happened but I do have matching value in DS2

Lookup expression-
=Lookup(Fields!ID.Value, Fields!ID.Value, "From Wallet DB","PGSQL")

Even though I have all the matching records in DS2 but still getting few values in my output.

My output is expecting "From Wallet DB" for all the rows


问:
How to consume a dead letter queue in AWS SQS using Justsaying
I'm working with SQS in my application. I have the following configuration.

```<code>justSaying
        .WithSqsTopicSubscriber()
        .IntoQueue(_busNamingConvention.QueueName())
        .ConfigureSubscriptionWith(x =>
        {
            x.VisibilityTimeoutSeconds = 60;
            x.RetryCountBeforeSendingToErrorQueue = 3;
        })
        .WithMessageHandler<MyMessage>(_handlerResolver)
        .WithSqsMessagePublisher<MyMessage>(config => config.QueueName = _busNamingConvention.QueueName());
</code>```

So, there will be 3 re-attempts before the messages gets to Dead Letter Queue. I want to consume this dead letter queue and process the message separately. In essence, I want to create a handler to deal with the messages in the DLQ.

I'm not sure if this is possible or SQS is not intended to be used this way. Please post if this is possible and if yes, is it okay to do this or is this an anti pattern.

Body:
I'm working with SQS in my application. I have the following configuration.

justSaying
        .WithSqsTopicSubscriber()
        .IntoQueue(_busNamingConvention.QueueName())
        .ConfigureSubscriptionWith(x =>
        {
            x.VisibilityTimeoutSeconds = 60;
            x.RetryCountBeforeSendingToErrorQueue = 3;
        })
        .WithMessageHandler<MyMessage>(_handlerResolver)
        .WithSqsMessagePublisher<MyMessage>(config => config.QueueName = _busNamingConvention.QueueName());

So, there will be 3 re-attempts before the messages gets to Dead Letter Queue. I want to consume this dead letter queue and process the message separately. In essence, I want to create a handler to deal with the messages in the DLQ.

I'm not sure if this is possible or SQS is not intended to be used this way. Please post if this is possible and if yes, is it okay to do this or is this an anti pattern.


问:
dial tcp 127.0.0.1:3333: can't assign requested address, getting this error while hitting http request concurrently for 40000 iterations
I am getting error:
dial tcp 127.0.0.1:3333: can't assign requested address
whenever i try to hit http request concurrently using go routines for 40000 iterations,

it was working fine till 20-30000 iterations,
Here is the code I am trying to run:

```<code>func TestHttp(c *gin.Context) {
    limit, _ := strconv.Atoi(c.Param("limit"))
    for i := 1; i <= limit; i++ {
        url := "http://hostname/merchant" + strconv.Itoa(i) + "/print-test?p=" + strconv.Itoa(i)
        go MakeRequest2(url, i)
    }
}

/*

 * Function to hit url with get method and close the response body
 */
func MakeRequest2(url string, i int) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    req.Close = true
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
}

func PrintTest(c *gin.Context) {
    a := make(map[string]int)
    for i := 1; i <= 10; i++ {
        a[strconv.Itoa(i)] = i
    }
    fmt.Println(a)
}

</code>```

I am getting this output:

```<code>Get "http://hostname/merchant34096/print-test?p=34096": dial tcp hostname: connect: cannot assign requested address >
</code>```

I am expecting to run this code for 1 million iterations concurrently.

Body:
I am getting error:
dial tcp 127.0.0.1:3333: can't assign requested address
whenever i try to hit http request concurrently using go routines for 40000 iterations,

it was working fine till 20-30000 iterations,
Here is the code I am trying to run:

func TestHttp(c *gin.Context) {
    limit, _ := strconv.Atoi(c.Param("limit"))
    for i := 1; i <= limit; i++ {
        url := "http://hostname/merchant" + strconv.Itoa(i) + "/print-test?p=" + strconv.Itoa(i)
        go MakeRequest2(url, i)
    }
}

/*

 * Function to hit url with get method and close the response body
 */
func MakeRequest2(url string, i int) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    req.Close = true
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
}

func PrintTest(c *gin.Context) {
    a := make(map[string]int)
    for i := 1; i <= 10; i++ {
        a[strconv.Itoa(i)] = i
    }
    fmt.Println(a)
}

I am getting this output:

Get "http://hostname/merchant34096/print-test?p=34096": dial tcp hostname: connect: cannot assign requested address >

I am expecting to run this code for 1 million iterations concurrently.


问:
Spring boot admin error with application home page URI
I have a Eureka application client and I am trying to register it with Spring Boot Admin.
All is well, but the home page URI always gets the path from the eureka service URI, not from
eureka.instance.home-page-url

This is critical because my application has server.servlet.context-path=myApp

and result link is invalid for example I need https://localhost:8080/myApp but Spring Boot Admin show just https://localhost:8080


Title: Employee monthly report including leaves and working days

Body:
Consider one week report start Dates: from 11/1/2022 to 11/5/2022

Table : Timesheet

timesheet_id
start_time_server
Login_by
user_id

1234
11/1/2022
16:20:00 AM
jon 101

1235
11/1/2022
12:20:100 AM
tom 102

1236
11/2/2022
18:40:00 AM
tom 102

1237
11/3/2022
18:40:00 AM
tom 102

Table : Leaves

timesheet_id
Leave_applied_date
Leave_start_time_server
user_id
user_name

1234
11/1/2022
16:20:00 AM #########
101
jon

1234
11/1/2022
16:20:00 AM #########
101
jon

1234
11/1/2022
16:20:00 AM #########
102
jon

1234
11/1/2022
16:20:00 AM #########
103
jon

1237
11/3/2022
18:40:00 AM #########
102
tom

1237
11/3/2022
18:40:00 AM #########
102
tom

final output DailyWorkReport :

user_name
11/1/2022
11/2/2022
11/3/2022
11/4/2022
11/5/2022

jon
8
Leave
Leave
Leave
Leave

tom
8
8
8
Leave
Leave

Please help how i can achieve this final Dailyworkreprot.


问:
Split a text file based on a specific word
I have two text file like this:

list.txt

```<code>file 'aavr-001-1.mp4'
file 'aavr-001-2.mp4'
file 'aavr-001-3.mp4'
file 'ccr-010-1.mp4'
file 'ccr-010-2.mp4'
file 'ccr-010-3.mp4'
file 'vvvw2-031-1.mp4'
file 'vvvw2-031-2.mp4'
</code>```

code.txt

```<code>aavr-001
ccr-010
vvvw2-031
</code>```

My code:

```<code>for f in $(cat code.txt); do
   s=$(echo $f)
   cat list.txt | sed '/$s/!d' >$s.txt
done
</code>```

I was expecting to get these three files with the following content:

aavr-001.txt

```<code>file 'aavr-001-1.mp4'
file 'aavr-001-2.mp4'
file 'aavr-001-3.mp4'
</code>```

ccr-010.txt

```<code>file 'ccr-010-1.mp4'
file 'ccr-010-2.mp4'
file 'ccr-010-3.mp4'
</code>```

vvvm2-031.txt

```<code>file 'vvvw2-031-1.mp4'
file 'vvvw2-031-2.mp4'
</code>```

But in the end I could only get three blank files: aavr-001.txt ccr-010.txt vvvw2-031.txt, not any content in them.

What should I do to fix the problem?

p.s. If I only input like cat list.txt | sed '/aavr-001/!d' >aavr-001.txt, I can get the result I want

Body:
I have two text file like this:

list.txt

file 'aavr-001-1.mp4'
file 'aavr-001-2.mp4'
file 'aavr-001-3.mp4'
file 'ccr-010-1.mp4'
file 'ccr-010-2.mp4'
file 'ccr-010-3.mp4'
file 'vvvw2-031-1.mp4'
file 'vvvw2-031-2.mp4'

code.txt

aavr-001
ccr-010
vvvw2-031

My code:

for f in $(cat code.txt); do
   s=$(echo $f)
   cat list.txt | sed '/$s/!d' >$s.txt
done

I was expecting to get these three files with the following content:

aavr-001.txt

file 'aavr-001-1.mp4'
file 'aavr-001-2.mp4'
file 'aavr-001-3.mp4'

ccr-010.txt

file 'ccr-010-1.mp4'
file 'ccr-010-2.mp4'
file 'ccr-010-3.mp4'

vvvm2-031.txt

file 'vvvw2-031-1.mp4'
file 'vvvw2-031-2.mp4'

But in the end I could only get three blank files: aavr-001.txt ccr-010.txt vvvw2-031.txt, not any content in them.

What should I do to fix the problem?

p.s. If I only input like cat list.txt | sed '/aavr-001/!d' >aavr-001.txt, I can get the result I want


问:
(matplotlib)Avoiding AnchoredText overlapping
My goal is to draw scatter plot with AnchoredText. The graph (1) below is as expected.
But the graph (2) shows the overlapped AnchoredTexts. How to make it non overlapped texts?

My data and function for drawing is:

```<code>import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.offsetbox import AnchoredText

data=pd.DataFrame({'val':[1, 1, 2, 2.1, 2, 2.5, 2.3],'site':['a','a','a','b','b','b','b'],
      'X2':[4, 5 ,6 ,10, 10, 11, 11], 'X3':[100,100,200,200,200,300,300],
     'applydate':[1101,1102,1201,1202,1204,1204,1204],
     'X1':['b','b','h','b','b','h','h'] })

def my_scatter(x,y, **kwargs):
     plt.scatter(x=x, y=y,**kwargs)
     mx = np.mean(x);my= np.mean(y);
     strText='AVG_H:'+str(np.round(mx,3))+'\nAVG_V:'+str(np.round(my,3))
     textbox = AnchoredText(strText, loc='lower right', frameon=False,)
     plt.gca().add_artist(textbox)
</code>```

The graph (1), which is ok.

```<code>g = sns.FacetGrid(data,col='site',height=3)
g.map(my_scatter, "X2", "val",s=100, alpha=.5)
g.add_legend()
</code>```

And the graph (2), which shows overlapped texts.(※The problem is that statistics for blue dots and orage dots are overlapped)

```<code>g = sns.FacetGrid(data,col='site',height=3, hue='X1') # I've assigned column X1 to hue variable.
g.map(my_scatter, "X2", "val",s=100, alpha=.5)
g.add_legend()
</code>```

Body:
My goal is to draw scatter plot with AnchoredText. The graph (1) below is as expected.
But the graph (2) shows the overlapped AnchoredTexts. How to make it non overlapped texts?

My data and function for drawing is:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.offsetbox import AnchoredText

data=pd.DataFrame({'val':[1, 1, 2, 2.1, 2, 2.5, 2.3],'site':['a','a','a','b','b','b','b'],
      'X2':[4, 5 ,6 ,10, 10, 11, 11], 'X3':[100,100,200,200,200,300,300],
     'applydate':[1101,1102,1201,1202,1204,1204,1204],
     'X1':['b','b','h','b','b','h','h'] })

def my_scatter(x,y, **kwargs):
     plt.scatter(x=x, y=y,**kwargs)
     mx = np.mean(x);my= np.mean(y);
     strText='AVG_H:'+str(np.round(mx,3))+'\nAVG_V:'+str(np.round(my,3))
     textbox = AnchoredText(strText, loc='lower right', frameon=False,)
     plt.gca().add_artist(textbox)

The graph (1), which is ok.

g = sns.FacetGrid(data,col='site',height=3)
g.map(my_scatter, "X2", "val",s=100, alpha=.5)
g.add_legend()

And the graph (2), which shows overlapped texts.(※The problem is that statistics for blue dots and orage dots are overlapped)

g = sns.FacetGrid(data,col='site',height=3, hue='X1') # I've assigned column X1 to hue variable.
g.map(my_scatter, "X2", "val",s=100, alpha=.5)
g.add_legend()


问:
How to feed a long text(to keep the memory from previous sentences) as input for huggingface's transformers model on translation task?
I'm trying to translate a long sentence from English to Spanish using Huggingface's transformers model on translation task. And often the models have a max limit of input text length. However, I'd like the model to see as many previous sentences as possible so that it wisely picks the translation words. How could I do that using the transformers model?</p>


问:
using "data" with jquery tempates and "each"
I'm building web content using jquery templates and json and I'm looking for a clean(er) way to get the json data associated with a click event on content that was built using those templates. The tmplItem().data that is stored is the array of objects for that template. When an item in that list is clicked, I want to pass just the json data for that item to a click event handler.

Currently I'm doing this:

```<code><script id="ribbonTemplate" type="x-jquery-tmpl">
{{each(i, item) ribbon_data}}
   <img id='${i}' src="${thumbnail_url}" alt="${content_url}"/>
{{/each}}
</script>
</code>```

and

```<code>    $(ribbonDiv).live('click', function(e){

       var clickItem = $(e.target);
       var tmplItem = clickItem.tmplItem();
       var imgId = clickItem.attr('id');
       var jsonBackingData = tmplItem.data['ribbon_data'][imgId];

       clickEvent(jsonBackingData);
    });
</code>```

This works but it seems a bit clunky. Is there a way that doesn't depend on using the id selector?

ContentLicense: CC BY-SA 3.0

Body:
I'm building web content using jquery templates and json and I'm looking for a clean(er) way to get the json data associated with a click event on content that was built using those templates. The tmplItem().data that is stored is the array of objects for that template. When an item in that list is clicked, I want to pass just the json data for that item to a click event handler.

Currently I'm doing this:

and

    $(ribbonDiv).live('click', function(e){

       var clickItem = $(e.target);
       var tmplItem = clickItem.tmplItem();
       var imgId = clickItem.attr('id');
       var jsonBackingData = tmplItem.data['ribbon_data'][imgId];

       clickEvent(jsonBackingData);
    });

This works but it seems a bit clunky. Is there a way that doesn't depend on using the id selector?


问:
Hibernate dynamic query performance issue
We are using hibernate dynamic queries in our application and observed that some performance issues when some load is put on the server. From a monitoring tool we saw that the time for hibernate queries is around 3 times the execution of JDBC queries executed under the hood.

Breakdown:              total(ms)  count
http request            22767        1
servlet dispatch       22648        1
jsp render            21578        1
hibernate queries    19760        32
jdbc queries         5989        32

We are using Oracle database server and observed high CPU usage. My understanding is queries are spending more time on CPU that's why it is higher. But not able to understand this huge time difference between hibernate and jdbc timings


问:
Jquery typeahead template selection on custom button click
I wanted to make selection of jQuery typeahead template on custom button click. But when I click on rendered options anywhere it is automatically get selected.

I have below example

```<code>$.typeahead({
            input: '.classSearchContainer',
            name: 'my_name',
            valueKey: 'classSubmit',
            minLength: 3,
            maxItem: 200,
            order: "asc",
            dynamic: true,
            delay: 300,
            hint:true,
            highlight:true,
            template: function (query, data) {
                var sLabelColor = "";
                if (data.iType == 1) {
                    sLabelColor = "badge badge-info";
                } else if (data.iType == 2) {
                    sLabelColor = "badge badge-success";
                } else if (data.iType == 3) {
                    sLabelColor = "badge badge-warning";
                } else if (data.iType == 4) {
                    sLabelColor = "badge badge-primary";
                }

                return `
                    <div class="row-fluid">
                        <strong>${data.sItemName}</strong><label class="${sLabelColor} pull-right">${data.sType}</label>
                    </div>
                    <select class="classSelectBox classStrength">
                        <option value="500mg">500mg</option>
                        <option value="250mg">250mg</option>
                        <option value="100mg">100mg</option>
                    </select>
                    <a class="btn btn-success btn-small classSubmit" value="Submit">Submit</a>
                `;
            },
            emptyTemplate: function (query) {
                if (query.length > 0) {
                    return `
                        No results found for <strong>${query}</strong>.
                    `;
                }
            },
            source: {
                details: {
                    display: [
                        "sItemName",
                        "sType"
                    ],
                    ajax: function (query) {
                        return {
                            type: "get",
                            url: "apiv2/types",
                            data: {
                                term: "{{query}}"
                            },
                            callback: {
                                done: function (data) {
                                    var details = [];

                                    $.map(data, function(details){
                                        var group;
                                        group = {
                                            iType: details.iType,
                                            sType: details.sType,
                                            iItemID: details.iItemID,
                                            sItemName: details.sItemName,
                                        };

                                        details.push(group);
                                    });

                                    return details;
                                }
                            }
                        }
                    }
                }
            },
        }).on('typeahead:selected', function(event, selection) {
            console.log(selection)
        });
</code>```

Currently when I try to select any option by modifying it & select it after click on button "Submit", it is not working & template selection by default working when I click on anywhere inside option details. I wanted the template selected only when I click on Submit button.

Body:
I wanted to make selection of jQuery typeahead template on custom button click. But when I click on rendered options anywhere it is automatically get selected.

I have below example

$.typeahead({
            input: '.classSearchContainer',
            name: 'my_name',
            valueKey: 'classSubmit',
            minLength: 3,
            maxItem: 200,
            order: "asc",
            dynamic: true,
            delay: 300,
            hint:true,
            highlight:true,
            template: function (query, data) {
                var sLabelColor = "";
                if (data.iType == 1) {
                    sLabelColor = "badge badge-info";
                } else if (data.iType == 2) {
                    sLabelColor = "badge badge-success";
                } else if (data.iType == 3) {
                    sLabelColor = "badge badge-warning";
                } else if (data.iType == 4) {
                    sLabelColor = "badge badge-primary";
                }

                return `

                        ${data.sItemName}${data.sType}

                    <select class="classSelectBox classStrength">
                        <option value="500mg">500mg</option>
                        <option value="250mg">250mg</option>
                        <option value="100mg">100mg</option>
                    </select>
                    Submit
                `;
            },
            emptyTemplate: function (query) {
                if (query.length > 0) {
                    return `
                        No results found for ${query}.
                    `;
                }
            },
            source: {
                details: {
                    display: [
                        "sItemName",
                        "sType"
                    ],
                    ajax: function (query) {
                        return {
                            type: "get",
                            url: "apiv2/types",
                            data: {
                                term: "{{query}}"
                            },
                            callback: {
                                done: function (data) {
                                    var details = [];

                                    $.map(data, function(details){
                                        var group;
                                        group = {
                                            iType: details.iType,
                                            sType: details.sType,
                                            iItemID: details.iItemID,
                                            sItemName: details.sItemName,
                                        };

                                        details.push(group);
                                    });

                                    return details;
                                }
                            }
                        }
                    }
                }
            },
        }).on('typeahead:selected', function(event, selection) {
            console.log(selection)
        });

Currently when I try to select any option by modifying it & select it after click on button "Submit", it is not working & template selection by default working when I click on anywhere inside option details. I wanted the template selected only when I click on Submit button.


问:
Why Map object showing size zero when data is populated in it?
I am populating a map object with response from API. Also I am trying to update the value of the map object in another function which is called from a child view. But the map object is showing size zero. My question is why the map object is empty even though it is populated in another object. I have attached two screenshots to show the non empty and empty map objects.

export function Catalogue(props: CatalogueProps) {

  const [categories, setCategory] = useState([]);
  const catalogueResponse = new Map();

  function getCategoryList() {
    httpRequest({
      url: '',
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then((result: AxiosResponse) => {
        const data = result.data;
        const men = {
          title: 'Men',
          id: 'men',
          value: []
        };
        const women = {
          title: 'Women',
          id: 'women',
          value: []
        };
        const misc = {
          title: 'Miscellaneous',
          id: 'misc',
          value: []
        }
        data.forEach((elem) => {
          // store data in the map
          catalogueResponse.set(elem.id, elem)
          if (elem.category === 1) {
            women.value.push(elem);
          } else if (elem.category === 2) {
            men.value.push(elem)
          } else if (elem.category === 3) {
            misc.value.push(elem);
          }
        });
        setCategory(() => {
          return [women, men, misc]
        });

      })
  }

  function updateCatalogueValue(val, category, id, type) {
    console.log(' -------- ', catalogueResponse)
    catalogueResponse.get(id);
    }

  return (
    <UiView style={{flex: 1}}>
      <ScrollView style={{flex: 1}} onLayout={getCategoryList}>
        {
          categories.map((elem: IAccordionList) => {
            return <View key={elem.id}>
              <List.Accordion
                title={elem.title}>
                {elem.value.map((elem: any) => {
                  return <UiAccordionListItem
                    onValueChange={(val, category, id, type) => updateCatalogueValue(val, category, id, type)}
                    elem={elem}
                    key={elem.id}/>
                })}
              </List.Accordion>
            </View>
          })
        }
      </ScrollView>
      <View>
        <UiButton onPress={() => console.log('test')}>Save</UiButton>
      </View>
    </UiView>

  );
}

export default Catalogue;
```


问:
How to add element attribute JQuery Webview Android?
I want to inject some script after the page is loaded, but the script is not injected or maybe i write it wrong. And here is the code that I want to inject.

```<code>val script = "javascript:(function() { $('.numberonly').attr('inputmode','numeric');}())"
</code>```

and onPageLoaded

```<code>binding.webview.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                isLoaded = true
                Utility.dismissProgressDialog()
                view.evaluateJavascript(script) {
                    Log.e("script", "onPageFinished: $it")
                }
            }
        }
</code>```

This is an example that I'm trying to add some attribute to an element, and I try this to text input. Does the script is correct to change an attribute, or what should I do without changing the Web Code directly?

Update

I try to add attributes by element ID, It can be added.
But when I try adding to the class, it's not added.

Here is the code

```<code>val script = "javascript: " +
                "var berninis = document.querySelectorAll('.numberonly');" +
                "for(var i = 0; i < berninis.length; i++) {" +
                "berninis[i].setAttribute(\"inputmode\", \"numeric\");" +
                "}"
</code>```

and this is the code when I try using element ID

```<code>val script = "javascript:document.getElementById('form_userid').setAttribute(\"inputmode\", \"numeric\");"
</code>```

Body:
I want to inject some script after the page is loaded, but the script is not injected or maybe i write it wrong. And here is the code that I want to inject.

val script = "javascript:(function() { $('.numberonly').attr('inputmode','numeric');}())"

and onPageLoaded

binding.webview.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                isLoaded = true
                Utility.dismissProgressDialog()
                view.evaluateJavascript(script) {
                    Log.e("script", "onPageFinished: $it")
                }
            }
        }

This is an example that I'm trying to add some attribute to an element, and I try this to text input. Does the script is correct to change an attribute, or what should I do without changing the Web Code directly?

Update

I try to add attributes by element ID, It can be added.
But when I try adding to the class, it's not added.

Here is the code

val script = "javascript: " +
                "var berninis = document.querySelectorAll('.numberonly');" +
                "for(var i = 0; i < berninis.length; i++) {" +
                "berninis[i].setAttribute(\"inputmode\", \"numeric\");" +
                "}"

and this is the code when I try using element ID

val script = "javascript:document.getElementById('form_userid').setAttribute(\"inputmode\", \"numeric\");"


问:
How to debug a python project with shell script as the entry?
When I tried to debug some Deep Learning projects, I noticed that there are many projects use the shell script as the method of passing parameters. We can easily run these projects by bash run.sh in command line, but how to debug these kind of projects in IDEs like Pycharm?

I have tried to use some methods of python to call system commands like: os.system('bash run.sh') in debugger.py and simply debug the debugger.py. But the breakpoint set by pycharm in this method do not work, and will be directly ignored. What is the reason?

I also try to parse the passed parameters in the shell script and add these parameters in the debug configuration of pycharm like this:

debug configuration

but it seems too troublesome, especially when the incoming parameters are complex.

Is there any elegant solution to debug a python project with shell script as the entry?
Or is it not normative to write too complex parameter processing flow in shell script?


问:
Android -Measure the Coordinates of texts with the onTouchEvent coordinates
I want to dynamically update the Coordinate values of texts stored in an array when MotionEvent.ACTION_MOVE triggers

The problem is i can manually change the Coordinates, But how to measure the Coordinates of Texts and Coordinates of Event.

```<code>package argha.paperzone.papereditor.paperviews;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

import argha.paperzone.papereditor.models.PaperTextModel;

public class PaperEditorView extends View {

    private Paint paint;
    private List<PaperTextModel> textModelList = new ArrayList<>();

    public PaperEditorView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(60);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.FILL);
    }

    public void addText(String text) {
        if (textModelList.size() == 0) {
            textModelList.add(new PaperTextModel(1, 100, 100));
        } else {
            int lastId = textModelList.get(textModelList.size() - 1).getId();
            int lastX = textModelList.get(textModelList.size() - 1).getXAxis();
            int lastY = textModelList.get(textModelList.size() - 1).getYAxis();
            textModelList.add(new PaperTextModel(lastId + 1, lastX, lastY + 100));
        }
        invalidate();
    }

    public void clearAll() {
        textModelList.clear();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (textModelList.size() > 0) {
            for (int i = 0; i < textModelList.size(); i++) {
                canvas.drawText("Text " + textModelList.get(i).getId(),
                        textModelList.get(i).getXAxis(),
                        textModelList.get(i).getYAxis(),
                        paint
                );
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int eventAction = event.getAction();

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (eventAction) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                textModelList.get(2).setXAxis(x);
                textModelList.get(2).setYAxis(y);
        }

        invalidate();

        return true;
    }
}

</code>```

Body:
I want to dynamically update the Coordinate values of texts stored in an array when MotionEvent.ACTION_MOVE triggers

The problem is i can manually change the Coordinates, But how to measure the Coordinates of Texts and Coordinates of Event.

package argha.paperzone.papereditor.paperviews;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

import argha.paperzone.papereditor.models.PaperTextModel;

public class PaperEditorView extends View {

    private Paint paint;
    private List<PaperTextModel> textModelList = new ArrayList<>();

    public PaperEditorView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(60);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.FILL);
    }

    public void addText(String text) {
        if (textModelList.size() == 0) {
            textModelList.add(new PaperTextModel(1, 100, 100));
        } else {
            int lastId = textModelList.get(textModelList.size() - 1).getId();
            int lastX = textModelList.get(textModelList.size() - 1).getXAxis();
            int lastY = textModelList.get(textModelList.size() - 1).getYAxis();
            textModelList.add(new PaperTextModel(lastId + 1, lastX, lastY + 100));
        }
        invalidate();
    }

    public void clearAll() {
        textModelList.clear();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (textModelList.size() > 0) {
            for (int i = 0; i < textModelList.size(); i++) {
                canvas.drawText("Text " + textModelList.get(i).getId(),
                        textModelList.get(i).getXAxis(),
                        textModelList.get(i).getYAxis(),
                        paint
                );
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int eventAction = event.getAction();

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (eventAction) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                textModelList.get(2).setXAxis(x);
                textModelList.get(2).setYAxis(y);
        }

        invalidate();

        return true;
    }
}


问:
C5208 and LNK2001&LNK2019
```<code>typedef struct {
    float b_xpos;
    float b_ypos;
    float b_xVel;
    float b_yVel;
    float f_xpos;
    float f_ypos;
    bool _flameOn = false;
    bool _isTrailing = false;
    float tb1_xpos;
    float tb1_ypos;
    float tb2_xpos;
    float tb2_ypos;
}ballData;
</code>```

In ball class:

```<code>ballData* data = new ballData();
</code>```

I want to write a game on visual studio 2022.And I have a problem. This is the part that compiler shows error. I don't know why is this code wrong. I have tried to add a name after struct like this.

```<code>typedef struct ya{
    float b_xpos;
    float b_ypos;
    float b_xVel;
    float b_yVel;
    float f_xpos;
    float f_ypos;
    bool _flameOn = false;
    bool _isTrailing = false;
    float tb1_xpos;
    float tb1_ypos;
    float tb2_xpos;
    float tb2_ypos;
}ballData;
</code>```

but it's still wrong. How can I fix this? This is the code I copied from github.
https://github.com/sj602/PikachuVolleyball?fbclid=IwAR3HGGvkJbhFWZs249D8jvxePwt2yjQk0HUzEYZ8Cg1cNEPaOvFXJvy91J4
When I change to simpler c++ syntax like this

```<code>struct ballData {
    float b_xpos;
    float b_ypos;
    float b_xVel;
    float b_yVel;
    float f_xpos;
    float f_ypos;
    bool _flameOn = false;
    bool _isTrailing = false;
    float tb1_xpos;
    float tb1_ypos;
    float tb2_xpos;
    float tb2_ypos;
};
</code>```

the new errors show like this.
enter image description here
Can someone help me?

Title: C5208 and LNK2001&LNK2019

Body:
typedef struct {
    float b_xpos;
    float b_ypos;
    float b_xVel;
    float b_yVel;
    float f_xpos;
    float f_ypos;
    bool _flameOn = false;
    bool _isTrailing = false;
    float tb1_xpos;
    float tb1_ypos;
    float tb2_xpos;
    float tb2_ypos;
}ballData;

In ball class:

ballData* data = new ballData();

I want to write a game on visual studio 2022.And I have a problem. This is the part that compiler shows error. I don't know why is this code wrong. I have tried to add a name after struct like this.

typedef struct ya{
    float b_xpos;
    float b_ypos;
    float b_xVel;
    float b_yVel;
    float f_xpos;
    float f_ypos;
    bool _flameOn = false;
    bool _isTrailing = false;
    float tb1_xpos;
    float tb1_ypos;
    float tb2_xpos;
    float tb2_ypos;
}ballData;

but it's still wrong. How can I fix this? This is the code I copied from github.
https://github.com/sj602/PikachuVolleyball?fbclid=IwAR3HGGvkJbhFWZs249D8jvxePwt2yjQk0HUzEYZ8Cg1cNEPaOvFXJvy91J4
When I change to simpler c++ syntax like this

struct ballData {
    float b_xpos;
    float b_ypos;
    float b_xVel;
    float b_yVel;
    float f_xpos;
    float f_ypos;
    bool _flameOn = false;
    bool _isTrailing = false;
    float tb1_xpos;
    float tb1_ypos;
    float tb2_xpos;
    float tb2_ypos;
};

the new errors show like this.
enter image description here
Can someone help me?


问:
len() in Python's duplicated set items
I have a python snippet for a set (we know that set is not for duplicate items), however, should it still not display the number of items as perceived below?

```<code>set2={1,2,3,'a','b','c',True,False,False}
print('Set:',set2, "Length:",len(set2))
</code>```

My assumption:
The above code to return the length to be '8' as there are two 'False' items.

But this is the output:
Set: {False, 1, 2, 3, 'a', 'b', 'c'} Length: 7

Title: len() in Python's duplicated set items

Body:
I have a python snippet for a set (we know that set is not for duplicate items), however, should it still not display the number of items as perceived below?

set2={1,2,3,'a','b','c',True,False,False}
print('Set:',set2, "Length:",len(set2))

My assumption:
The above code to return the length to be '8' as there are two 'False' items.

But this is the output:
Set: {False, 1, 2, 3, 'a', 'b', 'c'} Length: 7


问:
Lucene simulation for ElasticSearch queries - the NOT clause
I'm building a pure lucene-based implementation for legacy system that should locally (in-process) run arbitrary (more or less) queries. I receive queries in textual form, like term1:A OR term2:B. My default operator for queries is AND. For compatibility reasons I'm using lucene 5.5. I'm basing the solution on MemoryIndex single-document implementation.

My main problem is with how lucene deals with NOT clause: in query of sort
termA:(NOT 0) term2:(xxx) lucene would produce the following query:
+(-termA:0) +term2:xxx. While logically pretty sound, in practice this query shall always produce nothing since the negate-only clause always returns no_docs response and AND with it shall always produce empty result. The only workaround that I found (here on SOF) for this is to inject a MatchAllDocs clause together with the negative clause, like termA:(*:* NOT 0), but this is an error prone approach since it involves intricate clause parsing - the MatchAllDocs should only be injected if there are no positive clauses inside the parenthesis.

I'm looking for a more robust/generic approach to this problem, preferable some library that can parse/handle it for me, maybe something in contrib or similar.


问:
In integration test used not InMemoryDatabase, but i create test ApiFactory with InMemoryDatabase
I use ApiFactory for integration tests and mock DB. I took this code from the xUnit tests manual and use it in another project, where it  work good.

```<code>public class ApiFactory: WebApplicationFactory<Program>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return builder.ConfigureServices(services =>
            {
                services.AddDbContext<DatabaseContext>(options =>
                    options.UseInMemoryDatabase("TestDB"));
            })
            .UseStartup<Program>();

    }
}
</code>```
```<code>[Trait("Category", "Unit")]
public class UserTests : IClassFixture<ApiFactory>
{
     private readonly WebApplicationFactory<Program> _factory;

     public UserTests(ApiFactory factory)
     {
         _factory = factory;
     }

     [Fact]
     public void Test1()
     {
         using (var scope = _factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
         {
             using var db =  scope.ServiceProvider.GetService<DatabaseContext>();
             db.UserEntity.Add(New UserEntity(){Name = "Test"});
         }

         var result = _factory.CreateClient().GetAsync("api/v1/user");
         var user = await result.ReadResponceContentAsync<UserEntity>();

         Assert.Equal("Test", user.Name);
     }
}
</code>```

In this line

```<code>         using (var scope = _factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
</code>```

not creating ApiFactory, but filling db.

In this line

```<code>         var user = await result.ReadResponceContentAsync<UserEntity>();
</code>```

creating ApiFactory and invoke api, but db in service empty and test is fail.

Body:
I use ApiFactory for integration tests and mock DB. I took this code from the xUnit tests manual and use it in another project, where it  work good.

public class ApiFactory: WebApplicationFactory<Program>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return builder.ConfigureServices(services =>
            {
                services.AddDbContext<DatabaseContext>(options =>
                    options.UseInMemoryDatabase("TestDB"));
            })
            .UseStartup<Program>();

    }
}

[Trait("Category", "Unit")]
public class UserTests : IClassFixture<ApiFactory>
{
     private readonly WebApplicationFactory<Program> _factory;

     public UserTests(ApiFactory factory)
     {
         _factory = factory;
     }

     [Fact]
     public void Test1()
     {
         using (var scope = _factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
         {
             using var db =  scope.ServiceProvider.GetService<DatabaseContext>();
             db.UserEntity.Add(New UserEntity(){Name = "Test"});
         }

         var result = _factory.CreateClient().GetAsync("api/v1/user");
         var user = await result.ReadResponceContentAsync<UserEntity>();

         Assert.Equal("Test", user.Name);
     }
}

In this line

         using (var scope = _factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())

not creating ApiFactory, but filling db.

In this line

         var user = await result.ReadResponceContentAsync<UserEntity>();

creating ApiFactory and invoke api, but db in service empty and test is fail.


问:
How to send attachment from Oracle DB to Coupa
I have some attachments in Oracle DB, I need to call the coupa attachments API.
How to send the attachments from Oracle DB.

We are using NiFi as Middleware.