问:
Video to Gif - Stretch to Scale
I have some videos that I want to turn into a gif.

When I use scale=800x600 on let's say as an example on a 1280x720 video. Instead of the gif being squashed into a 800x600 it just crops the video or just captured 800x600 of the 1280x720.

What code do I need to tell it squash itself into a 800x600 gif? Normally it just turns the video into a 800x600 squashed if converted to a video but not working for the gif for some reason.

Title: Video to Gif - Stretch to Scale


来源: stackexchange

问:
Saving *pvtu files using vtkXMLPUnstructuredGrid
I have a bunch of *pvtu files generated from deal.ii. I am making some modifications to these files using pyvista and saving them as *pvtu using vtk. My python function to save files is as follows -

```<code>def parallelWrite(mesh,savename):
    writer=vtk.vtkXMLPUnstructuredGridWriter()
    writer.SetInputData(mesh)
    writer.SetNumberOfPieces(64)
    writer.SetFileName(savename)
    writer.SetStartPiece(0)
    writer.SetEndPiece(63)
    writer.Write()
</code>```

The parallelWrite function does generate *pvtu files, but the size of each *vtu files is as big as if written into a single *vtu file. The *pvtu files generated from deal.ii have only a fraction of the size despite having much more data.

These are the sample *pvtu files for reference - the one I generated and the one generated by deal.ii

ContentLicense: CC BY-SA 4.0

Body:
I have a bunch of *pvtu files generated from deal.ii. I am making some modifications to these files using pyvista and saving them as *pvtu using vtk. My python function to save files is as follows -

def parallelWrite(mesh,savename):
    writer=vtk.vtkXMLPUnstructuredGridWriter()
    writer.SetInputData(mesh)
    writer.SetNumberOfPieces(64)
    writer.SetFileName(savename)
    writer.SetStartPiece(0)
    writer.SetEndPiece(63)
    writer.Write()

The parallelWrite function does generate *pvtu files, but the size of each *vtu files is as big as if written into a single *vtu file. The *pvtu files generated from deal.ii have only a fraction of the size despite having much more data.

These are the sample *pvtu files for reference - the one I generated and the one generated by deal.ii


问:
issue while writing into postgresql database in glue job
Hey I am trying to write data into postgresql db from glue job but getting below error
IllegalArgumentException: Option 'dbtable' can not be empty.

Below is my code which seems to be correct

How I read from s3

```<code>glueContext.create_dynamic_frame.from_options(
            format_options={"multiline": False},
            connection_type="s3",
            format="json",
            connection_options={
                "paths": [s3path],
                "recurse": True,
            },
            transformation_ctx=S3_TO_CUSTOM_TRANSFORM,
        )
</code>```

And then after some transformation I try to writeusing below code

```<code>
glueContext.write_dynamic_frame.from_options(
            frame=df,
            connection_type="postgresql",
            connection_options={
                "url": "jdbc:postgresql://<host>:port/db",
                "user": "username",
                "password": "password",
                "dbtable": "table_name"
            }
        )
</code>```

Body:
Hey I am trying to write data into postgresql db from glue job but getting below error
IllegalArgumentException: Option 'dbtable' can not be empty.

Below is my code which seems to be correct

How I read from s3

glueContext.create_dynamic_frame.from_options(
            format_options={"multiline": False},
            connection_type="s3",
            format="json",
            connection_options={
                "paths": [s3path],
                "recurse": True,
            },
            transformation_ctx=S3_TO_CUSTOM_TRANSFORM,
        )

And then after some transformation I try to writeusing below code

glueContext.write_dynamic_frame.from_options(
            frame=df,
            connection_type="postgresql",
            connection_options={
                "url": "jdbc:postgresql://<host>:port/db",
                "user": "username",
                "password": "password",
                "dbtable": "table_name"
            }
        )


问:
Flutter: Create new Page or navigate when trying to scroll after the last page (overscroll) with PageView
I am trying to implement a feature so that the user can create a new Page when reaching the end of an PageView and trying to scroll further. There should be an indicator that shows that a new page will be created.

Here Is A GIF as an example of what I want to do:

My code :

```<code>final PageController _pageController = PageController();
final List<Widget> _pages = [
  Page1(),
  Page2(),
  Page3(),
];

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: PageView(
      controller: _pageController,
      children: _pages,
    ),
  );
}
</code>```

How could I do this? Can you give me tips?

Body:
I am trying to implement a feature so that the user can create a new Page when reaching the end of an PageView and trying to scroll further. There should be an indicator that shows that a new page will be created.

Here Is A GIF as an example of what I want to do:

My code :

final PageController _pageController = PageController();
final List<Widget> _pages = [
  Page1(),
  Page2(),
  Page3(),
];

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: PageView(
      controller: _pageController,
      children: _pages,
    ),
  );
}

How could I do this? Can you give me tips?


问:
ClientError: Unauthorized - Session does not match project host
Please help me out with this. I was trying to run npm run build but got this error instead.

If you want anything, please comment!

I was expecting a green check!


问:
Is there an actively maintained replacement for Bookshelf.js?
The most recent Bookshelf.js version is over two years old.

What is the recommended replacement?


问:
How to fix `trait cannot be made into a trait object` for Arc<dyn MyTrait> in HashSet?
I have the following code:

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
#[test]
fn test_hash() {
    trait LetMeHashed: Hash{}
    struct TraitTry{
        val: usize
    }
    impl Hash for TraitTry {
        fn hash<H: Hasher>(&self, state: &mut H) {
            self.val.hash(state);
        }
    }
    impl LetMeHashed for TraitTry{}
    let new = Box::new(TraitTry{val:1}) as Box<dyn LetMeHashed>;
    let mut new_hash = HashMap::new();
    new_hash.insert(new, 1);
    assert!(new_hash.contains(new.clone()))
}
```

I got the trait LetMeHashed cannot be made into an object error. Can I somehow implement a HashMap or HashSet while using Arc<dyn SomeTrait> as the key?

Body:
I have the following code:

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
#[test]
fn test_hash() {
    trait LetMeHashed: Hash{}
    struct TraitTry{
        val: usize
    }
    impl Hash for TraitTry {
        fn hash<H: Hasher>(&self, state: &mut H) {
            self.val.hash(state);
        }
    }
    impl LetMeHashed for TraitTry{}
    let new = Box::new(TraitTry{val:1}) as Box<dyn LetMeHashed>;
    let mut new_hash = HashMap::new();
    new_hash.insert(new, 1);
    assert!(new_hash.contains(new.clone()))
}

I got the trait LetMeHashed cannot be made into an object error. Can I somehow implement a HashMap or HashSet while using Arc<dyn SomeTrait> as the key?


Title: Weird query result when the fill clause is existed

Body:
When using the TDengine (v3.0.2), I found that the query result is some how weird when the fill clause exists in the time window query. And the following SQL statements can produce the result.

create table tu (ts timestamp, k int, z varchar(12));
insert into tu values('2022-6-1 1:1:1', 2,'b');
insert into tu values('2022-6-1 1:1:2', 3,'c');
insert into tu values('2022-6-1 1:1:3', 4,'d');

select _wstart, sum(k) from tu
where ts>='2022-06-01 1:1:0' and ts<='2022-6-1 1:1:3' interval(500a)
fill(prev) order by _wstart desc;

        _wstart         |        sum(k)         |
=================================================
2022-06-01 01:01:00.000 |                  NULL |
2022-06-01 01:01:00.500 |                  NULL |
2022-06-01 01:01:01.000 |                     2 |
2022-06-01 01:01:01.500 |                     2 |
2022-06-01 01:01:02.000 |                     3 |
2022-06-01 01:01:02.500 |                     3 |
2022-06-01 01:01:03.000 |                     4 |

select _wstart, sum(k) from tu
where ts>='2022-06-01 1:1:0' and ts<='2022-6-1 1:1:3' interval(500a)
fill(prev) order by _wstart asc;

         _wstart         |        sum(k)         |
==================================================
 2022-06-01 01:01:03.000 |                     4 |
 2022-06-01 01:01:02.500 |                     3 |
 2022-06-01 01:01:02.000 |                     3 |
 2022-06-01 01:01:01.500 |                     2 |
 2022-06-01 01:01:01.000 |                     2 |
 2022-06-01 01:01:00.500 |                     2 |
 2022-06-01 01:01:00.000 |                     2 |

I noticed that the order by clause affected the final results, not just the order of results, but also the result in ‘2022-06-01 01:01:00.000’ and ‘2022-06-01 01:01:00.500’.
But when the fill clause does not exist, the results are identical.

I’m wondering if is this a bug? or just a standard result of the fill clause.


问:
How can you make an array of text randomized and not repeat it self?
I am working on a project in Xcode where pre-written questions gets asked when pressing a button.

I want the questions to show in a randomized order, and that the order does not repeat already shown questions.
Can someone help me with this?

This is the code that I use:

```<code>struct Test: View {

    @State var Counter = 0

    var Words = ["Hello", "Goodbye", "See you later", "Thanks"]

    var body: some View {

    VStack {
        Text(Words[Counter])

        Button {
            self.Counter = Int.random(in: 0...4)
        } label: {
            Text("New word")
                .frame(width: 100, height: 50)
                .foregroundColor(.black)
                .background(.mint)
                .cornerRadius(10)
        }.padding(10)

    }

    }
}
</code>```

Body:
I am working on a project in Xcode where pre-written questions gets asked when pressing a button.

I want the questions to show in a randomized order, and that the order does not repeat already shown questions.
Can someone help me with this?

This is the code that I use:

struct Test: View {

    @State var Counter = 0

    var Words = ["Hello", "Goodbye", "See you later", "Thanks"]

    var body: some View {

    VStack {
        Text(Words[Counter])

        Button {
            self.Counter = Int.random(in: 0...4)
        } label: {
            Text("New word")
                .frame(width: 100, height: 50)
                .foregroundColor(.black)
                .background(.mint)
                .cornerRadius(10)
        }.padding(10)

    }

    }
}


问:
How can I add back the faint vertical line that shows the corresponding html
enter image description here
How can I get back the faint vertical line that shows the corresponding html tags?

enter image description here
Notice how the html, body, and head tags all have faint vertical lines?

I could not find any guide that solves this.


问:
Generate box shapes on click, if there is no empty space left disable button
I am trying to make a game where with a click of a button I generate random boxes. If there is no space left for another box, the button should be disabled.

CodeSandbox link: codesandbox.io/s/still-wind-w0dygo

Thanks!


问:
how can i make my pycharm identify odoo modules
hello I am using pycharm community for odoo development, but I have a problem when I created a module I tried this:

```<code>from odoo import fields, models, api
</code>```

but there is an error "cannot find references models api fields"

I have already added the addons path and my custom addons path to the conf file

```<code>addons_path=/home/abdo/odoo15/odoo/addons,/home/abdo/odoo15/odoo/custom_addons
</code>```

Body:
hello I am using pycharm community for odoo development, but I have a problem when I created a module I tried this:

from odoo import fields, models, api

but there is an error "cannot find references models api fields"

I have already added the addons path and my custom addons path to the conf file

addons_path=/home/abdo/odoo15/odoo/addons,/home/abdo/odoo15/odoo/custom_addons


问:
How to create content types that are not list in Sanity Studio?
I know how to create a content type in Sanity Studio for lists. For example, blog posts, customers, orders, payments, etc.

But now I want to use a Sanity project to provide content data for my home page.

On my home page, I have a Hero section, that is not a list.

It contains a title, a description, and a CTA that has text and a link.

How can I define the schema of this section, in my Sanity Studio?


问:
Is it possible to use testcontainer during KSP?
I want to use testcontainer during code generation. I have a project for 2 modules:

processor (with implementation of SymbolProcessorProvider and BuildProcessor)

workload

This is my build.gradle.kts in processor module

```<code>
plugins {
  kotlin("jvm")
}

group = "com.processor"
version = "1.0-SNAPSHOT"
val testcontainers = "1.17.6"

dependencies {
  implementation(kotlin("stdlib"))
  implementation("com.squareup:javapoet:1.12.1")
  implementation("com.google.devtools.ksp:symbol-processing-api:$kspVersion")
  implementation("org.testcontainers:testcontainers:$testcontainers")

}
</code>```

Unfortunately I get this error when I try to run any container:

```<code>Script file extensions:
[KOTLIN] Kotlin compilation 'jdkHome' argument: /Users/user/Library/Java/JavaVirtualMachines/adopt-openjdk-1.8.0_302/Contents/Home
i: found daemon on port 17051 (6824097 ms old), trying to connect
i: connected to the daemon
i: [ksp] loaded provider(s): [com.memodict.BuilderProcessorProvider]
e: [ksp] java.lang.IllegalStateException: Could not find a valid Docker environment. Please see logs and check configuration
</code>```

I'm wondering is it possible to use docker during KSP? In my workload module I can use docker in the test without any problem

Body:
I want to use testcontainer during code generation. I have a project for 2 modules:

processor (with implementation of SymbolProcessorProvider and BuildProcessor)

workload

This is my build.gradle.kts in processor module

plugins {
  kotlin("jvm")
}

group = "com.processor"
version = "1.0-SNAPSHOT"
val testcontainers = "1.17.6"

dependencies {
  implementation(kotlin("stdlib"))
  implementation("com.squareup:javapoet:1.12.1")
  implementation("com.google.devtools.ksp:symbol-processing-api:$kspVersion")
  implementation("org.testcontainers:testcontainers:$testcontainers")

}

Unfortunately I get this error when I try to run any container:

Script file extensions:
[KOTLIN] Kotlin compilation 'jdkHome' argument: /Users/user/Library/Java/JavaVirtualMachines/adopt-openjdk-1.8.0_302/Contents/Home
i: found daemon on port 17051 (6824097 ms old), trying to connect
i: connected to the daemon
i: [ksp] loaded provider(s): [com.memodict.BuilderProcessorProvider]
e: [ksp] java.lang.IllegalStateException: Could not find a valid Docker environment. Please see logs and check configuration

I'm wondering is it possible to use docker during KSP? In my workload module I can use docker in the test without any problem


问:
Problem with intent putExtra() passed item when querying Firestore
I am having some issues with the intent object. I already retrieved it with the new Activity but it doesn't work when passed to Firestore queries. The passed extra is the sellerId but surprisingly, if I use the auth Id of the current used using below code it works.

Though working, I actually don't need the my own auth id but the seller instead. There seems to be an issues with querying for me using extras as it is not recognized on both onCreate or onStart while doing a Firestore query.

Kindly enlighten me please and thanks in advance for anyone who can help solve this issue below.

All variables/dependencies below declared already here

```<code>     // This works
        firestore = FirebaseFirestore.getInstance();
            auth = FirebaseAuth.getInstance();
            user = auth.getCurrentUser();
            id= user.getCurrentId();

         firestore.collection("Users").document(id)
                    .addSnapshotListener(new EventListener<DocumentSnapshot>() {
                        @Override
                        public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable
            FirebaseFirestoreException error) {
                            if (error != null) {
                                Log.w(TAG, "Listen failed.", error);
                                return;
                            }

                            if (snapshot != null && snapshot.exists()) {

                                String name = snapshot.getString("name");
                                String id = snapshot.getString("id");
                                String email = snapshot.getString("email");
                                String description = snapshot.getString("description");

                            }
                        }
                    });

         // This doesn't work wether onCreate() or onStart()
         sellerDetail = getIntent().getStringExtra("seller");
         firestore.collection("Users").document(id)
                    .addSnapshotListener(new EventListener<DocumentSnapshot>() {
                        @Override
                        public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable
            FirebaseFirestoreException error) {
                            if (error != null) {
                                Log.w(TAG, "Listen failed.", error);
                                return;
                            }

                            if (snapshot != null && snapshot.exists()) {

                                String name = snapshot.getString("name");
                                String id = snapshot.getString("id");
                                String email = snapshot.getString("email");
                                String description = snapshot.getString("description");

                            }
                        }
                    });
</code>```

Body:
I am having some issues with the intent object. I already retrieved it with the new Activity but it doesn't work when passed to Firestore queries. The passed extra is the sellerId but surprisingly, if I use the auth Id of the current used using below code it works.

Though working, I actually don't need the my own auth id but the seller instead. There seems to be an issues with querying for me using extras as it is not recognized on both onCreate or onStart while doing a Firestore query.

Kindly enlighten me please and thanks in advance for anyone who can help solve this issue below.

All variables/dependencies below declared already here

     // This works
        firestore = FirebaseFirestore.getInstance();
            auth = FirebaseAuth.getInstance();
            user = auth.getCurrentUser();
            id= user.getCurrentId();

         firestore.collection("Users").document(id)
                    .addSnapshotListener(new EventListener<DocumentSnapshot>() {
                        @Override
                        public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable
            FirebaseFirestoreException error) {
                            if (error != null) {
                                Log.w(TAG, "Listen failed.", error);
                                return;
                            }

                            if (snapshot != null && snapshot.exists()) {

                                String name = snapshot.getString("name");
                                String id = snapshot.getString("id");
                                String email = snapshot.getString("email");
                                String description = snapshot.getString("description");

                            }
                        }
                    });

         // This doesn't work wether onCreate() or onStart()
         sellerDetail = getIntent().getStringExtra("seller");
         firestore.collection("Users").document(id)
                    .addSnapshotListener(new EventListener<DocumentSnapshot>() {
                        @Override
                        public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable
            FirebaseFirestoreException error) {
                            if (error != null) {
                                Log.w(TAG, "Listen failed.", error);
                                return;
                            }

                            if (snapshot != null && snapshot.exists()) {

                                String name = snapshot.getString("name");
                                String id = snapshot.getString("id");
                                String email = snapshot.getString("email");
                                String description = snapshot.getString("description");

                            }
                        }
                    });


问:
Getting Timeout while inserting in transaction using node-mssql package sqlserver

I recently started using mssql package in my Node-Express Application for accessing the DB.

I read through various documents, including the implementation and tutorial on how to establish and use a connection. Here are the few things that I am confused upon.

Clarification

Is it a good practice to keep a connection open across the application, i.e. I have my current implementation like this.

```<code>    global.sql = await mssql.connect(config, function (err) { /*LOGS*/});
</code>```

And wherever, I query, I query like

```<code>  function getItems(){
      await sql.query`select * from tbl where val in (${values})
   }
</code>```

Is it the right way of doing things, or should I do it like this?

```<code>  function getItems(){
      const sql = mssql.connect()
      await sql.query`select * from tbl where val in (${values})
   }
</code>```

Query:

I was going through the doc in the NPM readme.

There queries are done in 2 ways:

```<code>await sql.query`select * from mytable where id = ${value}`
</code>```

```<code> 2. ```
    await new sql.Request().query('select 1 as number')
```
<p>What is the difference between both, and which one has to be used when?</p>
<h3>Blocker:</h3>
<p>I am able to run a insert query by</p>
```   await sql.query`insert into tbl (val1, val2) values (${item}, ${userId})`
  // sql is the connection for the global variable as mentioned above
```
<p>I tried creating the above mentioned query in <code>Transaction</code>. For that I have used this</p>
```   transaction = new sql.Transaction()
   await transaction.begin();
   let request = new sql.Request(transaction);
   await request.query(/* insert into tbl .... */)
```

It was working fine, but after some time, when I retried, the query started giving timeout with error Timeout: Request failed to complete in 15000ms

Can't understand why this is happening?

I tried running the same query from the sql server management studio, and it was working as expected

Body:
I recently started using mssql package in my Node-Express Application for accessing the DB.

I read through various documents, including the implementation and tutorial on how to establish and use a connection. Here are the few things that I am confused upon.

Clarification

Is it a good practice to keep a connection open across the application, i.e. I have my current implementation like this.

    global.sql = await mssql.connect(config, function (err) { /*LOGS*/});

And wherever, I query, I query like

  function getItems(){
      await sql.query`select * from tbl where val in (${values})
   }

Is it the right way of doing things, or should I do it like this?

  function getItems(){
      const sql = mssql.connect()
      await sql.query`select * from tbl where val in (${values})
   }

Query:

I was going through the doc in the NPM readme.

There queries are done in 2 ways:

await sql.query`select * from mytable where id = ${value}`

 2. ```
    await new sql.Request().query('select 1 as number')

What is the difference between both, and which one has to be used when?

Blocker:

I am able to run a insert query by

   await sql.query`insert into tbl (val1, val2) values (${item}, ${userId})`
  // sql is the connection for the global variable as mentioned above

I tried creating the above mentioned query in Transaction. For that I have used this

   transaction = new sql.Transaction()
   await transaction.begin();
   let request = new sql.Request(transaction);
   await request.query(/* insert into tbl .... */)

It was working fine, but after some time, when I retried, the query started giving timeout with error Timeout: Request failed to complete in 15000ms

Can't understand why this is happening?

I tried running the same query from the sql server management studio, and it was working as expected


问:
pyautogui moves the courser but does not write in the function
The function P_10 is supposed randomly select a path from the dictionary Pic_10 and write it to pic_loc. Then the function py_auto is supposed to move the mouse cursor windows, explore the address bar, then write in the path to the folder.

It moves the cursor to the address bar but does not write anything.

Why is this code not working?

```<code>import pyautogui
import random
a = 287
b = 60
def py_auto():
    pyautogui.moveTo(a,b, duration = 1)
    pyautogui.click(a,b)
    pyautogui.write(pic_loc)

pic_loc =r""

Ovs_a_325 = r"D:\HOUSE PICS\10 marla\3F Ovs a ext @325"
OVB_8_425 = r"D:\HOUSE PICS\10 marla\8 overseas b @425"
ovb_40a_330 = r"D:\HOUSE PICS\10 marla"
tulip_47_350 =r"D:\HOUSE PICS\10 marla\47-c tulip @ 350"

Pic_10 = {
    1:Ovs_a_325,
    2:OVB_8_425,
    3:ovb_40a_330,
    4:tulip_47_350}
def P_10():
    global pic_loc
    pic_loc = random.choice(list(Pic_10.values()))
P_10()
py_auto()
</code>```

Body:
The function P_10 is supposed randomly select a path from the dictionary Pic_10 and write it to pic_loc. Then the function py_auto is supposed to move the mouse cursor windows, explore the address bar, then write in the path to the folder.

It moves the cursor to the address bar but does not write anything.

Why is this code not working?

import pyautogui
import random
a = 287
b = 60
def py_auto():
    pyautogui.moveTo(a,b, duration = 1)
    pyautogui.click(a,b)
    pyautogui.write(pic_loc)

pic_loc =r""

Ovs_a_325 = r"D:\HOUSE PICS\10 marla\3F Ovs a ext @325"
OVB_8_425 = r"D:\HOUSE PICS\10 marla\8 overseas b @425"
ovb_40a_330 = r"D:\HOUSE PICS\10 marla"
tulip_47_350 =r"D:\HOUSE PICS\10 marla\47-c tulip @ 350"

Pic_10 = {
    1:Ovs_a_325,
    2:OVB_8_425,
    3:ovb_40a_330,
    4:tulip_47_350}
def P_10():
    global pic_loc
    pic_loc = random.choice(list(Pic_10.values()))
P_10()
py_auto()


问:
my discord bot just repeats my first message
I'm configuring a bot to facilitate the company's service, in which we use colors to define priority. But the bot is only copying the first word, not the whole sentence. I've tried a few things, but it's easier to ask someone you already know for help.

down here is the red color code. Here is an example print

https://prnt.sc/hiMr2f7l5CYO

```<code>@client.command(name="v")
async def v (context, message):
        await context.message.channel.send("```diff\n-" + message + "\n```")
        await context.message.delete()
</code>```

I configured this line of code to copy the entire sentence, but it only repeats the first sentence. ❤

Body:
I'm configuring a bot to facilitate the company's service, in which we use colors to define priority. But the bot is only copying the first word, not the whole sentence. I've tried a few things, but it's easier to ask someone you already know for help.

down here is the red color code. Here is an example print

https://prnt.sc/hiMr2f7l5CYO

@client.command(name="v")
async def v (context, message):
        await context.message.channel.send("```diff\n-" + message + "\n```")
        await context.message.delete()

I configured this line of code to copy the entire sentence, but it only repeats the first sentence. ❤


问:
Error "Can only compare identically labeled Dataframe objects"
I am trying to compare two columns. But i keep getting the error below i have
changed the datatype of the columns as well but it doesn't help

```<code>col1 = \['AB12345C',WE23456K',CX23987L'\]

col2 = \['LK09876P',PO87654A',NM98765Z'\]

if col1 != col2:
print('okay')
else:
print('nothing')
</code>```

Error:Can only compare identically labeled data frame objects

Pandas "Can only compare identically-labeled DataFrame objects" error

Python Pandas Only Compare Identically Labeled DataFrame Objects

I have tried some solutions based on the above links as well but still getting the same answer.

Body:
I am trying to compare two columns. But i keep getting the error below i have
changed the datatype of the columns as well but it doesn't help

col1 = \['AB12345C',WE23456K',CX23987L'\]

col2 = \['LK09876P',PO87654A',NM98765Z'\]

if col1 != col2:
print('okay')
else:
print('nothing')

Error:Can only compare identically labeled data frame objects

Pandas "Can only compare identically-labeled DataFrame objects" error

Python Pandas Only Compare Identically Labeled DataFrame Objects

I have tried some solutions based on the above links as well but still getting the same answer.


问:
error when post file using urllib3 in python
I'm getting this error:
b'{"status":"error","message":"Upload failed."}'

I don't know why the file not getting uploaded. here is my code:

```<code>import urllib3

http = urllib3.PoolManager()
url = "https://tmpfiles.org/api/v1/upload"

dfile = open("image", "rb")
dfile=dfile.read()

response = http.request(
    "POST",
    url,
    fields={ "file": dfile }
)

print(response.data)

</code>```

I tried using requests, and it works fine, but I want to use urllib3 because it is faster

Body:
I'm getting this error:
b'{"status":"error","message":"Upload failed."}'

I don't know why the file not getting uploaded. here is my code:

import urllib3

http = urllib3.PoolManager()
url = "https://tmpfiles.org/api/v1/upload"

dfile = open("image", "rb")
dfile=dfile.read()

response = http.request(
    "POST",
    url,
    fields={ "file": dfile }
)

print(response.data)

I tried using requests, and it works fine, but I want to use urllib3 because it is faster


问:
Error in output either line or envelope shows up
I have used 2 code on Tradingview by LUXALGO

Nadaraya-Watson Estimator

Nadaraya-Watson Envelope

When the code is converted to ver 5.0 and compiled together, no compilation error is shown but the output only reflects either the Estimator Line or Estimator Envelope. Need both outputs together.

To replicate the problem, first select either the Estimator Checkbox or Envelope Checkbox, when both the Estimator and Envelope checkboxes are selected, we get only the envelope and the Estimator line disappears. Need help in resolving this issue.

The code is as below:

I have updated the variables inorder to not mix up while merging 2 scripts

```<code>// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo

//@version=5
indicator('Nadaraya-Watson Estimator & Envelope [LuxAlgo]', overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
grp_1 = "Estimator Settings"

show_est = input.bool(true, "Show Estimator", group = grp_1)
h_est = input(8.,'Bandwidth', group = grp_1)

src_est = input(close,'Source', group = grp_1)

disclaimer = input(false, 'Hide Disclaimer', group = grp_1)
//----
n_est = bar_index
var ln_est = array.new_line(0)
if barstate.isfirst
    for i = 0 to 499
        array.push(ln_est,line.new(na,na,na,na))
//----
float y2_est = na
float y1_est = na
float y1_d_est = na
//----
line l_est = na
label lb_est = na
if barstate.islast and show_est
    for i_est = 0 to math.min(499,n_est-1)
        sum_est = 0.
        sumw_est = 0.
        for j_est = 0 to math.min(499,n_est-1)
            w_est = math.exp(-(math.pow(i_est-j_est,2)/(h_est*h_est*2)))
            sum_est += src_est[j_est]*w_est
            sumw_est += w_est
        y2_est := sum_est/sumw_est
        d_est = y2_est - y1_est

        l_est := array.get(ln_est,i_est)
        line.set_xy1(l_est,n_est-i_est+1,y1_est)
        line.set_xy2(l_est,n_est-i_est,y2_est)
        line.set_color(l_est,y2_est > y1_est ? #ff1100 : #39ff14)
        line.set_width(l_est,2)

        if d_est > 0 and y1_d_est < 0
            label.new(n_est-i_est+1,src_est[i_est],'▲',color=#00000000,style=label.style_label_up,textcolor=#39ff14,textalign=text.align_center)
        if d_est < 0 and y1_d_est > 0
            label.new(n_est-i_est+1,src_est[i_est],'▼',color=#00000000,style=label.style_label_down,textcolor=#ff1100,textalign=text.align_center)

        y1_est := y2_est
        y1_d_est := d_est

//----
var tb_est = table.new(position.top_right, 1, 1
  , bgcolor = color.silver)

if barstate.isfirst and not disclaimer
    table.cell(tb_est, 0, 0, 'Nadaraya-Watson Estimator [LUX] Repaints'
      , text_size = size.small
      , text_color = #cc2f3c)

// // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// // © LuxAlgo
// //@version=5

// indicator("Nadaraya-Watson Envelope [LuxAlgo]",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
grp_2 = "Envelope Settings"
show_env    = input.bool(false, "Show Envelope")
length_env = input.float(500,'Window Size',maxval=500,minval=0, group = grp_2)
h_env      = input.float(8.,'Bandwidth', group = grp_2)
mult_env   = input.float(3., group = grp_2)
src_env    = input.source(close,'Source', group = grp_2)

up_col_env = input.color(#39ff14,'Colors',inline='col', group = grp_2)
dn_col_env = input.color(#ff1100,'',inline='col', group = grp_2)
// disclaimer = input(false, 'Hide Disclaimer')
//----
n_env = bar_index
var k_env = 2
var upper_env = array.new_line(0)
var lower_env = array.new_line(0)

lset(l,x1,y1,x2,y2,col)=>
    line.set_xy1(l,x1,y1)
    line.set_xy2(l,x2,y2)
    line.set_color(l,col)
    line.set_width(l,2)

if barstate.isfirst and show_env
    for i = 0 to length_env/k_env-1
        array.push(upper_env,line.new(na,na,na,na))
        array.push(lower_env,line.new(na,na,na,na))
//----
line up_env = na
line dn_env = na
//----
cross_up_env = 0.
cross_dn_env = 0.
if barstate.islast and show_env
    y_env = array.new_float(0)

    sum_e_env = 0.
    for i = 0 to length_env-1
        sum_env = 0.
        sumw_env = 0.

        for j = 0 to length_env-1
            w_env = math.exp(-(math.pow(i-j,2)/(h_env*h_env*2)))
            sum_env += src_env[j]*w_env
            sumw_env += w_env

        y2_env = sum_env/sumw_env
        sum_e_env += math.abs(src_env[i] - y2_env)
        array.push(y_env,y2_env)

    mae_env = sum_e_env/length_env*mult_env

    for i = 1 to length_env-1
        y2_env = array.get(y_env,i)
        y1_env = array.get(y_env,i-1)

        up_env := array.get(upper_env,i/k_env)
        dn_env := array.get(lower_env,i/k_env)

        lset(up_env,n_env-i+1,y1_env + mae_env,n_env-i,y2_env + mae_env,up_col_env)
        lset(dn_env,n_env-i+1,y1_env - mae_env,n_env-i,y2_env - mae_env,dn_col_env)

        if src_env[i] > y1_env + mae_env and src_env[i+1] < y1_env + mae_env
            label.new(n_env-i,src_env[i],'▼',color=#00000000,style=label.style_label_down,textcolor=dn_col_env,textalign=text.align_center)
        if src_env[i] < y1_env - mae_env and src_env[i+1] > y1_env - mae_env
            label.new(n_env-i,src_env[i],'▲',color=#00000000,style=label.style_label_up,textcolor=up_col_env,textalign=text.align_center)

    cross_up_env := array.get(y_env,0) + mae_env
    cross_dn_env := array.get(y_env,0) - mae_env

alertcondition(ta.crossover(src_env,cross_up_env),'Down','Down')
alertcondition(ta.crossunder(src_env,cross_dn_env),'Up','Up')

// //----
// var tb = table.new(position.top_right, 1, 1
//   , bgcolor = #35202b)

// if barstate.isfirst and not disclaimer
//     table.cell(tb, 0, 0, 'Nadaraya-Watson Envelope [LUX] Repaints'
//       , text_size = size.small
//       , text_color = #cc2f3c)
</code>```

Body:
I have used 2 code on Tradingview by LUXALGO

Nadaraya-Watson Estimator

Nadaraya-Watson Envelope

When the code is converted to ver 5.0 and compiled together, no compilation error is shown but the output only reflects either the Estimator Line or Estimator Envelope. Need both outputs together.

To replicate the problem, first select either the Estimator Checkbox or Envelope Checkbox, when both the Estimator and Envelope checkboxes are selected, we get only the envelope and the Estimator line disappears. Need help in resolving this issue.

The code is as below:

I have updated the variables inorder to not mix up while merging 2 scripts

// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo

//@version=5
indicator('Nadaraya-Watson Estimator & Envelope [LuxAlgo]', overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
grp_1 = "Estimator Settings"

show_est = input.bool(true, "Show Estimator", group = grp_1)
h_est = input(8.,'Bandwidth', group = grp_1)

src_est = input(close,'Source', group = grp_1)

disclaimer = input(false, 'Hide Disclaimer', group = grp_1)
//----
n_est = bar_index
var ln_est = array.new_line(0)
if barstate.isfirst
    for i = 0 to 499
        array.push(ln_est,line.new(na,na,na,na))
//----
float y2_est = na
float y1_est = na
float y1_d_est = na
//----
line l_est = na
label lb_est = na
if barstate.islast and show_est
    for i_est = 0 to math.min(499,n_est-1)
        sum_est = 0.
        sumw_est = 0.
        for j_est = 0 to math.min(499,n_est-1)
            w_est = math.exp(-(math.pow(i_est-j_est,2)/(h_est*h_est*2)))
            sum_est += src_est[j_est]*w_est
            sumw_est += w_est
        y2_est := sum_est/sumw_est
        d_est = y2_est - y1_est

        l_est := array.get(ln_est,i_est)
        line.set_xy1(l_est,n_est-i_est+1,y1_est)
        line.set_xy2(l_est,n_est-i_est,y2_est)
        line.set_color(l_est,y2_est > y1_est ? #ff1100 : #39ff14)
        line.set_width(l_est,2)

        if d_est > 0 and y1_d_est < 0
            label.new(n_est-i_est+1,src_est[i_est],'▲',color=#00000000,style=label.style_label_up,textcolor=#39ff14,textalign=text.align_center)
        if d_est < 0 and y1_d_est > 0
            label.new(n_est-i_est+1,src_est[i_est],'▼',color=#00000000,style=label.style_label_down,textcolor=#ff1100,textalign=text.align_center)

        y1_est := y2_est
        y1_d_est := d_est

//----
var tb_est = table.new(position.top_right, 1, 1
  , bgcolor = color.silver)

if barstate.isfirst and not disclaimer
    table.cell(tb_est, 0, 0, 'Nadaraya-Watson Estimator [LUX] Repaints'
      , text_size = size.small
      , text_color = #cc2f3c)

// // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// // © LuxAlgo
// //@version=5

// indicator("Nadaraya-Watson Envelope [LuxAlgo]",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
grp_2 = "Envelope Settings"
show_env    = input.bool(false, "Show Envelope")
length_env = input.float(500,'Window Size',maxval=500,minval=0, group = grp_2)
h_env      = input.float(8.,'Bandwidth', group = grp_2)
mult_env   = input.float(3., group = grp_2)
src_env    = input.source(close,'Source', group = grp_2)

up_col_env = input.color(#39ff14,'Colors',inline='col', group = grp_2)
dn_col_env = input.color(#ff1100,'',inline='col', group = grp_2)
// disclaimer = input(false, 'Hide Disclaimer')
//----
n_env = bar_index
var k_env = 2
var upper_env = array.new_line(0)
var lower_env = array.new_line(0)

lset(l,x1,y1,x2,y2,col)=>
    line.set_xy1(l,x1,y1)
    line.set_xy2(l,x2,y2)
    line.set_color(l,col)
    line.set_width(l,2)

if barstate.isfirst and show_env
    for i = 0 to length_env/k_env-1
        array.push(upper_env,line.new(na,na,na,na))
        array.push(lower_env,line.new(na,na,na,na))
//----
line up_env = na
line dn_env = na
//----
cross_up_env = 0.
cross_dn_env = 0.
if barstate.islast and show_env
    y_env = array.new_float(0)

    sum_e_env = 0.
    for i = 0 to length_env-1
        sum_env = 0.
        sumw_env = 0.

        for j = 0 to length_env-1
            w_env = math.exp(-(math.pow(i-j,2)/(h_env*h_env*2)))
            sum_env += src_env[j]*w_env
            sumw_env += w_env

        y2_env = sum_env/sumw_env
        sum_e_env += math.abs(src_env[i] - y2_env)
        array.push(y_env,y2_env)

    mae_env = sum_e_env/length_env*mult_env

    for i = 1 to length_env-1
        y2_env = array.get(y_env,i)
        y1_env = array.get(y_env,i-1)

        up_env := array.get(upper_env,i/k_env)
        dn_env := array.get(lower_env,i/k_env)

        lset(up_env,n_env-i+1,y1_env + mae_env,n_env-i,y2_env + mae_env,up_col_env)
        lset(dn_env,n_env-i+1,y1_env - mae_env,n_env-i,y2_env - mae_env,dn_col_env)

        if src_env[i] > y1_env + mae_env and src_env[i+1] < y1_env + mae_env
            label.new(n_env-i,src_env[i],'▼',color=#00000000,style=label.style_label_down,textcolor=dn_col_env,textalign=text.align_center)
        if src_env[i] < y1_env - mae_env and src_env[i+1] > y1_env - mae_env
            label.new(n_env-i,src_env[i],'▲',color=#00000000,style=label.style_label_up,textcolor=up_col_env,textalign=text.align_center)

    cross_up_env := array.get(y_env,0) + mae_env
    cross_dn_env := array.get(y_env,0) - mae_env

alertcondition(ta.crossover(src_env,cross_up_env),'Down','Down')
alertcondition(ta.crossunder(src_env,cross_dn_env),'Up','Up')

// //----
// var tb = table.new(position.top_right, 1, 1
//   , bgcolor = #35202b)

// if barstate.isfirst and not disclaimer
//     table.cell(tb, 0, 0, 'Nadaraya-Watson Envelope [LUX] Repaints'
//       , text_size = size.small
//       , text_color = #cc2f3c)


问:
Error working with COM object from Python throw clr reference - class not registred
Trying to make an App for Solidworks.
First tried to use win32com or comtypes to get access to the COM object of solidworks.
Made some progress, but couldnt get it working well.
Found a way to work with clr and interop dlls.
More progress, but now got stuck on this error:

```<code>System.Runtime.InteropServices.COMException:  (0x80040154): Retrieving the COM class factory for component with CLSID {27526253-6119-4B38-A1F9-2DC877E72334} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
   at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)
   at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)
   at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Python.Runtime.ConstructorBinder.InvokeRaw(BorrowedReference inst, BorrowedReference args, BorrowedReference kw, MethodBase info)
</code>```

my code is:

```<code>>>> import clr
>>> clr.AddReference("C:\Program Files\SOLIDWORKS 2019\SOLIDWORKS\SolidWorks.Interop.sldworks.dll")
<System.Reflection.RuntimeAssembly object at 0x000001D80F877040>
>>> clr.AddReference("C:\Program Files\SOLIDWORKS 2019\SOLIDWORKS\SolidWorks.Interop.swconst.dll")
<System.Reflection.RuntimeAssembly object at 0x000001D80F877080>
>>> from SolidWorks.Interop.sldworks import *
>>> from SolidWorks.Interop.swconst import *
>>> swApp = ISldWorks(SldWorksClass())
>>> swApp.Visible=True
>>> modl = IModelDoc2(ModelDoc2Class())
</code>```

Solidworks loads well, can work with it, but got no access to ModelDoc2 object.
All they are in registry (SdlWorksClass, ISldModelDoc2, ModelDoc2Class, IModelDoc2):
Their interfaces are both in registry. TypeLib is registred too.

from registry CLSID:

```<code>assembly: SolidWorks.Interop.sldworks, Version=27.5.0.72, Culture=neutral, PublicKeyToken=7c4797c3e4eeac0
class: SolidWorks.Interop.sldworks.ModelDoc2Class
</code>```

I can see ModelDoc2 object methods: dir(ModelDoc2)

As far as I dig the class is registered (cannot test otherwise, any suggestions?)
COMview tool shows me the typelib as CLSID. Tested on two SW versions: 2019 and 2020.

Stuck and cannot continue.
Please advice.
Thanks

Body:
Trying to make an App for Solidworks.
First tried to use win32com or comtypes to get access to the COM object of solidworks.
Made some progress, but couldnt get it working well.
Found a way to work with clr and interop dlls.
More progress, but now got stuck on this error:

System.Runtime.InteropServices.COMException:  (0x80040154): Retrieving the COM class factory for component with CLSID {27526253-6119-4B38-A1F9-2DC877E72334} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
   at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)
   at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)
   at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Python.Runtime.ConstructorBinder.InvokeRaw(BorrowedReference inst, BorrowedReference args, BorrowedReference kw, MethodBase info)

my code is:

>>> import clr
>>> clr.AddReference("C:\Program Files\SOLIDWORKS 2019\SOLIDWORKS\SolidWorks.Interop.sldworks.dll")
<System.Reflection.RuntimeAssembly object at 0x000001D80F877040>
>>> clr.AddReference("C:\Program Files\SOLIDWORKS 2019\SOLIDWORKS\SolidWorks.Interop.swconst.dll")
<System.Reflection.RuntimeAssembly object at 0x000001D80F877080>
>>> from SolidWorks.Interop.sldworks import *
>>> from SolidWorks.Interop.swconst import *
>>> swApp = ISldWorks(SldWorksClass())
>>> swApp.Visible=True
>>> modl = IModelDoc2(ModelDoc2Class())

Solidworks loads well, can work with it, but got no access to ModelDoc2 object.
All they are in registry (SdlWorksClass, ISldModelDoc2, ModelDoc2Class, IModelDoc2):
Their interfaces are both in registry. TypeLib is registred too.

from registry CLSID:

assembly: SolidWorks.Interop.sldworks, Version=27.5.0.72, Culture=neutral, PublicKeyToken=7c4797c3e4eeac0
class: SolidWorks.Interop.sldworks.ModelDoc2Class

I can see ModelDoc2 object methods: dir(ModelDoc2)

As far as I dig the class is registered (cannot test otherwise, any suggestions?)
COMview tool shows me the typelib as CLSID. Tested on two SW versions: 2019 and 2020.

Stuck and cannot continue.
Please advice.
Thanks


问:
Is accuracy, precision and recall measured for negative cases as well?
Most examples I have seen about accuracy, precision and recall use positive values. Eg.

Accuracy: The ratio of correct predictions (true positives + true
negatives) to the total number of predictions.

Precision: The fraction of the cases classified as positive that are actually positive (the number of true positives divided by the
number of true positives plus false positives).

Recall: The fraction of positive cases correctly identified (the number of true positives divided by the number of true positives plus
false negatives).

Is it better to measure these metrics for both positive and negative values?

Eg

Consider these two scenarios

If only positive cases are used in measures then

Accuracy - Model is 80% accurate for scenario 1 and 99.9% accurate for scenario 2
Precision - If models predicts that something is positive, it would be 75% correct in scenario 1 and 99.9% correct in scenario 2
Recall - Model would identify 90% of positive cases in scenario 1 and 100% of positive cases in scenario 2. So low recall?

However, the model for scenario 2 doesn't work as it fails 100% of times for negative cases.

In practice, is it better to measure the metrics for both positive and negative cases?


问:
I want to keep AddTransactionFragment while I navigate to other fragment with BottomNavigation (Android, Kotlin)
My problem is illustrated by this screen record.

When I click the FAB on FinanceFragment, it will open AddTransactionFragment. But when I navigate to ReminderFragment and go back to FinanceFragment, the AddTransactionFragment is destroyed.

How could I -- similar to the YouTube app when one switches between fragments -- keep AddTransactionFragment visible while I navigate to another fragment?

I tried to add addToBackStack() but this turned out not to be what I was looking for.


问:
Deploy ERC20Upgradeable without Proxy for governable upgrades
I've created an UUPS upgrade able token (minified for the example)

```<code>contract GovernanceToken is Initializable, ERC20Upgradeable, ERC20PermitUpgradeable, ERC20VotesUpgradeable, OwnableUpgradeable, UUPSUpgradeable {
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize() initializer public {
        __ERC20_init("GovernanceToken", "GT");
        __ERC20Permit_init("GovernanceToken");
        __ERC20Votes_init();
        __Ownable_init();
        __UUPSUpgradeable_init();
    }

    //...
}
</code>```

My deploy script looks like this:

```<code>const deployGovernanceToken: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
  // @ts-ignore
  const { getNamedAccounts, deployments, network } = hre
  const { deploy, save, log, get } = deployments
  const { deployer } = await getNamedAccounts()

  const governanceTokenContractFactory = await ethers.getContractFactory(GOVERNANCE_TOKEN_NAME);

  const deployedProxy = await upgrades.deployProxy(governanceTokenContractFactory, [], {
    initializer: "initialize",
    kind: "uups",
  });

  await deployedProxy.deployed();

  const governanceToken = await governanceTokenContractFactory.attach(
      deployedProxy.address
  );

  const timeLock = await get(TIMELOCK_CONTROLLER_NAME)
  const governanceTokenContract = await ethers.getContractAt(GOVERNANCE_TOKEN_NAME, governanceToken.address)

  const transferTx = await governanceTokenContract.transferOwnership(timeLock.address)
  await transferTx.wait(1)
}
</code>```

I would like to upgrade my token, however it's owned by the timelock so I cannot upgrade it from hardhat, so I'd like to deploy another version of the token so I can upgrade it though governance.

This is my upgrade script:

```<code>const { getNamedAccounts, deployments, network } = hre
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const timelockAddress = '0x...'

const governanceTokenV2 = await ethers.getContractFactory(GOVERNANCE_TOKEN_NAME);
const governanceTokenContract = await governanceTokenV2.deploy();

log(`Upgraded Token at ${governanceTokenContract.address}`)

const owner = await governanceTokenContract.owner();
log(`Verified Token at ${governanceTokenContract.address}`)
log(`owner: ${owner}`)
</code>```

When I run this I get an error:

Deploying governanceToken and waiting for confirmations...
Upgraded Token at 0x5Fb...
owner: 0x0000000000000000000000000000000000000000

Error HH604: Error running JSON-RPC server: ERROR processing C:..\deploy\00-deploy-upgraded-Token.ts:
Error: VM Exception while processing transaction: reverted with reason string 'Ownable: caller is not the owner'

The token I'm deploying claims the owner is the ZERO_ADDRESS, perhaps this is because the storage is usually associated with the proxy?

How can I deploy this token and transfer ownership to the proxy?

Note: I've tried calling the initialize method, and it claims it's already been initialized

Body:
I've created an UUPS upgrade able token (minified for the example)

contract GovernanceToken is Initializable, ERC20Upgradeable, ERC20PermitUpgradeable, ERC20VotesUpgradeable, OwnableUpgradeable, UUPSUpgradeable {
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize() initializer public {
        __ERC20_init("GovernanceToken", "GT");
        __ERC20Permit_init("GovernanceToken");
        __ERC20Votes_init();
        __Ownable_init();
        __UUPSUpgradeable_init();
    }

    //...
}

My deploy script looks like this:

const deployGovernanceToken: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
  // @ts-ignore
  const { getNamedAccounts, deployments, network } = hre
  const { deploy, save, log, get } = deployments
  const { deployer } = await getNamedAccounts()

  const governanceTokenContractFactory = await ethers.getContractFactory(GOVERNANCE_TOKEN_NAME);

  const deployedProxy = await upgrades.deployProxy(governanceTokenContractFactory, [], {
    initializer: "initialize",
    kind: "uups",
  });

  await deployedProxy.deployed();

  const governanceToken = await governanceTokenContractFactory.attach(
      deployedProxy.address
  );

  const timeLock = await get(TIMELOCK_CONTROLLER_NAME)
  const governanceTokenContract = await ethers.getContractAt(GOVERNANCE_TOKEN_NAME, governanceToken.address)

  const transferTx = await governanceTokenContract.transferOwnership(timeLock.address)
  await transferTx.wait(1)
}

I would like to upgrade my token, however it's owned by the timelock so I cannot upgrade it from hardhat, so I'd like to deploy another version of the token so I can upgrade it though governance.

This is my upgrade script:

const { getNamedAccounts, deployments, network } = hre
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const timelockAddress = '0x...'

const governanceTokenV2 = await ethers.getContractFactory(GOVERNANCE_TOKEN_NAME);
const governanceTokenContract = await governanceTokenV2.deploy();

log(`Upgraded Token at ${governanceTokenContract.address}`)

const owner = await governanceTokenContract.owner();
log(`Verified Token at ${governanceTokenContract.address}`)
log(`owner: ${owner}`)

When I run this I get an error:

Deploying governanceToken and waiting for confirmations...
Upgraded Token at 0x5Fb...
owner: 0x0000000000000000000000000000000000000000

Error HH604: Error running JSON-RPC server: ERROR processing C:..\deploy\00-deploy-upgraded-Token.ts:
Error: VM Exception while processing transaction: reverted with reason string 'Ownable: caller is not the owner'

The token I'm deploying claims the owner is the ZERO_ADDRESS, perhaps this is because the storage is usually associated with the proxy?

How can I deploy this token and transfer ownership to the proxy?

Note: I've tried calling the initialize method, and it claims it's already been initialized


问:
Chrome: CSS formatting for print: Prevent scaling
I am using the following CSS settings for printing :

```<code>@page {
           size: portrait !important;
           margin: 5mm 0mm 0mm 5mm !important;
        }
</code>```

This works great in Firefox browser. If the users should find that the margin settings don't work for their printers, they can still be customized.
Chrome on the other hand ignores custom margin settings when margins are set in CSS. Is there a way to enable customizability?

EDIT: I got it's workig now, but I'm not sure why. It may have been a problem with indentation and a bug in Chrome's print preview.

Also, I found that Chrome handles the contents (an SVG that needs to be printed at an accurate size) differently from Firefox when they are larger than the printable area on the page: Chrome scales down the image, while Firefox cuts it off. How can I prevent Chrome from scaling?

I've searched for CSS properties to set these things, but I haven't been able to find the correct ones.

Body:
I am using the following CSS settings for printing :

@page {
           size: portrait !important;
           margin: 5mm 0mm 0mm 5mm !important;
        }

This works great in Firefox browser. If the users should find that the margin settings don't work for their printers, they can still be customized.
Chrome on the other hand ignores custom margin settings when margins are set in CSS. Is there a way to enable customizability?

EDIT: I got it's workig now, but I'm not sure why. It may have been a problem with indentation and a bug in Chrome's print preview.

Also, I found that Chrome handles the contents (an SVG that needs to be printed at an accurate size) differently from Firefox when they are larger than the printable area on the page: Chrome scales down the image, while Firefox cuts it off. How can I prevent Chrome from scaling?

I've searched for CSS properties to set these things, but I haven't been able to find the correct ones.


问:
HTML Javascript execute arrow function given its name
Given a name (as a string) of a function in the global namespace, the function can be invoked easily. How can the same be achieved for an arrow function?

For instance, how can bar() be invoked without using eval()?

function foo(){ console.log("foo"); }
const bar = () => console.log("bar");

window["foo"]();
window["bar"]();  // TypeError: window.bar is not a function```


问:
Video does not play although the play() promise is fulfilled - React JS
I have a problem when clone the scroll-to-view feature of tiktok. When I reload the page, the first video does not play in spite of being on viewport. I have logged the promise return by play() method, and it says resolved. Here is my code:
`

```<code> // play video in viewport (pause when out)
    const inViewport = useIntersection(videoRef, '-240px');
    useEffect(() => {
        if (inViewport) {
            setPlaying(true);
        } else {
            setPlaying(false);
        }
    }, [inViewport]);

</code>```
```<code>useEffect(() => {
        const playPromise = videoRef.current.play();
        if (!playing) {
            if (playPromise !== undefined) {
                playPromise.then(() => videoRef.current.pause());
            }
        }

    }, [playing]);
</code>```

`
I check the return value of promise when pausing video to avoid this warning: Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

On the other hand, when I code like following, it works correctly (means that the first video auto play because of being on view):

```<code>
useEffect(() => {
        if (playing) {
            videoRef.current.play();
        } else {
            videoRef.current.pause();
        }
    }, [playing]);

</code>```

Certainly, the above code block will cause: Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

What is happening? And how to fix it? Or any others ways to fix the warning? Thanks in advance.

Body:
I have a problem when clone the scroll-to-view feature of tiktok. When I reload the page, the first video does not play in spite of being on viewport. I have logged the promise return by play() method, and it says resolved. Here is my code:
`

 // play video in viewport (pause when out)
    const inViewport = useIntersection(videoRef, '-240px');
    useEffect(() => {
        if (inViewport) {
            setPlaying(true);
        } else {
            setPlaying(false);
        }
    }, [inViewport]);

useEffect(() => {
        const playPromise = videoRef.current.play();
        if (!playing) {
            if (playPromise !== undefined) {
                playPromise.then(() => videoRef.current.pause());
            }
        }

    }, [playing]);

`
I check the return value of promise when pausing video to avoid this warning: Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

On the other hand, when I code like following, it works correctly (means that the first video auto play because of being on view):

useEffect(() => {
        if (playing) {
            videoRef.current.play();
        } else {
            videoRef.current.pause();
        }
    }, [playing]);

Certainly, the above code block will cause: Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

What is happening? And how to fix it? Or any others ways to fix the warning? Thanks in advance.


问:
Which filters should i use to edge dedection a picture?
I'm trying to use filters, image processing to get edges of an object by using Python. My image and targeted images are here: Original image here Targeted image here

Since colors are close to each other i'm having hard time to sepereate dolphins from background.

I've tried some filters such as median filter and tried some morhpological operators.


问:
My Flutter app UI is not rebuilding when i request new data from firebase
I have a dropdown button consisting of names of the days of a week. When i click on any day from the dropdown then the data corresponding to that day is fetched without any problem. But when i try to change the option like if i select monday first the data is shown then i again click the dropdown and select another day the data corresponding to it is not fetched. How to fix it?.

Here is my code

class messDiary extends StatefulWidget {
  messDiary({Key? key}) : super(key: key) {}

  @override
  State<messDiary> createState() => _messDiaryState();
}

class _messDiaryState extends State<messDiary> {
  String valueChoose = 'Select a day';

  final DocumentReference _collectListData =
      FirebaseFirestore.instance.collection('messdiary').doc('days');

  late Stream<DocumentSnapshot> _streamCollectList;
  @override
  void initState() {
    super.initState();
    whatIsToday = DateFormat('EEEE').format(DateTime.now());
    _streamCollectList = _collectListData.snapshots();
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
  child: AwesomeDropDown(
                dropDownList: const [
                  "Monday",
                  "Tuesday",
                  "Wednesday",
                  "Thursday",
                  "Friday",
                  "Saturday",
                  "Sunday"
                ],
                selectedItem: valueChoose,
                onDropDownItemClick: (selectedItem) {
                  setState(() {
                    valueChoose = selectedItem;
                  });
                },
                selectedItemTextStyle: const TextStyle(
                    color: Colors.white, fontWeight: FontWeight.bold),
                dropDownListTextStyle: const TextStyle(color: Colors.black),
                dropDownIcon: const Icon(
                  Icons.expand_circle_down,
                  color: Color(0xFF4A4C5C),
                ),
                dropDownBGColor: const Color(0xFF292A35),
              ),
              const SizedBox(
                height: 10,
              ),
              valueChoose == "Select a day"
                  ? const SizedBox()
                  : Container(
                      width: width * .95,
                      height: height * 0.4,
                      decoration: const BoxDecoration(
                          color: Color(0xFF292A35),
                          borderRadius: BorderRadius.all(Radius.circular(15))),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: StreamBuilder<DocumentSnapshot>(
                            stream: _streamCollectList,
                            builder: (context,
                                AsyncSnapshot<DocumentSnapshot> snapshot) {
                              if (!snapshot.hasData) {
                                return const Center(
                                  child: CircularProgressIndicator(),
                                );
                              }
                              var otherSnaps = snapshot.data!;
                              return ListView.separated(
                                physics: const NeverScrollableScrollPhysics(),
                                itemBuilder: (context, index) {
                                  var allDayMeals = otherSnaps[valueChoose]
                                      .map(
                                        (e) => ThisDaysItems(
                                          dayTime: e['daytime'],
                                          meal: e['title'],
                                        ),
                                      )
                                      .toList();
                                  final List<ThisDaysItems> mealsData = [
                                    ...allDayMeals
                                  ];
                                  final itemName = mealsData[index];
                                  return MealDayList(
                                      daytime: itemName.dayTime,
                                      meal: itemName.meal);
                                },
                                itemCount: 4,
                                separatorBuilder:
                                    (BuildContext context, int index) {
                                  return const Divider(
                                    color: Colors.white12,
                                  );
                                },
                              );
                            }),
   );
   }
   }```

This is my app list image(s)

Initial stage when nothing is selected

sample screen of my apps list

2.when i select monday for first time

monday selected

when tuesday selected nothing  is changing same list

tuesday is selected

Body:
I have a dropdown button consisting of names of the days of a week. When i click on any day from the dropdown then the data corresponding to that day is fetched without any problem. But when i try to change the option like if i select monday first the data is shown then i again click the dropdown and select another day the data corresponding to it is not fetched. How to fix it?.

Here is my code

class messDiary extends StatefulWidget {
  messDiary({Key? key}) : super(key: key) {}

  @override
  State<messDiary> createState() => _messDiaryState();
}

class _messDiaryState extends State<messDiary> {
  String valueChoose = 'Select a day';

  final DocumentReference _collectListData =
      FirebaseFirestore.instance.collection('messdiary').doc('days');

  late Stream<DocumentSnapshot> _streamCollectList;
  @override
  void initState() {
    super.initState();
    whatIsToday = DateFormat('EEEE').format(DateTime.now());
    _streamCollectList = _collectListData.snapshots();
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
  child: AwesomeDropDown(
                dropDownList: const [
                  "Monday",
                  "Tuesday",
                  "Wednesday",
                  "Thursday",
                  "Friday",
                  "Saturday",
                  "Sunday"
                ],
                selectedItem: valueChoose,
                onDropDownItemClick: (selectedItem) {
                  setState(() {
                    valueChoose = selectedItem;
                  });
                },
                selectedItemTextStyle: const TextStyle(
                    color: Colors.white, fontWeight: FontWeight.bold),
                dropDownListTextStyle: const TextStyle(color: Colors.black),
                dropDownIcon: const Icon(
                  Icons.expand_circle_down,
                  color: Color(0xFF4A4C5C),
                ),
                dropDownBGColor: const Color(0xFF292A35),
              ),
              const SizedBox(
                height: 10,
              ),
              valueChoose == "Select a day"
                  ? const SizedBox()
                  : Container(
                      width: width * .95,
                      height: height * 0.4,
                      decoration: const BoxDecoration(
                          color: Color(0xFF292A35),
                          borderRadius: BorderRadius.all(Radius.circular(15))),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: StreamBuilder<DocumentSnapshot>(
                            stream: _streamCollectList,
                            builder: (context,
                                AsyncSnapshot<DocumentSnapshot> snapshot) {
                              if (!snapshot.hasData) {
                                return const Center(
                                  child: CircularProgressIndicator(),
                                );
                              }
                              var otherSnaps = snapshot.data!;
                              return ListView.separated(
                                physics: const NeverScrollableScrollPhysics(),
                                itemBuilder: (context, index) {
                                  var allDayMeals = otherSnaps[valueChoose]
                                      .map(
                                        (e) => ThisDaysItems(
                                          dayTime: e['daytime'],
                                          meal: e['title'],
                                        ),
                                      )
                                      .toList();
                                  final List<ThisDaysItems> mealsData = [
                                    ...allDayMeals
                                  ];
                                  final itemName = mealsData[index];
                                  return MealDayList(
                                      daytime: itemName.dayTime,
                                      meal: itemName.meal);
                                },
                                itemCount: 4,
                                separatorBuilder:
                                    (BuildContext context, int index) {
                                  return const Divider(
                                    color: Colors.white12,
                                  );
                                },
                              );
                            }),
   );
   }
   }

This is my app list image(s)

Initial stage when nothing is selected

sample screen of my apps list

2.when i select monday for first time

monday selected

when tuesday selected nothing  is changing same list

tuesday is selected


问:
Where JDBC resultSet is stored?
I need to process millions of records. I am using JDBC (with Oracle driver) with fetchSize to get the records in batches from DB.
As per Oracle documentation, the select query is executed only once and round trips to DB is made based on fetch size set. So I understand that all the rows are not completed loaded into application server. This make sense and I am not worried about memory usage from application side.
But what I want to understand is how does Oracle stores the rows in resultSet in Oracle DB Server if it is executing the select query only once -

does it creates a temp table and stores the resultSet?

does it uses some mechanism which does not utilises any extra memory at DB server side?

```<code> val conn: Connection = datasource.connection
 var stmt: PreparedStatement? = null
 var resultSet: ResultSet? = null
 try {
     stmt = conn.prepareStatement("select query")
     stmt.fetchSize = 1000
     resultSet = stmt.executeQuery()
     // does above line load all the rows of resultSet in a
     // temp memory in DB or uses actual memory where actual
     // data is stored in Oracle DB ?
     while (resultSet.next()) {
         // do some operation
        }
     }
 finally {
     // close resultSet, statement, connection
 }
</code>```

I want to understand this from Oracle server side and not from application side. My logic goes to Oracle storing the resultSet data somewhere internally but I don't find any official documentation to support it. My application design will depend on how this actually behaves.

Title: Where JDBC resultSet is stored?

Body:
I need to process millions of records. I am using JDBC (with Oracle driver) with fetchSize to get the records in batches from DB.
As per Oracle documentation, the select query is executed only once and round trips to DB is made based on fetch size set. So I understand that all the rows are not completed loaded into application server. This make sense and I am not worried about memory usage from application side.
But what I want to understand is how does Oracle stores the rows in resultSet in Oracle DB Server if it is executing the select query only once -

does it creates a temp table and stores the resultSet?

does it uses some mechanism which does not utilises any extra memory at DB server side?

 val conn: Connection = datasource.connection
 var stmt: PreparedStatement? = null
 var resultSet: ResultSet? = null
 try {
     stmt = conn.prepareStatement("select query")
     stmt.fetchSize = 1000
     resultSet = stmt.executeQuery()
     // does above line load all the rows of resultSet in a
     // temp memory in DB or uses actual memory where actual
     // data is stored in Oracle DB ?
     while (resultSet.next()) {
         // do some operation
        }
     }
 finally {
     // close resultSet, statement, connection
 }

I want to understand this from Oracle server side and not from application side. My logic goes to Oracle storing the resultSet data somewhere internally but I don't find any official documentation to support it. My application design will depend on how this actually behaves.


问:
How to terminate the program after IsStopped()?
I don't understand what you are suppposed to do when IsStopped() is true

How does one "terminate the program"?

All I can think of is ExpertRemove() but that is unsatisfactory as it will wipe out your ExpertAdvisor from the chart completely, including your settings for it.

Below is from the MQL5 Reference (Help)

IsStopped

Checks the forced shutdown of an mql5 program.

bool  IsStopped();

Return Value
Returns true, if the _StopFlag system variable contains a value other than 0. A nonzero value is written into _StopFlag, if a mql5 program has been commanded to complete its operation. In this case, you must immediately terminate the program, otherwise the program will be completed forcibly from the outside after 3 seconds.


问:
Pycharm venv with the latest pip version
I am trying to figure out how to create new PyCharm projects with the latest pip version.

I am setting my Python Interpreter to venv python3.9 and when I install a package with pip I always get a warning that new pip version is availible

Is there a way to upgrade pip version for all new PyCharm projects?

I have tried looking at which python I am using as a base interpreter and updating pip there

/usr/bin/python3 -m pip install --upgrade pip
and
/Library/Developer/CommandLineTools/usr/bin/python3 -m pip install --upgrade pip

but when i create a new PyCharm project I still get a warning to update pip


问:
MongoDB: Populate reference in $group when aggregating?
I have a only first user witch

```<code>  await Reply.populate(replies, { path: "user" });
</code>```

. My aggregation pipeline is as such:

https://mongoplayground.net/p/tHh1se1IFGa

This is original i take it https://mongoplayground.net/p/amQBqO1Bhvl

I see it https://pastebin.com/YqhKZcV6 i need in children populete user thank you

i try

```<code> await Reply.populate(replies, { path: "user" });
</code>```

Body:
I have a only first user witch

  await Reply.populate(replies, { path: "user" });

. My aggregation pipeline is as such:

https://mongoplayground.net/p/tHh1se1IFGa

This is original i take it https://mongoplayground.net/p/amQBqO1Bhvl

I see it https://pastebin.com/YqhKZcV6 i need in children populete user thank you

i try

 await Reply.populate(replies, { path: "user" });


问:
I need to put hyperlinks to all cells in the different Excel Book using Python openpyxl
I can't understand how to put external links correctly.

I'm expecting that links to cells will be related to their location.

I tried this

```<code>import os

from openpyxl import load_workbook, Workbook

def main():
    input_workbook_path = r"C:\Users\User\Desktop\Hendler Python\1\1_Goals.xlsx"
    output_workbook_path = r"C:\Users\User\Desktop\Hendler Python\Test.xlsx"

    input_wb = load_workbook(input_workbook_path)
    output_wb = Workbook()

    sheet_in = input_wb["Sheet1"]
    sheet_out = output_wb["Sheet"]
    cell_column = ["A","B","C","D"]
    input_workbook_path1=r"C:\Users\User\Desktop\Hendler Python\1"
    input_sheet_name=r"1_Goals.xlsx"

    for i in cell_column:
        for row in range (1,6):
            for column in range (1, 6):
             external_cell_link = f'=\'{input_workbook_path1}\[{input_sheet_name}]{sheet_in.title}\'!${i}${row}'
             sheet_out.cell(row = row, column = column).value = external_cell_link

    output_wb.save(output_workbook_path)

if __name__ == '__main__':
    main()

</code>```

Body:
I can't understand how to put external links correctly.

I'm expecting that links to cells will be related to their location.

I tried this

import os

from openpyxl import load_workbook, Workbook

def main():
    input_workbook_path = r"C:\Users\User\Desktop\Hendler Python\1\1_Goals.xlsx"
    output_workbook_path = r"C:\Users\User\Desktop\Hendler Python\Test.xlsx"

    input_wb = load_workbook(input_workbook_path)
    output_wb = Workbook()

    sheet_in = input_wb["Sheet1"]
    sheet_out = output_wb["Sheet"]
    cell_column = ["A","B","C","D"]
    input_workbook_path1=r"C:\Users\User\Desktop\Hendler Python\1"
    input_sheet_name=r"1_Goals.xlsx"

    for i in cell_column:
        for row in range (1,6):
            for column in range (1, 6):
             external_cell_link = f'=\'{input_workbook_path1}\[{input_sheet_name}]{sheet_in.title}\'!${i}${row}'
             sheet_out.cell(row = row, column = column).value = external_cell_link

    output_wb.save(output_workbook_path)

if __name__ == '__main__':
    main()


问:
How to compare each element in two different lists in Karate?
Refer https://karatelabs.github.io/karate/#loops

Here

```<code>* def fun = function(i){ return i * 2 }
* def foo = karate.repeat(5, fun)
* match foo == [1, 1, 1, 6, 8]
</code>```

'foo' when mismatches with the first element, karate stops to match rest of the elements
What can be used here so as to compare all elements of two lists (index wise)

Body:
Refer https://karatelabs.github.io/karate/#loops

Here

* def fun = function(i){ return i * 2 }
* def foo = karate.repeat(5, fun)
* match foo == [1, 1, 1, 6, 8]

'foo' when mismatches with the first element, karate stops to match rest of the elements
What can be used here so as to compare all elements of two lists (index wise)


问:
How to add hardsubs to video losslessly using FFmpeg?
I'm trying to make a function in python that adds hardsubs to a video, only that the video contains its own subtitles in acc format + a range of fonts to go with it. Is there a lossless way to achieve this effect without using -crf 0, as this increases the file size dramatically (not sure why -_-).
Code:

```<code>def add_subtitles():
    filename = input("filename: ")
    subfilename = input("ubfilename: ")
    cmd('ffmpeg -i ./input/' + filename + ' -vf subtitles=./input/' + subfilename +
        ' -c:v libx264 -crf 10 -preset medium ./output/' + filename + '.mp4')
    # -preset ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo (default medium)
</code>```

Second situation, is there a better solution for best quality and colours:

```<code>def frames_to_video_with_sound(filename, fps):
    cmd('ffmpeg -r ' + fps + ' -i ./out_frames/frame%08d.jpg -i ./input/' + filename +
        ' -map 0:v:0 -map 1:a:0 -c:a copy -c:v libx264 -r ' + fps + ' -pix_fmt yuv420p ./output/' + filename)
</code>```

Please help

Body:
I'm trying to make a function in python that adds hardsubs to a video, only that the video contains its own subtitles in acc format + a range of fonts to go with it. Is there a lossless way to achieve this effect without using -crf 0, as this increases the file size dramatically (not sure why -_-).
Code:

def add_subtitles():
    filename = input("filename: ")
    subfilename = input("ubfilename: ")
    cmd('ffmpeg -i ./input/' + filename + ' -vf subtitles=./input/' + subfilename +
        ' -c:v libx264 -crf 10 -preset medium ./output/' + filename + '.mp4')
    # -preset ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo (default medium)

Second situation, is there a better solution for best quality and colours:

def frames_to_video_with_sound(filename, fps):
    cmd('ffmpeg -r ' + fps + ' -i ./out_frames/frame%08d.jpg -i ./input/' + filename +
        ' -map 0:v:0 -map 1:a:0 -c:a copy -c:v libx264 -r ' + fps + ' -pix_fmt yuv420p ./output/' + filename)

Please help


问:
How do compilers handle records and unions?
My class was assigned a project to create a simple compiler that does basic operations over integers, I, however, have already figured a way of implementing pointers and would like to implement records and unions as well in order to increase the range of functionalities.
How does the compiler interpret this C code for example:
struct name {int x; char x;};

Note I am not expecting a very practical answer as i do intend on thinking on the matter but would like some theory behind this matter if it's possible.


问:
Output is not fully displayed on terminal of visual studio code when using "run code" function
When I run the python file with "run code" mode, the output is not fully displayed in the terminal, but when I run the python file with "run python file" mode, the output is fully displayed.

I have set the terminal Integrated scrollback to a much higher number but that didn't fix it. I'm speculating this error is caused by the code runner extension. Hope someone can understand and solve this problem for me.


问:
When connecting it to my react frontend. I get spotipy invalid client. However example works just fine on backend host
Using the example for testing: https://github.com/spotipy-dev/spotipy/blob/master/examples/app.py

Trying to use a React frontend that gets the html from the backend ("http://127.0.0.1:8080", which is my callback).

When I try to request the data for it, I keep getting errors and undefined states. However when I just simply go to the callback redirect url and get data, it works perfectly What could be the issue? I set the necessary env variables

Here is my python and React code

React code:

Python:

```<code>import os
from flask import Flask, session, request, redirect
from flask_cors import CORS, cross_origin
from flask_session import Session
import spotipy

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(64)
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_FILE_DIR'] = './.flask_session/'
CORS(app)
Session(app)

client_id = os.getenv("SPOTIPY_CLIENT_ID")
client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")
redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI")

@app.route('/')
def index():

    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(scope='user-read-currently-playing playlist-modify-private',
                                               cache_handler=cache_handler,
                                               show_dialog=True)

    if request.args.get("code"):
        # Step 2. Being redirected from Spotify auth page
        auth_manager.get_access_token(request.args.get("code"))
        return redirect('/')

    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        # Step 1. Display sign in link when no token
        auth_url = auth_manager.get_authorize_url()
        return f'<h2><a href="{auth_url}">Sign in</a></h2>'

    # Step 3. Signed in, display data
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    return f'<small><a href="/sign_out">[sign out]<a/></small></h2>' \
           f'<a href="/playlists">my playlists</a> | ' \
           f'<a href="/currently_playing">currently playing</a> | ' \
        f'<a href="/current_user">me</a>' \

@app.route('/sign_out')
def sign_out():
    session.pop("token_info", None)
    return redirect('/')

@app.route('/playlists')
def playlists():
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        return redirect('/')

    spotify = spotipy.Spotify(auth_manager=auth_manager)
    return spotify.current_user_playlists()

@app.route('/currently_playing')
def currently_playing():
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        return redirect('/')
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    track = spotify.current_user_playing_track()
    if not track is None:
        return track
    return "No track currently playing."

@app.route('/current_user')
def current_user():
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        return redirect('/')
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    return spotify.current_user()

'''
Following lines allow application to be run more conveniently with
`python app.py` (Make sure you're using python3)
(Also includes directive to leverage pythons threading capacity.)
'''
if __name__ == '__main__':
    app.run(threaded=True, port=int(os.environ.get("PORT",
                                                   os.environ.get("SPOTIPY_REDIRECT_URI", "8080").split(":")[-1])))
</code>```

Body:
Using the example for testing: https://github.com/spotipy-dev/spotipy/blob/master/examples/app.py

Trying to use a React frontend that gets the html from the backend ("http://127.0.0.1:8080", which is my callback).

When I try to request the data for it, I keep getting errors and undefined states. However when I just simply go to the callback redirect url and get data, it works perfectly What could be the issue? I set the necessary env variables

Here is my python and React code

React code:

Python:

import os
from flask import Flask, session, request, redirect
from flask_cors import CORS, cross_origin
from flask_session import Session
import spotipy

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(64)
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_FILE_DIR'] = './.flask_session/'
CORS(app)
Session(app)

client_id = os.getenv("SPOTIPY_CLIENT_ID")
client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")
redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI")

@app.route('/')
def index():

    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(scope='user-read-currently-playing playlist-modify-private',
                                               cache_handler=cache_handler,
                                               show_dialog=True)

    if request.args.get("code"):
        # Step 2. Being redirected from Spotify auth page
        auth_manager.get_access_token(request.args.get("code"))
        return redirect('/')

    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        # Step 1. Display sign in link when no token
        auth_url = auth_manager.get_authorize_url()
        return f'
Sign in
'

    # Step 3. Signed in, display data
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    return f'[sign out]
' \
           f'my playlists | ' \
           f'currently playing | ' \
        f'me' \

@app.route('/sign_out')
def sign_out():
    session.pop("token_info", None)
    return redirect('/')

@app.route('/playlists')
def playlists():
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        return redirect('/')

    spotify = spotipy.Spotify(auth_manager=auth_manager)
    return spotify.current_user_playlists()

@app.route('/currently_playing')
def currently_playing():
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        return redirect('/')
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    track = spotify.current_user_playing_track()
    if not track is None:
        return track
    return "No track currently playing."

@app.route('/current_user')
def current_user():
    cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
    if not auth_manager.validate_token(cache_handler.get_cached_token()):
        return redirect('/')
    spotify = spotipy.Spotify(auth_manager=auth_manager)
    return spotify.current_user()

'''
Following lines allow application to be run more conveniently with
`python app.py` (Make sure you're using python3)
(Also includes directive to leverage pythons threading capacity.)
'''
if __name__ == '__main__':
    app.run(threaded=True, port=int(os.environ.get("PORT",
                                                   os.environ.get("SPOTIPY_REDIRECT_URI", "8080").split(":")[-1])))