问:
Passing schema name as a parameter in spring jdbc template doesn't work
Here is the code snippet that I am trying to execute.

```<code>String schema = _2022_12_003_data
final String s = "SELECT * FROM ?.network limit 1";
final List<Map<String, Object>> maps = jdbcTemplate.queryForList(s, schema);
</code>```

I am trying to pass the schema name but it is giving me an exception
Caused by: org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.

I tried passing schema name through spring.datasource.url and with Connection.setSchema but it doesn't seem to add schema name that way. I also tried passing the parameter as MapSqlParameterSource but I got another exception Can't infer the SQL type to use for an instance of org.springframework.jdbc.core.namedparam.MapSqlParameterSource.

How to correctly get the schema name within the query?

Body:
Here is the code snippet that I am trying to execute.

String schema = _2022_12_003_data
final String s = "SELECT * FROM ?.network limit 1";
final List<Map<String, Object>> maps = jdbcTemplate.queryForList(s, schema);

I am trying to pass the schema name but it is giving me an exception
Caused by: org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.

I tried passing schema name through spring.datasource.url and with Connection.setSchema but it doesn't seem to add schema name that way. I also tried passing the parameter as MapSqlParameterSource but I got another exception Can't infer the SQL type to use for an instance of org.springframework.jdbc.core.namedparam.MapSqlParameterSource.

How to correctly get the schema name within the query?


来源: stackexchange

问:
open browser from angular and nginx container, without ng serve
I have a simple 2 stage dockerfile for angular UI, with node and nginx base images.
is it possible to start the default browser automatically when the container is ready?
I don't want to use ng serve --open in production. is there a solution with the current docker setup?</p>

ContentLicense: CC BY-SA 4.0


问:
Mahalanobis distance with 0 variance
I'm developing a clustering algorithm, I'm using the Mahalanobis distance to decide if a point must be included in a cluster or not.
A cluster is represented by the statistics of the points that are included in it, the statistics are:

the sum of the components of all the points in each dimension named SUMi;

the sum of the squares of the components of all the points in each dimension, named SUMQi.

Choosing these statistics, the centroid’s coordinate in the ith dimension is the SUMi/N, where N is the number of points in the cluster. Talking about the variance, I should compute the variance in the ith dimension as SUMSQi/N − (SUMi/N)^2.
To initialize clusters I choose k random point in the dataset, where k is a priori known number of clusters, in this way I have k clusters, each represented by the statistics of 1 point, this means that SUMSQi/N = (SUMi/N)^2 and thus variance is 0, so I can't compute Mahalanobis distance because it need to divide by the variance of the cluster and in this case, it is 0.
Which is the correct approach to this problem? And since I'm working with d-dimensional points how should I choose the threshold to discriminate if a point should be added to a cluster? Is using the module or the mean of the element of the variance vector a good idea?

The clusters are represtend by (2*d) + 1 elements: the first is the number of points in the cluster, from the second to the d-th element there are the SUMi, from the d-th to the (2*d)-th there are the SUMQi.
This is the function I implemented in C to compute variance of a cluster and Mahalanobis distance of a point from the cluster:

```<code>double mahalanobis(double *cluster, double *point, int dimension) {

    double* std_dev = malloc(dimension * sizeof(double ));

    /**
     * variance of the cluster
     */

    for (int i = 0; i < dimension; ++i) {
        std_dev[i] = cluster[i + dimension + 1]/cluster[0] - pow(cluster[i + 1]/cluster[0], 2);
    }

    /**
     * mahalanobis distance
     */

    double sum = 0;
    for (int i = 0; i < dimension; ++i) {
        sum += pow(point[i] - ((cluster[i+1] + point[i])/(cluster[0] + 1)), 2)/std_dev[i];
    }

    free(std_dev);

    return sqrt(sum);
}
</code>```

Title: Mahalanobis distance with 0 variance

Body:
I'm developing a clustering algorithm, I'm using the Mahalanobis distance to decide if a point must be included in a cluster or not.
A cluster is represented by the statistics of the points that are included in it, the statistics are:

the sum of the components of all the points in each dimension named SUMi;

the sum of the squares of the components of all the points in each dimension, named SUMQi.

Choosing these statistics, the centroid’s coordinate in the ith dimension is the SUMi/N, where N is the number of points in the cluster. Talking about the variance, I should compute the variance in the ith dimension as SUMSQi/N − (SUMi/N)^2.
To initialize clusters I choose k random point in the dataset, where k is a priori known number of clusters, in this way I have k clusters, each represented by the statistics of 1 point, this means that SUMSQi/N = (SUMi/N)^2 and thus variance is 0, so I can't compute Mahalanobis distance because it need to divide by the variance of the cluster and in this case, it is 0.
Which is the correct approach to this problem? And since I'm working with d-dimensional points how should I choose the threshold to discriminate if a point should be added to a cluster? Is using the module or the mean of the element of the variance vector a good idea?

The clusters are represtend by (2*d) + 1 elements: the first is the number of points in the cluster, from the second to the d-th element there are the SUMi, from the d-th to the (2*d)-th there are the SUMQi.
This is the function I implemented in C to compute variance of a cluster and Mahalanobis distance of a point from the cluster:

double mahalanobis(double *cluster, double *point, int dimension) {

    double* std_dev = malloc(dimension * sizeof(double ));

    /**
     * variance of the cluster
     */

    for (int i = 0; i < dimension; ++i) {
        std_dev[i] = cluster[i + dimension + 1]/cluster[0] - pow(cluster[i + 1]/cluster[0], 2);
    }

    /**
     * mahalanobis distance
     */

    double sum = 0;
    for (int i = 0; i < dimension; ++i) {
        sum += pow(point[i] - ((cluster[i+1] + point[i])/(cluster[0] + 1)), 2)/std_dev[i];
    }

    free(std_dev);

    return sqrt(sum);
}


问:
SagePay 3D Secure - how to get response object from ACSURL in our own callback method
We are using PI integration of sagepay. Our project is done using ASP.NET MVC & C# language.

We are trying to implement 3D secure functionality of sagepay with help of below link.

https://developer-eu.elavon.com/docs/opayo/3d-secure-authentication

and reached upto Step2,

For Step2 we created form like shown below
Setp2

as a result we are able to get upto below screen :

resultScreen

For callback we have created an action method as BookingSagePayCallbackForm.

CallBackScreen

But After Next button click, we are able to redirect to the action method viz. BookingSagePayCallbackForm. However, we are not getting any response. We would like to know how to get response from Sage Pay within this callback method BookingSagePayCallbackForm

What code I need to do after this callback response?

Thank you in advance.


问:
findById returns empty array
`

```<code>import {Router} from 'express';
import { sample_exercises, sample_tags } from '../data';
import expressAsyncHandler from 'express-async-handler';
import { ExerciseModel } from '../models/excersise.model';

const router = Router();

router.get("/:exerciseId", expressAsyncHandler(
    async (req, res) => {
        const exercise = await ExerciseModel.findById(req.params.exerciseId);
        //const exercise = await ExerciseModel.find({_id: req.params.exerciseId})
        res.send(exercise);
    })
);

export default router;
</code>```

`

The get exerciseId router is the only one that's not working properly.
Other get and post routes are working properly

`

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

export interface Exercise{
    id: number;
    name: string;
    description: string;
    targetgroup: string[];
}

export const ExerciseSchema = new Schema<Exercise>(
    {
        //id is a default member of this schema
        //we just have to convert _id to id
        name: {type: String, required: true},
        description: {type: String, required: true},
        targetgroup: {type: [String], required: true},
    },{
        //virtuals are values that will not be saved in the db
        //they will be generated based on the value inside the db
        //toJSON: if we send the value using mongoose from the api to the client
        //then we're going to have _id
        //toObject: if you get a value from the db and u want to manipulate it in your code
        toJSON:{
            virtuals: true
        },
        toObject:{
            virtuals:true
        },
        //option: on creation and update of the exercise schema you get a timestamp
        timestamps:true
    }
);

//with this model we have access to crud operations to the db
export const ExerciseModel = model<Exercise>('exercise', ExerciseSchema);
</code>```

`

This is how the model looks like.

`

```<code>export const sample_exercises: any[] = [
  {
    id:1,
    name: 'Benchpress',
    description: 'It involves lying on a bench and pressing weight upward using either a barbell or a pair of dumbbells. During a bench press, you lower the weight down to chest level and then press upwards while extending your arm',
    targetgroup: ['mid-chest', 'lower-chest', 'triceps']
  },
</code>```

`
And here's a sample of the seeded data.

I've tried to modifying the router and model, but to no avail.
Still getting an empty array...

Title: findById returns empty array

Body:
`

import {Router} from 'express';
import { sample_exercises, sample_tags } from '../data';
import expressAsyncHandler from 'express-async-handler';
import { ExerciseModel } from '../models/excersise.model';

const router = Router();

router.get("/:exerciseId", expressAsyncHandler(
    async (req, res) => {
        const exercise = await ExerciseModel.findById(req.params.exerciseId);
        //const exercise = await ExerciseModel.find({_id: req.params.exerciseId})
        res.send(exercise);
    })
);

export default router;

`

The get exerciseId router is the only one that's not working properly.
Other get and post routes are working properly

`

import { Schema, model } from 'mongoose';

export interface Exercise{
    id: number;
    name: string;
    description: string;
    targetgroup: string[];
}

export const ExerciseSchema = new Schema<Exercise>(
    {
        //id is a default member of this schema
        //we just have to convert _id to id
        name: {type: String, required: true},
        description: {type: String, required: true},
        targetgroup: {type: [String], required: true},
    },{
        //virtuals are values that will not be saved in the db
        //they will be generated based on the value inside the db
        //toJSON: if we send the value using mongoose from the api to the client
        //then we're going to have _id
        //toObject: if you get a value from the db and u want to manipulate it in your code
        toJSON:{
            virtuals: true
        },
        toObject:{
            virtuals:true
        },
        //option: on creation and update of the exercise schema you get a timestamp
        timestamps:true
    }
);

//with this model we have access to crud operations to the db
export const ExerciseModel = model<Exercise>('exercise', ExerciseSchema);

`

This is how the model looks like.

`

export const sample_exercises: any[] = [
  {
    id:1,
    name: 'Benchpress',
    description: 'It involves lying on a bench and pressing weight upward using either a barbell or a pair of dumbbells. During a bench press, you lower the weight down to chest level and then press upwards while extending your arm',
    targetgroup: ['mid-chest', 'lower-chest', 'triceps']
  },

`
And here's a sample of the seeded data.

I've tried to modifying the router and model, but to no avail.
Still getting an empty array...


问:
List of Lists into Single DataFrame Column
I have created a List which contains multiple lists. Every lists contains 24 values, for every hour of the day, and 1065 observations, for 35 months. I have four of these lists inside lists. My objective is to create one DataFrame Column from these lists, so I have one column with 24 hour per day and 1065 days.
This is the lists:

svk_list = (['svk_1', 'svk_2', 'svk_3', 'svk_4'])

and they are structured like:

```<code>svk_1 = []
svk_1.append(list(range(24)))
svk_1.append(list(range(24,48)))
svk_1.append(list(range(48,72)))
</code>```

The thing is, I have already solved this problem, but now I have changed something, and it doesn't work. This is the code I used before.

```<code>svk_list = (['svk_1', 'svk_2', 'svk_3', 'svk_4'])
svk_list_2 = (['consumption_svk_1', 'consumption_svk_2', 'consumption_svk_3', 'consumption_svk_4'])

for i, j, s in zip(svk_list, svk_list_2, range(1,5)):
    locals()[j] = (locals()[i].stack(dropna=False)
                     .reset_index().rename(columns={'level_1': 'hour', 'level_0': 'date', 0: f'SE{s}_C'}))
    locals()[j]['date'] = df['date']
    locals()[j].drop(['hour'],axis=1,inplace=True)
    locals()[j].set_index('date', inplace=True)
</code>```

And yes, this require the data to be DataFrames, since .stack() doesn't work with lists.

Body:
I have created a List which contains multiple lists. Every lists contains 24 values, for every hour of the day, and 1065 observations, for 35 months. I have four of these lists inside lists. My objective is to create one DataFrame Column from these lists, so I have one column with 24 hour per day and 1065 days.
This is the lists:

svk_list = (['svk_1', 'svk_2', 'svk_3', 'svk_4'])

and they are structured like:

svk_1 = []
svk_1.append(list(range(24)))
svk_1.append(list(range(24,48)))
svk_1.append(list(range(48,72)))

The thing is, I have already solved this problem, but now I have changed something, and it doesn't work. This is the code I used before.

svk_list = (['svk_1', 'svk_2', 'svk_3', 'svk_4'])
svk_list_2 = (['consumption_svk_1', 'consumption_svk_2', 'consumption_svk_3', 'consumption_svk_4'])

for i, j, s in zip(svk_list, svk_list_2, range(1,5)):
    locals()[j] = (locals()[i].stack(dropna=False)
                     .reset_index().rename(columns={'level_1': 'hour', 'level_0': 'date', 0: f'SE{s}_C'}))
    locals()[j]['date'] = df['date']
    locals()[j].drop(['hour'],axis=1,inplace=True)
    locals()[j].set_index('date', inplace=True)

And yes, this require the data to be DataFrames, since .stack() doesn't work with lists.


Title: safety complaining about sqlalchemy version

Body:
I have safety version 1.10.3 installed on my conda environment as well as sqlalchemy version 1.4.39. When I run safety check with safety check command, I get this error:

+==============================================================================+
|                                                                              |
|                               /$$$$$$            /$$                         |
|                              /$$__  $$          | $$                         |
|           /$$$$$$$  /$$$$$$ | $$  \__//$$$$$$  /$$$$$$   /$$   /$$           |
|          /$$_____/ |____  $$| $$$$   /$$__  $$|_  $$_/  | $$  | $$           |
|         |  $$$$$$   /$$$$$$$| $$_/  | $$$$$$$$  | $$    | $$  | $$           |
|          \____  $$ /$$__  $$| $$    | $$_____/  | $$ /$$| $$  | $$           |
|          /$$$$$$$/|  $$$$$$$| $$    |  $$$$$$$  |  $$$$/|  $$$$$$$           |
|         |_______/  \_______/|__/     \_______/   \___/   \____  $$           |
|                                                          /$$  | $$           |
|                                                         |  $$$$$$/           |
|  by pyup.io                                              \______/            |
|                                                                              |
+==============================================================================+
| REPORT                                                                       |
| checked 159 packages, using free DB (updated once a month)                   |
+============================+===========+==========================+==========+
| package                    | installed | affected                 | ID       |
+============================+===========+==========================+==========+
| sqlalchemy                 | 1.4.39    | <2.0.0b1                 | 51668    |
+==============================================================================+

Even though I install sqlalchemy version 2.0.0b1 on my conda environment, still version 1.4.39 on sqlalchemy gets installed because version 2.0.0b1 is still pre-release (see here). what options do I have beside ignoring this error in python safety?
Also here is the link to the safety issue regarding sqlalchemy.


问:
How to zoom/move into the mandelbrot set
I'm doing the Mandelbrot set in c as a school project.

This is my code:

int mandelbrot(int x, int y, t_data *data)
{
    double complex  c;
    double complex  z;
    double          cx;
    double          cy;
    int             i;

    cx = map(x, 0, WIDTH, data->min,  data->max);
    cy = map(y, 0, HEIGHT, data->min ,  data->max);
    c = cx + cy * I;
    z = 0;
    i = 0;
    while (i < data->max_iteration)
    {
        z = z * z + c;
        if (creal(z) * creal(z) + cimag(z) * cimag(z) > 4)
            break;
        i++;
    }

    return (get_color(i, *data));
}
```
<p>I used the <code>map()</code> function to convert the window coordinates to the complex coordinates
and I used it to get the cursor coordinates in the complex space too:</p>
<pre class="lang-c prettyprint-override"><code>double map(double value, double screen_min, double screen_max
                       , double image_min, double image_max)
{
    return ((value - screen_min ) \
            * (image_max - image_min) \
            / (screen_max - screen_min) \
            + image_min);
}
</code>```

the data is a struct that has the variables I need for the mand:

typedef struct mouse
{
    double          cursor_cx; // cursor x coordinates in the complex plane
    double          cursor_cy; // cursor x coordinates in the complex plane
    double          min; // the minimum edge of the mand initialized to -2
    double          max; // initialized to 2
    int         max_iteration; // initialized to 100
    mlx_t           *mlx;  // the window I guess
    mlx_image_t     *g_img; // the img I'll draw my pixels to
}   t_data;
```
<p>My problem now is moving the mandelbrot around and zooming in and out.<br></p>
<p>1st: I managed to zoom in and out by changing the <code>min</code> and <code>max</code>:</p>
<pre class="lang-c prettyprint-override"><code>void    zoom_hook(double xdelta, double ydelta, void *param)
{
        int32_t cursor_x = get_cursor_x();
    int32_t cursor_y = get_cursor_x();

    float   step;

    step = 0.1;
    t_data *data = param;
    (void)xdelta;
    if (ydelta > 0)
    {
        data->min += step;
        data->max -= step;
    }
    else if (ydelta < 0)
    {
        data->min -= step;
        data->max += step;
    }
}
</code>```

but when I zoom in a few times the mand get's inverted and starts zooming out even tho I'm zooming in

that's because min is moving from -2 to 0 then if I zoom more then that from 0 to 2
and vise versa for max
so I need a better way of zooming in, I'm expecting to be able to zoom in forever as long as it is within the limits of the computer. but right now my mand get's inverted before reaching that limit.

and more than that I can get the cursor x and y positions so I want to zoom in into those coordinates.

2nd: I need to move my `mand` and this is what I tried but it doesn't work It's zooming in and out but in diagonal way:

void    key_hook(void *param)
{
    t_data  *data;
    float   step;

    step = 0.1;
    data = param;
    if (mlx_is_key_down(data->mlx, MLX_KEY_ESCAPE))
        mlx_close_window(data->mlx);
    if (mlx_is_key_down(data->mlx, MLX_KEY_RIGHT))
        data->min -= step;
    if (mlx_is_key_down(data->mlx, MLX_KEY_LEFT))
        data->min += step;
    if (mlx_is_key_down(data->mlx, MLX_KEY_UP))
        data->max += step;
    if (mlx_is_key_down(data->mlx, MLX_KEY_DOWN))
        data->max -= step;
}
```

I'm expecting it to move to the directions right, left, up and down.

So I need some helpt to move and zoom my mandelbrot set.

Thanks in advance.

Body:
I'm doing the Mandelbrot set in c as a school project.

This is my code:

int mandelbrot(int x, int y, t_data *data)
{
    double complex  c;
    double complex  z;
    double          cx;
    double          cy;
    int             i;

    cx = map(x, 0, WIDTH, data->min,  data->max);
    cy = map(y, 0, HEIGHT, data->min ,  data->max);
    c = cx + cy * I;
    z = 0;
    i = 0;
    while (i < data->max_iteration)
    {
        z = z * z + c;
        if (creal(z) * creal(z) + cimag(z) * cimag(z) > 4)
            break;
        i++;
    }

    return (get_color(i, *data));
}

I used the map() function to convert the window coordinates to the complex coordinates
and I used it to get the cursor coordinates in the complex space too:

double map(double value, double screen_min, double screen_max
                       , double image_min, double image_max)
{
    return ((value - screen_min ) \
            * (image_max - image_min) \
            / (screen_max - screen_min) \
            + image_min);
}

the data is a struct that has the variables I need for the mand:

typedef struct mouse
{
    double          cursor_cx; // cursor x coordinates in the complex plane
    double          cursor_cy; // cursor x coordinates in the complex plane
    double          min; // the minimum edge of the mand initialized to -2
    double          max; // initialized to 2
    int         max_iteration; // initialized to 100
    mlx_t           *mlx;  // the window I guess
    mlx_image_t     *g_img; // the img I'll draw my pixels to
}   t_data;

My problem now is moving the mandelbrot around and zooming in and out.

1st: I managed to zoom in and out by changing the min and max:

void    zoom_hook(double xdelta, double ydelta, void *param)
{
        int32_t cursor_x = get_cursor_x();
    int32_t cursor_y = get_cursor_x();

    float   step;

    step = 0.1;
    t_data *data = param;
    (void)xdelta;
    if (ydelta > 0)
    {
        data->min += step;
        data->max -= step;
    }
    else if (ydelta < 0)
    {
        data->min -= step;
        data->max += step;
    }
}

but when I zoom in a few times the mand get's inverted and starts zooming out even tho I'm zooming in

that's because min is moving from -2 to 0 then if I zoom more then that from 0 to 2
and vise versa for max
so I need a better way of zooming in, I'm expecting to be able to zoom in forever as long as it is within the limits of the computer. but right now my mand get's inverted before reaching that limit.

and more than that I can get the cursor x and y positions so I want to zoom in into those coordinates.

2nd: I need to move my `mand` and this is what I tried but it doesn't work It's zooming in and out but in diagonal way:

void    key_hook(void *param)
{
    t_data  *data;
    float   step;

    step = 0.1;
    data = param;
    if (mlx_is_key_down(data->mlx, MLX_KEY_ESCAPE))
        mlx_close_window(data->mlx);
    if (mlx_is_key_down(data->mlx, MLX_KEY_RIGHT))
        data->min -= step;
    if (mlx_is_key_down(data->mlx, MLX_KEY_LEFT))
        data->min += step;
    if (mlx_is_key_down(data->mlx, MLX_KEY_UP))
        data->max += step;
    if (mlx_is_key_down(data->mlx, MLX_KEY_DOWN))
        data->max -= step;
}

I'm expecting it to move to the directions right, left, up and down.

So I need some helpt to move and zoom my mandelbrot set.

Thanks in advance.


问:
Popup Hide Show
I want to create show and hide a alert bar using (alert) button click, If i click that alert button it needs to show what is that alert & again I click that button it needs to be (Hide) visibility gone...I want to switch that visibility thats all.

How to do this in android kotlin, I am new to this field, Plz help me..

This is my code

```<code>// for alert popup
binding.alertImage.setOnClickListener {
    binding.alertImage.setVisibility(View.INVISIBLE);
    binding.scrollText1.visibility = View.VISIBLE
}
</code>```

Title: Popup Hide Show

Body:
I want to create show and hide a alert bar using (alert) button click, If i click that alert button it needs to show what is that alert & again I click that button it needs to be (Hide) visibility gone...I want to switch that visibility thats all.

How to do this in android kotlin, I am new to this field, Plz help me..

This is my code

// for alert popup
binding.alertImage.setOnClickListener {
    binding.alertImage.setVisibility(View.INVISIBLE);
    binding.scrollText1.visibility = View.VISIBLE
}


问:
Display data from JSON result in laravel
I have this result from consol.log

```<code>0: {id: 8, account_name: 'Loan2', principal_loan: 10000, annual_interest_rate: 2, …}
1: {id: 15, account_name: 'Student Loan', principal_loan: 50000, annual_interest_rate: 6, …}
2: {id: 17, account_name: 'Personal Loan', principal_loan: 30000, annual_interest_rate: 3, …}
3: {id: 104, account_name: 'Loan test 1', principal_loan: 1000, annual_interest_rate: 2.8, …}
</code>```

I want to get all individual data but I only get the first data when I tried to display it.

Here's my code

```<code>success: function(data){
     console.log(data);
     $.each(data, function(x, object){
          $.each(object, function(i, obj){
             alert(i + obj);
          });
     });
 });
</code>```

But when I just use the first .each I only get the last data. I want to append individual data on the table with their calculations.

Here's my full code

```<code>$.each(data, function(i, obj){
    var principal_loan = parseFloat(obj.principal_loan);
    var rate = parseFloat(obj.rate);

    //some calculations here....

   do {

     //some calculations here....

     html += "<tr>";
     html     += "<td style=\"text-align:center;\">" +  obj.account_name + "</td>";

     //.....some codes here

     html += "</tr>";
   }

   while( i < $_no_of_payments );
   $("#debt-payment-schedule").html( html );

});
</code>```

Here's a sample result
Sample result

Please help me display this guys, thank you in advance.

Body:
I have this result from consol.log

0: {id: 8, account_name: 'Loan2', principal_loan: 10000, annual_interest_rate: 2, …}
1: {id: 15, account_name: 'Student Loan', principal_loan: 50000, annual_interest_rate: 6, …}
2: {id: 17, account_name: 'Personal Loan', principal_loan: 30000, annual_interest_rate: 3, …}
3: {id: 104, account_name: 'Loan test 1', principal_loan: 1000, annual_interest_rate: 2.8, …}

I want to get all individual data but I only get the first data when I tried to display it.

Here's my code

success: function(data){
     console.log(data);
     $.each(data, function(x, object){
          $.each(object, function(i, obj){
             alert(i + obj);
          });
     });
 });

But when I just use the first .each I only get the last data. I want to append individual data on the table with their calculations.

Here's my full code

$.each(data, function(i, obj){
    var principal_loan = parseFloat(obj.principal_loan);
    var rate = parseFloat(obj.rate);

    //some calculations here....

   do {

     //some calculations here....

     html += "
";
     html     += "" +  obj.account_name + "	";

     //.....some codes here

     html += "
";
   }

   while( i < $_no_of_payments );
   $("#debt-payment-schedule").html( html );

});

Here's a sample result
Sample result

Please help me display this guys, thank you in advance.


问:
Configuring access to sqlite database from a springboot docker container
I have a spring boot application that uses sqlite database stored in a computer. I try to setup:

Hikari for managing connection pools

JNDI to manage datasource

SQL lite database available from a local folder

I have configured the following application.properties:

```<code>server.servlet.context-path=/ws-application
spring.datasource.driverClassName=org.sqlite.JDBC
spring.datasource.url=jdbc:sqlite:C:/db/applicationdata.db
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.jndiName=jdbc/myDataSource

spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=false

spring.datasource.hikari.connection-timeout = 1800000
spring.datasource.hikari.connectionTimeout=1800000
spring.datasource.hikari.minimum-idle= 1
spring.datasource.hikari.maximum-pool-size= 1
spring.datasource.hikari.data-source-j-n-d-i=jdbc/myDataSource
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.idleTimeout=600000
spring.datasource.hikari.max-lifetime= 1800000
spring.datasource.hikari.maxLifetime=1800000
spring.datasource.hikari.auto-commit =true
</code>```

The application work fine when jar is executed. So far so good. Now I'm trying to create a docker image and launch the application with docker compose.

For the springboot application, i have a basic Dockerfile:

```<code># Build stage: requires maven
FROM maven:3.8.4-openjdk-17 AS build

WORKDIR /app
COPY ../../ws-proxy/. /app
RUN mvn clean package -DskipTests

# Package and Run stage
FROM openjdk:17-alpine
COPY --from=build app/target/ws-application.jar /usr/local/lib/ws-application.jar
ENTRYPOINT ["java", "-jar", "-Dspring.profiles.active=docker", "/usr/local/lib/ws-application.jar"]
</code>```

Now in my docker compose file, I added sqlite and my webservice:

```<code>version: "3.8"
services:
  sqlite3:
    image: nouchka/sqlite3:latest
    container_name: sqlite3
    restart: always
    stdin_open: true
    tty: true
    volumes:
      #Modify following line
      - sqliteDb:/app/
    ports:
      - '9000:9000' # expose ports - HOST:CONTAINER

  ws-proxy:
    image: ws-application
    container_name: ws-application
    restart: always
    build:
      context: ../
      dockerfile: docker/dockerfiles/Dockerfile.ws-application
    ports:
        - "8080:8080"
    environment:
        - SPRING_DATASOURCE_URL=jdbc:C:/db/applicationdata.db

volumes:
  sqliteDb:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: /C/db
</code>```

I do have 2 issues:

Caused by: java.sql.SQLException: Driver:org.sqlite.JDBC@4a31c2ee returned null for URL:jdbc:C:/db/applicationdata.db

org.springframework.jndi.JndiLookupFailureException: JndiObjectTargetSource failed to obtain new target object

In my application, JNDI is programmatically configured and read application.properties:

```<code>@Configuration
@EnableTransactionManagement
//@PropertySource("classpath:application.properties")
@EnableJpaRepositories(basePackages = "fr.app.io.repository")
public class AppConfig {

    @Bean
    public DatabaseProperties databaseProperties() {
        return new DatabaseProperties();
    }

    @Bean
    public TomcatServletWebServerFactory tomcatFactory() {
        return new TomcatServletWebServerFactory() {
            @Override
            protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
                tomcat.enableNaming();
                return super.getTomcatWebServer(tomcat);
            }

            @Override
            protected void postProcessContext(Context context) {
                ContextResource resource = new ContextResource();

                resource.setType("org.apache.tomcat.jdbc.pool.DataSource");
                resource.setName(databaseProperties().getJndiName());
                resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
                resource.setProperty("driverClassName", databaseProperties().getDriverClassName());
                resource.setProperty("url", databaseProperties().getUrl());
                resource.setProperty("username", databaseProperties().getUsername());
                resource.setProperty("password", databaseProperties().getPassword());

                context.getNamingResources().addResource(resource);
            }
        };
    }

    @Bean(destroyMethod = "")
    public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
        JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
        bean.setJndiName("java:comp/env/" + databaseProperties().getJndiName());
        bean.setProxyInterface(DataSource.class);
        bean.setLookupOnStartup(false);
        bean.afterPropertiesSet();
        return (DataSource) bean.getObject();
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() throws SQLException, IllegalArgumentException, NamingException {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabase(Database.MYSQL);
        vendorAdapter.setShowSql(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("fr.dsidiff.app.proxy.io.entity");
        factory.setDataSource(jndiDataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager()
            throws SQLException, IllegalArgumentException, NamingException {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }

}
</code>```

Other question: i tested code from this tutorial: https://roytuts.com/spring-boot-jndi-datasource/

As a bonus question any one can explain me why if i set the vendorAdapter to MYSQL I can do insertions using SQLITE ?

```<code>HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.MYSQL);
</code>```

Thanks

Body:
I have a spring boot application that uses sqlite database stored in a computer. I try to setup:

Hikari for managing connection pools

JNDI to manage datasource

SQL lite database available from a local folder

I have configured the following application.properties:

server.servlet.context-path=/ws-application
spring.datasource.driverClassName=org.sqlite.JDBC
spring.datasource.url=jdbc:sqlite:C:/db/applicationdata.db
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.jndiName=jdbc/myDataSource

spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=false

spring.datasource.hikari.connection-timeout = 1800000
spring.datasource.hikari.connectionTimeout=1800000
spring.datasource.hikari.minimum-idle= 1
spring.datasource.hikari.maximum-pool-size= 1
spring.datasource.hikari.data-source-j-n-d-i=jdbc/myDataSource
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.idleTimeout=600000
spring.datasource.hikari.max-lifetime= 1800000
spring.datasource.hikari.maxLifetime=1800000
spring.datasource.hikari.auto-commit =true

The application work fine when jar is executed. So far so good. Now I'm trying to create a docker image and launch the application with docker compose.

For the springboot application, i have a basic Dockerfile:

# Build stage: requires maven
FROM maven:3.8.4-openjdk-17 AS build

WORKDIR /app
COPY ../../ws-proxy/. /app
RUN mvn clean package -DskipTests

# Package and Run stage
FROM openjdk:17-alpine
COPY --from=build app/target/ws-application.jar /usr/local/lib/ws-application.jar
ENTRYPOINT ["java", "-jar", "-Dspring.profiles.active=docker", "/usr/local/lib/ws-application.jar"]

Now in my docker compose file, I added sqlite and my webservice:

version: "3.8"
services:
  sqlite3:
    image: nouchka/sqlite3:latest
    container_name: sqlite3
    restart: always
    stdin_open: true
    tty: true
    volumes:
      #Modify following line
      - sqliteDb:/app/
    ports:
      - '9000:9000' # expose ports - HOST:CONTAINER

  ws-proxy:
    image: ws-application
    container_name: ws-application
    restart: always
    build:
      context: ../
      dockerfile: docker/dockerfiles/Dockerfile.ws-application
    ports:
        - "8080:8080"
    environment:
        - SPRING_DATASOURCE_URL=jdbc:C:/db/applicationdata.db

volumes:
  sqliteDb:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: /C/db

I do have 2 issues:

Caused by: java.sql.SQLException: Driver:org.sqlite.JDBC@4a31c2ee returned null for URL:jdbc:C:/db/applicationdata.db

org.springframework.jndi.JndiLookupFailureException: JndiObjectTargetSource failed to obtain new target object

In my application, JNDI is programmatically configured and read application.properties:

@Configuration
@EnableTransactionManagement
//@PropertySource("classpath:application.properties")
@EnableJpaRepositories(basePackages = "fr.app.io.repository")
public class AppConfig {

    @Bean
    public DatabaseProperties databaseProperties() {
        return new DatabaseProperties();
    }

    @Bean
    public TomcatServletWebServerFactory tomcatFactory() {
        return new TomcatServletWebServerFactory() {
            @Override
            protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
                tomcat.enableNaming();
                return super.getTomcatWebServer(tomcat);
            }

            @Override
            protected void postProcessContext(Context context) {
                ContextResource resource = new ContextResource();

                resource.setType("org.apache.tomcat.jdbc.pool.DataSource");
                resource.setName(databaseProperties().getJndiName());
                resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
                resource.setProperty("driverClassName", databaseProperties().getDriverClassName());
                resource.setProperty("url", databaseProperties().getUrl());
                resource.setProperty("username", databaseProperties().getUsername());
                resource.setProperty("password", databaseProperties().getPassword());

                context.getNamingResources().addResource(resource);
            }
        };
    }

    @Bean(destroyMethod = "")
    public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
        JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
        bean.setJndiName("java:comp/env/" + databaseProperties().getJndiName());
        bean.setProxyInterface(DataSource.class);
        bean.setLookupOnStartup(false);
        bean.afterPropertiesSet();
        return (DataSource) bean.getObject();
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() throws SQLException, IllegalArgumentException, NamingException {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabase(Database.MYSQL);
        vendorAdapter.setShowSql(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("fr.dsidiff.app.proxy.io.entity");
        factory.setDataSource(jndiDataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager()
            throws SQLException, IllegalArgumentException, NamingException {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }

}

Other question: i tested code from this tutorial: https://roytuts.com/spring-boot-jndi-datasource/

As a bonus question any one can explain me why if i set the vendorAdapter to MYSQL I can do insertions using SQLITE ?

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.MYSQL);

Thanks


问:
Graphql Java upload scalar maximum size
I will like to limit the maximum size of the Upload scalar parameter by using schema directives but it does not work. See my code below:

```<code>directive @Size(min : Int = 0, max : Int = 1, message : String = "graphql.validation.Size.message") on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION

directive @Max(value : Int = 1048576, message : String = "graphql.validation.Max.message") on SCALAR

scalar Upload @Max

type Mutation {
    uploadFile(files: [Upload!] @Size(max : 1)): boolean
}
</code>```

Looking forward to receiving help from everyone.

Title: Graphql Java upload scalar maximum size

Body:
I will like to limit the maximum size of the Upload scalar parameter by using schema directives but it does not work. See my code below:

directive @Size(min : Int = 0, max : Int = 1, message : String = "graphql.validation.Size.message") on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION

directive @Max(value : Int = 1048576, message : String = "graphql.validation.Max.message") on SCALAR

scalar Upload @Max

type Mutation {
    uploadFile(files: [Upload!] @Size(max : 1)): boolean
}

Looking forward to receiving help from everyone.


问:
KerasRl ValueError: Error when checking input: expected input_3 to have 3 dimensions, but got array with shape (1, 1, 9, 9)
I made an env with Gym for Sudoku puzzle and I want to train an AI on it using KerasRL (I've removed the step reset and render method of the environment to not have too much code for StackOverflow).
I use a Flatten and 3 dense layers for my model and compile it with Adam.
I get a error when I try to compile it because the shape isn't the right one and i don't get why :

     from gym import Env
     from gym.spaces import Discrete, Box
     import numpy as np
     import random

     from tensorflow.keras.models import Sequential
     from tensorflow.keras.layers import Dense, Flatten, Input
     from tensorflow.keras.optimizers import Adam
     from numpy.linalg.linalg import double
     from numpy.core.numeric import ones

     class Sudoku(Env):
           #Fonction d'initialisaion
     def __init__(self):
               #Soit on met une case fixé et il y a 9 actions possibles (mettre un num de 1 à 9), sur la grille générale il y a 81 cases disponibles et 9 numéros possibles par case ->729
     self.action_space = Discrete(729)

               #81 cases qui prennent des valeurs entres 0 (case vide pour 0) et 9, le produit cartésien des deux donnent bien le nombre de grilles possibles au sudoku je pense
               #chaque case est représenté par une case de tableau, le premier array correspond a la borne inferieur prise par chaque case (0) et le deuxieme par la borne sup 9, ça fait enormément d'état possibles
     self.observation_space = Box(low= 0,high= 9, shape=(9,9),dtype=int)

               #definition de l'état de départ que des zeros dans les 81 cases (vides)
     self.state = np.zeros((9,9),dtype=int)

             #fonction application d'action
     def step(self,action):
     return self.state , reward , done , info

     def render(self, mode):

     def reset(self):
     return self.state

     def build_model(states,actions):
     model=Sequential()
     model.add(Input(shape=states))
     model.add(Flatten())
     model.add(Dense(100,activation='relu'))
     model.add(Dense(100,activation='relu'))
     model.add(Dense(actions,activation='linear'))
     return model

     from rl.agents import DQNAgent
     from rl.policy import BoltzmannQPolicy
     from rl.memory import SequentialMemory

     def build_agent(model,actions):
     policy= BoltzmannQPolicy()
     memory= SequentialMemory(limit=50000,window_length=1)
     agent= DQNAgent(model=model,memory=memory,policy=policy,nb_actions=actions,nb_steps_warmup=10,target_model_update=1e-2)
     return agent

     env=Sudoku()
     states=env.observation_space.shape
     print(states)
     actions=env.action_space.n
     model = build_model(states,actions)
     model.summary()
     agent = build_agent(model,actions)
     agent.compile(Adam(lr=1e-3),metrics=['mae'])
     agent.fit(env,nb_steps=20000,visualize=False,verbose=1)
```
<p>I get this error :</p>
<blockquote>
<p>Training for 20000 steps ... Interval 1 (0 steps performed)
--------------------------------------------------------------------------- ValueError                                Traceback (most recent call
last)  in
1 agent.compile(Adam(lr=1e-3),metrics=['mae'])
----> 2 agent.fit(env,nb_steps=20000,visualize=False,verbose=1)</p>
<p>7 frames
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training_utils.py
in standardize_input_data(data, names, shapes, check_batch_axis,
exception_prefix)
569         shape = shapes[i]
570         if len(data_shape) != len(shape):
--> 571           raise ValueError('Error when checking ' + exception_prefix +
572                            ': expected ' + names[i] + ' to have ' +
573                            str(len(shape)) + ' dimensions, but got array '</p>
```ValueError: Error when checking input: expected input_3 to have 3 dimensions, but got array with shape (1, 1, 9, 9)
```

Body:
I made an env with Gym for Sudoku puzzle and I want to train an AI on it using KerasRL (I've removed the step reset and render method of the environment to not have too much code for StackOverflow).
I use a Flatten and 3 dense layers for my model and compile it with Adam.
I get a error when I try to compile it because the shape isn't the right one and i don't get why :

     from gym import Env
     from gym.spaces import Discrete, Box
     import numpy as np
     import random

     from tensorflow.keras.models import Sequential
     from tensorflow.keras.layers import Dense, Flatten, Input
     from tensorflow.keras.optimizers import Adam
     from numpy.linalg.linalg import double
     from numpy.core.numeric import ones

     class Sudoku(Env):
           #Fonction d'initialisaion
     def __init__(self):
               #Soit on met une case fixé et il y a 9 actions possibles (mettre un num de 1 à 9), sur la grille générale il y a 81 cases disponibles et 9 numéros possibles par case ->729
     self.action_space = Discrete(729)

               #81 cases qui prennent des valeurs entres 0 (case vide pour 0) et 9, le produit cartésien des deux donnent bien le nombre de grilles possibles au sudoku je pense
               #chaque case est représenté par une case de tableau, le premier array correspond a la borne inferieur prise par chaque case (0) et le deuxieme par la borne sup 9, ça fait enormément d'état possibles
     self.observation_space = Box(low= 0,high= 9, shape=(9,9),dtype=int)

               #definition de l'état de départ que des zeros dans les 81 cases (vides)
     self.state = np.zeros((9,9),dtype=int)

             #fonction application d'action
     def step(self,action):
     return self.state , reward , done , info

     def render(self, mode):

     def reset(self):
     return self.state

     def build_model(states,actions):
     model=Sequential()
     model.add(Input(shape=states))
     model.add(Flatten())
     model.add(Dense(100,activation='relu'))
     model.add(Dense(100,activation='relu'))
     model.add(Dense(actions,activation='linear'))
     return model

     from rl.agents import DQNAgent
     from rl.policy import BoltzmannQPolicy
     from rl.memory import SequentialMemory

     def build_agent(model,actions):
     policy= BoltzmannQPolicy()
     memory= SequentialMemory(limit=50000,window_length=1)
     agent= DQNAgent(model=model,memory=memory,policy=policy,nb_actions=actions,nb_steps_warmup=10,target_model_update=1e-2)
     return agent

     env=Sudoku()
     states=env.observation_space.shape
     print(states)
     actions=env.action_space.n
     model = build_model(states,actions)
     model.summary()
     agent = build_agent(model,actions)
     agent.compile(Adam(lr=1e-3),metrics=['mae'])
     agent.fit(env,nb_steps=20000,visualize=False,verbose=1)

I get this error :

Training for 20000 steps ... Interval 1 (0 steps performed)
--------------------------------------------------------------------------- ValueError                                Traceback (most recent call
last)  in
1 agent.compile(Adam(lr=1e-3),metrics=['mae'])
----> 2 agent.fit(env,nb_steps=20000,visualize=False,verbose=1)

7 frames
/usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training_utils.py
in standardize_input_data(data, names, shapes, check_batch_axis,
exception_prefix)
569         shape = shapes[i]
570         if len(data_shape) != len(shape):
--> 571           raise ValueError('Error when checking ' + exception_prefix +
572                            ': expected ' + names[i] + ' to have ' +
573                            str(len(shape)) + ' dimensions, but got array '

ValueError: Error when checking input: expected input_3 to have 3 dimensions, but got array with shape (1, 1, 9, 9)


问:
C insertion sort with function as parameter
I'm trying to implement an insertion sort algorithm and it almost works. My code is the following:

```<code>#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int compare_desc(const char *input1, const char *input2){
    char a = (*input1);
    char b = (*input2);

    if (a == b){
        return 0;
    }

    if (a > b){
        return -1;
    }

    return 1;
}

int compare_ignore_case_asc(const char *input1, const char *input2){
    char a = tolower(*input1);
    char b = tolower(*input2);

    if (a == b) {
        return 0;
    }

    if (a > b) {
        return 1;
    }

    return -1;
}

void insertion_sort(char *array, size_t n, int (*compare)(const char *, const char *))
{
    for (size_t i = 1; i < n; i++)
    {
       for (size_t j = i; j > 0 && compare(&array[j-1], &array[j]); --j){
           char temp = array[j-1];
           array[j-1] = array[j];
           array[j] = temp;
       }
    }
}

int main(void) {

    return EXIT_SUCCESS;
}
</code>```

This code compares with the two compare functions (they are already correct and tested with test cases).

Am I somehow misunderstanding the point of insertion sort?

The problem I'm facing is the following:

```<code>'insertion_sort':
=================
After executing the function 'insertion_sort' the order of the values in the array 'base' is not as expected!
String representation of the contents of the array 'base' after execution:
Expected: "First"
Actual  : "iFstr"
The following code snippet led to this error:
char array[] = "rtsFi";
size_t length = 5;
int (*compare)(const char *, const char *) = compare_ignore_case_asc;
insertion_sort(array, length, compare);
</code>```

Where is my mistake?

I already tried and google and debug but I don't see the mistake I am currently making.

Body:
I'm trying to implement an insertion sort algorithm and it almost works. My code is the following:

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int compare_desc(const char *input1, const char *input2){
    char a = (*input1);
    char b = (*input2);

    if (a == b){
        return 0;
    }

    if (a > b){
        return -1;
    }

    return 1;
}

int compare_ignore_case_asc(const char *input1, const char *input2){
    char a = tolower(*input1);
    char b = tolower(*input2);

    if (a == b) {
        return 0;
    }

    if (a > b) {
        return 1;
    }

    return -1;
}

void insertion_sort(char *array, size_t n, int (*compare)(const char *, const char *))
{
    for (size_t i = 1; i < n; i++)
    {
       for (size_t j = i; j > 0 && compare(&array[j-1], &array[j]); --j){
           char temp = array[j-1];
           array[j-1] = array[j];
           array[j] = temp;
       }
    }
}

int main(void) {

    return EXIT_SUCCESS;
}

This code compares with the two compare functions (they are already correct and tested with test cases).

Am I somehow misunderstanding the point of insertion sort?

The problem I'm facing is the following:

'insertion_sort':
=================
After executing the function 'insertion_sort' the order of the values in the array 'base' is not as expected!
String representation of the contents of the array 'base' after execution:
Expected: "First"
Actual  : "iFstr"
The following code snippet led to this error:
char array[] = "rtsFi";
size_t length = 5;
int (*compare)(const char *, const char *) = compare_ignore_case_asc;
insertion_sort(array, length, compare);

Where is my mistake?

I already tried and google and debug but I don't see the mistake I am currently making.


问:
Can't seem to disable .onBackPressed() in Fragments
I'm trying to disable the back button for all screens in my app (Fragments and Activites).

I'm able to successfully disable the back button in my MainActivity by simply removing the super method in .onBackPressed()

```<code>@Override
    public void onBackPressed() {
        //Disabled
}
</code>```

The back button no longer works on this Activity screen.

However, once I have inflated a DialogFragment, the back button seems to work again, and once I click on it, it dismisses the inflated DialogFragment.

I am not sure why it's doing this, but after searching google I came accross this onBackPressedDispatcher

https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

I have tried the method in that doc which says to place this block of code inside my inflated DialogFragment

```<code> @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState
    ) {
        View view = inflater.inflate(R.layout.dialog_fragment, container, false);

        OnBackPressedCallback callback = new OnBackPressedCallback(
                false
        ) {
            @Override
            public void handleOnBackPressed() {

            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(
                this,
                callback);

        return view;
    }
</code>```

However the back button is still working. I am not sure what I'm doing incorrectly.

How can I disable the Android Back Button inside my DialogFragment?

Edit:___________________________________________

Calling dialog.setCancelable() does not work

```<code>@NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        final Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.setCancelable(false);
        return dialog;
    }
</code>```

Body:
I'm trying to disable the back button for all screens in my app (Fragments and Activites).

I'm able to successfully disable the back button in my MainActivity by simply removing the super method in .onBackPressed()

@Override
    public void onBackPressed() {
        //Disabled
}

The back button no longer works on this Activity screen.

However, once I have inflated a DialogFragment, the back button seems to work again, and once I click on it, it dismisses the inflated DialogFragment.

I am not sure why it's doing this, but after searching google I came accross this onBackPressedDispatcher

https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

I have tried the method in that doc which says to place this block of code inside my inflated DialogFragment

 @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState
    ) {
        View view = inflater.inflate(R.layout.dialog_fragment, container, false);

        OnBackPressedCallback callback = new OnBackPressedCallback(
                false
        ) {
            @Override
            public void handleOnBackPressed() {

            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(
                this,
                callback);

        return view;
    }

However the back button is still working. I am not sure what I'm doing incorrectly.

How can I disable the Android Back Button inside my DialogFragment?

Edit:___________________________________________

Calling dialog.setCancelable() does not work

@NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        final Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.setCancelable(false);
        return dialog;
    }


问:
Modify VSCode Jupyter Notebook appearance
Is it possible to change the appearance of Jupyter Notebooks on VSCode, for them to look more like the browser version ?
In particular, I find the inter-cells space (1) way too big, and the check mark that indicates the execution (2) to also taking too much place.

I think that at the end in a page I cannot see enough code.

Is it possible to modify that ?


问:
Capture output of tqdm
Is it possible to capture the output of tqdm? I have an API, and I'd like to parse out the time spent, estimated remaining, and the percentage to the API for a website to utilize in it's own progress bar. Is this possible?

I had figured something like this snippet would work, but it only captures my irrelevant timing functions print.

    class Capture(list):
        def __enter__(self):
            self._stdout = sys.stdout
            sys.stdout = self._stringio = StringIO()
            return self
        def __exit__(self, *args):
            self.extend(self._stringio.getvalue().splitlines())
            del self._stringio    # free up some memory
            sys.stdout = self._stdout
```

Title: Capture output of tqdm


问:
ValueError: Tensor conversion requested dtype float64 for Tensor with dtype float32
Trying to use Keras Tuner to optimize my hyperparameters. I build the following model:

```<code>def build_model(hp):
    model = Sequential(name='ESN_NE')
    model.add(InputLayer((timesteps, input_dim), name='input_layer'))
    model.add(ESN(units=hp.Int('units', min_value=100, max_value=400, step=50),
                  connectivity=hp.Float('connectivity', min_value=0.1, max_value=0.4, step=0.1),
                  spectral_radius=hp.Float('spectral_radius', min_value=0.5, max_value=0.9, step=0.1),
                  activation=hp.Choice('activation_esn', ['relu', 'tanh', 'sigmoid']),
                  name='esn_layer'))
    if hp.Boolean("dropout"):
        model.add(Dropout(rate=hp.Float('rate', min_value=0.2, max_value=0.5, step=0.1)))

    for k in range(hp.Int("num_layers", 1, 2)):
        model.add(Dense(units=hp.Int(f'units_{k}', min_value=24, max_value=120, step=24),
                        activation=hp.Choice('activation_dense', ['relu', 'tanh', 'sigmoid']),
                        name=f'{k}_dense'))
    model.add(Dense(units=24,
                    activation=hp.Choice('activation_out', ['relu', 'tanh', 'sigmoid']),
                    name='output_layer'))
    model.compile(optimizer='adam',
                  loss='mean_squared_error')
    return model
</code>```

I can build the model, using build_model(keras_tuner.HyperParameters()), and i get:

```<code><keras.engine.sequential.Sequential at 0x21e9ae2e320>
</code>```

But when i try to start the search, this happens:

```<code>Search: Running Trial #1
Value             |Best Value So Far |Hyperparameter
150               |?                 |units
0.2               |?                 |connectivity
0.7               |?                 |spectral_radius
sigmoid           |?                 |activation_esn
True              |?                 |dropout
1                 |?                 |num_layers
96                |?                 |units_0
sigmoid           |?                 |activation_dense
tanh              |?                 |activation_out
Traceback (most recent call last):
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\keras_tuner\engine\tuner.py", line 158, in _try_build
    model = self._build_hypermodel(hp)
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\keras_tuner\engine\tuner.py", line 146, in _build_hypermodel
    model = self.hypermodel.build(hp)
  File "<ipython-input-11-40dc25714941>", line 5, in build_model
    model.add(ESN(units=hp.Int('units', min_value=100, max_value=400, step=50),
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\tensorflow\python\training\tracking\base.py", line 629, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\tensorflow_addons\rnn\esn_cell.py", line 159, in build
    self.recurrent_kernel = self.add_weight(
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\tensorflow_addons\rnn\esn_cell.py", line 151, in _esn_recurrent_initializer
    scaling_factor = tf.math.divide_no_nan(
ValueError: Tensor conversion requested dtype float64 for Tensor with dtype float32: <tf.Tensor: shape=(), dtype=float32, numpy=0.4704204>
Invalid model 0/5
</code>```

It tries 5 more times, and all fail. The ESN layer i am using here is from Tensorflow Addons. What i did wrong here?

Body:
Trying to use Keras Tuner to optimize my hyperparameters. I build the following model:

def build_model(hp):
    model = Sequential(name='ESN_NE')
    model.add(InputLayer((timesteps, input_dim), name='input_layer'))
    model.add(ESN(units=hp.Int('units', min_value=100, max_value=400, step=50),
                  connectivity=hp.Float('connectivity', min_value=0.1, max_value=0.4, step=0.1),
                  spectral_radius=hp.Float('spectral_radius', min_value=0.5, max_value=0.9, step=0.1),
                  activation=hp.Choice('activation_esn', ['relu', 'tanh', 'sigmoid']),
                  name='esn_layer'))
    if hp.Boolean("dropout"):
        model.add(Dropout(rate=hp.Float('rate', min_value=0.2, max_value=0.5, step=0.1)))

    for k in range(hp.Int("num_layers", 1, 2)):
        model.add(Dense(units=hp.Int(f'units_{k}', min_value=24, max_value=120, step=24),
                        activation=hp.Choice('activation_dense', ['relu', 'tanh', 'sigmoid']),
                        name=f'{k}_dense'))
    model.add(Dense(units=24,
                    activation=hp.Choice('activation_out', ['relu', 'tanh', 'sigmoid']),
                    name='output_layer'))
    model.compile(optimizer='adam',
                  loss='mean_squared_error')
    return model

I can build the model, using build_model(keras_tuner.HyperParameters()), and i get:

<keras.engine.sequential.Sequential at 0x21e9ae2e320>

But when i try to start the search, this happens:

Search: Running Trial #1
Value             |Best Value So Far |Hyperparameter
150               |?                 |units
0.2               |?                 |connectivity
0.7               |?                 |spectral_radius
sigmoid           |?                 |activation_esn
True              |?                 |dropout
1                 |?                 |num_layers
96                |?                 |units_0
sigmoid           |?                 |activation_dense
tanh              |?                 |activation_out
Traceback (most recent call last):
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\keras_tuner\engine\tuner.py", line 158, in _try_build
    model = self._build_hypermodel(hp)
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\keras_tuner\engine\tuner.py", line 146, in _build_hypermodel
    model = self.hypermodel.build(hp)
  File "<ipython-input-11-40dc25714941>", line 5, in build_model
    model.add(ESN(units=hp.Int('units', min_value=100, max_value=400, step=50),
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\tensorflow\python\training\tracking\base.py", line 629, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\tensorflow_addons\rnn\esn_cell.py", line 159, in build
    self.recurrent_kernel = self.add_weight(
  File "C:\Users\Muril\PycharmProjects\tf-gpu\venv\lib\site-packages\tensorflow_addons\rnn\esn_cell.py", line 151, in _esn_recurrent_initializer
    scaling_factor = tf.math.divide_no_nan(
ValueError: Tensor conversion requested dtype float64 for Tensor with dtype float32: <tf.Tensor: shape=(), dtype=float32, numpy=0.4704204>
Invalid model 0/5

It tries 5 more times, and all fail. The ESN layer i am using here is from Tensorflow Addons. What i did wrong here?


问:
what is the add to cart hook in woocommerce
I am working on woocommerce right now and I am testing few things ,
I need to retrieve the data of the user and the product that is added to the cart,
for example when the user add the product to the list ,execute a function that

```<code> <script type="text">
"user _id":'.get_current_user_id().',
"product_id":'.$product->get_id().',
"product_price":'.$product->get_price().',
"product_name":'.$product->get_name().',

</script>';
</code>```

but I don't know what is the correct hook to write it in the add_action(hook name,function name)

I tried the same thing when the user enter the product page and it is working well by the following code:

```<code>
add_action( 'woocommerce_single_product_summary','get_product_data');

function get_product_data() {
    global $product;
    global $current_user;
    echo '
        <script type="text/test" id="product_data">
        {
            "user":
            {
            "user_id":'.get_current_user_id().',
            "user_name":'.$current_user->user_login.',
            "user_email":'.$current_user->user_email.'
            },
            "product":
            {
            "product_id":'.$product->get_id().',
            "product_price":'.$product->get_price().',
            "product_name":'.$product->get_name().',
            "product_description":'.$product->get_description().',
            "product_type":'.$product->get_type().',
            "product_average_rating":'.$product->get_average_rating().',
            "product_parent_id":'.$product->get_parent_id().',
            "product_rating_count":'.$product->get_rating_count().',
            "product_review_count":'.$product->get_review_count().',
            "product_children":'.$product->get_children().',
            "product_image_source":'.$src.'
            }
        }
        </script>
        ';
}
</code>```

then I tried this to the add to cart:

```<code>add_action( 'woocommerce_add_to_cart',array($this, 'get_add_to_cart_product_data'));
function get_add_to_cart_product_data(){
        global $product;
        global $current_user;
        echo ' <script>  alert("the user '.$current_user->user_login.' added succesfully the '.$product->get_name().' product to the cart"); </script>';
}
</code>```

it displays the correct user but it don't access the product,it gives me an error : Uncaught Error: Call to a member function get_name() on null
that means it does not have access on the product like the 'woocommerce_single_product_summary' hook.

any idea it would help me to solve my problem thanks you

Body:
I am working on woocommerce right now and I am testing few things ,
I need to retrieve the data of the user and the product that is added to the cart,
for example when the user add the product to the list ,execute a function that

 ';

but I don't know what is the correct hook to write it in the add_action(hook name,function name)

I tried the same thing when the user enter the product page and it is working well by the following code:

add_action( 'woocommerce_single_product_summary','get_product_data');

function get_product_data() {
    global $product;
    global $current_user;
    echo '

        ';
}

then I tried this to the add to cart:

add_action( 'woocommerce_add_to_cart',array($this, 'get_add_to_cart_product_data'));
function get_add_to_cart_product_data(){
        global $product;
        global $current_user;
        echo ' ';
}

it displays the correct user but it don't access the product,it gives me an error : Uncaught Error: Call to a member function get_name() on null
that means it does not have access on the product like the 'woocommerce_single_product_summary' hook.

any idea it would help me to solve my problem thanks you


问:
How do I configure ssl to run correctly on docker
Last week, I created a self-signed SSL certificate and it only works on port 80 I then tried to replace it with a lets-encrypt certificate. I deleted all of the certificate files, I have tried to restart docker and the daemon. I have also tried to remove the override file that I tried to put the certificate in.
To create the self-signed SSL certificate, I used the following script
https://raw.githubusercontent.com/AlexisAhmed/DockerSecurityEssentials/main/Docker-TLS-Authentication/secure-docker-daemon.sh

For the override.conf file within /etc/systemd/system/docker.service.d/override.conf I used the following configuration:

```<code> [Service]ExecStart=ExecStart=/usr/bin/dockerd -D -H unix:///var/run/docker.sock  --tlsverify  --tlscert=/home/<user>/.docker/server-cert.pem --tlscacert=/home/<user>/.docker/ca.pem --tlskey=/home/<user>/.docker/server-key.pem  -H tcp://0.0.0.0:2376
</code>```

I have restarted the docker container but that has also failed to work.

Furthermore, I have also deleted the ssl certificate so I have no idea where it is pulling the old on from.

Body:
Last week, I created a self-signed SSL certificate and it only works on port 80 I then tried to replace it with a lets-encrypt certificate. I deleted all of the certificate files, I have tried to restart docker and the daemon. I have also tried to remove the override file that I tried to put the certificate in.
To create the self-signed SSL certificate, I used the following script
https://raw.githubusercontent.com/AlexisAhmed/DockerSecurityEssentials/main/Docker-TLS-Authentication/secure-docker-daemon.sh

For the override.conf file within /etc/systemd/system/docker.service.d/override.conf I used the following configuration:

 [Service]ExecStart=ExecStart=/usr/bin/dockerd -D -H unix:///var/run/docker.sock  --tlsverify  --tlscert=/home/<user>/.docker/server-cert.pem --tlscacert=/home/<user>/.docker/ca.pem --tlskey=/home/<user>/.docker/server-key.pem  -H tcp://0.0.0.0:2376

I have restarted the docker container but that has also failed to work.

Furthermore, I have also deleted the ssl certificate so I have no idea where it is pulling the old on from.


问:
Modify code so each snippets start from begin instead end
source : https://davidwalsh.name/video-preview#comment-515168

the part of code that trim videos into snippets :

```<code> # Loop and generate video snippets
    mkdir $tempdir
    interval=$(($length/$desiredsnippets-$starttimeseconds))
    for i in $(seq 1 $desiredsnippets)
    do
        # Format the second marks into hh:mm:ss format
        start=$(($(($i*$interval))+$starttimeseconds))
        formattedstart=$(printf "%02d:%02d:%02d\n" $(($start/3600)) $(($start%3600/60)) $(($start%60)))
        echo 'Generating preview part ' $i $formattedstart
        # Generate the snippet at calculated time
        ffmpeg -i $sourcefile -vf scale=$dimensions -preset fast -qmin 1 -qmax 1 -ss $formattedstart -t $snippetlengthinseconds -threads $(nproc) $tempdir/$i.mp4
    done
</code>```

`

Video length is 3600 (60mins)

Desired snippets = 30, that mean 2mins each

It always start at 0:02:00 to 0:04:00 -> and so on

but i want it start at 0:00:00 (1st snippet) -> 0:02:00 (2nd snippet) -> (this put in code because it said invalid code format)

I want to make it trim from start of each snippets instead end of each snippets.

This code trim video into multiple parts(snippets) that set by user, and then merged all snippets into one video.

Body:
source : https://davidwalsh.name/video-preview#comment-515168

the part of code that trim videos into snippets :

 # Loop and generate video snippets
    mkdir $tempdir
    interval=$(($length/$desiredsnippets-$starttimeseconds))
    for i in $(seq 1 $desiredsnippets)
    do
        # Format the second marks into hh:mm:ss format
        start=$(($(($i*$interval))+$starttimeseconds))
        formattedstart=$(printf "%02d:%02d:%02d\n" $(($start/3600)) $(($start%3600/60)) $(($start%60)))
        echo 'Generating preview part ' $i $formattedstart
        # Generate the snippet at calculated time
        ffmpeg -i $sourcefile -vf scale=$dimensions -preset fast -qmin 1 -qmax 1 -ss $formattedstart -t $snippetlengthinseconds -threads $(nproc) $tempdir/$i.mp4
    done

`

Video length is 3600 (60mins)

Desired snippets = 30, that mean 2mins each

It always start at 0:02:00 to 0:04:00 -> and so on

but i want it start at 0:00:00 (1st snippet) -> 0:02:00 (2nd snippet) -> (this put in code because it said invalid code format)

I want to make it trim from start of each snippets instead end of each snippets.

This code trim video into multiple parts(snippets) that set by user, and then merged all snippets into one video.


问:
Login per Local HTML form, security?
Recently I had problems with my email account (gmx.net). I have about 30 failed login attempts a day. But that is not the topic of the question (I already changed my password).

It got me thinking. Is this in automatic attack? And if so, how is it done? I took a look at the HTML code of the page and found out, that it is pretty easy to just copy the source code of the form element and do a login attempt through a local html file (copy and paste, new HTML file, open in browser, enter your credentials, submit). That means it is an easy task to automate such things (write a little script, that does a post with various values --> Brute Force attack). I was about to write an email to the mail hosted, when I found out, that the exact same process can be done on facebook.com....

I had the impression, that since we have all these new fancy web frameworks like Rails, Django and so on, we have an automatic protection against such attacks (for example the protect from forgery which Rails includes http://ruby.about.com/od/security/a/forgeryprotect.htm)

My question here is:

Is there any sane reason to allow a login attempt from another server?

Don't give me "API", the most APIs for web application require a manual login process before authorization.

I know there are many more ways to brute force attack any website login (use a framework that controls a browser etc...) and there are many ways to protect (IP-banning etc). But shouldn't disabling a remote login be one of the first security mechanisms you would take?

ContentLicense: CC BY-SA 3.0

Title: Login per Local HTML form, security?


问:
VBA Application defined or object-defied error 1004 for my .csv extracton data code
I'm trying to have a code that will get the table data from a .csv file and transfer it in a proper way to my Master working file, named "Meterd Monthly Data Colector". Basicaly to open.csv with Power Query function, process the data inside, and save it/paste it in my Master working file Inside this file i have e Sheet named "Input" in which i want the .csv data to be saved, when processed. But i have an issue with my code - i received the above mentioned Run-time error 1004 (so something is unknown i suppose) in .ListObject.DisplayName = "TSO Metered Data". But i can't quite get it what to do and to define the sheet named "TSO Metered Data" from the source file with the same name ( source file name "TSO Metered Data"; single sheet inside, named "TSO Metered Data").
Here is my code :

```<code>Sub PowerQueryTransform()

  Dim myWorkBook As Excel.Workbook
  Dim myWorkSheet As Excel.Worksheet

  Set myWorkBook = Application.Workbooks("Meterd Monthly Data Colector.xlsm")
  Set myWorkSheet = myWorkBook.Sheets("Input")
  myWorkSheet.Select

  ActiveWorkbook.Worksheets.Add
  With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=TSO Metered    Data;Extended Properties=""""" _
    , Destination:=Range("$A$1")).QueryTable
    .CommandType = xlCmdSql
    .CommandText = Array( _
    "SELECT * FROM [TSO Metered Data]")
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .ListObject.DisplayName = "TSO Metered Data"
    .Refresh BackgroundQuery:=False
 End With
 Range("A1").Select
 Windows("Meterd Monthly Data Colector.xlsm").Activate

End Sub
</code>```

Body:
I'm trying to have a code that will get the table data from a .csv file and transfer it in a proper way to my Master working file, named "Meterd Monthly Data Colector". Basicaly to open.csv with Power Query function, process the data inside, and save it/paste it in my Master working file Inside this file i have e Sheet named "Input" in which i want the .csv data to be saved, when processed. But i have an issue with my code - i received the above mentioned Run-time error 1004 (so something is unknown i suppose) in .ListObject.DisplayName = "TSO Metered Data". But i can't quite get it what to do and to define the sheet named "TSO Metered Data" from the source file with the same name ( source file name "TSO Metered Data"; single sheet inside, named "TSO Metered Data").
Here is my code :

Sub PowerQueryTransform()

  Dim myWorkBook As Excel.Workbook
  Dim myWorkSheet As Excel.Worksheet

  Set myWorkBook = Application.Workbooks("Meterd Monthly Data Colector.xlsm")
  Set myWorkSheet = myWorkBook.Sheets("Input")
  myWorkSheet.Select

  ActiveWorkbook.Worksheets.Add
  With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=TSO Metered    Data;Extended Properties=""""" _
    , Destination:=Range("$A$1")).QueryTable
    .CommandType = xlCmdSql
    .CommandText = Array( _
    "SELECT * FROM [TSO Metered Data]")
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .ListObject.DisplayName = "TSO Metered Data"
    .Refresh BackgroundQuery:=False
 End With
 Range("A1").Select
 Windows("Meterd Monthly Data Colector.xlsm").Activate

End Sub


问:
Python compare value and leave loop
Good afternoon.
How do I access the result of take_name_res_list at the end of the string if I only get the last result.</p>

Title: Python compare value and leave loop


问:
how do i label my bar graph by using xticks
bar graph
code

Hi ,may i ask how do label all the years in data5_year,under every bar graph


问:
'pyrcc5' is not recognized as an internal or external command Anaconda
I'm currently trying to install LabelImg to work on a computer vision project to label photos, I am using Anaconda to download LabelImg and I am following the documentation on the GitHub page https://github.com/heartexlabs/labelImg#labelimg .

everything was going well until I tried to run:

```<code>pyrcc5 -o libs/resources.py resources.qrc
</code>```

it showed me this error message:

```<code>'pyrcc5' is not recognized as an internal or external command
</code>```

PS: I am running this code in the same directory of LabelImg using Anaconda Prompt

Body:
I'm currently trying to install LabelImg to work on a computer vision project to label photos, I am using Anaconda to download LabelImg and I am following the documentation on the GitHub page https://github.com/heartexlabs/labelImg#labelimg .

everything was going well until I tried to run:

pyrcc5 -o libs/resources.py resources.qrc

it showed me this error message:

'pyrcc5' is not recognized as an internal or external command

PS: I am running this code in the same directory of LabelImg using Anaconda Prompt


问:
Is is possible to show the service logs of only running Docker Swarm containers?
Currently the docker service logs command shows logs of all services, also the ones that already terminated. The logs are not guaranteed to be displayed in chronological order.
Is it possible to somehow hide the logs of containers which have been terminated?

The problem is that after doing
docker service update --force my_service
the docker service logs command shows logs which are sorted by the time and service name, and the logs from newly started containers may appear before the logs from the terminated containers.


问:
Localize constants not updating properly even after relaunch app?
I have app level language change option (English & Greek) in my app settings irrespective of device language.

App default language is English.

When I change the app language into Greek and re-launch the app some of the strings are not changing into Greek, but when I do the same in English it is working fine. When I re-launch the twice like that all words are changing into the Greek, but not in single re-launch.

How to resolve this language change issue?

We are using RKLocalization from GitHub.


问:
Create a transaction between google cloud storage and database (Asp dotnet core)
I am using google cloud storage with dotnet core 6 to create item with attachments, where saving the attachments in google cloud storage.
On deleting any item, I want to delete its related attachments and make sure that they are deleted from GCS, and in case of exception I want to rollback everything.

```<code>        public async Task<ItemModel> Delete(ItemId id)
        {
            ItemModel item = await this.repository.Get(id);
            DbItem itemToRemove = item.ToDbModel();

            await this.repository.Delete(itemToRemove);
            await this.repository.DeleteAttachments(itemToRemove.Attachments);

            return item;
        }
</code>```

In case that DeleteAttachments() function fails or throw exception, I want to rollback the actions I did in the previous function and leave the database intact, otherwise, it should work normally.

Is there any way to make a transaction that does this functionality or any logic to prevent the attachments from staying in gcs in case of failure ?

Body:
I am using google cloud storage with dotnet core 6 to create item with attachments, where saving the attachments in google cloud storage.
On deleting any item, I want to delete its related attachments and make sure that they are deleted from GCS, and in case of exception I want to rollback everything.

        public async Task<ItemModel> Delete(ItemId id)
        {
            ItemModel item = await this.repository.Get(id);
            DbItem itemToRemove = item.ToDbModel();

            await this.repository.Delete(itemToRemove);
            await this.repository.DeleteAttachments(itemToRemove.Attachments);

            return item;
        }

In case that DeleteAttachments() function fails or throw exception, I want to rollback the actions I did in the previous function and leave the database intact, otherwise, it should work normally.

Is there any way to make a transaction that does this functionality or any logic to prevent the attachments from staying in gcs in case of failure ?


Title: Why can't colab run tensorflow 1.14.0 version anymore?

Body:
I tried running...

!pip install tensorflow==1.14.0

I tried different ways to do so.

%tensorflow_version 1.x
!pip uninstall -y tensorflow
!pip install tensorflow-gpu==1.14.0

ValueError: Tensorflow 1 is unsupported in Colab.

Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/

ERROR: Could not find a version that satisfies the requirement tensorflow==1.14 (from versions: 2.2.0, 2.2.1, 2.2.2, 2.2.3, 2.3.0, 2.3.1, 2.3.2, 2.3.3, 2.3.4, 2.4.0, 2.4.1, 2.4.2, 2.4.3, 2.4.4, 2.5.0, 2.5.1, 2.5.2, 2.5.3, 2.6.0rc0, 2.6.0rc1, 2.6.0rc2, 2.6.0, 2.6.1, 2.6.2, 2.6.3, 2.6.4, 2.6.5, 2.7.0rc0, 2.7.0rc1, 2.7.0, 2.7.1, 2.7.2, 2.7.3, 2.7.4, 2.8.0rc0, 2.8.0rc1, 2.8.0, 2.8.1, 2.8.2, 2.8.3, 2.8.4, 2.9.0rc0, 2.9.0rc1, 2.9.0rc2, 2.9.0, 2.9.1, 2.9.2, 2.9.3, 2.10.0rc0, 2.10.0rc1, 2.10.0rc2, 2.10.0rc3, 2.10.0, 2.10.1, 2.11.0rc0, 2.11.0rc1, 2.11.0rc2, 2.11.0)
ERROR: No matching distribution found for tensorflow==1.14


问:
select2 ajax not firing on space input
I'm using select2 (v4.0.12) with Ajax (remote data) in asp.net core mvc web app. Remote data returns clients (name + surname) and they all contain a space between name and surname.

Everything works great except when a user inputs an empty space. Then the search event is not firing and there is a JS error in the browser Uncaught TypeError: i._removeOldTags is not a function.

I tried setting the tags and multiple to false, but it doesn't help. Is there a setting I'm missing?

The setup is pretty basic:

html select control:

<select class="form-control" id="ddlClients">
    <option value="0">... select client ...</option>
</select>
```
<p>javascript:</p>
<pre class="lang-js prettyprint-override"><code>$("#ddlClients").select2({
    tags: false,
    multiple: false,
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    language: {
        inputTooShort: function () {
        return 'Enter min 2 chars...';
    }
},
ajax: {
    url: '/MyController/GetClientsData',
    dataType: "json",
    type: "GET",
    data: function (params) {
    var queryParameters = {
        term: params.term
        }
        return queryParameters;
        },
    processResults: function (data) {
        return {
        results: $.map(data, function (item) {
        return {
        text: item.text,
        id: item.id
        }
    })
    };
    }
    }
});
</code>```

c# (controller)

public IActionResult GetClientsData(string term)
{
var result = GetDataFromMyDb(term)
    .Select(x => new
    {
        id = x.Value,
        text = x.Text,
    })
    .ToList();

    return Json(result);
}
```

Title: select2 ajax not firing on space input

Body:
I'm using select2 (v4.0.12) with Ajax (remote data) in asp.net core mvc web app. Remote data returns clients (name + surname) and they all contain a space between name and surname.

Everything works great except when a user inputs an empty space. Then the search event is not firing and there is a JS error in the browser Uncaught TypeError: i._removeOldTags is not a function.

I tried setting the tags and multiple to false, but it doesn't help. Is there a setting I'm missing?

The setup is pretty basic:

html select control:

<select class="form-control" id="ddlClients">
    <option value="0">... select client ...</option>
</select>

javascript:

$("#ddlClients").select2({
    tags: false,
    multiple: false,
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    language: {
        inputTooShort: function () {
        return 'Enter min 2 chars...';
    }
},
ajax: {
    url: '/MyController/GetClientsData',
    dataType: "json",
    type: "GET",
    data: function (params) {
    var queryParameters = {
        term: params.term
        }
        return queryParameters;
        },
    processResults: function (data) {
        return {
        results: $.map(data, function (item) {
        return {
        text: item.text,
        id: item.id
        }
    })
    };
    }
    }
});

c# (controller)

public IActionResult GetClientsData(string term)
{
var result = GetDataFromMyDb(term)
    .Select(x => new
    {
        id = x.Value,
        text = x.Text,
    })
    .ToList();

    return Json(result);
}


问:
How to create vertical container, with 3d filling effect
I am trying to create something like this in flutter:

Image 1 -
Image 2

The two main aspects are:

the filled part of the vertical container has this elipse with darker color on the top, which gives the 3d depth effect

on Image 2 there is that % indicator, moving accordingly

What I have tried is:

tried to modify different progress_indicator packages, so that to achieve the 2 things above. However, I was never able to do that 3d depth effect.

tried to implement it as 2 expanded containers, where the flex of the bottom one represents the persentage. However again I was not able to do the elipse on the top.

From my searches online, it looks like I need to use the CustomPaint class, but it look very complicated.

If you have any better suggestions, or ever code pieces that can help, I would be extremely thankful !


问:
Vercel cannot find static files from node_modules in NextJS
I have a simple NextJS API page which just fetches a JSON file from one of the node_modules and shows the content at http://localhost:3000/api/my-json. This is the code:

```<code>// Path: /pages/api/my-json.ts
import type { NextApiRequest, NextApiResponse } from "next";
import path from "path";
import { promises as fs } from "fs";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  //Find the absolute path of the json directory
  const jsonLocation = path.join(
    process.cwd(),
    "node_modules/@my-company/my-package/lib/my-json-file.json"
  );
  //Read the json data file data.json
  const fileContents = await fs.readFile(jsonLocation, "utf8");
  //Return the content of the data file in json format
  res.status(200).json(fileContents);
}
</code>```

It works fine in dev mode, also works when building a production NextJS app by running:

yarn install

yarn build

yarn start

But when I upload the code to Vercel, the app is unable to find the json file, and my page https://my-app.vercel.app/api/my-json returns 500 error:

```<code>2022-12-12T10:25:14.142Z    04b6a8fe-53f7-46b6-8c49-98dadf358eb3    ERROR   [Error: ENOENT: no such file or directory, open '/var/task/node_modules/@my-company/my-package/lib/my-json-file.json'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/var/task/node_modules/@my-company/my-package/lib/my-json-file.json'
}
</code>```

Somebody had this problem before? Do I need to copy that JSON file manually somehow during Vercel deployment? How comes it works on local builds but not on Vercel?

Body:
I have a simple NextJS API page which just fetches a JSON file from one of the node_modules and shows the content at http://localhost:3000/api/my-json. This is the code:

// Path: /pages/api/my-json.ts
import type { NextApiRequest, NextApiResponse } from "next";
import path from "path";
import { promises as fs } from "fs";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  //Find the absolute path of the json directory
  const jsonLocation = path.join(
    process.cwd(),
    "node_modules/@my-company/my-package/lib/my-json-file.json"
  );
  //Read the json data file data.json
  const fileContents = await fs.readFile(jsonLocation, "utf8");
  //Return the content of the data file in json format
  res.status(200).json(fileContents);
}

It works fine in dev mode, also works when building a production NextJS app by running:

yarn install

yarn build

yarn start

But when I upload the code to Vercel, the app is unable to find the json file, and my page https://my-app.vercel.app/api/my-json returns 500 error:

2022-12-12T10:25:14.142Z    04b6a8fe-53f7-46b6-8c49-98dadf358eb3    ERROR   [Error: ENOENT: no such file or directory, open '/var/task/node_modules/@my-company/my-package/lib/my-json-file.json'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/var/task/node_modules/@my-company/my-package/lib/my-json-file.json'
}

Somebody had this problem before? Do I need to copy that JSON file manually somehow during Vercel deployment? How comes it works on local builds but not on Vercel?


问:
Rapidminer FP-Growth Preparation
Salutations. I have trouble with preparing data for FP-Growth algorithm. I have Integer attribute like age and real value attributes like pulse and temperature. What should I do with these values? Filter them out or turn into Binomials?

Title: Rapidminer FP-Growth Preparation


问:
LeaveOneGroupOut split(): question on parameters
Please have a look at the page:
https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.LeaveOneGroupOut.html

The method get_n_splits([X, y, groups]) has three parameters but it only uses the groups parameter, X and y are ignored, as clearly stated.

Consider now the method split(X, y=None, groups=None):

it does not ignore X and y: why ?

groups can be None: why ? Isn't it the only parameter needed?

why is X required? How would it split the data when called as follows: split(X=whatever, y=None, groups=None)?


问:
model not converged when fitting SAIGE null model
When I fitted the null model in SAIGE step2 of single-variant test, it showed like following:

seqFitNullGLMM_SPA(pheno~age+sex, phenotye, grm, trait.type="quantitative", sample.col="IID", maf=0.005, missing.rate=0.01)

```<code>Filtering variants:
[==================================================] 100%, completed, 10s
Fit the null model: pheno ~ age + sex + var(GRM)
    # of samples: 10,033
    # of variants: 40,739
    using 1 thread
Transform on the design matrix with QR decomposition:
    new formula: y ~ x0 + x1 + x2 - 1
Start loading SNP genotypes:
[==================================================] 100%, completed, 13s
    using 590.1M (sparse matrix)
Quantitative outcome: pheno
         mean         sd  min  max
    0.2772192 0.05953586 0.05 1.04
Inverse normal transformation on residuals with standard deviation: 0.05748074
Initial fixed-effect coefficients:
               x0           x1           x2
    -5.064086e-09 8.959324e-05 0.0003868113
Initial variance component estimates, tau:
    Sigma_E: 0.00165196, Sigma_G: 0.00165196
Iteration 1:
    tau: (0.001737522, 0.001646519)
    fixed coeff: (-5.064086e-09, 8.959324e-05, 0.0003868113)
    tau: (0, 0)
Error in seqFitNullGLMM_SPA(pheno ~ age + sex,  :
  Sigma_E = 0, model not converged!
</code>```

Does anyone have any idea about this issue? By the way, the phenotype and covariates data are clean without any outlier. Is it related to the SNPs for grm?

I just wish to solve this "not converged" problem. Thanks in advance!

Body:
When I fitted the null model in SAIGE step2 of single-variant test, it showed like following:

seqFitNullGLMM_SPA(pheno~age+sex, phenotye, grm, trait.type="quantitative", sample.col="IID", maf=0.005, missing.rate=0.01)

Filtering variants:
[==================================================] 100%, completed, 10s
Fit the null model: pheno ~ age + sex + var(GRM)
    # of samples: 10,033
    # of variants: 40,739
    using 1 thread
Transform on the design matrix with QR decomposition:
    new formula: y ~ x0 + x1 + x2 - 1
Start loading SNP genotypes:
[==================================================] 100%, completed, 13s
    using 590.1M (sparse matrix)
Quantitative outcome: pheno
         mean         sd  min  max
    0.2772192 0.05953586 0.05 1.04
Inverse normal transformation on residuals with standard deviation: 0.05748074
Initial fixed-effect coefficients:
               x0           x1           x2
    -5.064086e-09 8.959324e-05 0.0003868113
Initial variance component estimates, tau:
    Sigma_E: 0.00165196, Sigma_G: 0.00165196
Iteration 1:
    tau: (0.001737522, 0.001646519)
    fixed coeff: (-5.064086e-09, 8.959324e-05, 0.0003868113)
    tau: (0, 0)
Error in seqFitNullGLMM_SPA(pheno ~ age + sex,  :
  Sigma_E = 0, model not converged!

Does anyone have any idea about this issue? By the way, the phenotype and covariates data are clean without any outlier. Is it related to the SNPs for grm?

I just wish to solve this "not converged" problem. Thanks in advance!