问:
CoreMongooseArray(0) bug instead of Normal array
This is my index.js file

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

const Dishes = require('./models/dishes');

const url = 'mongodb://localhost:27017/conFusion';
const connect = mongoose.connect(url);

connect.then((db) => {

console.log('Connected correctly to server');

Dishes.create({
    name: 'Uthappizza',
    description: 'test'
})
.then((dish) => {
    console.log(dish);

    return Dishes.findByIdAndUpdate(dish._id, {
        $set: { description: 'Updated test'}
    },{
        new: true
    })
    .exec();
})
.then((dish) => {
    console.log(dish);

    dish.comments.push({
        rating: 5,
        comment: 'I\'m getting a sinking feeling!',
        author: 'Leonardo di Carpaccio'
    });

    return dish.save();
})
.then((dish) => {
    console.log(dish);

    return Dishes.remove({});
})
.then(() => {
    return mongoose.connection.close();
})
.catch((err) => {
    console.log(err);
});

});
</code>```

this is my dishes.js file:

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

var commentSchema = new Schema({
    rating:  {
        type: Number,
        min: 1,
        max: 5,
        required: true
    },
    comment:  {
        type: String,
        required: true
    },
    author:  {
        type: String,
        required: true
    }
}, {
    timestamps: true
});

var dishSchema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    description: {
        type: String,
        required: true
    },
    comments:[commentSchema]
}, {
    timestamps: true
});

var Dishes = mongoose.model('Dish', dishSchema);
module.exports = Dishes;
</code>```

I am getting an error that says:

```<code>isNew: false,
  errors: undefined,
  _doc: {
    _id: 6207ff6455a72312f4426861,
    name: 'Uthappizza',
    description: 'Updated test',
    comments: CoreMongooseArray(0) [
      _path: 'comments',
      toBSON: [Function: toBSON],
      _atomics: {},
      _parent: [Circular *1],
      _cast: [Function: _cast],
      _markModified: [Function: _markModified],
      _registerAtomic: [Function: _registerAtomic],
      '$__getAtomics': [Function: $__getAtomics],
      hasAtomics: [Function: hasAtomics],
      _mapCast: [Function: _mapCast],
      push: [Function: push],
      nonAtomicPush: [Function: nonAtomicPush],
      '$pop': [Function: $pop],
      pop: [Function: pop],
      '$shift': [Function: $shift],
      shift: [Function: shift],
      pull: [Function: pull],
      splice: [Function: splice],
      unshift: [Function: unshift],
      sort: [Function: sort],
      addToSet: [Function: addToSet],
      set: [Function: set],
      toObject: [Function: toObject],
      inspect: [Function: inspect],
      indexOf: [Function: indexOf],
      remove: [Function: pull],
      id: [Function: id],
      create: [Function: create],
      notify: [Function: notify],
      isMongooseDocumentArray: true,
      validators: [],
      _schema: [DocumentArray],
      _handlers: [Object]
    ],
    createdAt: 2022-02-12T18:41:40.049Z,
    updatedAt: 2022-02-12T18:41:40.096Z,
    __v: 0
  }
</code>```

the issue is in the output of the comments part, can someone pls help me?
I have tried reading about it online, but i am not able to get anything where is the problem?

Ps: this is a part of course, I have followed all the steps very carefully, but I am still getting the problem

答:
First of all. On the Dish Schema you set rating to be required but you are creating the first time a dish without a rating. This will not work. That is probably what you see in the log. Try to check for errors as well.
I would recomment using async await and not .then for these things and put everything in a try catch block like so:</p>
```<code>try{
  const dish = await Dishes.create({...});
  console.log('first creation of dish', dish)
...
...
...
} catch(e) {
  console.log('error: ', e)
}
</code>```

Body:
This is my index.js file

const mongoose = require('mongoose');

const Dishes = require('./models/dishes');

const url = 'mongodb://localhost:27017/conFusion';
const connect = mongoose.connect(url);

connect.then((db) => {

console.log('Connected correctly to server');

Dishes.create({
    name: 'Uthappizza',
    description: 'test'
})
.then((dish) => {
    console.log(dish);

    return Dishes.findByIdAndUpdate(dish._id, {
        $set: { description: 'Updated test'}
    },{
        new: true
    })
    .exec();
})
.then((dish) => {
    console.log(dish);

    dish.comments.push({
        rating: 5,
        comment: 'I\'m getting a sinking feeling!',
        author: 'Leonardo di Carpaccio'
    });

    return dish.save();
})
.then((dish) => {
    console.log(dish);

    return Dishes.remove({});
})
.then(() => {
    return mongoose.connection.close();
})
.catch((err) => {
    console.log(err);
});

});

this is my dishes.js file:

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

var commentSchema = new Schema({
    rating:  {
        type: Number,
        min: 1,
        max: 5,
        required: true
    },
    comment:  {
        type: String,
        required: true
    },
    author:  {
        type: String,
        required: true
    }
}, {
    timestamps: true
});

var dishSchema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    description: {
        type: String,
        required: true
    },
    comments:[commentSchema]
}, {
    timestamps: true
});

var Dishes = mongoose.model('Dish', dishSchema);
module.exports = Dishes;

I am getting an error that says:

isNew: false,
  errors: undefined,
  _doc: {
    _id: 6207ff6455a72312f4426861,
    name: 'Uthappizza',
    description: 'Updated test',
    comments: CoreMongooseArray(0) [
      _path: 'comments',
      toBSON: [Function: toBSON],
      _atomics: {},
      _parent: [Circular *1],
      _cast: [Function: _cast],
      _markModified: [Function: _markModified],
      _registerAtomic: [Function: _registerAtomic],
      '$__getAtomics': [Function: $__getAtomics],
      hasAtomics: [Function: hasAtomics],
      _mapCast: [Function: _mapCast],
      push: [Function: push],
      nonAtomicPush: [Function: nonAtomicPush],
      '$pop': [Function: $pop],
      pop: [Function: pop],
      '$shift': [Function: $shift],
      shift: [Function: shift],
      pull: [Function: pull],
      splice: [Function: splice],
      unshift: [Function: unshift],
      sort: [Function: sort],
      addToSet: [Function: addToSet],
      set: [Function: set],
      toObject: [Function: toObject],
      inspect: [Function: inspect],
      indexOf: [Function: indexOf],
      remove: [Function: pull],
      id: [Function: id],
      create: [Function: create],
      notify: [Function: notify],
      isMongooseDocumentArray: true,
      validators: [],
      _schema: [DocumentArray],
      _handlers: [Object]
    ],
    createdAt: 2022-02-12T18:41:40.049Z,
    updatedAt: 2022-02-12T18:41:40.096Z,
    __v: 0
  }

the issue is in the output of the comments part, can someone pls help me?
I have tried reading about it online, but i am not able to get anything where is the problem?

Ps: this is a part of course, I have followed all the steps very carefully, but I am still getting the problem

Body:
First of all. On the Dish Schema you set rating to be required but you are creating the first time a dish without a rating. This will not work. That is probably what you see in the log. Try to check for errors as well.
I would recomment using async await and not .then for these things and put everything in a try catch block like so:

try{
  const dish = await Dishes.create({...});
  console.log('first creation of dish', dish)
...
...
...
} catch(e) {
  console.log('error: ', e)
}


来源: stackexchange

问:
How to store data from editText in a txt file and store the file on the phone?
This is my code so far, supposedly this helps generate a file but I can't find it anywhere. I believe that's becuase there isn't a file path or directory provided. So what should I add to properly set the path?</p>
```<code> fun generateFile(){
    val fileName = "dataFile.txt"
    try {
        val fos = openFileOutput(fileName, MODE_PRIVATE)
        val data: String = binding.text.toString()
        fos.write(data.toByteArray())
        fos.flush()
        fos.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    binding.text.setText("")
    Toast.makeText(applicationContext,"writing to file " + fileName.toString() + "completed...",Toast.LENGTH_SHORT).show()

}
</code>```

答:
I believe that's becuase there isn't a file path or directory provided

There is one implied by openFileOutput(). That puts the file into the directory referred to by getFilesDir() on Context.

but I can't find it anywhere

That location is part of internal storage. That file is accessible by your app, but not by users. On debug builds of your app, you can get it via tools like Android Studio's Device File Explorer.

ContentLicense: CC BY-SA 4.0

Body:
This is my code so far, supposedly this helps generate a file but I can't find it anywhere. I believe that's becuase there isn't a file path or directory provided. So what should I add to properly set the path?

 fun generateFile(){
    val fileName = "dataFile.txt"
    try {
        val fos = openFileOutput(fileName, MODE_PRIVATE)
        val data: String = binding.text.toString()
        fos.write(data.toByteArray())
        fos.flush()
        fos.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    binding.text.setText("")
    Toast.makeText(applicationContext,"writing to file " + fileName.toString() + "completed...",Toast.LENGTH_SHORT).show()

}


问:
Fade a color to white (increasing brightness)
I want to make a text box in .NET "glow" yellow, and then "fade" to white (basically, by incrementally increasing the brightness). I think Stackoverflow does this after you've posted an answer. I know that increasing brightness is not all that simple (it's not just uniformly increasing/decreasing RGB), but I'm not sure how to do this.

Perfect color accuracy is not important for this. I am using C#, although VB examples would be just fine, too.

Edit: This is for Winforms.

答: If you want to do it qucikly and smoothly, take a look at the ColorMatrix class.</p>

OwnerDisplayName: Jon B

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jon B

OwnerDisplayName: Neil N


问:
Loop flow control
I have an array of objects, each object has a function that returns a Boolean value. What I need to do, is have a loop continuously running until each object returns a true value when the function is called on each object.

EDIT: Sorry I wasn't clear enough, I meant that I want the loop to break, when ALL of the objects functions return true.

Any ideas?

答:
If I got your question, you can do like this...</p>

```<code>do
{
  test = 0;
  for(all functions)
  {
    char test_array[] = function_call();
  }
  int i = 0;
  for(test_array.length)
  {

    if(test_array[i] == true)
    {
      count_no_true = i++;
    }
  }
  if(count_no_true == no of function)
  {test == 1;}
  else
  {test == 0;}
}while(test == 1)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Loop flow control

Body:
If I got your question, you can do like this...

do
{
  test = 0;
  for(all functions)
  {
    char test_array[] = function_call();
  }
  int i = 0;
  for(test_array.length)
  {

    if(test_array[i] == true)
    {
      count_no_true = i++;
    }
  }
  if(count_no_true == no of function)
  {test == 1;}
  else
  {test == 0;}
}while(test == 1)


问:
Trouble spacing in JFrame
I am new to Java, what I am trying to do is generate a GUI with a bunch of images I have managed to generate a bunch of images, however, they have unnecessary space between them horizontally, is there any way that I can get rid of this currently I am generating them like so?

```<code>setLayout(new FlowLayout());
int numberOfTabs = 4;// number of times image is shown
for(int i = 0; i<numberOfTabs;i++) {
    add(
        new JLabel(new ImageIcon(getClass().getClassLoader().getResource("Path to image"))));
    //creates a new image anonymous object and adds it to the jframe
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Sheetssss");
pack();
setVisible(true);
//also in this context this = a Jframe object so all these methods can be called without an object reference
</code>```

is there some other method that I can call so that the horizontal spacing can be set to 0?
As shown in the image below there is space between the images, the 2 vertical black lines between images should be overlapping

Thanks

答:
You just need to change

```<code>setLayout(new FlowLayout())
</code>```

to

```<code>setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
</code>```

Title: Trouble spacing in JFrame

Body:
I am new to Java, what I am trying to do is generate a GUI with a bunch of images I have managed to generate a bunch of images, however, they have unnecessary space between them horizontally, is there any way that I can get rid of this currently I am generating them like so?

setLayout(new FlowLayout());
int numberOfTabs = 4;// number of times image is shown
for(int i = 0; i<numberOfTabs;i++) {
    add(
        new JLabel(new ImageIcon(getClass().getClassLoader().getResource("Path to image"))));
    //creates a new image anonymous object and adds it to the jframe
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Sheetssss");
pack();
setVisible(true);
//also in this context this = a Jframe object so all these methods can be called without an object reference

is there some other method that I can call so that the horizontal spacing can be set to 0?
As shown in the image below there is space between the images, the 2 vertical black lines between images should be overlapping

Thanks

Body:
You just need to change

setLayout(new FlowLayout())

to

setLayout(new FlowLayout(FlowLayout.LEFT,0,0));


问:
C# For Loop with LIST using LINQ
I'm using LINQ and returning a list to my Business Logic Layer. I'mtrying to change one of the values in the list (changing the 'star' rating to an image with the number of stars).

Although the counter (i) appears to be working, the FOR loop is not working correctly.  The first time through it stops at the correct IF but then it pops out at the ELSE statement for everything and all values end up with "star0.png."  It appears as though I'm not cycling through the list???  Thanks in advance!

```<code>    for (int i = 0; i < ReviewList.Count; i++)
    {
        string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
        if (serviceCode == "*")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star1.png";
        }
        else if (serviceCode == "**")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star2.png";
        }
        else if (serviceCode == "***")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star3.png";
        }
        else if (serviceCode == "****")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star4.png";
        }
        else
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star0.png";
        }
    }
</code>```

答:
Protection on double pass and with else condition

```<code>for (int i = 0; i < ReviewList.Count; i++)
{
    string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
    if(!serviceCode.Contains(".png")) { // once name set should not be modified
      if(serviceCode.Contains("*"))
         ReviewList[i].SERVICE.SERVICE_DESC = "star" + serviceCode.Length + ".png";
      else
         ReviewList[i].SERVICE.SERVICE_DESC = "star0.png";

   }
}
</code>```

alternate LINQ approach

```<code>       ReviewList.ForEach(rs=>if(!rs.SERVICE.SERVICE_DESC.Contains(".png"))
{ rs.SERVICE.SERVICE_DESC =
    "star" + rs.SERVICE.SERVICE_DESC.Length + ".png"});
</code>```

Title: C# For Loop with LIST using LINQ

Body:
I'm using LINQ and returning a list to my Business Logic Layer. I'mtrying to change one of the values in the list (changing the 'star' rating to an image with the number of stars).

Although the counter (i) appears to be working, the FOR loop is not working correctly.  The first time through it stops at the correct IF but then it pops out at the ELSE statement for everything and all values end up with "star0.png."  It appears as though I'm not cycling through the list???  Thanks in advance!

    for (int i = 0; i < ReviewList.Count; i++)
    {
        string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
        if (serviceCode == "*")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star1.png";
        }
        else if (serviceCode == "**")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star2.png";
        }
        else if (serviceCode == "***")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star3.png";
        }
        else if (serviceCode == "****")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star4.png";
        }
        else
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star0.png";
        }
    }

Body:
Protection on double pass and with else condition

for (int i = 0; i < ReviewList.Count; i++)
{
    string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
    if(!serviceCode.Contains(".png")) { // once name set should not be modified
      if(serviceCode.Contains("*"))
         ReviewList[i].SERVICE.SERVICE_DESC = "star" + serviceCode.Length + ".png";
      else
         ReviewList[i].SERVICE.SERVICE_DESC = "star0.png";

   }
}

alternate LINQ approach

       ReviewList.ForEach(rs=>if(!rs.SERVICE.SERVICE_DESC.Contains(".png"))
{ rs.SERVICE.SERVICE_DESC =
    "star" + rs.SERVICE.SERVICE_DESC.Length + ".png"});


问:
set x range in seaborne violinplot by month
I am trying to plot temperature data recorded over the year using a seaborn violinplot.

I manage to do the following plot:

I would like to start the plot in January, even if the data collection starts in March for 2021, in order to display yearly plots on top of each other and be able to visually compare same months of different years.

I tried the following use of set_xlim, but it didn't work

```<code>fig, ax = plt.subplots(figsize=(24,10))
fontsize=18
ax.set_xlim(1,12)
plt.rc('xtick', labelsize=fontsize)
plt.rc('ytick', labelsize=fontsize)

plt.rcParams['font.size']=24

seaborn.violinplot(x = weather21_2h.index.month, y = weather21_2h['T out_x'], ax=ax, palette="GnBu",inner = "box")
plt.title('Statistique des températures par mois 2021')
plt.xlabel('Mois', fontsize=24)
plt.ylabel('Températures (°C)')

plt.grid(True)

plt.show()
</code>```

Is there a way ?

答:
You can simply pass order parameter to saeborn.violinplot:

```<code>fig, ax = plt.subplots(figsize=(24,10))
fontsize=18

plt.rc('xtick', labelsize=fontsize)
plt.rc('ytick', labelsize=fontsize)

plt.rcParams['font.size']=24

sns.violinplot(x = weather21_2h.index.month,
               y = weather21_2h['T out_x'],
               ax=ax,
               palette="GnBu",
               inner = "box",
               order = range(1, 13))

ax.set_title('Statistique des températures par mois 2021')
ax.set_xlabel('Mois', fontsize=24)
ax.set_ylabel('Températures (°C)')

ax.grid(True)

plt.show()
</code>```

Body:
I am trying to plot temperature data recorded over the year using a seaborn violinplot.

I manage to do the following plot:

I would like to start the plot in January, even if the data collection starts in March for 2021, in order to display yearly plots on top of each other and be able to visually compare same months of different years.

I tried the following use of set_xlim, but it didn't work

fig, ax = plt.subplots(figsize=(24,10))
fontsize=18
ax.set_xlim(1,12)
plt.rc('xtick', labelsize=fontsize)
plt.rc('ytick', labelsize=fontsize)

plt.rcParams['font.size']=24

seaborn.violinplot(x = weather21_2h.index.month, y = weather21_2h['T out_x'], ax=ax, palette="GnBu",inner = "box")
plt.title('Statistique des températures par mois 2021')
plt.xlabel('Mois', fontsize=24)
plt.ylabel('Températures (°C)')

plt.grid(True)

plt.show()

Is there a way ?

Body:
You can simply pass order parameter to saeborn.violinplot:

fig, ax = plt.subplots(figsize=(24,10))
fontsize=18

plt.rc('xtick', labelsize=fontsize)
plt.rc('ytick', labelsize=fontsize)

plt.rcParams['font.size']=24

sns.violinplot(x = weather21_2h.index.month,
               y = weather21_2h['T out_x'],
               ax=ax,
               palette="GnBu",
               inner = "box",
               order = range(1, 13))

ax.set_title('Statistique des températures par mois 2021')
ax.set_xlabel('Mois', fontsize=24)
ax.set_ylabel('Températures (°C)')

ax.grid(True)

plt.show()


问:
Where exactly to see particular index data in kibana?
I am very new to ELK stack.Now i am able create custom index in elastic search by using log-stash and i can see created index in *9200/_plugin/head/ url . But want to view those created indexes/inside data in kibana.

I have kibana homepage *9200/_plugin/kibana/#/dashboard/file/default.json

Can any one suggest please ?

答:
This is for Kibana 8:

Open "Manage Spaces"

Open "Data Views" --> "Create data view

Enter Index + Timestamp and "Create data view"

Then go back to "Discover" and view the new "view".

You may have to "change data view"


问:
NoClassDefFoundError caused by Kotlin readLine function
Whenever i try to execute a .jar file containing my code, it throws NoClassDefFoundError: kotlin/io/ConsoleKt. So far i haven't found a solution to this problem but I think the problem has something to do with the readLine() function I have in the script but I don't know what. The weird thing is that my code ran perfectly in Intellij itself but once I built it started throwing this exception that never happened outside of IntelliJ. The specific error is:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/io/ConsoleKt
        at com.quantumzizo.calcualtorkotlin.DisplayKt.main(Display.kt:23)
        at com.quantumzizo.calcualtorkotlin.DisplayKt.main(Display.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.io.ConsoleKt
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
        ... 2 more
</code>```

Is there solution that can solve this?

答:
So it turns out all I had to do was build a fat jar with all the dependencies. I used the Gradle plugin Shadow to make a fat jar.
Props to @Endzeit for suggesting that I use it.

Body:
Whenever i try to execute a .jar file containing my code, it throws NoClassDefFoundError: kotlin/io/ConsoleKt. So far i haven't found a solution to this problem but I think the problem has something to do with the readLine() function I have in the script but I don't know what. The weird thing is that my code ran perfectly in Intellij itself but once I built it started throwing this exception that never happened outside of IntelliJ. The specific error is:

Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/io/ConsoleKt
        at com.quantumzizo.calcualtorkotlin.DisplayKt.main(Display.kt:23)
        at com.quantumzizo.calcualtorkotlin.DisplayKt.main(Display.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.io.ConsoleKt
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
        ... 2 more

Is there solution that can solve this?


问:
Setting the output file name in a biztalk send port
Good afternoon,

I'm trying to set the output file name in a send port and the available file name macros won't quite work.

I need something of the form "file.YYYYMMDD_HHMMSS". There's a datetime combined macro (with the wrong format), a time only macro, but no date only macro.

I don't have an orchestration for this process.

Is there any way I can set the file name from within a map or a pipeline?

Thanks!

答:
You can create a custom pipeline component to be placed on the send side (say encode stage), and then set the BTS.ReceiveFileName property to the custom file name value that needs to be set.

After this is done, you can use the %SourceFileName% macro in the Send Port. You can also refer to this MSDN forum link for more details


问:
Subquery help Postgres
I have 2 tables in my schema:

1 - covid_data (relevant columns: country, year, week, cases). Data example:

```<code>+-------+------+-----+-------+
|country| year | week| cases |
+-------+------+-----+-------+
|USA    | 2022 |  1  | 58488 |
|USA    | 2022 |  2  | 65154 |
|USA    | 2022 |  3  | 74154 |
|USA    | 2022 |  4  | 84158 |
|USA    | 2022 |  5  | 96997 |
+-------+------+-----+-------+
</code>```

countries_of_the_world (relevant column: country)

```<code>+-------+
|country|
+--------
|USA    |
|France |
|Brazil |
|Germany|
|China  |
+-------+
</code>```

I need to retrieve the most recent record for each country in countries_of_the_world. The rule for the "most recent record" is determined by higher value in year and higher value in week. For example, right now we are at week 6, year 2022.

I did the following code:

```<code>SELECT country, max(year), max(week)
FROM covid_data
WHERE week in (
    SELECT MAX(week)
    FROM covid_data
    WHERE year in (
        SELECT MAX(year)
        FROM covid_data
        GROUP BY year)
    GROUP BY week)
GROUP BY country;
</code>```

but is retrieving like the infos apart. For example week 53 for year 2022, because this week is "available" for the past year:

```<code>+--------------------+
|country| year | week|
+--------------------+
|USA    | 2022 | 53  |
+--------------------+
</code>```

How can I do this query including joining with every country with the other table?

答:
Untested but does the following give what you are after?</p>
```<code>with c as (
  select country, cases,
    Row_Number() over(partition by country order by year desc, week desc) rn
  from covid_data
)
select country, cases
from c
where rn = 1;
</code>```

Title: Subquery help Postgres

Body:
I have 2 tables in my schema:

1 - covid_data (relevant columns: country, year, week, cases). Data example:

+-------+------+-----+-------+
|country| year | week| cases |
+-------+------+-----+-------+
|USA    | 2022 |  1  | 58488 |
|USA    | 2022 |  2  | 65154 |
|USA    | 2022 |  3  | 74154 |
|USA    | 2022 |  4  | 84158 |
|USA    | 2022 |  5  | 96997 |
+-------+------+-----+-------+

countries_of_the_world (relevant column: country)

+-------+
|country|
+--------
|USA    |
|France |
|Brazil |
|Germany|
|China  |
+-------+

I need to retrieve the most recent record for each country in countries_of_the_world. The rule for the "most recent record" is determined by higher value in year and higher value in week. For example, right now we are at week 6, year 2022.

I did the following code:

SELECT country, max(year), max(week)
FROM covid_data
WHERE week in (
    SELECT MAX(week)
    FROM covid_data
    WHERE year in (
        SELECT MAX(year)
        FROM covid_data
        GROUP BY year)
    GROUP BY week)
GROUP BY country;

but is retrieving like the infos apart. For example week 53 for year 2022, because this week is "available" for the past year:

+--------------------+
|country| year | week|
+--------------------+
|USA    | 2022 | 53  |
+--------------------+

How can I do this query including joining with every country with the other table?

Body:
Untested but does the following give what you are after?

with c as (
  select country, cases,
    Row_Number() over(partition by country order by year desc, week desc) rn
  from covid_data
)
select country, cases
from c
where rn = 1;


问:
How to convert JWK to PEM
This question is more generic rather than for a specific language, so I will explain my issue and what I have tried in pseudocode.

I am trying to generate a PEM public key from a JWK Set. The JWK includes the "e" (exponent) and the "n" (modulus) variables. My question is what would be the exact steps to convert this JWK to PEM without using any libraries and without the OpenSSL command-line tool.

Here is the JWK for reference:

```<code>{
  "kty": "RSA",
  "alg": "RS512",
  "kid": "26887d3ee3293c526c0e6dd05f122df53aa3f13d7dad06d25e266fa6f51db79fb52422aaf79f121476237e98dcd6640350fee47fec70e783544ec9a36e4605bc",
  "use": "sig",
  "n": "14m79mVwIE0JxQdKrgXVf7dVcBS90U0TvG7Yf7dG4NJocz1PNUrKrzGhe_FryOe0JahL_sjA2_rKw7NBCpuVx_zSPFRw6kqjewGicjXGus5Fmlf3zDuqwV4BWIFHyQexMPOly0agFfcM0M0MgBULXjINgBs9MwnRv7JVfRoGqXHsNM45djFDd3o4liu4LPlge_DquZUFLNu-BYAyAlWkz0H2TepZhGrN9VEPmxzQkNzXc1R4MpZvbxrRRgaAA2z094ik3hk86JhfyFq-LDcueZhtshmrYZ95LWgMlQ7PixkeK1HkeEYMt20lmNzR8B8KabimYmibxA4Ay9gpRwfp-Q",
  "e": "AQAB"
}
</code>```

The bulk of my research originates from the node-jwk-to-pem library (which can be found here: https://github.com/Brightspace/node-jwk-to-pem) and a StackOverflow question which uses a JOSE library in PHP (which can be found here: How to convert a public key from a JWK into PEM for OpenSSL?)

From what I have figured out through reading the above mentioned libraries (plus a few other articles and questions that didn't quite mention the step-by-step process), I found that the first step would be to convert the modulus and exponents to integers (specifically BigInt). This usually results in the following:

```<code>n = 27209154847141595039206198313134388207882403216639061643382959557246344691110642716248339592972939239825436848454712213431917464875221502188500634554426063986720722251339335488215426908010590565758292169712942346285217861588132983738839891250753593240057639347814778952277719613395670962156961452389927728643840215833830614315091417876959205843957512422401240879135352731575182574836052718961865690645602829768565458494497550672252951063585023601307115444743487394113997186698238507983094748342588645472362960665610355698438390751920697759620235642103374737421940385132232531739910444003185620313592808726865629407737
e = 65537
</code>```

Using this information, how would I generate the PEM public key from the exponent and modulus? Any pseudocode or suggestions would be incredible!

答:
A RSA public key is defined by both the modulus n and the exponent e.

You can obtain that information directly from a JWK of type RSA using the n and e fields:

The "n" (modulus) parameter contains the modulus value for the RSA
public key.  It is represented as a Base64urlUInt-encoded value.

The "e" (exponent) parameter contains the exponent value for the RSA
public key.  It is represented as a Base64urlUInt-encoded value.

To create a PEM file that represent this public key information, you basically need to build its equivalent ASN.1 DER encoded representation, maybe with some preamble. In its original form, it is defined like this in RFC3447:

```<code>RSAPublicKey ::= SEQUENCE {
  modulus           INTEGER,  -- n
  publicExponent    INTEGER   -- e
}
</code>```

ASN.1 define rules and types for representing arbitrary data structures, and it is widely used in cryptography for that purpose.

ASN.1 only gives you a syntax, but the actual encoding of that information is performed using different encoding formats, especially DER.

The way in which that encoding is performed is non trivial: Let's Encrypt provides an excellent article about the subject. The great lapo.it/asn1js site provides a wonderful tool for inspecting ASN.1 DER encoded information as well.

Consider for instance the following modulus and exponent, extracted from a SO question mentioned below:

```<code>SEQUENCE (2 elements)
   INTEGER (2048 bit): EB506399F5C612F5A67A09C1192B92FAB53DB28520D859CE0EF6B7D83D40AA1C1DCE2C0720D15A0F531595CAD81BA5D129F91CC6769719F1435872C4BCD0521150A0263B470066489B918BFCA03CE8A0E9FC2C0314C4B096EA30717C03C28CA29E678E63D78ACA1E9A63BDB1261EE7A0B041AB53746D68B57B68BEF37B71382838C95DA8557841A3CA58109F0B4F77A5E929B1A25DC2D6814C55DC0F81CD2F4E5DB95EE70C706FC02C4FCA358EA9A82D8043A47611195580F89458E3DAB5592DEFE06CDE1E516A6C61ED78C13977AE9660A9192CA75CD72967FD3AFAFA1F1A2FF6325A5064D847028F1E6B2329E8572F36E708A549DDA355FC74A32FDD8DBA65
   INTEGER (24 bit): 010001
</code>```

The corresponding ASN.1 DER encoding is the following:

```<code>30 82 01 0A      ;sequence (0x10A bytes long)
   02 82 01 01   ;integer (0x101 bytes long)
      00 EB506399F5C612F5A67A09C1192B92FAB53DB28520D859CE0EF6B7D83D40AA1C1DCE2C0720D15A0F531595CAD81BA5D129F91CC6769719F1435872C4BCD0521150A0263B470066489B918BFCA03CE8A0E9FC2C0314C4B096EA30717C03C28CA29E678E63D78ACA1E9A63BDB1261EE7A0B041AB53746D68B57B68BEF37B71382838C95DA8557841A3CA58109F0B4F77A5E929B1A25DC2D6814C55DC0F81CD2F4E5DB95EE70C706FC02C4FCA358EA9A82D8043A47611195580F89458E3DAB5592DEFE06CDE1E516A6C61ED78C13977AE9660A9192CA75CD72967FD3AFAFA1F1A2FF6325A5064D847028F1E6B2329E8572F36E708A549DDA355FC74A32FDD8DBA65
   02 03         ;integer (3 bytes long)
      010001
</code>```

In ASN.1 DER, every element is encoded as type-length-value triplet.

The type is identified by a tag, usually encoded with one byte.

For example, 30 means a SEQUENCE whereas 02 corresponds to an INTEGER type.

The above mentioned article provides a list of the different types defined by ASN.1 with the corresponding tag.

The length is a bit tricky: it is indicated by a single byte if the associated value is up to 127 (0x7F) bytes long. If the number of bytes is greater than 127, then this first length byte specifies the number of bytes that actually define the length. Please, consider read the Length section of this article, I think it is very explanatory.

Then, you include the actual value.

In the example provided, 30 82 01 0A means:

30: A SEQUENCE.

82: the length byte. 0x82 & 0x7F -> 0x02 The actual value length is expressed in 2 bytes.

01 0A: Actual value length, 266 bytes long.

Now, the value 02 82 01 01 00 EB506399F5C612F5A67A09C119...:

02: An INTEGER

82: the length byte. Again, 0x82 & 0x7F -> 0x02. The actual value length is expressed in 2 bytes.

01 01: Actual value length, 257 bytes long, a modulus of 2048 bits padded with a first byte 0x00 (see the Integer padding section in the aforementioned article).

00 EB506399F5C612F5A67A09C119: padded modulus value.

Finally, 02 03 010001:

02: An INTEGER.

03: The exponent value is 3 bytes long.

010001: exponent value.

This result should be then encoded as base64 and enclosed within special text delimiters, -----BEGIN RSA PUBLIC KEY----- and -----END RSA PUBLIC KEY-----, for instance.

Please, be aware that you have several options to represent the key in PEM format, the one described above, PKCS#1, and the more generic X.509, suitable for the representation of keys in different formats (the one of the form -----BEGIN PUBLIC KEY-----). Consider read this wonderful SO question and related answer, it explains in great detail not only the RSA public key fundamentals, but the caveats of those different representations as well.

Consider read as well this and especially this other SO questions, I think they can be of help also.

Title: How to convert JWK to PEM

Body:
This question is more generic rather than for a specific language, so I will explain my issue and what I have tried in pseudocode.

I am trying to generate a PEM public key from a JWK Set. The JWK includes the "e" (exponent) and the "n" (modulus) variables. My question is what would be the exact steps to convert this JWK to PEM without using any libraries and without the OpenSSL command-line tool.

Here is the JWK for reference:

{
  "kty": "RSA",
  "alg": "RS512",
  "kid": "26887d3ee3293c526c0e6dd05f122df53aa3f13d7dad06d25e266fa6f51db79fb52422aaf79f121476237e98dcd6640350fee47fec70e783544ec9a36e4605bc",
  "use": "sig",
  "n": "14m79mVwIE0JxQdKrgXVf7dVcBS90U0TvG7Yf7dG4NJocz1PNUrKrzGhe_FryOe0JahL_sjA2_rKw7NBCpuVx_zSPFRw6kqjewGicjXGus5Fmlf3zDuqwV4BWIFHyQexMPOly0agFfcM0M0MgBULXjINgBs9MwnRv7JVfRoGqXHsNM45djFDd3o4liu4LPlge_DquZUFLNu-BYAyAlWkz0H2TepZhGrN9VEPmxzQkNzXc1R4MpZvbxrRRgaAA2z094ik3hk86JhfyFq-LDcueZhtshmrYZ95LWgMlQ7PixkeK1HkeEYMt20lmNzR8B8KabimYmibxA4Ay9gpRwfp-Q",
  "e": "AQAB"
}

The bulk of my research originates from the node-jwk-to-pem library (which can be found here: https://github.com/Brightspace/node-jwk-to-pem) and a StackOverflow question which uses a JOSE library in PHP (which can be found here: How to convert a public key from a JWK into PEM for OpenSSL?)

From what I have figured out through reading the above mentioned libraries (plus a few other articles and questions that didn't quite mention the step-by-step process), I found that the first step would be to convert the modulus and exponents to integers (specifically BigInt). This usually results in the following:

n = 27209154847141595039206198313134388207882403216639061643382959557246344691110642716248339592972939239825436848454712213431917464875221502188500634554426063986720722251339335488215426908010590565758292169712942346285217861588132983738839891250753593240057639347814778952277719613395670962156961452389927728643840215833830614315091417876959205843957512422401240879135352731575182574836052718961865690645602829768565458494497550672252951063585023601307115444743487394113997186698238507983094748342588645472362960665610355698438390751920697759620235642103374737421940385132232531739910444003185620313592808726865629407737
e = 65537

Using this information, how would I generate the PEM public key from the exponent and modulus? Any pseudocode or suggestions would be incredible!

Body:
A RSA public key is defined by both the modulus n and the exponent e.

You can obtain that information directly from a JWK of type RSA using the n and e fields:

The "n" (modulus) parameter contains the modulus value for the RSA
public key.  It is represented as a Base64urlUInt-encoded value.

The "e" (exponent) parameter contains the exponent value for the RSA
public key.  It is represented as a Base64urlUInt-encoded value.

To create a PEM file that represent this public key information, you basically need to build its equivalent ASN.1 DER encoded representation, maybe with some preamble. In its original form, it is defined like this in RFC3447:

RSAPublicKey ::= SEQUENCE {
  modulus           INTEGER,  -- n
  publicExponent    INTEGER   -- e
}

ASN.1 define rules and types for representing arbitrary data structures, and it is widely used in cryptography for that purpose.

ASN.1 only gives you a syntax, but the actual encoding of that information is performed using different encoding formats, especially DER.

The way in which that encoding is performed is non trivial: Let's Encrypt provides an excellent article about the subject. The great <a href="https://lapo.it/asn1js/#MIIFaTCCBFGgAwIBAgISA9QVMY4sVx0pBfw-BSdonQ0JMA0GCSqGSIb3DQEBCwUAMEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQDExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0xOTA5MjkxNjMzMzZaFw0xOTEyMjgxNjMzMzZaMBoxGDAWBgNVBAMTD2xldHNlbmNyeXB0Lm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANACdZdYiHLXjUhzqmaHENZ_mYp05-bbJw0RhmkCMN32iqPP0_2_KBRi60F87-itSNcKpQ_HQmEm5NoaH6rHzPuihv834og9TPsHeM0QOkaGOcR001h0kGRlIgynXzG7kSO7hTAUSbLfzCD4Hp8swLJHCz787sn_09DvPkJdeHhlQvrgfnGXqsHLqSXo9UtZXriwYS0HRCt5dKCLTOQAmS5ezKG2-7LVcuQQGsG1st3f2t092zJ8BDj_hAd0Zh8vKRwkDZvPzZzo76g4pGtVPRhmcDnVLin4PmsysWevEdzpJhNO7FXCsCA2aWo4ePAYKrR9BjyNlPAQ2QkKlI_cJx8CAwEAAaOCAncwggJzMA4GA1UdDwEB_wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH_BAIwADAdBgNVHQ4EFgQUfCuj5zyEXzjUdndlK8VKWGyO3aowHwYDVR0jBBgwFoAUqEpqYwR93brm0Tm3pkVl7_Oo7KEwbwYIKwYBBQUHAQEEYzBhMC4GCCsGAQUFBzABhiJodHRwOi8vb2NzcC5pbnQteDMubGV0c2VuY3J5cHQub3JnMC8GCCsGAQUFBzAChiNodHRwOi8vY2VydC5pbnQteDMubGV0c2VuY3J5cHQub3JnLzAvBgNVHREEKDAmgg9sZXRzZW5jcnlwdC5vcmeCE3d3dy5sZXRzZW5jcnlwdC5vcmcwTAYDVR0gBEUwQzAIBgZngQwBAgEwNwYLKwYBBAGC3xMBAQEwKDAmBggrBgEFBQcCARYaaHR0cDovL2Nwcy5sZXRzZW5jcnlwdC5vcmcwggECBgorBgEEAdZ5AgQCBIHzBIHwAO4AdQDiaUuuJujpQAnohhu2O4PUPuf-dIj7pI8okwGd3fHb_gAAAW1-FbruAAAEAwBGMEQCIBROHx_dL0yfOpZs7Y6teawOn0oawhuW-3lvVs61DhjcAiB2ZuYwHu3BwYtqJTqfwsjQzjMZm8bQOutdme7dfaLXvgB1ACk8UZZUyDlluqpQ_FgH1Ldvv1h6KXLcpMMM9OVFR_R4AAABbX4VuuYAAAQDAEYwRAIgTc8_QJi4odfZIQ1u74zzvkBobqa08Wb_vxoqlgviUYICIGnAFgaPUg-xzKTRZGTGO4cj8UGJ3f52NoD6UWipPgIvMA0GCSqGSIb3DQEBCwUAA4IBAQAWl67Avp7BgqZW3VEWEjXHganloM8OHMS6en6S46nyuW0itGzth8SmCuG4i7fseecEG3Zsm0U1S1d3AffClOwWAGxB5Ark8Bpjszy8nGtNo7pFH-psGCBGj1pnklteu3jUzkkXKHS00Dsna1fJIzswgD7X7et8PRvV3ufIidkvvbfev0L2TYPWEFMM7WO0eIysf9WTljuflgcbzJXY0PatUBzL59ekidJZvGZ7d-hTl14CcCTrZ-VGMZlmK6tMhBuXJdAa5R0QSUpqirGRLz37Ox-SVh_tjA-I2tcRs0euAoX0etcr5cbBapV4-6LtSUt_rLBddeXCnDxqAWQxyy0p" rel="nofollow noreferrer">lapo.it/asn1js site provides a wonderful tool for inspecting ASN.1 DER encoded information as well.

Consider for instance the following modulus and exponent, extracted from a SO question mentioned below:

SEQUENCE (2 elements)
   INTEGER (2048 bit): EB506399F5C612F5A67A09C1192B92FAB53DB28520D859CE0EF6B7D83D40AA1C1DCE2C0720D15A0F531595CAD81BA5D129F91CC6769719F1435872C4BCD0521150A0263B470066489B918BFCA03CE8A0E9FC2C0314C4B096EA30717C03C28CA29E678E63D78ACA1E9A63BDB1261EE7A0B041AB53746D68B57B68BEF37B71382838C95DA8557841A3CA58109F0B4F77A5E929B1A25DC2D6814C55DC0F81CD2F4E5DB95EE70C706FC02C4FCA358EA9A82D8043A47611195580F89458E3DAB5592DEFE06CDE1E516A6C61ED78C13977AE9660A9192CA75CD72967FD3AFAFA1F1A2FF6325A5064D847028F1E6B2329E8572F36E708A549DDA355FC74A32FDD8DBA65
   INTEGER (24 bit): 010001

The corresponding ASN.1 DER encoding is the following:

30 82 01 0A      ;sequence (0x10A bytes long)
   02 82 01 01   ;integer (0x101 bytes long)
      00 EB506399F5C612F5A67A09C1192B92FAB53DB28520D859CE0EF6B7D83D40AA1C1DCE2C0720D15A0F531595CAD81BA5D129F91CC6769719F1435872C4BCD0521150A0263B470066489B918BFCA03CE8A0E9FC2C0314C4B096EA30717C03C28CA29E678E63D78ACA1E9A63BDB1261EE7A0B041AB53746D68B57B68BEF37B71382838C95DA8557841A3CA58109F0B4F77A5E929B1A25DC2D6814C55DC0F81CD2F4E5DB95EE70C706FC02C4FCA358EA9A82D8043A47611195580F89458E3DAB5592DEFE06CDE1E516A6C61ED78C13977AE9660A9192CA75CD72967FD3AFAFA1F1A2FF6325A5064D847028F1E6B2329E8572F36E708A549DDA355FC74A32FDD8DBA65
   02 03         ;integer (3 bytes long)
      010001

In ASN.1 DER, every element is encoded as type-length-value triplet.

The type is identified by a tag, usually encoded with one byte.

For example, 30 means a SEQUENCE whereas 02 corresponds to an INTEGER type.

The above mentioned article provides a list of the different types defined by ASN.1 with the corresponding tag.

The length is a bit tricky: it is indicated by a single byte if the associated value is up to 127 (0x7F) bytes long. If the number of bytes is greater than 127, then this first length byte specifies the number of bytes that actually define the length. Please, consider read the Length section of this article, I think it is very explanatory.

Then, you include the actual value.

In the example provided, 30 82 01 0A means:

30: A SEQUENCE.

82: the length byte. 0x82 & 0x7F -> 0x02 The actual value length is expressed in 2 bytes.

01 0A: Actual value length, 266 bytes long.

Now, the value 02 82 01 01 00 EB506399F5C612F5A67A09C119...:

02: An INTEGER

82: the length byte. Again, 0x82 & 0x7F -> 0x02. The actual value length is expressed in 2 bytes.

01 01: Actual value length, 257 bytes long, a modulus of 2048 bits padded with a first byte 0x00 (see the Integer padding section in the aforementioned article).

00 EB506399F5C612F5A67A09C119: padded modulus value.

Finally, 02 03 010001:

02: An INTEGER.

03: The exponent value is 3 bytes long.

010001: exponent value.

This result should be then encoded as base64 and enclosed within special text delimiters, -----BEGIN RSA PUBLIC KEY----- and -----END RSA PUBLIC KEY-----, for instance.

Please, be aware that you have several options to represent the key in PEM format, the one described above, PKCS#1, and the more generic X.509, suitable for the representation of keys in different formats (the one of the form -----BEGIN PUBLIC KEY-----). Consider read this wonderful SO question and related answer, it explains in great detail not only the RSA public key fundamentals, but the caveats of those different representations as well.

Consider read as well this and especially this other SO questions, I think they can be of help also.


问:
How to run qt-creator project with 'sudo nice x' prefixes?
So i have a C program that i made a while back that im going to remake in qt with additional features.

Typically how i ran the program is I open the terminal, navigate to the project folder, and use the command

```<code>$ sudo nice --10 ./myprogram
</code>```

That is not the case anymore, since i am using qt-creator i now just simply click the 'run' button and the program starts. My program works best when it has elevated scheduler priority hence the nice --10.

How do i modify my qt-creator project to run my program with the sudo nice --10 command?

答:
I never tried, but in the config of your project you can add a user defined executable to be executed.

Maybe creator allows for a shellscript, than you can simply put your sudo nice --10 in a shellscript, or you write a little program which gets a program path as parameter and starts it with the elevated scheduler priority (guess there is a user api in linux for that...)

Body:
So i have a C program that i made a while back that im going to remake in qt with additional features.

Typically how i ran the program is I open the terminal, navigate to the project folder, and use the command

$ sudo nice --10 ./myprogram

That is not the case anymore, since i am using qt-creator i now just simply click the 'run' button and the program starts. My program works best when it has elevated scheduler priority hence the nice --10.

How do i modify my qt-creator project to run my program with the sudo nice --10 command?


问:
I'm trying to print one letter after another
I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it?
Code:</p>
```<code>    for (let i = 0; i < welcText.length; i++) {
        setTimeout(()=>{
            welcome.innerText += welcText[i];
        },100);
    }
</code>```

答:
You can do it using setInterval instead, and using an iterator to call the next char of the string every time. This is a bit more complicated, but has the advantage of not having multiple schedulers running if the string is too long. See the working example below.

const welcome = document.getElementById('welcome');
const welcomeText = 'Welcome!';

// returns a function that returns the next char in the string everytime its called
function createIterator(string) {
  let currentIndex = 0;
  return function() {
    return string[currentIndex++];
  }
}
// initializes the iterator with the text
let welcomeIterator = createIterator(welcomeText);

let welcomeInterval = setInterval(function() {
  let nextChar = welcomeIterator();
  // if we finish the string we clear the interval
  if (!nextChar) {
    return clearInterval(welcomeInterval);
  }
  // if the char exists, we append it to the div
  welcome.innerText += nextChar;
}, 100);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="welcome"></div></code>```

Body:
I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it?
Code:

    for (let i = 0; i < welcText.length; i++) {
        setTimeout(()=>{
            welcome.innerText += welcText[i];
        },100);
    }

Body:
You can do it using setInterval instead, and using an iterator to call the next char of the string every time. This is a bit more complicated, but has the advantage of not having multiple schedulers running if the string is too long. See the working example below.

const welcome = document.getElementById('welcome');
const welcomeText = 'Welcome!';

// returns a function that returns the next char in the string everytime its called
function createIterator(string) {
  let currentIndex = 0;
  return function() {
    return string[currentIndex++];
  }
}
// initializes the iterator with the text
let welcomeIterator = createIterator(welcomeText);

let welcomeInterval = setInterval(function() {
  let nextChar = welcomeIterator();
  // if we finish the string we clear the interval
  if (!nextChar) {
    return clearInterval(welcomeInterval);
  }
  // if the char exists, we append it to the div
  welcome.innerText += nextChar;
}, 100);

<div id="welcome"></div>


问:
Convert JSON to array with nlohmann/json
I've not used C++ in over 20 years, so I am a bit rusty on this.

I am using the nlohmann/json json.h library and need to convert a JSON string that is an array of objects to an actual array.

As an example, I need to take this kind of response from a TRESTResponse object and turn it into a C++ array:

```<code>RESTRequest1->Execute();
String Content = RESTResponse1->Content;
</code>```

Where Content =

```<code>"[{"fullname":"Norm A","e_mail":null,"phone":"999-555-4971"},{"fullname":"Norm C","e_mail":"ht2@yahoo.com","phone":"999-555-8887"},{"fullname":"Norma Jn","e_mail":null,"phone":"999-555-5947"},{"fullname":"Norma & Frank L","e_mail":null,"phone":"999-555-1790"},{"fullname":"Norm Sh","e_mail":null,"phone":"999-555-7545"},{"fullname":"Norm S","e_mail":null,"phone":"999-555-9955"}]"
</code>```

and get it into an array of objects.  I have been unsuccessful with the library.  While I can get an array into json properly, I can't seem to get json back to an array.

I've looked at some similar posts on Stackoverflow, but I did not see one that concerns the nlohmann/json library.

答:
At a guess, you were probably running into a problem because your input data contains null for a number of the strings (some of the email addresses).

To fix that, you need to explicitly check for is_null before attempting to convert the source to an std::string. At a quick guess, for a null input, you'd probably want to just leave that string empty. For that, your from_json would look something like this:

void from_json(json const &j, Person &p) {
    j.at("fullname").get_to(p.name);
    if (!j.at("e_mail").is_null())
        j.at("e_mail").get_to(p.email);
    j.at("phone").get_to(p.phone);
}
```
<p>That's enough to work for the sample data, but depending on the data involved, you might want/need to protect against a null name and/or phone numbers as well (which you'd do in the same way as shown above for the email address).</p>
<p>A complete demo program using this would might look roughly like this:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <sstream>
#include <string>
#include <iostream>
#include "nlohmann/json.hpp"

using json = nlohmann::json;

std::string input { R"(
[{"fullname":"Norm A","e_mail":null,"phone":"999-555-4971"},{"fullname":"Norm C","e_mail":"ht2@yahoo.com","phone":"999-555-8887"},{"fullname":"Norma Jn","e_mail":null,"phone":"999-555-5947"},{"fullname":"Norma & Frank L","e_mail":null,"phone":"999-555-1790"},{"fullname":"Norm Sh","e_mail":null,"phone":"999-555-7545"},{"fullname":"Norm S","e_mail":null,"phone":"999-555-9955"}]
)"};

namespace P {
struct Person {
    std::string name;
    std::string email;
    std::string phone;

    friend std::ostream &operator<<(std::ostream &os, Person const &p) {
        return os << "name: " << p.name << ", email: " << p.email << ", phone: " << p.phone;
    }
};

void from_json(json const &j, Person &p) {
    j.at("fullname").get_to(p.name);
    if (!j.at("e_mail").is_null())
        j.at("e_mail").get_to(p.email);
    j.at("phone").get_to(p.phone);
}
}

int main() {
    json j = json::parse(input);

    std::vector<P::Person> people;

    j.get_to(people);

    for (auto const &person : people) {
        std::cout << person << "\n";
    }
}
</code>```

Body:
I've not used C++ in over 20 years, so I am a bit rusty on this.

I am using the nlohmann/json json.h library and need to convert a JSON string that is an array of objects to an actual array.

As an example, I need to take this kind of response from a TRESTResponse object and turn it into a C++ array:

RESTRequest1->Execute();
String Content = RESTResponse1->Content;

Where Content =

"[{"fullname":"Norm A","e_mail":null,"phone":"999-555-4971"},{"fullname":"Norm C","e_mail":"ht2@yahoo.com","phone":"999-555-8887"},{"fullname":"Norma Jn","e_mail":null,"phone":"999-555-5947"},{"fullname":"Norma & Frank L","e_mail":null,"phone":"999-555-1790"},{"fullname":"Norm Sh","e_mail":null,"phone":"999-555-7545"},{"fullname":"Norm S","e_mail":null,"phone":"999-555-9955"}]"

and get it into an array of objects.  I have been unsuccessful with the library.  While I can get an array into json properly, I can't seem to get json back to an array.

I've looked at some similar posts on Stackoverflow, but I did not see one that concerns the nlohmann/json library.

Body:
At a guess, you were probably running into a problem because your input data contains null for a number of the strings (some of the email addresses).

To fix that, you need to explicitly check for is_null before attempting to convert the source to an std::string. At a quick guess, for a null input, you'd probably want to just leave that string empty. For that, your from_json would look something like this:

void from_json(json const &j, Person &p) {
    j.at("fullname").get_to(p.name);
    if (!j.at("e_mail").is_null())
        j.at("e_mail").get_to(p.email);
    j.at("phone").get_to(p.phone);
}

That's enough to work for the sample data, but depending on the data involved, you might want/need to protect against a null name and/or phone numbers as well (which you'd do in the same way as shown above for the email address).

A complete demo program using this would might look roughly like this:

#include <sstream>
#include <string>
#include <iostream>
#include "nlohmann/json.hpp"

using json = nlohmann::json;

std::string input { R"(
[{"fullname":"Norm A","e_mail":null,"phone":"999-555-4971"},{"fullname":"Norm C","e_mail":"ht2@yahoo.com","phone":"999-555-8887"},{"fullname":"Norma Jn","e_mail":null,"phone":"999-555-5947"},{"fullname":"Norma & Frank L","e_mail":null,"phone":"999-555-1790"},{"fullname":"Norm Sh","e_mail":null,"phone":"999-555-7545"},{"fullname":"Norm S","e_mail":null,"phone":"999-555-9955"}]
)"};

namespace P {
struct Person {
    std::string name;
    std::string email;
    std::string phone;

    friend std::ostream &operator<<(std::ostream &os, Person const &p) {
        return os << "name: " << p.name << ", email: " << p.email << ", phone: " << p.phone;
    }
};

void from_json(json const &j, Person &p) {
    j.at("fullname").get_to(p.name);
    if (!j.at("e_mail").is_null())
        j.at("e_mail").get_to(p.email);
    j.at("phone").get_to(p.phone);
}
}

int main() {
    json j = json::parse(input);

    std::vector<P::Person> people;

    j.get_to(people);

    for (auto const &person : people) {
        std::cout << person << "\n";
    }
}


问:
using pandas two perform Cross tab between one column and two others that share the same enumerated values
I have table with

```<code>|Majors|First Minor|Second Minor|
|Philosophy|English|Null|
|Math|Philosophy|English|
|English|Theology|Political Science
|Philosophy|Theology|English|
</code>```

The possible values of the "First Minor" and "Second Minor" columns are the same (English, Philosophy, Math, etc)

I want to see the correlation between "Major" and the "Minors" belonging to those majors. I don't care if the minor is a first or second minor. So based on the above sample I want an output that looks something like:

```<code>|Major|Philosophy|Math|English
First Minor||||
Philosophy|0|1|0|
|Math|0|0|0|
|English|2|1|0|
Political Science|0|0|1|
Theology|1|0|1|
Null|1|0|0
</code>```

The following code generates the desired result for just the "First Minor" or the "Second Minor":

ct = pd.crosstab(newdf.MajorInterMinor, newdf["First Minor"])

But I want to get the results for both columns ("First Minor" and "Second Minor") and I can't figure out how to get the combined result.

Any help/advice is much appreciated!

答:
melt the Minors, then apply crosstab:

```<code>df2 = df.melt(id_vars='Majors', value_name='Minors')

pd.crosstab(df2['Majors'], df2['Minors'])
</code>```

Output:

```<code>Minors      English  Null  Philosophy  Political Science  Theology
Majors
English           0     0           0                  1         1
Math              1     0           1                  0         0
Philosophy        2     1           0                  0         1
</code>```

Body:
I have table with

|Majors|First Minor|Second Minor|
|Philosophy|English|Null|
|Math|Philosophy|English|
|English|Theology|Political Science
|Philosophy|Theology|English|

The possible values of the "First Minor" and "Second Minor" columns are the same (English, Philosophy, Math, etc)

I want to see the correlation between "Major" and the "Minors" belonging to those majors. I don't care if the minor is a first or second minor. So based on the above sample I want an output that looks something like:

|Major|Philosophy|Math|English
First Minor||||
Philosophy|0|1|0|
|Math|0|0|0|
|English|2|1|0|
Political Science|0|0|1|
Theology|1|0|1|
Null|1|0|0

The following code generates the desired result for just the "First Minor" or the "Second Minor":

ct = pd.crosstab(newdf.MajorInterMinor, newdf["First Minor"])

But I want to get the results for both columns ("First Minor" and "Second Minor") and I can't figure out how to get the combined result.

Any help/advice is much appreciated!

Body:
melt the Minors, then apply crosstab:

df2 = df.melt(id_vars='Majors', value_name='Minors')

pd.crosstab(df2['Majors'], df2['Minors'])

Output:

Minors      English  Null  Philosophy  Political Science  Theology
Majors
English           0     0           0                  1         1
Math              1     0           1                  0         0
Philosophy        2     1           0                  0         1


问:
Robocopy access denied, despite having Full Control?
Pretty straightforward script:

```<code>ROBOCOPY \\servername\S$\SCCM2012\SCCMPackageSource\Files C:\Files /S /COPYALL /MIR /IS /LOG:C:\Copy.log
</code>```

I can run this as administrator just fine, and all the files get copied correctly. However when I push this script to a computer as an Application via SCCM 2012 and run it, the log file gives me the following:

```<code>NOTE : NTFS Security may not be copied - Source may not be NTFS.
2016/07/27 10:05:31 ERROR 5 (0x00000005) Accessing Source Directory \\servername\S$\SCCM2012\SCCMPackageSource\Files\
Access is denied.
</code>```

Both the SYSTEM account and the SCCM Network Access Account have Full Control over that folder. The folder is not shared. Tried with the /ZB switch as well, but that didn't make any difference. Any thoughts? Thanks!

答: Add to robocopy parameter /NODCOPY - to not transfer parameters of file - it helped me.</p>

Body:
Pretty straightforward script:

ROBOCOPY \\servername\S$\SCCM2012\SCCMPackageSource\Files C:\Files /S /COPYALL /MIR /IS /LOG:C:\Copy.log

I can run this as administrator just fine, and all the files get copied correctly. However when I push this script to a computer as an Application via SCCM 2012 and run it, the log file gives me the following:

NOTE : NTFS Security may not be copied - Source may not be NTFS.
2016/07/27 10:05:31 ERROR 5 (0x00000005) Accessing Source Directory \\servername\S$\SCCM2012\SCCMPackageSource\Files\
Access is denied.

Both the SYSTEM account and the SCCM Network Access Account have Full Control over that folder. The folder is not shared. Tried with the /ZB switch as well, but that didn't make any difference. Any thoughts? Thanks!


问:
Angular reuse same lazy load module for multiple root paths
I've splitted my app into two modules: one with main basic functionality and other with less-used features like account settings, faq pages and more.

What I'm trying to accomplish is to lazy load the second module for some root route paths, like /account or /settings without having to create many different modules. As far as I know Angular lazy load only works with one root route, and the routes configured in the lazy loaded module are set as children of that route.

```<code> {
        path: 'account',
        loadChildren: './modules/settings/settings.module#SettingsModule',
 },
 {
        path: 'settings',
        loadChildren: './modules/settings/settings.module#SettingsModule',
 },
</code>```

答:
The truth is that, unless you do something dynamically loaded, like in the answer above, you cannot do this. Angular is not intended to work, out of the box, with this type of structure. This is a common problem and is already being addressed for future releases, with the use of standalone components (see https://netbasal.com/aim-to-future-proof-your-standalone-angular-components-accb574d273f)

So, for your case, I think the best approach would be break your main module into core, and shared modules, and create a separate module for each feature module (account settings, faq pages, ...).

Body:
I've splitted my app into two modules: one with main basic functionality and other with less-used features like account settings, faq pages and more.

What I'm trying to accomplish is to lazy load the second module for some root route paths, like /account or /settings without having to create many different modules. As far as I know Angular lazy load only works with one root route, and the routes configured in the lazy loaded module are set as children of that route.

 {
        path: 'account',
        loadChildren: './modules/settings/settings.module#SettingsModule',
 },
 {
        path: 'settings',
        loadChildren: './modules/settings/settings.module#SettingsModule',
 },


问:
Unable to open file
I installed php manual and tried to open it, but:

Warning: fopen(e.txt) [function.fopen]: failed to open stream: Permission denied in

答:
As Joshua 'Cuppers' Whittle answer the problem is most likely with your CHMOD permissions. However, I will post my answer in the more PHP and "dynamic" form.

Before opening the file:

```<code>if (substr(sprintf('%o', fileperms('e.txt')), -4) == 1777) {
    chmod('e.txt', 777)
}
// And now the fopen(); part of your code
</code>```

(Sadly, I cant test it myself, so this answer is theoretical only.)

Title: Unable to open file

Body:
As Joshua 'Cuppers' Whittle answer the problem is most likely with your CHMOD permissions. However, I will post my answer in the more PHP and "dynamic" form.

Before opening the file:

if (substr(sprintf('%o', fileperms('e.txt')), -4) == 1777) {
    chmod('e.txt', 777)
}
// And now the fopen(); part of your code

(Sadly, I cant test it myself, so this answer is theoretical only.)


问:
calling a double from object seems to return the possition not value of the double
In a function i have this:

val sunRise = SunEquation(2459622)
binding.timeDisplay.setText("$sunRise.n")
```
<p>The SunEquation-Class looks like this:</p>
```class SunEquation(var jDate: Int,) {

    val jYear = 2451545
    val ttOffset = .0008

    var n = jDate - jYear + ttOffset
}
```
<p>the button- text that appears is:</p>
```com.example.soluna.SunEquation@6d1a94b.n
```

i would expect a double-value

答:
You have to add curly brackets around the value you want to inject into the String, like this:

binding.timeDisplay.setText("${sunRise.n}")
```
<p>The shorthand syntax without brackets only works for a single variable, but not
for access to a nested field or other more complex expressions.</p>
<p>In your case, this results in the object itself being injected into the String, which is resembled by <code>com.example.soluna.SunEquation@6d1a94b</code> based on the result of the corresponding <code>toString()</code> call, which defaults to the class name and the reference id of the object. Followed by the literal String <code>.n</code>.</p>
<p>Alternatively, you could extract the value into a <code>val</code> beforehand and reference that.</p>
<pre class="lang-kotlin prettyprint-override"><code>val customN = sunRise.n
binding.timeDisplay.setText("$customN")
</code>```

Body:
In a function i have this:

val sunRise = SunEquation(2459622)
binding.timeDisplay.setText("$sunRise.n")

The SunEquation-Class looks like this:

class SunEquation(var jDate: Int,) {

    val jYear = 2451545
    val ttOffset = .0008

    var n = jDate - jYear + ttOffset
}

the button- text that appears is:

com.example.soluna.SunEquation@6d1a94b.n

i would expect a double-value

Body:
You have to add curly brackets around the value you want to inject into the String, like this:

binding.timeDisplay.setText("${sunRise.n}")

The shorthand syntax without brackets only works for a single variable, but not
for access to a nested field or other more complex expressions.

In your case, this results in the object itself being injected into the String, which is resembled by com.example.soluna.SunEquation@6d1a94b based on the result of the corresponding toString() call, which defaults to the class name and the reference id of the object. Followed by the literal String .n.

Alternatively, you could extract the value into a val beforehand and reference that.

val customN = sunRise.n
binding.timeDisplay.setText("$customN")


问:
WAP to find the second largest number without using an array in java
I have received a question in my school programming assignment, which goes like this:
Enter n count of numbers and find the largest and smallest among the lot. Also find the second largest number.
Now, the main problem is the second smallest number part.. We have still not been taught arrays, so I want a solution to this question without arrays. This is what I have made till now, through this code, I am able to find the largest and the smallest number correctly, but I find the second smallest number part tough!

```<code>    import java.util.*;
class SecondLargest
{
    public static void main(String args[])
    {
        System.out.println('\u000C'); //used to clear screen
        Scanner y=new Scanner(System.in);
        System.out.println("Enter the number of values to be entered");
        int n=y.nextInt();
        System.out.println("Enter number 1");
        int num=y.nextInt();
        int max=num,min=num,temp=num;
        for(int i=2;i<=n;i++)
        {
            System.out.println("Enter number "+i);
            num=y.nextInt();
            if(num>max)
            max=num;
            else if(num<min)
            min=num;

        }
        System.out.println("The largest number is "+max);
        System.out.println("The smallest number is "+min);
    }
}
</code>```

答:
Create additional variable max2 and shift previous max value when a new maximum is detected, or check if there is a value over max2:

Scanner y = new Scanner(System.in);
System.out.println("Enter the number of values to be entered");
int n = y.nextInt();

System.out.println("Enter number 1");
int num = y.nextInt();
int max = num, max2 = num, min = num;

for (int i = 2; i <= n; i++) {
    System.out.println("Enter number " + i);
    num = y.nextInt();
    if (num < min) {
        min = num;
    } else if (num > max) {
        max2 = max; // shift previous max to become the 2nd largest
        max = num;  // store max
    } else if (num > max2) {
        max2 = num;
    }
}
System.out.println("The largest number is     " + max);
System.out.println("The 2nd largest number is " + max2);
System.out.println("The smallest number is    " + min);
```

Body:
I have received a question in my school programming assignment, which goes like this:
Enter n count of numbers and find the largest and smallest among the lot. Also find the second largest number.
Now, the main problem is the second smallest number part.. We have still not been taught arrays, so I want a solution to this question without arrays. This is what I have made till now, through this code, I am able to find the largest and the smallest number correctly, but I find the second smallest number part tough!

    import java.util.*;
class SecondLargest
{
    public static void main(String args[])
    {
        System.out.println('\u000C'); //used to clear screen
        Scanner y=new Scanner(System.in);
        System.out.println("Enter the number of values to be entered");
        int n=y.nextInt();
        System.out.println("Enter number 1");
        int num=y.nextInt();
        int max=num,min=num,temp=num;
        for(int i=2;i<=n;i++)
        {
            System.out.println("Enter number "+i);
            num=y.nextInt();
            if(num>max)
            max=num;
            else if(num<min)
            min=num;

        }
        System.out.println("The largest number is "+max);
        System.out.println("The smallest number is "+min);
    }
}


问:
Check if file exists - C programming
I've had trouble trying to create this function that takes users input and checks if the file exists or not. I keep on getting warning messages (format specifies type 'char *' but the argument has type 'const char **') every time I try to run the code.

I've tried to declare the variable fileName in different ways but it still seems to not be working. So I'm curious to know if I'm using access wrong or if it's even possible to use when taking user input.

```<code>int readFunc(const char *fileName) {
    printf("Search for file: ");
    scanf("%s", &fileName);

    if(access(fileName, F_OK) == 0) {
        menuFunc();
    } else {
        printf("File doesn't exist!\n");
    }
}
</code>```

答:
If the C programming language had a string data type, the following lines of code would be correct:

```<code>string fileName;
scanf("%s", &fileName);
</code>```

However, the C programming language does not have a string data type, but strings must be stored in arrays of characters.

The char * data type does not hold a complete string, but it holds a "pointer" to an array. This means: The data type holds a reference to an array where the string is stored.

Let's say we use a self-written variant of scanf() named myScanf():

```<code>const char * fileName;
myScanf("%s", &fileName);
</code>```

In this example the function myScanf() returns a "pointer" to a string. This means: The function stores the string in some array and then returns the reference ("pointer") to that array in the variable fileName.

The problem is: Because the function scanf() does not know which array should be used to store the string, you have to provide this array.

This means: scanf() does not return a pointer to an array (unlike "&d", which returns a number), but scanf() takes a pointer to an array (to the array where you want scanf() to store the string) as input argument:

```<code>int a;
char *b;
...
scanf("%d", &a); /* a is an output from scanf() */
scanf("%s", b); /* b is an input to scanf() */
</code>```

However, the following line will also not work:

```<code>scanf("%s", fileName);
</code>```

You tell scanf() to overwrite the array that has been passed as argument to the readFunc() function; and the const specifier says, that the function readFunc() must not overwrite this array!

You have to specify your own array where the file name is stored:

```<code>char fileName2[300]; /* Maximum 300-1 characters */
...
scanf("%s", fileName2);
...
access(fileName2, F_OK);
</code>```

Note that C cannot really pass arrays to functions as arguments.

Instead, it automatically creates a "pointer" (a reference, data type char *) to the array if you write something like access(fileName2 ...).

Title: Check if file exists - C programming

Body:
I've had trouble trying to create this function that takes users input and checks if the file exists or not. I keep on getting warning messages (format specifies type 'char *' but the argument has type 'const char **') every time I try to run the code.

I've tried to declare the variable fileName in different ways but it still seems to not be working. So I'm curious to know if I'm using access wrong or if it's even possible to use when taking user input.

int readFunc(const char *fileName) {
    printf("Search for file: ");
    scanf("%s", &fileName);

    if(access(fileName, F_OK) == 0) {
        menuFunc();
    } else {
        printf("File doesn't exist!\n");
    }
}

Body:
If the C programming language had a string data type, the following lines of code would be correct:

string fileName;
scanf("%s", &fileName);

However, the C programming language does not have a string data type, but strings must be stored in arrays of characters.

The char * data type does not hold a complete string, but it holds a "pointer" to an array. This means: The data type holds a reference to an array where the string is stored.

Let's say we use a self-written variant of scanf() named myScanf():

const char * fileName;
myScanf("%s", &fileName);

In this example the function myScanf() returns a "pointer" to a string. This means: The function stores the string in some array and then returns the reference ("pointer") to that array in the variable fileName.

The problem is: Because the function scanf() does not know which array should be used to store the string, you have to provide this array.

This means: scanf() does not return a pointer to an array (unlike "&d", which returns a number), but scanf() takes a pointer to an array (to the array where you want scanf() to store the string) as input argument:

int a;
char *b;
...
scanf("%d", &a); /* a is an output from scanf() */
scanf("%s", b); /* b is an input to scanf() */

However, the following line will also not work:

scanf("%s", fileName);

You tell scanf() to overwrite the array that has been passed as argument to the readFunc() function; and the const specifier says, that the function readFunc() must not overwrite this array!

You have to specify your own array where the file name is stored:

char fileName2[300]; /* Maximum 300-1 characters */
...
scanf("%s", fileName2);
...
access(fileName2, F_OK);

Note that C cannot really pass arrays to functions as arguments.

Instead, it automatically creates a "pointer" (a reference, data type char *) to the array if you write something like access(fileName2 ...).


问:
Query to return data from SQL Server table based on date criteria
I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.

```<code>DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("@From", From.Date);
oParam[1] = new SqlParameter("@To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN @From and @To", oParam);
</code>```

If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.

But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.

How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.

Something like :

```<code>select * rows where datevalue >= date1 and datevalue <= date2
</code>```

Thank you.

答:
From.Date and To.Date gets the date portion on c# side ignoring the time portion; you need to do something similar on the database side.

Try

```<code>"SELECT * FROM tblHistory WHERE cast(Date_Requested as DATE) BETWEEN @From and @To"
</code>```

to remove the time portion.

EDIT:
      as explained in this answer, you could change @To param value to

```<code>      oParam[1] = new SqlParameter("@To", To.Date.AddDays(1));
</code>```

Body:
I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.

DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("@From", From.Date);
oParam[1] = new SqlParameter("@To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN @From and @To", oParam);

If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.

But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.

How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.

Something like :

select * rows where datevalue >= date1 and datevalue <= date2

Thank you.

Body:
From.Date and To.Date gets the date portion on c# side ignoring the time portion; you need to do something similar on the database side.

Try

"SELECT * FROM tblHistory WHERE cast(Date_Requested as DATE) BETWEEN @From and @To"

to remove the time portion.

EDIT:
      as explained in this answer, you could change @To param value to

      oParam[1] = new SqlParameter("@To", To.Date.AddDays(1));


问:
CTRL+D is not working in vs code copy similar code
Previous in I have used ctr+d for duplicating the code many times, but when I switched to desktop and installed vs code and all the necessary extensions for my react project. And now this CTRL+D keyboard shortcut is not working. Can any help me to solve this issue</p>

答: For me it was a VS Code extension causing the ctrl + ... binds not to work. It was "Vim emulation". Try isolating the issue by uninstalling the extensions until you find which one.</p>


问:
Create a plot of Actual vs Predicted response values, as a function of time, in R
I am trying to plot the actual vs predicted values of some continuous response value (on the y axis), predicted and observed from a random forest model, against the input value of time.

Ideally, the figure generated would look something like below (note- this figure was not actually generated by the dummy data provided, and I am anticipating it to have lower resolution label text and geom points when rendered with R code):

Below is a dummy data set.

```<code># Necessary packages

library('tidyverse')
library('rsample')
library('ggplot2')
library('randomForest')

# Generate the dummy data

dummy_dat <- data.frame(var1 = c(29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897),
var2 = c(3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805),
var3 = c(5, 12, 24, 27, 33, 37, 57, 62, 91, 96, 97, 101),
var4 = c(0.336, 0.345, 0.433, 0.744, 1.22, 23.8, 6.75, 7.51, 52.73, 38.82, 101.2, 102.45),
var5 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
time = c(0.0, 0.129, 0.2097, 0.8226, 1.484, 2.290, 3.0, 3.694, 4.581, 4.887, 5.790, 6.5),
response = c(0, 4.755, 6.152, 7.247, 8.621, 11.388, 14.16, 16.652, 23.897, 28.085, 34.208, 36.7))

# Split the dummy data into a train and test set for random forest

set.seed(123)
dummy_dat_split = dummy_dat %>%
  rsample::initial_split(prop = 0.8)
dummy_dat _train = training(dummy_dat_split) # pull train set
dummy_dat_test = testing(dummy_dat_split) # pull test set

</code>```

I trained and tested a random forest model on these dummy data with the following code to get the actual vs predicted response values; all of the remaining variables, including time, were the predictor values.

```<code># Train a random forest model
train_rf <- randomForest(response ~ ., data = dummy_dat_train, mtry = 1, maxnodes = 50, ntree = 50) # creates an object of randomForest.formula class

# Test the random forest model
pred_response <- predict(train_rf, newdata = dummy_dat_test[,-7]) # gives a numeric for predicted response values

</code>```

I am unsure how to generate a plot, similar to the one attached within this post. The predicted response values / numerics can be obtained from the pred_response object generated above.

I can plot a geom_point plot (with ggplot2) for the predicted and observed values, but not as a function of time.

What are the necessary steps and/or functions that I will need to use to render something equivalent to the plot above, where predicted and observed values are a response to time? Thank you in advance.

答:
You are predicting from dummy_dat_test, so you will have one prediction per row for that data frame. In your example, this data frame only has 3 rows, so it's not a very interesting plot.

The easiest way to plot the predictions is to add them as a column to your data frame:

dummy_dat_test$predict <- pred_response

ggplot(dummy_dat_test, aes(time, response)) +
  geom_point(aes(color = "Observed"), size = 4) +
  geom_line(aes(color = "Observed")) +
  geom_point(aes(y = predict, color = "Predicted"), size = 4) +
  geom_line(aes(y = predict, color = "Predicted")) +
  scale_color_manual(values = c("orange", "deepskyblue3")) +
  theme_bw()
```

You could show the predictions from your entire data set in much the same way. Here the plot is a bit more interesting:

Body:
I am trying to plot the actual vs predicted values of some continuous response value (on the y axis), predicted and observed from a random forest model, against the input value of time.

Ideally, the figure generated would look something like below (note- this figure was not actually generated by the dummy data provided, and I am anticipating it to have lower resolution label text and geom points when rendered with R code):

Below is a dummy data set.

# Necessary packages

library('tidyverse')
library('rsample')
library('ggplot2')
library('randomForest')

# Generate the dummy data

dummy_dat <- data.frame(var1 = c(29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897, 29.897),
var2 = c(3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805, 3.7805),
var3 = c(5, 12, 24, 27, 33, 37, 57, 62, 91, 96, 97, 101),
var4 = c(0.336, 0.345, 0.433, 0.744, 1.22, 23.8, 6.75, 7.51, 52.73, 38.82, 101.2, 102.45),
var5 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
time = c(0.0, 0.129, 0.2097, 0.8226, 1.484, 2.290, 3.0, 3.694, 4.581, 4.887, 5.790, 6.5),
response = c(0, 4.755, 6.152, 7.247, 8.621, 11.388, 14.16, 16.652, 23.897, 28.085, 34.208, 36.7))

# Split the dummy data into a train and test set for random forest

set.seed(123)
dummy_dat_split = dummy_dat %>%
  rsample::initial_split(prop = 0.8)
dummy_dat _train = training(dummy_dat_split) # pull train set
dummy_dat_test = testing(dummy_dat_split) # pull test set

I trained and tested a random forest model on these dummy data with the following code to get the actual vs predicted response values; all of the remaining variables, including time, were the predictor values.

# Train a random forest model
train_rf <- randomForest(response ~ ., data = dummy_dat_train, mtry = 1, maxnodes = 50, ntree = 50) # creates an object of randomForest.formula class

# Test the random forest model
pred_response <- predict(train_rf, newdata = dummy_dat_test[,-7]) # gives a numeric for predicted response values

I am unsure how to generate a plot, similar to the one attached within this post. The predicted response values / numerics can be obtained from the pred_response object generated above.

I can plot a geom_point plot (with ggplot2) for the predicted and observed values, but not as a function of time.

What are the necessary steps and/or functions that I will need to use to render something equivalent to the plot above, where predicted and observed values are a response to time? Thank you in advance.

Body:
You are predicting from dummy_dat_test, so you will have one prediction per row for that data frame. In your example, this data frame only has 3 rows, so it's not a very interesting plot.

The easiest way to plot the predictions is to add them as a column to your data frame:

dummy_dat_test$predict <- pred_response

ggplot(dummy_dat_test, aes(time, response)) +
  geom_point(aes(color = "Observed"), size = 4) +
  geom_line(aes(color = "Observed")) +
  geom_point(aes(y = predict, color = "Predicted"), size = 4) +
  geom_line(aes(y = predict, color = "Predicted")) +
  scale_color_manual(values = c("orange", "deepskyblue3")) +
  theme_bw()

You could show the predictions from your entire data set in much the same way. Here the plot is a bit more interesting:


问:
Second Subquery Inside INSERT Into saves int 0
Read it carefully, we have this query which is inserting values in the table called users. For the value member_id we are running a subquery to select from the table admin_users the id of the member. The reason why there are single quotes with +, it's because we are trying to manipulate the query. At this moment this first subquery works correctly but what happends with the second subquery?

The second subquery selects the pass from the table settings, the table settings and the value pass totally exists and there is only one record, but this second query inside the INSERT INTO is not returning nothing. When the execution of the query INSERT INTO finishs, all the values are stored correctly except notes column which finally inserts 0. I don't know why but if you delete all the ''+ it works correctly the whole sql statement but in this time we can not delete ''+ because we are altering the query. I need a solution for this issue.

```<code>INSERT INTO `users` (`username`,`password`,`number`,`member_id`,`exp_date`,`notes`) VALUES ('balvin','sjeneoeoe','3',''+(select id from `admin_users` where username = 'TEST')+'','1644622354','' + (select pass from `settings`));#;');
</code>```

Also i have tried modifying the second subquery like this but it didn't work.

```<code>'' + (select pass from `settings` LIMIT 1)
'' + (select pass from `settings` GROUP BY pass LIMIT 1)
'' + (select pass from `settings` where id = 1 LIMIT 1)
</code>```

Perhaps the error it's the datatype of the column value pass in settings or the column notes in users

```<code>CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `member_id` int(11) DEFAULT NULL,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `exp_date` int(11) DEFAULT NULL,
  `notes` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  `number` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `member_id` (`member_id`),
  KEY `exp_date` (`exp_date`),
  KEY `username` (`username`),
  KEY `password` (`password`),
) ENGINE=InnoDB AUTO_INCREMENT=1702894 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

CREATE TABLE `settings` (
  `id` int(11) NOT NULL,
  `name` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  `pass` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  ...
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
</code>```

答:
Write your insert as a select, not values.

Untested, but something like:

```<code>INSERT INTO `users` (`username`,`password`,`number`,`member_id`,`exp_date`,`notes`)
select 'balvin','sjeneoeoe','3',
  (select id from `admin_users` where username = 'TEST'),
  '1644622354',
  (select pass from `settings`);
</code>```

Note each sub-query must return a single row.

Body:
Read it carefully, we have this query which is inserting values in the table called users. For the value member_id we are running a subquery to select from the table admin_users the id of the member. The reason why there are single quotes with +, it's because we are trying to manipulate the query. At this moment this first subquery works correctly but what happends with the second subquery?

The second subquery selects the pass from the table settings, the table settings and the value pass totally exists and there is only one record, but this second query inside the INSERT INTO is not returning nothing. When the execution of the query INSERT INTO finishs, all the values are stored correctly except notes column which finally inserts 0. I don't know why but if you delete all the ''+ it works correctly the whole sql statement but in this time we can not delete ''+ because we are altering the query. I need a solution for this issue.

INSERT INTO `users` (`username`,`password`,`number`,`member_id`,`exp_date`,`notes`) VALUES ('balvin','sjeneoeoe','3',''+(select id from `admin_users` where username = 'TEST')+'','1644622354','' + (select pass from `settings`));#;');

Also i have tried modifying the second subquery like this but it didn't work.

'' + (select pass from `settings` LIMIT 1)
'' + (select pass from `settings` GROUP BY pass LIMIT 1)
'' + (select pass from `settings` where id = 1 LIMIT 1)

Perhaps the error it's the datatype of the column value pass in settings or the column notes in users

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `member_id` int(11) DEFAULT NULL,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `exp_date` int(11) DEFAULT NULL,
  `notes` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  `number` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `member_id` (`member_id`),
  KEY `exp_date` (`exp_date`),
  KEY `username` (`username`),
  KEY `password` (`password`),
) ENGINE=InnoDB AUTO_INCREMENT=1702894 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

CREATE TABLE `settings` (
  `id` int(11) NOT NULL,
  `name` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  `pass` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  ...
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Body:
Write your insert as a select, not values.

Untested, but something like:

INSERT INTO `users` (`username`,`password`,`number`,`member_id`,`exp_date`,`notes`)
select 'balvin','sjeneoeoe','3',
  (select id from `admin_users` where username = 'TEST'),
  '1644622354',
  (select pass from `settings`);

Note each sub-query must return a single row.


问:
Date field from Power automate to sharepoint list
I have set automate up to parse an email i recieve regularly. The email is system generated through third party software without an API to link directly to SharePoint.

I have used the initialise variable function to parse the HTML from the email and create a new list item.

All fields work, however the Date will not pull through and fails the flow entirely.

I get this error:

The 'inputs.parameters' of workflow operation 'Create_item' of type 'OpenApiConnection' is not valid. Error details: Input parameter 'item/DateTime' is required to be of type 'String/date'. The runtime value '"25/02/2022"' to be converted doesn't have the expected format 'String/date'.

My column settings in the List are Date & Time field with Date Only set.

答:
I hope I've understood your problem correctly but the format 25/02/2022 is not considered to be a valid ISO 8601 date.

I created a variable called Date Time String and stored your date of 25/02/2022.

To make it valid, you need to convert it and to do that, this expression should do the trick.

concat(split(variables('Date Time String'), '/')[2], '-', split(variables('Date Time String'), '/')[1], '-', split(variables('Date Time String'), '/')[0])

It essentially reverses the date into a format that SharePoint will accept.

Before

After

New List Item Result


问:
Why nested virtualization for the Android emulator is very very slow?
Nested KVM virtualization should have a small overhead, but an Android emulator inside a VM should be usable.

When I launch the Android emulator inside ubuntu 20.04 guest (on ubuntu 20.04 host), it warns me that I'm on a nested virtualization and thus it will be slow. But it's painfully low, not just slow. It takes 10 minutes to boot into Android and yes, all the systems are x86_64, even the android image.

I thought this had to do with OpenGL so I enabled OpenGL virtualization on my virt-manager and thigns are still slow.

I tried the same thing on my Ryzen 7 2700x which has 16 cores, I gave all cores to the VM and passed an AMD gpu to it, and Android emulator is also painfully slow.

Why?

答:
For KVM one likely first has to enable nested virtualization; preferably with a x86 image:

https://docs.fedoraproject.org/en-US/quick-docs/using-nested-virtualization-in-kvm/

And even then, it's probably more effective to run a QEMU and connect through IP.


问:
Trying to add Eventlistener('click ') to a button Chrome extension
Hey guys im developing a Chrome extension.
the site
https://eportal.incometax.gov.in/iec/foservices/#/login

I want to display a modal when the button is clicked
I can add a eventlistener to the button but it doesnt get triggered need help

```<code><button _ngcontent-fes-c25="" class="large-button-primary width marTop16" disabled=""><span _ngcontent-fes-c25=""> Continue <!----><!----><img _ngcontent-fes-c25="" alt="disabled next icon" class="ng-star-inserted" src="https://static.incometax.gov.in/iec/foservices/assets/buttonIcons/nextIconDisabled.svg"><!----><!----></span></button>
</code>```

enter image description here

答:
In the content.js of your Chrome Extension, you'll want to create and append your modal element to the body of the page on load. You can do that with something like:

```<code>    const modal = document.createElement('h1');
    modal.innerText = 'This is the "modal"';
    modal.style.visibility = 'hidden';
    document.body.appendChild(modal);
</code>```

Then add event listener to the button using CSS selectors and addEventListener

```<code>const button = document.querySelector('button.large-button-primary');
button.addEventListener('click', showModal);
</code>```

And a function which changes your modal's visibility once it's clicked

```<code>const showModal = () => {
   modal.style.visibility = 'visible';
};
</code>```

<button _ngcontent-fes-c25="" class="large-button-primary width marTop16">

        Continue

</button>

```

If the event listener isn't working, then that's probably because you're setting the button variable before the target button is even on screen, which means the querySelector is just returning undefined.

Body:
Hey guys im developing a Chrome extension.
the site
https://eportal.incometax.gov.in/iec/foservices/#/login

I want to display a modal when the button is clicked
I can add a eventlistener to the button but it doesnt get triggered need help

<button _ngcontent-fes-c25="" class="large-button-primary width marTop16" disabled=""> Continue </button>

enter image description here

Body:
In the content.js of your Chrome Extension, you'll want to create and append your modal element to the body of the page on load. You can do that with something like:

    const modal = document.createElement('h1');
    modal.innerText = 'This is the "modal"';
    modal.style.visibility = 'hidden';
    document.body.appendChild(modal);

Then add event listener to the button using CSS selectors and addEventListener

const button = document.querySelector('button.large-button-primary');
button.addEventListener('click', showModal);

And a function which changes your modal's visibility once it's clicked

const showModal = () => {
   modal.style.visibility = 'visible';
};

<button _ngcontent-fes-c25="" class="large-button-primary width marTop16">
    <span _ngcontent-fes-c25="">
        Continue
        <!----><!----><img
            _ngcontent-fes-c25=""
            alt="disabled next icon"
            class="ng-star-inserted"
            src="https://static.incometax.gov.in/iec/foservices/assets/buttonIcons/nextIconDisabled.svg"
        /><!----><!----></span
    >
</button>

<script>
    const button = document.querySelector('button.large-button-primary');
    const modal = document.createElement('h1');
    modal.innerText = 'This is the "modal"';
    modal.style.visibility = 'hidden';
    document.body.appendChild(modal);

    const showModal = () => {
        modal.style.visibility = 'visible';
    };

    button.addEventListener('click', showModal);
</script>

If the event listener isn't working, then that's probably because you're setting the button variable before the target button is even on screen, which means the querySelector is just returning undefined.


问:
Android Development: Line Spacing With Line Numbering
In my app I have line numbers to the left of an EditText - everything is great so far, the line numbers are perfectly aligned with the lines of the EditText.

The problem is, if the user changes the text size of the EditText the line numbers aren't aligned properly. So I've added code so when the text size of the EditText is changed, the line numbers text size is changed too; but that causes another problem: if the user picks a big text size, the line numbers hog all the space, so there's barely any room to write in the EditText.

The only solution would be to set line spacing. So I eventually came across the setLineSpacing() function, and have tried using it based off tutorials but I don't understand how it works and can't get it aligned with the EditText's lines.

Can someone help me understand how to use it, or suggest a different way of getting each line in the line numbers TextView aligned with the EditText's lines?

Sorry if this is confusing, I'm not very good at explaining things well sigh.

Thanks,
Alex.

答:
I faced a similar situation in the past, in which the EditText's size was limited. It was decided that the max font size that can be chosen should be limited to a value in which the visual appearance does not look ugly. I feel it is useless to plug cases that can occur but don't make sense. It is better to block such cases. Perhaps you can think along these lines.

HTH,

Akshay