问:
What is the best approach to test abstract classes with parameterized constructors using NUnit and C#?
I am looking for the best way to test an abstract class with constructor parameters. It is important to me that I can also include members that are marked as protected. Here is what I came up with. Let's take the following class as an example:

public abstract class MyAbstractClass {

  public MyAbstractClass(string someParam) { ... }

  protected int MethodToTest(int param1, int param2) { ... }
}
```
<p>One possibility would be to derive the <code>TestFixture</code> directly from the abstract class and thus gain access to the members that are marked as <code>protected</code>. But what I rather don't like about it is that I have to pass the constructor parameter in the <code>TestFixture</code> attribute. Furthermore, I have introduced a magic string in addition to this (admittedly, I could still put it into a constant).</p>
<pre class="lang-cs prettyprint-override"><code>[TestFixture("constructor param here")]
public class MyTestFixture : MyAbstractClass {

  public MyTestFixture(string someParam) { ... }

  [Test]
  public void ConstructorTest() {
     Assert.Throws<ArgumentNullException>(() => _ = new MyTestFixture(null!));
  }

  [Test]
  public void MethodTest() {
    Assert.That(this.MethodToTest(1, 2), Is.EqualTo(3));
  }
}
</code>```

Another way might be to simply build a class (in the unit test project) around the abstract class and pass the protected member through. Somehow that doesn't seem very practical to me either. Above all, it bloats the file containing the test terribly as soon as the classes get bigger.

[TestFixture]
public class MyTestFixture {

  private class MyAbstractClassWrapper : MyAbstractClass {
    public MyAbstractClassWrapper(string someParam) : base(someParam) { }

    public new int MethodToTest(int param1, int param2) => base.MethodToTest(param1, param2);
  }

  [Test]
  public void ConstructorTest() {
     Assert.Throws<ArgumentNullException>(() => _ = new MyAbstractClassWrapper(null!));
  }

  [Test]
  public void MethodTest() {
    MyAbstractClassWrapper sut = new("constructor param");
    Assert.That(sut.MethodToTest(1, 2), Is.EqualTo(3));
  }
}
```

What do you guys think? Are there any better solutions or do I have to settle with my approaches above?

Body:
I am looking for the best way to test an abstract class with constructor parameters. It is important to me that I can also include members that are marked as protected. Here is what I came up with. Let's take the following class as an example:

public abstract class MyAbstractClass {

  public MyAbstractClass(string someParam) { ... }

  protected int MethodToTest(int param1, int param2) { ... }
}

One possibility would be to derive the TestFixture directly from the abstract class and thus gain access to the members that are marked as protected. But what I rather don't like about it is that I have to pass the constructor parameter in the TestFixture attribute. Furthermore, I have introduced a magic string in addition to this (admittedly, I could still put it into a constant).

[TestFixture("constructor param here")]
public class MyTestFixture : MyAbstractClass {

  public MyTestFixture(string someParam) { ... }

  [Test]
  public void ConstructorTest() {
     Assert.Throws<ArgumentNullException>(() => _ = new MyTestFixture(null!));
  }

  [Test]
  public void MethodTest() {
    Assert.That(this.MethodToTest(1, 2), Is.EqualTo(3));
  }
}

Another way might be to simply build a class (in the unit test project) around the abstract class and pass the protected member through. Somehow that doesn't seem very practical to me either. Above all, it bloats the file containing the test terribly as soon as the classes get bigger.

[TestFixture]
public class MyTestFixture {

  private class MyAbstractClassWrapper : MyAbstractClass {
    public MyAbstractClassWrapper(string someParam) : base(someParam) { }

    public new int MethodToTest(int param1, int param2) => base.MethodToTest(param1, param2);
  }

  [Test]
  public void ConstructorTest() {
     Assert.Throws<ArgumentNullException>(() => _ = new MyAbstractClassWrapper(null!));
  }

  [Test]
  public void MethodTest() {
    MyAbstractClassWrapper sut = new("constructor param");
    Assert.That(sut.MethodToTest(1, 2), Is.EqualTo(3));
  }
}

What do you guys think? Are there any better solutions or do I have to settle with my approaches above?


来源: stackexchange

问:
java.nio.file.Paths.get(URI uri) is throwing java.nio.file.FileSystemNotFoundException
Tech stack details:

Spring Boot version 2.7.0

Java Version : Java 17.0.3.1

Operating System : Windows 10 Pro

Setup: Trying to run the application built using Spring Boot and packaged as JAR

Business code reads a JSON file. Currently it was achieved by opening an InputStream over BufferedReader readLine()

As part of JDK upgrade from v8 to v17. we are planning to achieve the same using java.nio.file.Files readString(Path, Charset). readString takes Path as an argument. We are trying to build the path using Paths.get(new ClassPathResource(WAVEFORM_FILE_NAME).getURI()
But above line is throwing java.nio.file.FileSystemNotFoundException at ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:156). After debug what I understood is ZipFileSystemProvider has a hashMap filesystems. This is EMPTY. So even when uriToPath(URI uri) is building Path properly, getFileSystem(URI uri) of ZipFileSystemProvider is throwing FileSystemNotFoundException at line#156.

Stack Trace:

```<code> at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:156)
        at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:142)
        at java.base/java.nio.file.Path.of(Path.java:208)
        at java.base/java.nio.file.Paths.get(Paths.java:98)
        at com.x.y.z.streaming.mock.DataLoader.loadData(DataLoader.java:42)
</code>```

Please note: things work fine when spring application is ran inside an editor. Issue comes when we run application as java -jar app.jar

I see suggestions to use FileSystems.newFileSystem(URI.create(pathArray[0]), env) to make this work. I do not understand why Path.get() is having a challenge to read a JSON file inside SpringBoot built JAR. Any pointers would help!

I tried to debug and understand why the exception is thrown. Root Cause Analysis is given in the question. Also proposed solution in some discussion thread also tried. It seems to work but do not understand why Path.get() is not able to work independently. Trying to discuss the technicality.

ContentLicense: CC BY-SA 4.0

Body:
Tech stack details:

Spring Boot version 2.7.0

Java Version : Java 17.0.3.1

Operating System : Windows 10 Pro

Setup: Trying to run the application built using Spring Boot and packaged as JAR

Business code reads a JSON file. Currently it was achieved by opening an InputStream over BufferedReader readLine()

As part of JDK upgrade from v8 to v17. we are planning to achieve the same using java.nio.file.Files readString(Path, Charset). readString takes Path as an argument. We are trying to build the path using Paths.get(new ClassPathResource(WAVEFORM_FILE_NAME).getURI()
But above line is throwing java.nio.file.FileSystemNotFoundException at ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:156). After debug what I understood is ZipFileSystemProvider has a hashMap filesystems. This is EMPTY. So even when uriToPath(URI uri) is building Path properly, getFileSystem(URI uri) of ZipFileSystemProvider is throwing FileSystemNotFoundException at line#156.

Stack Trace:

 at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:156)
        at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:142)
        at java.base/java.nio.file.Path.of(Path.java:208)
        at java.base/java.nio.file.Paths.get(Paths.java:98)
        at com.x.y.z.streaming.mock.DataLoader.loadData(DataLoader.java:42)

Please note: things work fine when spring application is ran inside an editor. Issue comes when we run application as java -jar app.jar

I see suggestions to use FileSystems.newFileSystem(URI.create(pathArray[0]), env) to make this work. I do not understand why Path.get() is having a challenge to read a JSON file inside SpringBoot built JAR. Any pointers would help!

I tried to debug and understand why the exception is thrown. Root Cause Analysis is given in the question. Also proposed solution in some discussion thread also tried. It seems to work but do not understand why Path.get() is not able to work independently. Trying to discuss the technicality.


问:
How to detect Solution Tests in Visual Studio from Command Line
I've got a Visual Studio Solution File conatining multiple projects. About half of them are Unit Test Projects.

Visual Studio Test Explorer reliably picks up all Test Projects and allows me to run all of them at once.

We also got a CI that should run these Tests. Is there a way to use the Test Explorer functionality from the command line? Currently I have to pass a list of dll's and executables to the vstest.console.exe Tool.

I searched google for solutions but only found solutions that pass dll files to vstest.console.exe. I would expect a possibility to run the tests from a solution also from the command line similar to how dotnet test allows me to do this.

Unfortunately I cannot use dotnet test to reach my goal, as dotnet does not yet support native projects (which are also conatined in my solution).


问:
I want to set up CI / CD pipeline at GitLab for my Drupal 7 project which is hosted at Acquia cloud
I’m a new to GitLab and implementing CI.
I have a Drupal 7 project , just recently migrate from GitHub to GitLab.
Now I have to implement CI/CD pipeline.
My project hosted at Acquia cloud. Could any one provide me any link from where I can get proper documentation.</p>


问:
(DestMax > SourceLen) error when flash bootloader to DragonBoard 845c
I am following this 96boards documentation. I managed to boot DragonBoard 845c into fastboot. After that I executed ./flashall command. I got this error :

```<code>Handling Cmd: getvar:has-slot:partition
Handling Cmd:

Fastboot Send Fail
Handling Cmd: getvar:is-logical:partit
Handling Cmd: download:0000b000:partit

DXE_ASSERT!: /home/buildslave/workspace/lt-qcom-bootloader-dragonboard845c/abl/MdePkg/Library/BaseLib/SafeString.c (691): (DestMax > SourceLen)
</code>```

Why is this happening ?

Body:
I am following this 96boards documentation. I managed to boot DragonBoard 845c into fastboot. After that I executed ./flashall command. I got this error :

Handling Cmd: getvar:has-slot:partition
Handling Cmd:

Fastboot Send Fail
Handling Cmd: getvar:is-logical:partit
Handling Cmd: download:0000b000:partit

DXE_ASSERT!: /home/buildslave/workspace/lt-qcom-bootloader-dragonboard845c/abl/MdePkg/Library/BaseLib/SafeString.c (691): (DestMax > SourceLen)

Why is this happening ?


问:
Gainsight Mapping Issue - How to set Scope & Selector?
Testing Application in Gainsight, I am unable to map dynamic URLs in Gainsight. Please let me know how to map dynamic URLs in Gainsight. However working for static URLs.

Example : Some of the pages have dynamic URL i.e. https://blabla.com/#/bla/id/details. Here id may be any number.

How to set Scope & Selector for any dynamic URL in  Gainsight?


问:
Replicate entity with hibernate session error : Illegal attempt to associate a collection with two open sessions
I was trying to create a function to copy data from production to QA database. I used hibernate session to replicate entity, It was working fine except for an Entity that contains OneToMany relation and maintains child entity list. Hibernate was throwing an error about two sessions.

Here are my Entity class and test function :

```<code>@Entity
@Table(name = "project_worker" ,indexes = {@Index(columnList = "id",name="projectid_index" )})
public class ProjectWorker extends AbstractAuditingEntity implements Serializable {
    @Id
    private Long id

    @ManyToOne
    @JoinColumn(name = "project_id")
    private Project project;

    @OneToMany(mappedBy = "projectWorker")
    private List<WorkerDocument> workerDocuments;
}

@Entity
@Table(name="worker_document")
public class WorkerDocument {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name="document_link")
    private String documentLink;

    @ManyToOne
    @JoinColumn(name = "project_worker_id")
    @JsonIgnore
    private ProjectWorker projectWorker;
}
</code>```
```<code>@RunWith(MockitoJUnitRunner.class)
public class ReplicationTests {

    private EntityManager sourceEntityManager = createEntityManagerFactory("source", databaseUrl).createEntityManager();

    private EntityManager targetEntityManager = createEntityManagerFactory("target", targetDatabaseUrl).createEntityManager();

    private EntityManagerFactory createEntityManagerFactory(final String persistenceUnitName,
                                                            final String databaseUrl) {
        final LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();

        final DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName("org.postgresql.ds.PGSimpleDataSource");
        entityManagerFactory.setDataSource(dataSource);

        entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactory.setPackagesToScan("com.mypackage");
        entityManagerFactory.setPersistenceUnitName(persistenceUnitName);

        final Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "com.mypackage.domain.util.FixedPostgreSQL82Dialect");
        properties.setProperty("show_sql", "false");
        properties.setProperty("hibernate.cache.use_second_level_cache", "false");
        properties.setProperty("hibernate.cfj.naming_strategy", SpringNamingStrategy.class.getName());
        entityManagerFactory.setJpaProperties(properties);

        entityManagerFactory.afterPropertiesSet();
        return entityManagerFactory.getObject();
    }

    @Test
    public void copyEntityBetweenPersistenceUnits() {

        boolean overwrite = false;
        final Long projectId = 1024L;

        final Session hibernateSession = targetEntityManager.unwrap(Session.class);

        migrateObjects(projectId, overwrite, ProjectWorker.class, hibernateSession);
    }

    private <T> void migrateObjects(Long id, boolean overwrite, Class<T> tClass, Session hibernateSession) {
        TypedQuery<T> q = sourceEntityManager.createQuery(String.format("select ob from %s ob where ob.project.id =?1", tClass.getSimpleName()), tClass);
        q.setParameter(1, id);
        List<T> sourceEntityList = q.getResultList();

        for (T entity : sourceEntityList) {
            hibernateSession.replicate(entity, overwrite ? ReplicationMode.OVERWRITE : ReplicationMode.IGNORE);
        }
    }

}
</code>```

It is throwing error during replicating workers

```<code>org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions. Collection : [com.mypackage.domain.ProjectWorker.workerDocuments#1072]
Collection contents: [<uninitialized>]

    at org.hibernate.collection.internal.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:636)
    at org.hibernate.event.internal.OnReplicateVisitor.processCollection(OnReplicateVisitor.java:68)
    at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:121)
</code>```

Body:
I was trying to create a function to copy data from production to QA database. I used hibernate session to replicate entity, It was working fine except for an Entity that contains OneToMany relation and maintains child entity list. Hibernate was throwing an error about two sessions.

Here are my Entity class and test function :

@Entity
@Table(name = "project_worker" ,indexes = {@Index(columnList = "id",name="projectid_index" )})
public class ProjectWorker extends AbstractAuditingEntity implements Serializable {
    @Id
    private Long id

    @ManyToOne
    @JoinColumn(name = "project_id")
    private Project project;

    @OneToMany(mappedBy = "projectWorker")
    private List<WorkerDocument> workerDocuments;
}

@Entity
@Table(name="worker_document")
public class WorkerDocument {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name="document_link")
    private String documentLink;

    @ManyToOne
    @JoinColumn(name = "project_worker_id")
    @JsonIgnore
    private ProjectWorker projectWorker;
}

@RunWith(MockitoJUnitRunner.class)
public class ReplicationTests {

    private EntityManager sourceEntityManager = createEntityManagerFactory("source", databaseUrl).createEntityManager();

    private EntityManager targetEntityManager = createEntityManagerFactory("target", targetDatabaseUrl).createEntityManager();

    private EntityManagerFactory createEntityManagerFactory(final String persistenceUnitName,
                                                            final String databaseUrl) {
        final LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();

        final DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName("org.postgresql.ds.PGSimpleDataSource");
        entityManagerFactory.setDataSource(dataSource);

        entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactory.setPackagesToScan("com.mypackage");
        entityManagerFactory.setPersistenceUnitName(persistenceUnitName);

        final Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "com.mypackage.domain.util.FixedPostgreSQL82Dialect");
        properties.setProperty("show_sql", "false");
        properties.setProperty("hibernate.cache.use_second_level_cache", "false");
        properties.setProperty("hibernate.cfj.naming_strategy", SpringNamingStrategy.class.getName());
        entityManagerFactory.setJpaProperties(properties);

        entityManagerFactory.afterPropertiesSet();
        return entityManagerFactory.getObject();
    }

    @Test
    public void copyEntityBetweenPersistenceUnits() {

        boolean overwrite = false;
        final Long projectId = 1024L;

        final Session hibernateSession = targetEntityManager.unwrap(Session.class);

        migrateObjects(projectId, overwrite, ProjectWorker.class, hibernateSession);
    }

    private <T> void migrateObjects(Long id, boolean overwrite, Class<T> tClass, Session hibernateSession) {
        TypedQuery<T> q = sourceEntityManager.createQuery(String.format("select ob from %s ob where ob.project.id =?1", tClass.getSimpleName()), tClass);
        q.setParameter(1, id);
        List<T> sourceEntityList = q.getResultList();

        for (T entity : sourceEntityList) {
            hibernateSession.replicate(entity, overwrite ? ReplicationMode.OVERWRITE : ReplicationMode.IGNORE);
        }
    }

}

It is throwing error during replicating workers

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions. Collection : [com.mypackage.domain.ProjectWorker.workerDocuments#1072]
Collection contents: [<uninitialized>]

    at org.hibernate.collection.internal.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:636)
    at org.hibernate.event.internal.OnReplicateVisitor.processCollection(OnReplicateVisitor.java:68)
    at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:121)


问:
in my node code in routes it is show the cant read of property of undefined (readind get)
here is my code
//for getalllaunches i took data and export it json form

```<code>const {launches}=require('../../models/launches.model');

function getAllLaunches(req,res){
     return res.json(Array.from(launches.values()));
}

module.exports={
    getAllLaunches,
};
</code>```

for router i took data of getalllaunches and try to route it but it shows error in launchesrouter.get.

```<code>const express=require('express');

// const {launches}=require('../../models/launches.model');

const{
    getAllLaunches,
}=require('./launches.controller');

const {launchesRouter}=express.Router();

launchesRouter.get('/launches',getAllLaunches);

module.exports={
    launchesRouter,
};
</code>```

Body:
here is my code
//for getalllaunches i took data and export it json form

const {launches}=require('../../models/launches.model');

function getAllLaunches(req,res){
     return res.json(Array.from(launches.values()));
}

module.exports={
    getAllLaunches,
};

for router i took data of getalllaunches and try to route it but it shows error in launchesrouter.get.

const express=require('express');

// const {launches}=require('../../models/launches.model');

const{
    getAllLaunches,
}=require('./launches.controller');

const {launchesRouter}=express.Router();

launchesRouter.get('/launches',getAllLaunches);

module.exports={
    launchesRouter,
};


问:
Create calculated field based on the max of another value in Excel pivot table
I have a pivot table that summarized data from multiple lines of hours on different accounts an employee has planned to work.

I want to have a calculated field that shows the difference between the hours the employee has planned to work and the number of hours authorized for an employee to work for the year.

The number of hours authorized is different for certain employees.

I am currently using a helper field in my pivot table and xlookup to another employee authorized hours table to add the authorized hours on each of the lines in the source data.

I can get the table to display the correct authorized hours using the "max of" but I don't know how to calculate the difference by either modifying the table, or using calculated fields.

Any ideas appreciated.


问:
Emulator: Pixel 3a XL API 30 - unexpected system image feature string, emulator might not function correctly, please try updating the emulator
Emulator: Pixel 3a XL API 30 - unexpected system image feature string, emulator might not function correctly, please try updating the emulator.

i donloaded the android emulator and i run it. After the some 10-20 sec one message box is display and saying that your emulator is tarminated. After that i checked the idea.txt to check the reason why emulator is terminated then i found this line

Emulator: Pixel 3a XL API 30 - unexpected system image feature string, emulator might not function correctly, please try updating the emulator.


问:
Android onShowFileChooser not triggered
I have a basica app in Android that calls

```<code>  public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){
            Log.d("Message tag -2 File cho","onShowFileChooser done");
</code>```

So it shows "Message tag -2" when the file chooser is triggered, in Android 5.1 and Android 12 it works as it's supposed to.

The file chooser shows and a file can be choosen but it wont go through the code and wont return any file or image in Android 6 as if it ignored the onShowFileChooser

I also have some log messages in the activity result and it's also working fine in Android 5.1/12 but nothing is shown at all in Android 6 and no file is returned and no console logs of any kind show up.

Note that this is triggered by an input type file in a webview.

Title: Android onShowFileChooser not triggered

Body:
I have a basica app in Android that calls

  public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){
            Log.d("Message tag -2 File cho","onShowFileChooser done");

So it shows "Message tag -2" when the file chooser is triggered, in Android 5.1 and Android 12 it works as it's supposed to.

The file chooser shows and a file can be choosen but it wont go through the code and wont return any file or image in Android 6 as if it ignored the onShowFileChooser

I also have some log messages in the activity result and it's also working fine in Android 5.1/12 but nothing is shown at all in Android 6 and no file is returned and no console logs of any kind show up.

Note that this is triggered by an input type file in a webview.


问:
Register api is resposing 403 forbidden but csrf is disabled in spring boot
I am creating backend app and testing as well. my register url is resposing 403 forbidden but csrf is disabled. I can't fix this problem. Please help me P

Here is my configuration

```<code>package uz.renessans.configuration;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import uz.renessans.entity.user.UserRepository;
import uz.renessans.security.JwtFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final JwtFilter jwtFilter;
    private final UserRepository userRepository;

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        UserDetailsService userDetailsService = username ->
                userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException(username));

        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] OPEN_URLS = {
                "/api/v1/register/**",
                "/swagger-ui/**",
                "/api/v1/login"
        };

        http
                .csrf()
                .disable()
                .httpBasic()
                .disable()
                .authorizeRequests()
                .antMatchers(
                        "/api/v1/register/**",
                        "/swagger-ui/**",
                        "/api/v1/login"
                )
                .permitAll()
                .anyRequest()
                .authenticated();
//                .permitAll();
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
</code>```

Here is my jwt filter class:

```<code>package uz.renessans.security;

import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import uz.renessans.entity.user.User;
import uz.renessans.entity.user.UserRepository;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

@Component
@RequiredArgsConstructor
public class JwtFilter extends OncePerRequestFilter {
    private final JwtProvider jwtProvider;
    private final UserRepository userRepository;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer") && authorization.length() > 7) {
            authorization = authorization.substring(7);
            String username = jwtProvider.getPhoneNumber(authorization);
            if (username != null) {

                Optional<User> optionalUser = userRepository.findByUsername(username);

                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = null;
                if (optionalUser.isPresent()) {
                    usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(optionalUser.get(), null, optionalUser.get().getAuthorities());
                }
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }

        filterChain.doFilter(request, response);
    }
}
</code>```

Here is my register api

```<code>public HttpEntity<?> register(RegisterDto dto, Role role) {

    if (userRepository.existsByUsername(dto.getUsername()))
        return new ResponseEntity<>(new ApiResponse("Username already exists", false), HttpStatus.CONFLICT);

    if (!dto.getPassword().equals(dto.getRePassword()))
        return new ResponseEntity<>(new ApiResponse("Password must match", false), HttpStatus.CONFLICT);

    User user = new User();
    user.setRole(role);
    user.setUsername(dto.getUsername());
    user.setPassword(passwordEncoder.encode(dto.getPassword()));
    user.setFullName(dto.getFullName());

    User savedUser = userRepository.save(user);

    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            savedUser.getUsername(), savedUser.getPassword());
    authenticationManager.authenticate(authenticationToken);

    String token = jwtProvider.generateToken(savedUser.getUsername(), savedUser.getRole());

    Response response = Response.builder().token(token).role(role.toString()).build();
    return new ResponseEntity<>(new ApiResponse("Registered Successfully", true, response), HttpStatus.OK);
}
</code>```

Body:
I am creating backend app and testing as well. my register url is resposing 403 forbidden but csrf is disabled. I can't fix this problem. Please help me P

Here is my configuration

package uz.renessans.configuration;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import uz.renessans.entity.user.UserRepository;
import uz.renessans.security.JwtFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final JwtFilter jwtFilter;
    private final UserRepository userRepository;

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        UserDetailsService userDetailsService = username ->
                userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException(username));

        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] OPEN_URLS = {
                "/api/v1/register/**",
                "/swagger-ui/**",
                "/api/v1/login"
        };

        http
                .csrf()
                .disable()
                .httpBasic()
                .disable()
                .authorizeRequests()
                .antMatchers(
                        "/api/v1/register/**",
                        "/swagger-ui/**",
                        "/api/v1/login"
                )
                .permitAll()
                .anyRequest()
                .authenticated();
//                .permitAll();
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

Here is my jwt filter class:

package uz.renessans.security;

import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import uz.renessans.entity.user.User;
import uz.renessans.entity.user.UserRepository;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

@Component
@RequiredArgsConstructor
public class JwtFilter extends OncePerRequestFilter {
    private final JwtProvider jwtProvider;
    private final UserRepository userRepository;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer") && authorization.length() > 7) {
            authorization = authorization.substring(7);
            String username = jwtProvider.getPhoneNumber(authorization);
            if (username != null) {

                Optional<User> optionalUser = userRepository.findByUsername(username);

                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = null;
                if (optionalUser.isPresent()) {
                    usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(optionalUser.get(), null, optionalUser.get().getAuthorities());
                }
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }

        filterChain.doFilter(request, response);
    }
}

Here is my register api

public HttpEntity<?> register(RegisterDto dto, Role role) {

    if (userRepository.existsByUsername(dto.getUsername()))
        return new ResponseEntity<>(new ApiResponse("Username already exists", false), HttpStatus.CONFLICT);

    if (!dto.getPassword().equals(dto.getRePassword()))
        return new ResponseEntity<>(new ApiResponse("Password must match", false), HttpStatus.CONFLICT);

    User user = new User();
    user.setRole(role);
    user.setUsername(dto.getUsername());
    user.setPassword(passwordEncoder.encode(dto.getPassword()));
    user.setFullName(dto.getFullName());

    User savedUser = userRepository.save(user);

    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            savedUser.getUsername(), savedUser.getPassword());
    authenticationManager.authenticate(authenticationToken);

    String token = jwtProvider.generateToken(savedUser.getUsername(), savedUser.getRole());

    Response response = Response.builder().token(token).role(role.toString()).build();
    return new ResponseEntity<>(new ApiResponse("Registered Successfully", true, response), HttpStatus.OK);
}


问:
How to remove previous unix domain socket while closing RTCpeerconnection in webrtc in nodejs
```<code>const { RTCPeerConnection } = require('wrtc')

this.peerConnection =  new RTCPeerConnection(this.rtcConfig)
</code>```

------------- some coding --------------------------------------------------

```<code>this.peerConnection.close();

</code>```

//In above code i am closing the peerConnection but still previous unix domain socket continue to //exist and not getting destroyed and its increasing whenever i create new peer connection- below are //the logs of my process checked in terminal

```<code>unix  3      [ ]         STREAM     CONNECTED     3410597  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3417284  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3417285  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3410598  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3405499  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3410595  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3405497  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3410594  14738/Liveview
</code>```

i am expecting that when we close the rtcpeerconnection the unix domain socket related to that peer connection should be cleared

Body:
const { RTCPeerConnection } = require('wrtc')

this.peerConnection =  new RTCPeerConnection(this.rtcConfig)

------------- some coding --------------------------------------------------

this.peerConnection.close();

//In above code i am closing the peerConnection but still previous unix domain socket continue to //exist and not getting destroyed and its increasing whenever i create new peer connection- below are //the logs of my process checked in terminal

unix  3      [ ]         STREAM     CONNECTED     3410597  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3417284  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3417285  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3410598  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3405499  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3410595  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3405497  14738/Liveview
unix  3      [ ]         STREAM     CONNECTED     3410594  14738/Liveview

i am expecting that when we close the rtcpeerconnection the unix domain socket related to that peer connection should be cleared


问:
How to create scrollable tkinter widget to cycle through images?
I am writing a GUI to display images (essentially a slideshow). I would like to add a scroll bar so the user can cycle through multiple images at a faster rate then clicking a button. An example of what I would like is below.

Currently, I have implemented the scale widget which when moved with cycle through every 25 images. However, this only works in one direction. Is there a way to bind the scale widget with two commands, one to go forward and backwards? I already have left and right arrow buttons that will cycle through images one by one, but it does not "sync" with the scale widget.

```<code>scale = tk.Scale(master=self.root
                 , orient=tk.HORIZONTAL, from_=self.imgIndex + 1, to=int(len(self.img_lst)), resolution=25,
                 length=250, width =25,
                 showvalue=False, command=self.next_25)
# scale.pack(side=BOTTOM, fill=X)
scale.place(x=550,y=650, anchor=tk.CENTER)

</code>```

Any help/ideas would be greatly appreciated.

Body:
I am writing a GUI to display images (essentially a slideshow). I would like to add a scroll bar so the user can cycle through multiple images at a faster rate then clicking a button. An example of what I would like is below.

Currently, I have implemented the scale widget which when moved with cycle through every 25 images. However, this only works in one direction. Is there a way to bind the scale widget with two commands, one to go forward and backwards? I already have left and right arrow buttons that will cycle through images one by one, but it does not "sync" with the scale widget.

scale = tk.Scale(master=self.root
                 , orient=tk.HORIZONTAL, from_=self.imgIndex + 1, to=int(len(self.img_lst)), resolution=25,
                 length=250, width =25,
                 showvalue=False, command=self.next_25)
# scale.pack(side=BOTTOM, fill=X)
scale.place(x=550,y=650, anchor=tk.CENTER)

Any help/ideas would be greatly appreciated.


问:
How to find the parent tag of a particular element in an XML?
I am getting invalid character, line number and tag name by matching pattern using regular expression and I want to find parent tag from the line number. I am getting parent tag of the particular descendant but its checking from the first line not from the line which I found.

For example, I found invalid character on line number 302 and the tag on that line is <Example1> and I want to find parent tag of that  from that line number 302 not from the beginning. Because I have multiple <Example1> in my xml so my code is retrieving from the beginning.

I am sharing c# code and output which I am getting.

```<code>using (TextReader reader = new StreamReader(wc.OpenRead(path_xml)))
                        {
                            xml = reader.ReadToEnd();

                            string[] lines = xml.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);

                            //Here we save the Values according to your line numbers
                            List<string> values = new List<string>();

                            //hex unicode pattern
                            string pattern2 = @"&#x?[^;]{2,4};";

                            List<int> a = new List<int>();

                            Regex rg1 = new Regex(pattern2);

                            MatchCollection matchedXML1 = rg1.Matches(xml);

                            XDocument doc;
                            using (XmlReader xr = XmlReader.Create(path_xml, new XmlReaderSettings() { CheckCharacters = false }))
                            {
                                doc = XDocument.Load(xr);
                                //accessing line number where pattern has been matched
                                for (int i = 0; i < lines.Length; i++)
                                {
                                    sr.ReadLine();
                                    foreach (Match m in Regex.Matches(lines[i], pattern2))
                                    {
                                        string temp = lines[i].ToString().Trim();
                                        Console.Write("Line: " + (i + 1));
                                        Console.Write(" -> " + lines[i].ToString().Trim());

                                        string stringBeforeChar = temp.Substring(0, temp.IndexOf(">") + 1);
                                        String afterTrim = stringBeforeChar.Trim();
                                        string afterRemoval = afterTrim.TrimStart('<').TrimEnd('>');

                                        var element = doc.Descendants(afterRemoval).First();

                                        var names = element.AncestorsAndSelf()
                                                         .Reverse()
                                                         .Skip(1)
                                                         .Select(x => x.Name);
                                        var joined = string.Join("/", names);
                                        Console.Write(" -> Parent Tag: "+joined);

                                        for (int count = 0; count < matchedXML1.Count; count++)
                                        {
                                            if (lines[i].ToString().Contains(matchedXML1[count].Value))
                                            {
                                                Console.WriteLine(" -> " + matchedXML1[count].Value);

                                            }
                                        }
                                    }
                                }
                            }

                        }
</code>```

Output of above function:

Enter the location of XML file..

D:\xml_data\data_158920.xml

```<code>Line: 709 -> <Address>Some text�</Address> -> Parent Tag: PartyInfo/Address -> �
Line: 942 -> <LogDateTime>Some Text</LogDateTime> -> Parent Tag: RegistrationLog/LogDateTime ->
Line: 974 -> <LogDateTime>Some text</LogDateTime> -> Parent Tag: RegistrationLog/LogDateTime ->
Line: 1118 -> <LogDateTime>Some text</LogDateTime> -> Parent Tag: RegistrationLog/LogDateTime ->
</code>```

Parent tag I found which is from the beginning not from the line in which I am fetching..

I have added this line var element = doc.Descendants(afterRemoval).First(); So its checking first child node and then retrieving parent node of that child node. but I want to iterate till the line numbers which I got and print parent tag from that line number or whatever possible way.

Body:
I am getting invalid character, line number and tag name by matching pattern using regular expression and I want to find parent tag from the line number. I am getting parent tag of the particular descendant but its checking from the first line not from the line which I found.

For example, I found invalid character on line number 302 and the tag on that line is <Example1> and I want to find parent tag of that  from that line number 302 not from the beginning. Because I have multiple <Example1> in my xml so my code is retrieving from the beginning.

I am sharing c# code and output which I am getting.

using (TextReader reader = new StreamReader(wc.OpenRead(path_xml)))
                        {
                            xml = reader.ReadToEnd();

                            string[] lines = xml.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);

                            //Here we save the Values according to your line numbers
                            List<string> values = new List<string>();

                            //hex unicode pattern
                            string pattern2 = @"&#x?[^;]{2,4};";

                            List<int> a = new List<int>();

                            Regex rg1 = new Regex(pattern2);

                            MatchCollection matchedXML1 = rg1.Matches(xml);

                            XDocument doc;
                            using (XmlReader xr = XmlReader.Create(path_xml, new XmlReaderSettings() { CheckCharacters = false }))
                            {
                                doc = XDocument.Load(xr);
                                //accessing line number where pattern has been matched
                                for (int i = 0; i < lines.Length; i++)
                                {
                                    sr.ReadLine();
                                    foreach (Match m in Regex.Matches(lines[i], pattern2))
                                    {
                                        string temp = lines[i].ToString().Trim();
                                        Console.Write("Line: " + (i + 1));
                                        Console.Write(" -> " + lines[i].ToString().Trim());

                                        string stringBeforeChar = temp.Substring(0, temp.IndexOf(">") + 1);
                                        String afterTrim = stringBeforeChar.Trim();
                                        string afterRemoval = afterTrim.TrimStart('<').TrimEnd('>');

                                        var element = doc.Descendants(afterRemoval).First();

                                        var names = element.AncestorsAndSelf()
                                                         .Reverse()
                                                         .Skip(1)
                                                         .Select(x => x.Name);
                                        var joined = string.Join("/", names);
                                        Console.Write(" -> Parent Tag: "+joined);

                                        for (int count = 0; count < matchedXML1.Count; count++)
                                        {
                                            if (lines[i].ToString().Contains(matchedXML1[count].Value))
                                            {
                                                Console.WriteLine(" -> " + matchedXML1[count].Value);

                                            }
                                        }
                                    }
                                }
                            }

                        }

Output of above function:

Enter the location of XML file..

D:\xml_data\data_158920.xml

Line: 709 -> <Address>Some text�</Address> -> Parent Tag: PartyInfo/Address -> �
Line: 942 -> <LogDateTime>Some Text</LogDateTime> -> Parent Tag: RegistrationLog/LogDateTime ->
Line: 974 -> <LogDateTime>Some text</LogDateTime> -> Parent Tag: RegistrationLog/LogDateTime ->
Line: 1118 -> <LogDateTime>Some text</LogDateTime> -> Parent Tag: RegistrationLog/LogDateTime ->

Parent tag I found which is from the beginning not from the line in which I am fetching..

I have added this line var element = doc.Descendants(afterRemoval).First(); So its checking first child node and then retrieving parent node of that child node. but I want to iterate till the line numbers which I got and print parent tag from that line number or whatever possible way.


问:
How to find the termination time of the currently running process in my system?
I am currently using psutil package , I have used wmi package also but could not find the termination time of running process.

```<code>import psutil
import datetime

for process in psutil.process_iter(['pid', 'username']):
    pro_id = process.info['pid']
    print(process.info)

    p = psutil.Process(pro_id)
    p.create_time()
    print(f'Process Started at : {datetime.datetime.fromtimestamp(p.create_time()).strftime("%d-%m-%Y %H:%M:%S")}')

</code>```

output

{'username': 'NT AUTHORITY\SYSTEM', 'pid': 0}
Process Started at : 01-01-1970 05:30:00
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 4}
Process Started at : 21-12-2022 15:55:26
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 100}
Process Started at : 21-12-2022 15:55:09
{'username': 'LAPTOP-89SFF6RC\ayush', 'pid': 264}
Process Started at : 21-12-2022 16:11:23
{'username': 'NT AUTHORITY\LOCAL SERVICE', 'pid': 356}
Process Started at : 21-12-2022 15:56:00
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 472}
Process Started at : 21-12-2022 15:55:27
{'username': 'Font Driver Host\UMFD-1', 'pid': 516}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 572}
Process Started at : 21-12-2022 15:55:52
{'username': 'Font Driver Host\UMFD-0', 'pid': 600}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 652}
Process Started at : 21-12-2022 15:55:51
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 768}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 788}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 840}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 848}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 952}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\LOCAL SERVICE', 'pid': 1032}
Process Started at : 21-12-2022 15:55:53
{'username': 'NT AUTHORITY\NETWORK SERVICE', 'pid': 1068}
Process Started at : 21-12-2022 15:55:53
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 1124}

I need a method which sends a signal at the termination of any running process , using psutil or any other module in python.

Body:
I am currently using psutil package , I have used wmi package also but could not find the termination time of running process.

import psutil
import datetime

for process in psutil.process_iter(['pid', 'username']):
    pro_id = process.info['pid']
    print(process.info)

    p = psutil.Process(pro_id)
    p.create_time()
    print(f'Process Started at : {datetime.datetime.fromtimestamp(p.create_time()).strftime("%d-%m-%Y %H:%M:%S")}')

output

{'username': 'NT AUTHORITY\SYSTEM', 'pid': 0}
Process Started at : 01-01-1970 05:30:00
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 4}
Process Started at : 21-12-2022 15:55:26
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 100}
Process Started at : 21-12-2022 15:55:09
{'username': 'LAPTOP-89SFF6RC\ayush', 'pid': 264}
Process Started at : 21-12-2022 16:11:23
{'username': 'NT AUTHORITY\LOCAL SERVICE', 'pid': 356}
Process Started at : 21-12-2022 15:56:00
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 472}
Process Started at : 21-12-2022 15:55:27
{'username': 'Font Driver Host\UMFD-1', 'pid': 516}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 572}
Process Started at : 21-12-2022 15:55:52
{'username': 'Font Driver Host\UMFD-0', 'pid': 600}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 652}
Process Started at : 21-12-2022 15:55:51
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 768}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 788}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 840}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 848}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 952}
Process Started at : 21-12-2022 15:55:52
{'username': 'NT AUTHORITY\LOCAL SERVICE', 'pid': 1032}
Process Started at : 21-12-2022 15:55:53
{'username': 'NT AUTHORITY\NETWORK SERVICE', 'pid': 1068}
Process Started at : 21-12-2022 15:55:53
{'username': 'NT AUTHORITY\SYSTEM', 'pid': 1124}

I need a method which sends a signal at the termination of any running process , using psutil or any other module in python.


问:
Laravel fill empty days in collection of stdclass
I have a query that return a collection of stdclass objects with 'data' and 'day properties.  Returns a collection, with all the days that return data, but not those with no lines

```<code>$reservations = DB::table('reservation')->selectRaw("
        count(id) AS data,
        DAY(created_at) AS day
    ")
    ->where( DB::raw('YEAR(created_at)'), '=', '2023')
    ->where( DB::raw('MONTH(created_at)'), '=', '12')
    ->groupBy('day')
    ->get();
</code>```

I need to create an array with values for each day of the month containing only the data field. If the day does not exist in the collection, assign it a 0.

```<code>$array = [10, 23, 12, 0, 10...];
</code>```

I thought about making a loop for each day with CarbonPeriod, but inside I have to make another loop with the result to check if there is a match, add the value, and if not add the 0. Is there a collection method or other way to facilitate this?

```<code>foreach (CarbonPeriod::create($initmonth,'1 day',$lastDayMonth) as $key => $day) {
        foreach ($reservations as $key => $value) {
            //here I'm trying to find the match
            if($day->day == $value->day) $array[] = $value->data // else ???
        }
}
</code>```

Body:
I have a query that return a collection of stdclass objects with 'data' and 'day properties.  Returns a collection, with all the days that return data, but not those with no lines

$reservations = DB::table('reservation')->selectRaw("
        count(id) AS data,
        DAY(created_at) AS day
    ")
    ->where( DB::raw('YEAR(created_at)'), '=', '2023')
    ->where( DB::raw('MONTH(created_at)'), '=', '12')
    ->groupBy('day')
    ->get();

I need to create an array with values for each day of the month containing only the data field. If the day does not exist in the collection, assign it a 0.

$array = [10, 23, 12, 0, 10...];

I thought about making a loop for each day with CarbonPeriod, but inside I have to make another loop with the result to check if there is a match, add the value, and if not add the 0. Is there a collection method or other way to facilitate this?

foreach (CarbonPeriod::create($initmonth,'1 day',$lastDayMonth) as $key => $day) {
        foreach ($reservations as $key => $value) {
            //here I'm trying to find the match
            if($day->day == $value->day) $array[] = $value->data // else ???
        }
}


问:
pthread_mutex_lock called on a destroyed mutex
When i try to run my app it got crashed and gives the error shown in the imagepthread_mutex_lock called on a destroyed mutex

I try to run the app but it got crashedthis is the error


问:
Spring Cloud Gateway instance unable to connect to eureka server
I'm following this "Microservices with Spring Boot and Spring Cloud" book by Magnus Larsson, at chapter 10 Spring Cloud Gateway is introduced as an edge server into the microservices landscape, once all the microservices are started SCGateway is unable to connect with the Eureka server:

RedirectingEurekaHttpClient  : Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://eureka:8761/eureka/}, exception=I/O error on POST request for "http://eureka:8761/eureka/apps/GATEWAY": Connect to eureka:8761 [eureka/172.23.0.4] failed: Connection refused; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to eureka:8761 [eureka/172.23.0.4] failed: Connection refused stacktrace=org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://eureka:8761/eureka/apps/GATEWAY": Connect to eureka:8761 [eureka/172.23.0.4] failed: Connection refused; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to eureka:8761 [eureka/172.23.0.4] failed: Connection refused...

this is the docker-compose.yml file:

```<code>version: '2.1'

services:
  product:
    ...instance configuration

  recommendation:
    ...instance configuration

  review:
    ...instance configuration

  product-composite:
    ...instance configuration

  mongodb:
    ...instance configuration

  mysql:
    ...instance configuration

  rabbitmq:
    ...instance configuration

  eureka:
    build: spring-cloud/eureka-server
    mem_limit: 512m

  gateway:
    environment:
      - SPRING_PROFILES_ACTIVE=docker
    build: spring-cloud/gateway
    mem_limit: 512m
    ports:
      - "8085:8085"
</code>```

Eureka Dockerfile:

```<code>FROM adoptopenjdk:16_36-jre-hotspot as builder
WORKDIR extracted
ADD ./build/libs/*.jar app.jar
RUN java -Djarmode=layertools -jar app.jar extract

FROM adoptopenjdk:16_36-jre-hotspot
WORKDIR application
COPY --from=builder extracted/dependencies/ ./
COPY --from=builder extracted/spring-boot-loader/ ./
COPY --from=builder extracted/snapshot-dependencies/ ./
COPY --from=builder extracted/application/ ./

EXPOSE 8761

ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]
</code>```

Eureka application.yml file:

```<code>server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  # from: https://github.com/spring-cloud-samples/eureka/blob/master/src/main/resources/application.yml
  server:
    waitTimeInMsWhenSyncEmpty: 0
    response-cache-update-interval-ms: 5000

management.endpoints.web.exposure.include: "*"
</code>```

Spring Cloud Gateway Dockerfile:

```<code>FROM adoptopenjdk:16_36-jre-hotspot as builder
WORKDIR extracted
ADD ./build/libs/*.jar app.jar
RUN java -Djarmode=layertools -jar app.jar extract

FROM adoptopenjdk:16_36-jre-hotspot
WORKDIR application
COPY --from=builder extracted/dependencies/ ./
COPY --from=builder extracted/spring-boot-loader/ ./
COPY --from=builder extracted/snapshot-dependencies/ ./
COPY --from=builder extracted/application/ ./

EXPOSE 8085

ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]
</code>```

Spring Cloud Gateway application.yml file:

```<code>server.port: 8085

spring.application.name: gateway

app.eureka-server: localhost

eureka:
  client:
    serviceUrl:
      defaultZone: http://${app.eureka-server}:8761/eureka/
    initialInstanceInfoReplicationIntervalSeconds: 5
    registryFetchIntervalSeconds: 5
  instance:
    leaseRenewalIntervalInSeconds: 5
    leaseExpirationDurationInSeconds: 5

spring.cloud.gateway.routes:

- id: product-composite
  uri: lb://product-composite
  predicates:
  - Path=/product-composite/**

- id: product-composite-swagger-ui
  uri: lb://product-composite
  predicates:
  - Path=/openapi/**

- id: eureka-api
  uri: http://${app.eureka-server}:8761
  predicates:
  - Path=/eureka/api/{segment}
  filters:
  - SetPath=/eureka/{segment}

- id: eureka-web-start
  uri: http://${app.eureka-server}:8761
  predicates:
  - Path=/eureka/web
  filters:
  - SetPath=/

- id: eureka-web-other
  uri: http://${app.eureka-server}:8761
  predicates:
  - Path=/eureka/**

management.endpoint.health.show-details: "ALWAYS"
management.endpoints.web.exposure.include: "*"

logging:
  level:
    root: INFO
    org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator: INFO
    org.springframework.cloud.gateway: TRACE

---
spring.config.activate.on-profile: docker

app.eureka-server: eureka
</code>```

Originally the project uses Spring Boot version 2.5.2 and Spring Cloud version 2020.0.3, also tried with recent versions (with no success) such as:

Spring Boot version: 2.6.6 and 2.7.5

Spring Cloud: 2021.0.4

The Spring Cloud Gateway is always throwing the same exception:

org.apache.http.conn.HttpHostConnectException: Connect to eureka:8761
[eureka/172.23.0.4] failed: Connection refused

Trying to access the Eureka dashboard or http://localhost:8085/actuator/health endpoint hangs forever.

I'll appreciate any hints or help, thanks in advance.

Body:
I'm following this "Microservices with Spring Boot and Spring Cloud" book by Magnus Larsson, at chapter 10 Spring Cloud Gateway is introduced as an edge server into the microservices landscape, once all the microservices are started SCGateway is unable to connect with the Eureka server:

RedirectingEurekaHttpClient  : Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://eureka:8761/eureka/}, exception=I/O error on POST request for "http://eureka:8761/eureka/apps/GATEWAY": Connect to eureka:8761 [eureka/172.23.0.4] failed: Connection refused; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to eureka:8761 [eureka/172.23.0.4] failed: Connection refused stacktrace=org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://eureka:8761/eureka/apps/GATEWAY": Connect to eureka:8761 [eureka/172.23.0.4] failed: Connection refused; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to eureka:8761 [eureka/172.23.0.4] failed: Connection refused...

this is the docker-compose.yml file:

version: '2.1'

services:
  product:
    ...instance configuration

  recommendation:
    ...instance configuration

  review:
    ...instance configuration

  product-composite:
    ...instance configuration

  mongodb:
    ...instance configuration

  mysql:
    ...instance configuration

  rabbitmq:
    ...instance configuration

  eureka:
    build: spring-cloud/eureka-server
    mem_limit: 512m

  gateway:
    environment:
      - SPRING_PROFILES_ACTIVE=docker
    build: spring-cloud/gateway
    mem_limit: 512m
    ports:
      - "8085:8085"

Eureka Dockerfile:

FROM adoptopenjdk:16_36-jre-hotspot as builder
WORKDIR extracted
ADD ./build/libs/*.jar app.jar
RUN java -Djarmode=layertools -jar app.jar extract

FROM adoptopenjdk:16_36-jre-hotspot
WORKDIR application
COPY --from=builder extracted/dependencies/ ./
COPY --from=builder extracted/spring-boot-loader/ ./
COPY --from=builder extracted/snapshot-dependencies/ ./
COPY --from=builder extracted/application/ ./

EXPOSE 8761

ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]

Eureka application.yml file:

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  # from: https://github.com/spring-cloud-samples/eureka/blob/master/src/main/resources/application.yml
  server:
    waitTimeInMsWhenSyncEmpty: 0
    response-cache-update-interval-ms: 5000

management.endpoints.web.exposure.include: "*"

Spring Cloud Gateway Dockerfile:

FROM adoptopenjdk:16_36-jre-hotspot as builder
WORKDIR extracted
ADD ./build/libs/*.jar app.jar
RUN java -Djarmode=layertools -jar app.jar extract

FROM adoptopenjdk:16_36-jre-hotspot
WORKDIR application
COPY --from=builder extracted/dependencies/ ./
COPY --from=builder extracted/spring-boot-loader/ ./
COPY --from=builder extracted/snapshot-dependencies/ ./
COPY --from=builder extracted/application/ ./

EXPOSE 8085

ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]

Spring Cloud Gateway application.yml file:

server.port: 8085

spring.application.name: gateway

app.eureka-server: localhost

eureka:
  client:
    serviceUrl:
      defaultZone: http://${app.eureka-server}:8761/eureka/
    initialInstanceInfoReplicationIntervalSeconds: 5
    registryFetchIntervalSeconds: 5
  instance:
    leaseRenewalIntervalInSeconds: 5
    leaseExpirationDurationInSeconds: 5

spring.cloud.gateway.routes:

- id: product-composite
  uri: lb://product-composite
  predicates:
  - Path=/product-composite/**

- id: product-composite-swagger-ui
  uri: lb://product-composite
  predicates:
  - Path=/openapi/**

- id: eureka-api
  uri: http://${app.eureka-server}:8761
  predicates:
  - Path=/eureka/api/{segment}
  filters:
  - SetPath=/eureka/{segment}

- id: eureka-web-start
  uri: http://${app.eureka-server}:8761
  predicates:
  - Path=/eureka/web
  filters:
  - SetPath=/

- id: eureka-web-other
  uri: http://${app.eureka-server}:8761
  predicates:
  - Path=/eureka/**

management.endpoint.health.show-details: "ALWAYS"
management.endpoints.web.exposure.include: "*"

logging:
  level:
    root: INFO
    org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator: INFO
    org.springframework.cloud.gateway: TRACE

---
spring.config.activate.on-profile: docker

app.eureka-server: eureka

Originally the project uses Spring Boot version 2.5.2 and Spring Cloud version 2020.0.3, also tried with recent versions (with no success) such as:

Spring Boot version: 2.6.6 and 2.7.5

Spring Cloud: 2021.0.4

The Spring Cloud Gateway is always throwing the same exception:

org.apache.http.conn.HttpHostConnectException: Connect to eureka:8761
[eureka/172.23.0.4] failed: Connection refused

Trying to access the Eureka dashboard or http://localhost:8085/actuator/health endpoint hangs forever.

I'll appreciate any hints or help, thanks in advance.


问:
Cannot interact with Flutter web app TextButton (click, hover) on work computer using chrome, edge, or explorer, but firefox works
Update 2: created a new app with just the demo and it also doesn’t work on work computer except Firefox. Tried setting alerts throughout the index.html service_worker and they seem to trigger. The app that does work is older, so maybe something broken in the newer versions?

Update: I copied the working button into the non working one and it doesn’t work. So something about the entire web app doesn’t seem to work, not just the button.

Can someone suggest next steps to diagnose this issue? At home, everything works, so I'm assuming the issue lies in the workplace firewall (just a guess).

I'm using a simple TextButton, and on Firefox it works just fine (hover effect shows, and clicking does what it's supposed to).

However, in Chrome, Explorer, and Edge hovering over the button shows no hover effect, and clicking does nothing.

Unfortunately, the inspector is disabled at work, so I can't try and see what's going on, though that's limited anyway based on how Flutter draws out the app.

Interestingly (and perhaps helpfully), I have a second Flutter web app with a TextButton that does seem to work in all browsers at work. Here are the two buttons:

Working in all browsers:

```<code>TextButton(
  style: ButtonStyle(
    padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(20)),
    foregroundColor: MaterialStateProperty.all<Color>(Colors.blue),
    overlayColor: MaterialStateProperty.resolveWith<Color>(
          (Set<MaterialState> states) {
        if (states.contains(MaterialState.hovered))
          return Colors.blue.withOpacity(0.8);
        if (states.contains(MaterialState.focused) ||
            states.contains(MaterialState.pressed))
          return Colors.blue.withOpacity(0.12);
        return null; // Defer to the widget's default.
      },
    ),
  ),
  child: new Text("Button Text", style: TextStyle(color: Colors.white)),
  onPressed: () {
    setState(() {
      Navigator.pushNamed(context, '/route');
    });
  },
),
</code>```

Working only in Firefox:

```<code>TextButton(
  style: ButtonStyle(
    padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(20)),
    foregroundColor: MaterialStateProperty.resolveWith<Color>(
          (Set<MaterialState> states) {
        if (states.contains(MaterialState.hovered))
          return colorButtonTextHovered;
        if (states.contains(MaterialState.focused) ||
            states.contains(MaterialState.pressed))
          return colorButtonTextFocusPress;
        return colorButtonTextDefault;
      },
    ),
    backgroundColor: MaterialStateProperty.resolveWith<Color>(
          (Set<MaterialState> states) {
        if (states.contains(MaterialState.hovered))
          return colorButtonBackgroundHovered;
        if (states.contains(MaterialState.focused) ||
            states.contains(MaterialState.pressed))
          return colorButtonBackgroundFocusPress;
        return colorButtonBackgroundDefault;
      },
    ),
  ),
  child: new Text("Button Text"),
  onPressed: () {
    setState(() {
      Navigator.push(
        context,
        FadeRoute(
          MyApp.mtAppKey,
          '/route',
        ),
      );
    });
  },
),
</code>```

Any tips, suggestions, next steps to diagnosing and fixing this issue?

Body:
Update 2: created a new app with just the demo and it also doesn’t work on work computer except Firefox. Tried setting alerts throughout the index.html service_worker and they seem to trigger. The app that does work is older, so maybe something broken in the newer versions?

Update: I copied the working button into the non working one and it doesn’t work. So something about the entire web app doesn’t seem to work, not just the button.

Can someone suggest next steps to diagnose this issue? At home, everything works, so I'm assuming the issue lies in the workplace firewall (just a guess).

I'm using a simple TextButton, and on Firefox it works just fine (hover effect shows, and clicking does what it's supposed to).

However, in Chrome, Explorer, and Edge hovering over the button shows no hover effect, and clicking does nothing.

Unfortunately, the inspector is disabled at work, so I can't try and see what's going on, though that's limited anyway based on how Flutter draws out the app.

Interestingly (and perhaps helpfully), I have a second Flutter web app with a TextButton that does seem to work in all browsers at work. Here are the two buttons:

Working in all browsers:

TextButton(
  style: ButtonStyle(
    padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(20)),
    foregroundColor: MaterialStateProperty.all<Color>(Colors.blue),
    overlayColor: MaterialStateProperty.resolveWith<Color>(
          (Set<MaterialState> states) {
        if (states.contains(MaterialState.hovered))
          return Colors.blue.withOpacity(0.8);
        if (states.contains(MaterialState.focused) ||
            states.contains(MaterialState.pressed))
          return Colors.blue.withOpacity(0.12);
        return null; // Defer to the widget's default.
      },
    ),
  ),
  child: new Text("Button Text", style: TextStyle(color: Colors.white)),
  onPressed: () {
    setState(() {
      Navigator.pushNamed(context, '/route');
    });
  },
),

Working only in Firefox:

TextButton(
  style: ButtonStyle(
    padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(20)),
    foregroundColor: MaterialStateProperty.resolveWith<Color>(
          (Set<MaterialState> states) {
        if (states.contains(MaterialState.hovered))
          return colorButtonTextHovered;
        if (states.contains(MaterialState.focused) ||
            states.contains(MaterialState.pressed))
          return colorButtonTextFocusPress;
        return colorButtonTextDefault;
      },
    ),
    backgroundColor: MaterialStateProperty.resolveWith<Color>(
          (Set<MaterialState> states) {
        if (states.contains(MaterialState.hovered))
          return colorButtonBackgroundHovered;
        if (states.contains(MaterialState.focused) ||
            states.contains(MaterialState.pressed))
          return colorButtonBackgroundFocusPress;
        return colorButtonBackgroundDefault;
      },
    ),
  ),
  child: new Text("Button Text"),
  onPressed: () {
    setState(() {
      Navigator.push(
        context,
        FadeRoute(
          MyApp.mtAppKey,
          '/route',
        ),
      );
    });
  },
),

Any tips, suggestions, next steps to diagnosing and fixing this issue?


问:
How to spyon session storage in angular jasmine
How to write the spyon for session storage ?</p>
```<code>ngOnInit(){
 this.role=JSON.parse(sessionStorage.getItem('currentUser))['role'];

}
</code>```

Body:
How to write the spyon for session storage ?

ngOnInit(){
 this.role=JSON.parse(sessionStorage.getItem('currentUser))['role'];

}


问:
Get signed split APKs by ABI
currently I can download the signed universal APK from Google Play Console but I can't seem to find a way to get signed apks for each ABI. I looked into Play Developer API but those just give APKs which are split to the bare bones and that creates another dilemma of having to merge them all but not being able to sign the merged APK with the App Signing Key(Managed by Google). Anyone here know of a way to get signed apks split by ABI?

The main idea of wanting ABI-split APKs is so it'll be a smaller APK when users who don't have access to Google Play Store download our app from our GitHub Releases page(or some equivalent site).

Title: Get signed split APKs by ABI


问:
cmake - Troubleshooting LINK_DIRECTORIES
My cmake file contains this statement:

```<code>link_directories("C:/path/to/lib")
</code>```

In the properties of the generated Visual Studio solution I see:

```<code>/LIBPATH:"C:/path/to/lib"
/LIBPATH:"C:/path/to/lib/Release"
</code>```

I am not sure where that second LIBPATH is coming from.

Within the cmake file I would like to print out the LINK_DIRECTORIES property, how would I do that?  I have tried various things along the lines of...

```<code>cmake_print_properties(DIRECTORIES xxx PROPERTIES LINK_DIRECTORIES)
</code>```

...but I am not sure what parameters to pass.

Edit OK this worked:

```<code>cmake_print_properties(DIRECTORIES . PROPERTIES LINK_DIRECTORIES)
</code>```

It prints out:

```<code> Properties for DIRECTORY .:
   ..LINK_DIRECTORIES = "C:/path/to/lib"
</code>```

So where is that second LIBPATH coming from?  I don't know whether it is generated by cmake somehow, or added later by Visual Studio.

Body:
My cmake file contains this statement:

link_directories("C:/path/to/lib")

In the properties of the generated Visual Studio solution I see:

/LIBPATH:"C:/path/to/lib"
/LIBPATH:"C:/path/to/lib/Release"

I am not sure where that second LIBPATH is coming from.

Within the cmake file I would like to print out the LINK_DIRECTORIES property, how would I do that?  I have tried various things along the lines of...

cmake_print_properties(DIRECTORIES xxx PROPERTIES LINK_DIRECTORIES)

...but I am not sure what parameters to pass.

Edit OK this worked:

cmake_print_properties(DIRECTORIES . PROPERTIES LINK_DIRECTORIES)

It prints out:

 Properties for DIRECTORY .:
   ..LINK_DIRECTORIES = "C:/path/to/lib"

So where is that second LIBPATH coming from?  I don't know whether it is generated by cmake somehow, or added later by Visual Studio.


问:
How to create a generic extension function for an enum class annotated with kotlinx.serialization.Serializable?
Given the following Kotlin enum:

@kotlinx.serialization.Serializable
enum class MyEnum {
    @SerialName("One") ONE,
    @SerialName("Two") TWO,
    @SerialName("Three") THREE
}
```
<p>I can call the following generated function:</p>
<pre class="lang-kotlin prettyprint-override"><code>MyEnum.serialize()
</code>```

Sometimes I need to pipe this through an kotlinx.serialization.builtins.ArraySerializer:

ArraySerializer(MyEnum.serializer())
```
<p>Which could be wrapped in an extension function:</p>
<pre class="lang-kotlin prettyprint-override"><code>inline fun <reified T : Any> KSerializer<T>.asArray(): KSerializer<Array<T>> {
    return ArraySerializer(this)
}
</code>```

as used like this:

MyEnum.serialize().asArray()
```
<p>How can I write a <strong>generic</strong> extension function to do ...?</p>
<pre class="lang-kotlin prettyprint-override"><code>MyEnum.serializeAsArray()
</code>```

Body:
Given the following Kotlin enum:

@kotlinx.serialization.Serializable
enum class MyEnum {
    @SerialName("One") ONE,
    @SerialName("Two") TWO,
    @SerialName("Three") THREE
}

I can call the following generated function:

MyEnum.serialize()

Sometimes I need to pipe this through an kotlinx.serialization.builtins.ArraySerializer:

ArraySerializer(MyEnum.serializer())

Which could be wrapped in an extension function:

inline fun <reified T : Any> KSerializer<T>.asArray(): KSerializer<Array<T>> {
    return ArraySerializer(this)
}

as used like this:

MyEnum.serialize().asArray()

How can I write a generic extension function to do ...?

MyEnum.serializeAsArray()


问:
How to set device_token in genymotion android emulator?
I'm trying to pentest an app which needs device_token to work. How do I set device_token in my genymotion android emulator? Its running android 6 api 23.

I can set the androidID and deviceID from the right panel.


问:
OpenGL glGenBuffers with error message: EXC_BAD_ACCESS (code=1, address=0x0)
I wanted implement a simple code in C++ to create a triangle with OpenGL.
I generated a Buffer with glGenBuffers but it caused an error with the message:
EXC_BAD_ACCESS (code=1, address=0x0)</p>
```<code>> my code is
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>

int main(void)
{
    GLFWwindow* window;
    if(!glfwInit())
        return -1;
    window = glfwCreateWindow(640, 480, "OpenGL", NULL, NULL);
    if(!window)
    {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    float position[] ={
       -0.5f, -0.5f,0.0f, //0
        0.5f, -0.5f, 0.0f, //1
        0.5f, 0.5f, 0.0f, //2
        -0.5f, 0.5f, 0.0f //3
    };

    GLuint bufferID;
    glGenBuffers(1, &bufferID);
    glBindBuffer(GL_ARRAY_BUFFER, bufferID);
    glBufferData(GL_ARRAY_BUFFER,
                 12*sizeof(float),
                 position,
                 GL_STATIC_DRAW);

    //Loop until the user closes the window
    while(!glfwWindowShouldClose(window))
    {
        //Render here
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

        glfwSwapBuffers(window);
        glfwPollEvents();

    }
}

thanks for any help

</code>```

Body:
I wanted implement a simple code in C++ to create a triangle with OpenGL.
I generated a Buffer with glGenBuffers but it caused an error with the message:
EXC_BAD_ACCESS (code=1, address=0x0)

> my code is
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>

int main(void)
{
    GLFWwindow* window;
    if(!glfwInit())
        return -1;
    window = glfwCreateWindow(640, 480, "OpenGL", NULL, NULL);
    if(!window)
    {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    float position[] ={
       -0.5f, -0.5f,0.0f, //0
        0.5f, -0.5f, 0.0f, //1
        0.5f, 0.5f, 0.0f, //2
        -0.5f, 0.5f, 0.0f //3
    };

    GLuint bufferID;
    glGenBuffers(1, &bufferID);
    glBindBuffer(GL_ARRAY_BUFFER, bufferID);
    glBufferData(GL_ARRAY_BUFFER,
                 12*sizeof(float),
                 position,
                 GL_STATIC_DRAW);

    //Loop until the user closes the window
    while(!glfwWindowShouldClose(window))
    {
        //Render here
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

        glfwSwapBuffers(window);
        glfwPollEvents();

    }
}

thanks for any help


问:
eSpeak Installed via HomeBrew, unable to use it in python via subprocess
I installed espeak with homebrew.

Using the which espeak command in my terminal, I got this path : '/Users/username/homebrew/bin/espeak'

I added it to my path in python :

```<code>import os
os.environ['PATH'] += ':/Users/username/homebrew/bin/espeak'
</code>```

I then called eSpeak with subprocess

```<code>from subprocess import call
call(["espeak", "-v", "mb-us1", "Hello, I am espeak"])
</code>```

But I get this error :

```<code>Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
NotADirectoryError                        Traceback (most recent call last)
Cell In[14], line 3
      1 from subprocess import call
----> 3 call(["espeak", "-v", "mb-us1", "Hello, I am espeak"])

File /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py:349, in call(timeout, *popenargs, **kwargs)
    341 def call(*popenargs, timeout=None, **kwargs):
    342     """Run command with arguments.  Wait for command to complete or
    343     timeout, then return the returncode attribute.
    344
   (...)
    347     retcode = call(["ls", "-l"])
    348     """
--> 349     with Popen(*popenargs, **kwargs) as p:
    350         try:
    351             return p.wait(timeout=timeout)

File /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py:951, in Popen.__init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask)
    947         if self.text_mode:
    948             self.stderr = io.TextIOWrapper(self.stderr,
    949                     encoding=encoding, errors=errors)
--> 951     self._execute_child(args, executable, preexec_fn, close_fds,
    952                         pass_fds, cwd, env,
    953                         startupinfo, creationflags, shell,
...
   1820         err_msg = os.strerror(errno_num)
-> 1821     raise child_exception_type(errno_num, err_msg, err_filename)
   1822 raise child_exception_type(err_msg)

NotADirectoryError: [Errno 20] Not a directory: 'espeak'
</code>```

In the end, I need this to work in order to use the pyttsx3 packages to save audio as mp3 from text.

Any ideas how I can solve this ?

Gabriel

Body:
I installed espeak with homebrew.

Using the which espeak command in my terminal, I got this path : '/Users/username/homebrew/bin/espeak'

I added it to my path in python :

import os
os.environ['PATH'] += ':/Users/username/homebrew/bin/espeak'

I then called eSpeak with subprocess

from subprocess import call
call(["espeak", "-v", "mb-us1", "Hello, I am espeak"])

But I get this error :

Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
NotADirectoryError                        Traceback (most recent call last)
Cell In[14], line 3
      1 from subprocess import call
----> 3 call(["espeak", "-v", "mb-us1", "Hello, I am espeak"])

File /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py:349, in call(timeout, *popenargs, **kwargs)
    341 def call(*popenargs, timeout=None, **kwargs):
    342     """Run command with arguments.  Wait for command to complete or
    343     timeout, then return the returncode attribute.
    344
   (...)
    347     retcode = call(["ls", "-l"])
    348     """
--> 349     with Popen(*popenargs, **kwargs) as p:
    350         try:
    351             return p.wait(timeout=timeout)

File /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py:951, in Popen.__init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask)
    947         if self.text_mode:
    948             self.stderr = io.TextIOWrapper(self.stderr,
    949                     encoding=encoding, errors=errors)
--> 951     self._execute_child(args, executable, preexec_fn, close_fds,
    952                         pass_fds, cwd, env,
    953                         startupinfo, creationflags, shell,
...
   1820         err_msg = os.strerror(errno_num)
-> 1821     raise child_exception_type(errno_num, err_msg, err_filename)
   1822 raise child_exception_type(err_msg)

NotADirectoryError: [Errno 20] Not a directory: 'espeak'

In the end, I need this to work in order to use the pyttsx3 packages to save audio as mp3 from text.

Any ideas how I can solve this ?

Gabriel


问:
Tailwind CSS not working when I use the classes
I've followed all the steps shown in the documentation, but still my tailwindcss is not working.
Here are the codes below, what else should I need to do ?

Here is the code , where it fails
App.js

```<code>import React, { useState } from 'react';

const App = () => {
    const [darkTheme, setDarkTheme] = useState(false);
    return (
        <div className={darkTheme ? 'dark' : ''}>
            <div className="bg-gray-500">
                App
            </div>
        </div>
    )
}

export default App;
</code>```

global.css

```<code>@tailwind base;
@tailwind components;
@tailwind utilities;
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './global.css';

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

craco.config.js

```<code>module.exports = {
    style: {
        postcss: {
            plugins: [
                require('tailwindcss'),
                require('autoprefixer'),
            ],
        },
    },
}
</code>```

tailwind.config.js

```<code>/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
</code>```

Body:
I've followed all the steps shown in the documentation, but still my tailwindcss is not working.
Here are the codes below, what else should I need to do ?

Here is the code , where it fails
App.js

import React, { useState } from 'react';

const App = () => {
    const [darkTheme, setDarkTheme] = useState(false);
    return (

                App

    )
}

export default App;

global.css

@tailwind base;
@tailwind components;
@tailwind utilities;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './global.css';

ReactDOM.render(<App />, document.getElementById('root'));

craco.config.js

module.exports = {
    style: {
        postcss: {
            plugins: [
                require('tailwindcss'),
                require('autoprefixer'),
            ],
        },
    },
}

tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}


问:
Increase performance in PYQT6 QAbstractTableModel when using Checkboxes
I'm using PyQT6 for my application. I'm creating my own QAbstractTableModel where each row has some details and last 3 columns are checkboxes representing received, packed, sent. I successfully implemented the solution. The problem is there is a slight delay(0.3s - rough estimate) which is noticable when (un)checking the checkboxes. Propably the problem is in the performance is there better way to do this? All my data returned from database is in numpy arrays so that shouldn't be a problem.

Here is my class for the table.

class TableModel(QAbstractTableModel):
    def __init__(self, data, headers):
        super(TableModel, self).__init__()
        self._data = data
        self._headers = headers

    def data(self, index, role):
        value = self._data[index.row(), index.column()]
        if not index.isValid():
            return QVariant()

        if role == Qt.ItemDataRole.DisplayRole:
            if value == "True" or value == "False":
                return QVariant("")
            return QVariant(str(value))

        # set checkboxes
        elif role == Qt.ItemDataRole.CheckStateRole:
            if value == "True":
                return QVariant(Qt.CheckState.Checked)
            if value == "False":
                return QVariant(Qt.CheckState.Unchecked)

        elif role == Qt.ItemDataRole.BackgroundRole:
            if value == "True":
                return QVariant(QtGui.QColor("green"))
            if value == "False":
                return QVariant(QtGui.QColor("yellow"))
        elif role == Qt.ItemDataRole.TextAlignmentRole:
            return QVariant(Qt.AlignmentFlag.AlignCenter)

    # checking and unchecking checkbox
    def setData(self, index, value, role):
        if role == Qt.ItemDataRole.CheckStateRole:
            if value is not None:
                if value == 0:
                    self._data[index.row(), index.column()] = False
                elif value == 2:
                    self._data[index.row(), index.column()] = True
                queries.set_checkbox(self._data[index.row()], index.column())
                self.dataChanged.emit(index, index)
                return True
        return False

    def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
        if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
            return self._headers[section]
        return super().headerData(section, orientation, role)

    def rowCount(self, index):
        if not self._data.size:
            return 0
        return self._data.shape[0]

    def columnCount(self, index):
        if not self._data.size:
            return 0
        return self._data.shape[1]

    def flags(self, index):
        return Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable
```
<p>Here is my code for creating the table:</p>
<pre class="lang-py prettyprint-override"><code>def get_table(self, view, month):
    """get table from db to show in TableView"""
    deliveries = queries.get_deliveries(month)
    headers = queries.get_delivery_headers()
    self.model = TableModel(deliveries, headers)
    proxymodel = QSortFilterProxyModel()
    proxymodel.setSourceModel(self.model)
    view.setModel(proxymodel)
    view.sortByColumn(0, Qt.SortOrder.AscendingOrder)
    for x in range(2, len(headers)):
        view.resizeColumnToContents(x)
    view.show()
</code>```

Body:
I'm using PyQT6 for my application. I'm creating my own QAbstractTableModel where each row has some details and last 3 columns are checkboxes representing received, packed, sent. I successfully implemented the solution. The problem is there is a slight delay(0.3s - rough estimate) which is noticable when (un)checking the checkboxes. Propably the problem is in the performance is there better way to do this? All my data returned from database is in numpy arrays so that shouldn't be a problem.

Here is my class for the table.

class TableModel(QAbstractTableModel):
    def __init__(self, data, headers):
        super(TableModel, self).__init__()
        self._data = data
        self._headers = headers

    def data(self, index, role):
        value = self._data[index.row(), index.column()]
        if not index.isValid():
            return QVariant()

        if role == Qt.ItemDataRole.DisplayRole:
            if value == "True" or value == "False":
                return QVariant("")
            return QVariant(str(value))

        # set checkboxes
        elif role == Qt.ItemDataRole.CheckStateRole:
            if value == "True":
                return QVariant(Qt.CheckState.Checked)
            if value == "False":
                return QVariant(Qt.CheckState.Unchecked)

        elif role == Qt.ItemDataRole.BackgroundRole:
            if value == "True":
                return QVariant(QtGui.QColor("green"))
            if value == "False":
                return QVariant(QtGui.QColor("yellow"))
        elif role == Qt.ItemDataRole.TextAlignmentRole:
            return QVariant(Qt.AlignmentFlag.AlignCenter)

    # checking and unchecking checkbox
    def setData(self, index, value, role):
        if role == Qt.ItemDataRole.CheckStateRole:
            if value is not None:
                if value == 0:
                    self._data[index.row(), index.column()] = False
                elif value == 2:
                    self._data[index.row(), index.column()] = True
                queries.set_checkbox(self._data[index.row()], index.column())
                self.dataChanged.emit(index, index)
                return True
        return False

    def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
        if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
            return self._headers[section]
        return super().headerData(section, orientation, role)

    def rowCount(self, index):
        if not self._data.size:
            return 0
        return self._data.shape[0]

    def columnCount(self, index):
        if not self._data.size:
            return 0
        return self._data.shape[1]

    def flags(self, index):
        return Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable

Here is my code for creating the table:

def get_table(self, view, month):
    """get table from db to show in TableView"""
    deliveries = queries.get_deliveries(month)
    headers = queries.get_delivery_headers()
    self.model = TableModel(deliveries, headers)
    proxymodel = QSortFilterProxyModel()
    proxymodel.setSourceModel(self.model)
    view.setModel(proxymodel)
    view.sortByColumn(0, Qt.SortOrder.AscendingOrder)
    for x in range(2, len(headers)):
        view.resizeColumnToContents(x)
    view.show()