问:
Failed to execute Command Liner
Have some problem, when i was started my app, and try to load my entity from Command Liner, i getting next exception

```<code>java.lang.IllegalStateException: Failed to execute CommandLineRunner

Caused by: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [user.UK_ob8kqyqqgmefl0aco34akdtpe]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:270) ~[spring-orm-6.0.2.jar:6.0.2]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233) ~[spring-orm-6.0.2.jar:6.0.2]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:550) ~[spring-orm-6.0.2.jar:6.0.2]
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-6.0.2.jar:6.0.2]
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-6.0.2.jar:6.0.2]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152) ~[spring-tx-6.0.2.jar:6.0.2]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.0.2.jar:6.0.2]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:163) ~[spring-data-jpa-3.0.0.jar:3.0.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.0.2.jar:6.0.2]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-6.0.2.jar:6.0.2]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.0.2.jar:6.0.2]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:218) ~[spring-aop-6.0.2.jar:6.0.2]
    at jdk.proxy2/jdk.proxy2.$Proxy97.save(Unknown Source) ~[na:na]
    at spring.utility.OperationUtilityClass.createUsers(OperationUtilityClass.java:30) ~[classes/:na]
    at spring.utility.OperationUtilityClass.usersOperations(OperationUtilityClass.java:21) ~[classes/:na]
    at spring.CourseSystemApplication.run(CourseSystemApplication.java:42) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:767) ~[spring-boot-3.0.0.jar:3.0.0]
    ... 5 common frames omitted
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:60) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:56) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3288) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3898) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:80) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:653) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:283) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:264) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:322) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:340) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:184) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:129) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:53) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:735) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:719) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at
</code>```

My OperatioUtilityclass, where i create, update, delete and fetch User**

```<code>public class OperationUtilityClass {
    public static void usersOperations (UserDao dao) {
        createUsers (dao);
        updateUsers (dao);
        deleteUsers (dao);
        fetchUsers (dao);
}

    private static void createUsers (UserDao userDao) {
        User user1 = new User ("user1@gmail.com", "pass1");
        userDao.save(user1);

        User user2 = new User ("user2@gmail.com", "pass2");
        userDao.save(user2);

        User user3 = new User ("user3@gmail.com", "pass3");
        userDao.save(user3);

        User user4 = new User ("user4@gmail.com", "pass4");
        userDao.save(user4);
    }

    private static void updateUsers (UserDao userDao) {
        User user = userDao.findById(2L).orElseThrow(()->new EntityNotFoundException ("User Not Found"));
        user.setUserEmail("newemail@gmail.com");
        userDao.save(user);
    }

    private static void deleteUsers (UserDao userDao) {
        User user = userDao.findById(2L).orElseThrow(()->new EntityNotFoundException ("User Not Found"));
        userDao.delete(user);
        userDao.deleteById(3L);
    }

    private static void fetchUsers (UserDao userDao) {
        userDao.findAll().forEach(user-> System.out.println(user.toString()));
}
</code>```

UserDTO class

```<code>public interface UserDao extends JpaRepository <User, Long> {

    User findByuserEmail (String userEmail);

}
</code>```

And my Entity Class

```<code>@Entity
@Table (name = "User")
public class User {

    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    @Column (name = "user_id", nullable = false, unique = true)
    private Long userId;

    @Basic
    @Column (name = "email", nullable = false, length = 45, unique = true)
    private String userEmail;

    @Basic
    @Column (name = "password", nullable = false, length = 45, unique = true)
    private String userPassword;

    @ManyToMany (fetch = FetchType.EAGER)
    @JoinTable (name = "user_role",
                                   joinColumns = {@JoinColumn (name = "user_id")},
                                   inverseJoinColumns = {@JoinColumn (name = "role_id")})
    private Set <Role> roles = new HashSet<>();

    @OneToOne (mappedBy = "user")
    private Student student;

    @OneToOne (mappedBy = "user")
    private Instructor instructor;
</code>```

Also my main class

```<code>@EntityScan ("spring.entity")
@SpringBootApplication
public class CourseSystemApplication implements CommandLineRunner {

    @Autowired
    private UserDao userDao;

    @Autowired
    private CourseDao courseDao;

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private InstructorDao instructorDao;

    public static void main(String[] args) {
        SpringApplication.run(CourseSystemApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        OperationUtilityClass.usersOperations(userDao);

</code>```

If you know, why my Command Liner Failed, and why i have ConstraintViolationException, please help me. And i must add, then one user1@gmail.com is created in table, but other 3 not;

Title: Failed to execute Command Liner

Body:
Have some problem, when i was started my app, and try to load my entity from Command Liner, i getting next exception

java.lang.IllegalStateException: Failed to execute CommandLineRunner

Caused by: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [user.UK_ob8kqyqqgmefl0aco34akdtpe]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:270) ~[spring-orm-6.0.2.jar:6.0.2]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233) ~[spring-orm-6.0.2.jar:6.0.2]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:550) ~[spring-orm-6.0.2.jar:6.0.2]
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-6.0.2.jar:6.0.2]
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-6.0.2.jar:6.0.2]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152) ~[spring-tx-6.0.2.jar:6.0.2]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.0.2.jar:6.0.2]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:163) ~[spring-data-jpa-3.0.0.jar:3.0.0]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.0.2.jar:6.0.2]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-6.0.2.jar:6.0.2]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.0.2.jar:6.0.2]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:218) ~[spring-aop-6.0.2.jar:6.0.2]
    at jdk.proxy2/jdk.proxy2.$Proxy97.save(Unknown Source) ~[na:na]
    at spring.utility.OperationUtilityClass.createUsers(OperationUtilityClass.java:30) ~[classes/:na]
    at spring.utility.OperationUtilityClass.usersOperations(OperationUtilityClass.java:21) ~[classes/:na]
    at spring.CourseSystemApplication.run(CourseSystemApplication.java:42) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:767) ~[spring-boot-3.0.0.jar:3.0.0]
    ... 5 common frames omitted
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:60) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:56) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3288) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3898) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:80) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:653) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:283) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:264) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:322) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:340) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:184) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:129) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:53) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:735) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:719) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at

My OperatioUtilityclass, where i create, update, delete and fetch User**

public class OperationUtilityClass {
    public static void usersOperations (UserDao dao) {
        createUsers (dao);
        updateUsers (dao);
        deleteUsers (dao);
        fetchUsers (dao);
}

    private static void createUsers (UserDao userDao) {
        User user1 = new User ("user1@gmail.com", "pass1");
        userDao.save(user1);

        User user2 = new User ("user2@gmail.com", "pass2");
        userDao.save(user2);

        User user3 = new User ("user3@gmail.com", "pass3");
        userDao.save(user3);

        User user4 = new User ("user4@gmail.com", "pass4");
        userDao.save(user4);
    }

    private static void updateUsers (UserDao userDao) {
        User user = userDao.findById(2L).orElseThrow(()->new EntityNotFoundException ("User Not Found"));
        user.setUserEmail("newemail@gmail.com");
        userDao.save(user);
    }

    private static void deleteUsers (UserDao userDao) {
        User user = userDao.findById(2L).orElseThrow(()->new EntityNotFoundException ("User Not Found"));
        userDao.delete(user);
        userDao.deleteById(3L);
    }

    private static void fetchUsers (UserDao userDao) {
        userDao.findAll().forEach(user-> System.out.println(user.toString()));
}

UserDTO class

public interface UserDao extends JpaRepository <User, Long> {

    User findByuserEmail (String userEmail);

}

And my Entity Class

@Entity
@Table (name = "User")
public class User {

    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    @Column (name = "user_id", nullable = false, unique = true)
    private Long userId;

    @Basic
    @Column (name = "email", nullable = false, length = 45, unique = true)
    private String userEmail;

    @Basic
    @Column (name = "password", nullable = false, length = 45, unique = true)
    private String userPassword;

    @ManyToMany (fetch = FetchType.EAGER)
    @JoinTable (name = "user_role",
                                   joinColumns = {@JoinColumn (name = "user_id")},
                                   inverseJoinColumns = {@JoinColumn (name = "role_id")})
    private Set <Role> roles = new HashSet<>();

    @OneToOne (mappedBy = "user")
    private Student student;

    @OneToOne (mappedBy = "user")
    private Instructor instructor;

Also my main class

@EntityScan ("spring.entity")
@SpringBootApplication
public class CourseSystemApplication implements CommandLineRunner {

    @Autowired
    private UserDao userDao;

    @Autowired
    private CourseDao courseDao;

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private InstructorDao instructorDao;

    public static void main(String[] args) {
        SpringApplication.run(CourseSystemApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        OperationUtilityClass.usersOperations(userDao);

If you know, why my Command Liner Failed, and why i have ConstraintViolationException, please help me. And i must add, then one user1@gmail.com is created in table, but other 3 not;


来源: stackexchange

问:
Uncaught TypeError: (0 , _DataApi__WEBPACK_IMPORTED_MODULE_1__.mapIntoObject) is not a function
I am building a FullStack JS app while learning react and part of it is to display some data from a JSON file.
Before showing the data in the webpage I am mapping the data into objects. In the training I am following this works smoothly. In my case I get the following error:

Uncaught TypeError: (0 ,
DataApi__WEBPACK_IMPORTED_MODULE_1_.mapIntoObject) is not a function

Below are the code snippets and I'm trying to use.

DataAPi.js

function DataApi () {

    const mapIntoObject = (arr) => {
        return arr.reduce((acc, curr) => {
            acc[curr.id] = curr
            return acc
        }, {})
    }

    getArticles = () => {
        return mapIntoObject(data.articles);
    }
    getAuthors = () => {
        return mapIntoObject(data.authors);
    }
}

export default DataApi;```
</div>
</div>
</p>
<p>App.js</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { useState } from 'react'
import { mapIntoObject, getArticles, getAuthors} from '../DataApi'
import { data } from '../testData.json'
import ArticleList from './ArticleList'
import render from 'react-dom'

const api = mapIntoObject(data)

function App() {
    const [articles, setArticles] = useState(getArticles)
    const [authors, setAuthors] = useState(getAuthors)

    render(
        <ArticleList
            articles={articles}
            authors={authors} />
    )
}

export default App</code>```

I am trying to understand why the error happens and how to fix it.

Thanks for your time in advance.

ContentLicense: CC BY-SA 4.0

Body:
I am building a FullStack JS app while learning react and part of it is to display some data from a JSON file.
Before showing the data in the webpage I am mapping the data into objects. In the training I am following this works smoothly. In my case I get the following error:

Uncaught TypeError: (0 ,
DataApi__WEBPACK_IMPORTED_MODULE_1_.mapIntoObject) is not a function

Below are the code snippets and I'm trying to use.

DataAPi.js

function DataApi () {

    const mapIntoObject = (arr) => {
        return arr.reduce((acc, curr) => {
            acc[curr.id] = curr
            return acc
        }, {})
    }

    getArticles = () => {
        return mapIntoObject(data.articles);
    }
    getAuthors = () => {
        return mapIntoObject(data.authors);
    }
}

export default DataApi;

App.js

import React, { useState } from 'react'
import { mapIntoObject, getArticles, getAuthors} from '../DataApi'
import { data } from '../testData.json'
import ArticleList from './ArticleList'
import render from 'react-dom'

const api = mapIntoObject(data)

function App() {
    const [articles, setArticles] = useState(getArticles)
    const [authors, setAuthors] = useState(getAuthors)

    render(
        <ArticleList
            articles={articles}
            authors={authors} />
    )
}

export default App

I am trying to understand why the error happens and how to fix it.

Thanks for your time in advance.


问:
Chrome issue in Android 13
In Android 13 unable to open chrome browser using html textenter image description here

I am trying to open chrome browser in Android 13 using html text on UriParse but not working show the error unable to find explicitly activity class {Android package name}
Code screen shot

Title: Chrome issue in Android 13


问:
What strategy to draw boids using shaders and sfml?
I want to implement a Boids simulation using C++ and SFML. Each boid is a triangle at a position (x,y), an angle, a radius of sight, and a tail showing its path history.

Drawing each boid using shapes in SFML resulted in poor performances, I eventually rewrote everything using vertex arrays (sf::Lines for the tail, sf::Triangles for the boids, and regular CircleShapes for the sight radius).

With this, I am limited to 10k boid before dropping below 60fps. I am now considering drawing each boid using shaders, I can then add other fancy glowing effects.

However, I am lacking the proper strategy to implement this. Let's say a boid is:

```<code>struct Boid {
    Vec2 position, speed;
    float angle;
    float sight_radius;
}
</code>```

I tried to have a single full-screen texture and use fragment shader using uniforms array, but I am limited to 4k vec4 to pass the information of all boids. I also don't want to compute everything from the shader.

One solution could be to have one shader that receives varying such as:

The position of the boid

It's angle

It's radius of sight

But I don't understand how to combine this together: sfml + vertex + fragment.

I asked chat GPT which recommends this:

One way to approach this problem would be to use a geometry shader. A geometry shader is a type of shader that operates on whole primitives (triangles, lines, and points) and can output an arbitrary number of primitives, making it a good fit for your boids simulation.

I found an example, but my graphic card doesn't support geometry shaders.

Body:
I want to implement a Boids simulation using C++ and SFML. Each boid is a triangle at a position (x,y), an angle, a radius of sight, and a tail showing its path history.

Drawing each boid using shapes in SFML resulted in poor performances, I eventually rewrote everything using vertex arrays (sf::Lines for the tail, sf::Triangles for the boids, and regular CircleShapes for the sight radius).

With this, I am limited to 10k boid before dropping below 60fps. I am now considering drawing each boid using shaders, I can then add other fancy glowing effects.

However, I am lacking the proper strategy to implement this. Let's say a boid is:

struct Boid {
    Vec2 position, speed;
    float angle;
    float sight_radius;
}

I tried to have a single full-screen texture and use fragment shader using uniforms array, but I am limited to 4k vec4 to pass the information of all boids. I also don't want to compute everything from the shader.

One solution could be to have one shader that receives varying such as:

The position of the boid

It's angle

It's radius of sight

But I don't understand how to combine this together: sfml + vertex + fragment.

I asked chat GPT which recommends this:

One way to approach this problem would be to use a geometry shader. A geometry shader is a type of shader that operates on whole primitives (triangles, lines, and points) and can output an arbitrary number of primitives, making it a good fit for your boids simulation.

I found an example, but my graphic card doesn't support geometry shaders.


问:
PrimeNG table sticky header not working when rowGroupMode is specified
I am trying to show data in a PrimeNG table in a grouped manner. I am following the example given in their documentation https://www.primefaces.org/primeng-v13/table/rowgroup.

When I run the application I can see that the data is displayed in a grouped manner.

The problem that I am having is that when I scroll the grid, the header is not sticking. The row groups sticks. Please refer to the screenshots below,

Before scrolling,

After scrolling the header is not sticking,

Below is a screenshot of my table declaration,

I tried some solutions mentioned online of adding styling as below but it is still not working,

The PrimeNG version I am using is 13.4.1 and Angular 13

Can someone please let me know what I have missed.


问:
How can I get my Pycharm project to use the right python version?
I'm trying to get PyCharm to use python 3.9.1 on an ubuntu vm. The ubuntu terminal gives Python 3.9.1 when I run python -V but when I use the PyCharm terminal in the project folder, it gives Python 3.8.7. I have the interpreter for the project set to 3.9.1 but somehow it's not registering in the PyCharm terminal. How do I get them to match?</p>


问:
Custom freshness check predicate in install() rules
I am trying to make the install() rule generator of CMake to behave more smart with respect to our file contents. Basically, I would like to avoid the replacement of the destination file if it is not needed, and be able to define what "not needed" means. For example, if there is no change of the file contents, the destination should not be touched. Or if the file contents has changed only insignificantly (timestamp, detectable by regex) then this should also not be causing the copy operation.

And I cannot see a straight-forward way to describe this. It seems like there is only choice between install(CODE ... where the user has to write all the custom code for copy operation, in platform-dependend way, of using install(FILES ... which is quite dumb, it only looks at file modification time and file size. Actually I would like to use FILES mechanisms but somehow tell it to use a user-defined script at installation time to report the equality of source and destination.

Is there a good way to integrate a such checker?


问:
call method on file number in folder change (new file created)
How to detect when new file appears in the folder?
I tried FileObserver but it doesn't work with URI and
I can only get folder URI with Intent.ACTION_OPEN_DOCUMENT_TREE...

My main problem is that I have a function running periodically
detecting if new image comes (from camera) to selected folder.
But sometimes when the file is still copying (from camera) to folder -
and I try to load it to ImageView I get black screen.

So I think it's because I try to load incomplete file. Right?

K.

```<code>ivImageFromUrl.setImageURI(lastImageUri);
</code>```
```<code>if(howManyInTotal != numberOfFiles) {
    //we have new file so we need to load it
    loadLastImageFromUrl(folderUri);
    Log.d("FullscreenActivity","New image loaded.");
}

</code>```

Body:
How to detect when new file appears in the folder?
I tried FileObserver but it doesn't work with URI and
I can only get folder URI with Intent.ACTION_OPEN_DOCUMENT_TREE...

My main problem is that I have a function running periodically
detecting if new image comes (from camera) to selected folder.
But sometimes when the file is still copying (from camera) to folder -
and I try to load it to ImageView I get black screen.

So I think it's because I try to load incomplete file. Right?

K.

ivImageFromUrl.setImageURI(lastImageUri);

if(howManyInTotal != numberOfFiles) {
    //we have new file so we need to load it
    loadLastImageFromUrl(folderUri);
    Log.d("FullscreenActivity","New image loaded.");
}


问:
Data are not in sequence in dataframe
```<code>from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import requests
from csv import writer

options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-gpu")
options.add_argument("--window-size=1920x1080")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
wait = WebDriverWait(driver, 20)

url='https://mergr.com/login'

driver.get(url)

email=driver.find_element(By.CSS_SELECTOR,"input#username")
email.send_keys("timgr8@outlook.com")

password=driver.find_element(By.CSS_SELECTOR,"input#password")
password.send_keys("Cosmos1990$$$$$$$")

login=driver.find_element(By.CSS_SELECTOR,"button.btn").click()
product=[]
for page in range(1,3):
        URL = 'https://mergr.com/firms/search/employees?page={page}&firm%5BactiveInvestor%5D=2&sortColumn=employee_weight&sortDirection=asc'.format(page=page)
        driver.get(URL)
        added_urls = []

        soup = BeautifulSoup(driver.page_source,"lxml")
        details = soup.select("tbody tr")
        for detail in details:

                try:
                        t1 = detail.select_one("h5.profile-title a").text
                except:
                        # pass # then you'll just be using the previous row's t1
                        # [also, if this happens in the first loop, it will raise an error]

                        t1 = 'MISSING' # '' #

                try:
                        t2=detail.select_one("h5.profile-title small").text
                except:
                        pass

                try:
                        t3=detail.select_one("h5.profile-title + p a").text
                except:
                        pass

                try:
                        t4=detail.select_one("a[title='Email']").text

                except:
                        t4=' '

                try:
                        t5=detail.select_one("p[class='font-alt']").get_text(' ',strip=True)
                except:
                        pass

                wev = {
                        'Name':t1,
                        'Title/position':t2,
                        'Company name':t3,
                        'Email address':t4,
                        'Bio':t5
                        }
                product.append(wev)

df=pd.DataFrame(product)
df.to_csv('firm.csv')
</code>```

The data are not coming sequence in csv file  so how to resolve that issue I want that data come in sequence like that Name,Title/position,Company name and so but data  do not come in sequence they come in no sequence  as you above kindly why the data are not come in sequence in dataframe what wrong was that.....kindly recommend what I am doing wrong there

Title: Data are not in sequence in dataframe

Body:
from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import requests
from csv import writer

options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-gpu")
options.add_argument("--window-size=1920x1080")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
wait = WebDriverWait(driver, 20)

url='https://mergr.com/login'

driver.get(url)

email=driver.find_element(By.CSS_SELECTOR,"input#username")
email.send_keys("timgr8@outlook.com")

password=driver.find_element(By.CSS_SELECTOR,"input#password")
password.send_keys("Cosmos1990$$$$$$$")

login=driver.find_element(By.CSS_SELECTOR,"button.btn").click()
product=[]
for page in range(1,3):
        URL = 'https://mergr.com/firms/search/employees?page={page}&firm%5BactiveInvestor%5D=2&sortColumn=employee_weight&sortDirection=asc'.format(page=page)
        driver.get(URL)
        added_urls = []

        soup = BeautifulSoup(driver.page_source,"lxml")
        details = soup.select("tbody tr")
        for detail in details:

                try:
                        t1 = detail.select_one("h5.profile-title a").text
                except:
                        # pass # then you'll just be using the previous row's t1
                        # [also, if this happens in the first loop, it will raise an error]

                        t1 = 'MISSING' # '' #

                try:
                        t2=detail.select_one("h5.profile-title small").text
                except:
                        pass

                try:
                        t3=detail.select_one("h5.profile-title + p a").text
                except:
                        pass

                try:
                        t4=detail.select_one("a[title='Email']").text

                except:
                        t4=' '

                try:
                        t5=detail.select_one("p[class='font-alt']").get_text(' ',strip=True)
                except:
                        pass

                wev = {
                        'Name':t1,
                        'Title/position':t2,
                        'Company name':t3,
                        'Email address':t4,
                        'Bio':t5
                        }
                product.append(wev)

df=pd.DataFrame(product)
df.to_csv('firm.csv')

The data are not coming sequence in csv file  so how to resolve that issue I want that data come in sequence like that Name,Title/position,Company name and so but data  do not come in sequence they come in no sequence  as you above kindly why the data are not come in sequence in dataframe what wrong was that.....kindly recommend what I am doing wrong there


问:
Why isn't the rect in the right style?
I can not find whats wrong with my code, it says that it's a type error but I cant find where.

I have been trying to figure out why the rect isn't considered to by in the right format but I cannot figure out why. Help would be appriciated, I am a beginner programer and have only been coding in python for about a week.

```<code>from players import Player
import pygame
import sys

pygame.init()

window_width, window_height = 1200, 800
window = pygame.display.set_mode((window_width, window_height))

pygame.display.set_caption("pong")

clock = pygame.time.Clock()
fps = 144

x = 50
y = 100
p_speed = 6
color = 200, 0, 0
width = 30
height = 100

def main():
    p = Player(x, y, p_speed, window, width, height, color)

    while True:
        clock.tick(fps)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        p.draw()

        pygame.display.update()

main()
</code>```
```<code>import pygame

class Player():
    def __init__(self, x, y, p_speed, height, width, window, color):
        self.x = x
        self.y = y
        self.speed = p_speed
        self.height = height
        self.width = width
        self.window = window
        self.color = color

    def draw(self):
        rect = pygame.Rect(self.x, self.y, self.height, self.width)

        pygame.draw.rect(self.window, self.color, rect)
</code>```

Title: Why isn't the rect in the right style?

Body:
I can not find whats wrong with my code, it says that it's a type error but I cant find where.

I have been trying to figure out why the rect isn't considered to by in the right format but I cannot figure out why. Help would be appriciated, I am a beginner programer and have only been coding in python for about a week.

from players import Player
import pygame
import sys

pygame.init()

window_width, window_height = 1200, 800
window = pygame.display.set_mode((window_width, window_height))

pygame.display.set_caption("pong")

clock = pygame.time.Clock()
fps = 144

x = 50
y = 100
p_speed = 6
color = 200, 0, 0
width = 30
height = 100

def main():
    p = Player(x, y, p_speed, window, width, height, color)

    while True:
        clock.tick(fps)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        p.draw()

        pygame.display.update()

main()

import pygame

class Player():
    def __init__(self, x, y, p_speed, height, width, window, color):
        self.x = x
        self.y = y
        self.speed = p_speed
        self.height = height
        self.width = width
        self.window = window
        self.color = color

    def draw(self):
        rect = pygame.Rect(self.x, self.y, self.height, self.width)

        pygame.draw.rect(self.window, self.color, rect)


问:
VS Code takes too long to start debugging in Git Bash with Zsh
I have configured Windows' Git Bash with Zsh it works like a charm. However, when I try to launch the debugger through VS Code it takes too long, it seems like it writes the command character by character instead of running right away. I would like to know if there is a workaround to fix this.

I have tried with PowerShell, and bash and this problem does not occur so, most probably it is a problem with Zsh for Windows.

Thank you so much for your help and you insights.


问:
Spring Batch Scheduling
I am new to Spring batch. I have to create batch jobs and these jobs should be scheduled as per the below parameters. Kindly help me in setting up the coding for the below batch job scheduling parameters mentioned. That would be a very kind help to me.

Job ID/ Job Description [we can even give a view of its underlying steps]

Frequency of trigger [In Cycles, daily once, Minutes, Hourly, specific
defined time, weekly,        fortnightly, monthly, quarterly] with its
respective threshold values e.g. day/time etc.

Retry attempts post dependency condition not met.

Retry attempts post exceptions.

Monitoring Alert communication hierarchy emails/ phone numbers [Level-1,
Level-2, etc.]

Monitoring Alert communication email/ SMS template.

Exceptions Alert communication hierarchy emails/ phone numbers [Level-1,
Level-2, etc.]

Exceptions Alert communication email/ SMS template

Title: Spring Batch Scheduling


问:
Rails directing to CDN when using CDN
I have a simple Rails app, that I've added the following config to:

  if ENV.has_key?("CDN_HOST")
    config.asset_host = ENV["CDN_HOST"]
    config.action_controller.asset_host = ENV["CDN_HOST"]
    config.static_cache_control = "public, s-maxage=2592000, max-age=86400"
    config.serve_static_assets = true
    config.assets.digest = true
  end
```
<p>This means I'm generating a page fine, and that page contains links to assets on the <code>CDN_HOST</code> domain.  However, if I try to access those assets they come back with a <code>301</code>, and the new location is the same CDN host:</p>
<pre class="lang-bash prettyprint-override"><code>▶ curl -I https://example.com/asset.afc04ebb.css
HTTP/1.1 301 Moved Permanently
...
Location: https://example.com/asset.afc04ebb.css
</code>```

and on the server

```<code> at=info method=GET path="/asset.afc04ebb.css" host=example request_id=fc8cc478-1bf0-4f02-95d4-8a7323282c23 fwd="82.129.107.192,140.248.83.44" dyno=web.1 connect=0ms service=1ms status=301 bytes=242 protocol=http
</code>```

This is obviously failing on too many redirects given that it's circular.

How can I debug/resolve this?  A lot of this is internal to Rails via config rather than code I can step through.

Title: Rails directing to CDN when using CDN

Body:
I have a simple Rails app, that I've added the following config to:

  if ENV.has_key?("CDN_HOST")
    config.asset_host = ENV["CDN_HOST"]
    config.action_controller.asset_host = ENV["CDN_HOST"]
    config.static_cache_control = "public, s-maxage=2592000, max-age=86400"
    config.serve_static_assets = true
    config.assets.digest = true
  end

This means I'm generating a page fine, and that page contains links to assets on the CDN_HOST domain.  However, if I try to access those assets they come back with a 301, and the new location is the same CDN host:

▶ curl -I https://example.com/asset.afc04ebb.css
HTTP/1.1 301 Moved Permanently
...
Location: https://example.com/asset.afc04ebb.css

and on the server

 at=info method=GET path="/asset.afc04ebb.css" host=example request_id=fc8cc478-1bf0-4f02-95d4-8a7323282c23 fwd="82.129.107.192,140.248.83.44" dyno=web.1 connect=0ms service=1ms status=301 bytes=242 protocol=http

This is obviously failing on too many redirects given that it's circular.

How can I debug/resolve this?  A lot of this is internal to Rails via config rather than code I can step through.


问:
How can I expire a user logged in using active directory in a windows forms application?
We are using Active Directory to authenticate users in our Windows application.  The problem is once they log in, they are never prompted again.  We would like the ?token? to expire after 24 hours, but we have not been able to figure out how to do that.

The application is an old Windows Forms VB.NET application using .NET 4.8.  I have not been able to figure out if it is something we can code or if it is something we configure in the Azure Portal?

I tried messing with the cache creation, but that doesn't seem to do anything.


问:
Problem to execute https connection from a servlet: http 404 error occours
From my Tomcat's servlet I execute an https connection to an external servlet.
This is the code:

```<code>    HttpsURLConnection hpcon = null;
    try {
        URL url = new URL(surl);
        hpcon = (HttpsURLConnection) url.openConnection();
        hpcon.setRequestMethod("POST");
        hpcon.setDoInput(true);
        hpcon.setDoOutput(true);
        hpcon.setUseCaches(false);
        hpcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        OutputStreamWriter wr = new OutputStreamWriter(hpcon.getOutputStream());
        String params = "user=" + URLEncoder.encode(user, "UTF-8");
        params += "&psswd=" + URLEncoder.encode(pssw, "UTF-8");
        params += "&metodo=" + URLEncoder.encode(metodo, "UTF-8");
        wr.write(params);
        wr.flush();
        wr.close();
        hpcon.connect();
        int respCode = hpcon.getResponseCode();
        if (respCode == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(hpcon.getInputStream()));
            String response = "";
            String output;
            while ((output = br.readLine()) != null) {
                response += output;
            }
            if (response.indexOf("-") > 0) {
                response = "-12";
                System.out.println("ret = -12 - response = " + response);
            }
            br.close();
        } else {
            ret = "-11";
            System.out.println("ret = -11 - respCode = " + respCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
        ret = "-10";
        System.out.println("ret = -10");
    } finally {
        if (hpcon != null) {
            hpcon.disconnect();
        }
    }
</code>```

Where surl is the full url of a servlet present in a different domain and the three parameters are read from a db table (the third really is fixed and is the operation that is make by the external servlet).
The result is:
ret = -11 - respCode = 404

Before make the connection I turn off the certificate's verify using the above code:

```<code>try {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }};
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

If I execute the same servlet manually from a browser with parameters in get mode all run correctly.

I tried to execute it on my code using the get mode and passing the three parameters in query string, but the result is the same.

How can I do to resolve the problem?

Body:
From my Tomcat's servlet I execute an https connection to an external servlet.
This is the code:

    HttpsURLConnection hpcon = null;
    try {
        URL url = new URL(surl);
        hpcon = (HttpsURLConnection) url.openConnection();
        hpcon.setRequestMethod("POST");
        hpcon.setDoInput(true);
        hpcon.setDoOutput(true);
        hpcon.setUseCaches(false);
        hpcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        OutputStreamWriter wr = new OutputStreamWriter(hpcon.getOutputStream());
        String params = "user=" + URLEncoder.encode(user, "UTF-8");
        params += "&psswd=" + URLEncoder.encode(pssw, "UTF-8");
        params += "&metodo=" + URLEncoder.encode(metodo, "UTF-8");
        wr.write(params);
        wr.flush();
        wr.close();
        hpcon.connect();
        int respCode = hpcon.getResponseCode();
        if (respCode == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(hpcon.getInputStream()));
            String response = "";
            String output;
            while ((output = br.readLine()) != null) {
                response += output;
            }
            if (response.indexOf("-") > 0) {
                response = "-12";
                System.out.println("ret = -12 - response = " + response);
            }
            br.close();
        } else {
            ret = "-11";
            System.out.println("ret = -11 - respCode = " + respCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
        ret = "-10";
        System.out.println("ret = -10");
    } finally {
        if (hpcon != null) {
            hpcon.disconnect();
        }
    }

Where surl is the full url of a servlet present in a different domain and the three parameters are read from a db table (the third really is fixed and is the operation that is make by the external servlet).
The result is:
ret = -11 - respCode = 404

Before make the connection I turn off the certificate's verify using the above code:

try {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }};
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (Exception e) {
        e.printStackTrace();
    }

If I execute the same servlet manually from a browser with parameters in get mode all run correctly.

I tried to execute it on my code using the get mode and passing the three parameters in query string, but the result is the same.

How can I do to resolve the problem?


问:
How to upload a file to Azure Blob storage from Angular
I am getting error attached when i try to upload a file from angular. But, the same azure storage account configuration working from asp.net but not from angular. Can you please help me on this?cors error azure blob storage

I am trying to upload a file to azure blob storage from angular, the below is the code that, i implemented. I have directly added the sas token url instead of generating it to check whether file upload works or not.

below is the code

```<code>// environment file

export const environment = {
  production: false,
  accountName : "<accountname>",
  containerName:"<containername>",
   key:"<key>"
};

// added in pollyfills
(window as any).global = window;
 (window as any).process = require( 'process' );
 (window as any).Buffer = require( 'buffer' ).Buffer

//file upload method`

async uploadFileToBlob() {
    // generate account sas token
    const accountName = environment.accountName;
    const key = environment.key;

    var str = CryptoJS.HmacSHA256(StringToSign, CryptoJS.enc.Base64.parse(key));
    var sig = CryptoJS.enc.Base64.stringify(str);

    const sasToken = `sp=rac&st=2022-11-21T15:37:13Z&se=2023-12-31T23:37:13Z&spr=https&sv=2021-06-08&sr=c&sig=rYx4JWTcGPVSceUkuxJDSXN8u1%2BbNSFh3A7dYPqw3EA%3D`;
    const containerName = environment.containerName;

    const pipeline = newPipeline(new AnonymousCredential(), {
      retryOptions: { maxTries: 4 }, // Retry options
      userAgentOptions: { userAgentPrefix: "AdvancedSample V1.0.0" }, // Customized telemetry string
      keepAliveOptions: {
        // Keep alive is enabled by default, disable keep alive by setting false
        enable: false
      }
    });

    const blobServiceClient = new BlobServiceClient(`https://${accountName}.blob.core.windows.net?${sasToken}`,
      pipeline)
    const containerClient = blobServiceClient.getContainerClient(containerName)
    if (!containerClient.exists()) {
      console.log("the container does not exit")
      await containerClient.create()

    }
    const client = containerClient.getBlockBlobClient(this.fileName.name)
    const response = await client.uploadData(this.fileName, {
      blockSize: 4 * 1024 * 1024, // 4MB block size
      concurrency: 20, // 20 concurrency
      onProgress: (ev) => console.log(ev),
      blobHTTPHeaders: { blobContentType: this.fileName.type }
    })
    console.log(response._response.status)
  }
</code>```

Can you help me to resolve this issue ?

Body:
I am getting error attached when i try to upload a file from angular. But, the same azure storage account configuration working from asp.net but not from angular. Can you please help me on this?cors error azure blob storage

I am trying to upload a file to azure blob storage from angular, the below is the code that, i implemented. I have directly added the sas token url instead of generating it to check whether file upload works or not.

below is the code

// environment file

export const environment = {
  production: false,
  accountName : "<accountname>",
  containerName:"<containername>",
   key:"<key>"
};

// added in pollyfills
(window as any).global = window;
 (window as any).process = require( 'process' );
 (window as any).Buffer = require( 'buffer' ).Buffer

//file upload method`

async uploadFileToBlob() {
    // generate account sas token
    const accountName = environment.accountName;
    const key = environment.key;

    var str = CryptoJS.HmacSHA256(StringToSign, CryptoJS.enc.Base64.parse(key));
    var sig = CryptoJS.enc.Base64.stringify(str);

    const sasToken = `sp=rac&st=2022-11-21T15:37:13Z&se=2023-12-31T23:37:13Z&spr=https&sv=2021-06-08&sr=c&sig=rYx4JWTcGPVSceUkuxJDSXN8u1%2BbNSFh3A7dYPqw3EA%3D`;
    const containerName = environment.containerName;

    const pipeline = newPipeline(new AnonymousCredential(), {
      retryOptions: { maxTries: 4 }, // Retry options
      userAgentOptions: { userAgentPrefix: "AdvancedSample V1.0.0" }, // Customized telemetry string
      keepAliveOptions: {
        // Keep alive is enabled by default, disable keep alive by setting false
        enable: false
      }
    });

    const blobServiceClient = new BlobServiceClient(`https://${accountName}.blob.core.windows.net?${sasToken}`,
      pipeline)
    const containerClient = blobServiceClient.getContainerClient(containerName)
    if (!containerClient.exists()) {
      console.log("the container does not exit")
      await containerClient.create()

    }
    const client = containerClient.getBlockBlobClient(this.fileName.name)
    const response = await client.uploadData(this.fileName, {
      blockSize: 4 * 1024 * 1024, // 4MB block size
      concurrency: 20, // 20 concurrency
      onProgress: (ev) => console.log(ev),
      blobHTTPHeaders: { blobContentType: this.fileName.type }
    })
    console.log(response._response.status)
  }

Can you help me to resolve this issue ?


问:
CS50 pset4 recover > program is free of memory errors
I finished writing the program that recovers photos from a memory card and it's working properly
But there is an error closing the "output"file.
I just want to know where to write another "fclose"

This is the error:

:( program is free of memory errors
Cause
valgrind tests failed; see log for more information.
Log
running valgrind --show-leak-kinds=all --xml=yes --xml-file=/tmp/tmpie2_4mb5 -- ./recover card.raw...
checking that program exited with status 0...
checking for valgrind errors...
23,128 bytes in 49 blocks are still reachable in loss record 1 of 1: (file: recover.c, line: 35)

the problem in " output = fopen(fileName, "w"); "
`

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define BLOCK_SIZE 512

int main(int argc, char *argv[])
{
    // Check command-line arguments
    if (argc != 2)
    {
        printf("Usage: ./recover IMAGE\n");
        return 1;
    }

    // Open files and determine scaling factor
    FILE* input = fopen(argv[1], "r");
    if (input == NULL)
    {
        printf("Could not open file.\n");
        return 1;
    }

    FILE* output = NULL; //output_file
    typedef uint8_t BYTE;
    BYTE buffer[BLOCK_SIZE]; //buffer = 512
    char fileName[8]; // =malloc
    int count = 0; //count image

    while (fread(buffer, BLOCK_SIZE, sizeof(BYTE), input))
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer [3] & 0xf0) == 0xe0)
        {
            sprintf(fileName, "%03i.jpg", count);
            output = fopen(fileName, "w");
            count++;
        }
        if (output != NULL)
        {
            fwrite(buffer, BLOCK_SIZE, sizeof(BYTE), output);
        }
    }
    fclose(input);
    fclose(output);

    return 0;
}
</code>```

`

Body:
I finished writing the program that recovers photos from a memory card and it's working properly
But there is an error closing the "output"file.
I just want to know where to write another "fclose"

This is the error:

:( program is free of memory errors
Cause
valgrind tests failed; see log for more information.
Log
running valgrind --show-leak-kinds=all --xml=yes --xml-file=/tmp/tmpie2_4mb5 -- ./recover card.raw...
checking that program exited with status 0...
checking for valgrind errors...
23,128 bytes in 49 blocks are still reachable in loss record 1 of 1: (file: recover.c, line: 35)

the problem in " output = fopen(fileName, "w"); "
`

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define BLOCK_SIZE 512

int main(int argc, char *argv[])
{
    // Check command-line arguments
    if (argc != 2)
    {
        printf("Usage: ./recover IMAGE\n");
        return 1;
    }

    // Open files and determine scaling factor
    FILE* input = fopen(argv[1], "r");
    if (input == NULL)
    {
        printf("Could not open file.\n");
        return 1;
    }

    FILE* output = NULL; //output_file
    typedef uint8_t BYTE;
    BYTE buffer[BLOCK_SIZE]; //buffer = 512
    char fileName[8]; // =malloc
    int count = 0; //count image

    while (fread(buffer, BLOCK_SIZE, sizeof(BYTE), input))
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer [3] & 0xf0) == 0xe0)
        {
            sprintf(fileName, "%03i.jpg", count);
            output = fopen(fileName, "w");
            count++;
        }
        if (output != NULL)
        {
            fwrite(buffer, BLOCK_SIZE, sizeof(BYTE), output);
        }
    }
    fclose(input);
    fclose(output);

    return 0;
}

`


问:
Compiling OpenSSL 3.0.0 on Win x64 - how to specify FIPS in config
I am able to successfully compile openssl 3.0.0 using VS 2022 on Win x64 environment.
However, I am not able to find where does the configuration to do a FIPS compliant compilation needs to be specified.

The question here is helpful, but is outdated. The method here is not applicable any more since the manual specifies that the openssl fipsinstall does not work for openssl3.0.0 alpha release 16 onwards ([here])3

I need some guidance on how to specify FIPS capability to the configuration file for compiling this on Win 64 using VS.

Thanks for your attention and time


问:
CCXT fetch_ohlcv returns too much data when inside for loop
I have a function that takes data of the given minute and successfully takes the requested data:

```<code>def getBTC_data_from_binance(date):
   exchange = ccxt.binance()
   timestamp = int(datetime.datetime.strptime(f"{date}+00:00", "%Y-%m-%d %H:%M:%S%z").timestamp() * 1000
   time.sleep(2)
   response = exchange.fetch_ohlcv('BTC/USDT', '1m', timestamp, 1)
   print(response)
   response = response[0]
   timestamp = response[0]
   exact_value = response[1]
   open_value = response[1]
   high = response[2]
   low = response[3]
   close = response[4]
   print('\nbefore putting data in dict')
   btc_data = {
    'timestamp': date,
    'exact_value': exact_value,
    'open_value': open_value,
    'high': high,
    'low': low,
    'close': close,
   }
   print(btc_data)
   return btc_data
</code>```

This is the output:

{'timestamp': '2022-12-14 12:26:00', 'exact_value': 17863.79, 'open_value': 17863.79, 'high': 17880.0, 'low': 17862.58, 'close': 17877.46}

Now I want to call this function from a different one, inside a for loop:

```<code>def parse(self, response):
   acts = response.xpath("//*[@id='table_maina']/tbody/tr")
   for act in acts:
      ...
      btc_data = getBTC_data_from_binance(utc_datetime)
      print(btc_data)
</code>```

The issue is that when I run "parse" function which is only supposed to read different utc_datetime(a string) I get much more data then when I run "getBTC_data..." by itself:

[ccxt.base.exchange] DEBUG: GET https://api.binance.com/api/v3/exchangeInfo, Request: {'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '/', 'Connection': 'keep-alive'} None
[urllib3.connectionpool] DEBUG: Starting new HTTPS connection (1): api.binance.com:443
[urllib3.connectionpool] DEBUG: https://api.binance.com:443 "GET /api/v3/exchangeInfo HTTP/1.1" 200 75390
[ccxt.base.exchange] DEBUG: GET https://api.binance.com/api/v3/exchangeInfo, Response: 200 {'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '75390', 'Connection': 'keep-alive', 'Date': 'Wed, 14 Dec 2022 15:45:08 GMT', 'Server': 'nginx', 'x-mbx-uuid': 'cbe7dda3-a807-405c-ade2-ad191cd3a16b', 'x-mbx-used-weight': '10', 'x-mbx-used-weight-1m': '10', 'content-encoding': 'gzip', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block' ...

How can I get rid of all these data and keep it like I get it initially?

Body:
I have a function that takes data of the given minute and successfully takes the requested data:

def getBTC_data_from_binance(date):
   exchange = ccxt.binance()
   timestamp = int(datetime.datetime.strptime(f"{date}+00:00", "%Y-%m-%d %H:%M:%S%z").timestamp() * 1000
   time.sleep(2)
   response = exchange.fetch_ohlcv('BTC/USDT', '1m', timestamp, 1)
   print(response)
   response = response[0]
   timestamp = response[0]
   exact_value = response[1]
   open_value = response[1]
   high = response[2]
   low = response[3]
   close = response[4]
   print('\nbefore putting data in dict')
   btc_data = {
    'timestamp': date,
    'exact_value': exact_value,
    'open_value': open_value,
    'high': high,
    'low': low,
    'close': close,
   }
   print(btc_data)
   return btc_data

This is the output:

{'timestamp': '2022-12-14 12:26:00', 'exact_value': 17863.79, 'open_value': 17863.79, 'high': 17880.0, 'low': 17862.58, 'close': 17877.46}

Now I want to call this function from a different one, inside a for loop:

def parse(self, response):
   acts = response.xpath("//*[@id='table_maina']/tbody/tr")
   for act in acts:
      ...
      btc_data = getBTC_data_from_binance(utc_datetime)
      print(btc_data)

The issue is that when I run "parse" function which is only supposed to read different utc_datetime(a string) I get much more data then when I run "getBTC_data..." by itself:

[ccxt.base.exchange] DEBUG: GET https://api.binance.com/api/v3/exchangeInfo, Request: {'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '/', 'Connection': 'keep-alive'} None
[urllib3.connectionpool] DEBUG: Starting new HTTPS connection (1): api.binance.com:443
[urllib3.connectionpool] DEBUG: https://api.binance.com:443 "GET /api/v3/exchangeInfo HTTP/1.1" 200 75390
[ccxt.base.exchange] DEBUG: GET https://api.binance.com/api/v3/exchangeInfo, Response: 200 {'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '75390', 'Connection': 'keep-alive', 'Date': 'Wed, 14 Dec 2022 15:45:08 GMT', 'Server': 'nginx', 'x-mbx-uuid': 'cbe7dda3-a807-405c-ade2-ad191cd3a16b', 'x-mbx-used-weight': '10', 'x-mbx-used-weight-1m': '10', 'content-encoding': 'gzip', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block' ...

How can I get rid of all these data and keep it like I get it initially?


问:
Why am I getting "Cannot read properties of undefined (reading 'hasOwnProperty')" for an Autocomplete component
I am using the Autocomplete MUI component in a Preact app using Preact-cli. When I click into the textfield of the autocomplete component I get the following error.

```<code>Failed prop type: Cannot read properties of undefined (reading 'hasOwnProperty')
  in ForwardRef()
  in ForwardRef()
  in MuiPopperRoot
  in ForwardRef()
  in MuiAutocompletePopper
  in ForwardRef() (at /Users/name/code/parlibre/src/components/app.js:23)
</code>```

I am using the following Autocomplete component for testing purposes.

```<code><Autocomplete
   id="autocomplete"
   options={['1', '2', '3']}
   renderInput={(params) => <TextField {...params} label="autocomplete" />}
/>
</code>```

This problem occurs when I build and serve using:

```<code>npm run build
npm run serve
</code>```

but does not occur when I run it in a dev environment using:
npm run dev

Body:
I am using the Autocomplete MUI component in a Preact app using Preact-cli. When I click into the textfield of the autocomplete component I get the following error.

Failed prop type: Cannot read properties of undefined (reading 'hasOwnProperty')
  in ForwardRef()
  in ForwardRef()
  in MuiPopperRoot
  in ForwardRef()
  in MuiAutocompletePopper
  in ForwardRef() (at /Users/name/code/parlibre/src/components/app.js:23)

I am using the following Autocomplete component for testing purposes.

<Autocomplete
   id="autocomplete"
   options={['1', '2', '3']}
   renderInput={(params) => <TextField {...params} label="autocomplete" />}
/>

This problem occurs when I build and serve using:

npm run build
npm run serve

but does not occur when I run it in a dev environment using:
npm run dev


问:
Getting Error on Windows 11: (provider: SSL Provider, error: 0 - An existing connection was forcibly closed by the remote host.)
we have bought some new devices with Windows 11 pro and want to connect to our old voip server. He has a Microsoft SQL Server 2008R2 installed and we get this error on our self programme that trys a connection.

(provider: SSL Provider, error: 0 - An existing connection was forcibly closed by the remote host.)

But we don´t know why, because all other devices with Windows 10 have no problems at all. It is only on Windows 11. Now the funny part, we have installed a vm on our server with windows 11 (tweak needet for no tpm2.0 and CPU Support) but it runs. In this installation we have no problem to connect to the SQL Server.

So we have deactivated on the notebooks TPM. But that didn´t help.
Have anyone a hint?


问:
Printing data past .head()
I am using this example to print zip codes given latitudes and longitudes: How do I get zipcodes from longitude and latitude on python?

The first answer got me what I needed. However, now I want to print all data and not just the first five rows (.head())

Even if I just change longlat.head() to longlat. I get this error: KeyError: 'postcode'

How do I get around this and get the function to print for all and not just the first 5?

I tried to change and get rid of the .head() part of the function but I get errors.

Title: Printing data past .head()


问:
how to import fonts-family in react project
hi i want to use this font in my project how I can?</p>
```<code>Söhne, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Ubuntu, Cantarell, "Noto Sans", sans-serif, "Helvetica Neue", Arial, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";

</code>```

Body:
hi i want to use this font in my project how I can?

Söhne, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Ubuntu, Cantarell, "Noto Sans", sans-serif, "Helvetica Neue", Arial, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";


问:
MSAL4J - Token not found in the cache
When attempting to use the method PublicClientApplication.acquireTokenSilently() I am getting the error "Token not found in cache". It looks like it is failing to be stored. Our AuthenticationResult looks like this:

```<code>{
    "accessToken": "...",
    "expiresOn": 1671035322,
    "extExpiresOn": 0,
    "refreshOn": 0,
    "idToken": "...",
    "idTokenObject": {},
    "accountCacheEntity": {
        "homeAccountId": "...",
        "environment": "URL",
        "name": "username",
        "authorityType": "ADFS"
    },
    "account": {
        "value": {
            "homeAccountId": "...",
            "environment": "URL"
        }
    },
    "tenantProfile": {},
    "environment": "env",
    "expiresOnDate": {
        "value": "Dec 14, 2022 11:28:42 AM"
    },
    "scopes": "openid"
}
</code>```

I see that the account is missing the "name" field and I am wondering if that is part of it.  I'm not quite sure how to work around this issue.

I've looked at the source and it appears that result.account().username() is returning null.  I'm not sure if there is a way to use the value in accountCacheEntity.

Title: MSAL4J - Token not found in the cache

Body:
When attempting to use the method PublicClientApplication.acquireTokenSilently() I am getting the error "Token not found in cache". It looks like it is failing to be stored. Our AuthenticationResult looks like this:

{
    "accessToken": "...",
    "expiresOn": 1671035322,
    "extExpiresOn": 0,
    "refreshOn": 0,
    "idToken": "...",
    "idTokenObject": {},
    "accountCacheEntity": {
        "homeAccountId": "...",
        "environment": "URL",
        "name": "username",
        "authorityType": "ADFS"
    },
    "account": {
        "value": {
            "homeAccountId": "...",
            "environment": "URL"
        }
    },
    "tenantProfile": {},
    "environment": "env",
    "expiresOnDate": {
        "value": "Dec 14, 2022 11:28:42 AM"
    },
    "scopes": "openid"
}

I see that the account is missing the "name" field and I am wondering if that is part of it.  I'm not quite sure how to work around this issue.

I've looked at the source and it appears that result.account().username() is returning null.  I'm not sure if there is a way to use the value in accountCacheEntity.


问:
Create-react-app : Module not found: Error: Can't resolve
Using Create-react-app with VS2022 (typescript)

what I tried :

Tried the Javascript and Typescript version

delete the package-lock.json and npm install

delete the node_modules and npm install

added  "moduleResolution": "node",

A folder named "gitlab_auth" exists in ./node_modules

Browser :

```<code>Compiled with problems:X

ERROR in ./src/App.tsx 6:0-37

Module not found: Error: Can't resolve 'gitlab-auth' in 'C:\XXX\repos\CustomBoard\src'
</code>```

App.tsx :

```<code>import React from 'react';
import logo from './logo.svg';
import './App.css';
import GitlabAuth from "gitlab-auth";

function App() {
    return (
        <div className="App">
            <header className="App-header">
                <GitlabAuth
                    host="https://gitlab.local/"
                    application_id="123456789"
                    redirect_uri="http://localhost:3000/"
                    scope="read_api openid profile email"
                    >
                    <>This is rendered with GitLab access!</>
                </GitlabAuth>
            </header>
        </div>
    );
}

export default App;
</code>```

tsconfig.json :

```<code>{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src",
    "./node_modules/**/*"
  ]
}
</code>```

What I did wring? Thank you!

Body:
Using Create-react-app with VS2022 (typescript)

what I tried :

Tried the Javascript and Typescript version

delete the package-lock.json and npm install

delete the node_modules and npm install

added  "moduleResolution": "node",

A folder named "gitlab_auth" exists in ./node_modules

Browser :

Compiled with problems:X

ERROR in ./src/App.tsx 6:0-37

Module not found: Error: Can't resolve 'gitlab-auth' in 'C:\XXX\repos\CustomBoard\src'

App.tsx :

import React from 'react';
import logo from './logo.svg';
import './App.css';
import GitlabAuth from "gitlab-auth";

function App() {
    return (

                <GitlabAuth
                    host="https://gitlab.local/"
                    application_id="123456789"
                    redirect_uri="http://localhost:3000/"
                    scope="read_api openid profile email"
                    >
                    <>This is rendered with GitLab access!</>
                </GitlabAuth>

    );
}

export default App;

tsconfig.json :

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src",
    "./node_modules/**/*"
  ]
}

What I did wring? Thank you!


问:
How can I send someone my app through internet
I have built an Android app using Android Studio and I need to download the app on some other phone. I can't access the phone physically, so I can't connect it to my computer via USB and install it on the phone. I need a way to send the app files to the user via internet so that they can download and install and test the app. How can I accomplish this?</p>


问:
Google Analytics - Event Goal Completions much higher than Total Event numbers...Why?
I've been racking my brain trying to figure this out.

For the event goal setup, I've specified the category, action and label for the event I want tracked.

Why are goal completions so much higher - 70% higher!

Anyone have an idea why?

I was expecting goal completions to be lower than event number, since goal completions only track 1 completion per session compared to events which track every single one in a session.


问:
TextBox in RadGridViewColumn IN WPF
There is a textbox in the gridviewColumn And a ComboBox in the other column In need to set the TextBox  read only true and readOnly False On the section On COmboBox.</p>
```<code><telerik:GridViewDataColumn x:Name="requstamount" Header="Request Amount" Width="200">
    <telerik:GridViewColumn.CellTemplate >
        <DataTemplate>
            <TextBox IsEnabled="{Binding IsTextBoxEnabled, StringFormat=c, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                     Name="txtPaymentAMNT"
                     Text="{Binding PaymentAmount, StringFormat=c, UpdateSourceTrigger=PropertyChanged}"
                     Background="Transparent"
                     LostFocus="text_LostFocus"
                     BorderBrush="LightGray"
                     BorderThickness="0,0,0,3"
                     Width="141"
                     Margin="-5,0,0,0" />
        </DataTemplate>

    </telerik:GridViewColumn.CellTemplate>
</telerik:GridViewDataColumn>

<telerik:GridViewDataColumn Header="Request Type" Width="150">
    <telerik:GridViewColumn.CellTemplate >
        <DataTemplate>
            <telerik:RadComboBox x:Name="cboType"
                                 Background="Transparent"
                                 HorizontalAlignment="Left"
                                 BorderBrush="blue"
                                 BorderThickness="0,0,0,1"
                                 Margin="-5,0,0,0"
                                 telerik:StyleManager.Theme="Office2019"
                                 Width="100"
                                 Height="25"
                                 SelectedIndex="{Binding Path=Reqsttype, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                 SelectionChanged="cmbType_SelectionChanged"
                                 SelectedValuePath="{Binding OrderNo}">
                <telerik:RadComboBoxItem Name="Pre_Auth" IsSelected="True">
                    Pre-Auth
                </telerik:RadComboBoxItem>
                <telerik:RadComboBoxItem Name="Deposit">
                    Deposit
                </telerik:RadComboBoxItem>
            </telerik:RadComboBox>
        </DataTemplate>
    </telerik:GridViewColumn.CellTemplate>
</telerik:GridViewDataColumn>
</code>```

Title: TextBox in RadGridViewColumn IN WPF

Body:
There is a textbox in the gridviewColumn And a ComboBox in the other column In need to set the TextBox  read only true and readOnly False On the section On COmboBox.

<telerik:GridViewDataColumn x:Name="requstamount" Header="Request Amount" Width="200">
    <telerik:GridViewColumn.CellTemplate >
        <DataTemplate>
            <TextBox IsEnabled="{Binding IsTextBoxEnabled, StringFormat=c, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                     Name="txtPaymentAMNT"
                     Text="{Binding PaymentAmount, StringFormat=c, UpdateSourceTrigger=PropertyChanged}"
                     Background="Transparent"
                     LostFocus="text_LostFocus"
                     BorderBrush="LightGray"
                     BorderThickness="0,0,0,3"
                     Width="141"
                     Margin="-5,0,0,0" />
        </DataTemplate>

    </telerik:GridViewColumn.CellTemplate>
</telerik:GridViewDataColumn>

<telerik:GridViewDataColumn Header="Request Type" Width="150">
    <telerik:GridViewColumn.CellTemplate >
        <DataTemplate>
            <telerik:RadComboBox x:Name="cboType"
                                 Background="Transparent"
                                 HorizontalAlignment="Left"
                                 BorderBrush="blue"
                                 BorderThickness="0,0,0,1"
                                 Margin="-5,0,0,0"
                                 telerik:StyleManager.Theme="Office2019"
                                 Width="100"
                                 Height="25"
                                 SelectedIndex="{Binding Path=Reqsttype, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                 SelectionChanged="cmbType_SelectionChanged"
                                 SelectedValuePath="{Binding OrderNo}">
                <telerik:RadComboBoxItem Name="Pre_Auth" IsSelected="True">
                    Pre-Auth
                </telerik:RadComboBoxItem>
                <telerik:RadComboBoxItem Name="Deposit">
                    Deposit
                </telerik:RadComboBoxItem>
            </telerik:RadComboBox>
        </DataTemplate>
    </telerik:GridViewColumn.CellTemplate>
</telerik:GridViewDataColumn>


问:
Organize .faa file into dataframe using tidyr::extract and a regex
I'm trying to convert .faa file with 30.799 elements of protein sequences to a tabular format by separating IDs in one column, names in other column, and sequence to another column. An FAA file stores a record of one or more nucleic acid or protein sequences saved in the FASTA format. It can be considered as list of FASTA.

I have tried this solution written by @Martin Morgan

I couldn't go further due to having this issue of "Error: `regex` should define 2 groups; 4 found.". Since I did not quite understand regex, I couldn't manage to do it.

Data:
https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/001/215/GCF_000001215.4_Release_6_plus_ISO1_MT/GCF_000001215.4_Release_6_plus_ISO1_MT_protein.faa.gz

```<code>library(seqinr)
library(dplyr)
library(tidyr)
install.packages("BiocManager")
library(BiocManager)
BiocManager::install("Biostrings")
library(Biostrings)

url <- "https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/001/215/GCF_000001215.4_Release_6_plus_ISO1_MT/GCF_000001215.4_Release_6_plus_ISO1_MT_protein.faa.gz"
destfile <- tempfile()
download.file(url, destfile)

fruitfly <- readAAStringSet(destfile)
head(names(fruitfly), 3) #it returns good outcome. Try to separate it.

fields <-
  names(fruitfly) |>
  dplyr::as_tibble() |>
  tidyr::extract(
    "value",
    into = c(
      "names", "seq"
    ),
    regex = "^(.+)\\|(.+)\\|([^ ]+) (.*)"
  )
</code>```

It gives

"Error: regex should define 2 groups; 4 found.". Since I did not quite understand regex, I couldn't manage to do it.

Here is an overview of the data.

```<code>> print(fruitfly[30796])
AAStringSet object of length 1:
    width seq                                                                                names
[1]    96 MIMILYWSLPMILFILGLFCFVSNRKHLLSMLLSLEFIVLMLFFMLFIYLNMLNYESYFSMMFLTFSVCEGALGLSILVSMIRTHGNDYFQSFSIM         YP_009047275.1 NA...

> str(fruitfly)
Formal class 'AAStringSet' [package "Biostrings"] with 5 slots
  ..@ pool           :Formal class 'SharedRaw_Pool' [package "XVector"] with 2 slots
  .. .. ..@ xp_list                    :List of 1
  .. .. .. ..$ :<externalptr>
  .. .. ..@ .link_to_cached_object_list:List of 1
  .. .. .. ..$ :<environment: 0x000002140e4d4de8>
  ..@ ranges         :Formal class 'GroupedIRanges' [package "XVector"] with 7 slots
  .. .. ..@ group          : int [1:30799] 1 1 1 1 1 1 1 1 1 1 ...
  .. .. ..@ start          : int [1:30799] 1 1526 3051 4186 4814 5442 5828 5945 6413 6935 ...
  .. .. ..@ width          : int [1:30799] 1525 1525 1135 628 628 386 117 468 522 294 ...
  .. .. ..@ NAMES          : chr [1:30799] "NP_001007096.1 uncharacterized protein Dmel_CG42637, isoform C [Drosophila melanogaster]" "NP_001007097.1 uncharacterized protein Dmel_CG42637, isoform B [Drosophila melanogaster]" "NP_001014453.1 phosphatase 1 nuclear targeting subunit, isoform D [Drosophila melanogaster]" "NP_001014454.1 phosphatase 1 nuclear targeting subunit, isoform A [Drosophila melanogaster]" ...
  .. .. ..@ elementType    : chr "ANY"
  .. .. ..@ elementMetadata: NULL
  .. .. ..@ metadata       : list()
  ..@ elementType    : chr "AAString"
  ..@ elementMetadata: NULL
  ..@ metadata       : list()
</code>```

Body:
I'm trying to convert .faa file with 30.799 elements of protein sequences to a tabular format by separating IDs in one column, names in other column, and sequence to another column. An FAA file stores a record of one or more nucleic acid or protein sequences saved in the FASTA format. It can be considered as list of FASTA.

I have tried this solution written by @Martin Morgan

I couldn't go further due to having this issue of "Error: `regex` should define 2 groups; 4 found.". Since I did not quite understand regex, I couldn't manage to do it.

Data:
https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/001/215/GCF_000001215.4_Release_6_plus_ISO1_MT/GCF_000001215.4_Release_6_plus_ISO1_MT_protein.faa.gz

library(seqinr)
library(dplyr)
library(tidyr)
install.packages("BiocManager")
library(BiocManager)
BiocManager::install("Biostrings")
library(Biostrings)

url <- "https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/001/215/GCF_000001215.4_Release_6_plus_ISO1_MT/GCF_000001215.4_Release_6_plus_ISO1_MT_protein.faa.gz"
destfile <- tempfile()
download.file(url, destfile)

fruitfly <- readAAStringSet(destfile)
head(names(fruitfly), 3) #it returns good outcome. Try to separate it.

fields <-
  names(fruitfly) |>
  dplyr::as_tibble() |>
  tidyr::extract(
    "value",
    into = c(
      "names", "seq"
    ),
    regex = "^(.+)\\|(.+)\\|([^ ]+) (.*)"
  )

It gives

"Error: regex should define 2 groups; 4 found.". Since I did not quite understand regex, I couldn't manage to do it.

Here is an overview of the data.

> print(fruitfly[30796])
AAStringSet object of length 1:
    width seq                                                                                names
[1]    96 MIMILYWSLPMILFILGLFCFVSNRKHLLSMLLSLEFIVLMLFFMLFIYLNMLNYESYFSMMFLTFSVCEGALGLSILVSMIRTHGNDYFQSFSIM         YP_009047275.1 NA...

> str(fruitfly)
Formal class 'AAStringSet' [package "Biostrings"] with 5 slots
  ..@ pool           :Formal class 'SharedRaw_Pool' [package "XVector"] with 2 slots
  .. .. ..@ xp_list                    :List of 1
  .. .. .. ..$ :<externalptr>
  .. .. ..@ .link_to_cached_object_list:List of 1
  .. .. .. ..$ :<environment: 0x000002140e4d4de8>
  ..@ ranges         :Formal class 'GroupedIRanges' [package "XVector"] with 7 slots
  .. .. ..@ group          : int [1:30799] 1 1 1 1 1 1 1 1 1 1 ...
  .. .. ..@ start          : int [1:30799] 1 1526 3051 4186 4814 5442 5828 5945 6413 6935 ...
  .. .. ..@ width          : int [1:30799] 1525 1525 1135 628 628 386 117 468 522 294 ...
  .. .. ..@ NAMES          : chr [1:30799] "NP_001007096.1 uncharacterized protein Dmel_CG42637, isoform C [Drosophila melanogaster]" "NP_001007097.1 uncharacterized protein Dmel_CG42637, isoform B [Drosophila melanogaster]" "NP_001014453.1 phosphatase 1 nuclear targeting subunit, isoform D [Drosophila melanogaster]" "NP_001014454.1 phosphatase 1 nuclear targeting subunit, isoform A [Drosophila melanogaster]" ...
  .. .. ..@ elementType    : chr "ANY"
  .. .. ..@ elementMetadata: NULL
  .. .. ..@ metadata       : list()
  ..@ elementType    : chr "AAString"
  ..@ elementMetadata: NULL
  ..@ metadata       : list()


问:
Using multiple network interfaces on k3s
I'm sort of a newbie in k3s I know that in kubernetes, the multus plugin allows to to have multiple network interfaces attached to a pod, is there a way to have the same result with k3s?

There is this guide to install the plugin on k3s but I did  not manage to make it work, has anyone succeded?
https://gist.github.com/janeczku/ab5139791f28bfba1e0e03cfc2963ecf


问:
Cypress on WSL with X-Server opens empty windows
I've followed this article for running Cypress on WSL (Ubuntu distribution).

When I run cypress open in WSL it does open Cypress app on Windows but Cypress doesn't display anything and WSL throws errors:

```<code>[4186:1214/162139.560525:ERROR:bus.cc(397)] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
[4186:1214/162139.560902:ERROR:bus.cc(397)] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
[4186:1214/162139.564644:ERROR:udev_watcher.cc(63)] Failed to enable receiving udev events.
[4186:1214/162139.579120:WARNING:bluez_dbus_manager.cc(248)] Floss manager not present, cannot set Floss enable/disable.
[4339:1214/162139.734198:ERROR:sandbox_linux.cc(377)] InitializeSandbox() called with multiple threads in process gpu-process.
[4339:1214/162139.739939:ERROR:gpu_memory_buffer_support_x11.cc(44)] dri3 extension not supported.
</code>```

When I run cypress run (headless) tests end with timeout:

```<code>Running:  layout/footer.spec.ts                                                          (1 of 19)
Timed out waiting for the browser to connect. Retrying...
</code>```

When I run cypress run --headed it opens VcXsrv window but it's all empty:

After a while it opens another VcXsrv window, also empty. While tests are failing with timeouts (The browser never connected. Something is wrong.) it continues to open more and more empty VcXsrv windows.

My Node version is 16.1.8. Cypress version 9.7.0. Ubuntu version 22.04.1 LTS.

Body:
I've followed this article for running Cypress on WSL (Ubuntu distribution).

When I run cypress open in WSL it does open Cypress app on Windows but Cypress doesn't display anything and WSL throws errors:

[4186:1214/162139.560525:ERROR:bus.cc(397)] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
[4186:1214/162139.560902:ERROR:bus.cc(397)] Failed to connect to the bus: Could not parse server address: Unknown address type (examples of valid types are "tcp" and on UNIX "unix")
[4186:1214/162139.564644:ERROR:udev_watcher.cc(63)] Failed to enable receiving udev events.
[4186:1214/162139.579120:WARNING:bluez_dbus_manager.cc(248)] Floss manager not present, cannot set Floss enable/disable.
[4339:1214/162139.734198:ERROR:sandbox_linux.cc(377)] InitializeSandbox() called with multiple threads in process gpu-process.
[4339:1214/162139.739939:ERROR:gpu_memory_buffer_support_x11.cc(44)] dri3 extension not supported.

When I run cypress run (headless) tests end with timeout:

Running:  layout/footer.spec.ts                                                          (1 of 19)
Timed out waiting for the browser to connect. Retrying...

When I run cypress run --headed it opens VcXsrv window but it's all empty:

After a while it opens another VcXsrv window, also empty. While tests are failing with timeouts (The browser never connected. Something is wrong.) it continues to open more and more empty VcXsrv windows.

My Node version is 16.1.8. Cypress version 9.7.0. Ubuntu version 22.04.1 LTS.


问:
Combine two or multiple classes with MultiLabelBinarizer
Is it possible to combine two classes to get a single entry for the labels with MultiLabelBinarizer?
Normally one gets

```<code>labels = ['a', 'b', 'c', 'd', 'e']

x = ['a', 'c', 'd']
y = ['a', 'b', 'e']
z = ['c', 'd', 'e']

mlb = MultiLabelBinarizer(classes=labels)
a = mlb.fit_transform([x, y, z])

print(a)
</code>```
```<code>[[1 0 1 1 0]
 [1 1 0 0 1]
 [0 0 1 1 1]]
</code>```

But what I want is to combine two classes e.g if 'a' or 'b' is present, the label for x should look like

```<code>[[1 1 1]]
</code>```

So for 'a'+'b', 'c', 'd'+'e' the above should look like

```<code>[[1 1 1]
 [1 0 1]
 [0 1 1]]
</code>```

I just want to know if it is possible. Implementing some functions to get the same result is also possible, but I have a lot of classes and I want to speed things up.

Body:
Is it possible to combine two classes to get a single entry for the labels with MultiLabelBinarizer?
Normally one gets

labels = ['a', 'b', 'c', 'd', 'e']

x = ['a', 'c', 'd']
y = ['a', 'b', 'e']
z = ['c', 'd', 'e']

mlb = MultiLabelBinarizer(classes=labels)
a = mlb.fit_transform([x, y, z])

print(a)

[[1 0 1 1 0]
 [1 1 0 0 1]
 [0 0 1 1 1]]

But what I want is to combine two classes e.g if 'a' or 'b' is present, the label for x should look like

[[1 1 1]]

So for 'a'+'b', 'c', 'd'+'e' the above should look like

[[1 1 1]
 [1 0 1]
 [0 1 1]]

I just want to know if it is possible. Implementing some functions to get the same result is also possible, but I have a lot of classes and I want to speed things up.


问:
Creating and Writing to a text file on Android .NET MAUI
I'm trying write to a text file with my function which works fine on Windows Machine but doesn't create the txt file on Android.</p>
```<code>public async void WriteTextToFile(string text, string targetFileName)
{
    string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, targetFileName + ".txt");
    using FileStream outputStream = System.IO.File.OpenWrite(targetFile);
    using StreamWriter streamWriter = new StreamWriter(outputStream);
    await streamWriter.WriteAsync(text);
}
</code>```

Body:
I'm trying write to a text file with my function which works fine on Windows Machine but doesn't create the txt file on Android.

public async void WriteTextToFile(string text, string targetFileName)
{
    string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, targetFileName + ".txt");
    using FileStream outputStream = System.IO.File.OpenWrite(targetFile);
    using StreamWriter streamWriter = new StreamWriter(outputStream);
    await streamWriter.WriteAsync(text);
}


问:
How to set default value and label together for SelectOneMenu?
I have a simple selectOneMenu

    <f:selectItem itemLabel="choose signer" itemValue="#{null}"/>
    <f:selectItems value="#{Bean.signers}" var="signer"
                 itemLabel="#{signer.fullname}" itemValue="#{signer}"/>

```

In my case the first selectItem displays message but it doesn't have any value #{null}.
But I need a label as first item, and set the default value (the first item from list signers)
How I can do this two actions together?

Body:
I have a simple selectOneMenu

    <f:selectItem itemLabel="choose signer" itemValue="#{null}"/>
    <f:selectItems value="#{Bean.signers}" var="signer"
                 itemLabel="#{signer.fullname}" itemValue="#{signer}"/>

In my case the first selectItem displays message but it doesn't have any value #{null}.
But I need a label as first item, and set the default value (the first item from list signers)
How I can do this two actions together?