问:
Could not parse the Android Application Module's Gradle config ,While connecting to Firebase
I am getting this error ,While connecting the app to firebase from the firebase assistant in Android Studio. Error message -Could not parse the Android Application Module's Gradle config. Resolve gradle build issues and/or resync. I tried every posted Solution from Stack overflow and had watched many you tube videos , even cleared the gradle caches and also Updated the IDE. Even There is No error or Warning in my Gradle build files.
this my gradle.propertyes(proj):</p>
```<code>  # Specifies the JVM arguments used for the daemon process.
  # The setting is particularly useful for tweaking memory settings.org.gradle.jvmargs=-Xmx1536m

  # When configured, Gradle will run in incubating parallel mode.
  # This option should only be used with decoupled projects. More details, visit
  #http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
  # org.gradle.parallel=true

  # AndroidX package structure to make it clearer which packages are bundled with the
  # Android operating system, and which are packaged with your app's APK
  # https://developer.android.com/topic/libraries/support-library/androidx-rn
  android.useAndroidX=true
  android.enableJetifier=true
  android.debug.obsoleteApi=true
</code>```

Body:
I am getting this error ,While connecting the app to firebase from the firebase assistant in Android Studio. Error message -Could not parse the Android Application Module's Gradle config. Resolve gradle build issues and/or resync. I tried every posted Solution from Stack overflow and had watched many you tube videos , even cleared the gradle caches and also Updated the IDE. Even There is No error or Warning in my Gradle build files.
this my gradle.propertyes(proj):

  # Specifies the JVM arguments used for the daemon process.
  # The setting is particularly useful for tweaking memory settings.org.gradle.jvmargs=-Xmx1536m

  # When configured, Gradle will run in incubating parallel mode.
  # This option should only be used with decoupled projects. More details, visit
  #http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
  # org.gradle.parallel=true

  # AndroidX package structure to make it clearer which packages are bundled with the
  # Android operating system, and which are packaged with your app's APK
  # https://developer.android.com/topic/libraries/support-library/androidx-rn
  android.useAndroidX=true
  android.enableJetifier=true
  android.debug.obsoleteApi=true


来源: stackexchange

问:
Jackon JSON Adding deserializer module doesn't work, but annotation on class does
I am trying to implement a custom deserializer and when I try to install it on the ObjectMapper it never gets invoked, but when I use it directly as an annotation on the class, it does. Can someone explain why and how I can actually install it on the object mapper itself?

This is never invoked

        val bug = ObjectMapper().registerModule(KotlinModule.Builder().build())
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .registerModule(SimpleModule().addDeserializer(Bug::class.java, BugDeserializer()))
            .readValue(bugStream, Bug::class.java)

data class Bug(

    @JsonProperty("rptno")
    val id: Long,

    @JsonProperty("status")
    @JsonDeserialize(using = StatusDeserializer::class)
    val status: Status,
    @JsonProperty("reported_date")
    val reportedDate:Instant,
    @JsonProperty("updated_date")
    val updatedDate: Instant,
//    val pillar: String = "",
    @JsonProperty("product_id")
    @JsonDeserialize(using = ProductDeserializer::class)
    val product: Product,
    @JsonProperty("assignee")
    val assignee: String,
//    val serviceRequests: List<Long> = listOf(),

    @JsonProperty("subject")
    val title: String,
    @JsonProperty("bug_type")
    val type: String
)
```
<p>But, this does:</p>
<pre class="lang-kotlin prettyprint-override"><code>        val bug = ObjectMapper().registerModule(KotlinModule.Builder().build())
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .readValue(bugStream, Bug::class.java)

@JsonDeserialize(using = BugDeserializer::class)
data class Bug(

    @JsonProperty("rptno")
    val id: Long,

    @JsonProperty("status")
    @JsonDeserialize(using = StatusDeserializer::class)
    val status: Status,
    @JsonProperty("reported_date")
    val reportedDate:Instant,
    @JsonProperty("updated_date")
    val updatedDate: Instant,
//    val pillar: String = "",
    @JsonProperty("product_id")
    @JsonDeserialize(using = ProductDeserializer::class)
    val product: Product,
    @JsonProperty("assignee")
    val assignee: String,
//    val serviceRequests: List<Long> = listOf(),

    @JsonProperty("subject")
    val title: String,
    @JsonProperty("bug_type")
    val type: String
)

```kotlin
```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement a custom deserializer and when I try to install it on the ObjectMapper it never gets invoked, but when I use it directly as an annotation on the class, it does. Can someone explain why and how I can actually install it on the object mapper itself?

This is never invoked

        val bug = ObjectMapper().registerModule(KotlinModule.Builder().build())
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .registerModule(SimpleModule().addDeserializer(Bug::class.java, BugDeserializer()))
            .readValue(bugStream, Bug::class.java)

data class Bug(

    @JsonProperty("rptno")
    val id: Long,

    @JsonProperty("status")
    @JsonDeserialize(using = StatusDeserializer::class)
    val status: Status,
    @JsonProperty("reported_date")
    val reportedDate:Instant,
    @JsonProperty("updated_date")
    val updatedDate: Instant,
//    val pillar: String = "",
    @JsonProperty("product_id")
    @JsonDeserialize(using = ProductDeserializer::class)
    val product: Product,
    @JsonProperty("assignee")
    val assignee: String,
//    val serviceRequests: List<Long> = listOf(),

    @JsonProperty("subject")
    val title: String,
    @JsonProperty("bug_type")
    val type: String
)

But, this does:

        val bug = ObjectMapper().registerModule(KotlinModule.Builder().build())
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .readValue(bugStream, Bug::class.java)

@JsonDeserialize(using = BugDeserializer::class)
data class Bug(

    @JsonProperty("rptno")
    val id: Long,

    @JsonProperty("status")
    @JsonDeserialize(using = StatusDeserializer::class)
    val status: Status,
    @JsonProperty("reported_date")
    val reportedDate:Instant,
    @JsonProperty("updated_date")
    val updatedDate: Instant,
//    val pillar: String = "",
    @JsonProperty("product_id")
    @JsonDeserialize(using = ProductDeserializer::class)
    val product: Product,
    @JsonProperty("assignee")
    val assignee: String,
//    val serviceRequests: List<Long> = listOf(),

    @JsonProperty("subject")
    val title: String,
    @JsonProperty("bug_type")
    val type: String
)

```kotlin


问:
Altair modified rendering function not working
I have found a rendering function to render some chart embedded in Jupyter

```<code>def render(chart, id="vega-chart"):
chart_str = """
<div id="{id}"></div><script>
require(["vega-embed"], function(vg_embed) {{
    const spec = {chart};
    vg_embed("#{id}", spec, {{defaultStyle: true}}).catch(console.warn);
    console.log("anything?");
}});
console.log("really...anything?");
</script>
"""
return HTML(
    chart_str.format(
        id=id,
        chart=json.dumps(chart) if isinstance(chart, dict) else chart.to_json(indent=None)
    )
)
</code>```

however when I try to use it and render a chart it's not returning anything

```<code>chart=alt.Chart(data).mark_bar().encode(
    alt.X('ram', bin=True),
    y='count(*):Q',
    color='price_range:N',
).facet(column='price_range:N')

render(chart)
</code>```

I could use chart.show() (with altair_viewer) but that renders the chart into another page and that is not ideal.

Body:
I have found a rendering function to render some chart embedded in Jupyter

def render(chart, id="vega-chart"):
chart_str = """

"""
return HTML(
    chart_str.format(
        id=id,
        chart=json.dumps(chart) if isinstance(chart, dict) else chart.to_json(indent=None)
    )
)

however when I try to use it and render a chart it's not returning anything

chart=alt.Chart(data).mark_bar().encode(
    alt.X('ram', bin=True),
    y='count(*):Q',
    color='price_range:N',
).facet(column='price_range:N')

render(chart)

I could use chart.show() (with altair_viewer) but that renders the chart into another page and that is not ideal.


问:
Why in React-Native-Paper TextInput.Icon not working when extracted to custom component
In react-native-paper if I am using TextInput with Icon like this it works fine.

<TextInput
      label="Password"
      right={<TextInput.Icon icon="eye" />}
/>
```
<p>But if I export the Icon part to custom element it stop showing the Icon.
Am I doing something wrong here?</p>
<pre class="lang-js prettyprint-override"><code>const MyCustomIcon = () => {
  return <TextInput.Icon icon="eye" />;
};

const MyComponent = () => {

  return (
    <TextInput
      label="Password"
      right={<MyCustomIcon />}
    />
  );
};

export default MyComponent;
</code>```

Thanks.

Body:
In react-native-paper if I am using TextInput with Icon like this it works fine.

<TextInput
      label="Password"
      right={<TextInput.Icon icon="eye" />}
/>

But if I export the Icon part to custom element it stop showing the Icon.
Am I doing something wrong here?

const MyCustomIcon = () => {
  return <TextInput.Icon icon="eye" />;
};

const MyComponent = () => {

  return (
    <TextInput
      label="Password"
      right={<MyCustomIcon />}
    />
  );
};

export default MyComponent;

Thanks.


问:
How do I scroll a PDF that is "embedded"
I am opening a local PDF document using WebKitX which uses Chromium Embedded Framework (CEF3).

I would like to scroll this PDF up and down programmatically.

When I inspect the page's source code, I see this:

```<code><!DOCTYPE html><html><head><style media="screen" id="webkitx"></style></head><body style="height: 100%; width: 100%; overflow: hidden; margin:0px; background-color: rgb(38, 38, 38);" contenteditable="true"><embed style="position:absolute; left: 0; top: 0;" width="100%" height="100%" src="about:blank" type="application/pdf" internalid="F1CDFDFAE5B2264D8058FFBDF81477C9"></body></html>
</code>```

The following does NOT work:

```<code>window.scrollBy(0, 50);

document.documentElement.scrollTop += 50;
</code>```

Is there any way to scroll this PDF up and down without changing the html code and putting it into an iFrame or so?

Body:
I am opening a local PDF document using WebKitX which uses Chromium Embedded Framework (CEF3).

I would like to scroll this PDF up and down programmatically.

When I inspect the page's source code, I see this:

<!DOCTYPE html><embed style="position:absolute; left: 0; top: 0;" width="100%" height="100%" src="about:blank" type="application/pdf" internalid="F1CDFDFAE5B2264D8058FFBDF81477C9">

The following does NOT work:

window.scrollBy(0, 50);

document.documentElement.scrollTop += 50;

Is there any way to scroll this PDF up and down without changing the html code and putting it into an iFrame or so?


问:
ES6 errors in CodeSanbox are not showed
i want check some Js code in codesandbox vanilaJs template:

```<code>console.log(x);
let x = 5;

expect - Reference Error
actual - undefined (same with const)
</code>```

or

```<code>let x = 5
(function(){
   console.log(x);
    let x = 6;
})();

expect - Reference Error
actual - undefined

</code>```

Why i don't get expected result and how to achieve this?

Title: ES6 errors in CodeSanbox are not showed

Body:
i want check some Js code in codesandbox vanilaJs template:

console.log(x);
let x = 5;

expect - Reference Error
actual - undefined (same with const)

or

let x = 5
(function(){
   console.log(x);
    let x = 6;
})();

expect - Reference Error
actual - undefined

Why i don't get expected result and how to achieve this?


问:
Vue.js - Element Plus - How to test el-dropdown component
I have a problem that I can't trigger el-dropdown menu. I've followed the testing approach done in element-plus repository but couldn't able to simulate mouseenter event and see whether dropdown menu is opened.

my code can be found below.

<template>
  <el-dropdown>
    <el-icon>
      <MoreFilled/>
    </el-icon>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item>Send a message</el-dropdown-item>
        <el-dropdown-item>Report</el-dropdown-item>
        <el-dropdown-item>Block</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

```
<p>and my test code can be found here</p>
<pre class="lang-js prettyprint-override"><code>import { mount } from "@vue/test-utils";
import { nextTick } from "vue";
import { describe, it, expect, beforeEach, afterEach, vi  } from "vitest";
import EntryCardFooterDropdown from "../EntryCardFooterDropdown.vue";
import { ElTooltip } from "element-plus";

describe('EntryCardFooterDropdown', () => {
  it('render', async () => {
    const wrapper = mount(EntryCardFooterDropdown)
    await nextTick()

    const content = wrapper.findComponent(ElTooltip).vm as InstanceType<typeof ElTooltip>
    vi.useFakeTimers();

    const triggerElm = wrapper.find('.el-tooltip__trigger');
    expect(content.open).toBe(false);
    await triggerElm.trigger('mouseenter');

    vi.runAllTimers();
    expect(content.open).toBe(true);
  })
})
</code>```

Body:
I have a problem that I can't trigger el-dropdown menu. I've followed the testing approach done in element-plus repository but couldn't able to simulate mouseenter event and see whether dropdown menu is opened.

my code can be found below.

<template>
  <el-dropdown>
    <el-icon>
      <MoreFilled/>
    </el-icon>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item>Send a message</el-dropdown-item>
        <el-dropdown-item>Report</el-dropdown-item>
        <el-dropdown-item>Block</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

and my test code can be found here

import { mount } from "@vue/test-utils";
import { nextTick } from "vue";
import { describe, it, expect, beforeEach, afterEach, vi  } from "vitest";
import EntryCardFooterDropdown from "../EntryCardFooterDropdown.vue";
import { ElTooltip } from "element-plus";

describe('EntryCardFooterDropdown', () => {
  it('render', async () => {
    const wrapper = mount(EntryCardFooterDropdown)
    await nextTick()

    const content = wrapper.findComponent(ElTooltip).vm as InstanceType<typeof ElTooltip>
    vi.useFakeTimers();

    const triggerElm = wrapper.find('.el-tooltip__trigger');
    expect(content.open).toBe(false);
    await triggerElm.trigger('mouseenter');

    vi.runAllTimers();
    expect(content.open).toBe(true);
  })
})


问:
ReplaySubject as a cron scheduler
I have the desktop app based on Angular and need to run some jobs every workday at 2:00 AM, kind of 0 2 * * 1-5.

Can I use ReplaySubject somehow for it?

ReplaySubject has an API:

```<code>constructor(bufferSize?: number, windowTime?: number, scheduler?: SchedulerLike);

export interface SchedulerLike {
    now(): number;
    schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay?: number, state?: T): Subscription;
}

export interface SchedulerAction<T> extends Subscription {
    schedule(state?: T, delay?: number): Subscription;
}
</code>```

Can I use it to solve my task?

Title: ReplaySubject as a cron scheduler

Body:
I have the desktop app based on Angular and need to run some jobs every workday at 2:00 AM, kind of 0 2 * * 1-5.

Can I use ReplaySubject somehow for it?

ReplaySubject has an API:

constructor(bufferSize?: number, windowTime?: number, scheduler?: SchedulerLike);

export interface SchedulerLike {
    now(): number;
    schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay?: number, state?: T): Subscription;
}

export interface SchedulerAction<T> extends Subscription {
    schedule(state?: T, delay?: number): Subscription;
}

Can I use it to solve my task?


问:
Trying to make a smooth rotation script
I'm kind of new in learning Unity scripting and currently i'm writing a script where by pressing the Space key together with A or D key would do some sort of a "dash" movement by rotating faster.

In the gif below I show the basic A and D movement without dashing movement. What i've done is that i've put an empty with the script and an object parented to the rotating empty.

the example

What I wanted to do is that whenever the player wanted to go faster on a direction, it would "dash" on the left by pressing A+Space and on the right by pressing D+Space. I kind of managed to do this thing with this code (where rotSpeed is the rotation speed and dashAmount is the speed added to make the "dash"):

```<code>transform.Rotate(dashAmount + rotSpeed * Time.deltaTime, 0f, 0f);
</code>```

Of course, this worked but the cube would just teleport instead of "dashing" smoothly to the left or right. Then i found out about Quaternion.Lerp but the code i wrote doesn't really work correctly (destinationRot is the final rotation and dashSpeed is set to 0.8f)

```<code>if ((Input.GetKey(KeyCode.Space)) && (Input.GetKey(KeyCode.D)))
 {
   Quaternion destinationRot = Quaternion.Euler(transform.rotation.x + dashAmount, 0f, 0f);
                 transform.rotation = Quaternion.Lerp(transform.rotation, destinationRot, Time.deltaTime * dashSpeed);

}
</code>```

How can I fix this?

Title: Trying to make a smooth rotation script

Body:
I'm kind of new in learning Unity scripting and currently i'm writing a script where by pressing the Space key together with A or D key would do some sort of a "dash" movement by rotating faster.

In the gif below I show the basic A and D movement without dashing movement. What i've done is that i've put an empty with the script and an object parented to the rotating empty.

the example

What I wanted to do is that whenever the player wanted to go faster on a direction, it would "dash" on the left by pressing A+Space and on the right by pressing D+Space. I kind of managed to do this thing with this code (where rotSpeed is the rotation speed and dashAmount is the speed added to make the "dash"):

transform.Rotate(dashAmount + rotSpeed * Time.deltaTime, 0f, 0f);

Of course, this worked but the cube would just teleport instead of "dashing" smoothly to the left or right. Then i found out about Quaternion.Lerp but the code i wrote doesn't really work correctly (destinationRot is the final rotation and dashSpeed is set to 0.8f)

if ((Input.GetKey(KeyCode.Space)) && (Input.GetKey(KeyCode.D)))
 {
   Quaternion destinationRot = Quaternion.Euler(transform.rotation.x + dashAmount, 0f, 0f);
                 transform.rotation = Quaternion.Lerp(transform.rotation, destinationRot, Time.deltaTime * dashSpeed);

}

How can I fix this?


问:
Flask-WTF StopValidation after default validator fails
I am adding a field and validating it against IPAddress WTForms' validator:

from ipaddress import ip_network

from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired, IPAddress, ValidationError, StopValidation

class CreateForm(FlaskForm):
    ip = StringField(
        label="IP Address",
        validators=[DataRequired(), IPAddress(ipv4=True)],
        render_kw={"autocomplete": False, "placeholder": "IP Address"},
    )
...
```
<p>However, some extra custom validations are required and are defined as:</p>
<pre class="lang-py prettyprint-override"><code>...
def validate_ip(self, ip):
        if not ip_network(ip.data).overlaps(ip_network('192.168.1.1/24')):
            raise ValidationError(f"{ip.data} is out of bound for 192.168.1.1!")
...
</code>```

When I add an IP address for example 192.168.1.256 which is obviously an invalid IP, The validation is not stopped because StopValidation is not called and I get the exception raised in the browser, not under the field I want.

A workaround to this is to create a custom validator, the same as the built-in validator, before any other validations and raise the StopValidation:

...
def validate_ip(self, ip):
         try:
            ip_address(ip.data)
        except Exception as e:
            raise StopValidation(e) from e
        if not ip_network(ip.data).overlaps(ip_network('192.168.1.1/24')):
            raise ValidationError(f"{ip.data} is out of bound for 192.168.1.1!")
...
```

The question is how can I stop validation on the first validation error which is the default built-in validator in this case? If the default validation is invalid, stop the validation chain immediately, else continue with the rest of the validation rules.

I feel that recreating the built-in validator as a custom validator is a bit DRY.

Body:
I am adding a field and validating it against IPAddress WTForms' validator:

from ipaddress import ip_network

from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired, IPAddress, ValidationError, StopValidation

class CreateForm(FlaskForm):
    ip = StringField(
        label="IP Address",
        validators=[DataRequired(), IPAddress(ipv4=True)],
        render_kw={"autocomplete": False, "placeholder": "IP Address"},
    )
...

However, some extra custom validations are required and are defined as:

...
def validate_ip(self, ip):
        if not ip_network(ip.data).overlaps(ip_network('192.168.1.1/24')):
            raise ValidationError(f"{ip.data} is out of bound for 192.168.1.1!")
...

When I add an IP address for example 192.168.1.256 which is obviously an invalid IP, The validation is not stopped because StopValidation is not called and I get the exception raised in the browser, not under the field I want.

A workaround to this is to create a custom validator, the same as the built-in validator, before any other validations and raise the StopValidation:

...
def validate_ip(self, ip):
         try:
            ip_address(ip.data)
        except Exception as e:
            raise StopValidation(e) from e
        if not ip_network(ip.data).overlaps(ip_network('192.168.1.1/24')):
            raise ValidationError(f"{ip.data} is out of bound for 192.168.1.1!")
...

The question is how can I stop validation on the first validation error which is the default built-in validator in this case? If the default validation is invalid, stop the validation chain immediately, else continue with the rest of the validation rules.

I feel that recreating the built-in validator as a custom validator is a bit DRY.


问:
initialize VSPackage at startup
I need my package to get initialized when VS starts, without having to trigger it by invoking  the Command I implemented in it.

I try those, but that does not work.

```<code>[ProvideAutoLoad(UIContextGuids80.SolutionExists)]
[ProvideAutoLoad(VSConstants.UICONTEXT.NoSolution_string)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionHasMultipleProjects_string)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionHasSingleProject_string)]
</code>```

public sealed class VSIXProject1Package : AsyncPackage
<

My package is loaded, but the InitializeAsync method won't be called until I click on my command (command1) in the tools menu.

Title: initialize VSPackage at startup

Body:
I need my package to get initialized when VS starts, without having to trigger it by invoking  the Command I implemented in it.

I try those, but that does not work.

[ProvideAutoLoad(UIContextGuids80.SolutionExists)]
[ProvideAutoLoad(VSConstants.UICONTEXT.NoSolution_string)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionHasMultipleProjects_string)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionHasSingleProject_string)]

public sealed class VSIXProject1Package : AsyncPackage
<

My package is loaded, but the InitializeAsync method won't be called until I click on my command (command1) in the tools menu.


问:
Timeout Error while sending an email using my mail client software
im getting a AttributeError when i want to send a message using this mail client software that im working on. can anyone tell how to fix this error. here is the functions for the send email:

```<code>def compose_email(self):
    # Create a dialog to compose a new email
    dialog = QDialog(self)
    dialog.setWindowTitle('Compose Email')
    # Set up the form layout
    form = QFormLayout()
    # Add fields for the recipient, subject, and message body
    self.recipient_field = QLineEdit(dialog)
    form.addRow('To:', self.recipient_field)
    self.subject_field = QLineEdit(dialog)
    form.addRow('Subject:', self.subject_field)
    self.message_field = QTextEdit(dialog)
    form.addRow('Message:', self.message_field)
    # Add a "Add Attachment" button
    self.add_attachment_button = QPushButton('Add Attachment', dialog)
    self.add_attachment_button.clicked.connect(self.add_attachment)
    form.addRow(self.add_attachment_button)
    # Add a "Send" button and a "Cancel" button
    buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, dialog)
    buttons.accepted.connect(dialog.accept)
    buttons.rejected.connect(dialog.reject)
    form.addRow(buttons)
    # Set the layout of the dialog
    dialog.setLayout(form)
    # Show the dialog and get the result
    result = dialog.exec_()

        # If the user clicked the "Send" button, send the email
    try:
     if result == QDialog.Accepted:
        recipient = self.recipient_field.text()
        subject = self.subject_field.text()
        message = self.message_field.toPlainText()
        attachments = self.attachments
        self.send_email(recipient, subject, message, attachments)
    except Exception as e:
     print("if user clicked An error occurred while sending the message:", e)

def add_attachment(self):
    # Open a file dialog to select an attachment
    options = QFileDialog.Options()
    options |= QFileDialog.ReadOnly
    file_name, _ = QFileDialog.getOpenFileName(self, 'Select Attachment', '',
                                               'All Files (*);;Images (*.png *.xpm *.jpg *.bmp);;Videos (*.mp4 *.avi *.mov)',
                                               options=options)
    try:
     if file_name:
        # Add the selected file to the attachments list
        self.attachments.append(file_name)
    except Exception as e:
        print("attach An error occurred while sending the message:", e)
def send_email(self, recipient, subject, message, attachments):
    # Connect to the SMTP server
    try:
        smtp_server = smtplib.SMTP('smtp.gmx.com',587)
        smtp_server.login(self.mailbox.username, self.mailbox.password)
    except Exception as e:
        # Display an error message if the login failed
        QMessageBox.critical(self, 'Error', 'Failed to connect to the SMTP server'+ e)
        return

    # Create the email message
    msg = email.message.EmailMessage()
    msg['From'] = self.mailbox.user
    msg['To'] = recipient
    msg['Subject'] = subject
    msg.set_content(message)
    # Add the attachments to the message
    for file_name in attachments:
        with open(file_name, 'rb') as f:
            file_data = f.read()
            file_name = os.path.basename(file_name)
            msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

    # Send the email
    try:
        smtp_server.send_message(msg)
    except Exception as e:
        # Display an error message if the send failed
        QMessageBox.critical(self, 'Error', f'Failed to send the email: {e}')
        return

    # Close the connection to the SMTP server
    smtp_server.quit()

    # Display a success message///////
    QMessageBox.information(self, 'Success', 'The email was sent successfully')
</code>```

I Will be thankful if anyone can be help to fix it
i tried to debug the code by adding print statements the and its printing the subject and recepient, i guess its with the attachment, but i dont how to fix it and im not its because of it. i tried sending with and without attachments and im still getting this error. the authentication with SMTP server is working fine.
here is the error message i am getting: An error occurred while sending the message: can only concatenate str (not "AttributeError") to str

Body:
im getting a AttributeError when i want to send a message using this mail client software that im working on. can anyone tell how to fix this error. here is the functions for the send email:

def compose_email(self):
    # Create a dialog to compose a new email
    dialog = QDialog(self)
    dialog.setWindowTitle('Compose Email')
    # Set up the form layout
    form = QFormLayout()
    # Add fields for the recipient, subject, and message body
    self.recipient_field = QLineEdit(dialog)
    form.addRow('To:', self.recipient_field)
    self.subject_field = QLineEdit(dialog)
    form.addRow('Subject:', self.subject_field)
    self.message_field = QTextEdit(dialog)
    form.addRow('Message:', self.message_field)
    # Add a "Add Attachment" button
    self.add_attachment_button = QPushButton('Add Attachment', dialog)
    self.add_attachment_button.clicked.connect(self.add_attachment)
    form.addRow(self.add_attachment_button)
    # Add a "Send" button and a "Cancel" button
    buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, dialog)
    buttons.accepted.connect(dialog.accept)
    buttons.rejected.connect(dialog.reject)
    form.addRow(buttons)
    # Set the layout of the dialog
    dialog.setLayout(form)
    # Show the dialog and get the result
    result = dialog.exec_()

        # If the user clicked the "Send" button, send the email
    try:
     if result == QDialog.Accepted:
        recipient = self.recipient_field.text()
        subject = self.subject_field.text()
        message = self.message_field.toPlainText()
        attachments = self.attachments
        self.send_email(recipient, subject, message, attachments)
    except Exception as e:
     print("if user clicked An error occurred while sending the message:", e)

def add_attachment(self):
    # Open a file dialog to select an attachment
    options = QFileDialog.Options()
    options |= QFileDialog.ReadOnly
    file_name, _ = QFileDialog.getOpenFileName(self, 'Select Attachment', '',
                                               'All Files (*);;Images (*.png *.xpm *.jpg *.bmp);;Videos (*.mp4 *.avi *.mov)',
                                               options=options)
    try:
     if file_name:
        # Add the selected file to the attachments list
        self.attachments.append(file_name)
    except Exception as e:
        print("attach An error occurred while sending the message:", e)
def send_email(self, recipient, subject, message, attachments):
    # Connect to the SMTP server
    try:
        smtp_server = smtplib.SMTP('smtp.gmx.com',587)
        smtp_server.login(self.mailbox.username, self.mailbox.password)
    except Exception as e:
        # Display an error message if the login failed
        QMessageBox.critical(self, 'Error', 'Failed to connect to the SMTP server'+ e)
        return

    # Create the email message
    msg = email.message.EmailMessage()
    msg['From'] = self.mailbox.user
    msg['To'] = recipient
    msg['Subject'] = subject
    msg.set_content(message)
    # Add the attachments to the message
    for file_name in attachments:
        with open(file_name, 'rb') as f:
            file_data = f.read()
            file_name = os.path.basename(file_name)
            msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

    # Send the email
    try:
        smtp_server.send_message(msg)
    except Exception as e:
        # Display an error message if the send failed
        QMessageBox.critical(self, 'Error', f'Failed to send the email: {e}')
        return

    # Close the connection to the SMTP server
    smtp_server.quit()

    # Display a success message///////
    QMessageBox.information(self, 'Success', 'The email was sent successfully')

I Will be thankful if anyone can be help to fix it
i tried to debug the code by adding print statements the and its printing the subject and recepient, i guess its with the attachment, but i dont how to fix it and im not its because of it. i tried sending with and without attachments and im still getting this error. the authentication with SMTP server is working fine.
here is the error message i am getting: An error occurred while sending the message: can only concatenate str (not "AttributeError") to str


问:
How to convert html table to a csv file python?

I have a python script like this: I can login in to web with my login and password, but i need to convert html table to csv.

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd

login_url = 'myurl'
data = {
    '_username': 'myusername',
    '_password': 'mypassvord'
}

with requests.Session() as s:
    response = s.post(login_url , data)
    index_page = s.get('myurl/link')
    soup = BeautifulSoup(index_page.content, "html.parser")
    print(soup)
    print(index_page)
    table = soup.findAll("table class", {"class": "table hover"})
    print(table)

</code>```

Print(index_page) return Response[200] so it´s OK.

But I want to conert html table to CSV file.

```<code> table = soup.find_all("table class", {"class": "table hover"})
</code>```

returns []

Where I am doing wrong?

I can't get a table from HTML.

Body:
I have a python script like this: I can login in to web with my login and password, but i need to convert html table to csv.

import requests
from bs4 import BeautifulSoup
import pandas as pd

login_url = 'myurl'
data = {
    '_username': 'myusername',
    '_password': 'mypassvord'
}

with requests.Session() as s:
    response = s.post(login_url , data)
    index_page = s.get('myurl/link')
    soup = BeautifulSoup(index_page.content, "html.parser")
    print(soup)
    print(index_page)
    table = soup.findAll("table class", {"class": "table hover"})
    print(table)

Print(index_page) return Response[200] so it´s OK.

But I want to conert html table to CSV file.

 table = soup.find_all("table class", {"class": "table hover"})

returns []

Where I am doing wrong?

I can't get a table from HTML.


问:
Is it possible to get a diagnostic's arguments using the JavaCompiler Interface?
I'm using the JavaCompiler Interface to compile source code files from within a Java program. I've successfully written code that captures the errors that exist in the source code file. I'm now trying to access the arguments of the diagnostic (for example, a ';' is a diagnostic's argument when that diagnostic represents a missing ';' at the end of a line). I was wondering if there is a way I can access these arguments? My goal is to use these arguments to print custom error messages for the compiler errors in the source code to the terminal.

My code is as follows:

```<code>JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<>();

try (StandardJavaFileManager fm = compiler.getStandardFileManager(dc, null, null)) {
    File file = new File("Test.java");
    Iterable<? extends JavaFileObject> sources = fm.getJavaFileObjectsFromFiles(Arrays.asList(file));
    JavaCompiler.CompilationTask task = compiler.getTask(null, fm, dc, null, null, sources);
    task.call();
}
if (!dc.getDiagnostics().isEmpty()) {
    for (Diagnostic <? extends JavaFileObject> d: dc.getDiagnostics()) {
        System.out.println(d.getCode());
        System.out.format("Line: %d, %s in %s \n",
            d.getLineNumber(),
            d.getMessage(null),
            d.getSource().getName());
            System.out.println(d.toString());
    }
    System.exit(1);
}
</code>```

I've tried looking into the interface a bit myself, and I've seen that the diagnostics returned from my JavaCompiler via the DiagnosticCollector.getDiagnostics() method are of dynamic type ClientCodeWrapper/DiagnosticSourceUnwrapper, which has a JCDiagnostic field that has a getArgs() method as desired, but this JCDiagnostic field is inaccessible from my program.
I was thinking there might be some way to unwrap/cast the ClientCodeWrapper/DiagnosticSourceUnwrapper so as to access the JCDiagnostic field and use its getArgs() method, but I was unable to do so, as I ran into ClassCastExceptions and inaccessible types.

I also tried making my own implementation of the Diagnostic Interface, so as to write my own getArgs() method, but I wasn't able to successfully implement a class that would get the arguments of the diagnostic and also be compatible with the JavaCompiler Interfaces as I was currently using them.
I could see this line of thinking also leading to a solution, but I wasn't able to make it work myself.

I was also thinking that perhaps there is another API/framework that would be better to achieve my goal.

Thank you in advance.

Body:
I'm using the JavaCompiler Interface to compile source code files from within a Java program. I've successfully written code that captures the errors that exist in the source code file. I'm now trying to access the arguments of the diagnostic (for example, a ';' is a diagnostic's argument when that diagnostic represents a missing ';' at the end of a line). I was wondering if there is a way I can access these arguments? My goal is to use these arguments to print custom error messages for the compiler errors in the source code to the terminal.

My code is as follows:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<>();

try (StandardJavaFileManager fm = compiler.getStandardFileManager(dc, null, null)) {
    File file = new File("Test.java");
    Iterable<? extends JavaFileObject> sources = fm.getJavaFileObjectsFromFiles(Arrays.asList(file));
    JavaCompiler.CompilationTask task = compiler.getTask(null, fm, dc, null, null, sources);
    task.call();
}
if (!dc.getDiagnostics().isEmpty()) {
    for (Diagnostic <? extends JavaFileObject> d: dc.getDiagnostics()) {
        System.out.println(d.getCode());
        System.out.format("Line: %d, %s in %s \n",
            d.getLineNumber(),
            d.getMessage(null),
            d.getSource().getName());
            System.out.println(d.toString());
    }
    System.exit(1);
}

I've tried looking into the interface a bit myself, and I've seen that the diagnostics returned from my JavaCompiler via the DiagnosticCollector.getDiagnostics() method are of dynamic type ClientCodeWrapper/DiagnosticSourceUnwrapper, which has a JCDiagnostic field that has a getArgs() method as desired, but this JCDiagnostic field is inaccessible from my program.
I was thinking there might be some way to unwrap/cast the ClientCodeWrapper/DiagnosticSourceUnwrapper so as to access the JCDiagnostic field and use its getArgs() method, but I was unable to do so, as I ran into ClassCastExceptions and inaccessible types.

I also tried making my own implementation of the Diagnostic Interface, so as to write my own getArgs() method, but I wasn't able to successfully implement a class that would get the arguments of the diagnostic and also be compatible with the JavaCompiler Interfaces as I was currently using them.
I could see this line of thinking also leading to a solution, but I wasn't able to make it work myself.

I was also thinking that perhaps there is another API/framework that would be better to achieve my goal.

Thank you in advance.


问:
i have a problem a generate a maze in a correct way
the maze don't seems a maze and i don't understand why

Here's a brief explanation of how the code works:

The cell class represents a cell in the maze grid. Each cell has four walls (top, right, bottom, left) and a visited flag to keep track of whether the cell has been visited during the search.

The check_cell method returns the cell at the given x and y coordinates if it exists in the grid, otherwise it returns False.

The check_neighbors method returns a random unvisited neighbor of the current cell, or False if there are no unvisited neighbors.

The remove_walls method removes the walls between the current cell and the next cell.

The main loop continues until there are no more unvisited cells. At each iteration, it selects a random unvisited neighbor of the current cell (if there is one) and removes the walls between the two cells. If there are no more unvisited neighbors, it backtracks to the last cell visited by popping it off the stack.

Once the search is complete, the bitmap variable contains a two-dimensional list representation of the maze, where 0 represents a wall and 1 represents a path.

Finally, the bitmap is printed to the console.

```<code>from random import choice
continua = True
cols, rows = 10, 10

class cell:
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.walls = {'top':True,'right':True,'bottom':True,'left':True}
        self.visited = False

    def check_cell(self, x, y):
        find_index = lambda x, y: x + y * cols
        if x < 0 or x > cols - 1 or y < 0 or y > rows - 1:
            return False
        return grid_cells[find_index(x,y)]

    def check_neightbors(self):
        neightbors = []
        top = self.check_cell(self.x, self.y - 1)
        right = self.check_cell(self.x + 1, self.y)
        bottom = self.check_cell(self.x, self.y + 1)
        left = self.check_cell(self.x - 1, self.y)
        if top and not top.visited:
            neightbors.append(top)
        if right and not right.visited:
            neightbors.append(right)
        if bottom and not bottom.visited:
            neightbors.append(bottom)
        if left and not left.visited:
            neightbors.append(left)
        return choice(neightbors) if neightbors else False

def remove_walls(current, next):
    dx = current.x - next.x
    if dx == 1:
        current.walls['left'] = False
        next.walls['right'] = False
    elif dx == -1:
        current.walls['right'] = False
        next.walls['left'] = False
    dy = current.y - next.y
    if dy == 1:
        current.walls['top'] = False
        next.walls['bottom'] = False
    elif dy == -1:
        current.walls['bottom'] = False
        next.walls['top'] = False

grid_cells = [cell(col, row) for row in range(rows) for col in range(cols)]
current_cell = grid_cells[0]
stack = []

while continua:

    next_cell = current_cell.check_neightbors()
    if next_cell:
        next_cell.visited = True
        stack.append(current_cell)
        remove_walls(current_cell, next_cell)
        current_cell = next_cell
    elif stack:
        current_cell = stack.pop()

    bitmap = []

    # Iterate over all the rows of the maze
    for row in range(rows):
        # Initialize an empty list to store the row of the bitmap
        row_bitmap = []
        # Iterate over all the columns of the maze
        for col in range(cols):
            # Get the cell at the current row and column
            cell = grid_cells[row * cols + col]
            # If there is a wall on the top or left of the cell, append a 0 to the row
            if cell.walls['top'] or cell.walls['left']:
                row_bitmap.append(0)
            # If there are no walls on the top or left of the cell, append a 1 to the row
            else:
                row_bitmap.append(1)
        # Append the row to the bitmap
        bitmap.append(row_bitmap)
    #add external walls

    if current_cell == grid_cells[0] and len(stack) == 0: #check if is end
        for sublist in bitmap:
           sublist.insert(0, 1)
           sublist.append(1)
        top_bottom = [1] * len(bitmap[0])

# Insert the list full of 1s at the beginning and end of the two-dimensional list
        bitmap.insert(0, top_bottom)
        bitmap.append(top_bottom)

        print(bitmap)
        continua = False
#visual
for i in bitmap:
  for element in i:
    print(element, end=' ')
  print()
</code>```

the algorithm used is deep first search but maybe i mess up
1 is the walls and 0 is free
help please

Body:
the maze don't seems a maze and i don't understand why

Here's a brief explanation of how the code works:

The cell class represents a cell in the maze grid. Each cell has four walls (top, right, bottom, left) and a visited flag to keep track of whether the cell has been visited during the search.

The check_cell method returns the cell at the given x and y coordinates if it exists in the grid, otherwise it returns False.

The check_neighbors method returns a random unvisited neighbor of the current cell, or False if there are no unvisited neighbors.

The remove_walls method removes the walls between the current cell and the next cell.

The main loop continues until there are no more unvisited cells. At each iteration, it selects a random unvisited neighbor of the current cell (if there is one) and removes the walls between the two cells. If there are no more unvisited neighbors, it backtracks to the last cell visited by popping it off the stack.

Once the search is complete, the bitmap variable contains a two-dimensional list representation of the maze, where 0 represents a wall and 1 represents a path.

Finally, the bitmap is printed to the console.

from random import choice
continua = True
cols, rows = 10, 10

class cell:
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.walls = {'top':True,'right':True,'bottom':True,'left':True}
        self.visited = False

    def check_cell(self, x, y):
        find_index = lambda x, y: x + y * cols
        if x < 0 or x > cols - 1 or y < 0 or y > rows - 1:
            return False
        return grid_cells[find_index(x,y)]

    def check_neightbors(self):
        neightbors = []
        top = self.check_cell(self.x, self.y - 1)
        right = self.check_cell(self.x + 1, self.y)
        bottom = self.check_cell(self.x, self.y + 1)
        left = self.check_cell(self.x - 1, self.y)
        if top and not top.visited:
            neightbors.append(top)
        if right and not right.visited:
            neightbors.append(right)
        if bottom and not bottom.visited:
            neightbors.append(bottom)
        if left and not left.visited:
            neightbors.append(left)
        return choice(neightbors) if neightbors else False

def remove_walls(current, next):
    dx = current.x - next.x
    if dx == 1:
        current.walls['left'] = False
        next.walls['right'] = False
    elif dx == -1:
        current.walls['right'] = False
        next.walls['left'] = False
    dy = current.y - next.y
    if dy == 1:
        current.walls['top'] = False
        next.walls['bottom'] = False
    elif dy == -1:
        current.walls['bottom'] = False
        next.walls['top'] = False

grid_cells = [cell(col, row) for row in range(rows) for col in range(cols)]
current_cell = grid_cells[0]
stack = []

while continua:

    next_cell = current_cell.check_neightbors()
    if next_cell:
        next_cell.visited = True
        stack.append(current_cell)
        remove_walls(current_cell, next_cell)
        current_cell = next_cell
    elif stack:
        current_cell = stack.pop()

    bitmap = []

    # Iterate over all the rows of the maze
    for row in range(rows):
        # Initialize an empty list to store the row of the bitmap
        row_bitmap = []
        # Iterate over all the columns of the maze
        for col in range(cols):
            # Get the cell at the current row and column
            cell = grid_cells[row * cols + col]
            # If there is a wall on the top or left of the cell, append a 0 to the row
            if cell.walls['top'] or cell.walls['left']:
                row_bitmap.append(0)
            # If there are no walls on the top or left of the cell, append a 1 to the row
            else:
                row_bitmap.append(1)
        # Append the row to the bitmap
        bitmap.append(row_bitmap)
    #add external walls

    if current_cell == grid_cells[0] and len(stack) == 0: #check if is end
        for sublist in bitmap:
           sublist.insert(0, 1)
           sublist.append(1)
        top_bottom = [1] * len(bitmap[0])

# Insert the list full of 1s at the beginning and end of the two-dimensional list
        bitmap.insert(0, top_bottom)
        bitmap.append(top_bottom)

        print(bitmap)
        continua = False
#visual
for i in bitmap:
  for element in i:
    print(element, end=' ')
  print()

the algorithm used is deep first search but maybe i mess up
1 is the walls and 0 is free
help please


问:
Is the headers in an HTTPS request encrypted?
I am unsure if the headers in the are meant to be encrypted as I keep getting mixed answers?

I have read online that participants of an HTTPS interaction are not fully preserved as there are headers containing the sender and receiver adresses in the IP datagram. And from what I know, HTTPS uses TLS to encrypt data.

And in a few other stackoverflow questions such as this state that they are encrypted

Are HTTPS headers encrypted?

I am very confused on what is correct


问:
MPI send a struct which contains dynamic arrays
By using MPI I want to send a struct which contains a dynamic array of another kind of struct. To complicate matters, this last in turn contains a dynamic array of char.

I defined the following solution.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <time.h>
#include <stddef.h>

typedef struct Code {
  char character;
  int length;
  char *code;
} Code;

typedef struct CodeDictionary {
  int codesNr;
  Code *codes;
} CodeDictionary;

static const int CODE_NR = 5;

void buildCodeType(MPI_Datatype *codeType) {
    int blockLen[2] = {1, 1};
    MPI_Datatype types[2] = {MPI_CHAR, MPI_INT};

    MPI_Aint offsets[2];
    offsets[0] = offsetof(Code, character);
    offsets[1] = offsetof(Code, length);

    MPI_Type_create_struct(2, blockLen, offsets, types, codeType);
    MPI_Type_commit(codeType);
}

int getRand(int from, int to)
{
    int num = (rand() % (to - from + 1)) + from;
    return num;
}

int main(int argc,char *argv[]) {
    MPI_Init(NULL, NULL);

    int procNumber;
    int pid;

    MPI_Comm_size(MPI_COMM_WORLD, &procNumber);
    MPI_Comm_rank(MPI_COMM_WORLD, &pid);

    if (procNumber < 2) {
        printf("At least two processes required.\n");
        return 1;
    }

    const int from = 1;
    const int to = 9;

    srand(time(0));

    MPI_Datatype codeType;
    buildCodeType(&codeType);

    if (pid == 0) {
        CodeDictionary sndDict = {.codesNr = CODE_NR, .codes = calloc(CODE_NR, sizeof(Code))};

        // create some fake values
        for (int i = 0; i < CODE_NR; i++) {
            sndDict.codes[i].character = 'a' + i;
            sndDict.codes[i].length = getRand(from, to);
            sndDict.codes[i].code = calloc(sndDict.codes[i].length, sizeof(char));

            for (int j = 0; j < sndDict.codes[i].length; j++) {
                int randChar = getRand('a', 'z');
                sndDict.codes[i].code[j] = randChar + j;
            }
        }

        printf("source data\n");

        for (int i = 0; i < sndDict.codesNr; i++) {
            printf("codes[%d]:\n\t", i);

            printf("character: %c\tlength: %d\tcode: ", sndDict.codes[i].character, sndDict.codes[i].length);
            for (int j = 0; j < sndDict.codes[i].length; j++)
                printf("%c", sndDict.codes[i].code[j]);

            printf("\n");
        }

        for (int i = 1; i < procNumber; i++) { // maybe I can use MPI_Bcast
            MPI_Send(&sndDict.codesNr, 1, MPI_INT, i, 0, MPI_COMM_WORLD);

            for (int j = 0; j < sndDict.codesNr; j++) {
                MPI_Send(&sndDict.codes[j], 1, codeType, i, 0, MPI_COMM_WORLD);
                MPI_Send(sndDict.codes[j].code, sndDict.codes[j].length, MPI_CHAR, i, 0, MPI_COMM_WORLD);
            }
        }

        for (int i = 0; i < sndDict.codesNr; i++)
            free(sndDict.codes[i].code);

    } else {
        MPI_Status status;
        CodeDictionary rcvDict = {.codesNr = 0, .codes = NULL};

        MPI_Recv(&rcvDict.codesNr, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);

        rcvDict.codes = calloc(rcvDict.codesNr, sizeof(Code));
        for (int i = 0; i < rcvDict.codesNr; i++) {
            MPI_Recv(&rcvDict.codes[i], 1, codeType, 0, 0, MPI_COMM_WORLD, &status);

            rcvDict.codes[i].code = calloc(rcvDict.codes[i].length, sizeof(char));
            MPI_Recv(rcvDict.codes[i].code, rcvDict.codes[i].length, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status);
        }

       printf("\nreceived data\n");

        for (int i = 0; i < rcvDict.codesNr; i++) {
            printf("codes[%d]:\n\t", i);

            printf("character: %c\tlength: %d\tcode: ", rcvDict.codes[i].character, rcvDict.codes[i].length);
            for (int j = 0; j < rcvDict.codes[i].length; j++)
                printf("%c", rcvDict.codes[i].code[j]);

            printf("\n");
        }

        for (int i = 0; i < rcvDict.codesNr; i++)
            free(rcvDict.codes[i].code);
    }

    MPI_Type_free(&codeType);
    MPI_Finalize();

    return 0;
}
</code>```

I learned that I have to send first the size of the dynamic data, and then this last, otherwise I cannot allocate correctly the needed memory. Anyway I find this solution a bit complicated.

I'm developing in C and compiling with mpicc.

Do you know if there is a smarter solution?

Body:
By using MPI I want to send a struct which contains a dynamic array of another kind of struct. To complicate matters, this last in turn contains a dynamic array of char.

I defined the following solution.

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <time.h>
#include <stddef.h>

typedef struct Code {
  char character;
  int length;
  char *code;
} Code;

typedef struct CodeDictionary {
  int codesNr;
  Code *codes;
} CodeDictionary;

static const int CODE_NR = 5;

void buildCodeType(MPI_Datatype *codeType) {
    int blockLen[2] = {1, 1};
    MPI_Datatype types[2] = {MPI_CHAR, MPI_INT};

    MPI_Aint offsets[2];
    offsets[0] = offsetof(Code, character);
    offsets[1] = offsetof(Code, length);

    MPI_Type_create_struct(2, blockLen, offsets, types, codeType);
    MPI_Type_commit(codeType);
}

int getRand(int from, int to)
{
    int num = (rand() % (to - from + 1)) + from;
    return num;
}

int main(int argc,char *argv[]) {
    MPI_Init(NULL, NULL);

    int procNumber;
    int pid;

    MPI_Comm_size(MPI_COMM_WORLD, &procNumber);
    MPI_Comm_rank(MPI_COMM_WORLD, &pid);

    if (procNumber < 2) {
        printf("At least two processes required.\n");
        return 1;
    }

    const int from = 1;
    const int to = 9;

    srand(time(0));

    MPI_Datatype codeType;
    buildCodeType(&codeType);

    if (pid == 0) {
        CodeDictionary sndDict = {.codesNr = CODE_NR, .codes = calloc(CODE_NR, sizeof(Code))};

        // create some fake values
        for (int i = 0; i < CODE_NR; i++) {
            sndDict.codes[i].character = 'a' + i;
            sndDict.codes[i].length = getRand(from, to);
            sndDict.codes[i].code = calloc(sndDict.codes[i].length, sizeof(char));

            for (int j = 0; j < sndDict.codes[i].length; j++) {
                int randChar = getRand('a', 'z');
                sndDict.codes[i].code[j] = randChar + j;
            }
        }

        printf("source data\n");

        for (int i = 0; i < sndDict.codesNr; i++) {
            printf("codes[%d]:\n\t", i);

            printf("character: %c\tlength: %d\tcode: ", sndDict.codes[i].character, sndDict.codes[i].length);
            for (int j = 0; j < sndDict.codes[i].length; j++)
                printf("%c", sndDict.codes[i].code[j]);

            printf("\n");
        }

        for (int i = 1; i < procNumber; i++) { // maybe I can use MPI_Bcast
            MPI_Send(&sndDict.codesNr, 1, MPI_INT, i, 0, MPI_COMM_WORLD);

            for (int j = 0; j < sndDict.codesNr; j++) {
                MPI_Send(&sndDict.codes[j], 1, codeType, i, 0, MPI_COMM_WORLD);
                MPI_Send(sndDict.codes[j].code, sndDict.codes[j].length, MPI_CHAR, i, 0, MPI_COMM_WORLD);
            }
        }

        for (int i = 0; i < sndDict.codesNr; i++)
            free(sndDict.codes[i].code);

    } else {
        MPI_Status status;
        CodeDictionary rcvDict = {.codesNr = 0, .codes = NULL};

        MPI_Recv(&rcvDict.codesNr, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);

        rcvDict.codes = calloc(rcvDict.codesNr, sizeof(Code));
        for (int i = 0; i < rcvDict.codesNr; i++) {
            MPI_Recv(&rcvDict.codes[i], 1, codeType, 0, 0, MPI_COMM_WORLD, &status);

            rcvDict.codes[i].code = calloc(rcvDict.codes[i].length, sizeof(char));
            MPI_Recv(rcvDict.codes[i].code, rcvDict.codes[i].length, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status);
        }

       printf("\nreceived data\n");

        for (int i = 0; i < rcvDict.codesNr; i++) {
            printf("codes[%d]:\n\t", i);

            printf("character: %c\tlength: %d\tcode: ", rcvDict.codes[i].character, rcvDict.codes[i].length);
            for (int j = 0; j < rcvDict.codes[i].length; j++)
                printf("%c", rcvDict.codes[i].code[j]);

            printf("\n");
        }

        for (int i = 0; i < rcvDict.codesNr; i++)
            free(rcvDict.codes[i].code);
    }

    MPI_Type_free(&codeType);
    MPI_Finalize();

    return 0;
}

I learned that I have to send first the size of the dynamic data, and then this last, otherwise I cannot allocate correctly the needed memory. Anyway I find this solution a bit complicated.

I'm developing in C and compiling with mpicc.

Do you know if there is a smarter solution?


问:
Accessing Cookies from Different Paths for PHP
I am setting a userid cookie by assigning it the value from $userID:

```<code><?php
session_set_cookie_params(0, '/');
session_start();

$userID = 12345

setcookie('userid', $userID, time() + 60 * 60 * 24 * 30);

?>
</code>```

The issue is that when I look in Dev Tools, the path is listed as the location of the php script where I set the cookie value (/php/formProcess).

As seen above, I have tried using session_set_cookie_params(0, '/');, along with also adding the following in the php.ini file (and restarting the server):

```<code>[Session]
session.cookie_path = "/"
</code>```

Neither of these methods have worked to update the path of the userid cookie I set.

However, I can use:

```<code>setcookie('userid', $userID, time() + 60 * 60 * 24 * 30, '/', '', false, false);
</code>```

to set the correct path on a cookie-by-cookie basis. Why does session_set_cookie_params(0, '/'); not work as intended? Is there another way to globally set each cookie to be available in all paths?

Thank you

Body:
I am setting a userid cookie by assigning it the value from $userID:

<?php
session_set_cookie_params(0, '/');
session_start();

$userID = 12345

setcookie('userid', $userID, time() + 60 * 60 * 24 * 30);

?>

The issue is that when I look in Dev Tools, the path is listed as the location of the php script where I set the cookie value (/php/formProcess).

As seen above, I have tried using session_set_cookie_params(0, '/');, along with also adding the following in the php.ini file (and restarting the server):

[Session]
session.cookie_path = "/"

Neither of these methods have worked to update the path of the userid cookie I set.

However, I can use:

setcookie('userid', $userID, time() + 60 * 60 * 24 * 30, '/', '', false, false);

to set the correct path on a cookie-by-cookie basis. Why does session_set_cookie_params(0, '/'); not work as intended? Is there another way to globally set each cookie to be available in all paths?

Thank you


问:
Python Selenium: How to select the drop down menu with highlighted feature
I am trying to select the drop down menu. Selenium can control Chrome to click the drop down list and the list shows the options. However, it fails to select and click the options. Is it because the drop down list has a feature when the cursor point to the text and the text will be highlighted. The class name will be changed.

Here is the code:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)

url = 'https://system.arthuronline.co.uk/genieliew1/dashboards/index'
driver.get(url)
wait = WebDriverWait(driver, 20)

wait.until(EC.element_to_be_clickable((By.ID, 'username'))).send_keys("")
wait.until(EC.element_to_be_clickable((By.ID, 'password'))).send_keys("")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()

url = 'https://system.arthuronline.co.uk/genieliew1/units/view/377225/filter:Transaction-_statement:property-owner;Transaction-_payeeEntityId:149280;Transaction-unit_id:377225;Transaction-_order:default;/page:1#tab-transactions-7322b9'
driver.get(url)

#Click the drop down menu
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[@id='s2id__statement']"))).click()
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[contains(.,'Property Owner Statement')]"))).click()
</code>```

This is the error:

```<code>---------------------------------------------------------------------------
ElementClickInterceptedException          Traceback (most recent call last)
<ipython-input-26-3afc38e2a733> in <module>
     25 #Click the drop down menu
     26 WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[@id='s2id__statement']"))).click()
---> 27 WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[contains(.,'Property Owner Statement')]"))).click()

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in click(self)
     91     def click(self) -> None:
     92         """Clicks the element."""
---> 93         self._execute(Command.CLICK_ELEMENT)
     94
     95     def submit(self):

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in _execute(self, command, params)
    408             params = {}
    409         params["id"] = self._id
--> 410         return self._parent.execute(command, params)
    411
    412     def find_element(self, by=By.ID, value=None) -> WebElement:

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py in execute(self, driver_command, params)
    442         response = self.command_executor.execute(driver_command, params)
    443         if response:
--> 444             self.error_handler.check_response(response)
    445             response["value"] = self._unwrap_value(response.get("value", None))
    446             return response

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
    247                 alert_text = value["alert"].get("text")
    248             raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
--> 249         raise exception_class(message, screen, stacktrace)

ElementClickInterceptedException: Message: element click intercepted: Element <div id="outer">...</div> is not clickable at point (1280, 646). Other element would receive the click: <div id="select2-drop-mask" class="select2-drop-mask" style="width: 2560px; height: 1293px;"></div>
  (Session info: chrome=108.0.5359.124)
Stacktrace:
0   chromedriver                        0x00000001055fff38 chromedriver + 4910904
1   chromedriver                        0x000000010557fa03 chromedriver + 4385283
2   chromedriver                        0x00000001051c4747 chromedriver + 472903
3   chromedriver                        0x0000000105212588 chromedriver + 791944
4   chromedriver                        0x000000010520f9ec chromedriver + 780780
5   chromedriver                        0x000000010520c671 chromedriver + 767601
6   chromedriver                        0x000000010520b18b chromedriver + 762251
7   chromedriver                        0x00000001051fbac3 chromedriver + 699075
8   chromedriver                        0x000000010522f112 chromedriver + 909586
9   chromedriver                        0x00000001051fb0ed chromedriver + 696557
10  chromedriver                        0x000000010522f2ce chromedriver + 910030
11  chromedriver                        0x000000010524a28e chromedriver + 1020558
12  chromedriver                        0x000000010522eee3 chromedriver + 909027
13  chromedriver                        0x00000001051f930c chromedriver + 688908
14  chromedriver                        0x00000001051fa88e chromedriver + 694414
15  chromedriver                        0x00000001055cd1de chromedriver + 4702686
16  chromedriver                        0x00000001055d1b19 chromedriver + 4721433
17  chromedriver                        0x00000001055d928e chromedriver + 4752014
18  chromedriver                        0x00000001055d291a chromedriver + 4725018
19  chromedriver                        0x00000001055a6b02 chromedriver + 4545282
20  chromedriver                        0x00000001055f1888 chromedriver + 4851848
21  chromedriver                        0x00000001055f1a05 chromedriver + 4852229
22  chromedriver                        0x0000000105607e5f chromedriver + 4943455
23  libsystem_pthread.dylib             0x00007fff6bdeb109 _pthread_start + 148
24  libsystem_pthread.dylib             0x00007fff6bde6b8b thread_start + 15[!
</code>```

enter image description here]1

Body:
I am trying to select the drop down menu. Selenium can control Chrome to click the drop down list and the list shows the options. However, it fails to select and click the options. Is it because the drop down list has a feature when the cursor point to the text and the text will be highlighted. The class name will be changed.

Here is the code:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)

url = 'https://system.arthuronline.co.uk/genieliew1/dashboards/index'
driver.get(url)
wait = WebDriverWait(driver, 20)

wait.until(EC.element_to_be_clickable((By.ID, 'username'))).send_keys("")
wait.until(EC.element_to_be_clickable((By.ID, 'password'))).send_keys("")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()

url = 'https://system.arthuronline.co.uk/genieliew1/units/view/377225/filter:Transaction-_statement:property-owner;Transaction-_payeeEntityId:149280;Transaction-unit_id:377225;Transaction-_order:default;/page:1#tab-transactions-7322b9'
driver.get(url)

#Click the drop down menu
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[@id='s2id__statement']"))).click()
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[contains(.,'Property Owner Statement')]"))).click()

This is the error:

---------------------------------------------------------------------------
ElementClickInterceptedException          Traceback (most recent call last)
<ipython-input-26-3afc38e2a733> in <module>
     25 #Click the drop down menu
     26 WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[@id='s2id__statement']"))).click()
---> 27 WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[contains(.,'Property Owner Statement')]"))).click()

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in click(self)
     91     def click(self) -> None:
     92         """Clicks the element."""
---> 93         self._execute(Command.CLICK_ELEMENT)
     94
     95     def submit(self):

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in _execute(self, command, params)
    408             params = {}
    409         params["id"] = self._id
--> 410         return self._parent.execute(command, params)
    411
    412     def find_element(self, by=By.ID, value=None) -> WebElement:

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py in execute(self, driver_command, params)
    442         response = self.command_executor.execute(driver_command, params)
    443         if response:
--> 444             self.error_handler.check_response(response)
    445             response["value"] = self._unwrap_value(response.get("value", None))
    446             return response

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
    247                 alert_text = value["alert"].get("text")
    248             raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
--> 249         raise exception_class(message, screen, stacktrace)

ElementClickInterceptedException: Message: element click intercepted: Element
...
 is not clickable at point (1280, 646). Other element would receive the click:

  (Session info: chrome=108.0.5359.124)
Stacktrace:
0   chromedriver                        0x00000001055fff38 chromedriver + 4910904
1   chromedriver                        0x000000010557fa03 chromedriver + 4385283
2   chromedriver                        0x00000001051c4747 chromedriver + 472903
3   chromedriver                        0x0000000105212588 chromedriver + 791944
4   chromedriver                        0x000000010520f9ec chromedriver + 780780
5   chromedriver                        0x000000010520c671 chromedriver + 767601
6   chromedriver                        0x000000010520b18b chromedriver + 762251
7   chromedriver                        0x00000001051fbac3 chromedriver + 699075
8   chromedriver                        0x000000010522f112 chromedriver + 909586
9   chromedriver                        0x00000001051fb0ed chromedriver + 696557
10  chromedriver                        0x000000010522f2ce chromedriver + 910030
11  chromedriver                        0x000000010524a28e chromedriver + 1020558
12  chromedriver                        0x000000010522eee3 chromedriver + 909027
13  chromedriver                        0x00000001051f930c chromedriver + 688908
14  chromedriver                        0x00000001051fa88e chromedriver + 694414
15  chromedriver                        0x00000001055cd1de chromedriver + 4702686
16  chromedriver                        0x00000001055d1b19 chromedriver + 4721433
17  chromedriver                        0x00000001055d928e chromedriver + 4752014
18  chromedriver                        0x00000001055d291a chromedriver + 4725018
19  chromedriver                        0x00000001055a6b02 chromedriver + 4545282
20  chromedriver                        0x00000001055f1888 chromedriver + 4851848
21  chromedriver                        0x00000001055f1a05 chromedriver + 4852229
22  chromedriver                        0x0000000105607e5f chromedriver + 4943455
23  libsystem_pthread.dylib             0x00007fff6bdeb109 _pthread_start + 148
24  libsystem_pthread.dylib             0x00007fff6bde6b8b thread_start + 15[!

enter image description here]1


问:
Expand/Collapse ul li list groups under IE7
I'm using jQuery checkboxTree plug-in which transforms the structure like below into a collapsible/expandable check-box tree.

```<code><ul id="tree1">
    <li><input type="checkbox"><label>Node 1</label>
        <ul>
            <li><input type="checkbox"><label>Node 1.1</label>
                <ul>
                    <li><input type="checkbox"><label>Node 1.1.1</label>
                    <li><input type="checkbox"><label>Node 1.1.2</label>
                    <li><input type="checkbox"><label>Node 1.1.3</label>
                    <li><input type="checkbox"><label>Node 1.1.4</label>
                </ul>
        </ul>
        <ul>
            <li><input type="checkbox"><label>Node 1.2</label>
                <ul>
                    <li><input type="checkbox"><label>Node 1.2.1</label>
                    <li><input type="checkbox"><label>Node 1.2.2</label>
                    <li><input type="checkbox"><label>Node 1.2.3</label>
                    <li><input type="checkbox"><label>Node 1.2.4</label>
                </ul>
        </ul>
    <li>
</code>```

The problem is in that when I use IE7 and a subgroup of elements (e.g. Node 1.1) is being collapsed using jQuery hide() function the elements of subgroup Node 1.2 begin to slide up overlaying other items.
Is it possible to hide elements using different approach or how to refresh the list in order to redraw it?
You can see a live example on plug-in's website: http://checkboxtree.googlecode.com/svn/tags/checkboxtree-0.5.2/index.html but you have to run IE7 or emulate it (it also works)

ContentLicense: CC BY-SA 3.0

Body:
I'm using jQuery checkboxTree plug-in which transforms the structure like below into a collapsible/expandable check-box tree.

<input type="checkbox">Node 1

<input type="checkbox">Node 1.1

<input type="checkbox">Node 1.1.1

<input type="checkbox">Node 1.1.2

<input type="checkbox">Node 1.1.3

<input type="checkbox">Node 1.1.4

<input type="checkbox">Node 1.2

<input type="checkbox">Node 1.2.1

<input type="checkbox">Node 1.2.2

<input type="checkbox">Node 1.2.3

<input type="checkbox">Node 1.2.4

The problem is in that when I use IE7 and a subgroup of elements (e.g. Node 1.1) is being collapsed using jQuery hide() function the elements of subgroup Node 1.2 begin to slide up overlaying other items.
Is it possible to hide elements using different approach or how to refresh the list in order to redraw it?
You can see a live example on plug-in's website: http://checkboxtree.googlecode.com/svn/tags/checkboxtree-0.5.2/index.html but you have to run IE7 or emulate it (it also works)


问:
mov instruction's different behavior with variables and registers in assembly x86 NASM on Linux
The purpose of this program is to divide 36 by 10 and print the remainder (6) to the screen. The code I specified below doesn't work. I figured out that it was because on my marked line I was putting the value itself into ecx and not the address of that value in memory.

I later changed the code so that it first puts the value into a variable, and then did mov ecx, variable (which actually puts the address of the variable, not the value onto the register ecx). And it worked.

Why doing mov ecx, variable puts variables's address into ecx's value, but doing mov ecx, edx puts edx's value into ecx value?

How can I specify the address of a register and put it in another register's value?

```<code>global _start

section .text
_start:
    mov ebp, esp; for correct debugging

    ; division
    mov eax,36
    mov ebx,10
    mov edx,0   ; cleaning edx before division
    div ebx
    add edx,0x30 ; converting the remainder (integer) into ascii digit

    ; display result
    mov eax,4
    mov ebx,1
    mov ecx,edx        ; pay attention to this line
    mov edx,1
    int 80h

    ; exit
    mov eax,1
    mov ebx,0
    int 80h
</code>```

Body:
The purpose of this program is to divide 36 by 10 and print the remainder (6) to the screen. The code I specified below doesn't work. I figured out that it was because on my marked line I was putting the value itself into ecx and not the address of that value in memory.

I later changed the code so that it first puts the value into a variable, and then did mov ecx, variable (which actually puts the address of the variable, not the value onto the register ecx). And it worked.

Why doing mov ecx, variable puts variables's address into ecx's value, but doing mov ecx, edx puts edx's value into ecx value?

How can I specify the address of a register and put it in another register's value?

global _start

section .text
_start:
    mov ebp, esp; for correct debugging

    ; division
    mov eax,36
    mov ebx,10
    mov edx,0   ; cleaning edx before division
    div ebx
    add edx,0x30 ; converting the remainder (integer) into ascii digit

    ; display result
    mov eax,4
    mov ebx,1
    mov ecx,edx        ; pay attention to this line
    mov edx,1
    int 80h

    ; exit
    mov eax,1
    mov ebx,0
    int 80h


问:
MySQL JOIN does not seem to act as expected
I have the following code in MySQL:

SELECT *

FROM rbdbase R

JOIN awsectionals A

ON ('A.UNIQUE ID' = 'R.ID');

I am simply trying to join rbdbase and awsectionals together based on UNIQUE ID of awsectionals matching the ID of rbdbase.

If I use JOIN, I get zero results returned.

If I use LEFT JOIN, I get all rows from R with corresponding data from A being NULL
If I use RIGHT JOIN, I get all rows from A with corresponding data from R being NULL

Logs

I have checked that there is matching UNIQUE ID and ID from each table. All looks OK.

Thanks in advance for any help.

I am expecting a combined table based on matching values for A.UNIQUE ID and R.ID.


问:
How to run multiple instances of the same Next JS app with different configs on same machine
I would like to run 2 instances of the NextJS app on the same machine with different configurations and ports

First instance is on port 3000, the second on port 3001, and this works fine with

next dev

next dev -p 3001

I have a couple of environment variables, which need to have different values per instance, and this works fine as well when they are not running up in parallel.

```<code>API_1=xyz
API_2=xyz
</code>```

next dev

API_1=xzy123 API_2=xyz123 next dev -p 3001

The issue is, when I start both instances, environment variables from the last started instance are applied. I figure it that I should start each instance in a separate dist folder. So I tried to add dist folder name as env variable, but it doesn't work.

```<code>API_1=xyz
API_2=xyz
DIR=.next
</code>```
```<code>next.config.js

module.exports = {
    reactStrictMode: true,
    distDir: process.env.DIR
};
</code>```

next dev

DIR=.next-2 API_1=xzy123 API_2=xyz123 next dev -p 3001

Body:
I would like to run 2 instances of the NextJS app on the same machine with different configurations and ports

First instance is on port 3000, the second on port 3001, and this works fine with

next dev

next dev -p 3001

I have a couple of environment variables, which need to have different values per instance, and this works fine as well when they are not running up in parallel.

API_1=xyz
API_2=xyz

next dev

API_1=xzy123 API_2=xyz123 next dev -p 3001

The issue is, when I start both instances, environment variables from the last started instance are applied. I figure it that I should start each instance in a separate dist folder. So I tried to add dist folder name as env variable, but it doesn't work.

API_1=xyz
API_2=xyz
DIR=.next

next.config.js

module.exports = {
    reactStrictMode: true,
    distDir: process.env.DIR
};

next dev

DIR=.next-2 API_1=xzy123 API_2=xyz123 next dev -p 3001


问:
Dynamic line graph data excel 2016
I am using excel 2016 and I am trying to create a line graph that uses a range/array of data from another column but I keep getting an error. This video is nearly identical to what I am trying to achieve; however, I get a "There's an error in the formula you've entered." error when performing the step at 13:15ish. I get the error even when using the data following the steps identically from the video. Could it be related to the 2016 version of excel? I know there was a change in 2018 to how dynamic array formulas behavior but I dont know if that would affect this situation.

Below is a simple example of data.

A
B

10
11

11
14

12

13

14

15

The formula I am trying to use is =INDEX($A:$A,MATCH($B1,$A:$A,0)):INDEX($A:$A,MATCH($B2,$A:$A,0)) to get a line graph of 11-14. When a friend does this on her laptop it works, and the only difference I can think of is the excel version. This is driving me nuts, so thank you in advance for your help!

Title: Dynamic line graph data excel 2016


问:
Filtering data that is too different from numpy arrays
I've got data of multiple FRF(Frequency Response Functions) that I would like to average. But due to some bad measurements I have some corrupted data that must be excluded from averaging. For now I have plotted every single FRF and then based on graphs decided whether FRF was OK or not (if it was smooth enough). I would like to do that with a for loop because data is too big.
In every array there is 25600 numbers. Here are 2 pictures, 1st is good FPF, 2nd one is bad and would need to be excluded.

I've tried calculating std and mean but haven't figured the correct way of doing it.


问:
discord.py slash command not recognized
```<code>@bot.tree.command(name="nickname", description="Change nickname!", guild=discord.Object(guildid))
async def nick(interaction: discord. Interaction, nick: str):
     if interaction.channel.id == 1057919837306896444:
         embed = discord.Embed(title=f"**That's a great name!**" ,colour=0x87f854, timestamp=datetime.datetime.now(pytz.timezone('UTC')))
         embed.set_thumbnail(url=member.avatar),
         embed.set_footer(icon_url=interaction.guild.icon,text=f"Discord Village")
         embed.add_field(name="> existing nickname", value="``"+ member.display_name +"``", inline=True)
         embed.add_field(name="> current nickname", value=f"{interaction.author.mention}", inline=True)
         await interaction.response.send_message(embed=embed, ephemeral=False)
         await interaction.author.edit(nick="[Member] " + nick)
</code>```

Why isn't this working? The slash command is not recognized. no error message either. sorry my english is not good

/nickname (the name you want to change)
Name changed and embed create

Title: discord.py slash command not recognized

Body:
@bot.tree.command(name="nickname", description="Change nickname!", guild=discord.Object(guildid))
async def nick(interaction: discord. Interaction, nick: str):
     if interaction.channel.id == 1057919837306896444:
         embed = discord.Embed(title=f"**That's a great name!**" ,colour=0x87f854, timestamp=datetime.datetime.now(pytz.timezone('UTC')))
         embed.set_thumbnail(url=member.avatar),
         embed.set_footer(icon_url=interaction.guild.icon,text=f"Discord Village")
         embed.add_field(name="> existing nickname", value="``"+ member.display_name +"``", inline=True)
         embed.add_field(name="> current nickname", value=f"{interaction.author.mention}", inline=True)
         await interaction.response.send_message(embed=embed, ephemeral=False)
         await interaction.author.edit(nick="[Member] " + nick)

Why isn't this working? The slash command is not recognized. no error message either. sorry my english is not good

/nickname (the name you want to change)
Name changed and embed create


问:
Best way to move a mongodb document using aggregate and merge
I have a collection with documents. I would like to move the documents to another collection using _id and delete the document in the previous collection. When i post the document using the route below the document doesnt move to the expected collection.

clientarchive.js

```<code>

router.post('/new', (req, res, next) => {
    const _id = req.body._id
    clients.aggregate([
        {
          $match: {
            _id: _id
          }
        },
        {
          $merge: {
            into: "clientsarchive",
            on: "_id",
            whenMatched: "replace",
            whenNotMatched: "fail"
          }
        }
      ],
    )
    res.status(200).json({
        message: 'Document Moved',

      })
    }
  )
</code>```

i get the message document moved but the document still remains in the original collection. How can i improve this code? Thanks in advance.

Body:
I have a collection with documents. I would like to move the documents to another collection using _id and delete the document in the previous collection. When i post the document using the route below the document doesnt move to the expected collection.

clientarchive.js

router.post('/new', (req, res, next) => {
    const _id = req.body._id
    clients.aggregate([
        {
          $match: {
            _id: _id
          }
        },
        {
          $merge: {
            into: "clientsarchive",
            on: "_id",
            whenMatched: "replace",
            whenNotMatched: "fail"
          }
        }
      ],
    )
    res.status(200).json({
        message: 'Document Moved',

      })
    }
  )

i get the message document moved but the document still remains in the original collection. How can i improve this code? Thanks in advance.


问:
Getting 443 response from huggingface when trying to connect from Google Composer
I'm trying to run gpt2 in Google CLoud Composer, but i'm getting error on requesting previous trained model with this message:

```<code>{connectionpool.py:1003} DEBUG - Starting new HTTPS connection (1): huggingface.co:443
{connectionpool.py:456} DEBUG - https://huggingface.co:443
</code>```

This is my code:

```<code>def _write_article_gpt2_test():
    generator = pipeline('text-generation', model='gpt2')
    set_seed(random.randint(1, 100))
    introduction = generator(
        "iphone is ", max_length=500, num_return_sequences=5)
    return introduction
</code>```

How can I solve this?

This is the full log

```<code>[2022-12-30, 22:24:50 UTC] {connectionpool.py:1003} DEBUG - Starting new HTTPS connection (1): huggingface.co:443
[2022-12-30, 22:24:51 UTC] {connectionpool.py:456} DEBUG - https://huggingface.co:443 "HEAD /gpt2/resolve/main/config.json HTTP/1.1" 200 0
[2022-12-30, 22:24:55 UTC] {taskinstance.py:872} DEBUG - Refreshing TaskInstance <TaskInstance: dag_xxx.task_build_article_test manual__2022-12-30T22:24:36.796753+00:00 [running]> from DB
[2022-12-30, 22:24:56 UTC] {base_job.py:226} DEBUG - [heartbeat]
[2022-12-30, 22:25:01 UTC] {taskinstance.py:872} DEBUG - Refreshing TaskInstance <TaskInstance: dag_xxx.task_build_article_test manual__2022-12-30T22:24:36.796753+00:00 [running]> from DB
[2022-12-30, 22:25:01 UTC] {base_job.py:226} DEBUG - [heartbeat]
[2022-12-30, 22:25:07 UTC] {taskinstance.py:872} DEBUG - Refreshing TaskInstance <TaskInstance: dag_xxx.task_build_article_test manual__2022-12-30T22:24:36.796753+00:00 [running]> from DB
[2022-12-30, 22:25:07 UTC] {base_job.py:226} DEBUG - [heartbeat]
[2022-12-30, 22:25:12 UTC] {taskinstance.py:872} DEBUG - Refreshing TaskInstance <TaskInstance: dag_xxx.task_build_article_test manual__2022-12-30T22:24:36.796753+00:00 [running]> from DB
[2022-12-30, 22:25:12 UTC] {base_job.py:226} DEBUG - [heartbeat]
[2022-12-30, 22:25:15 UTC] {local_task_job.py:156} INFO - Task exited with return code Negsignal.SIGKILL
</code>```

Body:
I'm trying to run gpt2 in Google CLoud Composer, but i'm getting error on requesting previous trained model with this message:

{connectionpool.py:1003} DEBUG - Starting new HTTPS connection (1): huggingface.co:443
{connectionpool.py:456} DEBUG - https://huggingface.co:443

This is my code:

def _write_article_gpt2_test():
    generator = pipeline('text-generation', model='gpt2')
    set_seed(random.randint(1, 100))
    introduction = generator(
        "iphone is ", max_length=500, num_return_sequences=5)
    return introduction

How can I solve this?

This is the full log

[2022-12-30, 22:24:50 UTC] {connectionpool.py:1003} DEBUG - Starting new HTTPS connection (1): huggingface.co:443
[2022-12-30, 22:24:51 UTC] {connectionpool.py:456} DEBUG - https://huggingface.co:443 "HEAD /gpt2/resolve/main/config.json HTTP/1.1" 200 0
[2022-12-30, 22:24:55 UTC] {taskinstance.py:872} DEBUG - Refreshing TaskInstance <TaskInstance: dag_xxx.task_build_article_test manual__2022-12-30T22:24:36.796753+00:00 [running]> from DB
[2022-12-30, 22:24:56 UTC] {base_job.py:226} DEBUG - [heartbeat]
[2022-12-30, 22:25:01 UTC] {taskinstance.py:872} DEBUG - Refreshing TaskInstance <TaskInstance: dag_xxx.task_build_article_test manual__2022-12-30T22:24:36.796753+00:00 [running]> from DB
[2022-12-30, 22:25:01 UTC] {base_job.py:226} DEBUG - [heartbeat]
[2022-12-30, 22:25:07 UTC] {taskinstance.py:872} DEBUG - Refreshing TaskInstance <TaskInstance: dag_xxx.task_build_article_test manual__2022-12-30T22:24:36.796753+00:00 [running]> from DB
[2022-12-30, 22:25:07 UTC] {base_job.py:226} DEBUG - [heartbeat]
[2022-12-30, 22:25:12 UTC] {taskinstance.py:872} DEBUG - Refreshing TaskInstance <TaskInstance: dag_xxx.task_build_article_test manual__2022-12-30T22:24:36.796753+00:00 [running]> from DB
[2022-12-30, 22:25:12 UTC] {base_job.py:226} DEBUG - [heartbeat]
[2022-12-30, 22:25:15 UTC] {local_task_job.py:156} INFO - Task exited with return code Negsignal.SIGKILL


问:
Is It Possible to Use BotDetect Captcha in .NET 7 with a Linux Host?
BotDetect Captcha seems to be using System.Drawing.Common which--as of .NET 7--is no longer usable when running on Linux.

Is there an option I've overlooked?


问:
How can I create a playfab leaderboard for a local 2 player game using login details?
I want to get the 2 players playing my pool game to login separately and play the main game. Is there a way I can use login details to store stats in leaderboard formats in playfab?

I have set up playfab and have got a functioning login page in unity using the playfab api. The page can register new users, allow log in and send account recovery emails.


问:
SQL database management question for Webscraper project
I have very little Database management experience, I took a single class when I was in Undergrad. I wanted to see other's inputs on the best way to setup the database.

I have developed a docker application(Webscraping, PostGIS database). The webscraper scrapes from multiple websites everyday. Then uploads to the database, it also checks for duplicates before uploading to the database.

However, I don't want the Reasearch Assistants to be able to change things on the original tables, since lot of the webscraper depends on the structure of the original tables. I gave them SELECT access, but I want them to be able to share their data on the Database as this is a collaborative project.

My original thoughts was to create a new and empty database with full permission. And only SELECT access to the webscraper database. I don't know if this is the best way to do this.

What are your thoughts?

Also to note, this is a contract job for a university project under a grant so I won't be maintaining the database after the contract. Also the project isn't big enough to hire a person with Docker & Database experience just to maintain the database. So I am trying to bulletproof this as much as possible.


问:
row context not filtering as expected in a 1 to many relationship
I have this going on with two separate relationships but for the sake of this question we will focus on one.

I have a Fact table full of a given services info and a separate region lookup table

There are only six regions and IDs. The job table has a Job ID which is correlated to a specific region

i.e., Job-2000 is region 1000

I would expect that when I add the JobID and the region name, I would get

Job-2000 LA West

However, that is not happening when I test a count on the data in the matrix one region ID is returning multiple region names

I am unsure why this is, as the region_key are all distinct

So for example

this job despite having one region ID it is getting a count of 6 regions

I'd instead expect the following

```<code>JobName     RegionID                                     Region Name
Job-0069    00038329-ac05-4f61-897a-e2ec7924a8f3    Olive Plaza Pilot
</code>```

When I select the RegionID, I pull it from the Fact table and not the regions lookup table

What could be happening?

Body:
I have this going on with two separate relationships but for the sake of this question we will focus on one.

I have a Fact table full of a given services info and a separate region lookup table

There are only six regions and IDs. The job table has a Job ID which is correlated to a specific region

i.e., Job-2000 is region 1000

I would expect that when I add the JobID and the region name, I would get

Job-2000 LA West

However, that is not happening when I test a count on the data in the matrix one region ID is returning multiple region names

I am unsure why this is, as the region_key are all distinct

So for example

this job despite having one region ID it is getting a count of 6 regions

I'd instead expect the following

JobName     RegionID                                     Region Name
Job-0069    00038329-ac05-4f61-897a-e2ec7924a8f3    Olive Plaza Pilot

When I select the RegionID, I pull it from the Fact table and not the regions lookup table

What could be happening?


问:
Getting Axios Error when trying to setup authentication (MERN)

Error Message

```<code>AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
code
:
"ERR_BAD_RESPONSE"
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Request failed with status code 500"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
:
{data: 'Something went worng...', status: 500, statusText: 'Internal Server Error', headers: AxiosHeaders, config: {…}, …}
stack
:
"AxiosError: Request failed with status code 500\n    at settle (http://localhost:3000/main.ccb3dfb81e3968e0b0de.hot-update.js:1616:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/main.ccb3dfb81e3968e0b0de.hot-update.js:327:66)"
[[Prototype]]
:
Error
</code>```

Fronend API file

```<code>import axios from 'axios'

const API = axios.create({baseURL: 'http://localhost:5000'})

export const logIn = (authData) => API.post('/user/login', authData);
export const signUp = (authData) => API.post('/user/signup', authData);
</code>```

Frontend Auth file

```<code>import { Navigate } from 'react-router-dom'
import * as api from '../api'

export const signUp = (authData, history) => async (dispatch) => {
    try {
        const { data } = await api.signUp(authData)
        dispatch({ type: 'AUTH', data})
        Navigate('/')
     } catch (error) {
           console.log(error)
     }
}

export const login = (authData, history) => async (dispatch) => {
    try {
        const { data } = await api.signUp(authData)
        dispatch({ type: 'AUTH', data})
        Navigate('/')
     } catch (error) {
        console.log(error)
     }
}

</code>```

Backend Index

```<code>import express from 'express'
import mongoose from 'mongoose'
import cors from 'cors'

import userRoutes from './routes/users.js'

const app = express();
app.use(express.json({limit: "30mb", extended: true}))
app.use(express.urlencoded({limit:"30mb", extended: true}))
app.use(cors());

app.get('/',(req, res) => {
     res.send("This is Ask Panda API")
})

app.use('/user', userRoutes)

const PORT = process.env.PORT || 5000

const CONNECTION_URL = "<mongodb link>"

mongoose.connect ( CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true})
   .then(() => app.listen(PORT, () => {console.log('server running on port ${PORT}')} ))
   .catch((err) => console.log(err.message))
</code>```

Am trying to build simple sing up authentication in MERN, just learning it,
I am following Instructions from a Tutorial but yet I get this error, in the Tutorial, when typing Email and Password, it console logs the data in database and shows the result, but am just getting the above error, I feel like I typed something wrong.

Body:
Error Message

AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
code
:
"ERR_BAD_RESPONSE"
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Request failed with status code 500"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
:
{data: 'Something went worng...', status: 500, statusText: 'Internal Server Error', headers: AxiosHeaders, config: {…}, …}
stack
:
"AxiosError: Request failed with status code 500\n    at settle (http://localhost:3000/main.ccb3dfb81e3968e0b0de.hot-update.js:1616:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/main.ccb3dfb81e3968e0b0de.hot-update.js:327:66)"
[[Prototype]]
:
Error

Fronend API file

import axios from 'axios'

const API = axios.create({baseURL: 'http://localhost:5000'})

export const logIn = (authData) => API.post('/user/login', authData);
export const signUp = (authData) => API.post('/user/signup', authData);

Frontend Auth file

import { Navigate } from 'react-router-dom'
import * as api from '../api'

export const signUp = (authData, history) => async (dispatch) => {
    try {
        const { data } = await api.signUp(authData)
        dispatch({ type: 'AUTH', data})
        Navigate('/')
     } catch (error) {
           console.log(error)
     }
}

export const login = (authData, history) => async (dispatch) => {
    try {
        const { data } = await api.signUp(authData)
        dispatch({ type: 'AUTH', data})
        Navigate('/')
     } catch (error) {
        console.log(error)
     }
}

Backend Index

import express from 'express'
import mongoose from 'mongoose'
import cors from 'cors'

import userRoutes from './routes/users.js'

const app = express();
app.use(express.json({limit: "30mb", extended: true}))
app.use(express.urlencoded({limit:"30mb", extended: true}))
app.use(cors());

app.get('/',(req, res) => {
     res.send("This is Ask Panda API")
})

app.use('/user', userRoutes)

const PORT = process.env.PORT || 5000

const CONNECTION_URL = "<mongodb link>"

mongoose.connect ( CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true})
   .then(() => app.listen(PORT, () => {console.log('server running on port ${PORT}')} ))
   .catch((err) => console.log(err.message))

Am trying to build simple sing up authentication in MERN, just learning it,
I am following Instructions from a Tutorial but yet I get this error, in the Tutorial, when typing Email and Password, it console logs the data in database and shows the result, but am just getting the above error, I feel like I typed something wrong.