问:
Lazy loading works without transaction in Spring
I have:

Spring JPA app with Hibernate. App is configured without transaction manager.

2 entities: Item and Bid. Item can has some Bids.

I try to get Item by id (em.find) and I expect that Item will be print with empty List. But when I call System.out.println Hiber execute anoter query and loads List. Looks like it happened in transactio, but I don’t use any transaction explisitly.
So why lazy loading happened? And how disable it?

Config:

```<code>@Configuration
@ComponentScan(basePackages = {"com.john.jpaProf1.relation.oneToManyBags"})
@PropertySource("classpath:property.properties")
public class Config {

    @Bean
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:postgresql://localhost:5432/jpa1");
        dataSource.setUsername("postgres");
        dataSource.setPassword("postgres");
        return dataSource;
    }

    @Bean
    public EntityManager entityManager(LocalContainerEntityManagerFactoryBean factoryBean) {
        return factoryBean.getObject().createEntityManager();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setPackagesToScan("com.john.jpaProf1.relation.oneToManyBags");
        AbstractJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setShowSql(true);
        jpaVendorAdapter.setGenerateDdl(true);
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.getJpaPropertyMap().put("hibernate.format_sql", true);
        factoryBean.getJpaPropertyMap().put("hibernate.dialect", "org.hibernate.dialect.PostgreSQL82Dialect");
        return factoryBean;
    }
}
</code>```

property.properties:

```<code>spring.jpa.open-in-view=false
</code>```

Entity Bid:

```<code>@Entity
@Table(name = "t23bid")
public class Bid {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    protected Integer id;
    protected String name;
    @ManyToOne
    @JoinColumn(name = "item_id")
    protected Item item;
...

</code>```

Entity Item:

```<code>@Entity
@Table(name = "t23item")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    protected Integer id;
    protected String name;
    @OneToMany(mappedBy = "item", fetch = FetchType.LAZY)
    protected Collection<Bid> bids;
...
</code>```

Starter:

```<code>public class Starter {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        EntityManager em = context.getBean(EntityManager.class);
        Item item = em.find(Item.class, 1);
        System.out.println("\n-------after em.find() ? but before System.out.println() -------\n");
        System.out.println("\n" + item);
...
</code>```

Config

```<code>implementation 'com.zaxxer:HikariCP:4.0.3'
implementation 'org.springframework:spring-context:5.3.24'
implementation 'org.springframework:spring-orm:5.3.24'
implementation 'org.hibernate:hibernate-entitymanager:5.6.14.Final'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.0'
implementation 'org.postgresql:postgresql:42.4.1'
</code>```

Result:

Hibernate:
select
item0_.id as id1_2_0_,
item0_.name as name2_2_0_
from
t23item item0_
where
item0_.id=?

-------after em.find() ? but before System.out.println() -------

Hibernate:
select
bids0_.item_id as item_id3_0_0_,
bids0_.id as id1_0_0_,
bids0_.id as id1_0_1_,
bids0_.item_id as item_id3_0_1_,
bids0_.name as name2_0_1_
from
t23bid bids0_
where
bids0_.item_id=?

Item{id=1, name='name1', bids=[Item{id=1, name='bid1'}, Item{id=2, name='bid2'}]}

Body:
I have:

Spring JPA app with Hibernate. App is configured without transaction manager.

2 entities: Item and Bid. Item can has some Bids.

I try to get Item by id (em.find) and I expect that Item will be print with empty List. But when I call System.out.println Hiber execute anoter query and loads List. Looks like it happened in transactio, but I don’t use any transaction explisitly.
So why lazy loading happened? And how disable it?

Config:

@Configuration
@ComponentScan(basePackages = {"com.john.jpaProf1.relation.oneToManyBags"})
@PropertySource("classpath:property.properties")
public class Config {

    @Bean
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:postgresql://localhost:5432/jpa1");
        dataSource.setUsername("postgres");
        dataSource.setPassword("postgres");
        return dataSource;
    }

    @Bean
    public EntityManager entityManager(LocalContainerEntityManagerFactoryBean factoryBean) {
        return factoryBean.getObject().createEntityManager();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setPackagesToScan("com.john.jpaProf1.relation.oneToManyBags");
        AbstractJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setShowSql(true);
        jpaVendorAdapter.setGenerateDdl(true);
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.getJpaPropertyMap().put("hibernate.format_sql", true);
        factoryBean.getJpaPropertyMap().put("hibernate.dialect", "org.hibernate.dialect.PostgreSQL82Dialect");
        return factoryBean;
    }
}

property.properties:

spring.jpa.open-in-view=false

Entity Bid:

@Entity
@Table(name = "t23bid")
public class Bid {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    protected Integer id;
    protected String name;
    @ManyToOne
    @JoinColumn(name = "item_id")
    protected Item item;
...

Entity Item:

@Entity
@Table(name = "t23item")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    protected Integer id;
    protected String name;
    @OneToMany(mappedBy = "item", fetch = FetchType.LAZY)
    protected Collection<Bid> bids;
...

Starter:

public class Starter {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        EntityManager em = context.getBean(EntityManager.class);
        Item item = em.find(Item.class, 1);
        System.out.println("\n-------after em.find() ? but before System.out.println() -------\n");
        System.out.println("\n" + item);
...

Config

implementation 'com.zaxxer:HikariCP:4.0.3'
implementation 'org.springframework:spring-context:5.3.24'
implementation 'org.springframework:spring-orm:5.3.24'
implementation 'org.hibernate:hibernate-entitymanager:5.6.14.Final'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.0'
implementation 'org.postgresql:postgresql:42.4.1'

Result:

Hibernate:
select
item0_.id as id1_2_0_,
item0_.name as name2_2_0_
from
t23item item0_
where
item0_.id=?

-------after em.find() ? but before System.out.println() -------

Hibernate:
select
bids0_.item_id as item_id3_0_0_,
bids0_.id as id1_0_0_,
bids0_.id as id1_0_1_,
bids0_.item_id as item_id3_0_1_,
bids0_.name as name2_0_1_
from
t23bid bids0_
where
bids0_.item_id=?

Item{id=1, name='name1', bids=[Item{id=1, name='bid1'}, Item{id=2, name='bid2'}]}


来源: stackexchange

问:
For no gap audio concat in FFMPEG, which format to use?
It's my understanding that FFMPEG will add gaps in between concatenated audio because of so called priming samples that are needed to fill in empty buffers (I think).
Is there an audio format that will do away with this gap?
I'm recording WAV files and the concat command below will add a small gap between the output files. My assumption was that WAV, because it contains PCM data, would not cause the gap.</p>
```<code> "-i ${audioFile1} -i ${audioFile2} -filter_complex 'concat=n=2:v=0:a=1[a]' -map '[a]'  $outPath";
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It's my understanding that FFMPEG will add gaps in between concatenated audio because of so called priming samples that are needed to fill in empty buffers (I think).
Is there an audio format that will do away with this gap?
I'm recording WAV files and the concat command below will add a small gap between the output files. My assumption was that WAV, because it contains PCM data, would not cause the gap.

 "-i ${audioFile1} -i ${audioFile2} -filter_complex 'concat=n=2:v=0:a=1[a]' -map '[a]'  $outPath";


问:
How to enable on scroll listener at certain scroll point
I'm struggling with a quite simple JavaScript function showing the scrolled status of a particular page. Scroll status works, however as soon as I land on the page, it is loaded at 100% and after scrolling, it starts working as it should - increasing from 0% to 100%.

window.onscroll = function () {
  scrollStatus();
};

function scrollStatus() {
  const winScroll =
    document.body.scrollTop || document.documentElement.scrollTop;
  const height =
    document.documentElement.scrollHeight -
    document.documentElement.clientHeight;
  const scrolled = (winScroll / height) * 100;
  document.getElementById("myBar").style.width = scrolled + "%";
}
```
<p>Solution might be that the entire scroll bar will appear after the user scrolls a few points down.</p>
<p>I've tried to add something like this:</p>
<pre class="lang-js prettyprint-override"><code>if (scrolled = 0) {
  document.querySelector(".progress-bar").style.width = 0;
}
</code>```

There is CSS as well, just in case.

.progress-container {
  position: fixed;
  top: var(--nav-bar-top-position);
  width: 100%;
  z-index: 9;
}
.progress-bar {
  background: rgb(var(--secondary-color));
  border-bottom-right-radius: var(--border-radius-1);
  height: 4px;
}
```

I'm quite a beginner with a JS, so please keep that in mind while constructing your answers.

Body:
I'm struggling with a quite simple JavaScript function showing the scrolled status of a particular page. Scroll status works, however as soon as I land on the page, it is loaded at 100% and after scrolling, it starts working as it should - increasing from 0% to 100%.

window.onscroll = function () {
  scrollStatus();
};

function scrollStatus() {
  const winScroll =
    document.body.scrollTop || document.documentElement.scrollTop;
  const height =
    document.documentElement.scrollHeight -
    document.documentElement.clientHeight;
  const scrolled = (winScroll / height) * 100;
  document.getElementById("myBar").style.width = scrolled + "%";
}

Solution might be that the entire scroll bar will appear after the user scrolls a few points down.

I've tried to add something like this:

if (scrolled = 0) {
  document.querySelector(".progress-bar").style.width = 0;
}

There is CSS as well, just in case.

.progress-container {
  position: fixed;
  top: var(--nav-bar-top-position);
  width: 100%;
  z-index: 9;
}
.progress-bar {
  background: rgb(var(--secondary-color));
  border-bottom-right-radius: var(--border-radius-1);
  height: 4px;
}

I'm quite a beginner with a JS, so please keep that in mind while constructing your answers.


问:
Transpose the dataframe and do groupby operations
I have a dataframe which looks like this:

My issue is that I need to have the columns (from T12006 to T42007) as rows so I can do groupby operations. My aim is to have an output similar to this:

I have been struggling with this for a while. I tried some approach like df.pivot_table and df.T but i have been unsuccessul so far.


Title: Convert list of day names into lists of sublists for each week taking into account the fact that each week is reset in monday python

Body:
I have the following list "diasformated":

  ['Wednesday, 2023-02-01', 'Thursday, 2023-02-02', 'Friday, 2023-02-03', 'Saturday, 2023-02-04', 'Monday, 2023-02-06', 'Tuesday, 2023-02-07', 'Wednesday, 2023-02-08', 'Thursday, 2023-02-09', 'Friday, 2023-02-10', 'Saturday, 2023-02-11', 'Monday, 2023-02-13', 'Tuesday, 2023-02-14', 'Wednesday, 2023-02-15', 'Thursday, 2023-02-16', 'Friday, 2023-02-17', 'Saturday, 2023-02-18', 'Monday, 2023-02-20', 'Tuesday, 2023-02-21', 'Wednesday, 2023-02-22', 'Thursday, 2023-02-23', 'Friday, 2023-02-24', 'Saturday, 2023-02-25', 'Monday, 2023-02-27', 'Tuesday, 2023-02-28']

I want to convert that  into this type of list of lists, in such a way each sublist represent a week of that month:

[['Wednesday_2023_02_01',
  'Thursday_2023_02_02',
  'Friday_2023_02_03',
  'Saturday_2023_02_04',
  ['Monday_2023_02_06',
  'Tuesday_2023_02_07',
 'Wednesday_2023_02_08',
  'Thursday_2023_02_09',
  'Friday_2023_02_10',
  'Saturday_2023_02_11']
  ['Monday_2023_02_13',
  'Tuesday_2023_02_14'...,

but I get this result (it's returned a out of range error but you can type the name of the list and will return you this):

  [['Wednesday_2023_02_01',
  'Thursday_2023_02_02',
  'Friday_2023_02_03',
  'Saturday_2023_02_04',
  'Monday_2023_02_06',
  'Tuesday_2023_02_07',
  'Wednesday_2023_02_08',
  'Thursday_2023_02_09',
  'Friday_2023_02_10',
  'Saturday_2023_02_11',
  'Monday_2023_02_13',
  'Tuesday_2023_02_14',
  'Wednesday_2023_02_15',
  'Thursday_2023_02_16',
  'Friday_2023_02_17',
  'Saturday_2023_02_18',
  'Monday_2023_02_20',
  'Tuesday_2023_02_21',
  'Wednesday_2023_02_22',
  'Thursday_2023_02_23',
  'Friday_2023_02_24',
  'Saturday_2023_02_25',
  'Monday_2023_02_27',
  'Tuesday_2023_02_28'],
 [],
 [],
 [],
 []]

Product of this code which is missing something that I don't know:

ndays=end_dt-start_dt
weeks = calendar.monthcalendar(year, month_num)
nweeks = len(weeks)
turnlist=[[] for e in range(0,nweeks)]

#bring the days in n weeks (before was 4)
conteo1=0
for i in range(len(turnlist)):
    for j in range(len(diasformated)):
        while len(turnlist[i])<6 or 'Monday' not in diasformated[j]:
            turnlist[i].append(diasformated[j+conteo1])
            conteo1+=1

How can I get the desired result? I appreciate the help!


问:
Switch Github profile pictures according to the theme
I would like to automate the change of the profile picture according to the current theme on the github page, day or night. Is there a way to make this change?

I tried an html script but no way to get a result on github.

```<code><!DOCTYPE html>
<html>
<head>
    <title>switch_them</title>
</head>
<body>
<img id="day" src="img/0XCAF3_day.png" alt="day theme">
<img id="night" src="img/0XCAF3_night.png" alt="night theme">

<script>
    function switchTheme() {
        const dayThemePicture = '0XCAF3_day.png';
        const nightThemePicture = '0XCAF3_night.png';

        const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
        if (mediaQuery.matches) {
            document.getElementById('night').src = nightThemePicture;
        } else {
            document.getElementById('day').src = dayThemePicture;
        }
    }

    switchTheme();

    window.addEventListener('load', switchTheme);
    window.addEventListener('resize', switchTheme);
</script>
</body>
</html>
</code>```

Body:
I would like to automate the change of the profile picture according to the current theme on the github page, day or night. Is there a way to make this change?

I tried an html script but no way to get a result on github.

<!DOCTYPE html>

    <title>switch_them</title>


问:
Add Data to Radar Chart Through User Input with React
I want the user to add data to a Radar Chart in React through User Input. I tried different methods but it just does not work or the chart does not get displayed. Here is the code

```<code>import './App.css';
import React from 'react'
import {
    Chart as ChartJS,
    RadialLinearScale,
    PointElement,
    LineElement,
    Filler,
    Tooltip,
    Legend
} from "chart.js";
import { Radar } from "react-chartjs-2";

function App() {
  ChartJS.register(
    RadialLinearScale,
    PointElement,
    LineElement,
    Filler,
    Tooltip,
    Legend
  );

const data = {
    labels: ["Business 1", "Business 2", "Business 3"],
    datasets: [
      {
        label: "Number of Businesses",
        data: [1300, 400, 160],
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgba(255, 99, 132, 1)",
        borderWidth: 1
      }
    ]
  };

  return (
    <div className='App'>
      <Radar data={data} />

      <form>
        <input type='text' placeholder='Label' />
        <input type='text' placeholder='Dataset' />
        <button>Add Data</button>
      </form>
    </div>
  );
}

export default App;
</code>```

I would really appreciate any help or solution.

Body:
I want the user to add data to a Radar Chart in React through User Input. I tried different methods but it just does not work or the chart does not get displayed. Here is the code

import './App.css';
import React from 'react'
import {
    Chart as ChartJS,
    RadialLinearScale,
    PointElement,
    LineElement,
    Filler,
    Tooltip,
    Legend
} from "chart.js";
import { Radar } from "react-chartjs-2";

function App() {
  ChartJS.register(
    RadialLinearScale,
    PointElement,
    LineElement,
    Filler,
    Tooltip,
    Legend
  );

const data = {
    labels: ["Business 1", "Business 2", "Business 3"],
    datasets: [
      {
        label: "Number of Businesses",
        data: [1300, 400, 160],
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgba(255, 99, 132, 1)",
        borderWidth: 1
      }
    ]
  };

  return (

      <Radar data={data} />

      <form>
        <input type='text' placeholder='Label' />
        <input type='text' placeholder='Dataset' />
        <button>Add Data</button>
      </form>

  );
}

export default App;

I would really appreciate any help or solution.


问:
AWS Inspector + AWS SSM (NotApplicable patch)
I'm pretty new to AWS Inspector + SSM for patching but I've got a Windows Server 2019 that is affected by CVE-2022-30136 detected by AWS Inspector. Looks like it was fixed with kb5014692 however when i look it up on AWS SSM it says NotApplicable.

Does it mean that my server is not vulnerable? If so, why would AWS Inspector detect that vulnerability? Or am I missing something here.

Thanks


问:
Passing variables into command line arguments
I am trying to pass a variable as a part of a bash command in my Rust program.

```<code>let speed_output = 70;
Command::new("nvidia-settings")
        .arg("-a")
        .arg("GPUTargetFanSpeed[fan:0]=speed_output")
        .spawn()
        .expect("nvidia-settings command failed to execute");
</code>```

The program compiles correctly but my variable speed_output isn't passed to the bash shell. I would like to know how to pass variables from the Rust environment directly into the argument.

Body:
I am trying to pass a variable as a part of a bash command in my Rust program.

let speed_output = 70;
Command::new("nvidia-settings")
        .arg("-a")
        .arg("GPUTargetFanSpeed[fan:0]=speed_output")
        .spawn()
        .expect("nvidia-settings command failed to execute");

The program compiles correctly but my variable speed_output isn't passed to the bash shell. I would like to know how to pass variables from the Rust environment directly into the argument.


问:
autoComplete for username dont work in FireFox but password do
I have a input field for usename and password on seperate pages as a part of "email first" sign-in flow.
This works fine in Chrome and Edge but for some reason usename dont autofill in FireFox.

The weirdest part is that password autocomplete works in all three browsers and fills in nicely automatically.

Anyone experienced the same behavior?

This is how the inputs looks and I'm using react.

```<code>   <input
        id="user"
        autoComplete="username"
        name="UserName"
        value={value}
    />

   <input
        id="current-password"
        autoComplete="current-password"
        name="Password"
        value={value}
    />
</code>```

Body:
I have a input field for usename and password on seperate pages as a part of "email first" sign-in flow.
This works fine in Chrome and Edge but for some reason usename dont autofill in FireFox.

The weirdest part is that password autocomplete works in all three browsers and fills in nicely automatically.

Anyone experienced the same behavior?

This is how the inputs looks and I'm using react.

   <input
        id="user"
        autoComplete="username"
        name="UserName"
        value={value}
    />

   <input
        id="current-password"
        autoComplete="current-password"
        name="Password"
        value={value}
    />


问:
Using Excel to return a yes/no response from a data table, using multiple conditions in separate columns
I'm trying to refine a report dashboard utilized at my workplace. The process that I'm trying to automate is;

Data is generated into a worksheet via a query table (Worksheet called Imported Data)

From that table, i'm wanting to look at 3 separate columns for 3 conditions

Those conditions are a) Team, B) Frequency, C) Month and D) Yes (from a ye/no option)

Providing all those conditions are met Eg, Team A, Monthly, February, Yes, I want Excel to produce a response of Compliant, otherwise say Non-compliant, onto another worksheet called Governance Complaince

The response for this is on a separate work sheet.

The main query table that is generated has around 8 Team choices, 6 Frequency options, with 12 month and then the 2 (obviously) yes/no options.

I've tried a few different formulas to get this to work, but I only ever get the True value from the formula.

I Feel that maybe the formula is stopping once it sees the first Team A selection (Which by nature of how the query table is generated, is the first result in the Team column) and then ignoring the remainder of the formula, despite my best attempts.

The current formula I'm using is

```<code>=IF(COUNTIFS('Imported Data'!A:A,"Team A")+COUNTIFS('Imported Data'!C:C,"Monthly")+COUNTIFS('Imported Data'!F:F,"February")+COUNTIFS('Imported Data'!I:I,"Yes")>1,"Compliant","Non-compliant")
</code>```

I've tried

```<code>=IF(COUNTIFS('Imported Data'!A:A,"Team A")+COUNTIFS('Imported Data'!C:C,"Monthly")+COUNTIFS('Imported Data'!F:F,"February")+COUNTIFS('Imported Data'!I:I,"Yes")=ROWS('Imported Data'!A1:Z500),"Compliant","Non-compliant")
</code>```
```<code>=IF(AND('Imported Data'!A:A,"Team A")+AND('Imported Data'!C:C,"Monthly")+AND('Imported Data'!F:F,"February")+AND('Imported Data'!I:I,"Yes"),"Compliant","Non-compliant")
</code>```
```<code>=IF(AND('Imported Data'!A:A,"Team A")+AND('Imported Data'!C:C,"Monthly")+AND('Imported Data'!F:F,"February")+AND('Imported Data'!I:I,"Yes")=ROWS('Imported Data'!A1:Z500),"Compliant","Non-compliant")
</code>```

All I get is a #Value error, or only the Compliant value, despite any changes made to the data the formula references.

All the cells are text, there is no numerical data in the tables. The formula is placed into a cell in another worksheet called Governance Compliance

Essentially I want the formula to be able to look at the query table data, output the Ture/False value into a monthly tracker (This formula will be replicated over about 26 different audits for 8 teams) automatically, cutting down on manual processing. I've been able to get the date to then look at a quarterly array of teams and return a complaint/non-complaint result into another worksheet fine using

```<code>=IF(COUNTIF('Governance Compliance'!E11:G19,"Compliant")=ROWS('Governance Compliance'!E11:G19),"Yes","No")
</code>```

And I thought that my 3 condition if statement to get the compliant result into the Governance Compliance worksheet would just be an expansion of conditions on this formula, but I am clearly wrong.

The query table is sorted alphabetically by Team if that makes a difference.

Body:
I'm trying to refine a report dashboard utilized at my workplace. The process that I'm trying to automate is;

Data is generated into a worksheet via a query table (Worksheet called Imported Data)

From that table, i'm wanting to look at 3 separate columns for 3 conditions

Those conditions are a) Team, B) Frequency, C) Month and D) Yes (from a ye/no option)

Providing all those conditions are met Eg, Team A, Monthly, February, Yes, I want Excel to produce a response of Compliant, otherwise say Non-compliant, onto another worksheet called Governance Complaince

The response for this is on a separate work sheet.

The main query table that is generated has around 8 Team choices, 6 Frequency options, with 12 month and then the 2 (obviously) yes/no options.

I've tried a few different formulas to get this to work, but I only ever get the True value from the formula.

I Feel that maybe the formula is stopping once it sees the first Team A selection (Which by nature of how the query table is generated, is the first result in the Team column) and then ignoring the remainder of the formula, despite my best attempts.

The current formula I'm using is

=IF(COUNTIFS('Imported Data'!A:A,"Team A")+COUNTIFS('Imported Data'!C:C,"Monthly")+COUNTIFS('Imported Data'!F:F,"February")+COUNTIFS('Imported Data'!I:I,"Yes")>1,"Compliant","Non-compliant")

I've tried

=IF(COUNTIFS('Imported Data'!A:A,"Team A")+COUNTIFS('Imported Data'!C:C,"Monthly")+COUNTIFS('Imported Data'!F:F,"February")+COUNTIFS('Imported Data'!I:I,"Yes")=ROWS('Imported Data'!A1:Z500),"Compliant","Non-compliant")

=IF(AND('Imported Data'!A:A,"Team A")+AND('Imported Data'!C:C,"Monthly")+AND('Imported Data'!F:F,"February")+AND('Imported Data'!I:I,"Yes"),"Compliant","Non-compliant")

=IF(AND('Imported Data'!A:A,"Team A")+AND('Imported Data'!C:C,"Monthly")+AND('Imported Data'!F:F,"February")+AND('Imported Data'!I:I,"Yes")=ROWS('Imported Data'!A1:Z500),"Compliant","Non-compliant")

All I get is a #Value error, or only the Compliant value, despite any changes made to the data the formula references.

All the cells are text, there is no numerical data in the tables. The formula is placed into a cell in another worksheet called Governance Compliance

Essentially I want the formula to be able to look at the query table data, output the Ture/False value into a monthly tracker (This formula will be replicated over about 26 different audits for 8 teams) automatically, cutting down on manual processing. I've been able to get the date to then look at a quarterly array of teams and return a complaint/non-complaint result into another worksheet fine using

=IF(COUNTIF('Governance Compliance'!E11:G19,"Compliant")=ROWS('Governance Compliance'!E11:G19),"Yes","No")

And I thought that my 3 condition if statement to get the compliant result into the Governance Compliance worksheet would just be an expansion of conditions on this formula, but I am clearly wrong.

The query table is sorted alphabetically by Team if that makes a difference.


问:
Mapbox map loading crash
This is the error message shown from React Native app with mapbox GL JS that my dev team works on:

ERROR  Mapbox error MapLoad error Failed to load tile: Unknown exception type {"level": "error", "message": "MapLoad error Failed to load tile: Unknown exception type"}

Also, I am also encountering same crash with mapbox studio preview IOS version.

Interestingly, I duplicated the style and removed layers for my own debugging. However, after removing all layers, still there is crash with even no layer at all.

Successful Map loading

Title: Mapbox map loading crash


问:
Why won't my program import pynput in terminal but does so in PyCharm?
I installed pynput with pip and imported it into my code. However, when I run my code in the terminal, it won't run and gives me this error:

```<code>  File "C:\Users\toofast4u\projects\test.py", line 2, in <module>
    from pynput.keyboard import Key, Controller
ModuleNotFoundError: No module named 'pynput'
</code>```

I have looked through all available modules I can use in python, and I can't seem to find pynput.

I tried reinstalling it to see if that would work, but the same problem persists. Can anyone find the issue?

Body:
I installed pynput with pip and imported it into my code. However, when I run my code in the terminal, it won't run and gives me this error:

  File "C:\Users\toofast4u\projects\test.py", line 2, in <module>
    from pynput.keyboard import Key, Controller
ModuleNotFoundError: No module named 'pynput'

I have looked through all available modules I can use in python, and I can't seem to find pynput.

I tried reinstalling it to see if that would work, but the same problem persists. Can anyone find the issue?


问:
Cannot Build Rust GGEZ
I'm starting a new Rust project and included the ggez package in Cargo.toml

```<code>[package]
name = "Project"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
ggez = "0.8.1"
</code>```

However, when I run cargo build, I get the following error

```<code>error: failed to download `raw-window-handle v0.4.3`

Caused by:
  unable to get packages from source

Caused by:
  failed to parse manifest at `C:\Users\scout\.cargo\registry\src\github.com-1ecc6299db9ec823\raw-window-handle-0.4.3\Cargo.toml`

Caused by:
  could not parse input as TOML

Caused by:
  TOML parse error at line 1, column 1
    |
  1 |
    | ^
  Unexpected ``
  Expected key or end of input
</code>```

How can I remedy this issue?

I've tried including the raw-window-handle package manually, but I still get the same issue.

Title: Cannot Build Rust GGEZ

Body:
I'm starting a new Rust project and included the ggez package in Cargo.toml

[package]
name = "Project"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
ggez = "0.8.1"

However, when I run cargo build, I get the following error

error: failed to download `raw-window-handle v0.4.3`

Caused by:
  unable to get packages from source

Caused by:
  failed to parse manifest at `C:\Users\scout\.cargo\registry\src\github.com-1ecc6299db9ec823\raw-window-handle-0.4.3\Cargo.toml`

Caused by:
  could not parse input as TOML

Caused by:
  TOML parse error at line 1, column 1
    |
  1 |
    | ^
  Unexpected ``
  Expected key or end of input

How can I remedy this issue?

I've tried including the raw-window-handle package manually, but I still get the same issue.


问:
Append to a list in python for loop
I am tring to populate both matrix_of_ones and inner_matrix inside a for loop but the final matrix is not what i expect. I expect matrix_of_ones  to be equal expected_for_loop_output after the for loop is finished executing but the for loop actually generates actual_for_loop_output below. Could someone please why this is so?

enter image description here

I expect matrix_of_ones  to be equal expected_for_loop_output after the for loop is finished executing but the for loop actually generates actual_for_loop_output.

Title: Append to a list in python for loop


问:
How can I control the finder from vscode
Background:

Programming in Python (vscode)

on Mac

Story:
I am using selenium to automate a process and at some point throughout that process I have to upload a picture. I can click on the "from Computer" button that pops up but this opens the finder with all my files/documents. I do not know how I could tell python here to navigate to a given folder and klick "submit" (or upload).
Question:
Does anyone know a way to "control" the finder similarly to what selenium does for the web browser?

Thank you!

I have tried:

Selenium but it can not handle this (to my knowledge) since I am no longer in the browser.

I have also tried the package pyautogui but because I would like to be able to run the same program from several computers (the path will be the same) but they display the finder differently so I dont think that will do the trick.


问:
Popup does not appear when i use folium.CircleMarker
Code with folium.CircleMarker, i click the little circle in the map and the popup just doesnt appear, but when i use folium.Marker it appears just as usual, how can i solve this ?</p>
```<code>
import folium
import pandas as pd

def checkColor(elevation):
    if elevation < 1500:
        return 'green'
    elif elevation > 1500 and elevation < 3000:
        return 'orange'
    else:
           return 'red'

data = pd.read_csv('/home/r1x/Documents/map_project/Volcanoes.txt')
lat = list(data['LAT'])
lon = list(data['LON'])
elev = list(data['ELEV'])
names = list(data['NAME'])
map = folium.Map(location=[38.58,-99.09], zoom_start=6, tiles='Stamen Terrain')
html = """<h4>Volcano Information:</h4>
Volcano name:<br>
<a href="https://www.google.com/search?q=%%22%s%%22" target="_blank">%s</a><br>
Height: %s m
"""
fg = folium.FeatureGroup(name='My map')
for lt, lo, el, name in zip(lat,lon,elev,names):
    iframe = folium.IFrame(html=html % (name, name, el), width=200, height=100)
    fg.add_child(folium.CircleMarker(location=[lt, lo], popup=folium.Popup(iframe), fill_color = checkColor(el), color ='grey', radius = 6, fill_opacity = 0.7))
fg.add_child(folium.GeoJson(data=open('/home/r1x/Documents/map_project/world.json', 'r', encoding='utf-8-sig').read()))
map.add_child(fg)
map.save('Map1.html')
</code>```

Body:
Code with folium.CircleMarker, i click the little circle in the map and the popup just doesnt appear, but when i use folium.Marker it appears just as usual, how can i solve this ?

import folium
import pandas as pd

def checkColor(elevation):
    if elevation < 1500:
        return 'green'
    elif elevation > 1500 and elevation < 3000:
        return 'orange'
    else:
           return 'red'

data = pd.read_csv('/home/r1x/Documents/map_project/Volcanoes.txt')
lat = list(data['LAT'])
lon = list(data['LON'])
elev = list(data['ELEV'])
names = list(data['NAME'])
map = folium.Map(location=[38.58,-99.09], zoom_start=6, tiles='Stamen Terrain')
html = """
Volcano Information:

Volcano name:

%s

Height: %s m
"""
fg = folium.FeatureGroup(name='My map')
for lt, lo, el, name in zip(lat,lon,elev,names):
    iframe = folium.IFrame(html=html % (name, name, el), width=200, height=100)
    fg.add_child(folium.CircleMarker(location=[lt, lo], popup=folium.Popup(iframe), fill_color = checkColor(el), color ='grey', radius = 6, fill_opacity = 0.7))
fg.add_child(folium.GeoJson(data=open('/home/r1x/Documents/map_project/world.json', 'r', encoding='utf-8-sig').read()))
map.add_child(fg)
map.save('Map1.html')


问:
How do I replace "." in my date to "-" in python when working with a data frame
I have the following data frame:

DATE

16.12.2022

15.12.2022

14.12.2022

13.12.2022

12.12.2022

I want to replace the "." in my DATE column with "-"

The current code I was using is as follows:

df2['DATE'] = df2['DATE'].replace('.','-')

But this would provide the following output:

```<code>0       ----------
1       ----------
2       ----------
3       ----------
4       ----------
</code>```

All of the text in date has been replaced with "-"

Any suggestions as how I can make this work?

Body:
I have the following data frame:

DATE

16.12.2022

15.12.2022

14.12.2022

13.12.2022

12.12.2022

I want to replace the "." in my DATE column with "-"

The current code I was using is as follows:

df2['DATE'] = df2['DATE'].replace('.','-')

But this would provide the following output:

0       ----------
1       ----------
2       ----------
3       ----------
4       ----------

All of the text in date has been replaced with "-"

Any suggestions as how I can make this work?


问:
"AuthenticatorInterface" not found on Security\Guard, Symfony 6.2
I'm trying to create a custom Token authenticator for my Symfony 6.2 and API Platform project

```<code>class TokenAuthenticator extends JWTTokenAuthenticator
{
    /**
     * @param PreAuthenticationJWTUserToken $preAuthToken
     * @param UserProviderInterface $userProvider
     * @return UserInterface
     */
    public function getUser($preAuthToken, UserProviderInterface $userProvider): UserInterface
    {
        $user = parent::getUser($preAuthToken, $userProvider);

        var_dump($preAuthToken->getPayload());exit;
    }
}
</code>```

But I always get this error:

```<code>Attempted to load interface "AuthenticatorInterface" from namespace "Symfony\Component\Security\Guard".
Did you forget a "use" statement for "Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface"?
</code>```

that means, there's no AuthenticatorInterface on Security\Guard and Http\Authenticator replaces it, so the LexikJWTAuthenticationBundle must be updated to include the new change.

This new class contains new functions so is there any documentation regarding them? Also, the purpose of establishing this class TokenAuthenticator is to make the old token invalid when changing the password, so is there a better way to do this?

Body:
I'm trying to create a custom Token authenticator for my Symfony 6.2 and API Platform project

class TokenAuthenticator extends JWTTokenAuthenticator
{
    /**
     * @param PreAuthenticationJWTUserToken $preAuthToken
     * @param UserProviderInterface $userProvider
     * @return UserInterface
     */
    public function getUser($preAuthToken, UserProviderInterface $userProvider): UserInterface
    {
        $user = parent::getUser($preAuthToken, $userProvider);

        var_dump($preAuthToken->getPayload());exit;
    }
}

But I always get this error:

Attempted to load interface "AuthenticatorInterface" from namespace "Symfony\Component\Security\Guard".
Did you forget a "use" statement for "Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface"?

that means, there's no AuthenticatorInterface on Security\Guard and Http\Authenticator replaces it, so the LexikJWTAuthenticationBundle must be updated to include the new change.

This new class contains new functions so is there any documentation regarding them? Also, the purpose of establishing this class TokenAuthenticator is to make the old token invalid when changing the password, so is there a better way to do this?


问:
How To Try All Possible Combinations Of Hex Values In C# Code?
I have the following parts of C# Code for example and other else if's, where input_byte == have different Hex Values after the == :-

```<code>            input_byte = input_data[current_input_position];
            current_input_position++;

            if(input_byte == 0xFF) {
                //==============
                // Fin de chunk
                //==============
                Save();
                current_output_index++;

                RLE_sumador         = 0;
                line_min_length     = int.MaxValue;
                line_max_length     = 0;
                width_current       = 0;
                image_height        = 0;

            } else if(input_byte == 0xFE) {
                //=================
                // Siguiente linea
                //=================
                if(width_current < line_min_length) line_min_length = width_current;
                if(width_current > line_max_length) line_max_length = width_current;

                if(forced_image_width!=null) {
                    count = forced_image_width.Value - width_current;
                    if(count > 0) {
                        for(n=0; n<count; n++) {
                            output_buffer.Add(0);
                        }
                    }
                }

                image_height++;
                width_current = 0;

</code>```

With the If and Else If parts of the code i.e. input_byte == 0xFF 0xFE 0xFD etc.. I want to alter the code, so I can brute force all possible combinations of individual hex values.

I think from 0x00 to 0xFF that is either 255 or 256 hex values. For example instead of 0xFF it could be 0x6E instead of 0xFE it be 0xFA etc. I have tried altering input_byte == to different things in the hope I get something useful as an output image. This code was used on another DOS game, to save graphics images as greyscale bitmap images.

I using this on the previous DOS game in the series.

I was thinking of using:

```<code>For(int input_byte=0x00;
input_byte <= 0xFF;
input_byte++)
</code>```

Somewhere in the code, but I don't think that would do all possible combinations of hex values.

I have Added the following to my Code :-

```<code>for (int i = 0x00; i <= 0xFF; input_byte++)
</code>```

After

```<code>input_byte = input_data[current_input_position];
        current_input_position++;
</code>```

And changed all input_byte ==
to input_byte == 0x00

And removed a line of Code, that saves Files other than .bmp's, so only .bmp's are saved, have I done the write thing here ? As I am not sure.

The unpac Program is still running after 30 minutes. So possibly I have made the correct amendments ?

I have changed to using this line of Code instead :-

```<code> for (int i = 0x00; i <= 0xFF; ++input_byte)
</code>```

From :-

```<code>for (int i = 0x00; i <= 0xFF; input_byte++)
</code>```

After reading up some Stackoverflow posts, of what the differences are, between ++i and i++, the amended line of Code sounds more appropriate for what I want, I hope this brute forcing, method takes hours rather than much longer. Can someone clarify for me, if all the changes I have made to my C# Code, definately should work ?

I didn't get anywhere, with the above for loop, and I tried doing it the other way round i.e :-

```<code>for (int i = 0xFF; i >= 0x00; --input_byte)
</code>```

or :-

```<code>for (int i = 0xFF; i >= 0x00; i = --input_byte)
</code>```

i.e. working backwards, so changing all the five   input_byte == 0x00 to   input_byte == 0xFF.

When I run in either direction, the number in the brackets in the output in Command Prompt stays at (639) when going  0x00 to 0xFF, and (636) when it is the other way round. And the File Number just keeps going up and up. Whereas for other Ranges, I have tried small or large, i.e. loop from 0x00 to 0x01 but even as far as 0x00 to 0xFE, the number in the brackets changes, for each File output, and the Program runs for a few seconds. for either large or small ranges in the for loop, when I use :-

```<code>i = --input_byte
</code>```

or :-

```<code>i = ++input_byte
</code>```

Whereas if I use 0xFF, it goes on and on. The other hex value ranges small or large, do the same when I just use ++input_byte or --input_byte. I was getting the same outcomes when it was input_byte++ or input_byte--. I could really do with some help here, if that is okay ?

Could someone suggest, where I am going wrong with this, and what
changes, I need to make to my Code ?

Also how do I get the for loop, not to include all combinations of Hex Values that are numbers only ? As I know, these combinations won't produce saved .bmp Files.

i.e. all input bytes == are numbers only for each of the 5 input_byte == blocks of Code ? i.e both digits are numbers i.e. 00, 01 etc ?

Please can someone help me ?

Regards

Eddie Winch

Body:
I have the following parts of C# Code for example and other else if's, where input_byte == have different Hex Values after the == :-

            input_byte = input_data[current_input_position];
            current_input_position++;

            if(input_byte == 0xFF) {
                //==============
                // Fin de chunk
                //==============
                Save();
                current_output_index++;

                RLE_sumador         = 0;
                line_min_length     = int.MaxValue;
                line_max_length     = 0;
                width_current       = 0;
                image_height        = 0;

            } else if(input_byte == 0xFE) {
                //=================
                // Siguiente linea
                //=================
                if(width_current < line_min_length) line_min_length = width_current;
                if(width_current > line_max_length) line_max_length = width_current;

                if(forced_image_width!=null) {
                    count = forced_image_width.Value - width_current;
                    if(count > 0) {
                        for(n=0; n<count; n++) {
                            output_buffer.Add(0);
                        }
                    }
                }

                image_height++;
                width_current = 0;

With the If and Else If parts of the code i.e. input_byte == 0xFF 0xFE 0xFD etc.. I want to alter the code, so I can brute force all possible combinations of individual hex values.

I think from 0x00 to 0xFF that is either 255 or 256 hex values. For example instead of 0xFF it could be 0x6E instead of 0xFE it be 0xFA etc. I have tried altering input_byte == to different things in the hope I get something useful as an output image. This code was used on another DOS game, to save graphics images as greyscale bitmap images.

I using this on the previous DOS game in the series.

I was thinking of using:

For(int input_byte=0x00;
input_byte <= 0xFF;
input_byte++)

Somewhere in the code, but I don't think that would do all possible combinations of hex values.

I have Added the following to my Code :-

for (int i = 0x00; i <= 0xFF; input_byte++)

After

input_byte = input_data[current_input_position];
        current_input_position++;

And changed all input_byte ==
to input_byte == 0x00

And removed a line of Code, that saves Files other than .bmp's, so only .bmp's are saved, have I done the write thing here ? As I am not sure.

The unpac Program is still running after 30 minutes. So possibly I have made the correct amendments ?

I have changed to using this line of Code instead :-

 for (int i = 0x00; i <= 0xFF; ++input_byte)

From :-

for (int i = 0x00; i <= 0xFF; input_byte++)

After reading up some Stackoverflow posts, of what the differences are, between ++i and i++, the amended line of Code sounds more appropriate for what I want, I hope this brute forcing, method takes hours rather than much longer. Can someone clarify for me, if all the changes I have made to my C# Code, definately should work ?

I didn't get anywhere, with the above for loop, and I tried doing it the other way round i.e :-

for (int i = 0xFF; i >= 0x00; --input_byte)

or :-

for (int i = 0xFF; i >= 0x00; i = --input_byte)

i.e. working backwards, so changing all the five   input_byte == 0x00 to   input_byte == 0xFF.

When I run in either direction, the number in the brackets in the output in Command Prompt stays at (639) when going  0x00 to 0xFF, and (636) when it is the other way round. And the File Number just keeps going up and up. Whereas for other Ranges, I have tried small or large, i.e. loop from 0x00 to 0x01 but even as far as 0x00 to 0xFE, the number in the brackets changes, for each File output, and the Program runs for a few seconds. for either large or small ranges in the for loop, when I use :-

i = --input_byte

or :-

i = ++input_byte

Whereas if I use 0xFF, it goes on and on. The other hex value ranges small or large, do the same when I just use ++input_byte or --input_byte. I was getting the same outcomes when it was input_byte++ or input_byte--. I could really do with some help here, if that is okay ?

Could someone suggest, where I am going wrong with this, and what
changes, I need to make to my Code ?

Also how do I get the for loop, not to include all combinations of Hex Values that are numbers only ? As I know, these combinations won't produce saved .bmp Files.

i.e. all input bytes == are numbers only for each of the 5 input_byte == blocks of Code ? i.e both digits are numbers i.e. 00, 01 etc ?

Please can someone help me ?

Regards

Eddie Winch


问:
Why mocking fetch in Jest with beforeAll hook fails while beforeEach does work properly?
I'm practicing mocking with a simple React app using Jest + React Testing Library.

I did successfully mock fetch to test the app's functionality but I'm wondering why setting up the mock with beforeEach hook works while with the beforeAll hook my tests fail.

This is the (working) test code:

```<code>import {
  render,
  screen,
  waitForElementToBeRemoved,
} from "@testing-library/react";
import App from "./App";
import { mockFetch } from "./mock-fetch";
import { mockResponse } from "./utils";

beforeEach(() => {
  jest.spyOn(window, "fetch").mockImplementation(mockFetch);
});

describe("<App />", () => {
  it("renders correctly a title", async () => {
    render(<App />);

    await waitForLoading();

    expect(screen.getByText(/list of posts/i)).toBeInTheDocument();
  });

  describe("when requesting for posts", () => {
    it("renders the list of posts once they are successfully fetched", async () => {
      render(<App />);

      await waitForLoading();

      mockResponse.products.forEach((product) => {
        expect(screen.getByText(product.title)).toBeInTheDocument();
        expect(screen.getByText(product.price)).toBeInTheDocument();
      });
    });

    it("should render an error message when posts fetch is not successful", async () => {
      const error = "Error";
      window.fetch.mockResolvedValueOnce({
        ok: false,
        status: 500,
      });

      render(<App />);

      await waitForLoading();

      expect(screen.getByText(error)).toBeInTheDocument();
    });

    it("should render a no posts message if there are no posts to show", async () => {
      window.fetch.mockResolvedValueOnce({
        ok: true,
        status: 200,
        json: () =>
          Promise.resolve({
            products: [],
          }),
      });

      render(<App />);

      await waitForLoading();

      expect(screen.getByText(/no posts.../i)).toBeInTheDocument();
    });
  });
});

function waitForLoading() {
  return waitForElementToBeRemoved(() => screen.queryByText(/loading.../i));
}
</code>```

This is the App component:

```<code>import { useState, useEffect } from "react";
import Products from "./Products";
import "./App.css";
import { fetchProducts } from "./fetch-products";

function App() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    fetchProducts()
      .then((results) => {
        setProducts(results.products);
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  if (error) return <div>{error}</div>;

  return (
    <div>
      <h1>List of posts</h1>
      {loading ? <p>Loading...</p> : <Products products={products} />}
    </div>
  );
}

export default App;
</code>```

When using beforeAll instead of beforeEach the assertions fail because it can't find the elements I'm querying for. Also, I noticed that the fetchProducts function throws, this error is being set on the error state and in the test it's rendering the div containing the error with the message: Cannot read properties of undefined (reading 'ok').

Body:
I'm practicing mocking with a simple React app using Jest + React Testing Library.

I did successfully mock fetch to test the app's functionality but I'm wondering why setting up the mock with beforeEach hook works while with the beforeAll hook my tests fail.

This is the (working) test code:

import {
  render,
  screen,
  waitForElementToBeRemoved,
} from "@testing-library/react";
import App from "./App";
import { mockFetch } from "./mock-fetch";
import { mockResponse } from "./utils";

beforeEach(() => {
  jest.spyOn(window, "fetch").mockImplementation(mockFetch);
});

describe("<App />", () => {
  it("renders correctly a title", async () => {
    render(<App />);

    await waitForLoading();

    expect(screen.getByText(/list of posts/i)).toBeInTheDocument();
  });

  describe("when requesting for posts", () => {
    it("renders the list of posts once they are successfully fetched", async () => {
      render(<App />);

      await waitForLoading();

      mockResponse.products.forEach((product) => {
        expect(screen.getByText(product.title)).toBeInTheDocument();
        expect(screen.getByText(product.price)).toBeInTheDocument();
      });
    });

    it("should render an error message when posts fetch is not successful", async () => {
      const error = "Error";
      window.fetch.mockResolvedValueOnce({
        ok: false,
        status: 500,
      });

      render(<App />);

      await waitForLoading();

      expect(screen.getByText(error)).toBeInTheDocument();
    });

    it("should render a no posts message if there are no posts to show", async () => {
      window.fetch.mockResolvedValueOnce({
        ok: true,
        status: 200,
        json: () =>
          Promise.resolve({
            products: [],
          }),
      });

      render(<App />);

      await waitForLoading();

      expect(screen.getByText(/no posts.../i)).toBeInTheDocument();
    });
  });
});

function waitForLoading() {
  return waitForElementToBeRemoved(() => screen.queryByText(/loading.../i));
}

This is the App component:

import { useState, useEffect } from "react";
import Products from "./Products";
import "./App.css";
import { fetchProducts } from "./fetch-products";

function App() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    fetchProducts()
      .then((results) => {
        setProducts(results.products);
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  if (error) return
{error}
;

  return (

List of posts

      {loading ?
Loading...
 : <Products products={products} />}

  );
}

export default App;

When using beforeAll instead of beforeEach the assertions fail because it can't find the elements I'm querying for. Also, I noticed that the fetchProducts function throws, this error is being set on the error state and in the test it's rendering the div containing the error with the message: Cannot read properties of undefined (reading 'ok').


问:
How to manually trigger react state update with browser javascript
I'm trying to write a Chrome Snippet to interact with a React page - it takes some JSON data and fills out a form.  The problem is, programmatically setting the value of various inputs doesn't update their React state.  If there's any interaction which re-renders the component, the data is lost.

I'm wondering if there is any hack I can make use of to trigger the React state update.  I tried triggering 'change' and 'keyup' events on the inputs but that didn't work.

In case it wasn't clear, I don't have any access to the page's React code at all.  I don't own it or maintain it.


问:
CDK Ec2 MultipartUserData control script order
I am using CDK to provision some EC2 instances and configure them using user-data.

My user data consists of 2 files

cloud-config

shell script.

What I have been noticing is that the shell script executes before my cloud-config finishes resulting in the script failing as all dependencies have not finished downloading.

Is there a way to control the run order? The reason I did not do all the configuration in the cloud config is I need to pass some arguments to the script and was easy using the ec2.UserData.forLinux().addExecuteFileCommand

   const multipartUserData = new ec2.MultipartUserData();

   multipartUserData.addUserDataPart(
      this.createBootstrapConfig(),
      'text/cloud-config; charset="utf8"'
    );

   multipartUserData.addUserDataPart(
      this.runInstallationScript(),
      'text/x-shellscript; charset="utf8"'
    );
```


问:
add commands dynamically to cog in disnake
This is my cog

```<code>class MyCog(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        cmds = get_commands()
        for command in cmds:
            @commands.command(name=command['name'], description=command['description'], extras=command, case_insensitive=True)
            async def cmd(self, ctx, member:Member):
                embed = await generate_embed(ctx.command.extras['query'])
                await ctx.send(member.mention, embed=embed)
            self.bot.add_command(cmd)
</code>```

For now the commands are added to the bot and I access them from bot.commands(), but I want them to be added to the cog so I can use cog.get_commands()

Is this possible ? I tried setattr(MyCog, command['name'], cmd) but it doesn't work

Body:
This is my cog

class MyCog(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        cmds = get_commands()
        for command in cmds:
            @commands.command(name=command['name'], description=command['description'], extras=command, case_insensitive=True)
            async def cmd(self, ctx, member:Member):
                embed = await generate_embed(ctx.command.extras['query'])
                await ctx.send(member.mention, embed=embed)
            self.bot.add_command(cmd)

For now the commands are added to the bot and I access them from bot.commands(), but I want them to be added to the cog so I can use cog.get_commands()

Is this possible ? I tried setattr(MyCog, command['name'], cmd) but it doesn't work


问:
sequence of events in shiny r when simulating button clicks by javascript in a loop
I am simulating several clicks on an action button by doing javascript calls document.getElementById('btn').click(); in a loop.
The issue is that the loop runs first to the end (say 3 times as in example below) and only after that the clicks on the button actually happen (3 in a row).
I want to change this behavior so that the loop with js code waits until the triggered observeEvent for the button stops executing and only then proceeds to the next i value.

The below code demonstrates this behavior by outputting sequence of events into textOutput.
Pressing "trigger" produces:

TRIGGER,  TRIGGER,  TRIGGER,  BUTTON,  BUTTON,  BUTTON,

And what I want is

TRIGGER,  BUTTON,  TRIGGER,  BUTTON,  TRIGGER,  BUTTON,

```<code>library(shiny)
library(shinyjs)

shinyApp(
  ui = fluidPage(
    useShinyjs(),
    actionButton("trigger", "Trigger 3 clicks"),
    actionButton("btn", "BUTTON"),
    verbatimTextOutput("num"),
  ),
  server = function(input, output) {

    sequence <- reactiveVal(c())

    observeEvent(input$trigger, {
      for (i in 1:3) {
        sequence(append(sequence(), "TRIGGER, "))
        runjs("document.getElementById('btn').click();")
      }
    })

    observeEvent(input$btn, {
      sequence(append(sequence(), "BUTTON, "))
      output$num <- renderText(sequence())
    })
  }
)
</code>```

Body:
I am simulating several clicks on an action button by doing javascript calls document.getElementById('btn').click(); in a loop.
The issue is that the loop runs first to the end (say 3 times as in example below) and only after that the clicks on the button actually happen (3 in a row).
I want to change this behavior so that the loop with js code waits until the triggered observeEvent for the button stops executing and only then proceeds to the next i value.

The below code demonstrates this behavior by outputting sequence of events into textOutput.
Pressing "trigger" produces:

TRIGGER,  TRIGGER,  TRIGGER,  BUTTON,  BUTTON,  BUTTON,

And what I want is

TRIGGER,  BUTTON,  TRIGGER,  BUTTON,  TRIGGER,  BUTTON,

library(shiny)
library(shinyjs)

shinyApp(
  ui = fluidPage(
    useShinyjs(),
    actionButton("trigger", "Trigger 3 clicks"),
    actionButton("btn", "BUTTON"),
    verbatimTextOutput("num"),
  ),
  server = function(input, output) {

    sequence <- reactiveVal(c())

    observeEvent(input$trigger, {
      for (i in 1:3) {
        sequence(append(sequence(), "TRIGGER, "))
        runjs("document.getElementById('btn').click();")
      }
    })

    observeEvent(input$btn, {
      sequence(append(sequence(), "BUTTON, "))
      output$num <- renderText(sequence())
    })
  }
)


问:
Load User after Login in react js
I want to load user after they login in react js using redux,

I have loaded the user in App.js like this

```<code>import { useEffect } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import "./App.css";
import Cart from "./pages/Cart/Cart";
import Home from "./pages/Home";
import Login from "./pages/Login/Login";
import NotFound from "./pages/NotFound";
import ProductDetail from "./pages/Prduct Detail/ProductDetail";
import ProductsList from "./pages/Product/ProductsList";
import Profile from "./pages/Profile/Profile";
import Register from "./pages/Register/Register";
import Shipment from "./pages/Shipment/Shipment";
import Status from "./pages/Status/Status";
import Transaction from "./pages/Transaction/Transaction";
import { loadUser } from "./redux/action/authAction";
import store from "./store";
import Cookies from "js-cookie";

function App() {
  useEffect(() => {
    store.dispatch(loadUser());
  }, []);

  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
          <Route path="*" element={<NotFound />} />
          <Route path="/" element={<Home />} />

          <Route path="/products/:category" element={<ProductsList />} />
          <Route path="/products/" element={<ProductsList />} />

          <Route path="/detail/:id" element={<ProductDetail />} />

          <Route path="/register" element={<Register />} />
          <Route path="/login" element={<Login />} />

          <Route path="/cart" element={<Cart />} />
          <Route path="/cart/shipment" element={<Shipment />} />
          <Route path="/payment/status" element={<Status />} />
          <Route path="/transaction" element={<Transaction />} />

          <Route path="/profile" element={<Profile />} />
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;

</code>```

it is success loading using after they login, but in console, the error like this appear
Error in console

I believe, when user goes to Login page, it triggers this code

```<code> useEffect(() => {
    store.dispatch(loadUser());
  }, []);
</code>```

further explanation: loadUser is action in redux, it retieve token in cookie

I want to load user without having error in console,

can anyone help me with this?

Title: Load User after Login in react js

Body:
I want to load user after they login in react js using redux,

I have loaded the user in App.js like this

import { useEffect } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import "./App.css";
import Cart from "./pages/Cart/Cart";
import Home from "./pages/Home";
import Login from "./pages/Login/Login";
import NotFound from "./pages/NotFound";
import ProductDetail from "./pages/Prduct Detail/ProductDetail";
import ProductsList from "./pages/Product/ProductsList";
import Profile from "./pages/Profile/Profile";
import Register from "./pages/Register/Register";
import Shipment from "./pages/Shipment/Shipment";
import Status from "./pages/Status/Status";
import Transaction from "./pages/Transaction/Transaction";
import { loadUser } from "./redux/action/authAction";
import store from "./store";
import Cookies from "js-cookie";

function App() {
  useEffect(() => {
    store.dispatch(loadUser());
  }, []);

  return (

      <BrowserRouter>
        <Routes>
          <Route path="*" element={<NotFound />} />
          <Route path="/" element={<Home />} />

          <Route path="/products/:category" element={<ProductsList />} />
          <Route path="/products/" element={<ProductsList />} />

          <Route path="/detail/:id" element={<ProductDetail />} />

          <Route path="/register" element={<Register />} />
          <Route path="/login" element={<Login />} />

          <Route path="/cart" element={<Cart />} />
          <Route path="/cart/shipment" element={<Shipment />} />
          <Route path="/payment/status" element={<Status />} />
          <Route path="/transaction" element={<Transaction />} />

          <Route path="/profile" element={<Profile />} />
        </Routes>
      </BrowserRouter>

  );
}

export default App;

it is success loading using after they login, but in console, the error like this appear
Error in console

I believe, when user goes to Login page, it triggers this code

 useEffect(() => {
    store.dispatch(loadUser());
  }, []);

further explanation: loadUser is action in redux, it retieve token in cookie

I want to load user without having error in console,

can anyone help me with this?


问:
Flutter: push a new page and scroll down to certain widget
I have a web app in Flutter. My app bar has 5 buttons. Four of them scroll within the first page. The 5th one pushes a new page.

There are three different widgets on stage:

page A (HomeView)

page B (ContactView)

the AppBar

When the user is on page A, the buttons of page A should scroll down or up, and the button of page B should push the new view. When the user is on page B (contact) and presses any of the buttons of page A, it should push the home page and scroll to the required position.

I tried to do this with ScrollController.animateTo and Riverpod for state management, but I couldn't do it. The page scrolled down but, for some reason, it scrolled up again and didn't maintain position. I couldn't find any related post on the Internet and keepScrollOffset was not the answer. I also didn't know how to scroll to the desired position when the user is not on 0 (it scrolled down from current position).

After that, I tried to do it with GlobalKeys. It worked, up to a certain point. On page A, everything worked fine. However, from page B to page A, it said the keys are duplicated. I used pop instead of pushNamed as suggested in one of the answers of this post (the only answer that worked for me). The behavior was finally as expected, but I can't use pop since I have more pages on the website, so I can't ensure that the user is coming from page A. I tried with pushReplacement as the same answer gives that for an alternative option. It doesn't work now. When trying to go from page B (contact) to page A, it throws error Unexpected null value.. Furthermore, I need to keep the back button functionality since it is a website. I would prefer, then, to not pop the current page from the stack.

The page A (HomeView) is built like this inside of a StatefulWidget:

```<code>  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      controller: _scrollController,
      child: Column(
        children: [
          HomeHeader(key: HomeView.homeKey),
          WhatWeOffer(key: HomeView.servicesKey),
          WhatWeDo(key: HomeView.referencesKey),
          WhoWeAre(key: HomeView.aboutKey),
          const LetsGetInTouch(),
        ],
      ),
    );
  }
</code>```

The GlobalKeys are defined like this inside of the Page A (HomeView) widget:

```<code>  static GlobalKey homeKey = GlobalKey(debugLabel: 'homeHeaderKey');
  static GlobalKey servicesKey = GlobalKey(debugLabel: 'whatWeOfferKey');
  static GlobalKey referencesKey = GlobalKey(debugLabel: 'whatWeDoKey');
  static GlobalKey aboutKey = GlobalKey(debugLabel: 'whoWeAreKey');
</code>```

This is how I implement the navigation to page A:

```<code>if (ModalRoute.of(context)?.settings.name != '/') {
  Navigator.pushReplacementNamed(
    context,
    Navigation(context).routes["/"]!,
  );
}
Scrollable.ensureVisible(
  HomeView.homeKey.currentContext!,
  duration: const Duration(milliseconds: 500),
  curve: Curves.easeInOut,
);
</code>```

And this is how I implement the navigation to page B:

```<code>   Navigator.pushReplacementNamed(
     context,
     Navigation(context).routes["/contact"]!,
   ),
</code>```

Maybe GlobalKey is not the right approach to my problem? Is there any easier way to push a new page and scroll down to a widget?

EDIT:

I think the Unexpected null value problem was caused because the view was not built yet when I was trying to call it. I solved it by making the functions async and waiting before using the keys:

```<code>  TextButton(
    child: Text('home', style: style),
    onPressed: () async {
      if (ModalRoute.of(context)?.settings.name != '/') {
        Navigator.pushReplacementNamed(
          context,
          Navigation(context).routes['/']!,
        );
      await Future.delayed(const Duration(milliseconds: 500));
      }
      Scrollable.ensureVisible(
        HomeView.homeKey.currentContext!,
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
    },
  ),
</code>```

However, this does not solve my problem of the back button. As I use pushReplacementNamed instead of pushNamed, I can't go back. Is there a more optimal way to do this, where I can keep the back button functionality?

Body:
I have a web app in Flutter. My app bar has 5 buttons. Four of them scroll within the first page. The 5th one pushes a new page.

There are three different widgets on stage:

page A (HomeView)

page B (ContactView)

the AppBar

When the user is on page A, the buttons of page A should scroll down or up, and the button of page B should push the new view. When the user is on page B (contact) and presses any of the buttons of page A, it should push the home page and scroll to the required position.

I tried to do this with ScrollController.animateTo and Riverpod for state management, but I couldn't do it. The page scrolled down but, for some reason, it scrolled up again and didn't maintain position. I couldn't find any related post on the Internet and keepScrollOffset was not the answer. I also didn't know how to scroll to the desired position when the user is not on 0 (it scrolled down from current position).

After that, I tried to do it with GlobalKeys. It worked, up to a certain point. On page A, everything worked fine. However, from page B to page A, it said the keys are duplicated. I used pop instead of pushNamed as suggested in one of the answers of this post (the only answer that worked for me). The behavior was finally as expected, but I can't use pop since I have more pages on the website, so I can't ensure that the user is coming from page A. I tried with pushReplacement as the same answer gives that for an alternative option. It doesn't work now. When trying to go from page B (contact) to page A, it throws error Unexpected null value.. Furthermore, I need to keep the back button functionality since it is a website. I would prefer, then, to not pop the current page from the stack.

The page A (HomeView) is built like this inside of a StatefulWidget:

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      controller: _scrollController,
      child: Column(
        children: [
          HomeHeader(key: HomeView.homeKey),
          WhatWeOffer(key: HomeView.servicesKey),
          WhatWeDo(key: HomeView.referencesKey),
          WhoWeAre(key: HomeView.aboutKey),
          const LetsGetInTouch(),
        ],
      ),
    );
  }

The GlobalKeys are defined like this inside of the Page A (HomeView) widget:

  static GlobalKey homeKey = GlobalKey(debugLabel: 'homeHeaderKey');
  static GlobalKey servicesKey = GlobalKey(debugLabel: 'whatWeOfferKey');
  static GlobalKey referencesKey = GlobalKey(debugLabel: 'whatWeDoKey');
  static GlobalKey aboutKey = GlobalKey(debugLabel: 'whoWeAreKey');

This is how I implement the navigation to page A:

if (ModalRoute.of(context)?.settings.name != '/') {
  Navigator.pushReplacementNamed(
    context,
    Navigation(context).routes["/"]!,
  );
}
Scrollable.ensureVisible(
  HomeView.homeKey.currentContext!,
  duration: const Duration(milliseconds: 500),
  curve: Curves.easeInOut,
);

And this is how I implement the navigation to page B:

   Navigator.pushReplacementNamed(
     context,
     Navigation(context).routes["/contact"]!,
   ),

Maybe GlobalKey is not the right approach to my problem? Is there any easier way to push a new page and scroll down to a widget?

EDIT:

I think the Unexpected null value problem was caused because the view was not built yet when I was trying to call it. I solved it by making the functions async and waiting before using the keys:

  TextButton(
    child: Text('home', style: style),
    onPressed: () async {
      if (ModalRoute.of(context)?.settings.name != '/') {
        Navigator.pushReplacementNamed(
          context,
          Navigation(context).routes['/']!,
        );
      await Future.delayed(const Duration(milliseconds: 500));
      }
      Scrollable.ensureVisible(
        HomeView.homeKey.currentContext!,
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
    },
  ),

However, this does not solve my problem of the back button. As I use pushReplacementNamed instead of pushNamed, I can't go back. Is there a more optimal way to do this, where I can keep the back button functionality?


问:
Instance of 'PostgrestFilterBuilder<dynamic>' to bool
i'm working on a flutter app and supabase. I have a table with some information and one of the column is a bool type.

when I recall an information of that column, I receive Instance of 'PostgrestFilterBuilder' and not a true/false information.

the code i used is this:

```<code>autorizzazione = supabase.from('profili').select('autorized').textSearch('usernumber', matricola!)
</code>```

I think I'm so wrong with that code.

Update (31/12/2022)

I tried some experiments and I found a part of solution: Future function asynced.

If I use a function like this:

```<code>    Future<Map<String, String>> _nameOfFunction(BuildContext context, String Input) async {
         var output = supabase.from('table').select('column1, column2').textSearch('column1', Input);
...other code here...
         return userinfo;
    }
</code>```

I receive exactly what I want, because "userinfo" saved the info. But, if I recall that funcion in a `Widget build(BuildContext context) {}', that doesn't work. It returns "Instance of 'Map<String, String>' " and not the real output.

However, my problem is to recall that info stored in that table on supabase before create the SideBar and used it for enable or disable the buttons.

Body:
i'm working on a flutter app and supabase. I have a table with some information and one of the column is a bool type.

when I recall an information of that column, I receive Instance of 'PostgrestFilterBuilder' and not a true/false information.

the code i used is this:

autorizzazione = supabase.from('profili').select('autorized').textSearch('usernumber', matricola!)

I think I'm so wrong with that code.

Update (31/12/2022)

I tried some experiments and I found a part of solution: Future function asynced.

If I use a function like this:

    Future<Map<String, String>> _nameOfFunction(BuildContext context, String Input) async {
         var output = supabase.from('table').select('column1, column2').textSearch('column1', Input);
...other code here...
         return userinfo;
    }

I receive exactly what I want, because "userinfo" saved the info. But, if I recall that funcion in a `Widget build(BuildContext context) {}', that doesn't work. It returns "Instance of 'Map<String, String>' " and not the real output.

However, my problem is to recall that info stored in that table on supabase before create the SideBar and used it for enable or disable the buttons.


问:
How do I make an AWS Budget Action stop serving public files from an S3 bucket?
I have an Amazon S3 bucket hosting some images for a static website. To keep things simple, I made folders in the bucket publicly readable with "make public using ACL" in the web console (so I can just link to the images from elsewhere).

I want to set up a budget limit on this bucket so I don't wake up to a huge S3 charge if it gets Reddit-hugged etc. Can I make a Budget Action that disables public read access for an S3 bucket (folder)?

None of the built-in budget actions in the web console seem relevant. The bewildering AWS docs mention something about SCPs but I don't see those could apply here. Someone else asked a similar question here but got no answers.

So far I've

Made my bucket and the files in it publicly readable (that's the point)

Attached a user-defined tag (eg "budget_limit_foo") to the bucket

Activated this tag as a cost allocation tag

Created a budget in the Billing Console set to Fixed Budget, Blended Costs, and using tag "budget_limit_foo" as a filter dimension.

Created a budget alert with threshold at 90% (that's the one that'll trip the action)

Gotten to "attach actions" in the "Create Budgets" template and hit a wall.

And to clarify, I only want to disable public read — or file transfer out — on this one bucket when it hits its limit. I'd prefer it didn't delete the files!


问:
React Native cheerio.load() not working properly neither is JSDOM library
Well I'm new to this app development thing especially react-native and I wanted to know when I'm trying to scrap a website using cheerio and axios in react-native and then save it to firebase realtime database in the following way:
and yes i have done all the imports and also initalized my app using firebaseConfig

```<code>const db = firebase.database();

async function loadFurniture() {
  const Url = 'https://hoid.pk/product-category/bedroom/beds-bedroom/';
  const html = await axios.get(Url);  // fetch page
  const $ = cheerio.load(html);   //parse html String
  const furniture = [];
  $('.product-wrapper ').each((i, element) => {
    const title = $(element).find('h2.product-name').text();
    const imageUrl = $(element).find('img.primary_image').attr('src');
    const price = $(element).find('span.woocommerce-Price-amount amount').text();
    console.log(title);

    furniture.push({ title, imageUrl, price });
  });
    // Save the furniture to the Firebase Realtime Database
  db
    .ref('/furniture/bed')
    .set({
      title: furniture.title,
      price: furniture.price,
      object_image : furniture.imageUrl,
    })
  .then(() => console.log('Data set.'));
  console.log(furniture);
//  Return the extracted information
  return furniture;
}
</code>```

and then calling this function in a button

```<code><Button
                title="Fetch"
                onPress = {() => loadFurniture() }
                />
</code>```

The data was not being scraped so I tried to console.log() the data being fetched.
Whenever I click the button there is no error but just a log [ Function initialize ] with respect to console.log(title)
And before anyone says yup I've looked into the structure and 9it does returns me my desired  classes after axios.get()
I just want to know that if there's some error in my code or if I'm  going wrong somewhere.

I tried to scrap furniture titles, images and prices from certain website and then save it to database for any further use but it's just not working.
I've checked my network issues the html page being scraped and everything else one can think of. Now i just want to know either my code is accurate or if there's some mistake.
I tired to scrap the data of same website using python and it scraps it perfectly.

Edit:

I found out that the cheerio.load() function is not working there was no problem with the database... Is there some problem with cheerio.load() in it's latest version "1.0.0-rc.12" ?? If so what's the solution... I've tried number of libraries and each is giving a different kind of error so cheerio might be the only possible solution so if there's an alternative way of using cheerio.load() in react native do let me know.

Body:
Well I'm new to this app development thing especially react-native and I wanted to know when I'm trying to scrap a website using cheerio and axios in react-native and then save it to firebase realtime database in the following way:
and yes i have done all the imports and also initalized my app using firebaseConfig

const db = firebase.database();

async function loadFurniture() {
  const Url = 'https://hoid.pk/product-category/bedroom/beds-bedroom/';
  const html = await axios.get(Url);  // fetch page
  const $ = cheerio.load(html);   //parse html String
  const furniture = [];
  $('.product-wrapper ').each((i, element) => {
    const title = $(element).find('h2.product-name').text();
    const imageUrl = $(element).find('img.primary_image').attr('src');
    const price = $(element).find('span.woocommerce-Price-amount amount').text();
    console.log(title);

    furniture.push({ title, imageUrl, price });
  });
    // Save the furniture to the Firebase Realtime Database
  db
    .ref('/furniture/bed')
    .set({
      title: furniture.title,
      price: furniture.price,
      object_image : furniture.imageUrl,
    })
  .then(() => console.log('Data set.'));
  console.log(furniture);
//  Return the extracted information
  return furniture;
}

and then calling this function in a button

<Button
                title="Fetch"
                onPress = {() => loadFurniture() }
                />

The data was not being scraped so I tried to console.log() the data being fetched.
Whenever I click the button there is no error but just a log [ Function initialize ] with respect to console.log(title)
And before anyone says yup I've looked into the structure and 9it does returns me my desired  classes after axios.get()
I just want to know that if there's some error in my code or if I'm  going wrong somewhere.

I tried to scrap furniture titles, images and prices from certain website and then save it to database for any further use but it's just not working.
I've checked my network issues the html page being scraped and everything else one can think of. Now i just want to know either my code is accurate or if there's some mistake.
I tired to scrap the data of same website using python and it scraps it perfectly.

Edit:

I found out that the cheerio.load() function is not working there was no problem with the database... Is there some problem with cheerio.load() in it's latest version "1.0.0-rc.12" ?? If so what's the solution... I've tried number of libraries and each is giving a different kind of error so cheerio might be the only possible solution so if there's an alternative way of using cheerio.load() in react native do let me know.


问:
Using Simscape multibody to monitor temperature and pressure changes
I have imported Cad models of a mechanical system to Simscape multibody.
I need to reflect the effect of some physical parameters (like temperature, pressure...) on the surface of the parts of the system, such that their color changes according to the level of the parameter.
Are there any specific methods that could help me to achieve this step?</p>


问:
how to draw a sprite on a surface with transparent elements in Pygame?
In my code, I use surface as a scrolling panel that stores various notes. The panel has the shape of a square with rounded corners. Therefore, when I use the blit() method to draw information in the feed, it constantly climbs into areas where the corners are rounded. How can I draw a sprite onto the surface of another without rendering it in places on the surface where its pixels are transparent?

I tried to use the special_flags=pygame.BLEND_RGBA_MULT argument for the blit() method, but it raped my application. the transparent parts of the panel turned black, and the objects inside became transparent.


问:
Maven settings.xml - upload same build jar files to multiple maven repositories
I'm looking to use mvn deploy to deploy all of the same jar file build artifacts to different maven repositories. Basically, I'm looking to make duplicate copies in multiple places. I'm trying to do this because I'm trying to migrate from one repository to another and I want to push to both places as a transitional step. (And I can't mirror the repositories as a whole.)

My (probably flawed) understanding is that I'd setup multiple "repositories" and "servers" in my settings.xml.

from settings.xml

        <servers>
            <server>
                <id>${env.MAVEN_SERVER_ID_1</id>
                <username>${env.MAVEN_SERVER_USERNAME_1}</username>
                <password>${env.MAVEN_SERVER_PASSWORD_1}</password>
            </server>
            <server>
                <id>${env.MAVEN_SERVER_ID_2</id>
                <username>${env.MAVEN_SERVER_USERNAME_2}</username>
                <password>${env.MAVEN_SERVER_PASSWORD_2}</password>
            </server>
        </servers>

        <profiles>
            <profile>
                <id>my-profile</id>
                <repositories>
                  <repository>
                    <id>${env.MAVEN_SERVER_ID_1}</id>
                    <name>${env.MAVEN_SERVER_NAME_1}</name>
                    <url>${env.MAVEN_REPOSITORY_URL_1}</url>
                    <layout>default</layout>
                  </repository>
                  <repository>
                    <id>${env.MAVEN_SERVER_ID_2}</id>
                    <name>${env.MAVEN_SERVER_NAME_2}</name>
                    <url>${env.MAVEN_REPOSITORY_URL_2}</url>
                    <layout>default</layout>
                  </repository>
                </repositories>
            </profile>
        </profiles>

        <activeProfiles>
            <activeProfile>my-profile</activeProfile>
        </activeProfiles>

```
<p>Then, when deploying, this is run.</p>
<pre class="lang-bash prettyprint-override"><code>mvn --settings=/path/to/settings.xml \
   deploy \
  -DaltDeploymentRepository="${MAVEN_SERVER_ID_1}::default::${MAVEN_REPOSITORY_URL_1}" \
  /path/to/project/
</code>```

This only pushes to one of the 2 repositories, but how do I change it so the deploy will push to both repositories at the same time?  This maven deploy is something that is currently automated, so I'm trying to update the automation to deploy to both places.

I'm pretty new to maven, so maybe this is an obvious answer, but I'd be very appreciative of any help.

Body:
I'm looking to use mvn deploy to deploy all of the same jar file build artifacts to different maven repositories. Basically, I'm looking to make duplicate copies in multiple places. I'm trying to do this because I'm trying to migrate from one repository to another and I want to push to both places as a transitional step. (And I can't mirror the repositories as a whole.)

My (probably flawed) understanding is that I'd setup multiple "repositories" and "servers" in my settings.xml.

from settings.xml

        <servers>
            <server>
                <id>${env.MAVEN_SERVER_ID_1</id>
                <username>${env.MAVEN_SERVER_USERNAME_1}</username>
                <password>${env.MAVEN_SERVER_PASSWORD_1}</password>
            </server>
            <server>
                <id>${env.MAVEN_SERVER_ID_2</id>
                <username>${env.MAVEN_SERVER_USERNAME_2}</username>
                <password>${env.MAVEN_SERVER_PASSWORD_2}</password>
            </server>
        </servers>

        <profiles>
            <profile>
                <id>my-profile</id>
                <repositories>
                  <repository>
                    <id>${env.MAVEN_SERVER_ID_1}</id>
                    <name>${env.MAVEN_SERVER_NAME_1}</name>
                    <url>${env.MAVEN_REPOSITORY_URL_1}</url>
                    <layout>default</layout>
                  </repository>
                  <repository>
                    <id>${env.MAVEN_SERVER_ID_2}</id>
                    <name>${env.MAVEN_SERVER_NAME_2}</name>
                    <url>${env.MAVEN_REPOSITORY_URL_2}</url>
                    <layout>default</layout>
                  </repository>
                </repositories>
            </profile>
        </profiles>

        <activeProfiles>
            <activeProfile>my-profile</activeProfile>
        </activeProfiles>

Then, when deploying, this is run.

mvn --settings=/path/to/settings.xml \
   deploy \
  -DaltDeploymentRepository="${MAVEN_SERVER_ID_1}::default::${MAVEN_REPOSITORY_URL_1}" \
  /path/to/project/

This only pushes to one of the 2 repositories, but how do I change it so the deploy will push to both repositories at the same time?  This maven deploy is something that is currently automated, so I'm trying to update the automation to deploy to both places.

I'm pretty new to maven, so maybe this is an obvious answer, but I'd be very appreciative of any help.


问:
Laravel Jetstream Profile Photo Not Stored on Vapor
I'm using Laravel Jetstream (Laravel V9 + InertiaJS Vue 3) on vapor.
I installed the jetstream package in default Laravel and deployed on vapor.

When I updated profile photo on profile page, It's still showing ui-avatars with Remove Photo button and profile_photo_path column in users table is updated as 1. (instead of NULL)

I changed profile_photo_disk to s3 in jetstream configuration.

And the other image uploads (spatie medialibrary) are working fine.


问:
How do I fix my command prompt now being able to run and command prompt applications?
I cannot open any command prompt applications inside of my command prompt (Windows 10). These include things like SFC or DISM. I cant run pip or anything like that. Why is it broken and how do I fix it?

Whenever I try to run a command prompt application it says "Command application" not recongnized or external command

I tried restarting my pc and fixing system files. Neither worked.


问:
How to check expiry date of GCP application default token from python?
Is there a way using python to check whether Application Default Token needs to be renewed or not? I'd like to do this check and update ADC accordingly to avoid the need to enter the password for auth when running an app locally.

I didn't find anything useful in the ADC file in the path shared by Google.


问:
Problem with Using Anderson Acceleration within perceptron algorithm for multi-class classification
I am trying to implement a perceptron algorithm for multi-class classification where I want to observe the effect of anderson acceleration on the convergence. Here is my code

```<code>import numpy as np

def perceptron_aa(X, y, n_iterations, alpha):
    """
    Perceptron algorithm with Anderson acceleration for multi-class classification.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Training data.
    y : array-like, shape (n_samples,)
        Target labels.
    n_iterations : int
        Number of iterations to run the algorithm.
    alpha : float
        Anderson acceleration factor.

    Returns
    -------
    w : array-like, shape (n_features,)
        Weight vector.
    loss : list
        Loss at each iteration.
    """
    # Convert the labels to one-hot encoded labels
    y_one_hot = np.eye(np.max(y) + 1)[y]

    # Initialize the weight vector and the loss list
    w = np.random.randn(X.shape[1])
    loss = []

    # Initialize the weight vector history
    w_history = [w]

    # Run the Perceptron algorithm with Anderson acceleration
    for i in range(n_iterations):
        # Initialize the loss for this iteration
        iter_loss = 0

        # Loop through the training data and update the weight vector
        for x, y in zip(X, y_one_hot):
            # Predict the class using the current weight vector
            y_pred = np.argmax(np.dot(w, x))

            # Update the weight vector if the prediction is incorrect
            if np.any(y_pred != y):
#                 w[np.argmax(y)] += x
#                 w[np.argmax(y_pred)] -= x

                w[np.argmax(y)] += x[np.argmax(y)]
                w[np.argmax(y_pred)] -= x[np.argmax(y_pred)]

            # Compute the loss for this sample
            sample_loss = np.mean((y_pred - y) ** 2)

            # Increment the loss for this iteration
            iter_loss += sample_loss

        # Add the updated weight vector to the history
        w_history.append(w)

        # If we have enough past weight vectors, perform Anderson acceleration
        if len(w_history) > 2:
            # Extrapolate from the past weight vectors using Anderson acceleration
            w = w + alpha * (w - w_history[-2])

        # Store the average loss per sample for this iteration
        loss.append(iter_loss / len(X))

    return w, loss
</code>```

I am then using some random data to test the performance of the above function using different number of iterations and alpha values

```<code>import matplotlib.pyplot as plt

n_classes = 5
# n_iterations = 10

# Load the training data and labels
X_train = np.random.randn(100, n_classes)
y_train = np.random.randint(n_classes, size=100)

# Load the test data and labels
X_test = np.random.randn(20, n_classes)
y_test = np.random.randint(n_classes, size=20)

# Set the number of iterations
n_iterations = 10

# Run the Perceptron algorithm with Anderson acceleration using different values of alpha
alpha_values = [0.1, 0.2, 0.3, 0.4, 0.5]
losses = []
for alpha in alpha_values:
    _, loss = perceptron_aa(X_train, y_train, n_iterations, alpha)
    losses.append(loss)

# Plot the loss for each value of alpha
for i, loss in enumerate(losses):
    plt.plot(loss, label=f'alpha={alpha_values[i]:.1f}')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.legend()
plt.show()
</code>```

However, the plot always shows the same loss values with the increasing number of iterations. Any idea what I am doing wrong? Ideally, the loss should decrease with the number of iterations and eventually it should converge at some point. But even with 100 number of iterations, I see the flat line for the loss.

Body:
I am trying to implement a perceptron algorithm for multi-class classification where I want to observe the effect of anderson acceleration on the convergence. Here is my code

import numpy as np

def perceptron_aa(X, y, n_iterations, alpha):
    """
    Perceptron algorithm with Anderson acceleration for multi-class classification.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Training data.
    y : array-like, shape (n_samples,)
        Target labels.
    n_iterations : int
        Number of iterations to run the algorithm.
    alpha : float
        Anderson acceleration factor.

    Returns
    -------
    w : array-like, shape (n_features,)
        Weight vector.
    loss : list
        Loss at each iteration.
    """
    # Convert the labels to one-hot encoded labels
    y_one_hot = np.eye(np.max(y) + 1)[y]

    # Initialize the weight vector and the loss list
    w = np.random.randn(X.shape[1])
    loss = []

    # Initialize the weight vector history
    w_history = [w]

    # Run the Perceptron algorithm with Anderson acceleration
    for i in range(n_iterations):
        # Initialize the loss for this iteration
        iter_loss = 0

        # Loop through the training data and update the weight vector
        for x, y in zip(X, y_one_hot):
            # Predict the class using the current weight vector
            y_pred = np.argmax(np.dot(w, x))

            # Update the weight vector if the prediction is incorrect
            if np.any(y_pred != y):
#                 w[np.argmax(y)] += x
#                 w[np.argmax(y_pred)] -= x

                w[np.argmax(y)] += x[np.argmax(y)]
                w[np.argmax(y_pred)] -= x[np.argmax(y_pred)]

            # Compute the loss for this sample
            sample_loss = np.mean((y_pred - y) ** 2)

            # Increment the loss for this iteration
            iter_loss += sample_loss

        # Add the updated weight vector to the history
        w_history.append(w)

        # If we have enough past weight vectors, perform Anderson acceleration
        if len(w_history) > 2:
            # Extrapolate from the past weight vectors using Anderson acceleration
            w = w + alpha * (w - w_history[-2])

        # Store the average loss per sample for this iteration
        loss.append(iter_loss / len(X))

    return w, loss

I am then using some random data to test the performance of the above function using different number of iterations and alpha values

import matplotlib.pyplot as plt

n_classes = 5
# n_iterations = 10

# Load the training data and labels
X_train = np.random.randn(100, n_classes)
y_train = np.random.randint(n_classes, size=100)

# Load the test data and labels
X_test = np.random.randn(20, n_classes)
y_test = np.random.randint(n_classes, size=20)

# Set the number of iterations
n_iterations = 10

# Run the Perceptron algorithm with Anderson acceleration using different values of alpha
alpha_values = [0.1, 0.2, 0.3, 0.4, 0.5]
losses = []
for alpha in alpha_values:
    _, loss = perceptron_aa(X_train, y_train, n_iterations, alpha)
    losses.append(loss)

# Plot the loss for each value of alpha
for i, loss in enumerate(losses):
    plt.plot(loss, label=f'alpha={alpha_values[i]:.1f}')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.legend()
plt.show()

However, the plot always shows the same loss values with the increasing number of iterations. Any idea what I am doing wrong? Ideally, the loss should decrease with the number of iterations and eventually it should converge at some point. But even with 100 number of iterations, I see the flat line for the loss.