问:
Claims not visible after AWS Cognito Authentication
```<code>from flask import Flask, render_template, redirect, jsonify, request
from flask_awscognito import AWSCognitoAuthentication

application = Flask(__name__)

application.config['AWS_DEFAULT_REGION'] = 'eu-west-1'
application.config['AWS_COGNITO_DOMAIN'] = 'https://xxxxxx.auth.eu-west-1.amazoncognito.com' #seguro
application.config['AWS_COGNITO_USER_POOL_ID'] = 'xxxxxx'
application.config['AWS_COGNITO_USER_POOL_CLIENT_ID'] = 'xxxxxxx'
application.config['AWS_COGNITO_USER_POOL_CLIENT_SECRET'] = 'xxxxxxx'
application.config['AWS_COGNITO_REDIRECT_URL'] = 'http://localhost:5000/aws_cognito_redirect'

aws_auth = AWSCognitoAuthentication(application)

@application.route('/')
@aws_auth.authentication_required
def index():
    claims = aws_auth.claims
    return jsonify({'claims': claims})

@application.route('/aws_cognito_redirect')
def aws_cognito_redirect():
    access_token = aws_auth.get_access_token(request.args)
    return jsonify({'access_token': access_token})

@application.route('/sign_in')
def sign_in():
    return redirect(aws_auth.get_sign_in_url())
</code>```

after sign in it shows the token properly:

But now if I type http://localhost:5000/ on the browser it says there is no Token and I have no access to the claims:

Am I missing something? thanks

Body:
from flask import Flask, render_template, redirect, jsonify, request
from flask_awscognito import AWSCognitoAuthentication

application = Flask(__name__)

application.config['AWS_DEFAULT_REGION'] = 'eu-west-1'
application.config['AWS_COGNITO_DOMAIN'] = 'https://xxxxxx.auth.eu-west-1.amazoncognito.com' #seguro
application.config['AWS_COGNITO_USER_POOL_ID'] = 'xxxxxx'
application.config['AWS_COGNITO_USER_POOL_CLIENT_ID'] = 'xxxxxxx'
application.config['AWS_COGNITO_USER_POOL_CLIENT_SECRET'] = 'xxxxxxx'
application.config['AWS_COGNITO_REDIRECT_URL'] = 'http://localhost:5000/aws_cognito_redirect'

aws_auth = AWSCognitoAuthentication(application)

@application.route('/')
@aws_auth.authentication_required
def index():
    claims = aws_auth.claims
    return jsonify({'claims': claims})

@application.route('/aws_cognito_redirect')
def aws_cognito_redirect():
    access_token = aws_auth.get_access_token(request.args)
    return jsonify({'access_token': access_token})

@application.route('/sign_in')
def sign_in():
    return redirect(aws_auth.get_sign_in_url())

after sign in it shows the token properly:

But now if I type http://localhost:5000/ on the browser it says there is no Token and I have no access to the claims:

Am I missing something? thanks


来源: stackexchange

问:
How to add an error when there is a duplicate on a list?
sorry for the lengthy code.

```<code>s = """1,james,burgerking;
    2,jeff,mcdonalds;"""

##turning string into list
all_data = []
for row in map(str.strip, s.split(";")):
    if row == "":
        continue
    idx, name, work = row.split(",")
    all_data.append((int(idx), name, work))

##adding into list
num = int(input("Enter Number: "))
name = input("Enter name: ")
work = input("Enter work: ")

##for sorting
all_data.append((num, name, work))
all_data.sort(key=lambda k: k[0])

##printing
print()
for idx, name, work in all_data:
    print(f'''number: {idx}. {name} works in {work}.\n''')
</code>```

I need help with the adding into list part, say I put in the same number and name that's already in the s string, it would show an error, but I don't know how to implement it, any help?

output should end up like:

```<code>Enter number: 1
number already taken! please enter another name.
Enter number: 3
Enter name: Jeff
name already taken! please enter another name.
Enter name: mike
Enter work: google

1.  James works at burgerking.
2.  jeff works at mcdonalds.
3. mike works at google.
</code>```

any help would be appreciated.

ContentLicense: CC BY-SA 4.0

Body:
sorry for the lengthy code.

s = """1,james,burgerking;
    2,jeff,mcdonalds;"""

##turning string into list
all_data = []
for row in map(str.strip, s.split(";")):
    if row == "":
        continue
    idx, name, work = row.split(",")
    all_data.append((int(idx), name, work))

##adding into list
num = int(input("Enter Number: "))
name = input("Enter name: ")
work = input("Enter work: ")

##for sorting
all_data.append((num, name, work))
all_data.sort(key=lambda k: k[0])

##printing
print()
for idx, name, work in all_data:
    print(f'''number: {idx}. {name} works in {work}.\n''')

I need help with the adding into list part, say I put in the same number and name that's already in the s string, it would show an error, but I don't know how to implement it, any help?

output should end up like:

Enter number: 1
number already taken! please enter another name.
Enter number: 3
Enter name: Jeff
name already taken! please enter another name.
Enter name: mike
Enter work: google

1.  James works at burgerking.
2.  jeff works at mcdonalds.
3. mike works at google.

any help would be appreciated.


问:
Undesired R.java values when including Gradle modules via androidTestImplementation
In pursuit of "write once, run anywhere" integration tests, I am trying to move my test helpers into a Gradle module that can be included via testImplementation or androidTestImplementation. This helper module contains Espresso actions and assertions, which depend on View IDs and String resource identifiers from my app.

The problem -- When my helper module is included via androidTestImplementation, the module's resource references are only resolvable with the test context InstrumentationRegistry.context, rather than my app's InstrumentationRegistry.targetContext.

Is this expected? How else could I share resource reference-containing code between test and androidTest contexts, such that references always resolve to the target app context?

Sample code:

```<code>// :sharedtest Gradle module script
// Imports features in order to pull in their resource IDs
implementation(project(":features1"))
implementation(project(":features2"))
...

// Kotlin helpers inside :sharedtest Gradle module
import com.myapp.sharedtest.R

fun clickInsights() {
  onView(withId(R.id.insights_tool)).perform(click())
}
...

// Integration test inside :app which
// includes :sharedtest module via androidTestImplementation
@Test
fun verifyClickInsights() {
 // fails because com.myapp.sharedtest.R.id.insights_tool is not resolved as expected
 clickInsights()
}
...
</code>```

I explored Test Fixtures to house my test helpers, but seems AGP doesn't support them for Android Kotlin code at this time. I also considered source sets, but those have been deprecated in favor of Gradle modules.

I found success in changing my sharedtest helper imports to be child-module relative, i.e. com.myapp.feature1.R works, but com.myapp.sharedtest.R doesn't. But I'd like to
A) understand why this works and
B) avoid it if possible, since using sharedtest references everywhere is simplest codewise.

Body:
In pursuit of "write once, run anywhere" integration tests, I am trying to move my test helpers into a Gradle module that can be included via testImplementation or androidTestImplementation. This helper module contains Espresso actions and assertions, which depend on View IDs and String resource identifiers from my app.

The problem -- When my helper module is included via androidTestImplementation, the module's resource references are only resolvable with the test context InstrumentationRegistry.context, rather than my app's InstrumentationRegistry.targetContext.

Is this expected? How else could I share resource reference-containing code between test and androidTest contexts, such that references always resolve to the target app context?

Sample code:

// :sharedtest Gradle module script
// Imports features in order to pull in their resource IDs
implementation(project(":features1"))
implementation(project(":features2"))
...

// Kotlin helpers inside :sharedtest Gradle module
import com.myapp.sharedtest.R

fun clickInsights() {
  onView(withId(R.id.insights_tool)).perform(click())
}
...

// Integration test inside :app which
// includes :sharedtest module via androidTestImplementation
@Test
fun verifyClickInsights() {
 // fails because com.myapp.sharedtest.R.id.insights_tool is not resolved as expected
 clickInsights()
}
...

I explored Test Fixtures to house my test helpers, but seems AGP doesn't support them for Android Kotlin code at this time. I also considered source sets, but those have been deprecated in favor of Gradle modules.

I found success in changing my sharedtest helper imports to be child-module relative, i.e. com.myapp.feature1.R works, but com.myapp.sharedtest.R doesn't. But I'd like to
A) understand why this works and
B) avoid it if possible, since using sharedtest references everywhere is simplest codewise.


问:
How to make one annotation imply another in Java or Kotlin
I am using Retrofit and Kotlin to build an API client. For accessibility, I will provide examples in Java.

There are a few methods in this API that require a JSON body with only one parameter. I made an annotation @SingletonBody(String) that tells a call adapter to wrap the argument in a Map<String,Object>.

For example, to rename an account we PUT a A simple json body.

```<code>curl -X PUT https://api.example.com/account/whatever -d '{ "name": "the new name for the account" }'
</code>```

I want to pass a String name argument for simplicity rather than a Map. I could accomplish this by creating a default method that delegates to another method.

```<code>public interface AccountApi {

    // Inconvenient delegate
    @PUT("/accounts/{accountId}")
    Call<Void> renameAccount(@Path("accountId") String accountId, @Body Map<String,Object> body);

    // Convenient wrapper
    default Call<Void> renameAccount(String accountId, String name) {
        return renameAccount(accountId, Collections.singletonMap("name", name));
    }
}
</code>```

This felt messy to me. My @SingletonBody annotation allows me to declare only one method.

```<code>public interface AccountApi {

    @PUT("/accounts/{accountId}")
    Call<Void> renameAccount(@Path("accountId") String accountId,
                             @Body @SingletonBody("name") String name);

}
</code>```

TL;DR

My @SingletonBody annotation necessarily implies Retrofit's @Body annotation. How can I tell the complier to infer @Body from @SingletonBody such that I don't need to write both? Perhaps with an annotation preprocessor?

My instinct was to extend Retrofit's annotation, but the JVM (Kotlin too) does not allow annotations to have explicit superclasses or superinterfaces.

Body:
I am using Retrofit and Kotlin to build an API client. For accessibility, I will provide examples in Java.

There are a few methods in this API that require a JSON body with only one parameter. I made an annotation @SingletonBody(String) that tells a call adapter to wrap the argument in a Map<String,Object>.

For example, to rename an account we PUT a A simple json body.

curl -X PUT https://api.example.com/account/whatever -d '{ "name": "the new name for the account" }'

I want to pass a String name argument for simplicity rather than a Map. I could accomplish this by creating a default method that delegates to another method.

public interface AccountApi {

    // Inconvenient delegate
    @PUT("/accounts/{accountId}")
    Call<Void> renameAccount(@Path("accountId") String accountId, @Body Map<String,Object> body);

    // Convenient wrapper
    default Call<Void> renameAccount(String accountId, String name) {
        return renameAccount(accountId, Collections.singletonMap("name", name));
    }
}

This felt messy to me. My @SingletonBody annotation allows me to declare only one method.

public interface AccountApi {

    @PUT("/accounts/{accountId}")
    Call<Void> renameAccount(@Path("accountId") String accountId,
                             @Body @SingletonBody("name") String name);

}

TL;DR

My @SingletonBody annotation necessarily implies Retrofit's @Body annotation. How can I tell the complier to infer @Body from @SingletonBody such that I don't need to write both? Perhaps with an annotation preprocessor?

My instinct was to extend Retrofit's annotation, but the JVM (Kotlin too) does not allow annotations to have explicit superclasses or superinterfaces.


问:
How to speed up Rust function to search through a large JSON file
Currently I have a Rust function that searches through a large JSON file (About 1,080,000 lines) Currently this function takes about 1 second to search through this file, the data in this file is mostly stuff like this:

{"although":false,"radio":2056538449,"hide":1713884795,"hello":1222349560.787047,"brain":903780409.0046091,"heard":-1165604870.8374772}

How would I be able to increase the performance of this function?

Here is my Main.rs file.

```<code>use std::collections::VecDeque;
use std::fs::File;
use std::io::BufWriter;
use std::io::{BufRead, BufReader, Write};

fn search(filename: &str, search_line: &str) -> Result<VecDeque<u32>, std::io::Error> {
    let file = File::open(filename)?;
    let mut reader = BufReader::with_capacity(2048 * 2048, file);
    let mut line_numbers = VecDeque::new();
    let mut line_number = 0;
    let start = std::time::Instant::now();
    loop {
        line_number += 1;
        let mut line = String::new();
        let n = reader.read_line(&mut line)?;
        if n == 0 {
            break;
        }
        if line.trim() == search_line {
            line_numbers.push_back(line_number);
            println!(
                "Matching line found on line number {}: {}",
                line_number, line
            );
                    break;
        }
    }
    let elapsed = start.elapsed();
    println!("Elapsed time: {:?}", elapsed);
    if line_numbers.is_empty() {
        println!("No lines found that match the given criteria");
    }
    Ok(line_numbers)
}

fn main() {
    let database = "Test.json";
    if let Err(e) = search(database, r#"{"08934":420696969}"#) {
        println!("Error reading file: {}", e);
    }
}
</code>```

Body:
Currently I have a Rust function that searches through a large JSON file (About 1,080,000 lines) Currently this function takes about 1 second to search through this file, the data in this file is mostly stuff like this:

{"although":false,"radio":2056538449,"hide":1713884795,"hello":1222349560.787047,"brain":903780409.0046091,"heard":-1165604870.8374772}

How would I be able to increase the performance of this function?

Here is my Main.rs file.

use std::collections::VecDeque;
use std::fs::File;
use std::io::BufWriter;
use std::io::{BufRead, BufReader, Write};

fn search(filename: &str, search_line: &str) -> Result<VecDeque<u32>, std::io::Error> {
    let file = File::open(filename)?;
    let mut reader = BufReader::with_capacity(2048 * 2048, file);
    let mut line_numbers = VecDeque::new();
    let mut line_number = 0;
    let start = std::time::Instant::now();
    loop {
        line_number += 1;
        let mut line = String::new();
        let n = reader.read_line(&mut line)?;
        if n == 0 {
            break;
        }
        if line.trim() == search_line {
            line_numbers.push_back(line_number);
            println!(
                "Matching line found on line number {}: {}",
                line_number, line
            );
                    break;
        }
    }
    let elapsed = start.elapsed();
    println!("Elapsed time: {:?}", elapsed);
    if line_numbers.is_empty() {
        println!("No lines found that match the given criteria");
    }
    Ok(line_numbers)
}

fn main() {
    let database = "Test.json";
    if let Err(e) = search(database, r#"{"08934":420696969}"#) {
        println!("Error reading file: {}", e);
    }
}


问:
Why does my discord bot sub command won't show in discord.js V14?
I was trying to make a warning system with a sub command to add, remove, clear, check in my discord bot, but the sub command can't show in the command menu when trying to send a slash command in Discord. There is no error founded in the program.

Here is my command code:

```<code>
const { Client, IntentsBitField } = require("discord.js");

const app = new Client({
    intents: [
        IntentsBitField.Flags.Guilds,
        IntentsBitField.Flags.MessageContent,
        IntentsBitField.Flags.GuildMessages
    ]
});

const GUILD_ID = "1052930644524670996";
const GUILD = app.guilds.cache.get(GUILD_ID);

app.on("ready", function() {
    console.log("Bot is READY!");

    let commands;

    if (GUILD) {
        commands = GUILD.commands;
    } else {
        commands = app.application?.commands;
    }

    commands?.create({
        name: "warnings",
        description: "Warn peoples before taking further action.",
        perm: "ADMINISTRATOR",
        choices: [
            {
                name: "add",
                description: "Add warn to target.",
                type: "SUB_COMMAND",
                options: [
                    {
                        name: "name",
                        description: "Select the target.",
                        type: "USER",
                        required: true
                    },
                    {
                        name: "reason",
                        description: "Reason of the warnings.",
                        type: "STRING",
                        required: true
                    },
                    {
                        name: "evidance",
                        description: "The evidance of the warnings.",
                        type: "USER",
                        required: false
                    },
                ]
            },
            {
                name: "check",
                description: "Check warn of the target",
                type: "SUB_COMMAND",
                options: [
                    {
                        name: "name",
                        description: "Select the target.",
                        type: "USER",
                        required: true
                    },
                ]
            },
            {
                name: "remove",
                description: "Remove warnings from the target.",
                type: "SUB_COMMAND",
                options: [
                    {
                        name: "name",
                        description: "Select the target.",
                        type: "USER",
                        required: true
                    },
                    {
                        name: "warnID",
                        description: "ID of the warn.",
                        type: "STRING",
                        required: true
                    },
                ]
            },
            {
                name: "clear",
                description: "Clear warnings from the target.",
                type: "SUB_COMMAND",
                options: [
                    {
                        name: "name",
                        description: "Select the target.",
                        type: "USER",
                        required: true
                    },
                ]
            },
        ]
    })
})

</code>```

I'm expecting so my warning command to show the sub command in the discord command menu.

Body:
I was trying to make a warning system with a sub command to add, remove, clear, check in my discord bot, but the sub command can't show in the command menu when trying to send a slash command in Discord. There is no error founded in the program.

Here is my command code:

const { Client, IntentsBitField } = require("discord.js");

const app = new Client({
    intents: [
        IntentsBitField.Flags.Guilds,
        IntentsBitField.Flags.MessageContent,
        IntentsBitField.Flags.GuildMessages
    ]
});

const GUILD_ID = "1052930644524670996";
const GUILD = app.guilds.cache.get(GUILD_ID);

app.on("ready", function() {
    console.log("Bot is READY!");

    let commands;

    if (GUILD) {
        commands = GUILD.commands;
    } else {
        commands = app.application?.commands;
    }

    commands?.create({
        name: "warnings",
        description: "Warn peoples before taking further action.",
        perm: "ADMINISTRATOR",
        choices: [
            {
                name: "add",
                description: "Add warn to target.",
                type: "SUB_COMMAND",
                options: [
                    {
                        name: "name",
                        description: "Select the target.",
                        type: "USER",
                        required: true
                    },
                    {
                        name: "reason",
                        description: "Reason of the warnings.",
                        type: "STRING",
                        required: true
                    },
                    {
                        name: "evidance",
                        description: "The evidance of the warnings.",
                        type: "USER",
                        required: false
                    },
                ]
            },
            {
                name: "check",
                description: "Check warn of the target",
                type: "SUB_COMMAND",
                options: [
                    {
                        name: "name",
                        description: "Select the target.",
                        type: "USER",
                        required: true
                    },
                ]
            },
            {
                name: "remove",
                description: "Remove warnings from the target.",
                type: "SUB_COMMAND",
                options: [
                    {
                        name: "name",
                        description: "Select the target.",
                        type: "USER",
                        required: true
                    },
                    {
                        name: "warnID",
                        description: "ID of the warn.",
                        type: "STRING",
                        required: true
                    },
                ]
            },
            {
                name: "clear",
                description: "Clear warnings from the target.",
                type: "SUB_COMMAND",
                options: [
                    {
                        name: "name",
                        description: "Select the target.",
                        type: "USER",
                        required: true
                    },
                ]
            },
        ]
    })
})

I'm expecting so my warning command to show the sub command in the discord command menu.


问:
How to make images not required angular
i have the following image field:

```<code>      <div class="image-preview" *ngIf="imagePreview !== '' && imagePreview && form.get('image').valid">
        <img [src]="imagePreview" [alt]="form.value.title">
      </div>
</code>```

here is the formgroup snip where the field is set to required and verified::

```<code>  this.form = new FormGroup({
      jobTypes: this.jobTypes,  // this line works, but I feel there is a better way of doing this
    // jobTypes: new FormControl(''), // i wan to use this line, but it does not work when i try to print the content of the form later on
      content: new FormControl(null, { validators: [Validators.required] }),
      address: new FormControl(null, { validators: [Validators.required] }),
      image: new FormControl(null, {
        validators: [Validators.required],
        asyncValidators: [mimeType],
      }),
    });
</code>```

the issue that I am having is that if I remove "validators: [Validators.required],"

I get the following error:

```<code>core.js:4002 ERROR TypeError: Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'.
    at _global.<computed>.<computed> [as readAsArrayBuffer] (zone.js:1444:1)
    at Observable._subscribe (mime-type.validator.ts:43:18)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43:1)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29:1)
    at _loop_1 (forkJoin.js:42:1)
    at Observable._subscribe (forkJoin.js:65:1)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43:1)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29:1)
    at push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call (map.js:18:1)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:24:1)
</code>```

this is what the mimeType file looks like::
https://github.com/casas1010/mean-project/blob/main/src/app/posts/post-create/mime-type.validator.ts

Any idea as to why I am getting an error?

I didn't see any similar posts on stackoverflow

Title: How to make images not required angular

Body:
i have the following image field:

here is the formgroup snip where the field is set to required and verified::

  this.form = new FormGroup({
      jobTypes: this.jobTypes,  // this line works, but I feel there is a better way of doing this
    // jobTypes: new FormControl(''), // i wan to use this line, but it does not work when i try to print the content of the form later on
      content: new FormControl(null, { validators: [Validators.required] }),
      address: new FormControl(null, { validators: [Validators.required] }),
      image: new FormControl(null, {
        validators: [Validators.required],
        asyncValidators: [mimeType],
      }),
    });

the issue that I am having is that if I remove "validators: [Validators.required],"

I get the following error:

core.js:4002 ERROR TypeError: Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'.
    at _global.<computed>.<computed> [as readAsArrayBuffer] (zone.js:1444:1)
    at Observable._subscribe (mime-type.validator.ts:43:18)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43:1)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29:1)
    at _loop_1 (forkJoin.js:42:1)
    at Observable._subscribe (forkJoin.js:65:1)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43:1)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29:1)
    at push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call (map.js:18:1)
    at push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:24:1)

this is what the mimeType file looks like::
https://github.com/casas1010/mean-project/blob/main/src/app/posts/post-create/mime-type.validator.ts

Any idea as to why I am getting an error?

I didn't see any similar posts on stackoverflow


问:
Rethinking Python for loop to pySpark to create dataframes
I have a list of accounts which I iterate in a loop calling the details from an API function get_accounts. The JSON response for each call includes details for one account with one or more contacts which I add to dataframes df_accounts and df_contacts respectively.

The API loop portion works though it takes a long time. The volume of data is under 5K accounts and 10K contacts. The final goal is to save two delta tables one for all accounts and one contacts. I know there must be a better approach utilizing pySpark architecture.

```<code>account_details = []
provider_details = []

for account_id in account_header['providerAccounts']:
    account_detail = get_accounts(account_id['id'])

    account_details.append(spark.createDataFrame(data = [account_detail['providerAccount']], schema=account_schema))

    for provider in account_detail['providerAccount']['providers']:
        provider_details.append(spark.createDataFrame(data = [provider], schema=provider_schema))

df_account = reduce(DataFrame.unionAll, account_details)
df_provider = reduce(DataFrame.unionAll, provider_details)
</code>```

However an error occurs when I try to save the dataframes as a delta tables.

```<code>df_accounts.write.format("delta").mode('overwrite').save(acct_fulldeltapath)
df_provider.write.format("delta").mode('overwrite').save(px_fulldeltapath)
</code>```

Error code below:

```<code>Py4JJavaError                             Traceback (most recent call last)
<ipython-input-19-7b487f51> in <module>
      4 px_fulldeltapath = pathFormatted + px_pathSparkSubFolderFull
      5
----> 6 df_contacts.write.format("delta").mode('overwrite').save(px_fulldeltapath)

/opt/spark/python/lib/pyspark.zip/pyspark/sql/readwriter.py in save(self, path, format, mode, partitionBy, **options)
    738             self._jwrite.save()
    739         else:
--> 740             self._jwrite.save(path)
    741
    742     @since(1.4)

~/cluster-env/env/lib/python3.8/site-packages/py4j/java_gateway.py in __call__(self, *args)
   1319
   1320         answer = self.gateway_client.send_command(command)
-> 1321         return_value = get_return_value(
   1322             answer, self.gateway_client, self.target_id, self.name)
   1323

/opt/spark/python/lib/pyspark.zip/pyspark/sql/utils.py in deco(*a, **kw)
    109     def deco(*a, **kw):
    110         try:
--> 111             return f(*a, **kw)
    112         except py4j.protocol.Py4JJavaError as e:
    113             converted = convert_exception(e.java_exception)

~/cluster-env/env/lib/python3.8/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    324             value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325             if answer[1] == REFERENCE_TYPE:
--> 326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
    328                     format(target_id, ".", name), value)

Py4JJavaError: An error occurred while calling o63219.save.

...

Caused by: org.apache.spark.SparkException: Job aborted due to stage failure: Total size of serialized results of 14638 tasks (4.0 GiB) is bigger than spark.driver.maxResultSize (4.0 GiB)
    at org.apache.spark.scheduler.DAGScheduler.failJobAndIndependentStages(DAGScheduler.scala:2464)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2(DAGScheduler.scala:2413)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2$adapted(DAGScheduler.scala:2412)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)
</code>```

Body:
I have a list of accounts which I iterate in a loop calling the details from an API function get_accounts. The JSON response for each call includes details for one account with one or more contacts which I add to dataframes df_accounts and df_contacts respectively.

The API loop portion works though it takes a long time. The volume of data is under 5K accounts and 10K contacts. The final goal is to save two delta tables one for all accounts and one contacts. I know there must be a better approach utilizing pySpark architecture.

account_details = []
provider_details = []

for account_id in account_header['providerAccounts']:
    account_detail = get_accounts(account_id['id'])

    account_details.append(spark.createDataFrame(data = [account_detail['providerAccount']], schema=account_schema))

    for provider in account_detail['providerAccount']['providers']:
        provider_details.append(spark.createDataFrame(data = [provider], schema=provider_schema))

df_account = reduce(DataFrame.unionAll, account_details)
df_provider = reduce(DataFrame.unionAll, provider_details)

However an error occurs when I try to save the dataframes as a delta tables.

df_accounts.write.format("delta").mode('overwrite').save(acct_fulldeltapath)
df_provider.write.format("delta").mode('overwrite').save(px_fulldeltapath)

Error code below:

Py4JJavaError                             Traceback (most recent call last)
<ipython-input-19-7b487f51> in <module>
      4 px_fulldeltapath = pathFormatted + px_pathSparkSubFolderFull
      5
----> 6 df_contacts.write.format("delta").mode('overwrite').save(px_fulldeltapath)

/opt/spark/python/lib/pyspark.zip/pyspark/sql/readwriter.py in save(self, path, format, mode, partitionBy, **options)
    738             self._jwrite.save()
    739         else:
--> 740             self._jwrite.save(path)
    741
    742     @since(1.4)

~/cluster-env/env/lib/python3.8/site-packages/py4j/java_gateway.py in __call__(self, *args)
   1319
   1320         answer = self.gateway_client.send_command(command)
-> 1321         return_value = get_return_value(
   1322             answer, self.gateway_client, self.target_id, self.name)
   1323

/opt/spark/python/lib/pyspark.zip/pyspark/sql/utils.py in deco(*a, **kw)
    109     def deco(*a, **kw):
    110         try:
--> 111             return f(*a, **kw)
    112         except py4j.protocol.Py4JJavaError as e:
    113             converted = convert_exception(e.java_exception)

~/cluster-env/env/lib/python3.8/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    324             value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325             if answer[1] == REFERENCE_TYPE:
--> 326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
    328                     format(target_id, ".", name), value)

Py4JJavaError: An error occurred while calling o63219.save.

...

Caused by: org.apache.spark.SparkException: Job aborted due to stage failure: Total size of serialized results of 14638 tasks (4.0 GiB) is bigger than spark.driver.maxResultSize (4.0 GiB)
    at org.apache.spark.scheduler.DAGScheduler.failJobAndIndependentStages(DAGScheduler.scala:2464)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2(DAGScheduler.scala:2413)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2$adapted(DAGScheduler.scala:2412)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)


问:
python qlistwidget, how do i get setCurrentItem by string?
im trying to get a name of selected item by text on QListWidget and the opposite (set currentitem by text)
i could get the name of selected item by doing this.

```<code>A = QListWidget.currentItem().text()
</code>```

but i want to set the currentitem by text as well. (something like below)

```<code>QListWidget.setcurrentItem().text(A)
</code>```

how can i accomplish this?

Body:
im trying to get a name of selected item by text on QListWidget and the opposite (set currentitem by text)
i could get the name of selected item by doing this.

A = QListWidget.currentItem().text()

but i want to set the currentitem by text as well. (something like below)

QListWidget.setcurrentItem().text(A)

how can i accomplish this?


问:
Couldn't able to install ng for angular/cli
I got stuck in installing angular. It was working smootly before on the other day but today when I came back to my project, it keep saying ng command not found.
I read few documents how to fix the error , but I couldn't able to solve it.

Now when I run ng --version, it says "zsh: command not found: --version".

I uninstalled node.js and did everything from the beginning but doesn't work.

I think i having problem in the path to the ng folder something.
WHen I run npm config get prefix on the command prompt it gets:

```<code>/Users/amritmalhi/.npm-global
</code>```

My Angular Project Path is at /Users/amritmalhi/Projects/Angular_Project.

```<code>amritmalhi@Amrits-MBP Angular_Project % ng --version
zsh: command not found: --version
amritmalhi@Amrits-MBP Angular_Project %
</code>```

Body:
I got stuck in installing angular. It was working smootly before on the other day but today when I came back to my project, it keep saying ng command not found.
I read few documents how to fix the error , but I couldn't able to solve it.

Now when I run ng --version, it says "zsh: command not found: --version".

I uninstalled node.js and did everything from the beginning but doesn't work.

I think i having problem in the path to the ng folder something.
WHen I run npm config get prefix on the command prompt it gets:

/Users/amritmalhi/.npm-global

My Angular Project Path is at /Users/amritmalhi/Projects/Angular_Project.

amritmalhi@Amrits-MBP Angular_Project % ng --version
zsh: command not found: --version
amritmalhi@Amrits-MBP Angular_Project %


问:
Control alarms via session in tradingview
I just want to allow a certain amount of trading time per day and set the time via sessions. It works so far and the strategy.entries are not displayed in Tradingview either, but the alarms in Tradingview continue to run and are not deactivated when the specified trading time has expired. Is there a possibility to deactivate the TV alarms according to times? I tried that but it doesn't work</p>
```<code>InSession(sessionTimes, sessionTimeZone=syminfo.timezone) =>
    not na(time(timeframe.period, sessionTimes, sessionTimeZone))

// Create the inputs
sessionInput = input.session("0900-1730", title="Session Times",
     group="Trading Session", tooltip="Use the checkboxes to select " +
     "on which days of the week this session is active. The session " +
     "has to be active on at least one day.")
monSession = input.bool(true, title="Mon ", group="Trading Session", inline="d1")
tueSession = input.bool(true, title="Tue ", group="Trading Session", inline="d1")
wedSession = input.bool(true, title="Wed ", group="Trading Session", inline="d1")
thuSession = input.bool(true, title="Thu ", group="Trading Session", inline="d1")
friSession = input.bool(true, title="Fri   ", group="Trading Session", inline="d2")
satSession = input.bool(false, title="Sat  ", group="Trading Session", inline="d2")
sunSession = input.bool(false, title="Sun ", group="Trading Session", inline="d2")

// Make a days of week string based on the value of the checkboxes
sessionDays = ""

if sunSession
    sessionDays += "1"
if monSession
    sessionDays += "2"
if tueSession
    sessionDays += "3"
if wedSession
    sessionDays += "4"
if thuSession
    sessionDays += "5"
if friSession
    sessionDays += "6"
if satSession
    sessionDays += "7"

// Make the session string by joining the time with the days
tradingSession = sessionInput + ":" + sessionDays

// Abfrage der Sessionzeiten zusamengefasst
time_is_allowed = time("1", tradingSession)

// Position für Long ausführen
if(long_beding and barstate.isconfirmed and time_is_allowed) // long_beding //  and gr_kerze > herzen_h
    alertLongEntry = input.string("Entry Long {{ticker}}!", "Alert Message Long Entry: ", group = "Alert Settings")
    strategy.entry("GL", strategy.long, alert_message = alertLongEntry)

// Position für Short ausführen
if(short_beding and barstate.isconfirmed and time_is_allowed) // short_beding //and gr_kerze > herzen_h
    alertShortEntry = input.string("Entry Short {{ticker}}!", "Alert Message Short Entry: ", group = "Alert Settings")
    strategy.entry("GS", strategy.short, alert_message = alertShortEntry)

</code>```

Body:
I just want to allow a certain amount of trading time per day and set the time via sessions. It works so far and the strategy.entries are not displayed in Tradingview either, but the alarms in Tradingview continue to run and are not deactivated when the specified trading time has expired. Is there a possibility to deactivate the TV alarms according to times? I tried that but it doesn't work

InSession(sessionTimes, sessionTimeZone=syminfo.timezone) =>
    not na(time(timeframe.period, sessionTimes, sessionTimeZone))

// Create the inputs
sessionInput = input.session("0900-1730", title="Session Times",
     group="Trading Session", tooltip="Use the checkboxes to select " +
     "on which days of the week this session is active. The session " +
     "has to be active on at least one day.")
monSession = input.bool(true, title="Mon ", group="Trading Session", inline="d1")
tueSession = input.bool(true, title="Tue ", group="Trading Session", inline="d1")
wedSession = input.bool(true, title="Wed ", group="Trading Session", inline="d1")
thuSession = input.bool(true, title="Thu ", group="Trading Session", inline="d1")
friSession = input.bool(true, title="Fri   ", group="Trading Session", inline="d2")
satSession = input.bool(false, title="Sat  ", group="Trading Session", inline="d2")
sunSession = input.bool(false, title="Sun ", group="Trading Session", inline="d2")

// Make a days of week string based on the value of the checkboxes
sessionDays = ""

if sunSession
    sessionDays += "1"
if monSession
    sessionDays += "2"
if tueSession
    sessionDays += "3"
if wedSession
    sessionDays += "4"
if thuSession
    sessionDays += "5"
if friSession
    sessionDays += "6"
if satSession
    sessionDays += "7"

// Make the session string by joining the time with the days
tradingSession = sessionInput + ":" + sessionDays

// Abfrage der Sessionzeiten zusamengefasst
time_is_allowed = time("1", tradingSession)

// Position für Long ausführen
if(long_beding and barstate.isconfirmed and time_is_allowed) // long_beding //  and gr_kerze > herzen_h
    alertLongEntry = input.string("Entry Long {{ticker}}!", "Alert Message Long Entry: ", group = "Alert Settings")
    strategy.entry("GL", strategy.long, alert_message = alertLongEntry)

// Position für Short ausführen
if(short_beding and barstate.isconfirmed and time_is_allowed) // short_beding //and gr_kerze > herzen_h
    alertShortEntry = input.string("Entry Short {{ticker}}!", "Alert Message Short Entry: ", group = "Alert Settings")
    strategy.entry("GS", strategy.short, alert_message = alertShortEntry)


问:
Changing color of occluded part of mesh within shader
I am working with THREE.JS and want to be able to have a mesh that changes the occluded part of itself into a different color.

Simple Example

The above image is a simple example, where the wall is in front of the Mesh and obstructing part of the Mesh but not all of it. The visible part of the mesh should be colored green whilst the occluded part should be colored red. Note that the wall is not transparent; the occluded part of the mesh should still be rendered using depthTest = false.

I've tried messing around with some basic shaders, but I don't really how to get started. Currently, the core parts of my code looks like this:

// My cube's material
const overlayMat = new THREE.ShaderMaterial({
    uniforms: {
        "maskTexture": { value: null },
    },
    vertexShader:
        `varying vec2 vUv;
        void main() {
            vUv = uv;
            gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
        }`,
    fragmentShader:
        `varying vec2 vUv;
        uniform sampler2D maskTexture;

        void main() {
            vec4 maskColor = texture2D(maskTexture, vUv);
            float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;
            // Attempt to set the green value to the visibility factor
            gl_FragColor = vec4(1.0, visibilityFactor, 0.0, 1.0);
        }`,
    depthTest: false,
    depthWrite: false,
    transparent: true
});

// My mask
let renderTargetMaskBuffer = new THREE.WebGLRenderTarget(innerWidth, innerHeight, {
    minFilter: THREE.LinearFilter,
    magFilter: THREE.LinearFilter,
    format: THREE.RGBAFormat
});

// Inside my animate function:

function animate() {
    // ...
    overlayMat.uniforms["maskTexture"].value = renderTargetMaskBuffer.depthTexture;
    renderer.render(scene, camera);
}
```

Which does not work, the cube remains one constant color.

Full code (with the "wall" that occludes part of the mesh) (JSFiddle)

Body:
I am working with THREE.JS and want to be able to have a mesh that changes the occluded part of itself into a different color.

Simple Example

The above image is a simple example, where the wall is in front of the Mesh and obstructing part of the Mesh but not all of it. The visible part of the mesh should be colored green whilst the occluded part should be colored red. Note that the wall is not transparent; the occluded part of the mesh should still be rendered using depthTest = false.

I've tried messing around with some basic shaders, but I don't really how to get started. Currently, the core parts of my code looks like this:

// My cube's material
const overlayMat = new THREE.ShaderMaterial({
    uniforms: {
        "maskTexture": { value: null },
    },
    vertexShader:
        `varying vec2 vUv;
        void main() {
            vUv = uv;
            gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
        }`,
    fragmentShader:
        `varying vec2 vUv;
        uniform sampler2D maskTexture;

        void main() {
            vec4 maskColor = texture2D(maskTexture, vUv);
            float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;
            // Attempt to set the green value to the visibility factor
            gl_FragColor = vec4(1.0, visibilityFactor, 0.0, 1.0);
        }`,
    depthTest: false,
    depthWrite: false,
    transparent: true
});

// My mask
let renderTargetMaskBuffer = new THREE.WebGLRenderTarget(innerWidth, innerHeight, {
    minFilter: THREE.LinearFilter,
    magFilter: THREE.LinearFilter,
    format: THREE.RGBAFormat
});

// Inside my animate function:

function animate() {
    // ...
    overlayMat.uniforms["maskTexture"].value = renderTargetMaskBuffer.depthTexture;
    renderer.render(scene, camera);
}

Which does not work, the cube remains one constant color.

Full code (with the "wall" that occludes part of the mesh) (JSFiddle)


问:
perf experiments to understand what the hardware can do
Multiplying larger and larger arrays of fp64 values takes the same time up until some point where the time increases. However, it isn't what I expect. First the results and then the code. The first number is the size of the array of numbers and the last number is the time in seconds. The time is for 1,000,000 executions. It is on a 4090. While looking consider a few questions. If there are only 16,384 CUDA cores then why does the time stay the same from before 16,384 fp64 values till well after that? Only at 262,144 multiples does it take significantly longer. Then after that the time doesn't quite double(1.8x) for reasons I don't understand. Once you've saturated the device then doubling the work should be at least 2X slower. Finally when going from 2097152 to 4194304 multiplies it takes 4.5 times as long. ???

```<code>8192: t1 * t2 took 2.081
16384: t1 * t2 took 2.095
32768: t1 * t2 took 2.066
65536: t1 * t2 took 2.057
131072: t1 * t2 took 2.209   Q1: Why still about 2 second with way over num of cuda cores?
262144: t1 * t2 took 2.991
524288: t1 * t2 took 5.989   2X slower which makes sense
1048576: t1 * t2 took 10.388  Only 1.7X slower which is a suprise given it is twice the work
2097152: t1 * t2 took 18.95   Q2: 1.8X slower but why ONLY 1.8X
4194304: t1 * t2 took 86.161  Q3:  4.5X slower for twice the work What is going on here?
</code>```
```<code>import torch
import time
from datetime import datetime
from datetime import timedelta

with torch.cuda.device(0):
    dim1 = 256
    dim2 = 16
    while dim2 <= 16384:
        t1 = 1 + torch.rand((dim1,dim2), device='cuda', dtype=torch.float64)/10000
        t2 = 1 + torch.rand((dim1,dim2), device='cuda', dtype=torch.float64)/10000
        i = 0
        tm0 = datetime.now()
        while i < 1000000:
            t1 = t1 * t2
            #torch.cuda.synchronize()  # MULT is dependent on previous result
            i += 1
        torch.cuda.synchronize()
        print(f"{dim1*dim2}: t1 * t2 took {round(timedelta.total_seconds(datetime.now()-tm0)+.0001, 3)}")
        dim2 *= 2
</code>```

I tried the code above and I was expecting 32,768 multiplies would take twice the time as 16,384 given the actual number of cuda cores.

Body:
Multiplying larger and larger arrays of fp64 values takes the same time up until some point where the time increases. However, it isn't what I expect. First the results and then the code. The first number is the size of the array of numbers and the last number is the time in seconds. The time is for 1,000,000 executions. It is on a 4090. While looking consider a few questions. If there are only 16,384 CUDA cores then why does the time stay the same from before 16,384 fp64 values till well after that? Only at 262,144 multiples does it take significantly longer. Then after that the time doesn't quite double(1.8x) for reasons I don't understand. Once you've saturated the device then doubling the work should be at least 2X slower. Finally when going from 2097152 to 4194304 multiplies it takes 4.5 times as long. ???

8192: t1 * t2 took 2.081
16384: t1 * t2 took 2.095
32768: t1 * t2 took 2.066
65536: t1 * t2 took 2.057
131072: t1 * t2 took 2.209   Q1: Why still about 2 second with way over num of cuda cores?
262144: t1 * t2 took 2.991
524288: t1 * t2 took 5.989   2X slower which makes sense
1048576: t1 * t2 took 10.388  Only 1.7X slower which is a suprise given it is twice the work
2097152: t1 * t2 took 18.95   Q2: 1.8X slower but why ONLY 1.8X
4194304: t1 * t2 took 86.161  Q3:  4.5X slower for twice the work What is going on here?

import torch
import time
from datetime import datetime
from datetime import timedelta

with torch.cuda.device(0):
    dim1 = 256
    dim2 = 16
    while dim2 <= 16384:
        t1 = 1 + torch.rand((dim1,dim2), device='cuda', dtype=torch.float64)/10000
        t2 = 1 + torch.rand((dim1,dim2), device='cuda', dtype=torch.float64)/10000
        i = 0
        tm0 = datetime.now()
        while i < 1000000:
            t1 = t1 * t2
            #torch.cuda.synchronize()  # MULT is dependent on previous result
            i += 1
        torch.cuda.synchronize()
        print(f"{dim1*dim2}: t1 * t2 took {round(timedelta.total_seconds(datetime.now()-tm0)+.0001, 3)}")
        dim2 *= 2

I tried the code above and I was expecting 32,768 multiplies would take twice the time as 16,384 given the actual number of cuda cores.


问:
How to plot 3 columns on Altair?
I am struggling to plot 3 columns in Altair from the following data:

I would like to use MilkType and FatLevel on the X axis and Count on the Y axis, however my plot shows up blank with the following code:

```<code>
alt.Chart(fat_count, width=500, height=300).mark_bar().encode(
    x='MilkType:Q',
    y='Count:N',
    row=alt.Row('FatLevel')
).transform_fold(
    as_=['MilkType','Count'],
    fold=['lower fat','higher fat'])

</code>```

Any help would be appreciated

Title: How to plot 3 columns on Altair?

Body:
I am struggling to plot 3 columns in Altair from the following data:

I would like to use MilkType and FatLevel on the X axis and Count on the Y axis, however my plot shows up blank with the following code:

alt.Chart(fat_count, width=500, height=300).mark_bar().encode(
    x='MilkType:Q',
    y='Count:N',
    row=alt.Row('FatLevel')
).transform_fold(
    as_=['MilkType','Count'],
    fold=['lower fat','higher fat'])

Any help would be appreciated


问:
Speech to Text Model, where the model doesn't attempt to correct errors/grammer?
Is there an Vosk speech to text model, or any other open source/closed sourced model, where the model would output the spoken words into text. But it wouldn't correct them into proper words or fix their grammer, just output what they are saying in english/gibberish?

Currently, Vosk English level models and Deepspeech models output and accurately correct what the user is saying, but I am trying to find the opposite where it just outputs what is spoken.

If there are no models already trained for this, how would I go to getting one to behave like this?


问:
How to show the lua line that has an error using C code
How can I get the line from the lua file that is showing error, I have a table as follows

My table:

```<code>Test = {
    var1 = "...",
    var2 = "...",
    var3 = "..."
};
</code>```

My Code:

```<code>int lua_line(lua_State *L) {
    lua_Debug ar;
    lua_getstack(L, 0, &ar);
    lua_getinfo(L, "l", &ar);
    return ar.currentline;
}

void read_table(void) {
    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs(L);

    if (luaL_loadfile(L, "table.lua") || lua_pcall(L, 0, 0, 0))
    {
        ShowError("Error reading 'table.lua'\n");
        return;
    }

    lua_getglobal(L, "Test");

    lua_getfield(L, lua_gettop(L), "var1");
    var->one = lua_tointeger(L, 1);
    if(var->one > MAX_VALUE) {
       printf("Value of var1 must not be greater than %d, Error line %d", MAX_VALUE, lua_line(L));
    }
    ....
}
</code>```

When var->one is greater than MAX_VALUE I want to show which lua line should be corrected

I tried to create something using lua_Debug, but without success

When I try to print lua_line the program just stops responding

How should I do to show the line of the lua file with problem?

Body:
How can I get the line from the lua file that is showing error, I have a table as follows

My table:

Test = {
    var1 = "...",
    var2 = "...",
    var3 = "..."
};

My Code:

int lua_line(lua_State *L) {
    lua_Debug ar;
    lua_getstack(L, 0, &ar);
    lua_getinfo(L, "l", &ar);
    return ar.currentline;
}

void read_table(void) {
    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs(L);

    if (luaL_loadfile(L, "table.lua") || lua_pcall(L, 0, 0, 0))
    {
        ShowError("Error reading 'table.lua'\n");
        return;
    }

    lua_getglobal(L, "Test");

    lua_getfield(L, lua_gettop(L), "var1");
    var->one = lua_tointeger(L, 1);
    if(var->one > MAX_VALUE) {
       printf("Value of var1 must not be greater than %d, Error line %d", MAX_VALUE, lua_line(L));
    }
    ....
}

When var->one is greater than MAX_VALUE I want to show which lua line should be corrected

I tried to create something using lua_Debug, but without success

When I try to print lua_line the program just stops responding

How should I do to show the line of the lua file with problem?


问:
Backend-framework that can use ImageMagick and S3
I'm new to web development field, and this is the first time for me to design system. If I can receive any advice, it will be appreciated.

Currently, I am working on video-hosting platform, using AWS S3. So the backend-framework should be connected to S3. When a user download a image from backend, they should be able to edit the image with ImageMagick or something similar.

Here is a question;
Is there a good backend-framework that makes uploading images to S3 easier? I think rails active storage system works really well in this regard. But the problem of rails is that it can't use full ImageMagick functions.

What I have to care about is the connection to S3, and the ability to use image-editting system.

For now, I plant to use Ruby on Rails, but I would like to know other options and their pros and cons.
Thank you.


问:
Create folder outline with CSS
I want to create a folder outline using CSS below you can see my code, but there are a few problems. It is the upper right corner that haunts me, it is quite light compared to the rest of the folder.

What is the best way to fix my code so that it does not have defects?

Or is it better to rewrite everything? I'm not very good at CSS.

.wrapper_folder {
    @include folder;
}

@mixin folder {
    height: 348px;
    width: clamp(150px, 100%, 466px);
    &::after {
        bottom: 0;
        content: '';
        height: 306px;
        position: absolute;
        border-radius: 23px;
        background-color: white;
        width: clamp(150px, 100%, 466px);
        border-top: 1px solid black;
        border-right: 1px solid black;
    }
    &::before {
        top: 19px;
        z-index: 1;
        content: '';
        height: 22px;
        position: absolute;
        width: calc(50% + 20px);
        background-color: white;
        background-repeat: no-repeat;
        border-bottom: 25px solid white;
        filter: drop-shadow(0px 0px 0px black);
        background: radial-gradient(circle 23px at top right,#0000 95%,white ) top right;
    }

    position: absolute;
    border-radius: 23px;
    border-left: 1px solid black;
    border-bottom: 1px solid black;

    & > .folder_name {
        @include folderName;
    }
    & > .folder_box {
        @include folderBox;
    }
}

@mixin folderName {
    z-index: 1;
    height: 42px;
    display: flex;
    position: relative;
    text-align: center;
    border-radius: 23px;
    width: calc(50% - 3px);
    flex-direction: column;
    justify-content: center;
    background-color: white;
    border-top: 1px solid black;
    & > p{
        margin-top: 21px;
        margin-left: -19px;
    }
}

@mixin folderBox {
    background-color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper_folder three_folder">
    <div class="folder_name">
        <p class="folder_name_title">folder</p>
   </div>
    <div class="folder_box">
        <span class="folder_box_description"></span>
    </div>
</div></code>```

Title: Create folder outline with CSS

Body:
I want to create a folder outline using CSS below you can see my code, but there are a few problems. It is the upper right corner that haunts me, it is quite light compared to the rest of the folder.

What is the best way to fix my code so that it does not have defects?

Or is it better to rewrite everything? I'm not very good at CSS.

.wrapper_folder {
    @include folder;
}

@mixin folder {
    height: 348px;
    width: clamp(150px, 100%, 466px);
    &::after {
        bottom: 0;
        content: '';
        height: 306px;
        position: absolute;
        border-radius: 23px;
        background-color: white;
        width: clamp(150px, 100%, 466px);
        border-top: 1px solid black;
        border-right: 1px solid black;
    }
    &::before {
        top: 19px;
        z-index: 1;
        content: '';
        height: 22px;
        position: absolute;
        width: calc(50% + 20px);
        background-color: white;
        background-repeat: no-repeat;
        border-bottom: 25px solid white;
        filter: drop-shadow(0px 0px 0px black);
        background: radial-gradient(circle 23px at top right,#0000 95%,white ) top right;
    }

    position: absolute;
    border-radius: 23px;
    border-left: 1px solid black;
    border-bottom: 1px solid black;

    & > .folder_name {
        @include folderName;
    }
    & > .folder_box {
        @include folderBox;
    }
}

@mixin folderName {
    z-index: 1;
    height: 42px;
    display: flex;
    position: relative;
    text-align: center;
    border-radius: 23px;
    width: calc(50% - 3px);
    flex-direction: column;
    justify-content: center;
    background-color: white;
    border-top: 1px solid black;
    & > p{
        margin-top: 21px;
        margin-left: -19px;
    }
}

@mixin folderBox {
    background-color: white;
}

folder


问:
JavaScriptCore: cannot modify array elements attached to Swift-defined objects
I've defined an Entity class in Swift and exported it to JS using JSExport like so:

```<code>@objc protocol EntityJSExports: JSExport {
    var position: [NSNumber] { get set }
    init()
}

@objc public class Entity: NSObject, EntityJSExports {
    dynamic var position: [NSNumber]
    required init() {
        self.position = [0,0,0]
    }
}
</code>```

I then instantiate a JS context and populate it with an instance of an Entity:

```<code>let entity = Entity()
let jsContext = JSContext()!
jsContext.setObject(entity, forKeyedSubscript: "entity" as NSString)
</code>```

But the following JavaScript code does not behave as expected. Note that I can replace the entire position property with a new array but I cannot modify any element within it. The only way to do so is to make a temporary copy of the whole array, modify it, and write back. However, if I attach a new property, e.g. foo, it works.

```<code>print("position = " + entity.position);
entity.position[1] = 2;
print("position = " + entity.position + " (should be [0,2,0])");

var tmp = entity.position;
tmp[1] = 2;
entity.position = tmp;
print("position = " + entity.position + " (now is [0,2,0])");

entity.foo = [1,1,1];
entity.foo[1] = 2;
print("foo = " + entity.foo + " (as expected)");
</code>```

The output of this script is (I define a print() function to log):

```<code>position = 0,0,0
position = 0,0,0 (should be [0,2,0])
position = 0,2,0 (now is [0,2,0])
foo = 1,2,1 ([1,2,1] as expected)
</code>```

I'm stumped. What is going on?

Body:
I've defined an Entity class in Swift and exported it to JS using JSExport like so:

@objc protocol EntityJSExports: JSExport {
    var position: [NSNumber] { get set }
    init()
}

@objc public class Entity: NSObject, EntityJSExports {
    dynamic var position: [NSNumber]
    required init() {
        self.position = [0,0,0]
    }
}

I then instantiate a JS context and populate it with an instance of an Entity:

let entity = Entity()
let jsContext = JSContext()!
jsContext.setObject(entity, forKeyedSubscript: "entity" as NSString)

But the following JavaScript code does not behave as expected. Note that I can replace the entire position property with a new array but I cannot modify any element within it. The only way to do so is to make a temporary copy of the whole array, modify it, and write back. However, if I attach a new property, e.g. foo, it works.

print("position = " + entity.position);
entity.position[1] = 2;
print("position = " + entity.position + " (should be [0,2,0])");

var tmp = entity.position;
tmp[1] = 2;
entity.position = tmp;
print("position = " + entity.position + " (now is [0,2,0])");

entity.foo = [1,1,1];
entity.foo[1] = 2;
print("foo = " + entity.foo + " (as expected)");

The output of this script is (I define a print() function to log):

position = 0,0,0
position = 0,0,0 (should be [0,2,0])
position = 0,2,0 (now is [0,2,0])
foo = 1,2,1 ([1,2,1] as expected)

I'm stumped. What is going on?


问:
Retrieving all living people from wikipedia/wikidata
I have the following query from the WikiData query builder to fetch people, but I would like to fetch only people who are alive. I've tried playing around with date of death but I can't get anything that seems to work, I'm not very familiar with SPARQL.

```<code>SELECT DISTINCT ?item ?itemLabel WHERE {
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
  {
    SELECT DISTINCT ?item WHERE {
      ?item p:P31 ?statement0.
      ?statement0 (ps:P31/(wdt:P279*)) wd:Q215627.
    }
    LIMIT 100
  }
}

</code>```

https://query.wikidata.org

I'd optimally want to return the top 50,000 living people sorted by some sort of metric of popularity. If there's a way to do this by API or some other pre-built wrapper around Wikidata I'd appreciate that as well. Thanks!

Body:
I have the following query from the WikiData query builder to fetch people, but I would like to fetch only people who are alive. I've tried playing around with date of death but I can't get anything that seems to work, I'm not very familiar with SPARQL.

SELECT DISTINCT ?item ?itemLabel WHERE {
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
  {
    SELECT DISTINCT ?item WHERE {
      ?item p:P31 ?statement0.
      ?statement0 (ps:P31/(wdt:P279*)) wd:Q215627.
    }
    LIMIT 100
  }
}

https://query.wikidata.org

I'd optimally want to return the top 50,000 living people sorted by some sort of metric of popularity. If there's a way to do this by API or some other pre-built wrapper around Wikidata I'd appreciate that as well. Thanks!


问:
Is there a way to make a shadow with an arc in the middle?
How to draw the top shadow under the bottom navigation with a circular arc ?

The navigation

Like this shadow

I used cardview + cardUseCompatPadding=true but it doesn't work.

layer-list can only stack shapes, but I don’t know how to draw arc-shaped shadows


问:
Failed <<< osrf_testing_tools_cpp while compiling ROS from source
I was compiling ROS2 from source on Ubuntu. I received this error,

```<code>Failed   <<< osrf_testing_tools_cpp
</code>```

when running the command,

```<code>colcon build --symlink-install
</code>```

this is the full error

Is there any reason why I would be getting this error?

Body:
I was compiling ROS2 from source on Ubuntu. I received this error,

Failed   <<< osrf_testing_tools_cpp

when running the command,

colcon build --symlink-install

this is the full error

Is there any reason why I would be getting this error?


问:
Is there a way to give FloatSlider values from a dataframe column?
I'm working on Jupyter notebook, with recession data. I want to make a FloatSlider that takes values from a column(it contains 737 observations for Yield spreads between 1962-2020). Then I want to use that to interact it with another column and plot it. I want see how changing Yield spread on the slider will change the graph of the other variable.

I don't have any concrete code for this because I am still figuring if this is possible. Would appreciate any help!

So far I only have this:

```<code>def plot_func(m):
    #m = m_clean['Yield_Spread'].tolist()
    fig = plt.figure()
    ax = fig.subplots()
    ax.set_title('y_pred_Probit')
    fig1 = ax.plot(m_clean['Yield_Spread'], color='blue', label = '' , linewidth = 2)
    #ax2 = ax.twinx()
    fig2= ax.plot(m_clean['y_pred_Probit'],color='brown', label = 'y_pred_Probit', linewidth = 2)
    plt.show()

smoo = interact(plot_func, m = FloatSlider(min=0.0,max=1.0,step=0.5, continuous_update=True))
</code>```

but I need to assign m as the values of Yield_Spread and I also want it to be updated using an update function.

Body:
I'm working on Jupyter notebook, with recession data. I want to make a FloatSlider that takes values from a column(it contains 737 observations for Yield spreads between 1962-2020). Then I want to use that to interact it with another column and plot it. I want see how changing Yield spread on the slider will change the graph of the other variable.

I don't have any concrete code for this because I am still figuring if this is possible. Would appreciate any help!

So far I only have this:

def plot_func(m):
    #m = m_clean['Yield_Spread'].tolist()
    fig = plt.figure()
    ax = fig.subplots()
    ax.set_title('y_pred_Probit')
    fig1 = ax.plot(m_clean['Yield_Spread'], color='blue', label = '' , linewidth = 2)
    #ax2 = ax.twinx()
    fig2= ax.plot(m_clean['y_pred_Probit'],color='brown', label = 'y_pred_Probit', linewidth = 2)
    plt.show()

smoo = interact(plot_func, m = FloatSlider(min=0.0,max=1.0,step=0.5, continuous_update=True))

but I need to assign m as the values of Yield_Spread and I also want it to be updated using an update function.


问:
Pytorch model runtime error when testing U-Net
RuntimeError: Given transposed=1, weight of size [1024, 512, 2, 2], expected input[24, 512, 48, 48] to have 1024 channels, but got 512 channels instead

unet.py

```<code>import torch
from torch import nn
from torch.nn import functional as F

class Unet(nn.Module):

    def __init__(self, in_chans, out_chans):
        super().__init__()
        self.in_chans = in_chans
        self.out_chans = out_chans

        self.first_block = ConvBlock(in_chans, 64)
        self.down1 = Down(64, 128)
        self.down2 = Down(128, 256)
        self.down3 = Down(256, 512)
        self.down4 = Down(512, 1024)
        self.up1 = Up(1024, 512)
        self.up2 = Up(512, 256)
        self.up3 = Up(256, 128)
        self.up4 = Up(128, 64)
        self.last_block = nn.Conv2d(64, out_chans, kernel_size=1)

    def norm(self, x):
        b, h, w = x.shape
        x = x.view(b, h * w)
        mean = x.mean(dim=1).view(b, 1, 1)
        std = x.std(dim=1).view(b, 1, 1)
        x = x.view(b, h, w)
        return (x - mean) / std, mean, std

    def unnorm(self, x, mean, std):
        return x * std + mean

    def forward(self, input):
        input, mean, std = self.norm(input)
        input = input.unsqueeze(1)
        d1 = self.first_block(input)
        d2 = self.down1(d1)
        d3 = self.down2(d2)
        d4 = self.down3(d3)
        m0 = self.down4(d4)
        u1 = self.up1(m0, d4)
        u2 = self.up1(u1, d3)
        u3 = self.up1(u2, d2)
        u4 = self.up1(u3, d1)
        output = self.last_block(u4)
        output = output.squeeze(1)
        output = self.unnorm(output, mean, std)

        return output

class ConvBlock(nn.Module):

    def __init__(self, in_chans, out_chans):
        super().__init__()
        self.in_chans = in_chans
        self.out_chans = out_chans
        self.layers = nn.Sequential(
            nn.Conv2d(in_chans, out_chans, kernel_size=3, padding=1),
            nn.BatchNorm2d(out_chans),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_chans, out_chans, kernel_size=3, padding=1),
            nn.BatchNorm2d(out_chans),
            nn.ReLU(inplace=True)
        )

    def forward(self, x):
        return self.layers(x)

class Down(nn.Module):

    def __init__(self, in_chans, out_chans):
        super().__init__()
        self.in_chans = in_chans
        self.out_chans = out_chans
        self.layers = nn.Sequential(
            nn.MaxPool2d(2),
            ConvBlock(in_chans, out_chans)
        )

    def forward(self, x):
        return self.layers(x)

class Up(nn.Module):

    def __init__(self, in_chans, out_chans):
        super().__init__()
        self.in_chans = in_chans
        self.out_chans = out_chans
        self.up = nn.ConvTranspose2d(in_chans, in_chans // 2, kernel_size=2, stride=2)
        self.conv = ConvBlock(in_chans, out_chans)

    def forward(self, x, concat_input):
        x = self.up(x)
        concat_output = torch.cat([concat_input, x], dim=1)
        return self.conv(concat_output)
</code>```

train.py

```<code>import sys
sys.path.append("/content/drive/MyDrive/FastMRI")
import argparse
import shutil
from utils.learning.train_part import train
from pathlib import Path

def parse():
    parser = argparse.ArgumentParser(description='Train Unet on FastMRI challenge Images',
                                    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-g', '--GPU-NUM', type=int, default=0, help='GPU number to allocate')
    parser.add_argument('-b', '--batch-size', type=int, default=24, help='Batch size')
    parser.add_argument('-e', '--num-epochs', type=int, default=30, help='Number of epochs')
    parser.add_argument('-l', '--lr', type=float, default=1e-3, help='Learning rate')
    parser.add_argument('-r', '--report-interval', type=int, default=500, help='Report interval')
    parser.add_argument('-n', '--net-name', type=Path, default='test_Unet', help='Name of network')
    parser.add_argument('-t', '--data-path-train', type=Path, default='Train/', help='Directory of train data')
    parser.add_argument('-v', '--data-path-val', type=Path, default='Validation/', help='Directory of validation data')

    parser.add_argument('--in-chans', type=int, default=1, help='Size of input channels for network')
    parser.add_argument('--out-chans', type=int, default=1, help='Size of output channels for network')
    parser.add_argument('--input-key', type=str, default='image_input', help='Name of input key')
    parser.add_argument('--target-key', type=str, default='image_label', help='Name of target key')
    parser.add_argument('--max-key', type=str, default='max', help='Name of max key in attributes')

    args = parser.parse_args()
    return args

if __name__ == '__main__':
    args = parse()
    args.exp_dir = '../result' / args.net_name / 'checkpoints'
    args.val_dir = '../result' / args.net_name / 'reconstructions_val'
    args.main_dir = '../result' / args.net_name / __file__

    args.exp_dir.mkdir(parents=True, exist_ok=True)
    args.val_dir.mkdir(parents=True, exist_ok=True)

    train(args)
</code>```

Where is the problem?..

An error occurred while configuring the unet. I don't know where the problem is.
I want to solve the problem.

```<code>        self.first_block = ConvBlock(in_chans, 2)
        self.down1 = Down(2, 4)
        self.up1 = Up(4, 2)
        self.last_block = nn.Conv2d(2, out_chans, kernel_size=1)
</code>```
```<code>       d1 = self.first_block(input)
        m0 = self.down1(d1)
        u1 = self.up1(m0, d1)
        output = self.last_block(u1)
</code>```

There was no error when it was like this, but an error occurred when the value was increased.

Body:
RuntimeError: Given transposed=1, weight of size [1024, 512, 2, 2], expected input[24, 512, 48, 48] to have 1024 channels, but got 512 channels instead

unet.py

import torch
from torch import nn
from torch.nn import functional as F

class Unet(nn.Module):

    def __init__(self, in_chans, out_chans):
        super().__init__()
        self.in_chans = in_chans
        self.out_chans = out_chans

        self.first_block = ConvBlock(in_chans, 64)
        self.down1 = Down(64, 128)
        self.down2 = Down(128, 256)
        self.down3 = Down(256, 512)
        self.down4 = Down(512, 1024)
        self.up1 = Up(1024, 512)
        self.up2 = Up(512, 256)
        self.up3 = Up(256, 128)
        self.up4 = Up(128, 64)
        self.last_block = nn.Conv2d(64, out_chans, kernel_size=1)

    def norm(self, x):
        b, h, w = x.shape
        x = x.view(b, h * w)
        mean = x.mean(dim=1).view(b, 1, 1)
        std = x.std(dim=1).view(b, 1, 1)
        x = x.view(b, h, w)
        return (x - mean) / std, mean, std

    def unnorm(self, x, mean, std):
        return x * std + mean

    def forward(self, input):
        input, mean, std = self.norm(input)
        input = input.unsqueeze(1)
        d1 = self.first_block(input)
        d2 = self.down1(d1)
        d3 = self.down2(d2)
        d4 = self.down3(d3)
        m0 = self.down4(d4)
        u1 = self.up1(m0, d4)
        u2 = self.up1(u1, d3)
        u3 = self.up1(u2, d2)
        u4 = self.up1(u3, d1)
        output = self.last_block(u4)
        output = output.squeeze(1)
        output = self.unnorm(output, mean, std)

        return output

class ConvBlock(nn.Module):

    def __init__(self, in_chans, out_chans):
        super().__init__()
        self.in_chans = in_chans
        self.out_chans = out_chans
        self.layers = nn.Sequential(
            nn.Conv2d(in_chans, out_chans, kernel_size=3, padding=1),
            nn.BatchNorm2d(out_chans),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_chans, out_chans, kernel_size=3, padding=1),
            nn.BatchNorm2d(out_chans),
            nn.ReLU(inplace=True)
        )

    def forward(self, x):
        return self.layers(x)

class Down(nn.Module):

    def __init__(self, in_chans, out_chans):
        super().__init__()
        self.in_chans = in_chans
        self.out_chans = out_chans
        self.layers = nn.Sequential(
            nn.MaxPool2d(2),
            ConvBlock(in_chans, out_chans)
        )

    def forward(self, x):
        return self.layers(x)

class Up(nn.Module):

    def __init__(self, in_chans, out_chans):
        super().__init__()
        self.in_chans = in_chans
        self.out_chans = out_chans
        self.up = nn.ConvTranspose2d(in_chans, in_chans // 2, kernel_size=2, stride=2)
        self.conv = ConvBlock(in_chans, out_chans)

    def forward(self, x, concat_input):
        x = self.up(x)
        concat_output = torch.cat([concat_input, x], dim=1)
        return self.conv(concat_output)

train.py

import sys
sys.path.append("/content/drive/MyDrive/FastMRI")
import argparse
import shutil
from utils.learning.train_part import train
from pathlib import Path

def parse():
    parser = argparse.ArgumentParser(description='Train Unet on FastMRI challenge Images',
                                    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-g', '--GPU-NUM', type=int, default=0, help='GPU number to allocate')
    parser.add_argument('-b', '--batch-size', type=int, default=24, help='Batch size')
    parser.add_argument('-e', '--num-epochs', type=int, default=30, help='Number of epochs')
    parser.add_argument('-l', '--lr', type=float, default=1e-3, help='Learning rate')
    parser.add_argument('-r', '--report-interval', type=int, default=500, help='Report interval')
    parser.add_argument('-n', '--net-name', type=Path, default='test_Unet', help='Name of network')
    parser.add_argument('-t', '--data-path-train', type=Path, default='Train/', help='Directory of train data')
    parser.add_argument('-v', '--data-path-val', type=Path, default='Validation/', help='Directory of validation data')

    parser.add_argument('--in-chans', type=int, default=1, help='Size of input channels for network')
    parser.add_argument('--out-chans', type=int, default=1, help='Size of output channels for network')
    parser.add_argument('--input-key', type=str, default='image_input', help='Name of input key')
    parser.add_argument('--target-key', type=str, default='image_label', help='Name of target key')
    parser.add_argument('--max-key', type=str, default='max', help='Name of max key in attributes')

    args = parser.parse_args()
    return args

if __name__ == '__main__':
    args = parse()
    args.exp_dir = '../result' / args.net_name / 'checkpoints'
    args.val_dir = '../result' / args.net_name / 'reconstructions_val'
    args.main_dir = '../result' / args.net_name / __file__

    args.exp_dir.mkdir(parents=True, exist_ok=True)
    args.val_dir.mkdir(parents=True, exist_ok=True)

    train(args)

Where is the problem?..

An error occurred while configuring the unet. I don't know where the problem is.
I want to solve the problem.

        self.first_block = ConvBlock(in_chans, 2)
        self.down1 = Down(2, 4)
        self.up1 = Up(4, 2)
        self.last_block = nn.Conv2d(2, out_chans, kernel_size=1)

       d1 = self.first_block(input)
        m0 = self.down1(d1)
        u1 = self.up1(m0, d1)
        output = self.last_block(u1)

There was no error when it was like this, but an error occurred when the value was increased.


问:
How to recover pickled Keras histories?
Does anyone know how I can recover a list of Keras history objects that I saved to drive by pickling with the following code:

```<code>import pickle

with open("H:/hists", "wb") as fp:   #Pickling
     pickle.dump(hists, fp)
</code>```

Currently I'm trying :

```<code>with open("H:/hists", "rb") as fp:   # Unpickling
     hists = pickle.load(fp)
</code>```

but getting this error:

```<code>FileNotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ram://b3edea45-d0d4-442d-ab4f-b0c43a87d19e/variables/variables
 You may be trying to load on a different device from the computational device. Consider setting the `experimental_io_device` option in `tf.saved_model.LoadOptions` to the io_device such as '/job:localhost'.
</code>```

Which I believe is because the python kernel in which I saved the history object has been terminated and a new one started.

I now think that the best way to save histories is to convert them to DataFrames or numpy arrays and save those, but that's not possible now since the histories are no longer in memory. It took about 5 hours to produce the histories, so I'm hoping it's possible to recover them.

Title: How to recover pickled Keras histories?

Body:
Does anyone know how I can recover a list of Keras history objects that I saved to drive by pickling with the following code:

import pickle

with open("H:/hists", "wb") as fp:   #Pickling
     pickle.dump(hists, fp)

Currently I'm trying :

with open("H:/hists", "rb") as fp:   # Unpickling
     hists = pickle.load(fp)

but getting this error:

FileNotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ram://b3edea45-d0d4-442d-ab4f-b0c43a87d19e/variables/variables
 You may be trying to load on a different device from the computational device. Consider setting the `experimental_io_device` option in `tf.saved_model.LoadOptions` to the io_device such as '/job:localhost'.

Which I believe is because the python kernel in which I saved the history object has been terminated and a new one started.

I now think that the best way to save histories is to convert them to DataFrames or numpy arrays and save those, but that's not possible now since the histories are no longer in memory. It took about 5 hours to produce the histories, so I'm hoping it's possible to recover them.


问:
Copilot stopped working on vscode after trying multiple fixes
Randomly my copilot has stopped working (I still have time left on my free trial). The problem seems to be that no matter what I do I cannot get the pop up to authorise copilot to appear when installing the extension again. Does anyone have any idea why?

I've tried everything from:

Signing out of Github on vscode and signing back in.

Uninstalling vscode (removing .vscode folder; deleting the code folder under AppData/Roaming; deleting vscode)

Uninstalling the extension.

Multiple restarts.

Removing all git credentials from credential manager.

I'm on Windows 11.

I was playing around with the black formatter around the time it stopped working.


问:
Subprocess.call appears to modify (rsync) command inputs causing failure
I am attempting to write a python script that calls rsync to synchronize code between my vm and my local machine. I had done this successfully using subprocess.call to write from my local machine to my vm, but when I tried to write a command that would sync from my vm to my local machine, subprocess.call seems to erroneously duplicate text or modify the command in a way that doesn't make sense to me.

I've seen a number of posts about subprocess relating to whether a shell is expected / being used, but I tried running the command with both shell=True and shell=False` and saw the same weird command modification.

Here is what I am running:

command = ['rsync', '-avP', f'{user}@{host}:/home/{user}/Workspace/{remote_dir}', os.getcwd()])  # attempting to sync from a dir on my remote machine to my current directory on my local machine
print('command: ' + ' '.join(command))
subprocess.call(command)
```
<p>Here is the output (censored):</p>
```command: rsync -avP  benjieg@[hostname]:/home/benjieg/Workspace/maige[dirname] /Users/benjieg/Workspace
building file list ...
rsync: link_stat "/Users/benjieg/Workspace/benjieg@[hostname]:/home/benjieg/Workspace/[dirname]" failed: No such file or directory (2)
8383 files to consider

sent 181429 bytes  received 20 bytes  362898.00 bytes/sec
total size is 217164673  speedup is 1196.84
rsync error: some files could not be transferred (code 23) at /AppleInternal/Library/BuildRoots/810eba08-405a-11ed-86e9-6af958a02716/Library/Caches/com.apple.xbs/Sources/rsync/rsync/main.c(996) [sender=2.6.9]
```

If I run the command directly in my terminal, it works just fine. The mysterious thing that i'm seeing is that subprocess appears to append some extra path before my user name in the command. You can see this in the 'link stat' line in the output. I'm guessing this is why it's unable to find the directory. But I really can't figure out why it would do that.

Further, I tried moving out of the 'Workspace' directory on my local machine to home, and even more weird behavior ensued. It seemed to begin looking into all of the files on my local machine, even prompting dropbox to ask me if iterm2 had permission to access it. Why would this happen? Why would whatever subprocess is doing cause a search of my whole local file system? I'm really mystified by this seemingly random behavior.

I'm on MacOS 13.0.1 (22A400) using python 3.10.4

Body:
I am attempting to write a python script that calls rsync to synchronize code between my vm and my local machine. I had done this successfully using subprocess.call to write from my local machine to my vm, but when I tried to write a command that would sync from my vm to my local machine, subprocess.call seems to erroneously duplicate text or modify the command in a way that doesn't make sense to me.

I've seen a number of posts about subprocess relating to whether a shell is expected / being used, but I tried running the command with both shell=True and shell=False` and saw the same weird command modification.

Here is what I am running:

command = ['rsync', '-avP', f'{user}@{host}:/home/{user}/Workspace/{remote_dir}', os.getcwd()])  # attempting to sync from a dir on my remote machine to my current directory on my local machine
print('command: ' + ' '.join(command))
subprocess.call(command)

Here is the output (censored):

command: rsync -avP  benjieg@[hostname]:/home/benjieg/Workspace/maige[dirname] /Users/benjieg/Workspace
building file list ...
rsync: link_stat "/Users/benjieg/Workspace/benjieg@[hostname]:/home/benjieg/Workspace/[dirname]" failed: No such file or directory (2)
8383 files to consider

sent 181429 bytes  received 20 bytes  362898.00 bytes/sec
total size is 217164673  speedup is 1196.84
rsync error: some files could not be transferred (code 23) at /AppleInternal/Library/BuildRoots/810eba08-405a-11ed-86e9-6af958a02716/Library/Caches/com.apple.xbs/Sources/rsync/rsync/main.c(996) [sender=2.6.9]

If I run the command directly in my terminal, it works just fine. The mysterious thing that i'm seeing is that subprocess appears to append some extra path before my user name in the command. You can see this in the 'link stat' line in the output. I'm guessing this is why it's unable to find the directory. But I really can't figure out why it would do that.

Further, I tried moving out of the 'Workspace' directory on my local machine to home, and even more weird behavior ensued. It seemed to begin looking into all of the files on my local machine, even prompting dropbox to ask me if iterm2 had permission to access it. Why would this happen? Why would whatever subprocess is doing cause a search of my whole local file system? I'm really mystified by this seemingly random behavior.

I'm on MacOS 13.0.1 (22A400) using python 3.10.4


问:
How to configure Vite to run eslint after building?
I'm trying to run eslint AFTER vite bundles my code

```<code>import eslint from 'vite-plugin-eslint'

const outDir = 'out'
export default defineConfig({
  plugins: [
    {
    ...eslint({
      include: outDir + '/**/*',
      overrideConfigFile: '.eslintrc.js',
      fix: true,
      failOnError: true,
      failOnWarning: true
    }),
    enforce: 'post',
    apply: 'build',
    }
  ],

  build: {
    emptyOutDir: false,
    outDir,
    sourcemap: false,
    watch: {},
    minify: false,
    lib: {
      entry: {
        server_scripts : "./src/server/index.ts",
        startup_scripts : "./src/startup/index.ts",
        client_scripts : "./src/client/index.ts",
      },
      fileName: '[name]/bundle',
      formats: ["cjs"],
    },
  },
})
</code>```

here's what i have so far, i thought doing enforce:'post' should work but it doesn't, eslintrc already has the rules and doing eslint --fix manually fixes it. and i'm sure it's using the right eslint because it throws the error when i do lintOnStart option

Body:
I'm trying to run eslint AFTER vite bundles my code

import eslint from 'vite-plugin-eslint'

const outDir = 'out'
export default defineConfig({
  plugins: [
    {
    ...eslint({
      include: outDir + '/**/*',
      overrideConfigFile: '.eslintrc.js',
      fix: true,
      failOnError: true,
      failOnWarning: true
    }),
    enforce: 'post',
    apply: 'build',
    }
  ],

  build: {
    emptyOutDir: false,
    outDir,
    sourcemap: false,
    watch: {},
    minify: false,
    lib: {
      entry: {
        server_scripts : "./src/server/index.ts",
        startup_scripts : "./src/startup/index.ts",
        client_scripts : "./src/client/index.ts",
      },
      fileName: '[name]/bundle',
      formats: ["cjs"],
    },
  },
})

here's what i have so far, i thought doing enforce:'post' should work but it doesn't, eslintrc already has the rules and doing eslint --fix manually fixes it. and i'm sure it's using the right eslint because it throws the error when i do lintOnStart option


问:
TensorFlow Lite for Microcontrollers: Didn't find op for builtin opcode 'REDUCE_PROD' version '1'
I am using a Seeed Studio XIAO to play some machine learning.
I follow the tutorialhere

The model in this example seems to have an input size of [None, time_steps * num_features]. In its case, the input instance to the model is [1, 119 samples * 6 IMU features].

I could also run the .ino file on my Seeed Studio board without any errors.

However, I built and trained a model with an input size of [None, 30(time_steps), 6(num_features)].
Basically, my model just had Input layer (None, 30, 6), 2 dense layers, a flatten layer, and a final dense layer (None, 4).
I was able to convert the model to .tflite and .h. But when I loaded it to Arduino, the Serial Port showed error:

20:26:45.976 -> Didn't find op for builtin opcode 'REDUCE_PROD' version '1'. An older version of this builtin might be supported. Are you using an old TFLite binary with a newer model?
20:26:45.976 ->
20:26:45.976 -> Failed to get registration from op code REDUCE_PROD

Anyone has an idea?

I also noticed that Flatten() is not supported by tflite micro, then I used Reshape() in my model. However, same error was shown in the Serial Port.

In TensorFlow Lite for Microcontroller applications, what should I do to run a model with an input size [None, time_steps, num_features]?