问:
internal/modules/cjs/loader.js:888 throw err; ^ Error: Cannot find module './Auth' Require stack:
I do the mern project and in this i create a route folder and in this auth.js file is there and when i want to access this file in index.js the error is occured

```<code>const express=require("express");
const mongoose= require("mongoose");
const app=express();
const dotenv=require("dotenv")
dotenv.config()

//connect router
const route=require("./routes/User");
const authRoute=require("./routes/Auth");

mongoose
    .connect(
        process.env.local
        )
        .then(()=>console.log("MongoDB connected")).catch((err)=>{
            console.log(err)
        });

//accept json
app.use(express.json())

app.use("/data",route)
app.use("/authData",authRoute)

app.listen(process.env.PORT || 5000,()=>{
    console.log("Backend server is running ")
});
</code>```

Error:

```<code>nternal/modules/cjs/loader.js:888 throw err; ^ Error: Cannot find module './routes/Auth' Require stack: - C:\Users\ASUS\Desktop\E-commerce_Web\backendnode\index.js at Function.Module._resolveFilename (internal/modules/cjs/loader.js:885:15) at Function.Module._load (internal/modules/cjs/loader.js:730:27) at Module.require (internal/modules/cjs/loader.js:957:19) at require (internal/modules/cjs/helpers.js:88:18) at Object.<anonymous> (C:\Users\ASUS\Desktop\E-commerce_Web\backendnode\index.js:9:17) at Module._compile (internal/modules/cjs
</code>```

Body:
I do the mern project and in this i create a route folder and in this auth.js file is there and when i want to access this file in index.js the error is occured

const express=require("express");
const mongoose= require("mongoose");
const app=express();
const dotenv=require("dotenv")
dotenv.config()

//connect router
const route=require("./routes/User");
const authRoute=require("./routes/Auth");

mongoose
    .connect(
        process.env.local
        )
        .then(()=>console.log("MongoDB connected")).catch((err)=>{
            console.log(err)
        });

//accept json
app.use(express.json())

app.use("/data",route)
app.use("/authData",authRoute)

app.listen(process.env.PORT || 5000,()=>{
    console.log("Backend server is running ")
});

Error:

nternal/modules/cjs/loader.js:888 throw err; ^ Error: Cannot find module './routes/Auth' Require stack: - C:\Users\ASUS\Desktop\E-commerce_Web\backendnode\index.js at Function.Module._resolveFilename (internal/modules/cjs/loader.js:885:15) at Function.Module._load (internal/modules/cjs/loader.js:730:27) at Module.require (internal/modules/cjs/loader.js:957:19) at require (internal/modules/cjs/helpers.js:88:18) at Object.<anonymous> (C:\Users\ASUS\Desktop\E-commerce_Web\backendnode\index.js:9:17) at Module._compile (internal/modules/cjs


来源: stackexchange

问:
Sharing common pytest configuration between multiple pytest ini files
I have multiple pytest ini files in my test repo for running different tests for different jobs on CI e.g. Jenkins.
Each pytest.ini specifies a different subset of the tests and specifies slightly different options.
But they do share some common settings e.g. basic log config and markers.

Is there a way to define a root/parent ini that all pytest ini can inherit from so I don't need to copy and paste the same configuration across the pytest ini files? It will also make it easier when it comes to maintaining the configurations e.g. when I change one common configuration; I don't have to copy-paste / synchronise the changes.

So my question is how do I define common log config or markers in pytest if that is possible.

I have looked up the pytest documentation but there does not seem to be a way to do it hence asking.

ContentLicense: CC BY-SA 4.0


问:
Why do I get Nan?
I would like to sum two numbers but when I want to display the result of these two values, I have an error message: NaN ? :S

image 1

image 2

By looking on this page:

Why do I get NaN from I function in JavaScript

If I understand correctly, I have a variable that is empty?

I don't see what is blocking?

```<code>let ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let stockPriceElementsec2 = document.getElementById('value1');
let stockPriceElementsec3 = document.getElementById('value2');

let lastPrice = null
let stockObject = null;

let val1 = null;
let val2 = null;
let sum = null;

ws.onmessage = (event) => {
    stockObject = JSON.parse(event.data);
};

setTimeout(() => {
    if (stockObject === null) {
        return;
    }
    let price = parseFloat(stockObject.p).toFixed(2);

    stockPriceElementsec2.innerText = price;
    stockPriceElementsec2.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red';

    lastPrice = price;
    stockObject = null;

    //console.log("Element 1 => " + lastPrice);
    val1 = lastPrice;
    console.log("Element 1 => " + val1);

}, 2000);

setTimeout(() => {
    if (stockObject === null) {
        return;
    }
    let price = parseFloat(stockObject.p).toFixed(2);

    stockPriceElementsec3.innerText = price;
    stockPriceElementsec3.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red';

    lastPrice = price;
    stockObject = null;

    //console.log("Element 2 => " + lastPrice);
    val2 = lastPrice;
    console.log("Element 2 => " + val2);

}, 3000);

sum = document.getElementById("result").innerHTML = (parseInt(val1) + parseInt(val2));
console.log(sum);
</code>```

...

```<code><div class="container ">
    <div class="row">
      <br /><br />
      <div id="no-more-tables">
        <table class="col-md-12 table-bordered table-striped table-condensed cf ">
          <thead class="cf">
            <tr>
              <th>Current course</th>
              <th class="numeric w7 text-center">Value 1</th>
              <th class="numeric w7 text-center">Value 2</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>BTC</td>
              <td class="numeric"><span id="value1"></span></td>
              <td class="numeric"><span id="value2"></span></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <br />
  <p>Sum : <span id="result"></span></p>
</code>```

Title: Why do I get Nan?

Body:
I would like to sum two numbers but when I want to display the result of these two values, I have an error message: NaN ? :S

image 1

image 2

By looking on this page:

Why do I get NaN from I function in JavaScript

If I understand correctly, I have a variable that is empty?

I don't see what is blocking?

let ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let stockPriceElementsec2 = document.getElementById('value1');
let stockPriceElementsec3 = document.getElementById('value2');

let lastPrice = null
let stockObject = null;

let val1 = null;
let val2 = null;
let sum = null;

ws.onmessage = (event) => {
    stockObject = JSON.parse(event.data);
};

setTimeout(() => {
    if (stockObject === null) {
        return;
    }
    let price = parseFloat(stockObject.p).toFixed(2);

    stockPriceElementsec2.innerText = price;
    stockPriceElementsec2.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red';

    lastPrice = price;
    stockObject = null;

    //console.log("Element 1 => " + lastPrice);
    val1 = lastPrice;
    console.log("Element 1 => " + val1);

}, 2000);

setTimeout(() => {
    if (stockObject === null) {
        return;
    }
    let price = parseFloat(stockObject.p).toFixed(2);

    stockPriceElementsec3.innerText = price;
    stockPriceElementsec3.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red';

    lastPrice = price;
    stockObject = null;

    //console.log("Element 2 => " + lastPrice);
    val2 = lastPrice;
    console.log("Element 2 => " + val2);

}, 3000);

sum = document.getElementById("result").innerHTML = (parseInt(val1) + parseInt(val2));
console.log(sum);

...

              Current course
              Value 1
              Value 2

              BTC

Sum :


问:
When using the blade structure in Laravel 9, I get the error "Undefined variable $__env"
There is no problem when I get php's own tags instead of '@' tags. Can anyone make sense of this?

<?php function buildCategory($parent, $category){ ?>
@isset($category['parent_cats'][$parent])

        @foreach ($category['parent_cats'][$parent] as $cat_id)
            @foreach ($category['userPagePerms'] as $userPagePerm)
                @if (!isset($category['parent_cats'][$cat_id]))

backend_page_permission_id == $cat_id) ? 'true' : 'false' }},"opened":true}'>
                        id }}'> {{ $category['categories'][$cat_id]->name}}

                @endif
                @if (isset($category['parent_cats'][$cat_id]))

backend_page_permission_id == $cat_id) ? 'true' : 'false' }},"opened":true}'>
                        id }}'>{{$category['categories'][$cat_id]->name }}
                            <?php buildCategory($cat_id, $category); ?>

                @endif
            @endforeach
        @endforeach

@endisset
<?php } buildCategory(0, $category); ?>
```
<p>It worked when using PHP's own tags. I would expect it to work with the '@' tag.</p>
<p>The code snippet I was able to run. Only the foreach part is the problem.</p>
<pre class="lang-php prettyprint-override"><code><?php foreach ($category['parent_cats'][$parent] as $cat_id) {
    <?php foreach ($category['userPagePerms'] as $userPagePerm) { ?>
</code>```

Error ss : enter image description here

Body:
There is no problem when I get php's own tags instead of '@' tags. Can anyone make sense of this?

<?php function buildCategory($parent, $category){ ?>
@isset($category['parent_cats'][$parent])

        @foreach ($category['parent_cats'][$parent] as $cat_id)
            @foreach ($category['userPagePerms'] as $userPagePerm)
                @if (!isset($category['parent_cats'][$cat_id]))

backend_page_permission_id == $cat_id) ? 'true' : 'false' }},"opened":true}'>
                        id }}'> {{ $category['categories'][$cat_id]->name}}

                @endif
                @if (isset($category['parent_cats'][$cat_id]))

backend_page_permission_id == $cat_id) ? 'true' : 'false' }},"opened":true}'>
                        id }}'>{{$category['categories'][$cat_id]->name }}
                            <?php buildCategory($cat_id, $category); ?>

                @endif
            @endforeach
        @endforeach

@endisset
<?php } buildCategory(0, $category); ?>

It worked when using PHP's own tags. I would expect it to work with the '@' tag.

The code snippet I was able to run. Only the foreach part is the problem.

<?php foreach ($category['parent_cats'][$parent] as $cat_id) {
    <?php foreach ($category['userPagePerms'] as $userPagePerm) { ?>

Error ss : enter image description here


问:
Use props inside button with onclick event
I need help, I'm make a application, in mi app need that press the button and redirect to other external page, I know this onclick function its easy

```<code>onClick={event =>  window.location.href='/your-href'}
</code>```

My problem is that I need to use props to select an external page, I need this to be dynamic, I thought of using onClick={event => window.location.href='{props.url'} obviously doesn't work, how to do?

well I say, I thought of using onClick={event => window.location.href='{props.url'} obviously doesn't work, how to do? can someone help me??

Body:
I need help, I'm make a application, in mi app need that press the button and redirect to other external page, I know this onclick function its easy

onClick={event =>  window.location.href='/your-href'}

My problem is that I need to use props to select an external page, I need this to be dynamic, I thought of using onClick={event => window.location.href='{props.url'} obviously doesn't work, how to do?

well I say, I thought of using onClick={event => window.location.href='{props.url'} obviously doesn't work, how to do? can someone help me??


问:
How to export dataframe as .csv from a loop but maintain column names?
I have a list of data frames that I'am relying to maintain the same column name, but when I export the names are personalized based on their name

for example I have three tables

```<code>c("Table1",Table2","Table3")
</code>```

Each table has the same columns

```<code>c("Col1","Col2","Col3","Col4")
</code>```

When I open the file Table1 it has personalized columns such as

```<code>c("Table1.Col1","Table1.Col2","Table1.Col3","Table1.Col4")
</code>```

I want all .csv to maintain their proper column name and not get modified based on their dataframe name.

I'm using

```<code>for(i in 1:length(df)){
write.csv(df[i], paste0(df,names(list)[i], ".csv"), row.names = FALSE,na="")
}
</code>```

Body:
I have a list of data frames that I'am relying to maintain the same column name, but when I export the names are personalized based on their name

for example I have three tables

c("Table1",Table2","Table3")

Each table has the same columns

c("Col1","Col2","Col3","Col4")

When I open the file Table1 it has personalized columns such as

c("Table1.Col1","Table1.Col2","Table1.Col3","Table1.Col4")

I want all .csv to maintain their proper column name and not get modified based on their dataframe name.

I'm using

for(i in 1:length(df)){
write.csv(df[i], paste0(df,names(list)[i], ".csv"), row.names = FALSE,na="")
}


问:
Why is my mongoose populate query throwing "Cannot populate path because it is not in your schema" error?
I'm building a form management program but right now I'm just trying to build a queue system to handle all the forms when they're assigned to someone.

when I call this first function, it should populate the elements of the activeWork array by pulling from each collection that the entries reference, there are several collections that could be referenced in active work, so I'm trying to use the collection type field to determine what collection to pull from, I don't know if I formatted any of this correctly because its my first time building any of this.

```<code>
import statesPersons from "./statesPersons.schema.js";

export async function getStatesPersonsActiveWorkByProfileId(req, res){
    try{
        const { profileId } = req.params

        const data = await statesPersons.find({profileId})
            .populate('statesPersons.activeWork.referenceId')
        return res.send({
            message: "success",
             data: data,
             status: 200 })
    }catch(e) {
        console.error(e.message)
        return res.send({
            message: "couldn't fetch active work",
             data: null,
             status: 500 })
    }
}
</code>```

Here is the schema for statesPersons, the collection where active work is stored.

```<code>import mongoose, {model, Schema}  from "mongoose";

const activeWorkSchema = new Schema({
  active: Boolean,
  collectionType: {
    type: String,
    enum: ['messages'],
  },
  referenceId: {
    type: Schema.Types.ObjectId,
    refPath: "statesPersons.activeWork.collectionType"
  },
  sentBy: {
    type: Schema.Types.String,
    ref: "statesPerson",
  },
  sentTo:  {
    type: Schema.Types.String,
    ref: "statesPerson",
  },
  timeRecived: Date,
  dueDate: Date,
  subject: String,
  viewed: Boolean,
  content: {},
})

const statesPersonsSchema = new Schema({
  profileId:{
    type: String,
    required: true,
    unique: true

  },
  department: {
    type: String,
    required: true,
    index: true,
  },
  firstName: String,
  lastName: String,
  location: String,
  org: String,
  title: String,
  jobDescription: String,
  email: {
    type: String,
    lowercase: true,
  },
  phoneNumber: String,
  activeWork: [activeWorkSchema],
  emailList: [String],
  jobAssignments: [String],
  affiantInfo: {
    affiantInfoTitle: String,
    affiantInfoExperience: String,
  },
  assessments: [
    {
      assessdBy: {
        type: Schema.Types.ObjectId,
        ref: "statesPerson",
      },
      dueDate: Date,
      questions: {},
    },
  ],
});

export default mongoose.model("statesPersons", statesPersonsSchema);
</code>```

When I make a query, I get:

Cannot populate path statesPersons.activeWork.referenceId because it is not in your schema. Set the strictPopulate option to false to override.

I don't know if I formatted my populate correctly or if the problem is in my schema,

Body:
I'm building a form management program but right now I'm just trying to build a queue system to handle all the forms when they're assigned to someone.

when I call this first function, it should populate the elements of the activeWork array by pulling from each collection that the entries reference, there are several collections that could be referenced in active work, so I'm trying to use the collection type field to determine what collection to pull from, I don't know if I formatted any of this correctly because its my first time building any of this.

import statesPersons from "./statesPersons.schema.js";

export async function getStatesPersonsActiveWorkByProfileId(req, res){
    try{
        const { profileId } = req.params

        const data = await statesPersons.find({profileId})
            .populate('statesPersons.activeWork.referenceId')
        return res.send({
            message: "success",
             data: data,
             status: 200 })
    }catch(e) {
        console.error(e.message)
        return res.send({
            message: "couldn't fetch active work",
             data: null,
             status: 500 })
    }
}

Here is the schema for statesPersons, the collection where active work is stored.

import mongoose, {model, Schema}  from "mongoose";

const activeWorkSchema = new Schema({
  active: Boolean,
  collectionType: {
    type: String,
    enum: ['messages'],
  },
  referenceId: {
    type: Schema.Types.ObjectId,
    refPath: "statesPersons.activeWork.collectionType"
  },
  sentBy: {
    type: Schema.Types.String,
    ref: "statesPerson",
  },
  sentTo:  {
    type: Schema.Types.String,
    ref: "statesPerson",
  },
  timeRecived: Date,
  dueDate: Date,
  subject: String,
  viewed: Boolean,
  content: {},
})

const statesPersonsSchema = new Schema({
  profileId:{
    type: String,
    required: true,
    unique: true

  },
  department: {
    type: String,
    required: true,
    index: true,
  },
  firstName: String,
  lastName: String,
  location: String,
  org: String,
  title: String,
  jobDescription: String,
  email: {
    type: String,
    lowercase: true,
  },
  phoneNumber: String,
  activeWork: [activeWorkSchema],
  emailList: [String],
  jobAssignments: [String],
  affiantInfo: {
    affiantInfoTitle: String,
    affiantInfoExperience: String,
  },
  assessments: [
    {
      assessdBy: {
        type: Schema.Types.ObjectId,
        ref: "statesPerson",
      },
      dueDate: Date,
      questions: {},
    },
  ],
});

export default mongoose.model("statesPersons", statesPersonsSchema);

When I make a query, I get:

Cannot populate path statesPersons.activeWork.referenceId because it is not in your schema. Set the strictPopulate option to false to override.

I don't know if I formatted my populate correctly or if the problem is in my schema,


问:
Non parametric bootstrap for tweedie distribution
Does anyone know of a non-parametric bootstrapping method that will work for a tweedie distribution GLMM using glmmTMB? The biggest lead I have right now is glmmboot but I am not finding any pubs or strong support (i.e., not a lot of evidence of use) for this package. Thanks!

I tried the code below with a tweedie distribution glmm (using glmmTMB) and it worked just fine. I'm not sure if there is something inherently wrong with me using this, though. From https://github.com/ColmanHumphrey/glmmboot

My model (zero inflated with zeros, so I can't use GAMMA) has multiple fixed effects with some interactions and only has one random effect, by the way.

```<code>library(glmmboot)
boot_results <- bootstrap_model(base_model = base_run,
                             base_data = sample_frame,
                                resamples = 999)
</code>```

Body:
Does anyone know of a non-parametric bootstrapping method that will work for a tweedie distribution GLMM using glmmTMB? The biggest lead I have right now is glmmboot but I am not finding any pubs or strong support (i.e., not a lot of evidence of use) for this package. Thanks!

I tried the code below with a tweedie distribution glmm (using glmmTMB) and it worked just fine. I'm not sure if there is something inherently wrong with me using this, though. From https://github.com/ColmanHumphrey/glmmboot

My model (zero inflated with zeros, so I can't use GAMMA) has multiple fixed effects with some interactions and only has one random effect, by the way.

library(glmmboot)
boot_results <- bootstrap_model(base_model = base_run,
                             base_data = sample_frame,
                                resamples = 999)


问:
How do I drag and drop an icon onto a form?
I need to access the icon's image and its properties when the icon is dropped onto a form.

I have tried variations of e.Data.GetData(DataFormats.FileDrop) but that only provides me with the text for the .lnk.

My drop routine is:

```<code>    private void listBox1_DragDrop(object sender, DragEventArgs e)
    {
      Array dataObjects = (Array)e.Data.GetData(DataFormats.FileDrop);
      for (int i = 0; i < dataObjects.Length; ++i)
      {
        string fileName = dataObjects.GetValue(i).ToString();
        listBox1.Items.Add("String value: " + fileName);
      }
    }
</code>```

The results look something like String value: I:\folder\ico.lnk

I need to access the properties associated with the icon: target type, target location, starting, Shortcut key, etc.

Body:
I need to access the icon's image and its properties when the icon is dropped onto a form.

I have tried variations of e.Data.GetData(DataFormats.FileDrop) but that only provides me with the text for the .lnk.

My drop routine is:

    private void listBox1_DragDrop(object sender, DragEventArgs e)
    {
      Array dataObjects = (Array)e.Data.GetData(DataFormats.FileDrop);
      for (int i = 0; i < dataObjects.Length; ++i)
      {
        string fileName = dataObjects.GetValue(i).ToString();
        listBox1.Items.Add("String value: " + fileName);
      }
    }

The results look something like String value: I:\folder\ico.lnk

I need to access the properties associated with the icon: target type, target location, starting, Shortcut key, etc.


问:
What is causing "Could not resolve CoreCLR path" when referencing a Console App from another Console App?
I'm trying to build a console application, A, into another console application, B (an NUnit testing project). B references A by a ProjectReference.

It seems that necessary dependencies for A aren't copied over. When running A on its build, it works fine. All is also fine when I run B without referencing A. Thus, why is it that the CoreCLR path cannot be resolved in the case of B referencing A?

Some similar questions I've found are no use;

https://github.com/dotnet/sdk/issues/5779 - My runtimeconfig is as follows;

{
    "runtimeOptions": {
        "tfm" : "net6.0",
        "framework" : {
            "name" : "Microsoft.NETCore.App",
            "version" : "6.0.12"
        }
    }
}
```
<ul>
<li>https://github.com/dotnet/sdk/issues/5844 - Not related</li>
<li>https://github.com/dotnet/core/issues/4825 - Not fully related</li>
</ul>
<p>Note that setting <code>COREHOST_TRACE</code> to 1 only provides the same error (directly after culture dependency errors/logs)</p>
<pre class="lang-bash prettyprint-override"><code>Could not resolve CoreCLR path. For more details, enable tracing by setting COREHOST_TRACE environment variable to 1
</code>```

https://github.com/dotnet/sdk/issues/5916 - dotnet restore and dotnet build are of no use.

https://github.com/dotnet/sdk/issues/5672 - Fix seems irrelevant

https://developercommunity.visualstudio.com/t/could-not-resolve-coreclr-path-error/50916 - I'm using win-x86, no changes there

https://github.com/dotnet/sdk/issues/4870 - Not using Ubuntu, seems irrelevant

As for https://github.com/dotnet/sdk/issues/4870#issuecomment-542991656;

I can confirm that the necessary package dependencies and JSON files are present in the output directory of B. This is what actually fixed a preceding error, relating to hostpolicy.dll.

Body:
I'm trying to build a console application, A, into another console application, B (an NUnit testing project). B references A by a ProjectReference.

It seems that necessary dependencies for A aren't copied over. When running A on its build, it works fine. All is also fine when I run B without referencing A. Thus, why is it that the CoreCLR path cannot be resolved in the case of B referencing A?

Some similar questions I've found are no use;

https://github.com/dotnet/sdk/issues/5779 - My runtimeconfig is as follows;

{
    "runtimeOptions": {
        "tfm" : "net6.0",
        "framework" : {
            "name" : "Microsoft.NETCore.App",
            "version" : "6.0.12"
        }
    }
}

https://github.com/dotnet/sdk/issues/5844 - Not related

https://github.com/dotnet/core/issues/4825 - Not fully related

Note that setting COREHOST_TRACE to 1 only provides the same error (directly after culture dependency errors/logs)

Could not resolve CoreCLR path. For more details, enable tracing by setting COREHOST_TRACE environment variable to 1

https://github.com/dotnet/sdk/issues/5916 - dotnet restore and dotnet build are of no use.

https://github.com/dotnet/sdk/issues/5672 - Fix seems irrelevant

https://developercommunity.visualstudio.com/t/could-not-resolve-coreclr-path-error/50916 - I'm using win-x86, no changes there

https://github.com/dotnet/sdk/issues/4870 - Not using Ubuntu, seems irrelevant

As for https://github.com/dotnet/sdk/issues/4870#issuecomment-542991656;

I can confirm that the necessary package dependencies and JSON files are present in the output directory of B. This is what actually fixed a preceding error, relating to hostpolicy.dll.


问:
How to display an animation when receiving an SSE event in ReactJS
I have to build rock paper scissors ReactJS app for my end of term exam. I'm provided an API which supports SSE. I was wondering how I could display a sort of animation (with framer-motion) when receiving a certain event. I thought using a boolean state that could be false by default and set to true when receiving an event. Maybe it could be reset after a timeout which would be equal to the animation duration.

I can't make myself believe this is a good solution, but right now it's the only solution I got on my mind.


问:
Ray Tune conflicting with the `breakpoint()` function
The code section attached below, which is basically copy-pasted from the official documentation of Ray Tune runs as expected until the last line, but calling breakpoint() after tuner.fit() breaks the debugger (I can't see any call stack or local variables in PyCharm's debugger), and prints the following warning:

```<code>PYDEV DEBUGGER WARNING:
sys.settrace() should not be used when the debugger is being used.
This may cause the debugger to stop working correctly.
If this is needed, please check:
http://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-with.html
to see how to restore the debug tracing back correctly.
Call Location:
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\bdb.py", line 334, in set_trace
    sys.settrace(self.trace_dispatch)

*** Temporarily disabling Ray worker logs ***
--Return--
> c:\users\username\appdata\local\jetbrains\toolbox\apps\pycharm-p\ch-0\223.7571.203\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_breakpointhook.py(13)pydevd_breakpointhook()->None
-> sys.__breakpointhook__(*args, **kwargs)
(Pdb)
>?
</code>```

How could I solve the issue and make the breakpoint() function and the debugger work as expected?

I'm using PyCharm, Python 3.8.10, Windows 10.

main.py

```<code>from ray import tune
from ray.tune.search.bayesopt import BayesOptSearch
from ray import air
from ray.air import session

def objective(x, a, b):  # Define an objective function.
    return a * (x**0.5) + b

def trainable(config):  # Pass a "config" dictionary into your trainable.

    for x in range(20):  # "Train" for 20 iterations and compute intermediate scores.
        score = objective(x, config["a"], config["b"])

        session.report({"score": score})  # Send the score to Tune.

# Define the search space
search_space = {"a": tune.uniform(0, 1), "b": tune.uniform(0, 20)}

algo = BayesOptSearch(random_search_steps=4)

tuner = tune.Tuner(
    trainable,
    tune_config=tune.TuneConfig(
        metric="score",
        mode="min",
        search_alg=algo,
    ),
    run_config=air.RunConfig(stop={"training_iteration": 20}),
    param_space=search_space,
)

breakpoint()  # works as expected

r = tuner.fit()

breakpoint()  # raises warning

</code>```

requirements.txt

```<code>pip==21.3.1
setuptools==60.2.0
wheel==0.37.1
ray[tune]==2.2.0
bayesian-optimization==1.4.2

</code>```

What have I tried?

Inside the PDB session, using traceback.print_stack() I get the following:

```<code>  ... pydev/pydevd.py ...
  File "C:\Repos\RayTune\main.py", line 38, in <module>
    breakpoint()  # raises warning
  File "C:\Users\username\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\223.7571.203\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_breakpointhook.py", line 27, in breakpointhook
    pydevd_breakpointhook()
  File "C:\Users\username\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\223.7571.203\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_breakpointhook.py", line 13, in pydevd_breakpointhook
    sys.__breakpointhook__(*args, **kwargs)
File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\bdb.py", line 92, in trace_dispatch
    return self.dispatch_return(frame, arg)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\bdb.py", line 151, in dispatch_return
    self.user_return(frame, arg)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 294, in user_return
    self.interaction(frame, None)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 357, in interaction
    self._cmdloop()
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 322, in _cmdloop
    self.cmdloop()
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\cmd.py", line 138, in cmdloop
    stop = self.onecmd(line)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 423, in onecmd
    return cmd.Cmd.onecmd(self, line)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\cmd.py", line 216, in onecmd
    return self.default(line)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 381, in default
    exec(code, globals, locals)
  File "<stdin>", line 1, in <module>
</code>```

locals() evaluate to:

```<code>{'args': (), 'kwargs': {}, 'hookname': 'ray.util.rpdb._driver_set_trace', '__return__': None, 'traceback': <module 'traceback' from 'C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38\\lib\\traceback.py'>}
</code>```

Body:
The code section attached below, which is basically copy-pasted from the official documentation of Ray Tune runs as expected until the last line, but calling breakpoint() after tuner.fit() breaks the debugger (I can't see any call stack or local variables in PyCharm's debugger), and prints the following warning:

PYDEV DEBUGGER WARNING:
sys.settrace() should not be used when the debugger is being used.
This may cause the debugger to stop working correctly.
If this is needed, please check:
http://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-with.html
to see how to restore the debug tracing back correctly.
Call Location:
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\bdb.py", line 334, in set_trace
    sys.settrace(self.trace_dispatch)

*** Temporarily disabling Ray worker logs ***
--Return--
> c:\users\username\appdata\local\jetbrains\toolbox\apps\pycharm-p\ch-0\223.7571.203\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_breakpointhook.py(13)pydevd_breakpointhook()->None
-> sys.__breakpointhook__(*args, **kwargs)
(Pdb)
>?

How could I solve the issue and make the breakpoint() function and the debugger work as expected?

I'm using PyCharm, Python 3.8.10, Windows 10.

main.py

from ray import tune
from ray.tune.search.bayesopt import BayesOptSearch
from ray import air
from ray.air import session

def objective(x, a, b):  # Define an objective function.
    return a * (x**0.5) + b

def trainable(config):  # Pass a "config" dictionary into your trainable.

    for x in range(20):  # "Train" for 20 iterations and compute intermediate scores.
        score = objective(x, config["a"], config["b"])

        session.report({"score": score})  # Send the score to Tune.

# Define the search space
search_space = {"a": tune.uniform(0, 1), "b": tune.uniform(0, 20)}

algo = BayesOptSearch(random_search_steps=4)

tuner = tune.Tuner(
    trainable,
    tune_config=tune.TuneConfig(
        metric="score",
        mode="min",
        search_alg=algo,
    ),
    run_config=air.RunConfig(stop={"training_iteration": 20}),
    param_space=search_space,
)

breakpoint()  # works as expected

r = tuner.fit()

breakpoint()  # raises warning

requirements.txt

pip==21.3.1
setuptools==60.2.0
wheel==0.37.1
ray[tune]==2.2.0
bayesian-optimization==1.4.2

What have I tried?

Inside the PDB session, using traceback.print_stack() I get the following:

  ... pydev/pydevd.py ...
  File "C:\Repos\RayTune\main.py", line 38, in <module>
    breakpoint()  # raises warning
  File "C:\Users\username\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\223.7571.203\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_breakpointhook.py", line 27, in breakpointhook
    pydevd_breakpointhook()
  File "C:\Users\username\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\223.7571.203\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_breakpointhook.py", line 13, in pydevd_breakpointhook
    sys.__breakpointhook__(*args, **kwargs)
File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\bdb.py", line 92, in trace_dispatch
    return self.dispatch_return(frame, arg)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\bdb.py", line 151, in dispatch_return
    self.user_return(frame, arg)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 294, in user_return
    self.interaction(frame, None)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 357, in interaction
    self._cmdloop()
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 322, in _cmdloop
    self.cmdloop()
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\cmd.py", line 138, in cmdloop
    stop = self.onecmd(line)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 423, in onecmd
    return cmd.Cmd.onecmd(self, line)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\cmd.py", line 216, in onecmd
    return self.default(line)
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\pdb.py", line 381, in default
    exec(code, globals, locals)
  File "<stdin>", line 1, in <module>

locals() evaluate to:

{'args': (), 'kwargs': {}, 'hookname': 'ray.util.rpdb._driver_set_trace', '__return__': None, 'traceback': <module 'traceback' from 'C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python38\\lib\\traceback.py'>}


问:
Firebase Realtime Database Setup Rules For Custom Auth
I am using Firebase Real time database for our chat app and it's works fine until i try to set rules
right now i have unsecured rules.

```<code>{
  "rules": {
    ".read": true,
    ".write": true
  }
}
</code>```

Where anyone can write and read the entire database. So i generate custom token at user login then  sign in with FirebaseAuth.

```<code>mAuth.signInWithCustomToken(mCustomToken)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success

                } else {
                    // If sign in fails
                    Toast.makeText(CustomAuthActivity.this, "Authentication failed.",
                }
            }
        });
</code>```

If i use Database reference without child DatabaseReference db = FirebaseDatabase.getInstance().getReference() and rules like below then it's works without any issues

```<code>{
  "rules": {
    ".read": "auth.uid !== null",
    ".write": "auth.uid !== null",
  }
}
</code>```

and when i start adding children like this DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Chat"); then it showing DatabaseError: Permission denied in log. My app is live with users so it won't set rules for now because it will block our users to access database and chat.

This is my actual realtime database.

```<code>{
  "Chat": {
    "919810012345-919810012346": "",
    "919810012347-919810012348": {
      "-NI7hqW3YTFKpnSZU422": {
        "Message": "Test Message",
        "Message_From": "Demo User5",
        "Message_From_ID": "0001",
        "Message_To": "Test User",
        "Status": "Delivered",
        "Time": "1669814773643",
      }
    },
    "919810012345-919810012349": "",
    "919810012345-919810012350": {
      "-NI7hXybU02Mg6vYqdKp": {
        "Message": "Test Message",
        "Message_From": "Demo User5 ",
        "Message_From_ID": "0001",
        "Message_To": "Dummy User",
        "Status": "Delivered",
        "Time": "1669814693724",
        "Type": "Typed_Message",
      }
    }
  },
  "Users": {
    "0001": {
      "Online": false,
      "lastSeen": "1671742997177"
    },
    "0002": {
      "Online": false
    },
    "0003": {
      "Online": false
    }
  },
  "UsersLocations": {
    "0001": {
      "-1": {
        "Latitude": "28.531",
        "Longitude": "77.257"
      }
    }
  }
}
</code>```

Can anyone help me to set rules for above database structure?

Body:
I am using Firebase Real time database for our chat app and it's works fine until i try to set rules
right now i have unsecured rules.

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Where anyone can write and read the entire database. So i generate custom token at user login then  sign in with FirebaseAuth.

mAuth.signInWithCustomToken(mCustomToken)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success

                } else {
                    // If sign in fails
                    Toast.makeText(CustomAuthActivity.this, "Authentication failed.",
                }
            }
        });

If i use Database reference without child DatabaseReference db = FirebaseDatabase.getInstance().getReference() and rules like below then it's works without any issues

{
  "rules": {
    ".read": "auth.uid !== null",
    ".write": "auth.uid !== null",
  }
}

and when i start adding children like this DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Chat"); then it showing DatabaseError: Permission denied in log. My app is live with users so it won't set rules for now because it will block our users to access database and chat.

This is my actual realtime database.

{
  "Chat": {
    "919810012345-919810012346": "",
    "919810012347-919810012348": {
      "-NI7hqW3YTFKpnSZU422": {
        "Message": "Test Message",
        "Message_From": "Demo User5",
        "Message_From_ID": "0001",
        "Message_To": "Test User",
        "Status": "Delivered",
        "Time": "1669814773643",
      }
    },
    "919810012345-919810012349": "",
    "919810012345-919810012350": {
      "-NI7hXybU02Mg6vYqdKp": {
        "Message": "Test Message",
        "Message_From": "Demo User5 ",
        "Message_From_ID": "0001",
        "Message_To": "Dummy User",
        "Status": "Delivered",
        "Time": "1669814693724",
        "Type": "Typed_Message",
      }
    }
  },
  "Users": {
    "0001": {
      "Online": false,
      "lastSeen": "1671742997177"
    },
    "0002": {
      "Online": false
    },
    "0003": {
      "Online": false
    }
  },
  "UsersLocations": {
    "0001": {
      "-1": {
        "Latitude": "28.531",
        "Longitude": "77.257"
      }
    }
  }
}

Can anyone help me to set rules for above database structure?


问:
Restarting dependency docker container
as per this docker-compose file

```<code>version: "3.8"
services:
  b:
    image: b
    restart: "on-failure"
    ports:
      - "6002:6002"
  a:
    image: a
    restart: "on-failure"
    depends_on:
      - b
  c:
    image: c
    restart: "on-failure"
</code>```

in case container a restarts container b should be restarted.

Any guidance please help.

I tried placing the shell script in dockerfile container.
Since I can't come docker-compose directory this attempt failed.

Title: Restarting dependency docker container

Body:
as per this docker-compose file

version: "3.8"
services:
  b:
    image: b
    restart: "on-failure"
    ports:
      - "6002:6002"
  a:
    image: a
    restart: "on-failure"
    depends_on:
      - b
  c:
    image: c
    restart: "on-failure"

in case container a restarts container b should be restarted.

Any guidance please help.

I tried placing the shell script in dockerfile container.
Since I can't come docker-compose directory this attempt failed.


问:
Mudblazor: How to add child div to main div on button click
I am not much familiar with Javascript. I am working on a Mudblazor project. All the Backend and Frontend logic is implemented using c#. I have main div which displays several MudTextFields in one child div (Div1) and after this div there is another child div (Div2) which displays MudSelect associated with MudTextField. Please see the image below.

You can see in Picture two child divs Div1 and Div2. I want that when Add Div MudButton is clicked than a new row should be added into Div2 so that I could select new MudSelectItem from MudSelect and enter it's value into MudTextField. Please guide me how can I implement this requirement.
I will appreciate your help.


问:
invalid project layout error while deploying shiny app
I want to deploy a shiny app but i am getting this error.

Error in lint(appDir, appFiles, appPrimaryDoc) :
Cancelling deployment: invalid project layout.
The project should have one of the following layouts:

'server.R' and 'ui.R' in the application base directory,

'server.R' and 'www/index.html' in the application base directory,

'app.R' or a single-file Shiny .R file,

An R Markdown (.Rmd) or Quarto (.qmd) document,

A static HTML (.html) or PDF (.pdf) document.

'plumber.R' API description .R file

'entrypoint.R' plumber startup script

A tensorflow saved model

rsconnect::deployApp('Shared/Thomas/thomaps')

thomaps has an r script and a data folder with one excel sheet in it.


问:
Discord bot not responding correctly in the console
I've started developing a discord bot and for some reason the bot I've created won't print the correct text in the console.

```<code>import hikari

bot = hikari.GatewayBot(token = "TOKEN")

@bot.listen(hikari.GuildMessageCreateEvent)
async def print_message(event):
    print(event.content)

bot.run()
</code>```

In discord, when a message is sent the bot should print it in the console, for example:
My discord window
But whatever I input the bot always outputs 'None'. What should I do? I've been following this tutorial; Tutorial playlist and I've copied the code exactly as the video says and it still doesn't work?

Body:
I've started developing a discord bot and for some reason the bot I've created won't print the correct text in the console.

import hikari

bot = hikari.GatewayBot(token = "TOKEN")

@bot.listen(hikari.GuildMessageCreateEvent)
async def print_message(event):
    print(event.content)

bot.run()

In discord, when a message is sent the bot should print it in the console, for example:
My discord window
But whatever I input the bot always outputs 'None'. What should I do? I've been following this tutorial; Tutorial playlist and I've copied the code exactly as the video says and it still doesn't work?


问:
Can we use Eventarc to trigger a google workflow only if certain set of google workflows get executed?
I am having use case where one workflow needs to be executed if certain n no. of workflows gets completed. Can we achieve this using eventarc trigger feature of Google Cloud ?</p>


问:
Android SDK onCreate problem
I think I've gotten myself seriously confused.  Up until recently my app was working great.  I hadn't changed anything except updated java and android tools.  I'm not sure if that caused my problem or what, that's all I can remember changing related to it.

Here's the problem I'm running into, which just started.

Debug mode (installed app on phone through Eclipse):

Tap app icon to open app, onCreate is called

Hit home button, state is saved

Tap app icon to open app, it resumes, onCreate is not called

That worked, my app is happy.

Now I export the signed and zip aligned app, remove the app on my phone, install the new one, and repeat these steps:

Tap app icon to open app, onCreate is called

Hit home button, state is saved

Tap app icon to open app, onCreate is called again

Ugg, onCreate is called again? Bundle is null, my variables reset. This happens on the emulator too and for other users of the app.  I can hold the home button down and switch to it and it continue where it left off but if I tap the icon it calls onCreate every single time.

Why is this happening?  My app is a single activity.

ContentLicense: CC BY-SA 3.0

Title: Android SDK onCreate problem


问:
How to regenerate autoloader per local changes to package composer.json
I know this is sloppy and unconventional, but I need to test some changes to a package by manually adjusting a composer.json file within a package in the vendor folder. But I can't figure out how to get the new dependencies and "autoloader->file" changes to take hold. I've tried composer install, composer dumpautoload -o, and installing directly from that folder (which merely created a new and useless "vendor" folder within the package directory).

Is this even possible, or just too sloppy for Composer to offer a way to go about it?


问:
Set defaultValue for association field that targets a unique non-primary key
I have two tables on Postgres:

```<code>class Account extends Model {
    static associate(models) {
      Account.belongsTo(models.Status, {
        targetKey: 'name',
        foreignKey: { name: 'status', allowNull: false, defaultValue: 'offline' },
      })
    }}

Account.init(
    {
      firstName: { type: DataTypes.STRING, allowNull: false },
      lastName: { type: DataTypes.STRING, allowNull: false },
      email: { type: DataTypes.STRING, allowNull: false, unique: true },
      password: { type: DataTypes.STRING, allowNull: false },
      image: DataTypes.STRING,
      telephone: DataTypes.STRING,
    },
    {
      sequelize,
      tableName: 'accounts',
    },
)
</code>```
```<code>  class Status extends Model {}
  Status.init(
    {
      name: { type: DataTypes.STRING, allowNull: false, unique: true },
    },
    {
      sequelize,
      tableName: 'statuses',
    },
  )
</code>```

I want to set the default association Status for Account to be the record with the name "offline". And in top of that I want to reference not the primary key, but the unique value on the name column.

The generated query is:
ALTER TABLE "accounts" ALTER COLUMN "status" SET NOT NULL;ALTER TABLE "accounts" ALTER COLUMN "status" SET DEFAULT 'offline' REFERENCES "statuses" ("name") ON DELETE NO ACTION ON UPDATE CASCADE;ALTER TABLE "accounts" ALTER COLUMN "status" TYPE VARCHAR(255);

But it throws the following error when doing Sequelize.sync() :
syntax error at or near «REFERENCES»

Body:
I have two tables on Postgres:

class Account extends Model {
    static associate(models) {
      Account.belongsTo(models.Status, {
        targetKey: 'name',
        foreignKey: { name: 'status', allowNull: false, defaultValue: 'offline' },
      })
    }}

Account.init(
    {
      firstName: { type: DataTypes.STRING, allowNull: false },
      lastName: { type: DataTypes.STRING, allowNull: false },
      email: { type: DataTypes.STRING, allowNull: false, unique: true },
      password: { type: DataTypes.STRING, allowNull: false },
      image: DataTypes.STRING,
      telephone: DataTypes.STRING,
    },
    {
      sequelize,
      tableName: 'accounts',
    },
)

  class Status extends Model {}
  Status.init(
    {
      name: { type: DataTypes.STRING, allowNull: false, unique: true },
    },
    {
      sequelize,
      tableName: 'statuses',
    },
  )

I want to set the default association Status for Account to be the record with the name "offline". And in top of that I want to reference not the primary key, but the unique value on the name column.

The generated query is:
ALTER TABLE "accounts" ALTER COLUMN "status" SET NOT NULL;ALTER TABLE "accounts" ALTER COLUMN "status" SET DEFAULT 'offline' REFERENCES "statuses" ("name") ON DELETE NO ACTION ON UPDATE CASCADE;ALTER TABLE "accounts" ALTER COLUMN "status" TYPE VARCHAR(255);

But it throws the following error when doing Sequelize.sync() :
syntax error at or near «REFERENCES»


问:
React native expo: deep link / url scheme to send instagram direct message
I'm looking for a way to send a direct message on instagram from my app using url schemes, this is the example of whatsapp

```<code>let url = "whatsapp://send?text=" + msg;
</code>```

I basically want to do the same for instagram. Anyone ever find a solution for this ?

Thank you,

Body:
I'm looking for a way to send a direct message on instagram from my app using url schemes, this is the example of whatsapp

let url = "whatsapp://send?text=" + msg;

I basically want to do the same for instagram. Anyone ever find a solution for this ?

Thank you,


问:
Android Unity build crashes during the spash screen, upon the re-entry of the application
After building the game and sending it to my phone as an apk and then installing it. Then I launch the game and it works.

But, after exiting the game, the second time it's launched, it seems to freeze at the splash screen. After the unity logo disappears, it looks like the screen is resizing itself, as the background image of the splash screen which seems to be frozen gets a little bigger on a side of the screen (when landscaping)

So far I have attempted:

Modifying the manifest, I got nothing.

Changing Unity versions, I got nothing. The only version that seems stable and runs properly it's 2019.2.21f1, I am using this version because of my hardware limitations. I am also using 2019.4, but it's not a big difference, and I get the same problem.

Disabling Optimised Frame Pacing but nothing.

I also tried different API levels, Gradle versions, and JDKs. All that can be updated and downgraded but still nothing.


问:
How to create short incremental Unique IDs for content database in Notion
I'm struggling with finding the correct answer for incrementally increasing unique ids. I'm creating a database to create a content database inside Notion.

I want to create something similar to this video - https://youtu.be/60d1yusIadc - in Airtable they can create a function and concat that with an auto number. I left a pic of where I'm currently at with the code, but there should be a simpler way to do this functionally.

Current Notion code - "C " + slice(id(), 0, 5)


问:
Finding average of multiple lines in matplotlib
I am trying to create a graph that takes the averages from the below lines and plot them on the same new graph of the same nature.

```<code>fig, ax = plt.subplots(1,1, figsize=(10,12))
yticks = np.arange(nchan) * 0.2

lines_BC = plt.plot(resampled_BC.T + yticks[np.newaxis], label = "BC", c='black')
lines_CP = plt.plot(resampled_CP.T + yticks[np.newaxis], label = "CP", c='red')
lines_CR = plt.plot(resampled_CR.T + yticks[np.newaxis], label = "CR", c='cyan')
lines_DC = plt.plot(resampled_DC.T + yticks[np.newaxis], label = "DC", c='blue')
lines_JC = plt.plot(resampled_JC.T + yticks[np.newaxis], label = "JC", c='lime')

ax.set_yticks(yticks)
ax.set_yticklabels(muscles)
ax.set_ylabel('Muscles')
ax.set_xlabel('Time (ms)')
leg = ax.legend([lines_BC[0]] + [lines_CP[0]] + [lines_CR[0]] + [lines_DC[0]] + [lines_JC[0]], ['BC', 'CP', 'CR', 'DC', 'JC'], loc='upper right')
plt.show()
</code>```

I have tried using np.mean but to no luck.

Body:
I am trying to create a graph that takes the averages from the below lines and plot them on the same new graph of the same nature.

fig, ax = plt.subplots(1,1, figsize=(10,12))
yticks = np.arange(nchan) * 0.2

lines_BC = plt.plot(resampled_BC.T + yticks[np.newaxis], label = "BC", c='black')
lines_CP = plt.plot(resampled_CP.T + yticks[np.newaxis], label = "CP", c='red')
lines_CR = plt.plot(resampled_CR.T + yticks[np.newaxis], label = "CR", c='cyan')
lines_DC = plt.plot(resampled_DC.T + yticks[np.newaxis], label = "DC", c='blue')
lines_JC = plt.plot(resampled_JC.T + yticks[np.newaxis], label = "JC", c='lime')

ax.set_yticks(yticks)
ax.set_yticklabels(muscles)
ax.set_ylabel('Muscles')
ax.set_xlabel('Time (ms)')
leg = ax.legend([lines_BC[0]] + [lines_CP[0]] + [lines_CR[0]] + [lines_DC[0]] + [lines_JC[0]], ['BC', 'CP', 'CR', 'DC', 'JC'], loc='upper right')
plt.show()

I have tried using np.mean but to no luck.


问:
Nifi Unable to convert CSV to Excel using POI API
I want to convert csv flowfile content into XLS file usin groovy script + POI API

I m using ivy to grab POI dependencies and it seems work well.

please find more details below:

This is my Nifi flow:

This is my script

```<code>@Grapes(@Grab(group='org.apache.poi', module='poi-ooxml', version='3.9'))
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.extractor.*
import java.nio.charset.*
import java.io.*
import org.apache.commons.io.IOUtils

def flowFile = session.get()
def date = new Date()

if(!flowFile) return

flowFile = session.write(flowFile, {inputStream, outputStream ->
try {

Workbook wb = WorkbookFactory.create(inputStream,);
Sheet mySheet = wb.getSheetAt(0);

def record = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
outputStream.write(record.getBytes(StandardCharsets.UTF_8))

wb.close();

} catch(e) {
 log.error("Error during processing", e)
 session.transfer(flowFile, REL_FAILURE)
}
} as StreamCallback)

def filename = flowFile.getAttribute('filename')+'.xlsx'
flowFile = session.putAttribute(flowFile, 'filename', filename)

session.transfer(flowFile, REL_SUCCESS)
</code>```

I get this error

Any idea about this error ?

Edit:
I changed my script and still had the same error:

```<code>@Grapes(@Grab(group='org.apache.poi', module='poi-ooxml', version='3.9'))
import com.opencsv.CSVReader
@Grapes(@Grab(group='com.opencsv', module='opencsv', version='4.2'))
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.extractor.*
import java.nio.charset.*
import java.io.*
import org.apache.commons.io.IOUtils

def flowFile = session.get()
def date = new Date()

if(!flowFile) return

flowFile = session.write(flowFile, {inputStream, outputStream ->
try {
def nextLine = ''
reader = new CSVReader(new FileReader(csvFilePath), FILE_DELIMITER);

  Workbook wb = WorkbookFactory.create(inputStream,);
 Sheet sheet1 = wb.createSheet("Feuille");

// workBook = new SXSSFWorkbook();
//sheet = (SXSSFSheet) workBook.createSheet('Sheet');

int rowNum = 0;
while((nextLine = reader.readNext()) != null) {
Row currentRow = sheet1.createRow(rowNum++);
for(int i=0; i < nextLine.length; i++) {
if(NumberUtils.isDigits(nextLine[i])) {
currentRow.createCell(i).setCellValue(Integer.parseInt(nextLine[i]));
} else if (NumberUtils.isNumber(nextLine[i])) {
currentRow.createCell(i).setCellValue(Double.parseDouble(nextLine[i]));
} else {
currentRow.createCell(i).setCellValue(nextLine[i]);
}
}
}

fileOutputStream = new FileOutputStream(generatedXlsFilePath.trim());
wb.write(fileOutputStream);

wb.close();
fileOutputStream.close();
reader.close();
outputStream.close();

} catch(e) {
session.transfer(flowFile, REL_FAILURE)
}
} as StreamCallback)

def filename = flowFile.getAttribute('filename')+'.xlsx'
flowFile = session.putAttribute(flowFile, 'filename', filename)

session.transfer(flowFile, REL_SUCCESS)
</code>```

Body:
I want to convert csv flowfile content into XLS file usin groovy script + POI API

I m using ivy to grab POI dependencies and it seems work well.

please find more details below:

This is my Nifi flow:

This is my script

@Grapes(@Grab(group='org.apache.poi', module='poi-ooxml', version='3.9'))
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.extractor.*
import java.nio.charset.*
import java.io.*
import org.apache.commons.io.IOUtils

def flowFile = session.get()
def date = new Date()

if(!flowFile) return

flowFile = session.write(flowFile, {inputStream, outputStream ->
try {

Workbook wb = WorkbookFactory.create(inputStream,);
Sheet mySheet = wb.getSheetAt(0);

def record = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
outputStream.write(record.getBytes(StandardCharsets.UTF_8))

wb.close();

} catch(e) {
 log.error("Error during processing", e)
 session.transfer(flowFile, REL_FAILURE)
}
} as StreamCallback)

def filename = flowFile.getAttribute('filename')+'.xlsx'
flowFile = session.putAttribute(flowFile, 'filename', filename)

session.transfer(flowFile, REL_SUCCESS)

I get this error

Any idea about this error ?

Edit:
I changed my script and still had the same error:

@Grapes(@Grab(group='org.apache.poi', module='poi-ooxml', version='3.9'))
import com.opencsv.CSVReader
@Grapes(@Grab(group='com.opencsv', module='opencsv', version='4.2'))
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.extractor.*
import java.nio.charset.*
import java.io.*
import org.apache.commons.io.IOUtils

def flowFile = session.get()
def date = new Date()

if(!flowFile) return

flowFile = session.write(flowFile, {inputStream, outputStream ->
try {
def nextLine = ''
reader = new CSVReader(new FileReader(csvFilePath), FILE_DELIMITER);

  Workbook wb = WorkbookFactory.create(inputStream,);
 Sheet sheet1 = wb.createSheet("Feuille");

// workBook = new SXSSFWorkbook();
//sheet = (SXSSFSheet) workBook.createSheet('Sheet');

int rowNum = 0;
while((nextLine = reader.readNext()) != null) {
Row currentRow = sheet1.createRow(rowNum++);
for(int i=0; i < nextLine.length; i++) {
if(NumberUtils.isDigits(nextLine[i])) {
currentRow.createCell(i).setCellValue(Integer.parseInt(nextLine[i]));
} else if (NumberUtils.isNumber(nextLine[i])) {
currentRow.createCell(i).setCellValue(Double.parseDouble(nextLine[i]));
} else {
currentRow.createCell(i).setCellValue(nextLine[i]);
}
}
}

fileOutputStream = new FileOutputStream(generatedXlsFilePath.trim());
wb.write(fileOutputStream);

wb.close();
fileOutputStream.close();
reader.close();
outputStream.close();

} catch(e) {
session.transfer(flowFile, REL_FAILURE)
}
} as StreamCallback)

def filename = flowFile.getAttribute('filename')+'.xlsx'
flowFile = session.putAttribute(flowFile, 'filename', filename)

session.transfer(flowFile, REL_SUCCESS)


问:
Changing the size of a FitImage in proportion to Swiper Size
I'm trying to change the size of a swiper in kivymd while also making the image viewable at the same time.

```<code><SwiperItem1@MDSwiperItem>

    FitImage:
        source: "duck1.png"
        radius: [20,]

MDScreen:

    MDFloatLayout:
        size_hint:1,1
        radius: [20,]
        MDSwiper:
            size_hint: 0.3,1
            pos_hint:{"center_x":0.5,"center_y":0.5}

            SwiperItem1:

</code>```

Using that, I have been changing the size_hint of the swiper and when I do that the FitImage doesn't change in proportion, so when size_hint is changed to 0.3 and 1, 30% of the image is shown of the x axis and 100% on the y axis, which is in accordance to the percentages on size_hint yet I'm trying to make the image size change with the swiper to make the image completely viewable in a smaller swiper.

Body:
I'm trying to change the size of a swiper in kivymd while also making the image viewable at the same time.

<SwiperItem1@MDSwiperItem>

    FitImage:
        source: "duck1.png"
        radius: [20,]

MDScreen:

    MDFloatLayout:
        size_hint:1,1
        radius: [20,]
        MDSwiper:
            size_hint: 0.3,1
            pos_hint:{"center_x":0.5,"center_y":0.5}

            SwiperItem1:

Using that, I have been changing the size_hint of the swiper and when I do that the FitImage doesn't change in proportion, so when size_hint is changed to 0.3 and 1, 30% of the image is shown of the x axis and 100% on the y axis, which is in accordance to the percentages on size_hint yet I'm trying to make the image size change with the swiper to make the image completely viewable in a smaller swiper.


问:
Pytorch Video model frame_length X sample rate
Pre-trained pytorch video models have names like:

```<code>slowfast_4x16_resnet50_kinetics400
</code>```

4 is the frame_length, 16 is the sample rate.

What do they mean. Let us say I have a video at 30 frames per second. Do I take every 16th frame (sample rate) and include 4 such samples as input to the model?

Just trying to figure out what frame length and sample rate mean and how they are used.

Thank you very much

Look at pytorch model documents. No luck so far.

Body:
Pre-trained pytorch video models have names like:

slowfast_4x16_resnet50_kinetics400

4 is the frame_length, 16 is the sample rate.

What do they mean. Let us say I have a video at 30 frames per second. Do I take every 16th frame (sample rate) and include 4 such samples as input to the model?

Just trying to figure out what frame length and sample rate mean and how they are used.

Thank you very much

Look at pytorch model documents. No luck so far.


问:
Wrap a hyper::Body in a BufReader in Rust
I have a hyper::Body and I want to wrap it in a BufReader (for example tokio::io::BufReader, but futures_util::io::BufReader or any other is fine too).

Using it directly didn't work:

fn foo(body: hyper::Body) {
    let bufreader = tokio::io::BufReader::new(body);
}
```
```error[E0277]: the trait bound `Body: AsyncRead` is not satisfied
  --> src/lib.rs:2:47
   |
2  |     let bufreader = tokio::io::BufReader::new(body);
   |                     ------------------------- ^^^^ the trait `AsyncRead` is not implemented for `Body`
   |                     |
   |                     required by a bound introduced by this call
   |
   = help: the following other types implement trait `AsyncRead`:
             &[u8]
             &mut T
             AddrStream
             Box<T>
             BufStream<RW>
             DuplexStream
             Pin

             Upgraded
           and 20 others
note: required by a bound in `tokio::io::BufReader::<R>::new`
  --> /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.23.0/src/io/util/buf_reader.rs:37:9
   |
37 | impl<R: AsyncRead> BufReader<R> {
   |         ^^^^^^^^^ required by this bound in `tokio::io::BufReader::<R>::new`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error
```

I'm aware there are multiple AsyncRead in rust, tokio_util::compat::* and futures_util::compat::* can be used to convert between them, but it seems hyper::Body doesn't implement either of them.

It implements futures_core::stream::Stream but I don't know how to feed this into a BufReader.

Body:
I have a hyper::Body and I want to wrap it in a BufReader (for example tokio::io::BufReader, but futures_util::io::BufReader or any other is fine too).

Using it directly didn't work:

fn foo(body: hyper::Body) {
    let bufreader = tokio::io::BufReader::new(body);
}

error[E0277]: the trait bound `Body: AsyncRead` is not satisfied
  --> src/lib.rs:2:47
   |
2  |     let bufreader = tokio::io::BufReader::new(body);
   |                     ------------------------- ^^^^ the trait `AsyncRead` is not implemented for `Body`
   |                     |
   |                     required by a bound introduced by this call
   |
   = help: the following other types implement trait `AsyncRead`:
             &[u8]
             &mut T
             AddrStream
             Box<T>
             BufStream<RW>
             DuplexStream
             Pin

             Upgraded
           and 20 others
note: required by a bound in `tokio::io::BufReader::<R>::new`
  --> /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.23.0/src/io/util/buf_reader.rs:37:9
   |
37 | impl<R: AsyncRead> BufReader<R> {
   |         ^^^^^^^^^ required by this bound in `tokio::io::BufReader::<R>::new`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error

I'm aware there are multiple AsyncRead in rust, tokio_util::compat::* and futures_util::compat::* can be used to convert between them, but it seems hyper::Body doesn't implement either of them.

It implements futures_core::stream::Stream but I don't know how to feed this into a BufReader.


问:
Save json list in a text file
I got a json log file that i rearrange to be correct, after this i am trying to save the results to the same file. The results are a list. but the problem that i am unable to save and will give me the following error:

```<code>write() argument must be str, not list
</code>```

Here is the code it self:

```<code>

import regex as re
import re

f_name = 'test1.txt'

splitter = r'"Event\d+":{(.*?)}'  # a search pattern to capture the stuff in braces

#Open the file as Read.
with open(f_name, 'r') as src:
    data = src.readlines()

# tokenize the data source...
tokens = re.findall(splitter, str(data))

#print(tokens)

# now we can operate on the tokens and split them up into key-value pairs and put them into a list
result = []
for token in tokens:
    # make an empty dictionary to hold the row elements
    line_dict = {}
    # we can split the line (token) by comma to get the key-value pairs
    pairs = token.split(',')
    for pair in pairs:
        # another regex split needed here, because the timestamps have colons too
        splitter = r'"(.*)"\s*:\s*"(.*)"'    # capture two groups of things in quotes on opposite sides of colon
        parts = re.search(splitter, pair)
        key, value = parts.group(1), parts.group(2)
        line_dict[key] = value
    # add the dictionary of line elements to the result
    result.append(line_dict)

with open(f_name, 'w') as src:
   for line in result:
     src.write(result)
</code>```

i.e the code it self was not written by me -> Log file management with python (thanks AirSquid)
Thanks for the assistance, New at Python here.

Tried to import json and use json.dump, also tried to append the text, but in most cases i end up with just [] or empty file.

Title: Save json list in a text file

Body:
I got a json log file that i rearrange to be correct, after this i am trying to save the results to the same file. The results are a list. but the problem that i am unable to save and will give me the following error:

write() argument must be str, not list

Here is the code it self:

import regex as re
import re

f_name = 'test1.txt'

splitter = r'"Event\d+":{(.*?)}'  # a search pattern to capture the stuff in braces

#Open the file as Read.
with open(f_name, 'r') as src:
    data = src.readlines()

# tokenize the data source...
tokens = re.findall(splitter, str(data))

#print(tokens)

# now we can operate on the tokens and split them up into key-value pairs and put them into a list
result = []
for token in tokens:
    # make an empty dictionary to hold the row elements
    line_dict = {}
    # we can split the line (token) by comma to get the key-value pairs
    pairs = token.split(',')
    for pair in pairs:
        # another regex split needed here, because the timestamps have colons too
        splitter = r'"(.*)"\s*:\s*"(.*)"'    # capture two groups of things in quotes on opposite sides of colon
        parts = re.search(splitter, pair)
        key, value = parts.group(1), parts.group(2)
        line_dict[key] = value
    # add the dictionary of line elements to the result
    result.append(line_dict)

with open(f_name, 'w') as src:
   for line in result:
     src.write(result)

i.e the code it self was not written by me -> Log file management with python (thanks AirSquid)
Thanks for the assistance, New at Python here.

Tried to import json and use json.dump, also tried to append the text, but in most cases i end up with just [] or empty file.


问:
Modal doesn't show on specific chrome user
I have a modal that should open on clicking on a button, it opens in incognito mode and opens in guest mode, but it doesn't open when I use my current chrome user (I can see it in the DOM but it doesn't appear on the UI).
It also opens in Firefox.

I tried clearing cache, I tried restarting chrome, I tried allowing Popups and redirection, and I also tried restarting my laptop, nothing has worked.


问:
Py4JJavaError: An error occurred while calling o103.load. : java.lang.ClassNotFoundException
**connector psyspark with mongodb in jupyter and access to database test.user (mongodb)
**

(https://i.stack.imgur.com/1eXUg.png)
(https://i.stack.imgur.com/ZFWio.png)

openjdk 11.0.17
Scala version 2.12.15
spark version 3.2.0
mongodb version v6.0.3


问:
How can I inject the JS Chunks at the  tag instead of  using Vite
I am building a reactjs app and when I try to run npm run build, the js chunks are being injected at the  tags instead of the  tags. I have tried adding the following code to my vite.config.js file but it still doesn't work

```<code>export default {
 optimizeDeps: {
inject: 'body'
},
</code>```

Kindly help. Thank you

Title: How can I inject the JS Chunks at the <body> tag instead of <head> using Vite

Body:
I am building a reactjs app and when I try to run npm run build, the js chunks are being injected at the  tags instead of the  tags. I have tried adding the following code to my vite.config.js file but it still doesn't work

export default {
 optimizeDeps: {
inject: 'body'
},

Kindly help. Thank you