问:
Getting number format exception in Hive when changing mapred.max.split.size
I am running many commands like this to export data from hive as CSVs:

```<code>INSERT OVERWRITE DIRECTORY '/output/database/table/'
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
SELECT * FROM database.table;
</code>```

That command does exactly what I want it to, but I am getting totally random file sizes on the output ranging from 100mb to 500mb. So in an effort to set the max file size I am setting these hive settings:

```<code>set mapred.min.split.size=1024;
set mapred.max.split.size=128000000;
set tez.grouping.min-size=1024;
set tez.grouping.max-size=128000000;
</code>```

But when I run the above query I am getting this error:

```<code>ERROR : Status: Failed
ERROR : Vertex failed, vertexName=Map 1, vertexId=vertex_1642026592077_2420_5_00, diagnostics=[Vertex vertex_1642026592077_2420_5_00 [Map 1] killed/failed due to:ROOT_INPUT_INIT_FAILURE, Vertex Input: table initializer failed, vertex=vertex_1642026592077_2420_5_00 [Map 1], java.lang.NumberFormatException: For input string: "128000000"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Long.parseLong(Long.java:589)
        at java.lang.Long.parseLong(Long.java:631)
        at org.apache.hadoop.conf.Configuration.getLong(Configuration.java:1540)
        at org.apache.hadoop.hive.conf.HiveConf.getLongVar(HiveConf.java:5134)
        at org.apache.hadoop.hive.ql.io.orc.OrcInputFormat$Context.<init>(OrcInputFormat.java:642)
        at org.apache.hadoop.hive.ql.io.orc.OrcInputFormat.getSplits(OrcInputFormat.java:1960)
        at org.apache.hadoop.hive.ql.io.HiveInputFormat.addSplitsForGroup(HiveInputFormat.java:532)
        at org.apache.hadoop.hive.ql.io.HiveInputFormat.getSplits(HiveInputFormat.java:789)
        at org.apache.hadoop.hive.ql.exec.tez.HiveSplitGenerator.initialize(HiveSplitGenerator.java:243)
        at org.apache.tez.dag.app.dag.RootInputInitializerManager$InputInitializerCallable$1.run(RootInputInitializerManager.java:278)
        at org.apache.tez.dag.app.dag.RootInputInitializerManager$InputInitializerCallable$1.run(RootInputInitializerManager.java:269)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1730)
        at org.apache.tez.dag.app.dag.RootInputInitializerManager$InputInitializerCallable.call(RootInputInitializerManager.java:269)
        at org.apache.tez.dag.app.dag.RootInputInitializerManager$InputInitializerCallable.call(RootInputInitializerManager.java:253)
        at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:125)
        at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:69)
        at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:78)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
]
ERROR : DAG did not succeed due to VERTEX_FAILURE. failedVertices:1 killedVertices:0
</code>```

As far as I know 128000000 is a valid number, so I am at a loss with this error

答:
Settings you are using are for controlling mappers parallelism.

Try to trigger merge step and specify the file size required. See comments:

```<code>set hive.merge.mapfiles=true;
set hive.merge.mapredfiles=true;
set hive.merge.size.per.task=128000000;  --Size of merged files at the end of the job
set hive.merge.smallfiles.avgsize=120000000; --When the average output file size of a job is less than this number,
--Hive will start an additional map-reduce job to merge the output files into bigger files
--For Tez
set hive.merge.tezfiles=true;
set hive.merge.size.per.task=128000000;
set hive.merge.smallfiles.avgsize=120000000;
</code>```

Body:
I am running many commands like this to export data from hive as CSVs:

INSERT OVERWRITE DIRECTORY '/output/database/table/'
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
SELECT * FROM database.table;

That command does exactly what I want it to, but I am getting totally random file sizes on the output ranging from 100mb to 500mb. So in an effort to set the max file size I am setting these hive settings:

set mapred.min.split.size=1024;
set mapred.max.split.size=128000000;
set tez.grouping.min-size=1024;
set tez.grouping.max-size=128000000;

But when I run the above query I am getting this error:

ERROR : Status: Failed
ERROR : Vertex failed, vertexName=Map 1, vertexId=vertex_1642026592077_2420_5_00, diagnostics=[Vertex vertex_1642026592077_2420_5_00 [Map 1] killed/failed due to:ROOT_INPUT_INIT_FAILURE, Vertex Input: table initializer failed, vertex=vertex_1642026592077_2420_5_00 [Map 1], java.lang.NumberFormatException: For input string: "128000000"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Long.parseLong(Long.java:589)
        at java.lang.Long.parseLong(Long.java:631)
        at org.apache.hadoop.conf.Configuration.getLong(Configuration.java:1540)
        at org.apache.hadoop.hive.conf.HiveConf.getLongVar(HiveConf.java:5134)
        at org.apache.hadoop.hive.ql.io.orc.OrcInputFormat$Context.<init>(OrcInputFormat.java:642)
        at org.apache.hadoop.hive.ql.io.orc.OrcInputFormat.getSplits(OrcInputFormat.java:1960)
        at org.apache.hadoop.hive.ql.io.HiveInputFormat.addSplitsForGroup(HiveInputFormat.java:532)
        at org.apache.hadoop.hive.ql.io.HiveInputFormat.getSplits(HiveInputFormat.java:789)
        at org.apache.hadoop.hive.ql.exec.tez.HiveSplitGenerator.initialize(HiveSplitGenerator.java:243)
        at org.apache.tez.dag.app.dag.RootInputInitializerManager$InputInitializerCallable$1.run(RootInputInitializerManager.java:278)
        at org.apache.tez.dag.app.dag.RootInputInitializerManager$InputInitializerCallable$1.run(RootInputInitializerManager.java:269)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1730)
        at org.apache.tez.dag.app.dag.RootInputInitializerManager$InputInitializerCallable.call(RootInputInitializerManager.java:269)
        at org.apache.tez.dag.app.dag.RootInputInitializerManager$InputInitializerCallable.call(RootInputInitializerManager.java:253)
        at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:125)
        at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:69)
        at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:78)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
]
ERROR : DAG did not succeed due to VERTEX_FAILURE. failedVertices:1 killedVertices:0

As far as I know 128000000 is a valid number, so I am at a loss with this error

Body:
Settings you are using are for controlling mappers parallelism.

Try to trigger merge step and specify the file size required. See comments:

set hive.merge.mapfiles=true;
set hive.merge.mapredfiles=true;
set hive.merge.size.per.task=128000000;  --Size of merged files at the end of the job
set hive.merge.smallfiles.avgsize=120000000; --When the average output file size of a job is less than this number,
--Hive will start an additional map-reduce job to merge the output files into bigger files
--For Tez
set hive.merge.tezfiles=true;
set hive.merge.size.per.task=128000000;
set hive.merge.smallfiles.avgsize=120000000;


来源: stackexchange

问:
DataSpell - save state like in RStudio?
Is it possible to save the Jupyter variables in DataSpell similar to how this works in RStudio?

At the moment, after I closed DS, I need to recompute everything. Of course I can write the main variables to disk myself, but I don't want to do that for all variables all the time.

答:
I think the closest thing to the save/load workspace behavior in RStudio is the %store magic. IPython provides the %store magic, but %store is available in Jupyter Notebooks in DataSpell.

Here is the %store documentation: https://ipython.readthedocs.io/en/stable/config/extensions/storemagic.html

ContentLicense: CC BY-SA 4.0

Title: DataSpell - save state like in RStudio?


问:
With paypal REST API V2 if payer does not complete the payment, what is the best way to implement retry payment feature?
I am quite new to PayPal rest API and wanted to provide user with a way to retry payment option in case user does not continue or cancel from the PayPal approve URL. Should I create a new order altogether and get a new approve URL or is there a way to retry payment for an old order in 'CREATED' OR 'APPROVED' state?</p>

答:
An order is valid for 72 hours from the moment it is created, and for 3 hours once loaded in a PayPal checkout for approval.

If a user abandons it and is going to restart their checkout on your site, it's generally best to forget about the old order and generate a new one. You can specify a unique invoice_id for orders to prevent any accidental duplicate payments (by default the PayPal account will only allow one completed payment per invoice ID)

Rather than redirecting away from your website to PayPal for approval, for modern websites it's best to keep the user on your site, and have them approve the payment in an in-context experience/lightbox, which also has the option of expanding a credit card form right within your website. See the demo at https://developer.paypal.com/demo/checkout/#/pattern/server


问:
How to randomly change 50% of a column observations based on another column condition?
I'm analyzing a survey and I need to do an interaction.plot() between variable disclosure_1 and TYPE_1 to see how they affect a third variable ADTRUST.

The survey randomly showed a different scenario to each participant. DISCLOSURE_1 is the code to indicate the type of disclosure that was shown to a respondent (B = Before, D = During, A = After, N = None).
TYPE_1 indicates the terminology used (DF = Deepfake, SM = Sythetic Media).

When creating the survey I dumbly only used DF for N because I thought there was no need to create an SM scenario if there was no disclosure shown (so no difference in terminology used). It still makes no sense logically, but when plotting the interaction plot the variable N does not appear. And since the study wants to analyze:

how disclosure impacts ADTRUST

how disclosure positioning impacts ADTRUST

how different terminology used in disclosure impact ADTRUST

I need to randomly substitute 50% of the observations with SM instead of DF under TYPE_1 but ONLY if the column DISCLOSURE_1 is == N.

I have no clue how to do that. Could somebody please help?

NOTE!!!! The structure is part of a bigger dataset. the dput was only done only for [25:26], so keep in mind I need to be able to precisely select the columns in the code.

Thank youu

```<code>structure(list(DISCLOSURE_1 = structure(c(4L, 3L, 1L, 3L, 1L,
1L, 4L, 3L, 4L, 3L, 4L, 1L, 3L, 3L, 4L, 1L, 3L, 3L, 1L, 3L, 3L,
4L, 2L, 1L, 1L, 4L, 2L, 3L, 3L, 1L, 4L, 1L, 1L, 4L, 4L, 1L, 3L,
2L, 2L, 1L, 4L, 1L, 1L, 1L, 4L, 3L, 4L, 3L, 2L, 3L, 1L, 1L, 3L,
1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 2L, 1L, 3L, 3L, 3L, 3L, 2L, 2L,
3L, 3L, 2L, 1L, 2L, 3L, 1L, 2L, 2L, 1L, 1L, 1L, 3L, 2L, 2L, 3L,
3L, 2L, 3L, 3L, 2L, 1L, 3L, 1L, 1L, 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, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L,
2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L,
2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("DF",
"SM"), class = "factor")), row.names = c(NA, -367L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

答:
If the 50% requirement is approximate, you can use runif() > 0.5

library(dplyr)
table(df)

            TYPE_1
DISCLOSURE_1 DF SM
           A 52 51
           B 52 53
           D 55 51
           N 53  0

mut <- df |>
  mutate(TYPE_1 = ifelse(DISCLOSURE_1 == "N" &
                         TYPE_1 == "DF" &
                         runif(n()) > 0.5,
                         "SM",
                         as.character(TYPE_1)))

table(mut)

            TYPE_1
DISCLOSURE_1 DF SM
           A 52 51
           B 52 53
           D 55 51
           N 27 26
```

Body:
I'm analyzing a survey and I need to do an interaction.plot() between variable disclosure_1 and TYPE_1 to see how they affect a third variable ADTRUST.

The survey randomly showed a different scenario to each participant. DISCLOSURE_1 is the code to indicate the type of disclosure that was shown to a respondent (B = Before, D = During, A = After, N = None).
TYPE_1 indicates the terminology used (DF = Deepfake, SM = Sythetic Media).

When creating the survey I dumbly only used DF for N because I thought there was no need to create an SM scenario if there was no disclosure shown (so no difference in terminology used). It still makes no sense logically, but when plotting the interaction plot the variable N does not appear. And since the study wants to analyze:

how disclosure impacts ADTRUST

how disclosure positioning impacts ADTRUST

how different terminology used in disclosure impact ADTRUST

I need to randomly substitute 50% of the observations with SM instead of DF under TYPE_1 but ONLY if the column DISCLOSURE_1 is == N.

I have no clue how to do that. Could somebody please help?

NOTE!!!! The structure is part of a bigger dataset. the dput was only done only for [25:26], so keep in mind I need to be able to precisely select the columns in the code.

Thank youu

structure(list(DISCLOSURE_1 = structure(c(4L, 3L, 1L, 3L, 1L,
1L, 4L, 3L, 4L, 3L, 4L, 1L, 3L, 3L, 4L, 1L, 3L, 3L, 1L, 3L, 3L,
4L, 2L, 1L, 1L, 4L, 2L, 3L, 3L, 1L, 4L, 1L, 1L, 4L, 4L, 1L, 3L,
2L, 2L, 1L, 4L, 1L, 1L, 1L, 4L, 3L, 4L, 3L, 2L, 3L, 1L, 1L, 3L,
1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 2L, 1L, 3L, 3L, 3L, 3L, 2L, 2L,
3L, 3L, 2L, 1L, 2L, 3L, 1L, 2L, 2L, 1L, 1L, 1L, 3L, 2L, 2L, 3L,
3L, 2L, 3L, 3L, 2L, 1L, 3L, 1L, 1L, 4L, 4L, 1L, 2L, 4L, 3L, 1L,
1L, 1L, 3L, 2L, 3L, 1L, 2L, 2L, 3L, 4L, 2L, 4L, 2L, 3L, 3L, 2L,
4L, 4L, 3L, 4L, 1L, 1L, 3L, 3L, 1L, 3L, 2L, 3L, 3L, 1L, 2L, 1L,
4L, 1L, 2L, 3L, 3L, 1L, 4L, 2L, 3L, 2L, 1L, 1L, 2L, 2L, 1L, 4L,
2L, 4L, 1L, 4L, 2L, 1L, 1L, 1L, 3L, 2L, 3L, 2L, 4L, 3L, 1L, 3L,
1L, 1L, 3L, 2L, 3L, 2L, 4L, 3L, 3L, 1L, 1L, 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, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L,
2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("DF",
"SM"), class = "factor")), row.names = c(NA, -367L), class = c("tbl_df",
"tbl", "data.frame"))


问:
Mongoose const castError = new CastError();
I seem to be getting this error:

```<code>C:\...\node_modules\mongoose\lib\query.js:4638
  const castError = new CastError();
                    ^

CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "cProd"
    at model.Query.exec (C:\...\node_modules\mongoose\lib\query.js:4638:21)
    at model.Query.Query.then (C:\...\node_modules\mongoose\lib\query.js:4737:15)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  messageFormat: undefined,
  stringValue: '"undefined"',
  kind: 'ObjectId',
  value: 'undefined',
  path: '_id',
  reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters
      at new BSONTypeError (C:\...\node_modules\bson\lib\error.js:41:28)
      at new ObjectId (C:\...\node_modules\bson\lib\objectid.js:65:23)
      at castObjectId (C:\...\node_modules\mongoose\lib\cast\objectid.js:24:12)
      at ObjectId.cast (C:\...\node_modules\mongoose\lib\schema\objectid.js:247:12)
      at ObjectId.SchemaType.applySetters (C:\...\node_modules\mongoose\lib\schematype.js:1180:12)
      at ObjectId.SchemaType._castForQuery (C:\...\node_modules\mongoose\lib\schematype.js:1615:15)
      at ObjectId.SchemaType.castForQuery (C:\...\node_modules\mongoose\lib\schematype.js:1605:15)
      at ObjectId.SchemaType.castForQueryWrapper (C:\...\node_modules\mongoose\lib\schematype.js:1582:20)
      at cast (C:\...\node_modules\mongoose\lib\cast.js:341:32)
      at model.Query.Query.cast (C:\...\node_modules\mongoose\lib\query.js:5073:12),
  valueType: 'string'
}
</code>```

for this code:

```<code>const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const cProd = require('./models/cProd');

mongoose.connect('mongodb://localhost:#/database', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Database connected');
});

const app = express();

// app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))

// Parsing request.body

app.use(express.urlencoded({extended: true}))

app.get('/', (req, res) => {
    res.render('main')
});

app.get('/cProds', async (req, res) => {
    const cProds = await cProd.find({});
    res.render('cProds/index', {cProds})
});

app.get('/cProds/create', (req, res) => {
    res.render('cProds/create');
})

app.post('/cProds', async (req, res) => {
    const conProd = new cProd(req.body.cProd);
    await conProd.save();
    res.redirect(`/cProds/${cProd._id}`)
});

app.get('/cProds/:id', async (req, res) => {
    const conProd = await cProd.findById(req.params.id)
    res.render('cProds/show', {conProd})
});

app.listen(3000, () => {
    console.log('Serving on port #')
})
</code>```

The app.post above seems to work when I do a simple res.send(req.body), but I get this error if I finish the code.

Dumb question, is it possibly due to not installing UUID? I don't believe I have yet.

Please help - complete beginner here who has exhausted research and figuring this out.

UPDATE: Schema and Model

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const opts = {toJSON:{virtuals:true}};

const CProdSchema = new Schema({
    product_name: String,
    type: String,
    description: String
}, opts);

CProdSchema.virtual('properties.popUpMarkup').get(function() {
    return `
    <strong><a href="/campgrounds/${this._id}">${this.product_name}</a></strong>
    <p>${this.description.substring(0,20)}...</p>`
});

module.exports = mongoose.model('cProd', CProdSchema)
</code>```

答:
Ah, I think I was blind.

Your problem method:

```<code>app.post('/cProds', async (req, res) => {
    const conProd = new cProd(req.body.cProd);
    await conProd.save();
    res.redirect(`/cProds/${cProd._id}`)
});
</code>```

You want to send the user to the url for the newly created cProd. But cProd is the model name, while conProd is the new document created.
Simply change the last line:

```<code>    res.redirect(`/cProds/${conProd._id}`)
</code>```

To avoid the confusion in future, I recommend sticking to capitalized first letter of models. I'm making a guess at the name, so for example:

```<code>const CampgroundProduct = require('./models/cProd');
</code>```

And any instances (documents) of this model can be called campgroundProduct or simply product.

As to how that specific error code happened, I'm guessing that model._id references the creator for that type of field, which would be mongoose.Types.ObjectId()

Body:
I seem to be getting this error:

C:\...\node_modules\mongoose\lib\query.js:4638
  const castError = new CastError();
                    ^

CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "cProd"
    at model.Query.exec (C:\...\node_modules\mongoose\lib\query.js:4638:21)
    at model.Query.Query.then (C:\...\node_modules\mongoose\lib\query.js:4737:15)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  messageFormat: undefined,
  stringValue: '"undefined"',
  kind: 'ObjectId',
  value: 'undefined',
  path: '_id',
  reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters
      at new BSONTypeError (C:\...\node_modules\bson\lib\error.js:41:28)
      at new ObjectId (C:\...\node_modules\bson\lib\objectid.js:65:23)
      at castObjectId (C:\...\node_modules\mongoose\lib\cast\objectid.js:24:12)
      at ObjectId.cast (C:\...\node_modules\mongoose\lib\schema\objectid.js:247:12)
      at ObjectId.SchemaType.applySetters (C:\...\node_modules\mongoose\lib\schematype.js:1180:12)
      at ObjectId.SchemaType._castForQuery (C:\...\node_modules\mongoose\lib\schematype.js:1615:15)
      at ObjectId.SchemaType.castForQuery (C:\...\node_modules\mongoose\lib\schematype.js:1605:15)
      at ObjectId.SchemaType.castForQueryWrapper (C:\...\node_modules\mongoose\lib\schematype.js:1582:20)
      at cast (C:\...\node_modules\mongoose\lib\cast.js:341:32)
      at model.Query.Query.cast (C:\...\node_modules\mongoose\lib\query.js:5073:12),
  valueType: 'string'
}

for this code:

const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const cProd = require('./models/cProd');

mongoose.connect('mongodb://localhost:#/database', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Database connected');
});

const app = express();

// app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))

// Parsing request.body

app.use(express.urlencoded({extended: true}))

app.get('/', (req, res) => {
    res.render('main')
});

app.get('/cProds', async (req, res) => {
    const cProds = await cProd.find({});
    res.render('cProds/index', {cProds})
});

app.get('/cProds/create', (req, res) => {
    res.render('cProds/create');
})

app.post('/cProds', async (req, res) => {
    const conProd = new cProd(req.body.cProd);
    await conProd.save();
    res.redirect(`/cProds/${cProd._id}`)
});

app.get('/cProds/:id', async (req, res) => {
    const conProd = await cProd.findById(req.params.id)
    res.render('cProds/show', {conProd})
});

app.listen(3000, () => {
    console.log('Serving on port #')
})

The app.post above seems to work when I do a simple res.send(req.body), but I get this error if I finish the code.

Dumb question, is it possibly due to not installing UUID? I don't believe I have yet.

Please help - complete beginner here who has exhausted research and figuring this out.

UPDATE: Schema and Model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const opts = {toJSON:{virtuals:true}};

const CProdSchema = new Schema({
    product_name: String,
    type: String,
    description: String
}, opts);

CProdSchema.virtual('properties.popUpMarkup').get(function() {
    return `
    ${this.product_name}

${this.description.substring(0,20)}...
`
});

module.exports = mongoose.model('cProd', CProdSchema)

Body:
Ah, I think I was blind.

Your problem method:

app.post('/cProds', async (req, res) => {
    const conProd = new cProd(req.body.cProd);
    await conProd.save();
    res.redirect(`/cProds/${cProd._id}`)
});

You want to send the user to the url for the newly created cProd. But cProd is the model name, while conProd is the new document created.
Simply change the last line:

    res.redirect(`/cProds/${conProd._id}`)

To avoid the confusion in future, I recommend sticking to capitalized first letter of models. I'm making a guess at the name, so for example:

const CampgroundProduct = require('./models/cProd');

And any instances (documents) of this model can be called campgroundProduct or simply product.

As to how that specific error code happened, I'm guessing that model._id references the creator for that type of field, which would be mongoose.Types.ObjectId()


问:
How do you avoid repeating styles in shadow DOM?
I'm new to web components, so not sure if there's an easy answer or best practice on this one.

If I want to create a series of repeating elements with encapsulated style how do I avoid repeating the style block with each element.

A reduced version of the code I'm using is:

```<code><ul id="wrapper"></ul>

<template id="template">
  <style>
    li { color: red }
  </style>

  <li></li>
</template>

<script>
var wrapper = document.getElementById('wrapper');
var tpl = document.getElementById('template');
var shadow = wrapper.createShadowRoot();
var arr = ['a', 'b', 'c'];

for(var i = 0, ii = arr.length; i < ii; i++) {
  tpl.content.querySelector('li').textContent = arr[i];

  var clone = document.importNode(tpl.content, true);

  shadow.appendChild(clone);
}
</script>
</code>```

The problem I have with that is that the shadow DOM has a duplicated style block for each
, and am not sure the best way round it.

I have tried nesting a template and that is either never going to work or I'm not doing it right.

答:
Fast-forward to 2022 and we now have "constructable stylesheets".  Reference here.  Basically the browser is smart enough to use only a single constructed stylesheet for all those copies of your webcomponent on the page!  :)

Quoting from the article:

Constructable Stylesheets make it possible to define and prepare shared CSS styles, and then apply those styles to multiple Shadow Roots or the Document easily and without duplication. Updates to a shared CSSStyleSheet are applied to all roots into which it has been adopted

ContentLicense: CC BY-SA 3.0

Body:
I'm new to web components, so not sure if there's an easy answer or best practice on this one.

If I want to create a series of repeating elements with encapsulated style how do I avoid repeating the style block with each element.

A reduced version of the code I'm using is:

<template id="template">

</template>

The problem I have with that is that the shadow DOM has a duplicated style block for each
, and am not sure the best way round it.

I have tried nesting a template and that is either never going to work or I'm not doing it right.


问:
How to find the 'm' oldest forks of a repository using GitHub api
I need to obtain the 'm' oldest forks of a given repository, using the GitHub API. To get the 'm' oldest forks I'm trying to obtain the forks sorted from oldest to newest.

Taking the example of "it-cert-automation-practice" repository of google, I've tried the following APIs:

```<code>https://api.github.com/repos/google/it-cert-automation-practice/forks?q=sort:created_at
</code>```
```<code>https://api.github.com/repos/google/it-cert-automation-practice/forks?q=sort:oldest
</code>```
```<code>https://api.github.com/repos/google/it-cert-automation-practice/forks?q=sort:updated_at&fork:true&order:asc
</code>```
```<code>https://api.github.com/repos/google/it-cert-automation-practice/forks?q=sort:created_at&fork:true&order:asc
</code>```

答:
You can use List forks endpoint, take into account the following:

Use sort parameter with value oldest

If you want to list more than 100 repositories, you will need to handle pagination using the page parameter.

See a working example using Octokit for getting the oldest 40 forks of Node.js repository.

Get oldest forks of GitHub repository
View in Fusebit

const owner = 'nodejs';
const repo = 'node';
const repoInfo = await github.request(`GET /repos/${owner}/${repo}`, {
  owner,
  repo,
});

const {forks_count} = repoInfo.data;

// By default it will return 30 results, you can get up to 100 using per_page parameter.
const searchResult = await github.rest.repos.listForks({
  owner,
  repo,
  sort: 'oldest',
  per_page: 40
});

console.log(searchResult.data.map(repo => `${repo.full_name} created at ${repo.created_at}`), `Found ${searchResult.data.length} of ${forks_count} total forks for ${owner}/${repo} repository`);

```

Body:
I need to obtain the 'm' oldest forks of a given repository, using the GitHub API. To get the 'm' oldest forks I'm trying to obtain the forks sorted from oldest to newest.

Taking the example of "it-cert-automation-practice" repository of google, I've tried the following APIs:

https://api.github.com/repos/google/it-cert-automation-practice/forks?q=sort:created_at

https://api.github.com/repos/google/it-cert-automation-practice/forks?q=sort:oldest

https://api.github.com/repos/google/it-cert-automation-practice/forks?q=sort:updated_at&fork:true&order:asc

https://api.github.com/repos/google/it-cert-automation-practice/forks?q=sort:created_at&fork:true&order:asc


问:
PHP equivalent of Python's __name__ == "__main__"?
As per the title, is there PHP equivalent of __name__ == "__main__"?

Is there something that would work for both scripts executed through the command line and through a web request, or would a custom function be needed?

For those unfamiliar with Python, __name__ == "__main__" allows you to define a module file, and also have some things that allow you to run it if it is the entry point. The equivalent structure in PHP would resemble this:

```<code>// SomeClass.php
<?php
class SomeClass
{
    function doStuff() {
        echo "wahey!\n";
    }
}

// python, I know.
if (__name__ == "__main__") {
    $sc = new SomeClass;
    $sc->doStuff();
}
?>

// OtherClass.php
<?php
require_once("SomeClass.php");
class OtherClass
{
    public $yep;
}
?>

// command line:
php SomeClass.php     // outputs "wahey!"
php OtherClass.php    // outputs nothing
</code>```

Note:
zerkms' answer is the best, but is not quite right - it should read:

```<code>if (!debug_backtrace()) {
    // do useful stuff
}
</code>```

This is significantly faster than !count(debug_backtrace()), which itself is about twice as fast as my solution involving realpath().

答:
```<code>if(get_included_files()[0] == __FILE__) doStuff();
</code>```

Body:
As per the title, is there PHP equivalent of __name__ == "__main__"?

Is there something that would work for both scripts executed through the command line and through a web request, or would a custom function be needed?

For those unfamiliar with Python, __name__ == "__main__" allows you to define a module file, and also have some things that allow you to run it if it is the entry point. The equivalent structure in PHP would resemble this:

// SomeClass.php
<?php
class SomeClass
{
    function doStuff() {
        echo "wahey!\n";
    }
}

// python, I know.
if (__name__ == "__main__") {
    $sc = new SomeClass;
    $sc->doStuff();
}
?>

// OtherClass.php
<?php
require_once("SomeClass.php");
class OtherClass
{
    public $yep;
}
?>

// command line:
php SomeClass.php     // outputs "wahey!"
php OtherClass.php    // outputs nothing

Note:
zerkms' answer is the best, but is not quite right - it should read:

if (!debug_backtrace()) {
    // do useful stuff
}

This is significantly faster than !count(debug_backtrace()), which itself is about twice as fast as my solution involving realpath().


问:
Django Plotly Dash Scatter chart loses interactivity when DataTable added
I am using the django-plotly-dash utility to embed Dash apps into a Django page.

If I have a Plotly Scatter chart on the same app as a Dash DataTable then the chart loses it's interactivity.

答:
Turns out the culprit was a Dash styling css from this Codepen.

I previously had it included externally via

```<code>external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = DjangoDash("signalapp" external_stylesheets=external_stylesheets)
</code>```

And switched it to local hosting by changing to

```<code>app.css.append_css({ "external_url" : "/static/myapp/css/bWLwgP.css" })
</code>```

Then by a process of elimination discovered that the float parameter of the following class caused the issue if set to either 'right' or 'left'

```<code>.columns {
  width: 100%;
  float: left;
  box-sizing: border-box; }
</code>```

Body:
Turns out the culprit was a Dash styling css from this Codepen.

I previously had it included externally via

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = DjangoDash("signalapp" external_stylesheets=external_stylesheets)

And switched it to local hosting by changing to

app.css.append_css({ "external_url" : "/static/myapp/css/bWLwgP.css" })

Then by a process of elimination discovered that the float parameter of the following class caused the issue if set to either 'right' or 'left'

.columns {
  width: 100%;
  float: left;
  box-sizing: border-box; }


问:
How can I convert an array of characters to an integer (for 2 or more digits)
The array has to be entered by the user, and not specified in the app itself.

```<code>char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    cin >> coeff[i];
    cin >> expo[i];
}
</code>```

When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit and still be saved in it in the variable?

PS. I'm forced into using an array of characters here and not integers

答: You're storing it in char array. Change the type of coeff and expo to the right one. Eg: int coeff[20] if you expect to store 20 ints.

Body:
The array has to be entered by the user, and not specified in the app itself.

char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    cin >> coeff[i];
    cin >> expo[i];
}

When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit and still be saved in it in the variable?

PS. I'm forced into using an array of characters here and not integers


问:
Error trying to style a component directly with styled-components
I'm trying to style a component like this:

```<code>function _MenuItem({label, icon}){
    return <div>
        {icon}
        <p>{label}</p>
    </div>
}

export const MenuItem = styled(props => <_MenuItem {...props} />)`
    color: red;
    p{color: red}
    *{color: red}
`
</code>```

The component is rendering, but the styles are not being applied.

I have managed to apply the styles by making a styled div and creating the component from that div, but I was wondering if there is a way to apply the styles directly to the component?

I am very new with react and more with styled-components so I assume that I have misunderstood some basic concepts.

答:
Making a styled div is the correct way of doing things. I couldn't find anything on styling a component directly nor felt the urge to done it before.

Even when the styled-component docs describe how to style any component, they are basically styling an element just with a different syntax.

There doesn't seem to be a good enough reason to do what you want to do,  since you can achieve what you want to achieve by using the styled components as intended.

The following way of doing things works and it is super simple:

```<code>import styled from "styled-components"

const _MenuItem = ({label, icon}) => {
    return <Root>
        {icon}
        <p>{label}</p>
    </Root>
}

const Root = styled.div`
    color: red;
    p{color: red}
    *{color: red}
`

export default _MenuItem;
</code>```

Please let me know if I'm missing some specific use-case or something other.

Body:
I'm trying to style a component like this:

function _MenuItem({label, icon}){
    return

        {icon}

{label}

}

export const MenuItem = styled(props => <_MenuItem {...props} />)`
    color: red;
    p{color: red}
    *{color: red}
`

The component is rendering, but the styles are not being applied.

I have managed to apply the styles by making a styled div and creating the component from that div, but I was wondering if there is a way to apply the styles directly to the component?

I am very new with react and more with styled-components so I assume that I have misunderstood some basic concepts.

Body:
Making a styled div is the correct way of doing things. I couldn't find anything on styling a component directly nor felt the urge to done it before.

Even when the styled-component docs describe how to style any component, they are basically styling an element just with a different syntax.

There doesn't seem to be a good enough reason to do what you want to do,  since you can achieve what you want to achieve by using the styled components as intended.

The following way of doing things works and it is super simple:

import styled from "styled-components"

const _MenuItem = ({label, icon}) => {
    return <Root>
        {icon}
        <p>{label}</p>
    </Root>
}

const Root = styled.div`
    color: red;
    p{color: red}
    *{color: red}
`

export default _MenuItem;

Please let me know if I'm missing some specific use-case or something other.


问:
Unable to insert char* to the Azure Telemetry Payload In Arduino
I'm trying to add char* variable which contains date to the Azure telemetry payload. But error is occurring.

```<code>az_span temp_span = az_span_create(telemetry_payload, sizeof(telemetry_payload));
temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR("{ \"Humidity\": "));
  (void)az_span_u32toa(temp_span, humidity, &temp_span);

  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR(", \n \"Temperature\": "));
  (void)az_span_u32toa(temp_span, temperature, &temp_span);

  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR(", \n \"LocalTime\": "));

  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
  //Error from above line

  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR(" }"));
  temp_span = az_span_copy_u8(temp_span, '\0');
</code>```

getCurrentLocalTimeString function definition is here

```<code>static char* getCurrentLocalTimeString()
{
  time_t now = time(NULL);
  return ctime(&now);
}
</code>```

Error

```<code>In file included from C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_base64.h:20,
                 from C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_core.h:18,
                 from G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:40:
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino: In function 'char* getTelemetryPayload()':
Azure_IoT_Hub_ESP8266:335:57: error: cast from 'char*' to 'uint8_t' {aka 'unsigned char'} loses precision [-fpermissive]
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                                         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:108:25: note: in definition of macro 'AZ_SPAN_LITERAL_FROM_STR'
  108 |       .ptr = (uint8_t*)(STRING_LITERAL),              \
      |                         ^~~~~~~~~~~~~~
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:335:39: note: in expansion of macro 'AZ_SPAN_FROM_STR'
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                       ^~~~~~~~~~~~~~~~
Azure_IoT_Hub_ESP8266:335:57: error: cast from 'char*' to 'uint8_t' {aka 'unsigned char'} loses precision [-fpermissive]
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                                         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:93:43: note: in definition of macro '_az_STRING_LITERAL_LEN'
   93 | #define _az_STRING_LITERAL_LEN(S) (sizeof(S "") - 1)
      |                                           ^
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:125:52: note: in expansion of macro 'AZ_SPAN_LITERAL_FROM_STR'
  125 | #define AZ_SPAN_FROM_STR(STRING_LITERAL) (az_span) AZ_SPAN_LITERAL_FROM_STR(STRING_LITERAL)
      |                                                    ^~~~~~~~~~~~~~~~~~~~~~~~
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:335:39: note: in expansion of macro 'AZ_SPAN_FROM_STR'
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                       ^~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:93:45: error: expected ')' before string constant
   93 | #define _az_STRING_LITERAL_LEN(S) (sizeof(S "") - 1)
      |                                          ~  ^~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:109:15: note: in expansion of macro '_az_STRING_LITERAL_LEN'
  109 |       .size = _az_STRING_LITERAL_LEN(STRING_LITERAL), \
      |               ^~~~~~~~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:125:52: note: in expansion of macro 'AZ_SPAN_LITERAL_FROM_STR'
  125 | #define AZ_SPAN_FROM_STR(STRING_LITERAL) (az_span) AZ_SPAN_LITERAL_FROM_STR(STRING_LITERAL)
      |                                                    ^~~~~~~~~~~~~~~~~~~~~~~~
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:335:39: note: in expansion of macro 'AZ_SPAN_FROM_STR'
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                       ^~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:125:50: error: expected primary-expression before ')' token
  125 | #define AZ_SPAN_FROM_STR(STRING_LITERAL) (az_span) AZ_SPAN_LITERAL_FROM_STR(STRING_LITERAL)
      |                                                  ^
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:335:39: note: in expansion of macro 'AZ_SPAN_FROM_STR'
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                       ^~~~~~~~~~~~~~~~
exit status 1
cast from 'char*' to 'uint8_t' {aka 'unsigned char'} loses precision [-fpermissive]
</code>```

答:
This bit of code:

```<code>(uint8_t)getCurrentLocalTimeString()
</code>```

doesn't do what you think it does.

Your function getCurrentLocalTimeString() returns the address of an array of characters which contains a string representing the current local time.

You then try to cast this 32 bit memory address to an 8 bit unsigned integer, which is why the compiler warns that you're losing precision.

The best you can hope for here is publishing the first 8 bits of the memory address of this string, which I'm sure isn't what you want.

Since you seem to want to publish this as a string, you'd just drop the (uint8_t), like so:

```<code>temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR(getCurrentLocalTimeString() ));
</code>```

Body:
I'm trying to add char* variable which contains date to the Azure telemetry payload. But error is occurring.

az_span temp_span = az_span_create(telemetry_payload, sizeof(telemetry_payload));
temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR("{ \"Humidity\": "));
  (void)az_span_u32toa(temp_span, humidity, &temp_span);

  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR(", \n \"Temperature\": "));
  (void)az_span_u32toa(temp_span, temperature, &temp_span);

  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR(", \n \"LocalTime\": "));

  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
  //Error from above line

  temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR(" }"));
  temp_span = az_span_copy_u8(temp_span, '\0');

getCurrentLocalTimeString function definition is here

static char* getCurrentLocalTimeString()
{
  time_t now = time(NULL);
  return ctime(&now);
}

Error

In file included from C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_base64.h:20,
                 from C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_core.h:18,
                 from G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:40:
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino: In function 'char* getTelemetryPayload()':
Azure_IoT_Hub_ESP8266:335:57: error: cast from 'char*' to 'uint8_t' {aka 'unsigned char'} loses precision [-fpermissive]
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                                         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:108:25: note: in definition of macro 'AZ_SPAN_LITERAL_FROM_STR'
  108 |       .ptr = (uint8_t*)(STRING_LITERAL),              \
      |                         ^~~~~~~~~~~~~~
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:335:39: note: in expansion of macro 'AZ_SPAN_FROM_STR'
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                       ^~~~~~~~~~~~~~~~
Azure_IoT_Hub_ESP8266:335:57: error: cast from 'char*' to 'uint8_t' {aka 'unsigned char'} loses precision [-fpermissive]
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                                         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:93:43: note: in definition of macro '_az_STRING_LITERAL_LEN'
   93 | #define _az_STRING_LITERAL_LEN(S) (sizeof(S "") - 1)
      |                                           ^
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:125:52: note: in expansion of macro 'AZ_SPAN_LITERAL_FROM_STR'
  125 | #define AZ_SPAN_FROM_STR(STRING_LITERAL) (az_span) AZ_SPAN_LITERAL_FROM_STR(STRING_LITERAL)
      |                                                    ^~~~~~~~~~~~~~~~~~~~~~~~
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:335:39: note: in expansion of macro 'AZ_SPAN_FROM_STR'
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                       ^~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:93:45: error: expected ')' before string constant
   93 | #define _az_STRING_LITERAL_LEN(S) (sizeof(S "") - 1)
      |                                          ~  ^~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:109:15: note: in expansion of macro '_az_STRING_LITERAL_LEN'
  109 |       .size = _az_STRING_LITERAL_LEN(STRING_LITERAL), \
      |               ^~~~~~~~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:125:52: note: in expansion of macro 'AZ_SPAN_LITERAL_FROM_STR'
  125 | #define AZ_SPAN_FROM_STR(STRING_LITERAL) (az_span) AZ_SPAN_LITERAL_FROM_STR(STRING_LITERAL)
      |                                                    ^~~~~~~~~~~~~~~~~~~~~~~~
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:335:39: note: in expansion of macro 'AZ_SPAN_FROM_STR'
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                       ^~~~~~~~~~~~~~~~
C:\Users\hansa\Documents\Arduino\libraries\Azure_SDK_for_C\src/az_span.h:125:50: error: expected primary-expression before ')' token
  125 | #define AZ_SPAN_FROM_STR(STRING_LITERAL) (az_span) AZ_SPAN_LITERAL_FROM_STR(STRING_LITERAL)
      |                                                  ^
G:\AZURE Messaging IoT\Azure_IoT_Hub_ESP8266\Azure_IoT_Hub_ESP8266.ino:335:39: note: in expansion of macro 'AZ_SPAN_FROM_STR'
  335 |   temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR( (uint8_t)getCurrentLocalTimeString() ));
      |                                       ^~~~~~~~~~~~~~~~
exit status 1
cast from 'char*' to 'uint8_t' {aka 'unsigned char'} loses precision [-fpermissive]

Body:
This bit of code:

(uint8_t)getCurrentLocalTimeString()

doesn't do what you think it does.

Your function getCurrentLocalTimeString() returns the address of an array of characters which contains a string representing the current local time.

You then try to cast this 32 bit memory address to an 8 bit unsigned integer, which is why the compiler warns that you're losing precision.

The best you can hope for here is publishing the first 8 bits of the memory address of this string, which I'm sure isn't what you want.

Since you seem to want to publish this as a string, you'd just drop the (uint8_t), like so:

temp_span = az_span_copy(temp_span, AZ_SPAN_FROM_STR(getCurrentLocalTimeString() ));


问:
Python counting up (1+2+3 etc.) until input value
How to keep counting up (1+2+3) until user input value?

This is my code so far,

```<code>until = int(input("Keep counting until: "))

x = 1

while until >= x:

    x = x + 1

print(x)
</code>```

I can't figure out how to keep increasing the value by one at a time... the goal should be

e.g if input value was 2 to print 3 and if 10, 10 and 18,  21.

答:
The problem with your code is you always do x + 1, but you want x + i where i increments each time. Then you want to stop when x < until not when x <= until.

This will do what you need:

```<code>until = int(input("Keep counting until: "))

x = 0
i=0
while x < until:
    i+=1
    x = x + i

print(x)
</code>```

Example output:

```<code>Keep counting until: 18
21
</code>```

Body:
How to keep counting up (1+2+3) until user input value?

This is my code so far,

until = int(input("Keep counting until: "))

x = 1

while until >= x:

    x = x + 1

print(x)

I can't figure out how to keep increasing the value by one at a time... the goal should be

e.g if input value was 2 to print 3 and if 10, 10 and 18,  21.

Body:
The problem with your code is you always do x + 1, but you want x + i where i increments each time. Then you want to stop when x < until not when x <= until.

This will do what you need:

until = int(input("Keep counting until: "))

x = 0
i=0
while x < until:
    i+=1
    x = x + i

print(x)

Example output:

Keep counting until: 18
21


问:
Make JavaScript wait until websocket receives a reply
So as the title says, I'm playing around with websockets. So far all good, except for the fact that I can't make the page wait until we get a reponse. Now, I do actually have a good reason to do this; the requests times are about 2-10 ms due it going to 127.0.0.1 , so barely noticable. It is however long enough for the page to progress long enough to get to a part where the response is needed.

As you can tell, that is kind of a problem.

I am using the normal JS socket interface on the client and a golang websocket library on the backend.

Any ideas?

答:
Just embed your part where a responds is needed inside</p>
```<code>socket.onmessage = function (msg) {
    // part where msg.data is needed
}
</code>```

Body:
Just embed your part where a responds is needed inside

socket.onmessage = function (msg) {
    // part where msg.data is needed
}


问:
how do i get the current url of qwebengineview in pyqt5 python?
So guys currently i'm working on a small web browser on python in PyQt5 but I want to get the current URL of the webpage on the QWebEngineView widget.
I try:

```<code>webEngineView.url()
</code>```

But no such luck. remember that I am using PyQt5, NOT PyQt4.
Can somebody help me?
What I mean is, I need the attribute of QWebEngineView, which is the URL of the widget.

答:
.url() returns a QUrl object. Call toString() on the QUrl to get the raw Url.

webEngineView.url().toString()

Documentation

Body:
So guys currently i'm working on a small web browser on python in PyQt5 but I want to get the current URL of the webpage on the QWebEngineView widget.
I try:

webEngineView.url()

But no such luck. remember that I am using PyQt5, NOT PyQt4.
Can somebody help me?
What I mean is, I need the attribute of QWebEngineView, which is the URL of the widget.


问:
React Table - new order after filtering
I have a table made with React Table. I want it to have a fresh order after each filtering. So far, I have achieved only one order which is created at render.

Here is the Table component:

```<code>import React, { useEffect } from "react";
import { Table as BTable } from "react-bootstrap";
import { useTable, useSortBy, useGlobalFilter } from "react-table";

function Table({ data, columns, variant, filter = "" }) {
  const {
    getTableProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    setGlobalFilter,
  } = useTable(
    {
      columns,
      data,
    },
    useGlobalFilter,
    useSortBy
  );

  const { globalFilter } = state;

  useEffect(() => {
    setGlobalFilter(filter);
    // eslint-disable-next-line
  }, []);
  return (
    <>
      <span>Search: </span>
      <input
        value={globalFilter}
        onChange={(e) => setGlobalFilter(e.target.value)}
        onMouseMove={(e) => setGlobalFilter(e.target.value)}
      ></input>
      <hr></hr>
      <BTable striped bordered hover variant={variant} {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th
                  width={column.width}
                  {...column.getHeaderProps(column.getSortByToggleProps())}
                >
                  {column.render("Header")}
                  <span>
                    {column.isSorted
                      ? column.isSortedDesc
                        ? " "
                        : " "
                      : ""}
                  </span>
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody>
          {rows.map((row, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </BTable>
    </>
  );
}

export default Table;
</code>```

And implementation:

```<code>const columns = React.useMemo(
    () => [
      {
        Header: "#",
        Cell: (row) => {
          return <div>{Number(row.row.id) + 1}</div>;
        },
      },
      {
        Header: "ID",
        accessor: "id",
      },
      {
        Header: "Added By",
        accessor: "addedBy",
      },
      { Header: "Date of creation", accessor: "dateOfCreation", width: "10%" },
      {
        Header: "Ordertaker",
        accessor: "orderTaker",
        width: "5%",
      },
      {
        Header: "Customer",
        accessor: "customer",
        width: "20%",
      },
      {
        Header: "Description",
        accessor: "description",
        disableSortBy: "true",
        width: "30%",
      },
      {
        Header: "Status",
        accessor: "status",
        disableSortBy: "true",
        width: "10%",
      },
    ],
  );

return (
            <Table
              data={data} // data is fetched from firebase
              columns={columns}
              variant="dark"
            />
  );

</code>```

"#" column has number from 1 for each row. What I want is to reset order in "#" column after each filtering to start with 1. Any ideas how can it be done?

答:
map returns are inherently ordered in the insertion order. You could try a sort before hand. Here's a link.

Something like this might work:

rows.sort((a, b) => a.# - b.#).map((row, i) => ...
```

Title: React Table - new order after filtering

Body:
I have a table made with React Table. I want it to have a fresh order after each filtering. So far, I have achieved only one order which is created at render.

Here is the Table component:

import React, { useEffect } from "react";
import { Table as BTable } from "react-bootstrap";
import { useTable, useSortBy, useGlobalFilter } from "react-table";

function Table({ data, columns, variant, filter = "" }) {
  const {
    getTableProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    setGlobalFilter,
  } = useTable(
    {
      columns,
      data,
    },
    useGlobalFilter,
    useSortBy
  );

  const { globalFilter } = state;

  useEffect(() => {
    setGlobalFilter(filter);
    // eslint-disable-next-line
  }, []);
  return (
    <>
      Search:
      <input
        value={globalFilter}
        onChange={(e) => setGlobalFilter(e.target.value)}
        onMouseMove={(e) => setGlobalFilter(e.target.value)}
      ></input>

      <BTable striped bordered hover variant={variant} {...getTableProps()}>

          {headerGroups.map((headerGroup) => (

              {headerGroup.headers.map((column) => (

                  {column.render("Header")}

                    {column.isSorted
                      ? column.isSortedDesc
                        ? " "
                        : " "
                      : ""}

              ))}

          ))}

          {rows.map((row, i) => {
            prepareRow(row);
            return (

                {row.cells.map((cell) => {
                  return (
                    {cell.render("Cell")}
                  );
                })}

            );
          })}

      </BTable>
    </>
  );
}

export default Table;

And implementation:

const columns = React.useMemo(
    () => [
      {
        Header: "#",
        Cell: (row) => {
          return
{Number(row.row.id) + 1}
;
        },
      },
      {
        Header: "ID",
        accessor: "id",
      },
      {
        Header: "Added By",
        accessor: "addedBy",
      },
      { Header: "Date of creation", accessor: "dateOfCreation", width: "10%" },
      {
        Header: "Ordertaker",
        accessor: "orderTaker",
        width: "5%",
      },
      {
        Header: "Customer",
        accessor: "customer",
        width: "20%",
      },
      {
        Header: "Description",
        accessor: "description",
        disableSortBy: "true",
        width: "30%",
      },
      {
        Header: "Status",
        accessor: "status",
        disableSortBy: "true",
        width: "10%",
      },
    ],
  );

return (

  );

"#" column has number from 1 for each row. What I want is to reset order in "#" column after each filtering to start with 1. Any ideas how can it be done?


答:
With data as your data.frame, this will replace exactly half (rounded down) of the N's with DF with SM:

```<code>blnN <- data$DISCLOSURE_1 == "N" & data$TYPE_1 == "DF"
data$TYPE_1[sample(which(blnN), sum(blnN)/2)] <- "SM"
</code>```

Title: How to randomly change 50% of a column observations based on another column condition?

Body:
I'm analyzing a survey and I need to do an interaction.plot() between variable disclosure_1 and TYPE_1 to see how they affect a third variable ADTRUST.

The survey randomly showed a different scenario to each participant. DISCLOSURE_1 is the code to indicate the type of disclosure that was shown to a respondent (B = Before, D = During, A = After, N = None).
TYPE_1 indicates the terminology used (DF = Deepfake, SM = Sythetic Media).

When creating the survey I dumbly only used DF for N because I thought there was no need to create an SM scenario if there was no disclosure shown (so no difference in terminology used). It still makes no sense logically, but when plotting the interaction plot the variable N does not appear. And since the study wants to analyze:

how disclosure impacts ADTRUST

how disclosure positioning impacts ADTRUST

how different terminology used in disclosure impact ADTRUST

I need to randomly substitute 50% of the observations with SM instead of DF under TYPE_1 but ONLY if the column DISCLOSURE_1 is == N.

I have no clue how to do that. Could somebody please help?

NOTE!!!! The structure is part of a bigger dataset. the dput was only done only for [25:26], so keep in mind I need to be able to precisely select the columns in the code.

Thank youu

structure(list(DISCLOSURE_1 = structure(c(4L, 3L, 1L, 3L, 1L,
1L, 4L, 3L, 4L, 3L, 4L, 1L, 3L, 3L, 4L, 1L, 3L, 3L, 1L, 3L, 3L,
4L, 2L, 1L, 1L, 4L, 2L, 3L, 3L, 1L, 4L, 1L, 1L, 4L, 4L, 1L, 3L,
2L, 2L, 1L, 4L, 1L, 1L, 1L, 4L, 3L, 4L, 3L, 2L, 3L, 1L, 1L, 3L,
1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 2L, 1L, 3L, 3L, 3L, 3L, 2L, 2L,
3L, 3L, 2L, 1L, 2L, 3L, 1L, 2L, 2L, 1L, 1L, 1L, 3L, 2L, 2L, 3L,
3L, 2L, 3L, 3L, 2L, 1L, 3L, 1L, 1L, 4L, 4L, 1L, 2L, 4L, 3L, 1L,
1L, 1L, 3L, 2L, 3L, 1L, 2L, 2L, 3L, 4L, 2L, 4L, 2L, 3L, 3L, 2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 1L, 1L, 2L, 2L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L,
2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("DF",
"SM"), class = "factor")), row.names = c(NA, -367L), class = c("tbl_df",
"tbl", "data.frame"))

Body:
With data as your data.frame, this will replace exactly half (rounded down) of the N's with DF with SM:

blnN <- data$DISCLOSURE_1 == "N" & data$TYPE_1 == "DF"
data$TYPE_1[sample(which(blnN), sum(blnN)/2)] <- "SM"


问:
Using Poetry with PyEnv and having Python version issues
I'm working on WSL2 Ubuntu. I've been taking a course in backend API development using Fastapi. My Ubuntu default python is 3.8 I believe. I'm trying to use python 3.10.0 for my development. I've done the following:

pyenv install 3.10.0

cd to my project folder and pyenv local 3.10.0 (creates .python-version file containing 3.10.0)

poetry shell (this creates a .venv folder and all dependencies are added there during development). Bash Prompt has (.venv) in it.

python --version shows 3.10.0 as current version

My problem is that when I look into the .venv/bin file, all of the symbolic links show python 3.8.

```<code>drwxr-xr-x 2 mryan mryan 4096 Feb  1 23:12 .
drwxr-xr-x 4 mryan mryan 4096 Feb  1 23:12 ..
-rw-r--r-- 1 mryan mryan 2152 Feb  1 23:12 activate
-rw-r--r-- 1 mryan mryan 1444 Feb  1 23:12 activate.csh
-rw-r--r-- 1 mryan mryan 3033 Feb  1 23:12 activate.fish
-rw-r--r-- 1 mryan mryan 1303 Feb  1 23:12 activate.nu
-rw-r--r-- 1 mryan mryan 1754 Feb  1 23:12 activate.ps1
-rw-r--r-- 1 mryan mryan 1199 Feb  1 23:12 activate_this.py
-rw-r--r-- 1 mryan mryan  333 Feb  1 23:12 deactivate.nu
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip-3.8
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip3
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip3.8
lrwxrwxrwx 1 mryan mryan   18 Feb  1 23:12 python -> /usr/bin/python3.8
lrwxrwxrwx 1 mryan mryan    6 Feb  1 23:12 python3 -> python
lrwxrwxrwx 1 mryan mryan    6 Feb  1 23:12 python3.8 -> python
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel-3.8
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel3
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel3.8
</code>```

When I try using the command poetry env use 3.10.0 I get the following:

```<code>(.venv) mryan ~/python/fastapi1/.venv/bin $poetry env use 3.10.0
/bin/sh: 1: python3.10: not found

  EnvCommandError

  Command python3.10 -c "import sys; print('.'.join([str(s) for s in sys.version_info[:3]]))" errored with the following return code 127, and output:

  at ~/.local/share/pypoetry/venv/lib/python3.8/site-packages/poetry/utils/env.py:378 in activate
       374│                     shell=True,
       375│                 )
       376│             )
       377│         except CalledProcessError as e:
    →  378│             raise EnvCommandError(e)
       379│
       380│         python_version = Version.parse(python_version.strip())
       381│         minor = "{}.{}".format(python_version.major, python_version.minor)
       382│         patch = python_version.text
(.venv) mryan ~/python/fastapi1/.venv/bin $python3.10
python3.10: command not found
</code>```

What am I doing wrong here? I feel I'm missing something significant here. I've been through a zillion web pages on poetry and virtual environments.

答:
I had the same problem you are having, I used to be able to use:

pyenv local 3.10.0

poetry new example-project

And poetry would create example-project with a venv in it based on python 3.10.0. This no longer worked for me so I found that these commands did work for me:

```<code>poetry new example-project
cd example-project/
poetry env use 3.10.0
poetry update
</code>```

In case your project already had a venv installed it might be a good idea to remove that first before using the poetry env command. I'm pretty sure you haven't added pyenv to your PATH properly. Check out the installation instructions for pyenv, specifically the 'Configure your shell's environment for Pyenv' section.

Body:
I'm working on WSL2 Ubuntu. I've been taking a course in backend API development using Fastapi. My Ubuntu default python is 3.8 I believe. I'm trying to use python 3.10.0 for my development. I've done the following:

pyenv install 3.10.0

cd to my project folder and pyenv local 3.10.0 (creates .python-version file containing 3.10.0)

poetry shell (this creates a .venv folder and all dependencies are added there during development). Bash Prompt has (.venv) in it.

python --version shows 3.10.0 as current version

My problem is that when I look into the .venv/bin file, all of the symbolic links show python 3.8.

drwxr-xr-x 2 mryan mryan 4096 Feb  1 23:12 .
drwxr-xr-x 4 mryan mryan 4096 Feb  1 23:12 ..
-rw-r--r-- 1 mryan mryan 2152 Feb  1 23:12 activate
-rw-r--r-- 1 mryan mryan 1444 Feb  1 23:12 activate.csh
-rw-r--r-- 1 mryan mryan 3033 Feb  1 23:12 activate.fish
-rw-r--r-- 1 mryan mryan 1303 Feb  1 23:12 activate.nu
-rw-r--r-- 1 mryan mryan 1754 Feb  1 23:12 activate.ps1
-rw-r--r-- 1 mryan mryan 1199 Feb  1 23:12 activate_this.py
-rw-r--r-- 1 mryan mryan  333 Feb  1 23:12 deactivate.nu
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip-3.8
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip3
-rwxr-xr-x 1 mryan mryan  249 Feb  1 23:12 pip3.8
lrwxrwxrwx 1 mryan mryan   18 Feb  1 23:12 python -> /usr/bin/python3.8
lrwxrwxrwx 1 mryan mryan    6 Feb  1 23:12 python3 -> python
lrwxrwxrwx 1 mryan mryan    6 Feb  1 23:12 python3.8 -> python
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel-3.8
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel3
-rwxr-xr-x 1 mryan mryan  236 Feb  1 23:12 wheel3.8

When I try using the command poetry env use 3.10.0 I get the following:

(.venv) mryan ~/python/fastapi1/.venv/bin $poetry env use 3.10.0
/bin/sh: 1: python3.10: not found

  EnvCommandError

  Command python3.10 -c "import sys; print('.'.join([str(s) for s in sys.version_info[:3]]))" errored with the following return code 127, and output:

  at ~/.local/share/pypoetry/venv/lib/python3.8/site-packages/poetry/utils/env.py:378 in activate
       374│                     shell=True,
       375│                 )
       376│             )
       377│         except CalledProcessError as e:
    →  378│             raise EnvCommandError(e)
       379│
       380│         python_version = Version.parse(python_version.strip())
       381│         minor = "{}.{}".format(python_version.major, python_version.minor)
       382│         patch = python_version.text
(.venv) mryan ~/python/fastapi1/.venv/bin $python3.10
python3.10: command not found

What am I doing wrong here? I feel I'm missing something significant here. I've been through a zillion web pages on poetry and virtual environments.

Body:
I had the same problem you are having, I used to be able to use:

pyenv local 3.10.0

poetry new example-project

And poetry would create example-project with a venv in it based on python 3.10.0. This no longer worked for me so I found that these commands did work for me:

poetry new example-project
cd example-project/
poetry env use 3.10.0
poetry update

In case your project already had a venv installed it might be a good idea to remove that first before using the poetry env command. I'm pretty sure you haven't added pyenv to your PATH properly. Check out the installation instructions for pyenv, specifically the 'Configure your shell's environment for Pyenv' section.


问:
Failed to listen on 127.0.0.1:443 (reason: Permission denied)
hope you are all good,

I 'am working on a react native app for android, and i need data from my laravel API, the route works fine when i test it with Postman but on my mobile app i got an Error : Network Error.

I have been told that is because i need to put my laravel project on https so i tried

php artisan serve --port=443

but i got this error

Failed to listen on 127.0.0.1:443 (reason: Permission denied).

i'am really stuck and i don't know where the problem is...

Thank you all for you help mates

答:
You've got a bunch of misconceptions interacting with each other here.

Misconception: Running on port 443 will give you HTTPS

Your attempted solution is to make your server listen on port 443, which is the default port for HTTPS.

It is failing because you are running the server as a user that doesn't have permission to listen on that port.

While you could solve that by running with admin privileges, that will just mean you are running an HTTP server on the default HTTPS port. Anything connecting to https://127.0.0.1/ will get an error because it will try to establish an encrypted connection and the HTTP server will be confused.

As far as I can tell, Artisan doesn't support HTTPS directly and you have to use a proxy server instead.

If you were to go down that route, then you could run both Artisan and the HTTPS proxy on any port. You can port a port number in an https:// URL just as you can with an http:// URL.

Misconception: You need HTTPS

You're getting a Network Error error when you try to connect from the mobile app.

While there are some things which require HTTPS, just loading a web page isn't one of them, and the things that do generally are quite explicit about requiring HTTPS in their error logs.

The real cause is most likely because the server is listening on 127.0.0.1 — localhost. It isn't accessible from a different computer.

Solutions

Listen on a different Network interface

You can listen on a non-privileged port on a LAN-facing IP address and then any device on your LAN can connect to it.

```<code>php artisan serve --host 192.168.1.101 --port 8000
</code>```

Make sure you replace the host with an IP address belonging to your computer!

Use a proxy

A service like ngrok will expose your local (listening only on localhost) service on the public Internet (tunneling through any NAT on your router if needed) making it accessible to just about any device.

It can wrap it in HTTPS at the same time if you like.

Body:
You've got a bunch of misconceptions interacting with each other here.

Misconception: Running on port 443 will give you HTTPS

Your attempted solution is to make your server listen on port 443, which is the default port for HTTPS.

It is failing because you are running the server as a user that doesn't have permission to listen on that port.

While you could solve that by running with admin privileges, that will just mean you are running an HTTP server on the default HTTPS port. Anything connecting to https://127.0.0.1/ will get an error because it will try to establish an encrypted connection and the HTTP server will be confused.

As far as I can tell, Artisan doesn't support HTTPS directly and you have to use a proxy server instead.

If you were to go down that route, then you could run both Artisan and the HTTPS proxy on any port. You can port a port number in an https:// URL just as you can with an http:// URL.

Misconception: You need HTTPS

You're getting a Network Error error when you try to connect from the mobile app.

While there are some things which require HTTPS, just loading a web page isn't one of them, and the things that do generally are quite explicit about requiring HTTPS in their error logs.

The real cause is most likely because the server is listening on 127.0.0.1 — localhost. It isn't accessible from a different computer.

Solutions

Listen on a different Network interface

You can listen on a non-privileged port on a LAN-facing IP address and then any device on your LAN can connect to it.

php artisan serve --host 192.168.1.101 --port 8000

Make sure you replace the host with an IP address belonging to your computer!

Use a proxy

A service like ngrok will expose your local (listening only on localhost) service on the public Internet (tunneling through any NAT on your router if needed) making it accessible to just about any device.

It can wrap it in HTTPS at the same time if you like.


问:
multiprocessing.Queue get() works from a Process but not another Thread
I feel like I am losing my mind here.

My program creates a Multiprocessing Queue, then spawns a new Process. From within that Process, I can call get() on the queue and receive objects. However, if I spawn a new Thread from within that Process, the Thread CANNOT receive anything when calling get(). I also tried it with a Manager.Queue and got the same result.

Here is a simplified snippet.

```<code>    from multiprocessing import Process, Queue
    import threading

    def create_process():
        """ Create the queue and start the process """
        cmd_queue = Queue()

        my_proc = Process(target=process_run, args=(cmd_queue,), daemon=True)
        my_proc.start()

        # DEBUGGING:
        time.sleep(1)
        cmd_queue.put("test1")
        time.sleep(1)
        cmd_queue.put("test2")

    def process_run(cmd_queue:Queue):
        """ Function to be run as a multiprocessing Process."""
        logger.info("process_run get(): %s", cmd_queue.get())

        # Set up thread to receive commands:
        thd = threading.Thread(target=thread_commands, args=(cmd_queue,), name="Commands", daemon=True)
        thd.start()

    def thread_commands(cmd_queue:Queue):
        """ Thread to retrieve commands from the command queue and process them """
        while True:
            logger.info("thread_commands get(): %s", cmd_queue.get())
</code>```

When I run this, I get the message "process_run get(): test1", but "thread_commands" never returns from get(). What am I doing wrong here?

答:
Yep it was me being dumb.

I started the Thread with daemon=True and then the Process exited, thus killing the thread.

Body:
I feel like I am losing my mind here.

My program creates a Multiprocessing Queue, then spawns a new Process. From within that Process, I can call get() on the queue and receive objects. However, if I spawn a new Thread from within that Process, the Thread CANNOT receive anything when calling get(). I also tried it with a Manager.Queue and got the same result.

Here is a simplified snippet.

    from multiprocessing import Process, Queue
    import threading

    def create_process():
        """ Create the queue and start the process """
        cmd_queue = Queue()

        my_proc = Process(target=process_run, args=(cmd_queue,), daemon=True)
        my_proc.start()

        # DEBUGGING:
        time.sleep(1)
        cmd_queue.put("test1")
        time.sleep(1)
        cmd_queue.put("test2")

    def process_run(cmd_queue:Queue):
        """ Function to be run as a multiprocessing Process."""
        logger.info("process_run get(): %s", cmd_queue.get())

        # Set up thread to receive commands:
        thd = threading.Thread(target=thread_commands, args=(cmd_queue,), name="Commands", daemon=True)
        thd.start()

    def thread_commands(cmd_queue:Queue):
        """ Thread to retrieve commands from the command queue and process them """
        while True:
            logger.info("thread_commands get(): %s", cmd_queue.get())

When I run this, I get the message "process_run get(): test1", but "thread_commands" never returns from get(). What am I doing wrong here?


问:
How does static field initialization work in C#?
Should static field initialization be completed before constructor is called?

The following program provides output that seems incorrect to me.

```<code>new A()
_A == null
static A()
new A()
_A == A
</code>```

The code:

```<code>public class A
{
    public static string _A = (new A()).I();

    public A()
    {
        Console.WriteLine("new A()");
        if (_A == null)
            Console.WriteLine("_A == null");
        else
            Console.WriteLine("_A == " + _A);
    }

    static A()
    {
        Console.WriteLine("static A()");
    }

    public string I()
    {
        return "A";
    }
}

class Program
{
    static void Main(string[] args)
    {
       var a = new A();
    }
}
</code>```

答:
I actually believe that it is doing what you think.  Your test makes it hard to tell.

Your initalization for _A

```<code>public static string _A = (new A()).I();
</code>```

First creates a new instance of A, thus your writings of new A() and _A = null.  Because it was null when it started, as this is the initialization.  Once initalized, the static constructor is called, which returns the new instance.

ContentLicense: CC BY-SA 2.5

Body:
Should static field initialization be completed before constructor is called?

The following program provides output that seems incorrect to me.

new A()
_A == null
static A()
new A()
_A == A

The code:

public class A
{
    public static string _A = (new A()).I();

    public A()
    {
        Console.WriteLine("new A()");
        if (_A == null)
            Console.WriteLine("_A == null");
        else
            Console.WriteLine("_A == " + _A);
    }

    static A()
    {
        Console.WriteLine("static A()");
    }

    public string I()
    {
        return "A";
    }
}

class Program
{
    static void Main(string[] args)
    {
       var a = new A();
    }
}

Body:
I actually believe that it is doing what you think.  Your test makes it hard to tell.

Your initalization for _A

public static string _A = (new A()).I();

First creates a new instance of A, thus your writings of new A() and _A = null.  Because it was null when it started, as this is the initialization.  Once initalized, the static constructor is called, which returns the new instance.

OwnerDisplayName: Mitchel Sellers


问:
VSCode textmate scopes not overriding color theme when there are multiple scopes
I have installed a custom color theme extension for VSCode and i've been able to override some of the colors from my settings.json, however whenever the theme uses more than one scope, overriding doesn't work on those.

Is there a way to override this color ?

"editor.tokenColorCustomizations": {
        "[Firefox Devtools Italic]": {
            "textMateRules": [
                { // This works:
                    "scope": ["keyword.control"],
                    "settings": {"foreground": "#FF97E9"}
                },
                { // This doesn't work:
                  "scope": [
                        "meta.function-call.js",
                        "entity.name.function.js"
                    ],
                    "settings": {"foreground": "#B98EFF"}
                },
                { // This doesn't work either:
                    "scope": "meta.function-call.js,entity.name.function.js",
                    "settings": {"foreground": "#B98EFF"}
                },
            ]
        }
}
```

答:
It seems that we have to include the space in the array string for it to work as per the following code:

{
    "scope": ["meta.function-call.js entity.name.function.js"],
    "settings": {"foreground": "#B98EFF"}
},
```


问:
time difference between dates depending on id
I am looking for a data.table solution for a simple problem: I have data like this:

```<code>library(data.table)
data1 <- data.table(
  id = rep(1,3),
  date = as.Date(c("2016-03-30", "2016-03-31", "2016-04-05"))
)

data2 <- data.table(
  id = rep(2,2),
  date = as.Date(c("2016-03-30", "2016-03-31"))
)

data3 <- data.table(
    id = rep(3,4),
    date = as.Date(c("2016-03-30", "2016-03-31", "2016-04-05", "2017-04-05"))
    )
data <- rbind(data1,data2,data3)
</code>```

I would like to calculate the time difference between the first date for each unique id and each subsequent date for that unique id. I would like to end with the following, but there must be a one-line solution for this?

```<code>data_want <- data.table(
  t_dif = c(difftime("2016-03-30","2016-03-30",units="days"),
            difftime("2016-03-31","2016-03-30",units="days"),
            difftime("2016-04-05","2016-03-30",units="days"),
            difftime("2016-03-30","2016-03-30",units="days"),
            difftime("2016-03-31","2016-03-30",units="days"),
            difftime("2016-03-30","2016-03-30",units="days"),
            difftime("2016-03-31","2016-03-30",units="days"),
            difftime("2016-04-05","2016-03-30",units="days"),
            difftime("2017-04-05","2016-03-30",units="days"))
)
data_want <- cbind(data, data_want)
</code>```

答:
As it is a data.table, use by for grouping ('id'), get the difftime between the first value of 'date' and the 'date' column and assign (:=) to new column 't_dif'

```<code>library(data.table)
data[, t_dif := difftime(date, first(date), units = 'days' ), by = id]
</code>```

-checking with OP's expected

```<code>> identical(data, data_want)
[1] TRUE
</code>```

Body:
I am looking for a data.table solution for a simple problem: I have data like this:

library(data.table)
data1 <- data.table(
  id = rep(1,3),
  date = as.Date(c("2016-03-30", "2016-03-31", "2016-04-05"))
)

data2 <- data.table(
  id = rep(2,2),
  date = as.Date(c("2016-03-30", "2016-03-31"))
)

data3 <- data.table(
    id = rep(3,4),
    date = as.Date(c("2016-03-30", "2016-03-31", "2016-04-05", "2017-04-05"))
    )
data <- rbind(data1,data2,data3)

I would like to calculate the time difference between the first date for each unique id and each subsequent date for that unique id. I would like to end with the following, but there must be a one-line solution for this?

data_want <- data.table(
  t_dif = c(difftime("2016-03-30","2016-03-30",units="days"),
            difftime("2016-03-31","2016-03-30",units="days"),
            difftime("2016-04-05","2016-03-30",units="days"),
            difftime("2016-03-30","2016-03-30",units="days"),
            difftime("2016-03-31","2016-03-30",units="days"),
            difftime("2016-03-30","2016-03-30",units="days"),
            difftime("2016-03-31","2016-03-30",units="days"),
            difftime("2016-04-05","2016-03-30",units="days"),
            difftime("2017-04-05","2016-03-30",units="days"))
)
data_want <- cbind(data, data_want)

Body:
As it is a data.table, use by for grouping ('id'), get the difftime between the first value of 'date' and the 'date' column and assign (:=) to new column 't_dif'

library(data.table)
data[, t_dif := difftime(date, first(date), units = 'days' ), by = id]

-checking with OP's expected

> identical(data, data_want)
[1] TRUE


问:
Setting up a ViewController via url and show it as a popup
I currently have a method that I use to setup a new ViewController

```<code>func setRootView(viewController vc: UIViewController){
    UIApplication.shared.windows.first?.rootViewController = vc
    UIApplication.shared.windows.first?.makeKeyAndVisible()
}
</code>```

How can I modify the presentation that the ViewController will show over the other screen like presentation style not modally ?

That is the function that gets called after the button is pressed and the view should change:

```<code>func moveToNextVC(isLogin: Bool){
    if self.checkNetworkConnection(){
        let vc = HomeVC(nibName: "HomeVC", bundle: nil)
        if isLogin{
            vc.modalPresentationStyle = .automatic
            vc.url = loginLink

        }else{
            vc.modalPresentationStyle = .automatic
            vc.url = signupLink

        }
        setRootView(viewController: vc)
    }
    else{
        showAlert("Alert!", message: "Please check your internet connection, then try again.")
    }
}
</code>```

答:
Per Shawn Frank's comment:

Instead of doing this UIApplication.shared.windows.first?.rootViewController = vc, I would do present(vc, animated: true)

This solved the problem.

Body:
I currently have a method that I use to setup a new ViewController

func setRootView(viewController vc: UIViewController){
    UIApplication.shared.windows.first?.rootViewController = vc
    UIApplication.shared.windows.first?.makeKeyAndVisible()
}

How can I modify the presentation that the ViewController will show over the other screen like presentation style not modally ?

That is the function that gets called after the button is pressed and the view should change:

func moveToNextVC(isLogin: Bool){
    if self.checkNetworkConnection(){
        let vc = HomeVC(nibName: "HomeVC", bundle: nil)
        if isLogin{
            vc.modalPresentationStyle = .automatic
            vc.url = loginLink

        }else{
            vc.modalPresentationStyle = .automatic
            vc.url = signupLink

        }
        setRootView(viewController: vc)
    }
    else{
        showAlert("Alert!", message: "Please check your internet connection, then try again.")
    }
}


问:
Regex - capture character before pattern until a specific character
I'm trying to match h.Z.getAssetUrl("/FullLogo.svg") from the following string

```<code>4H18V5.2H2z"})),t)})),p=t(7103),h=t(1313),m=function(){return(0,o.jsx)(a.Ee,{src:`h.Z.getAssetUrl("/FullLogo.svg")`,width:"195px",height:"36px"})},g=function(e){var r=e.toggle,t=e.isOpen;return(0,o.jsx)(i.xu,{display:{base:"block",md:"none"}
</code>```

I've tried /getAssetUrl\(.+?\)/, this matches getAssetUrl("/FullLogo.svg"). How do I also match the h.Z. before it. I want to match ahead until a : is encounterd.

答:
You can match all but : chars before your pattern:

/[^:]*getAssetUrl\([^()]*\)/
```

I also suggest using a negated character class to match a string between two parentheses.

Details:

[^:]* - zero or more chars other than :

getAssetUrl\( - a getAssetUrl( string

[^()]* - zero or more chars other than ( and ) chars

\) - a ) char.

See the regex demo.

Body:
I'm trying to match h.Z.getAssetUrl("/FullLogo.svg") from the following string

4H18V5.2H2z"})),t)})),p=t(7103),h=t(1313),m=function(){return(0,o.jsx)(a.Ee,{src:`h.Z.getAssetUrl("/FullLogo.svg")`,width:"195px",height:"36px"})},g=function(e){var r=e.toggle,t=e.isOpen;return(0,o.jsx)(i.xu,{display:{base:"block",md:"none"}

I've tried /getAssetUrl\(.+?\)/, this matches getAssetUrl("/FullLogo.svg"). How do I also match the h.Z. before it. I want to match ahead until a : is encounterd.

Body:
You can match all but : chars before your pattern:

/[^:]*getAssetUrl\([^()]*\)/

I also suggest using a negated character class to match a string between two parentheses.

Details:

[^:]* - zero or more chars other than :

getAssetUrl\( - a getAssetUrl( string

[^()]* - zero or more chars other than ( and ) chars

\) - a ) char.

See the regex demo.