问:
Is there a way to monitor Health Check of an application in Grafana?
I want to monitor the health check of a Java application in Grafana. (the liveness and readiness)
I used smallrye-health.
There is a way to see in Grafana if the app is healthy or not? and Ready or not?
Thanks.

Blackbox exporter can query endpoints like /health/live and /health/ready and it checks the status code, I'am not sure that it can read the json result and display it in Grafana.


来源: stackexchange

问:
Example expression with four comparison operators
I'm trying to write the simplest valid expression for the following 4 comparison operators, <, <=, >, >=. My thinking was:

```<code>(1 < 2) <= (3 > 2)
</code>```

And I've got three...What would be a simple expression with all four?

Here's an example that uses one operator twice:

```<code>(1 < 2) <= (3 > 2) >= (1 < 2)
</code>```

Or, if we allow a boolean literal:

```<code>(1 < 2) <= (3 > 2) >= true
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write the simplest valid expression for the following 4 comparison operators, <, <=, >, >=. My thinking was:

(1 < 2) <= (3 > 2)

And I've got three...What would be a simple expression with all four?

Here's an example that uses one operator twice:

(1 < 2) <= (3 > 2) >= (1 < 2)

Or, if we allow a boolean literal:

(1 < 2) <= (3 > 2) >= true


问:
Recurring EJS Error with Variable Not Defined
I've been working on this project for a few weeks now and in the last 2 weeks I've had random occurences where a variable not defined error comes up when trying to log into the app and after I submit a form within the app. However, sometimes everything works as expected! I can't figure out what causes it and how to prevent it.

Error received:

```<code>ReferenceError: /Users/carinadaidone/Desktop/Tryl/views/index.ejs:118
    116|                   </thead>
    117|                   <tbody>
 >> 118|                     <% trialList.forEach(tryls => { %>
    119|                         <tr>
    120|                             <td>
    121|                               <div class="d-flex px-2 py-1">

trialList is not defined
    at eval ("/Users/carinadaidone/Desktop/Tryl/views/index.ejs":12:8)
    at index (/Users/carinadaidone/Desktop/Tryl/node_modules/ejs/lib/ejs.js:703:17)
    at tryHandleCache (/Users/carinadaidone/Desktop/Tryl/node_modules/ejs/lib/ejs.js:274:36)
    at exports.renderFile [as engine] (/Users/carinadaidone/Desktop/Tryl/node_modules/ejs/lib/ejs.js:491:10)
    at View.render (/Users/carinadaidone/Desktop/Tryl/node_modules/express/lib/view.js:135:8)
    at tryRender (/Users/carinadaidone/Desktop/Tryl/node_modules/express/lib/application.js:657:10)
    at Function.render (/Users/carinadaidone/Desktop/Tryl/node_modules/express/lib/application.js:609:3)
    at ServerResponse.render (/Users/carinadaidone/Desktop/Tryl/node_modules/express/lib/response.js:1039:7)
    at res.render (/Users/carinadaidone/Desktop/Tryl/node_modules/express-ejs-layouts/lib/express-layouts.js:77:18)
    at /Users/carinadaidone/Desktop/Tryl/server.js:129:9

</code>```

Code where trialList is called (index.ejs):

```<code><tbody>
    <% trialList.forEach(tryls => { %>
        <tr>
            <td>
                <div class="d-flex px-2 py-1">
                    <div class="d-flex flex-column justify-content-center">
                        <h6 class="mb-0 text-xs"><%= tryls.companyname %></h6>
                    </div>
                </div>
            </td>
            <td>
                <p class="text-xs font-weight-bold mb-0" style="text-align: center;"><%= tryls.trialduration %></p>
            </td>
            <td class="align-middle text-center">
                <span class="text-secondary text-xs font-weight-normal"><%= moment(tryls.trialexpiration).format( 'L') %></span>
            </td>
            <td class="align-middle">
                <button class="btn btn-link text-info me-auto border-0" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                <i class="material-icons text-lg">edit</i>
                </button>
           </td>
       </tr>
<% }) %>
</tbody>

</code>```

server.js:

```<code>app.get("/", function(req, res) {
    Tryl.find({}, function(err, tryls) {
        res.render('index', {
          trialList: tryls,
          moment: moment
        })
    })
});

app.post("/", function(req, res) {
    let newTryl = new Tryl({
        companyname: req.body.companyname,
        trialduration: req.body.trialduration,
        trialexpiration: req.body.trialexpiration
    });
    newTryl.save();
    res.redirect('/');
});
</code>```

This specific error occured when I tried logging into the app and after hitting the log in button that directs to /index, this error came up.

Expected to happen: index.ejs displays

Body:
I've been working on this project for a few weeks now and in the last 2 weeks I've had random occurences where a variable not defined error comes up when trying to log into the app and after I submit a form within the app. However, sometimes everything works as expected! I can't figure out what causes it and how to prevent it.

Error received:

ReferenceError: /Users/carinadaidone/Desktop/Tryl/views/index.ejs:118
    116|

    117|

 >> 118|                     <% trialList.forEach(tryls => { %>
    119|

    120|
    121|

trialList is not defined
    at eval ("/Users/carinadaidone/Desktop/Tryl/views/index.ejs":12:8)
    at index (/Users/carinadaidone/Desktop/Tryl/node_modules/ejs/lib/ejs.js:703:17)
    at tryHandleCache (/Users/carinadaidone/Desktop/Tryl/node_modules/ejs/lib/ejs.js:274:36)
    at exports.renderFile [as engine] (/Users/carinadaidone/Desktop/Tryl/node_modules/ejs/lib/ejs.js:491:10)
    at View.render (/Users/carinadaidone/Desktop/Tryl/node_modules/express/lib/view.js:135:8)
    at tryRender (/Users/carinadaidone/Desktop/Tryl/node_modules/express/lib/application.js:657:10)
    at Function.render (/Users/carinadaidone/Desktop/Tryl/node_modules/express/lib/application.js:609:3)
    at ServerResponse.render (/Users/carinadaidone/Desktop/Tryl/node_modules/express/lib/response.js:1039:7)
    at res.render (/Users/carinadaidone/Desktop/Tryl/node_modules/express-ejs-layouts/lib/express-layouts.js:77:18)
    at /Users/carinadaidone/Desktop/Tryl/server.js:129:9

Code where trialList is called (index.ejs):

    <% trialList.forEach(tryls => { %>

<%= tryls.companyname %>

<%= tryls.trialduration %>

                <%= moment(tryls.trialexpiration).format( 'L') %>

                <button class="btn btn-link text-info me-auto border-0" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                edit
                </button>

<% }) %>

server.js:

app.get("/", function(req, res) {
    Tryl.find({}, function(err, tryls) {
        res.render('index', {
          trialList: tryls,
          moment: moment
        })
    })
});

app.post("/", function(req, res) {
    let newTryl = new Tryl({
        companyname: req.body.companyname,
        trialduration: req.body.trialduration,
        trialexpiration: req.body.trialexpiration
    });
    newTryl.save();
    res.redirect('/');
});

This specific error occured when I tried logging into the app and after hitting the log in button that directs to /index, this error came up.

Expected to happen: index.ejs displays


问:
Ext.Net 1.7 Get in gridpanel differrent values in comboboxes
I tried to hand over list in list and insert this in gridpanel. List value to be placed into combobox and display list value. How do how to do it?

I need to make comboboxes with different values in gridpanel


问:
Turning a Rust `String` formatted exactly like an Array into an `Array`
I am working on a small, simple interpreter for a language i'm working on and i'm using Rust.

I have managed to lex the file into a list:

{function1 ("args", "args", "args!")} into "["fn","function1",["args","args","args!"]]" works, for example (but it's a string because find+replace was used).

"["fn","function1",["args","args","args!"]]" (a string) into ["fn","function1",["args","args","args!"]] (an array) is impossible with my current skillset, which is why i've came here.

However, now that i have the String, i am stuck finding a way to parse the string into an array, which would be a lot more useful.

I have tried searching up terms such as "how to turn rust string formatted exactly like an array into an array" or "turn string with array inside it to array rust" to no relevant results.

I have tried contorting impl into various forms.

```<code>let array = string.impl(From <String>)
</code>```

Body:
I am working on a small, simple interpreter for a language i'm working on and i'm using Rust.

I have managed to lex the file into a list:

{function1 ("args", "args", "args!")} into "["fn","function1",["args","args","args!"]]" works, for example (but it's a string because find+replace was used).

"["fn","function1",["args","args","args!"]]" (a string) into ["fn","function1",["args","args","args!"]] (an array) is impossible with my current skillset, which is why i've came here.

However, now that i have the String, i am stuck finding a way to parse the string into an array, which would be a lot more useful.

I have tried searching up terms such as "how to turn rust string formatted exactly like an array into an array" or "turn string with array inside it to array rust" to no relevant results.

I have tried contorting impl into various forms.

let array = string.impl(From <String>)


问:
Cannot run pip even when I have the package installed
I'm new to OpenWrt and I'm trying to use python3-pip installed with opkg, but even though I have installed it succesfully, I can't run pip command (or any other command like python, python3 etc.)

My goal is to run

pip install --upgrade pip

```<code>root@OpenWrt:/usr/bin# opkg install python3-pip
Package python3-pip (22.2.2-1) installed in root is up to date.
</code>```
```<code>root@OpenWrt:/usr/bin# pip
-ash: pip: not found
</code>```
```<code>root@OpenWrt:/usr/bin# python3
-ash: python3: not found
</code>```
```<code>root@OpenWrt:/usr/bin# python3-pip
-ash: python3-pip: not found
</code>```

I'm using OpenWrt with
Firmware Version: OpenWrt SNAPSHOT r20027-586c2426d9 / LuCI Master git-22.167.28356-8effea5

Kernel Version: 5.10.127

Arch: MediaTek MT7688 ver:1 eco:2

Target Platform: ramips/mt76x8

Body:
I'm new to OpenWrt and I'm trying to use python3-pip installed with opkg, but even though I have installed it succesfully, I can't run pip command (or any other command like python, python3 etc.)

My goal is to run

pip install --upgrade pip

root@OpenWrt:/usr/bin# opkg install python3-pip
Package python3-pip (22.2.2-1) installed in root is up to date.

root@OpenWrt:/usr/bin# pip
-ash: pip: not found

root@OpenWrt:/usr/bin# python3
-ash: python3: not found

root@OpenWrt:/usr/bin# python3-pip
-ash: python3-pip: not found

I'm using OpenWrt with
Firmware Version: OpenWrt SNAPSHOT r20027-586c2426d9 / LuCI Master git-22.167.28356-8effea5

Kernel Version: 5.10.127

Arch: MediaTek MT7688 ver:1 eco:2

Target Platform: ramips/mt76x8


问:
Terminal Appender in Minecraft Forge
When I create a new, completely clean forge server and turn it on with my .bat file, a very strange problem arises - the console does not have different text colors (this is supported in Log4j2 Appender ), similarly, TerminalConsoleAppender, which refuses to hold text in the last line of the console, it just flies away with new information that is rendered in the console. And also there is no search for commands when pressing Tab.

Start.bat

```<code>java -Xms1G -Xmx2G
-XX:+UseG1GC
-XX:+ParallelRefProcEnabled
-XX:MaxGCPauseMillis=200
-XX:+UnlockExperimentalVMOptions
-XX:+DisableExplicitGC
-XX:+AlwaysPreTouch
-XX:G1HeapWastePercent=5
-XX:G1MixedGCCountTarget=4
-XX:G1MixedGCLiveThresholdPercent=90
-XX:G1RSetUpdatingPauseTimePercent=5
-XX:SurvivorRatio=32
-XX:+PerfDisableSharedMem
-XX:MaxTenuringThreshold=1
-XX:G1NewSizePercent=30
-XX:G1MaxNewSizePercent=40
-XX:G1HeapRegionSize=8M
-XX:G1ReservePercent=20
-XX:InitiatingHeapOccupancyPercent=15
-jar forge-1.16.5-36.2.34.jar nogui
</code>```

Tried every version higher than 1.12.2-14.23.5.2847 - not working correctly, only on a version of forge 1.12.2-14.23.5.2847 and below works correctly.At the same time, there are no such problems with bukkit or other vanilla API.

TerminalConsoleAppender

Text problem

Title: Terminal Appender in Minecraft Forge

Body:
When I create a new, completely clean forge server and turn it on with my .bat file, a very strange problem arises - the console does not have different text colors (this is supported in Log4j2 Appender ), similarly, TerminalConsoleAppender, which refuses to hold text in the last line of the console, it just flies away with new information that is rendered in the console. And also there is no search for commands when pressing Tab.

Start.bat

java -Xms1G -Xmx2G
-XX:+UseG1GC
-XX:+ParallelRefProcEnabled
-XX:MaxGCPauseMillis=200
-XX:+UnlockExperimentalVMOptions
-XX:+DisableExplicitGC
-XX:+AlwaysPreTouch
-XX:G1HeapWastePercent=5
-XX:G1MixedGCCountTarget=4
-XX:G1MixedGCLiveThresholdPercent=90
-XX:G1RSetUpdatingPauseTimePercent=5
-XX:SurvivorRatio=32
-XX:+PerfDisableSharedMem
-XX:MaxTenuringThreshold=1
-XX:G1NewSizePercent=30
-XX:G1MaxNewSizePercent=40
-XX:G1HeapRegionSize=8M
-XX:G1ReservePercent=20
-XX:InitiatingHeapOccupancyPercent=15
-jar forge-1.16.5-36.2.34.jar nogui

Tried every version higher than 1.12.2-14.23.5.2847 - not working correctly, only on a version of forge 1.12.2-14.23.5.2847 and below works correctly.At the same time, there are no such problems with bukkit or other vanilla API.

TerminalConsoleAppender

Text problem


问:
How can I change the font type to "Italic" for the Y-axis of a Heat Map? If possible only the gene + rs
##I used ggplot2
library(ggplot2)

#cardiometaboli_risk is the dataset (excel)
g1<-Cardiometabolic_risk

#This code is for the heatmap
cardiometabolic <- ggplot(mapping = aes(x = g1$`Lyfestyle Exposure`, y = g1$Details)) +
geom_tile(mapping = aes(fill = g1$p)) +
labs(y = 'Reference | Population | Gene varation', x = 'Exposure', fill = 'Pinteraction')

#This is to run the heatmap
cardiometabolic

#`your text`What I have tried does not work at all. [e.g., myheatmap](https://i.stack.imgur.com/TCJgK.png)


问:
Authentification in ASP.NET Core using existing SQL Users
i'm kind of new to asp.net core and how authentication and authorization is working.

I want a start point or an explication how i can make an authentication method to make use of the existing SQL users for the server, because it would be more integrated with the system.

I need to mention that i want to rewrite the WPF application, and it makes use of System.DirectoryEntry.

Thanks in advance.

I searched in https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-7.0&tabs=visual-studio and this is not helping me.


问:
Whitelabel Error Page There was an unexpected error (type=Not Found, status=404). SpringBoot
I'm starting spring studies, I'm following a tutorial the same way, but it returns an error:

Here's my code :

```<code>package com.example.demo;

import com.example.demo.Student.Student;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.Year;
import java.util.List;

@SpringBootApplication
@RestController
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

   @GetMapping
   public List<Student> Students(){
      return List.of(
            new Student(
                  1L,
                  "Mohamed",
                  "Mohamed@gmail.com",
                  LocalDate.of(1999, Month.MARCH, 28),
                  23
            )
      );
   }
}
</code>```

`

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

i already created the class but it doesen't show in the screen as a json and i don't know why ?

Btw i commented the JPA part in pom.xml cuz i'm not gonna use db yet

Thanks for your help!

Body:
I'm starting spring studies, I'm following a tutorial the same way, but it returns an error:

Here's my code :

package com.example.demo;

import com.example.demo.Student.Student;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.Year;
import java.util.List;

@SpringBootApplication
@RestController
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

   @GetMapping
   public List<Student> Students(){
      return List.of(
            new Student(
                  1L,
                  "Mohamed",
                  "Mohamed@gmail.com",
                  LocalDate.of(1999, Month.MARCH, 28),
                  23
            )
      );
   }
}

`

i already created the class but it doesen't show in the screen as a json and i don't know why ?

Btw i commented the JPA part in pom.xml cuz i'm not gonna use db yet

Thanks for your help!


问:
JavaScript PromiseResult Access array of objects
I have fetched an API request and now access the values in the array I'm having issues.
I see that all the objects are successful in the PromiseResult. But if I try object[0].propertyName I get it cannot be read.

Here is my full method and some stuff i tried.

```<code> methods: {
        fetchByteArray() {
            this.post = true;
            this.loading = false;
            //Docs\003
            console.log("inside FetchByteArray");
            fetch('https://localhost:5001/api/Doc/GetFolder/003')
                .then(response => {
                    console.log(response.json());
                    //console.log(JSON.stringify(response));
                    //console.log(response.body);

                    let result = Promise.resolve(response);
                    result.then(val => console.log(val));
                })

                .then(bytes => {
                    //console.log(bytes);

                    //this.byteArrays = bytes;
                    console.log(bytes.fileName);
                })
                .catch(error => console.log(error.message));

[[PromiseResult]]
:
Array(6)
0
:
{fileID: 0, fileName: 'image00.png', fileExtension: '.png', filePath: 'C:\\Users\\user1\\Documents\\zTests\\Docs\\003', byteArray: 'System.IO.MemoryStream', …}
1
:
{fileID: 1, fileName: 'image01.png', fileExtension: '.png', filePath: 'C:\\Users\\user2\\Documents\\zTests\\Docs\\003', byteArray: 'System.IO.MemoryStream', …}
</code>```

Body:
I have fetched an API request and now access the values in the array I'm having issues.
I see that all the objects are successful in the PromiseResult. But if I try object[0].propertyName I get it cannot be read.

Here is my full method and some stuff i tried.

 methods: {
        fetchByteArray() {
            this.post = true;
            this.loading = false;
            //Docs\003
            console.log("inside FetchByteArray");
            fetch('https://localhost:5001/api/Doc/GetFolder/003')
                .then(response => {
                    console.log(response.json());
                    //console.log(JSON.stringify(response));
                    //console.log(response.body);

                    let result = Promise.resolve(response);
                    result.then(val => console.log(val));
                })

                .then(bytes => {
                    //console.log(bytes);

                    //this.byteArrays = bytes;
                    console.log(bytes.fileName);
                })
                .catch(error => console.log(error.message));

[[PromiseResult]]
:
Array(6)
0
:
{fileID: 0, fileName: 'image00.png', fileExtension: '.png', filePath: 'C:\\Users\\user1\\Documents\\zTests\\Docs\\003', byteArray: 'System.IO.MemoryStream', …}
1
:
{fileID: 1, fileName: 'image01.png', fileExtension: '.png', filePath: 'C:\\Users\\user2\\Documents\\zTests\\Docs\\003', byteArray: 'System.IO.MemoryStream', …}


问:
Generating a new, more dense grids using existing and scale
I use Python for fitting various experimental data.

The data I have is stored in NumPy arrays, e.g.

```<code>x = np.array([53.821593,  53.85265044, 53.88373501, 53.91484627, 53.94598466, 53.97714997, 54.00834218, 54.03956172, 54.07080797, 54.10208155, 54.13338225, 54.16471028,
 54.19606522, 54.2274477])
</code>```

where x stands for some coordinate of experimental data.

the distance between elements of an x array varies (the grid is nonuniform and some regions along the axis have ).

I need a package or a function to create a new grid based on the initial grid but more dense and will include the coordinates of the initial grid.

```<code>def resample_grid(initial_grid: np.array, scale: float) -> np.array:
</code>```

Something that will add additional points between the given points using some provided parameter, e.g. scale so the new grid will have (x.size * scale) points (approx.), while the left and right borders of the new grid must be the same as in the initial.

It's preferable that this function/tool will not give random values, so the result of applying it to the initial array will have a steady result.

Is there any package or solution?

Edited:
To be more specific - it's required to obtain a new grid with the known number of points in the resulting array that includes old coordinates and adds new ones to obtain a "more uniform" grid, e.g. by adding points in regions where the grid is too coarse and do not touch regions where we have maximum density values. So the resulting grid will have a "more uniform" grid - to minimize the mean length of intervals in the new grid (and the variance of lengths) for resulting array in comparison with the initial grid.

```<code>def resample_grid(initial_grid: np.array, num_out_points: int) -> np.array:
</code>```

Body:
I use Python for fitting various experimental data.

The data I have is stored in NumPy arrays, e.g.

x = np.array([53.821593,  53.85265044, 53.88373501, 53.91484627, 53.94598466, 53.97714997, 54.00834218, 54.03956172, 54.07080797, 54.10208155, 54.13338225, 54.16471028,
 54.19606522, 54.2274477])

where x stands for some coordinate of experimental data.

the distance between elements of an x array varies (the grid is nonuniform and some regions along the axis have ).

I need a package or a function to create a new grid based on the initial grid but more dense and will include the coordinates of the initial grid.

def resample_grid(initial_grid: np.array, scale: float) -> np.array:

Something that will add additional points between the given points using some provided parameter, e.g. scale so the new grid will have (x.size * scale) points (approx.), while the left and right borders of the new grid must be the same as in the initial.

It's preferable that this function/tool will not give random values, so the result of applying it to the initial array will have a steady result.

Is there any package or solution?

Edited:
To be more specific - it's required to obtain a new grid with the known number of points in the resulting array that includes old coordinates and adds new ones to obtain a "more uniform" grid, e.g. by adding points in regions where the grid is too coarse and do not touch regions where we have maximum density values. So the resulting grid will have a "more uniform" grid - to minimize the mean length of intervals in the new grid (and the variance of lengths) for resulting array in comparison with the initial grid.

def resample_grid(initial_grid: np.array, num_out_points: int) -> np.array:


问:
DateTime.ParseExact converts date to 19th century
Whenever I try to do DateTime.ParseExact for MMyy for year greater than 2030 it forces to 19th century.

For e.g:

```<code>var expiry30 = DateTime.ParseExact("0430", "MMyy", System.Globalization.CultureInfo.InvariantCulture);
</code>```

This gives:  04/01/1930 00:00:00

However, a year lesser than 2030 is correct

For e.g:

```<code>var expiry29 = DateTime.ParseExact("0429", "MMyy", System.Globalization.CultureInfo.InvariantCulture);
</code>```

This gives: 04/01/2029 00:00:00

Could you please let me know if I'm missing something?

Body:
Whenever I try to do DateTime.ParseExact for MMyy for year greater than 2030 it forces to 19th century.

For e.g:

var expiry30 = DateTime.ParseExact("0430", "MMyy", System.Globalization.CultureInfo.InvariantCulture);

This gives:  04/01/1930 00:00:00

However, a year lesser than 2030 is correct

For e.g:

var expiry29 = DateTime.ParseExact("0429", "MMyy", System.Globalization.CultureInfo.InvariantCulture);

This gives: 04/01/2029 00:00:00

Could you please let me know if I'm missing something?


问:
Jenkins-GitLab integration
I can't seem to get the Jenkins-GitLab integration to work as indicated (https://about.gitlab.com/solutions/jenkins/).  If I make a change in GitLab, Jenkins does in fact kick off a build as expected (indicating that the 2 are talking to each other).  But if I try a merge request, Jenkins does not run a build, no PR shows up in Jenkins and GitLab does not indicate a passing/failing build.  GitLab acts as though it's trying to do a CI/CD build within GitLab rather than Jenkins.  Any guidance on a fix would be appreciated.

Note: I'm using multibranch pipelines in Jenkins with a Jenkinsfile in GitLab.
Note: using GitLab Community Edition

I have enabled Jenkins under the integration section in GitLab.  I would expect that a merge request would kick off a build in Jenkins and GitLab would indicate if said build passes/fails.

Title: Jenkins-GitLab integration


问:
How to select option in context menu in selenium java
I'm trying to right click and select option in Selenium Java.
That is my code:

```<code>Actions action1= new Actions(driver);

action1.moveToElement(captcha);
Thread.sleep(2000);
action1.contextClick(captcha).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).build().perform();
</code>```

The first step works by right clicking, but when trying to hit the down arrow button the page scrolls down, but I want to select the object in the context menu.

Body:
I'm trying to right click and select option in Selenium Java.
That is my code:

Actions action1= new Actions(driver);

action1.moveToElement(captcha);
Thread.sleep(2000);
action1.contextClick(captcha).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).build().perform();

The first step works by right clicking, but when trying to hit the down arrow button the page scrolls down, but I want to select the object in the context menu.


问:
install .EXE on server
I have an EXE file (wrote by C++) which receive an input file (.txt) and do process then return results in a TXT file. Now I want to write an API by NodeJS and I need to have access to this EXE file on server, open it, give it a specific input file and then send the result as response. Is it possible? and if yes how ? I read something about TSplus or remote app, but I don't think these could be useful.

I tried to find ways to install a program on the server and then be able to control that program with NodeJS.

Title: install .EXE on server


问:
tar and csv.gz files
I have problem in pre-process of game churn data. The data consist of 600 per csv file as zipped as csv.gz and all csv.gz files also zipped as .tar format. When i process the data in Python, some id's doesnt match in final data. Is there anyone suggest to process that kind of data. My code is in below</p>
```<code>my_file_list = [f for f in glob.glob("data/csv/*.csv.gz")]        # reading all .csv.gz (change path as per your directory)
appended_data = []
i = 0
for filename in my_file_list:
    headers = [*pd.read_csv(filename, nrows=1, compression='gzip', error_bad_lines=False)]
    df = pd.read_csv(filename, compression='gzip', error_bad_lines=False, usecols=[c for c in headers if c not in removable_columns])
</code>```

Title: tar and csv.gz files

Body:
I have problem in pre-process of game churn data. The data consist of 600 per csv file as zipped as csv.gz and all csv.gz files also zipped as .tar format. When i process the data in Python, some id's doesnt match in final data. Is there anyone suggest to process that kind of data. My code is in below

my_file_list = [f for f in glob.glob("data/csv/*.csv.gz")]        # reading all .csv.gz (change path as per your directory)
appended_data = []
i = 0
for filename in my_file_list:
    headers = [*pd.read_csv(filename, nrows=1, compression='gzip', error_bad_lines=False)]
    df = pd.read_csv(filename, compression='gzip', error_bad_lines=False, usecols=[c for c in headers if c not in removable_columns])


问:
Dynamic align text to the center
How i could stop the Loading text from moving to the left, but still continue aligned to the center of the button?

```<code>auto timer = new QTimer();
auto button = new QPushButton(this);

button->setGeometry(50, 50, 200, 50);
QGridLayout* layout = new QGridLayout();
button->setLayout(layout);

QLabel* label = new QLabel(button);
label->setStyleSheet("qproperty-alignment: AlignCenter;");

layout->addWidget(label);

timer->setInterval(500);
timer->start();

QObject::connect(timer, &QTimer::timeout, [=]
{
    static int dot = 0;

    dot = (dot + 1) % 4;

    QString text = "Loading...";
    text.resize(7 + dot);

    label->setText(text);
});
</code>```

Title: Dynamic align text to the center

Body:
How i could stop the Loading text from moving to the left, but still continue aligned to the center of the button?

auto timer = new QTimer();
auto button = new QPushButton(this);

button->setGeometry(50, 50, 200, 50);
QGridLayout* layout = new QGridLayout();
button->setLayout(layout);

QLabel* label = new QLabel(button);
label->setStyleSheet("qproperty-alignment: AlignCenter;");

layout->addWidget(label);

timer->setInterval(500);
timer->start();

QObject::connect(timer, &QTimer::timeout, [=]
{
    static int dot = 0;

    dot = (dot + 1) % 4;

    QString text = "Loading...";
    text.resize(7 + dot);

    label->setText(text);
});


问:
when i attempt to install wpscan i get Error: Failed to build gem native extension
when i attempt to install wpscan i get Error: Failed to build gem native extension.</p>
```<code>Temporarily enhancing PATH for MSYS/MINGW...
Building native extensions. This could take a while...
ERROR:  Error installing wpscan:
        ERROR: Failed to build gem native extension.

    current directory: C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/yajl-ruby-1.4.3/ext/yajl
C:/Ruby31-x64/bin/ruby.exe -I C:/Ruby31-x64/lib/ruby/3.1.0 extconf.rb
creating Makefile

current directory: C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/yajl-ruby-1.4.3/ext/yajl
make DESTDIR\= sitearchdir\=./.gem.20221212-20256-e7lofg sitelibdir\=./.gem.20221212-20256-e7lofg clean
current directory: C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/yajl-ruby-1.4.3/ext/yajl
make DESTDIR\= sitearchdir\=./.gem.20221212-20256-e7lofg sitelibdir\=./.gem.20221212-20256-e7lofg
make failedNo such file or directory - make

Gem files will remain installed in C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/yajl-ruby-1.4.3 for inspection.
Results logged to C:/Ruby31-x64/lib/ruby/gems/3.1.0/extensions/x64-mingw-ucrt/3.1.0/yajl-ruby-1.4.3/gem_make.out```
</code>```

Body:
when i attempt to install wpscan i get Error: Failed to build gem native extension.

Temporarily enhancing PATH for MSYS/MINGW...
Building native extensions. This could take a while...
ERROR:  Error installing wpscan:
        ERROR: Failed to build gem native extension.

    current directory: C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/yajl-ruby-1.4.3/ext/yajl
C:/Ruby31-x64/bin/ruby.exe -I C:/Ruby31-x64/lib/ruby/3.1.0 extconf.rb
creating Makefile

current directory: C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/yajl-ruby-1.4.3/ext/yajl
make DESTDIR\= sitearchdir\=./.gem.20221212-20256-e7lofg sitelibdir\=./.gem.20221212-20256-e7lofg clean
current directory: C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/yajl-ruby-1.4.3/ext/yajl
make DESTDIR\= sitearchdir\=./.gem.20221212-20256-e7lofg sitelibdir\=./.gem.20221212-20256-e7lofg
make failedNo such file or directory - make

Gem files will remain installed in C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/yajl-ruby-1.4.3 for inspection.
Results logged to C:/Ruby31-x64/lib/ruby/gems/3.1.0/extensions/x64-mingw-ucrt/3.1.0/yajl-ruby-1.4.3/gem_make.out```


问:
Obtaining the frequency content of my data
I have a time series data in a list of arrays called epoch. Here's a MWE of how it looks like:

```<code>import numpy as np
epoch = [(np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]]),
          np.array([100, 101, 102])),
         (np.array([[10, 11, 12, 13],
                    [14, 15, 16, 17],
                    [18, 19, 20, 21]]),
          np.array([103, 104, 105,106])),
         (np.array([[22, 23, 24, 25, 26],
                    [26, 27, 28, 29, 30],
                    [31, 32, 33, 34, 35]]),
          np.array([107, 108, 109, 110, 111]))
           ]
</code>```

For every i, epoch[i][0] is the data and epoch [i][1] is the time corresponding to that data. Each epoch[i][0] contains data from 3 channels, or signals from 3 different sources. I would like to get the frequency content of each channel, from every epoch.

Here's what I did:

```<code>FFT_freq = []
for i in range(len(epoch)):
    chj_fftfreq = []
    chj_fftvals = []
    for j in range(3):
        chj_fftvals.append(np.absolute(np.fft.rfft(epoch[i][0][j])))
        chj_fftfreq.append(np.fft.rfftfreq(len(epoch[i][0][j])))
    mat = np.column_stack(chj_fftfreq)
    FFT_freq.append(mat)
</code>```

However, this gives me a lot of repeated values when I apply the code to my actual data. Am I doing something wrong or the frequencies of the three channels in every epoch are the same?

Body:
I have a time series data in a list of arrays called epoch. Here's a MWE of how it looks like:

import numpy as np
epoch = [(np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]]),
          np.array([100, 101, 102])),
         (np.array([[10, 11, 12, 13],
                    [14, 15, 16, 17],
                    [18, 19, 20, 21]]),
          np.array([103, 104, 105,106])),
         (np.array([[22, 23, 24, 25, 26],
                    [26, 27, 28, 29, 30],
                    [31, 32, 33, 34, 35]]),
          np.array([107, 108, 109, 110, 111]))
           ]

For every i, epoch[i][0] is the data and epoch [i][1] is the time corresponding to that data. Each epoch[i][0] contains data from 3 channels, or signals from 3 different sources. I would like to get the frequency content of each channel, from every epoch.

Here's what I did:

FFT_freq = []
for i in range(len(epoch)):
    chj_fftfreq = []
    chj_fftvals = []
    for j in range(3):
        chj_fftvals.append(np.absolute(np.fft.rfft(epoch[i][0][j])))
        chj_fftfreq.append(np.fft.rfftfreq(len(epoch[i][0][j])))
    mat = np.column_stack(chj_fftfreq)
    FFT_freq.append(mat)

However, this gives me a lot of repeated values when I apply the code to my actual data. Am I doing something wrong or the frequencies of the three channels in every epoch are the same?


问:
How to import an .html file containing a three.js animated shape into a Vue component
I have a simple, functioning three.js animated cube object located in an src/animation/animation.html file within my Vue project. I can open this html file using Live Server in VS code and see it working. Here's the code:

// init

const camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;

const scene = new THREE.Scene();

const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();

const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animation );
document.body.appendChild( renderer.domElement );

// animation

function animation( time ) {

  mesh.rotation.x = time / 2000;
  mesh.rotation.y = time / 1000;

  renderer.render( scene, camera );

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/three@0.122.0/build/three.min.js"></script></code>```

I'd like to import this .html file into a Vue component for display, I understand that I'll probably need to install html-loader and alter some configuration stuff but unsure on the specifics. Any advise on how to proceed?

Body:
I have a simple, functioning three.js animated cube object located in an src/animation/animation.html file within my Vue project. I can open this html file using Live Server in VS code and see it working. Here's the code:

// init

const camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;

const scene = new THREE.Scene();

const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();

const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animation );
document.body.appendChild( renderer.domElement );

// animation

function animation( time ) {

  mesh.rotation.x = time / 2000;
  mesh.rotation.y = time / 1000;

  renderer.render( scene, camera );

}

I'd like to import this .html file into a Vue component for display, I understand that I'll probably need to install html-loader and alter some configuration stuff but unsure on the specifics. Any advise on how to proceed?


问:
SSH Firewall blocking blocking python module websocket client
I really need some help.

We are using an api + python websockets but the when we receive data from the api the firewall blocks the data.

Running python script with module "websocket-client" on centos7 server gets blocked by firewall or csf.

the firewall first blocked the outgoing data but it always occured on the same port so I just unblocked that port. The ingoing data always enter on different ports so I'm not able to use the same method.

Some Ideas for a solution but I don't know how/if they are possible: If there is a way to allow script to ignore the firewall when executing it, e.g. something similar to sudo. always get the in data on a specific port.

the python script works on my local windows 10 pc.

websocket module: https://pypi.org/project/websocket-client/

var/log/messages:

```<code>kernel: Firewall: *TCP_IN Blocked* IN=venet0 OUT= MAC= SRC=80.82.77.234 DST=XX.XXX.XXX.XXX LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=23663 PROTO=TCP SPT=46651 DPT=5089 WINDOW=1024 RES=0x00 SYN URGP=0
</code>```

This is the error message:

```<code>File "/usr/local/lib/python3.6/site-packages/websocket/_handshake.py", line 143, in _get_resp_headers
    raise WebSocketBadStatusException("Handshake status %d %s", status, status_message, resp_headers)
websocket._exceptions.WebSocketBadStatusException: Handshake status 451 None
</code>```

py snippet with some mixed in psudo code:

```<code>from websocket import create_connection

#set url variable
#set msg variable
ws = create_connection(url)
ws.send(msg)

while True:
  response = ws.recv()
  #do stuff
</code>```

I cant open a port in because the data always gets back in a different port
or it seems like that at least.

Body:
I really need some help.

We are using an api + python websockets but the when we receive data from the api the firewall blocks the data.

Running python script with module "websocket-client" on centos7 server gets blocked by firewall or csf.

the firewall first blocked the outgoing data but it always occured on the same port so I just unblocked that port. The ingoing data always enter on different ports so I'm not able to use the same method.

Some Ideas for a solution but I don't know how/if they are possible: If there is a way to allow script to ignore the firewall when executing it, e.g. something similar to sudo. always get the in data on a specific port.

the python script works on my local windows 10 pc.

websocket module: https://pypi.org/project/websocket-client/

var/log/messages:

kernel: Firewall: *TCP_IN Blocked* IN=venet0 OUT= MAC= SRC=80.82.77.234 DST=XX.XXX.XXX.XXX LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=23663 PROTO=TCP SPT=46651 DPT=5089 WINDOW=1024 RES=0x00 SYN URGP=0

This is the error message:

File "/usr/local/lib/python3.6/site-packages/websocket/_handshake.py", line 143, in _get_resp_headers
    raise WebSocketBadStatusException("Handshake status %d %s", status, status_message, resp_headers)
websocket._exceptions.WebSocketBadStatusException: Handshake status 451 None

py snippet with some mixed in psudo code:

from websocket import create_connection

#set url variable
#set msg variable
ws = create_connection(url)
ws.send(msg)

while True:
  response = ws.recv()
  #do stuff

I cant open a port in because the data always gets back in a different port
or it seems like that at least.


问:
How to sanely handle conditional TS class mixins
My use case is that I have 1 base class that all of these mixins will be for, and they need to be omitted or applied based on a set of object properties that corresponds to the base class

```<code>interface Thing {
  hasColour: boolean,
  hasShape: boolean,
  hasSmell: boolean
}

class ThingBase {
  constructor(thing: Thing) {}
}

function Colourable(Base: ThingBase) {
  return class Colourable extends Base {
    constructor(thing: Thing) {}

    getColour(): string {}
  }
}

function Shapeable(Base: ThingBase) {
  return class Shapeable extends Base {
    constructor(thing: Thing) {}

    getShape(): string {}
  }
}

function Smellable(Base: ThingBase) {
  return class Smellable extends Base {
    constructor(thing: Thing) {}

    getSmell(): string {}
  }
}
</code>```

So I've got this working but the problem is that there's 8 combinations of these mixins right? And if I add a new one there's 16 etc. So I need to create these classes dynamically at the time of instantiation? I can use something like what the TS docs link to is doing:

```<code>let mix = (superclass) => new MixinBuilder(superclass);

class MixinBuilder {
  constructor(superclass) {
    this.superclass = superclass;
  }

  with(...mixins) {
    return mixins.reduce((c, mixin) => mixin(c), this.superclass);
  }
}
</code>```

But then how do I do instanceof elsewhere in the code? Do I rebuild the dynamic class every time I want to check the instance type?

```<code>const mixins: ((base: ThingBase) => ThingBase)[] = []
const thing = {
  hasColour: true,
  hasShape: true,
  hasSmell: true,
}

thing.hasColour && mixins.push(Colourable);
thing.hasShape && mixins.push(Shapeable);
thing.hasSmell && mixins.push(Smellable);

const ThingClass = mix(ThingBase).with(...mixins)
const thingClassInstance = new ThingClass(thing);

console.log(thingClassInstance instanceof ???)
</code>```

This is a very contrived example since I need to do these checks across the system and not just in the same scope. Is there a better way to build these classes/refer back to what I created? Should I just keep an exponentially growing library of them pre-built so that I can always statically check the instance type?

Edit: I've made a codesandbox repro

Body:
My use case is that I have 1 base class that all of these mixins will be for, and they need to be omitted or applied based on a set of object properties that corresponds to the base class

interface Thing {
  hasColour: boolean,
  hasShape: boolean,
  hasSmell: boolean
}

class ThingBase {
  constructor(thing: Thing) {}
}

function Colourable(Base: ThingBase) {
  return class Colourable extends Base {
    constructor(thing: Thing) {}

    getColour(): string {}
  }
}

function Shapeable(Base: ThingBase) {
  return class Shapeable extends Base {
    constructor(thing: Thing) {}

    getShape(): string {}
  }
}

function Smellable(Base: ThingBase) {
  return class Smellable extends Base {
    constructor(thing: Thing) {}

    getSmell(): string {}
  }
}

So I've got this working but the problem is that there's 8 combinations of these mixins right? And if I add a new one there's 16 etc. So I need to create these classes dynamically at the time of instantiation? I can use something like what the TS docs link to is doing:

let mix = (superclass) => new MixinBuilder(superclass);

class MixinBuilder {
  constructor(superclass) {
    this.superclass = superclass;
  }

  with(...mixins) {
    return mixins.reduce((c, mixin) => mixin(c), this.superclass);
  }
}

But then how do I do instanceof elsewhere in the code? Do I rebuild the dynamic class every time I want to check the instance type?

const mixins: ((base: ThingBase) => ThingBase)[] = []
const thing = {
  hasColour: true,
  hasShape: true,
  hasSmell: true,
}

thing.hasColour && mixins.push(Colourable);
thing.hasShape && mixins.push(Shapeable);
thing.hasSmell && mixins.push(Smellable);

const ThingClass = mix(ThingBase).with(...mixins)
const thingClassInstance = new ThingClass(thing);

console.log(thingClassInstance instanceof ???)

This is a very contrived example since I need to do these checks across the system and not just in the same scope. Is there a better way to build these classes/refer back to what I created? Should I just keep an exponentially growing library of them pre-built so that I can always statically check the instance type?

Edit: I've made a codesandbox repro


问:
Updating clientStates in cloudidentity api failing
Following the guide in Google's documentation I am attempting to update fields for a device. This returns Permission denied. Did you provide the correct client id? which I have verified is absolutely the correct id.

If I log the error.msg I get HTTP Error 400: Bad Request, and looking at the contents I see that

```<code><p>The requested URL <code>/v1/devices/abc123/deviceUsers/abc-123-ddd/clientState/companyid-string?updateMask=healthScore</code> was not found on this server.  <ins>That\xe2\x80\x99s all we know.
</code>```

I took the resource name from using the list method, as suggested by the docs, so I am fairly certain this is the correct name. I don't believe its a scope permission error as the scope listed works to list/get devices.

I have tried updating different fields, different devices, and switching it up as much as I could think to do and still run into a 400. If anyone has updated any of the clientState fields and can provide guidance I would greatly appreciate it.

Body:
Following the guide in Google's documentation I am attempting to update fields for a device. This returns Permission denied. Did you provide the correct client id? which I have verified is absolutely the correct id.

If I log the error.msg I get HTTP Error 400: Bad Request, and looking at the contents I see that

The requested URL /v1/devices/abc123/deviceUsers/abc-123-ddd/clientState/companyid-string?updateMask=healthScore was not found on this server.  That\xe2\x80\x99s all we know.

I took the resource name from using the list method, as suggested by the docs, so I am fairly certain this is the correct name. I don't believe its a scope permission error as the scope listed works to list/get devices.

I have tried updating different fields, different devices, and switching it up as much as I could think to do and still run into a 400. If anyone has updated any of the clientState fields and can provide guidance I would greatly appreciate it.


问:
KeyError when selecting column after reset_index(drop=True) in Python / Pandas
I'm doing some pivot / melt processes to a df using python / pandas.  First I pivot wide and assign 4 fields as indices:

```<code>df1_wide = df1_long.pivot(index=id_cols2,columns='Subgroup',values="Students")
</code>```

id_cols2 has the names of the columns I don't want to pivot wide. Then I reset_index() to work on the wide data:

```<code>df2 = df1_wide.reset_index()
</code>```

I apply a function fn to that (Disc_Type is one of the fields in id_cols2 and 'All Subgroups' is one of the categories that pivoted wide):

```<code>df2[(df2['Disc_Type'] != 'All_Disc') & (df2['All Subgroups'] < 6)].apply(fn, axis=1)
</code>```

The function works fine.  However, as a next step when I try to melt, it includes the index column in the pivot:

```<code>df2_long = pd.melt(df2,id_vars=id_cols2,var_name='Subgroup',value_name='Students')
</code>```

So in the "Subgroup" row, it'll have values for "index" and then will list the index number under 'Students'. My first solution was to simply drop the index in the earlier step:

```<code>df2 = df1_wide.reset_index(drop=True)
</code>```

But then I get a KeyError when I try to reference Disc_Type in the filtering for the function call. I thought reset with drop=True still undoes the existing index/indices, but I guess not?  Any way I should be doing this instead? I'm not sure I'm handing the pivot/melt sequence entirely right.

Body:
I'm doing some pivot / melt processes to a df using python / pandas.  First I pivot wide and assign 4 fields as indices:

df1_wide = df1_long.pivot(index=id_cols2,columns='Subgroup',values="Students")

id_cols2 has the names of the columns I don't want to pivot wide. Then I reset_index() to work on the wide data:

df2 = df1_wide.reset_index()

I apply a function fn to that (Disc_Type is one of the fields in id_cols2 and 'All Subgroups' is one of the categories that pivoted wide):

df2[(df2['Disc_Type'] != 'All_Disc') & (df2['All Subgroups'] < 6)].apply(fn, axis=1)

The function works fine.  However, as a next step when I try to melt, it includes the index column in the pivot:

df2_long = pd.melt(df2,id_vars=id_cols2,var_name='Subgroup',value_name='Students')

So in the "Subgroup" row, it'll have values for "index" and then will list the index number under 'Students'. My first solution was to simply drop the index in the earlier step:

df2 = df1_wide.reset_index(drop=True)

But then I get a KeyError when I try to reference Disc_Type in the filtering for the function call. I thought reset with drop=True still undoes the existing index/indices, but I guess not?  Any way I should be doing this instead? I'm not sure I'm handing the pivot/melt sequence entirely right.


问:
How can I generate a Select prompt with dialoguer from an enum?
I have the following code that prompts for a color:

enum Color {
  Red,
  Yellow,
  Green,
  Blue
}

let color_response: usize = Select::with_theme(&ColorfulTheme::default())
  .with_prompt("Color")
  .default(0)
  .items(/* this takes a slice with strings. what should i put here? */)
  .interact()
  .unwrap();

let color: Color = // what to put here? should I use a match statement
```

I am unsure how to properly generate the enum names and index the enum to get the name from it. How can I accomplish this?

Body:
I have the following code that prompts for a color:

enum Color {
  Red,
  Yellow,
  Green,
  Blue
}

let color_response: usize = Select::with_theme(&ColorfulTheme::default())
  .with_prompt("Color")
  .default(0)
  .items(/* this takes a slice with strings. what should i put here? */)
  .interact()
  .unwrap();

let color: Color = // what to put here? should I use a match statement

I am unsure how to properly generate the enum names and index the enum to get the name from it. How can I accomplish this?


问:
How to open a file's folder? C#
Im working in c# winforms, and my plan is to have a button which opens explorer, and shows the data.txt files im working with in my program. I havent really found anything, or any commands. I would appreciate some help :)

```<code>FileStream f = new FileStream("data.txt", FileMode.Open);
            if (File.Exists("path"))
            {
                Process.Start(new ProcessStartInfo("explorer.exe", " /select, " + path/data.txt");
            }
            f.Close();
</code>```

im kinda new to c#, so if i made some mistakes please correct me :d
thanks in advance<3

Title: How to open a file's folder? C#

Body:
Im working in c# winforms, and my plan is to have a button which opens explorer, and shows the data.txt files im working with in my program. I havent really found anything, or any commands. I would appreciate some help :)

FileStream f = new FileStream("data.txt", FileMode.Open);
            if (File.Exists("path"))
            {
                Process.Start(new ProcessStartInfo("explorer.exe", " /select, " + path/data.txt");
            }
            f.Close();

im kinda new to c#, so if i made some mistakes please correct me :d
thanks in advance<3


问:
Unrecognized option access_token under security.firewalls.main
I've switched recently to Symfony 6.2 and want to use the newly introduces AccessTokenHandler for Bearer Authentication.

So all the cache is cleared after updating and I'm following the guide at https://symfony.com/doc/current/security/access_token.html.

This is part of my security.yaml:

```<code>security:
       firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            access_token:
                token_handler: App\Security\AccessTokenHandler
                token_extractors: header
            lazy: true
            provider: app_user_provider
            form_login:
                login_path: app_login
                check_path: app_login
            logout:
                path: app_logout
</code>```

But when I make some requests to my page, it says

Unrecognized option "access_token" under "security.firewalls.main".
Available options are "access_denied_handler", "access_denied_url",
"context", "custom_authenticators", "entry_point", "form_login",
"form_login_ldap", "host", "http_basic", "http_basic_ldap",
"json_login", "json_login_ldap", "lazy", "login_link",
"login_throttling", "logout", "methods", "pattern", "provider",
"remember_me", "remote_user", "request_matcher", "required_badges",
"security", "stateless", "switch_user", "user_checker", "x509".

So this looks like the changes to symfony 6.2 are not working. Or am I missing something?

Body:
I've switched recently to Symfony 6.2 and want to use the newly introduces AccessTokenHandler for Bearer Authentication.

So all the cache is cleared after updating and I'm following the guide at https://symfony.com/doc/current/security/access_token.html.

This is part of my security.yaml:

security:
       firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            access_token:
                token_handler: App\Security\AccessTokenHandler
                token_extractors: header
            lazy: true
            provider: app_user_provider
            form_login:
                login_path: app_login
                check_path: app_login
            logout:
                path: app_logout

But when I make some requests to my page, it says

Unrecognized option "access_token" under "security.firewalls.main".
Available options are "access_denied_handler", "access_denied_url",
"context", "custom_authenticators", "entry_point", "form_login",
"form_login_ldap", "host", "http_basic", "http_basic_ldap",
"json_login", "json_login_ldap", "lazy", "login_link",
"login_throttling", "logout", "methods", "pattern", "provider",
"remember_me", "remote_user", "request_matcher", "required_badges",
"security", "stateless", "switch_user", "user_checker", "x509".

So this looks like the changes to symfony 6.2 are not working. Or am I missing something?


问:
Not giving same results with dimensions and metrics from front end to API
I was able to do the following request: { "dimensions":[ { "name":"date" } { "name":"deviceCategory" } { "name":"eventName" } { "name":"customEvent:from_marketplace" } ] "metrics":[ { "name":"eventCount" } { "name":"eventCountPerUser" } ] "dateRanges":[ { "startDate":"2022-11-01" "endDate":"2022-12-12" } ] "dimensionFilter":{ "filter":{ "stringFilter":{ "matchType":"EXACT" "value":"send_offer" } "fieldName":"eventName" } } "offset":"0" "keepEmptyRows":true } when pulling data for dates before Nov 1, i get data for the event, but after Nov1, I dont get any data. If i remove the customEvent:from_marketplace and then i get data.

I usually minimized the # of dimensions in a call, but don't understand why the front end with the same dimensions and metrics provide data.


问:
Why doesn't this zsh script run?
I have a script:

for k in $(git branch -r --merged master| egrep -v "^(  origin\/master|  origin\/dev|  origin\/HEAD)"); do do
  if [ -z "$(git log -1 --before='2022-11-01 00:00' -s $k)" ]; then
    echo "$k"
  fi
done
```
<p>This gives me a <code>fatal: unrecognized argument</code> error when run in MacOS terminal. However this runs perfectly fine:</p>
<pre class="lang-bash prettyprint-override"><code>for k in $(git branch -r --merged | sed /\*/d); do
  if [ -z "$(git log -1 --since='2022-11-01 00:00' -s $k)" ]; then
    echo "$k"
  fi
done
</code>```

The git book clearly states that both are supported:

https://git-scm.com/docs/git-log

What goes wrong?

Title: Why doesn't this zsh script run?

Body:
I have a script:

for k in $(git branch -r --merged master| egrep -v "^(  origin\/master|  origin\/dev|  origin\/HEAD)"); do do
  if [ -z "$(git log -1 --before='2022-11-01 00:00' -s $k)" ]; then
    echo "$k"
  fi
done

This gives me a fatal: unrecognized argument error when run in MacOS terminal. However this runs perfectly fine:

for k in $(git branch -r --merged | sed /\*/d); do
  if [ -z "$(git log -1 --since='2022-11-01 00:00' -s $k)" ]; then
    echo "$k"
  fi
done

The git book clearly states that both are supported:

https://git-scm.com/docs/git-log

What goes wrong?


问:
Python : Iterating over a list of dictionaries gives key error even though the key exists
I have a list l1 and list of dictionaries l2. The keys of the dictionaries in l2 are part of the list l1, so they basically look like this

```<code>l1 =[1,2,3,4]
l2 =[{'1':1234},{'2':2345},{'3':4567},{'4':8976}]
</code>```

I need to get the get the values for the keys present in l1

I am using the below snippet the code

```<code>for i, j in zip(l1, l2):
    x = j[i]
</code>```

But it gives me the error that key is not present
KeyError: 1

Can someone please suggest what am I doing wrong here?

Body:
I have a list l1 and list of dictionaries l2. The keys of the dictionaries in l2 are part of the list l1, so they basically look like this

l1 =[1,2,3,4]
l2 =[{'1':1234},{'2':2345},{'3':4567},{'4':8976}]

I need to get the get the values for the keys present in l1

I am using the below snippet the code

for i, j in zip(l1, l2):
    x = j[i]

But it gives me the error that key is not present
KeyError: 1

Can someone please suggest what am I doing wrong here?


问:
Why is my getUserPrincipal() not a instanceof KeycloakPrincipal?
I'm working at a project that uses keycloak and quarkus. `For this project I would need the ID of a logged in user. To retrieve the ID I used the code below.

The problem with this is that principal is not a instace of keycloak, why is this?
Do i need set a specific setting for this? So yea can someone point me in the right direction.

```<code>@Path("/api/users")
public class UserResource {

    private static final Logger logger = Logger.getLogger(UserResource.class);

    @Inject
    SecurityIdentity identity;

    @Context
    SecurityContext sc;

    @GET
    @Path("/me")
    @NoCache
    public String me() {

        String userName = sc.getUserPrincipal().getName();
        logger.info(userName);
        if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
        KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>)  sc.getUserPrincipal();

            logger.info("pricipal is keycloak principal");

            userName = kp.getKeycloakSecurityContext().getToken().getSubject();
        }
        return userName;
    }
}
</code>```

This is the payload of the token.

```<code>{
    "exp": 1670882964,
    "iat": 1670882664,
    "auth_time": 1670882663,
    "jti": "1f7bcd19-2641-456f-a77c-05150cffef71",
    "iss": "http://localhost:8180/realms/quarkus",
    "sub": "b79a8a40-1cbc-48a5-82b0-fadd9e25fb8d",
    "typ": "Bearer",
    "azp": "quarkus-app",
    "nonce": "nHaSpEC",
    "session_state": "5dbab352-b6be-4403-ab6e-0bd2d43a7425",
    "acr": "1",
    "scope": "openid microprofile-jwt address profile",
    "sid": "5dbab352-b6be-4403-ab6e-0bd2d43a7425",
    "upn": "bob",
    "address": {},
    "groups": [
        "user"
    ],
    "preferred_username": "bob"
}
</code>```

Body:
I'm working at a project that uses keycloak and quarkus. `For this project I would need the ID of a logged in user. To retrieve the ID I used the code below.

The problem with this is that principal is not a instace of keycloak, why is this?
Do i need set a specific setting for this? So yea can someone point me in the right direction.

@Path("/api/users")
public class UserResource {

    private static final Logger logger = Logger.getLogger(UserResource.class);

    @Inject
    SecurityIdentity identity;

    @Context
    SecurityContext sc;

    @GET
    @Path("/me")
    @NoCache
    public String me() {

        String userName = sc.getUserPrincipal().getName();
        logger.info(userName);
        if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
        KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>)  sc.getUserPrincipal();

            logger.info("pricipal is keycloak principal");

            userName = kp.getKeycloakSecurityContext().getToken().getSubject();
        }
        return userName;
    }
}

This is the payload of the token.

{
    "exp": 1670882964,
    "iat": 1670882664,
    "auth_time": 1670882663,
    "jti": "1f7bcd19-2641-456f-a77c-05150cffef71",
    "iss": "http://localhost:8180/realms/quarkus",
    "sub": "b79a8a40-1cbc-48a5-82b0-fadd9e25fb8d",
    "typ": "Bearer",
    "azp": "quarkus-app",
    "nonce": "nHaSpEC",
    "session_state": "5dbab352-b6be-4403-ab6e-0bd2d43a7425",
    "acr": "1",
    "scope": "openid microprofile-jwt address profile",
    "sid": "5dbab352-b6be-4403-ab6e-0bd2d43a7425",
    "upn": "bob",
    "address": {},
    "groups": [
        "user"
    ],
    "preferred_username": "bob"
}


问:
Keep getting error "Unable to implement Repository method: RepoClass.updateAll(Iterable arg0). No possible implementations found."
Using Micronaut data v3, I created the following simple classes:
MyEntity.java

```<code>package test;
import io.micronaut.data.annotation.GeneratedValue;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;

@MappedEntity
public class MyEntity {
    @id
    @GeneratedValue(GeneratedValue.Type.AUTO)
    Long id;

    String name;
}
</code>```

MyRepo.java:

```<code>package test;
import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.CrudRepository;

@JdbcRepository(dialect = Dialect.MYSQL)
public interface MyRepo extends CrudRepository<MyEntity, Long> {
}
</code>```

The project can build without above 2 classes. Once I add these 2 classes, I got the error
java: Unable to implement Repository method: MyRepo.updateAll(Iterable arg0). No possible implementations found.

Body:
Using Micronaut data v3, I created the following simple classes:
MyEntity.java

package test;
import io.micronaut.data.annotation.GeneratedValue;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;

@MappedEntity
public class MyEntity {
    @id
    @GeneratedValue(GeneratedValue.Type.AUTO)
    Long id;

    String name;
}

MyRepo.java:

package test;
import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.CrudRepository;

@JdbcRepository(dialect = Dialect.MYSQL)
public interface MyRepo extends CrudRepository<MyEntity, Long> {
}

The project can build without above 2 classes. Once I add these 2 classes, I got the error
java: Unable to implement Repository method: MyRepo.updateAll(Iterable arg0). No possible implementations found.


问:
Deploy an Angular app configured with a proxy on AWS CloudFront and S3 bucket
I want to deploy an Angular app on Amazon CloudFront. I have also configured a proxy in this Angular app in order to redirect different requests to different microservices. The proxy can be seen below that has been configured in the Angular App.

```<code>module.exports = [

  {
    context: function (pathname, _request) {
      return pathname.match('/api/[^/]+/storefiles');
    },
    target: 'http://localhost:8900',
    secure: false,
    logLevel: 'info',
    changeOrigin: true,
  },
  {
    context: function (pathname, _request) {
      return pathname.match('/api/[^/]+/triggermljob');
    },
    target: 'http://localhost:8500',
    secure: false,
    logLevel: 'info',
    changeOrigin: true,
  },
  {
    context: '/api',
    target: 'http://localhost:8080',
    secure: true,
    logLevel: 'info',
    changeOrigin: true,
  }
];

</code>```

Now my question is that how I can configure this proxy in AWS? When I use ng build command, this command only builds the project. The proxy is not included in the assembled project. I can deploy the build from the dist folder in the S3 bucket and then I know how to configure Amazon CloudFront but I am confused that how I can configure or include this proxy in AWS that I use to send requests of my Angular app to different microservices. Will I have to configure any additional resource in AWS? Kindly guide me in this regard?

Body:
I want to deploy an Angular app on Amazon CloudFront. I have also configured a proxy in this Angular app in order to redirect different requests to different microservices. The proxy can be seen below that has been configured in the Angular App.

module.exports = [

  {
    context: function (pathname, _request) {
      return pathname.match('/api/[^/]+/storefiles');
    },
    target: 'http://localhost:8900',
    secure: false,
    logLevel: 'info',
    changeOrigin: true,
  },
  {
    context: function (pathname, _request) {
      return pathname.match('/api/[^/]+/triggermljob');
    },
    target: 'http://localhost:8500',
    secure: false,
    logLevel: 'info',
    changeOrigin: true,
  },
  {
    context: '/api',
    target: 'http://localhost:8080',
    secure: true,
    logLevel: 'info',
    changeOrigin: true,
  }
];

Now my question is that how I can configure this proxy in AWS? When I use ng build command, this command only builds the project. The proxy is not included in the assembled project. I can deploy the build from the dist folder in the S3 bucket and then I know how to configure Amazon CloudFront but I am confused that how I can configure or include this proxy in AWS that I use to send requests of my Angular app to different microservices. Will I have to configure any additional resource in AWS? Kindly guide me in this regard?


问:
How to structure API call architecture for getting a list of objects sorted by day for a given week?
I have Postgres backend and I need to display items sorted into buckets by the day they are associated with for an entire week.

When structurng the RestAPI I see two options.

Create a monolithic api call that returns a list of lists that corresponds to every item for every day.

Create modular api calls that returns smaller requirements and compose for the larger requirements from the smaller api calls.

Create a getDay api endpoint that gets the day.

Create a getWeek api endpoint that gets the week via calling getDay 7 times.

Lets put up some reasonable constraints like the physical processing of the data is relatively small and each day will have at most 10-15 items.

I am fairly certain that the monolithic approach will be faster and require less server bandwith but are those things I should care about given the use case?


问:
How to repeatedly prompt for user input until it meets some criteria?
I am creating a collector in discord.js version 13.6.0. At this point, my code is working fine, as far as what I want to have. What I don't know is how to query the user and get this information from them to tag roles. This is difficult for me because if I just add another variable and a condition to check if it's a role, it just kind of makes everything work twice and suddenly the collector stops. I would like everything to work in sequence and not stop when there is an error just to have the collector repeat so many times until someone gives a good value.

const collector = await mainMessage.channel.createMessageCollector({ filter: filter, max: 2, time: 900000 });

collector.on("collect", (message) => {
    const priceItem = message.content;
    if (isNaN(parseFloat(priceItem))) return message.channel.send(`To nie liczba`);

    collector.stop();

    mainMessage.edit({
        content: `Nazwa: ${itemName}\nPieniadze: ${priceItem}.`,
    });
});

collector.on("end", () => {
    return message.channel.send(`123 123`);
});
```


问:
How to set the default function for @PrimaryGeneratedColumn when I set the entity with TypeORM
I'm planning to upgrade my Postgres database from v10 to v13, since the uuid-ossp module is no longer under maintenance for Postgres v13, so I'm trying to update the default uuid generation function from uuid_generate_v4() to gen_random_uuid()

The entity I had before was:

@PrimaryGeneratedColumn('uuid')
id: string;

Since the @PrimaryGeneratedColumn('uuid') is default to use uuid_generate_v4(), and I want to update the default function to gen_random_uuid(), however it doesn't support this kind of customization according to their official doc.

any help please?


问:
Deploy Rails program to Heroku under Fedora 15
```<code>[root@chris-notebook helloworld]# heroku create helloworld --stack cedar
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': no such file to load -- readline (LoadError)
    from /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/lib/heroku/command/run.rb:1:in `<top (required)>'
    from /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/lib/heroku/command.rb:17:in `block in load'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/lib/heroku/command.rb:16:in `each'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/lib/heroku/command.rb:16:in `load'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/bin/heroku:13:in `<top (required)>'
    from /usr/local/bin/heroku:19:in `load'
    from /usr/local/bin/heroku:19:in `<main>'
</code>```

When I try to create that, every time I got same error.
What should I do? I saw similar problems but under Ubuntu. They solve it by going some place ...src/ruby../ext/readline and then execute

```<code>ruby extconf.rb
make
make install
</code>```

but I don't see that folder in file system. Why is it all so difficult?

Update

Solved by installing next packages

```<code>readline-devel.i686
readline-static.i686
</code>```

And then making similar operations in the folder ext/readline that placed in downloaded sources of ruby.

ContentLicense: CC BY-SA 3.0

Body:
[root@chris-notebook helloworld]# heroku create helloworld --stack cedar
/usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': no such file to load -- readline (LoadError)
    from /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/lib/heroku/command/run.rb:1:in `<top (required)>'
    from /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/lib/heroku/command.rb:17:in `block in load'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/lib/heroku/command.rb:16:in `each'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/lib/heroku/command.rb:16:in `load'
    from /usr/local/lib/ruby/gems/1.9.1/gems/heroku-2.8.0/bin/heroku:13:in `<top (required)>'
    from /usr/local/bin/heroku:19:in `load'
    from /usr/local/bin/heroku:19:in `'

When I try to create that, every time I got same error.
What should I do? I saw similar problems but under Ubuntu. They solve it by going some place ...src/ruby../ext/readline and then execute

ruby extconf.rb
make
make install

but I don't see that folder in file system. Why is it all so difficult?

Update

Solved by installing next packages

readline-devel.i686
readline-static.i686

And then making similar operations in the folder ext/readline that placed in downloaded sources of ruby.


问:
Hold reference to Numpy array inside C++ object
I want to create C++ wrapper for Numpy array. For that purpose I need to hold reference to Numpy array (for returning it to Python later) and reference to raw data of that array.

For that I've wrote the code:

C++

// mynumpy.h

#include <boost/python.hpp>
#include <boost/python/numpy.hpp>

namespace py = boost::python;
namespace np = boost::python::numpy;

class MyNumpy
    {
    private:
        np::ndarray* _pydata;
        unsigned char* _data;
    public:
        MyNumpy(np::ndarray& pydata);
        np::ndarray const& numpy();
    };
```
<pre class="lang-cpp prettyprint-override"><code>// mynumpy.cpp
#include "mynumpy.h"

namespace py = boost::python;
namespace np = boost::python::numpy;

MyNumpy::MyNumpy(np::ndarray& pydata)
    {
        _pydata = &pydata;
        _data = reinterpret_cast<unsigned char*>(pydata.get_data());
    }

    np::ndarray const& MyNumpy::numpy()
    {
        return *_pydata;
    }

BOOST_PYTHON_MODULE(test)
{
    Py_Initialize();
    np::initialize();

    py::class_<MyNumpy>("MyNumpy", py::init<np::ndarray&>())
        .def("numpy", &MyNumpy::numpy, py::return_value_policy<py::copy_const_reference>());
}
</code>```

Python

import numpy as np
import test

data = np.array([0])
mynp = test.MyNumpy(data)
print(mynp.numpy())
```

But the following Python code seems to crash silently when trying to call mynp.numpy(). I've noticed that after calling the constructor, _pydata points to empty Python object. I'm not sure how am I supposed to hold those references.

Body:
I want to create C++ wrapper for Numpy array. For that purpose I need to hold reference to Numpy array (for returning it to Python later) and reference to raw data of that array.

For that I've wrote the code:

C++

// mynumpy.h

#include <boost/python.hpp>
#include <boost/python/numpy.hpp>

namespace py = boost::python;
namespace np = boost::python::numpy;

class MyNumpy
    {
    private:
        np::ndarray* _pydata;
        unsigned char* _data;
    public:
        MyNumpy(np::ndarray& pydata);
        np::ndarray const& numpy();
    };

// mynumpy.cpp
#include "mynumpy.h"

namespace py = boost::python;
namespace np = boost::python::numpy;

MyNumpy::MyNumpy(np::ndarray& pydata)
    {
        _pydata = &pydata;
        _data = reinterpret_cast<unsigned char*>(pydata.get_data());
    }

    np::ndarray const& MyNumpy::numpy()
    {
        return *_pydata;
    }

BOOST_PYTHON_MODULE(test)
{
    Py_Initialize();
    np::initialize();

    py::class_<MyNumpy>("MyNumpy", py::init<np::ndarray&>())
        .def("numpy", &MyNumpy::numpy, py::return_value_policy<py::copy_const_reference>());
}

Python

import numpy as np
import test

data = np.array([0])
mynp = test.MyNumpy(data)
print(mynp.numpy())

But the following Python code seems to crash silently when trying to call mynp.numpy(). I've noticed that after calling the constructor, _pydata points to empty Python object. I'm not sure how am I supposed to hold those references.


问:
Node simple cluster but workers have different ports
I'm trying to implement the following:

server listens 5000 port and when receives requests - sends them to cluster workers

several cluster workers run on 5001, 5002, ... ports, proceed requests and send responses to the client

worker should work with the same instance of in-memory-db (array postsDB)

so if first worker receives POST request and second worker receives GET request - they change data in the same array

I'm using cluster hoping that it will distribute requests for workers using built-in Round-Robin Algorithm

But at the moment I don't understand how I can emit request received from process inside worker_CRUD_server.
Also I am not sure if they would use only on instance of in-memory DB

```<code>const cluster = require("cluster");
const http = require("http");
const os = require("os");
let port = 5000;
const server = http.createServer().listen(port);

const postsDB = [{ title: "First Post" }, { title: "Second Post" }];

if (cluster.isPrimary) {
  for (let i = 0; i < os.cpus().length - 1; i++) {
    server.on("connect", (req) => {
      const worker = cluster.fork();
      worker.send(req);
    });
  }
}

if (cluster.isWorker) {
  const worker_CRUD_server = http
    .createServer(/* hadling requests and sending responses - CRUD with postsDB*/)
    .listen(++port);

  process.on("message", (req) => {
    /* somehow send req to worker_CRUD_server and invoke proceeding request and sending response to client?? */
  });
}
</code>```

From documentation example I understand that it's more simple to run workers on the same PORT, but I need to implement this as I described - Main port sends tasks to worker ports.

Body:
I'm trying to implement the following:

server listens 5000 port and when receives requests - sends them to cluster workers

several cluster workers run on 5001, 5002, ... ports, proceed requests and send responses to the client

worker should work with the same instance of in-memory-db (array postsDB)

so if first worker receives POST request and second worker receives GET request - they change data in the same array

I'm using cluster hoping that it will distribute requests for workers using built-in Round-Robin Algorithm

But at the moment I don't understand how I can emit request received from process inside worker_CRUD_server.
Also I am not sure if they would use only on instance of in-memory DB

const cluster = require("cluster");
const http = require("http");
const os = require("os");
let port = 5000;
const server = http.createServer().listen(port);

const postsDB = [{ title: "First Post" }, { title: "Second Post" }];

if (cluster.isPrimary) {
  for (let i = 0; i < os.cpus().length - 1; i++) {
    server.on("connect", (req) => {
      const worker = cluster.fork();
      worker.send(req);
    });
  }
}

if (cluster.isWorker) {
  const worker_CRUD_server = http
    .createServer(/* hadling requests and sending responses - CRUD with postsDB*/)
    .listen(++port);

  process.on("message", (req) => {
    /* somehow send req to worker_CRUD_server and invoke proceeding request and sending response to client?? */
  });
}

From documentation example I understand that it's more simple to run workers on the same PORT, but I need to implement this as I described - Main port sends tasks to worker ports.


问:
No Spring WebApplicationInitalizer types detected on classpath
Trying to start a maven project on a tomcat server and getting this info/error message? Tried almost everything and can't seem to figure it out...

I rebuilt the project and cleaned the working servers work directory among many other things.


问:
Using supportedInterfaceOrientationsForWindow in appdelegate to restrict orientation
```<code>@interface MyAppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
{
    NSInteger skipforeground;
    NSInteger allowLandscape;
    NSInteger NoCheck;
}
- (UIInterfaceOrientationMask)application:(UIApplication *) application
  supportedInterfaceOrientationsForWindow:(UIWindow *) window {

    if (self->allowLandscape) {
        NSLog(@"rotation yes !");
        return UIInterfaceOrientationMaskAll;
    } else
    {
        return UIInterfaceOrientationMaskPortrait;
    };

}
</code>```

If I set self->allowLandscape to true elsewhere in the code and try to rotate my iphone, "rotation yes" will show up in the debugger window but the screen won't rotate.

If I replace the "self->allowLandscape" condition by "2>1" it will work.

How come both times the return is the same but one works and the other won't ?

Body:
@interface MyAppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
{
    NSInteger skipforeground;
    NSInteger allowLandscape;
    NSInteger NoCheck;
}
- (UIInterfaceOrientationMask)application:(UIApplication *) application
  supportedInterfaceOrientationsForWindow:(UIWindow *) window {

    if (self->allowLandscape) {
        NSLog(@"rotation yes !");
        return UIInterfaceOrientationMaskAll;
    } else
    {
        return UIInterfaceOrientationMaskPortrait;
    };

}

If I set self->allowLandscape to true elsewhere in the code and try to rotate my iphone, "rotation yes" will show up in the debugger window but the screen won't rotate.

If I replace the "self->allowLandscape" condition by "2>1" it will work.

How come both times the return is the same but one works and the other won't ?


问:
Javascript function to detect CSV line-endings
Looking for the best method to detect line endings in an imported csv file.

```<code>\n (UNIX default)
\r (Mac Excel)
\r\n (Windows)
</code>```

so far i have this but i know its terribly buggy. Any help appreciated:

```<code>  private determineCSVLineBreak(text: any) {
    const r = text.match(/\r/g).length;
    const n = text.match(/\n/g).length;
    const rn = text.match(/\r\n/g).length;
    if (rn >= r && rn >= n) {
      return "\r\n";
    } else if (r > n) {
      return "\r";
    } else {
      return "\n";
    }
  }
</code>```

Body:
Looking for the best method to detect line endings in an imported csv file.

\n (UNIX default)
\r (Mac Excel)
\r\n (Windows)

so far i have this but i know its terribly buggy. Any help appreciated:

  private determineCSVLineBreak(text: any) {
    const r = text.match(/\r/g).length;
    const n = text.match(/\n/g).length;
    const rn = text.match(/\r\n/g).length;
    if (rn >= r && rn >= n) {
      return "\r\n";
    } else if (r > n) {
      return "\r";
    } else {
      return "\n";
    }
  }


问:
Which size should I use to find out if I'm getting close to the storage limit on my Lite plan
When I query cloudant for database info, there are a number of sizes returned:

I have:

```<code>let  db = require('nano')(IBMdburl);
let  nano = require('nano')(IBMurl);
</code>```

Then if I invoke:

```<code> nano.request({ db: 'wxd', path: '/_design/app/_info' })
    .then(body => {
      console.log('got design doc info', body);
    })
</code>```

I get following sizes:

```<code>view_index: {
    ...
    sizes: { file: 451178400, external: 510408846, active: 273442954 },
    ...
}
</code>```

and for the database info:

```<code>  db.info()
    .then(body => {
      console.log('got database info', body);
    })

</code>```

the following:

```<code>sizes: { file: 914744004, external: 294471620, active: 747430633 },
</code>```

Which sizes should I use to know how close I am to the 1GB Lite plan limit?

Body:
When I query cloudant for database info, there are a number of sizes returned:

I have:

let  db = require('nano')(IBMdburl);
let  nano = require('nano')(IBMurl);

Then if I invoke:

 nano.request({ db: 'wxd', path: '/_design/app/_info' })
    .then(body => {
      console.log('got design doc info', body);
    })

I get following sizes:

view_index: {
    ...
    sizes: { file: 451178400, external: 510408846, active: 273442954 },
    ...
}

and for the database info:

  db.info()
    .then(body => {
      console.log('got database info', body);
    })

the following:

sizes: { file: 914744004, external: 294471620, active: 747430633 },

Which sizes should I use to know how close I am to the 1GB Lite plan limit?


问:
Zustand State being Stale React

Issue

I am having a rerendering issue that is occurring.  For some reason the state I update in the store object does not propogate to the components.  It doesn't have the most up to date state.

Notice how the object before the  had 63: null.  I deleted the object there in the store, but in the state when I call syncPhotoshopLayersAndContexts from components.  However, the state the components get back isn't updated.

Stack:

immer

zustand

TypeScript

List item

export const useContextStore = create(
    immer((set: any, get: any) => ({
        // this data structure is the main context store.  This is what we update the app with.
        layerID2Context: {},
        // this data structure is the cache we used to restore from, the user will hit ctrl+z at some point.
        contextCache: {},
        setAILayerContext: (layerID: number, layerContext: LayerAIContext) =>
            set((state: ContextStoreState) => {
                state.layerID2Context[layerID] = layerContext;
            }),
        getAILayerContext: (layerID: number) => get().layerID2Context[layerID],
        removeAILayerContext: (layerID: number) => {
            let layerContext = get().getAILayerContext(layerID)
            console.log("below is the context being removed")
            console.log(layerContext)
            set((state: ContextStoreState) => {

                // making a copy for good measure
                let newContext = {
                    ...layerContext
                }
                // storing previous version in cache for a back up in case of an undo.
                state.contextCache[layerID] = newContext
                delete state.layerID2Context[layerID]
            })

        },
        retreiveContextFromCache: (layerID: number) => {
            return get().contextCache[layerID]

        },
        syncPhotoshopLayersAndContexts: (layers: Array<Layer>) => {
            let activeLayerIDsWithContexts =  Object.keys(get().layerID2Context).map(key => parseInt(key))
            set((state: ContextStoreState) => {
                let activeLayerIDsInApp = layers.map(layer => layer.id)
                let layerIDsToCache = activeLayerIDsWithContexts.filter(x => !activeLayerIDsInApp.includes(x));
                console.log(layerIDsToCache)
                console.log("")
                console.log(get().layerID2Context)
                for(let layerID of layerIDsToCache){
                    // state.removeAILayerContext(layerID)
                    state.setAILayerContext(layerID, null)
                }
                console.log(get().layerID2Context)
                console.log("")
            })

        }

    }))
);
```

Here is the where the log is being displayed in the frontend component.  However, it has two contexts, when it should have just the one that isn't null.

Ask

What could the issue be?  Why is my component not getting the updated state?  It does exist at some point, just never given to the component to be rendered out.

Title: Zustand State being Stale React

Body:
Issue

I am having a rerendering issue that is occurring.  For some reason the state I update in the store object does not propogate to the components.  It doesn't have the most up to date state.

Notice how the object before the  had 63: null.  I deleted the object there in the store, but in the state when I call syncPhotoshopLayersAndContexts from components.  However, the state the components get back isn't updated.

Stack:

immer

zustand

TypeScript

List item

export const useContextStore = create(
    immer((set: any, get: any) => ({
        // this data structure is the main context store.  This is what we update the app with.
        layerID2Context: {},
        // this data structure is the cache we used to restore from, the user will hit ctrl+z at some point.
        contextCache: {},
        setAILayerContext: (layerID: number, layerContext: LayerAIContext) =>
            set((state: ContextStoreState) => {
                state.layerID2Context[layerID] = layerContext;
            }),
        getAILayerContext: (layerID: number) => get().layerID2Context[layerID],
        removeAILayerContext: (layerID: number) => {
            let layerContext = get().getAILayerContext(layerID)
            console.log("below is the context being removed")
            console.log(layerContext)
            set((state: ContextStoreState) => {

                // making a copy for good measure
                let newContext = {
                    ...layerContext
                }
                // storing previous version in cache for a back up in case of an undo.
                state.contextCache[layerID] = newContext
                delete state.layerID2Context[layerID]
            })

        },
        retreiveContextFromCache: (layerID: number) => {
            return get().contextCache[layerID]

        },
        syncPhotoshopLayersAndContexts: (layers: Array<Layer>) => {
            let activeLayerIDsWithContexts =  Object.keys(get().layerID2Context).map(key => parseInt(key))
            set((state: ContextStoreState) => {
                let activeLayerIDsInApp = layers.map(layer => layer.id)
                let layerIDsToCache = activeLayerIDsWithContexts.filter(x => !activeLayerIDsInApp.includes(x));
                console.log(layerIDsToCache)
                console.log("")
                console.log(get().layerID2Context)
                for(let layerID of layerIDsToCache){
                    // state.removeAILayerContext(layerID)
                    state.setAILayerContext(layerID, null)
                }
                console.log(get().layerID2Context)
                console.log("")
            })

        }

    }))
);

Here is the where the log is being displayed in the frontend component.  However, it has two contexts, when it should have just the one that isn't null.

Ask

What could the issue be?  Why is my component not getting the updated state?  It does exist at some point, just never given to the component to be rendered out.


问:
Selenium Python Detecting Page Changes
I'm developing a helper tool with PyQT that ultimately leads to a combination of automated input to a webpage from selenium and manual input from the user. Is there a way for selenium to detect events triggered by the user? For example, how could I trigger the onPageChange() function in my example to confirm the current page after the user clicks a link?</p>
```<code>from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

targetUrl = 'https://www.python.org/downloads/'
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
driver.get('https://www.python.org/')

class MainWindow(QMainWindow):
    def onPageChange(self):
        if driver.current_url == targetUrl:
            msg = QMessageBox()
            msg.setWindowTitle("Success")
            msg.exec()

app = QApplication([])
window = MainWindow()
window.show()
app.exec()
</code>```

Title: Selenium Python Detecting Page Changes

Body:
I'm developing a helper tool with PyQT that ultimately leads to a combination of automated input to a webpage from selenium and manual input from the user. Is there a way for selenium to detect events triggered by the user? For example, how could I trigger the onPageChange() function in my example to confirm the current page after the user clicks a link?

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

targetUrl = 'https://www.python.org/downloads/'
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
driver.get('https://www.python.org/')

class MainWindow(QMainWindow):
    def onPageChange(self):
        if driver.current_url == targetUrl:
            msg = QMessageBox()
            msg.setWindowTitle("Success")
            msg.exec()

app = QApplication([])
window = MainWindow()
window.show()
app.exec()


问:
sqlalchemy - different way to create a put method
I am trying to create a fastapi put/update method in my crud.py but all I have found is the following documentation -- > https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.update

I'm having an sqlite db where I have 1 column serving the primary key as Id -- > int, second and third one that are having values to strings.

I would like to use this put method so I can call on a Id and then update the values in the two columns. Is there another way to write it except the one suggested in the link above?


问:
Create 2D array in C++ from dimension given in constructor of a class
I am trying to build a method inside a class that populates a matrix.

```<code>class my_function{

public:

    my_function(double _x
        , double _y
        , int_N) {

        x = _x;
        y = _y;
        N= _N;

    }

       void Make_matrix() {
        vector<vector<double>> my_matrix(N+1, vector<double>(N+1));

        for (int i = 0; i <= N; i++) {
            for (int j = 0; j <= i; j++) {
                my_matrix[i][j] = x*y;
                cout << my_matrix[i][j] << endl;
            }
        }

    }

public:
    double x;
    double y;
    int N;
};
</code>```

However, this code throws several errors:

```<code>1.l-value specifies const object
2.'std::vector<std::vector<double,std::allocator<double>>,std::allocator<std::vector<double,std::allocator<double>>>>::vector(const unsigned int,const _Alloc &)': cannot convert argument 2 from'std::vector<int,std::allocator<int>>' to 'const _Alloc &'
3.'my_function::N':  an object of const-qualified type must be initialized
</code>```

Do you know how I can actually find a way to initialize and populate this 2D vector from the N specified in the constructor? Error 1 seems to be referring to N, which I am not sure whether requires to be of type const as it defines the dimensions of the 2D vector. I am open for any suggestion!
Thank you!

I tried defining N in different ways however it did not really work...
Just want to say that I have just started using c++ in visual studio for windows.

Body:
I am trying to build a method inside a class that populates a matrix.

class my_function{

public:

    my_function(double _x
        , double _y
        , int_N) {

        x = _x;
        y = _y;
        N= _N;

    }

       void Make_matrix() {
        vector<vector<double>> my_matrix(N+1, vector<double>(N+1));

        for (int i = 0; i <= N; i++) {
            for (int j = 0; j <= i; j++) {
                my_matrix[i][j] = x*y;
                cout << my_matrix[i][j] << endl;
            }
        }

    }

public:
    double x;
    double y;
    int N;
};

However, this code throws several errors:

1.l-value specifies const object
2.'std::vector<std::vector<double,std::allocator<double>>,std::allocator<std::vector<double,std::allocator<double>>>>::vector(const unsigned int,const _Alloc &)': cannot convert argument 2 from'std::vector<int,std::allocator<int>>' to 'const _Alloc &'
3.'my_function::N':  an object of const-qualified type must be initialized

Do you know how I can actually find a way to initialize and populate this 2D vector from the N specified in the constructor? Error 1 seems to be referring to N, which I am not sure whether requires to be of type const as it defines the dimensions of the 2D vector. I am open for any suggestion!
Thank you!

I tried defining N in different ways however it did not really work...
Just want to say that I have just started using c++ in visual studio for windows.


问:
Talkback always reads application name when opening Jetpack Compose Dialog
When opening a Dialog in Jetpack Compose, Talkback will always read the application label, before reading the Dialog title.

I have already tried setting the activity lable in the manifest to something different or just a space. While doing that, I noticed that talkback completely ignores the activity label and always goes for the outer application label.

Is there a way to stop Talkback from reading the application label entirely? And can I control what is read instead when opening a Dialog?