问:
Trendline Chart JS Plugin not displayed in Symfony with Webpack
I'm using Chart JS with Symfony UX (composer req symfony/ux-chartjs). I added the plugin chartjs-plugin-trendline.
I load the plugin in my app.js file with

```<code>    import Chart from 'chart.js';
    import chartTrendline from 'chartjs-plugin-trendline';
    Chart.plugins.register(chartTrendline);
</code>```

and compile it.
Then I create my chart in Controller.php like this

```<code>    $stock_changes_per_day_chart->setData([
     'labels' => $stock_changes_per_day_day,
     'datasets' => [
      [
       'label' => 'Number of Stock Changes per Day (last '.$days.' Days)',
       'backgroundColor' => '#FF6384',
       'borderColor' => '#FF6384',
       'data' => $stock_changes_per_day_number,
       'trendlineLinear' => [
        'colorMin' => "red",
        'colorMax' => "green",
        'lineStyle' => "dotted",
        'width' => 2
       ]
      ],
    ]);
    $stock_changes_per_day_chart->setOptions([
     'responsive' => true,
     'maintainAspectRatio' => false,
    ]);
</code>```

Can anybody imagine why the trendline is not displayed in my frontend?
What configuration am I missing?
Thanks!

Body:
I'm using Chart JS with Symfony UX (composer req symfony/ux-chartjs). I added the plugin chartjs-plugin-trendline.
I load the plugin in my app.js file with

    import Chart from 'chart.js';
    import chartTrendline from 'chartjs-plugin-trendline';
    Chart.plugins.register(chartTrendline);

and compile it.
Then I create my chart in Controller.php like this

    $stock_changes_per_day_chart->setData([
     'labels' => $stock_changes_per_day_day,
     'datasets' => [
      [
       'label' => 'Number of Stock Changes per Day (last '.$days.' Days)',
       'backgroundColor' => '#FF6384',
       'borderColor' => '#FF6384',
       'data' => $stock_changes_per_day_number,
       'trendlineLinear' => [
        'colorMin' => "red",
        'colorMax' => "green",
        'lineStyle' => "dotted",
        'width' => 2
       ]
      ],
    ]);
    $stock_changes_per_day_chart->setOptions([
     'responsive' => true,
     'maintainAspectRatio' => false,
    ]);

Can anybody imagine why the trendline is not displayed in my frontend?
What configuration am I missing?
Thanks!


来源: stackexchange

问:
Move page title from content area to page header in WordPress
I would like to put the page title in the page header (next to the site title) but I can't find what file(s) I'm supposed to edit or what how I should edit them. I found some answers but they're from 2015 and I don't think that they're still relevant. I am just starting to learn Php so it is a bit hard to understand which file does what, specially when I see that there are several header files. Does someone know how to move page title ?

Thanks :)

ContentLicense: CC BY-SA 4.0


问:
Gulp - SASS task not compiling scss files
I start gulp task

```<code>ondrej@vostro-ov:~/o2kna/okna$ gulp
[09:34:23] Using gulpfile ~/o2kna/okna/gulpfile.js
[09:34:23] Starting 'default'...
[09:34:23] Starting 'styles'...
[09:34:23] No files matched your Sass source.
[09:34:23] Finished 'styles' after 15 ms
[09:34:23] Starting 'connect-sync'...
PHP 7.2.24-0ubuntu0.18.04.15 Development Server started at Tue Dec 20 09:34:23 2022
Listening on http://127.0.0.1:8000
Document root is /home/ondrej/o2kna/okna
Press Ctrl-C to quit.
[Tue Dec 20 09:34:23 2022] 127.0.0.1:54122 [404]: / - No such file or directory
[Browsersync] Proxying: http://okna.loc
[Browsersync] Access URLs:
--------------------------------------
Local: http://localhost:3000
External: http://192.168.1.120:3000
--------------------------------------
UI: http://localhost:3001
UI External: http://localhost:3001
--------------------------------------
[Browsersync] Couldn't open browser (if you are using BrowserSync in a headless environment, you might want to set the open option to false)
</code>```

From gulpfile.js

```<code>var gulp = require('gulp'),
autoprefixer = require('gulp-autoprefixer'),
sourcemaps = require('gulp-sourcemaps'),
connect = require('gulp-connect-php'),
sass = require('gulp-ruby-sass'),
browserSync = require('browser-sync');

var output = './css';
var autoprefixerOptions = {
  browsers: ['last 2 versions']
};
gulp.task('styles', function () {
  return sass('/www/styles/frontModule/scss/index.scss', { style: 'compressed', sourcemap:true })
    .pipe(sourcemaps.init())
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(sourcemaps.write())
    .pipe(sourcemaps.write('maps', {
       includeContent: false,
       sourceRoot: 'source'
    }))
    .pipe(gulp.dest(output))
    .pipe(browserSync.stream({ match: '**/*.css' }));
});

gulp.task('connect-sync', function () {
  connect.server({}, function () {
    browserSync({
      proxy: 'okna.loc'
    });
  });
});

gulp.task('watch', function () {
  gulp.watch("/www/styles/frontModule/scss/**", ['styles']);
  gulp.watch(['js/**/*.js', '*.html', '**/*.php']).on('change', browserSync.reload);
});

gulp.task('default', gulp.series('styles', 'connect-sync', function () {
  gulp.start('watch');
}));
</code>```

File package.json

```<code>{
  "name": "guwii gulp",
  "version": "1.0",
  "description": "guwii's quick gulp setup",
  "author": "guwii",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo 'Error: no test specified' && exit 1"
  },
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.24.5",
    "gulp-autoprefixer": "^5.0.0",
    "gulp-sourcemaps": "^2.6.4"
  },
  "dependencies": {
    "gulp": "^3.9.1",
    "gulp-connect-php": "^1.0.3",
    "gulp-ruby-sass": "^4.0.0"
  }
}
</code>```

Folder and files structure in project have

root

www

styles

frontModule

scss

index.scss

gulpfile.js

I do not know where is error, but alert "No files matched your Sass source." is not correctly.

When I change "index.scss" file does not compile to css.

Gulp file I use from https://guwii.com/bytes/best-simple-gulp-setup-sass-browsersync-local-server/

Can any ideas what is wrong?
Thanks

Body:
I start gulp task

ondrej@vostro-ov:~/o2kna/okna$ gulp
[09:34:23] Using gulpfile ~/o2kna/okna/gulpfile.js
[09:34:23] Starting 'default'...
[09:34:23] Starting 'styles'...
[09:34:23] No files matched your Sass source.
[09:34:23] Finished 'styles' after 15 ms
[09:34:23] Starting 'connect-sync'...
PHP 7.2.24-0ubuntu0.18.04.15 Development Server started at Tue Dec 20 09:34:23 2022
Listening on http://127.0.0.1:8000
Document root is /home/ondrej/o2kna/okna
Press Ctrl-C to quit.
[Tue Dec 20 09:34:23 2022] 127.0.0.1:54122 [404]: / - No such file or directory
[Browsersync] Proxying: http://okna.loc
[Browsersync] Access URLs:
--------------------------------------
Local: http://localhost:3000
External: http://192.168.1.120:3000
--------------------------------------
UI: http://localhost:3001
UI External: http://localhost:3001
--------------------------------------
[Browsersync] Couldn't open browser (if you are using BrowserSync in a headless environment, you might want to set the open option to false)

From gulpfile.js

var gulp = require('gulp'),
autoprefixer = require('gulp-autoprefixer'),
sourcemaps = require('gulp-sourcemaps'),
connect = require('gulp-connect-php'),
sass = require('gulp-ruby-sass'),
browserSync = require('browser-sync');

var output = './css';
var autoprefixerOptions = {
  browsers: ['last 2 versions']
};
gulp.task('styles', function () {
  return sass('/www/styles/frontModule/scss/index.scss', { style: 'compressed', sourcemap:true })
    .pipe(sourcemaps.init())
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(sourcemaps.write())
    .pipe(sourcemaps.write('maps', {
       includeContent: false,
       sourceRoot: 'source'
    }))
    .pipe(gulp.dest(output))
    .pipe(browserSync.stream({ match: '**/*.css' }));
});

gulp.task('connect-sync', function () {
  connect.server({}, function () {
    browserSync({
      proxy: 'okna.loc'
    });
  });
});

gulp.task('watch', function () {
  gulp.watch("/www/styles/frontModule/scss/**", ['styles']);
  gulp.watch(['js/**/*.js', '*.html', '**/*.php']).on('change', browserSync.reload);
});

gulp.task('default', gulp.series('styles', 'connect-sync', function () {
  gulp.start('watch');
}));

File package.json

{
  "name": "guwii gulp",
  "version": "1.0",
  "description": "guwii's quick gulp setup",
  "author": "guwii",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo 'Error: no test specified' && exit 1"
  },
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.24.5",
    "gulp-autoprefixer": "^5.0.0",
    "gulp-sourcemaps": "^2.6.4"
  },
  "dependencies": {
    "gulp": "^3.9.1",
    "gulp-connect-php": "^1.0.3",
    "gulp-ruby-sass": "^4.0.0"
  }
}

Folder and files structure in project have

root

www

styles

frontModule

scss

index.scss

gulpfile.js

I do not know where is error, but alert "No files matched your Sass source." is not correctly.

When I change "index.scss" file does not compile to css.

Gulp file I use from https://guwii.com/bytes/best-simple-gulp-setup-sass-browsersync-local-server/

Can any ideas what is wrong?
Thanks


问:
Webpack won't work while trying to build on multiple domain
We are running a Rails 6.1.7 and we want to duplicate our website, while using a new domain and set for it a dedicated theme.scss

In order to have the proper URL being used to load assets we set this in config file:

```<code>  config.action_controller.asset_host = Proc.new do |source, request|
    if source && request && request.ssl?
      "#{request.protocol}#{request.host_with_port}"
    else
      "www.test.local:4000"
    end
  end
</code>```

And it works until Webpack need to build after we changed any JS or CSS files.

Once I changed files (CSS or JS) I have an error I don't explain much:

```<code>Showing /app/views/layouts/index.erb where line #44 raised:

undefined method `host' for nil:NilClass

Extracted source (around line #53):
51  config.action_controller.default_asset_host = "www.test.local:4000"
52
53 config.action_controller.asset_host = Proc.new do |source, request|
54 if source && request && request.ssl?
55  "#{request.protocol}#{request.host_with_port}"
56 else
</code>```

We have for index.erb

```<code>43    <%= stylesheet_pack_tag 'frontend', media: 'all', 'data-turbolinks-track': 'reload' %>
44    <%= javascript_pack_tag 'frontend', 'data-turbolinks-track': 'reload' %>
45    <%= javascript_include_tag "translations", skip_pipeline: true %>
</code>```

So what is going wrong here? Any help would be much appreciate!

Body:
We are running a Rails 6.1.7 and we want to duplicate our website, while using a new domain and set for it a dedicated theme.scss

In order to have the proper URL being used to load assets we set this in config file:

  config.action_controller.asset_host = Proc.new do |source, request|
    if source && request && request.ssl?
      "#{request.protocol}#{request.host_with_port}"
    else
      "www.test.local:4000"
    end
  end

And it works until Webpack need to build after we changed any JS or CSS files.

Once I changed files (CSS or JS) I have an error I don't explain much:

Showing /app/views/layouts/index.erb where line #44 raised:

undefined method `host' for nil:NilClass

Extracted source (around line #53):
51  config.action_controller.default_asset_host = "www.test.local:4000"
52
53 config.action_controller.asset_host = Proc.new do |source, request|
54 if source && request && request.ssl?
55  "#{request.protocol}#{request.host_with_port}"
56 else

We have for index.erb

43    <%= stylesheet_pack_tag 'frontend', media: 'all', 'data-turbolinks-track': 'reload' %>
44    <%= javascript_pack_tag 'frontend', 'data-turbolinks-track': 'reload' %>
45    <%= javascript_include_tag "translations", skip_pipeline: true %>

So what is going wrong here? Any help would be much appreciate!


问:
Adding scenario on existing dataframe
I am implementing a scenario based two stage stochastic programming model in gurobi. I am trying to add scenarios on my existing cost data. But I couldn't get the result I need.

```<code>import pandas as pd

cost = pd.read_excel('costdata.xlsx', index_col = 0)

# Getting list of customer zones
J = list(cost.columns)

# Getting list of warehouses
I = list(cost.index)

# Average cost
c = {}
for i in I:
    for j in J:
        c[i,j] = cost.loc[i,j]

S = ['s1', 's2', 's3'] # Number of scenarios
p = {'s1': 0.2, 's2': 0.35, 's3': 0.45} # Probability each scenario

## Cost determination in all scenarios

#Cost increases by 5% in the first scenario
#Cost increases by 10% in the second scenario
#Cost increases by 15% in the third scenario

c_s = {}
for i in I:
    for j in J:
        for s in S:
            c_s[i,j,s] = ? # I got difficulty in converting the average cost data to scenario based values
</code>```

My sample excel data is:
sampledata

And I would like to get data that is similar to;
expecteddata

Title: Adding scenario on existing dataframe

Body:
I am implementing a scenario based two stage stochastic programming model in gurobi. I am trying to add scenarios on my existing cost data. But I couldn't get the result I need.

import pandas as pd

cost = pd.read_excel('costdata.xlsx', index_col = 0)

# Getting list of customer zones
J = list(cost.columns)

# Getting list of warehouses
I = list(cost.index)

# Average cost
c = {}
for i in I:
    for j in J:
        c[i,j] = cost.loc[i,j]

S = ['s1', 's2', 's3'] # Number of scenarios
p = {'s1': 0.2, 's2': 0.35, 's3': 0.45} # Probability each scenario

## Cost determination in all scenarios

#Cost increases by 5% in the first scenario
#Cost increases by 10% in the second scenario
#Cost increases by 15% in the third scenario

c_s = {}
for i in I:
    for j in J:
        for s in S:
            c_s[i,j,s] = ? # I got difficulty in converting the average cost data to scenario based values

My sample excel data is:
sampledata

And I would like to get data that is similar to;
expecteddata


问:
Best way to structure the model in Svelte
This is a general question. I'm not sure it has the same answer in all different cases that can come up, so my question is if that's the case (if this can be seen a general guideline to how to structure data in a Svelte app).

Imagine I have nested data like this in my app (the relevant thing here being that the data is nested (object in an array in an object in an array, etc.)):

const appState = {
    fileSystems: [{
        name: "Main File System",
        folders: [{
            name: "first-folder",
            files: [{
                name: "file-a.txt",
            }, {
                // More files...
            }],
        }, {
            // More folders...
        }]
    }, {
        // More file systems...
    }]
}
```
<p>That's how I would store the data in Vue. And <code>App.vue</code> would list all <code>fileSystems</code> and show the selected one in <code>FileSystem.vue</code>, which list all <code>folders</code> in the selected file system and show the selected folder in <code>Folder.vue</code>, which list all <code>files</code> in the selected folder, etc. That's what I'm used to.</p>
<p>But the way updates are handled in Svelte is that when I update one thing deep down in the nested data, Svelte updates everything, since it just keep track of changes made to variables/stores, not individual objects/arrays/properties. So if I deep down in the component hierarchy has an operation like *Move file to a new file system", that would add a new file system object to <code>appState.fileSystems</code>, then all the GUI would be updated. That's correct, right?</p>
<p>To avoid that, the recommendation is usually to use separate variables/stores, instead of "grouping" them in objects (right?). Well, with this nested data, that's not possible, since it's nested. But, I'm thinking I can structure the data the same way as in a relational database:</p>
<pre class="lang-js prettyprint-override"><code>const appState = {
    fileSystems: [{
        id: 1,
        name: "Main File System",
    }, {
        // More file systems...
    }],
    folders: [{
        id: 1,
        fileSystemId: 1,
        name: "first-folder",
    }, {
       // More folders...
    }]
    files: [{
        id: 1,
        folderId: 1,
        name: "file-a.txt",
    }, {
        // More files...
    }],
}
</code>```

Voila! Now we can put fileSystems in one variable/store, folders in one variable/store, and files in one variable/store, and then, for example, do filtering to only obtain the files in a specific folder, and this can lead to Svelte doing smarter/smaller GUI updates when something changes. For example, when updating a file object, that should not update the GUI parts using only file system objects.

So, my question is: is the second strategy really better than the first one? Will it lead to Svelte doing smaller GUI updates when some data changes in practice? Or will it usually depend on how it's being used, and only better in some specific situations?

Body:
This is a general question. I'm not sure it has the same answer in all different cases that can come up, so my question is if that's the case (if this can be seen a general guideline to how to structure data in a Svelte app).

Imagine I have nested data like this in my app (the relevant thing here being that the data is nested (object in an array in an object in an array, etc.)):

const appState = {
    fileSystems: [{
        name: "Main File System",
        folders: [{
            name: "first-folder",
            files: [{
                name: "file-a.txt",
            }, {
                // More files...
            }],
        }, {
            // More folders...
        }]
    }, {
        // More file systems...
    }]
}

That's how I would store the data in Vue. And App.vue would list all fileSystems and show the selected one in FileSystem.vue, which list all folders in the selected file system and show the selected folder in Folder.vue, which list all files in the selected folder, etc. That's what I'm used to.

But the way updates are handled in Svelte is that when I update one thing deep down in the nested data, Svelte updates everything, since it just keep track of changes made to variables/stores, not individual objects/arrays/properties. So if I deep down in the component hierarchy has an operation like *Move file to a new file system", that would add a new file system object to appState.fileSystems, then all the GUI would be updated. That's correct, right?

To avoid that, the recommendation is usually to use separate variables/stores, instead of "grouping" them in objects (right?). Well, with this nested data, that's not possible, since it's nested. But, I'm thinking I can structure the data the same way as in a relational database:

const appState = {
    fileSystems: [{
        id: 1,
        name: "Main File System",
    }, {
        // More file systems...
    }],
    folders: [{
        id: 1,
        fileSystemId: 1,
        name: "first-folder",
    }, {
       // More folders...
    }]
    files: [{
        id: 1,
        folderId: 1,
        name: "file-a.txt",
    }, {
        // More files...
    }],
}

Voila! Now we can put fileSystems in one variable/store, folders in one variable/store, and files in one variable/store, and then, for example, do filtering to only obtain the files in a specific folder, and this can lead to Svelte doing smarter/smaller GUI updates when something changes. For example, when updating a file object, that should not update the GUI parts using only file system objects.

So, my question is: is the second strategy really better than the first one? Will it lead to Svelte doing smaller GUI updates when some data changes in practice? Or will it usually depend on how it's being used, and only better in some specific situations?


问:
css z-index lost with transform: rotateX on safari
i made this flipbook animation that works well on chrome to me.
https://jsfiddle.net/qjnhdavw/
If you open it with safari, as you can see, it doesn't work well.

After some tests, I have seen that only on safari, the cover11 element loses the priority given to it by the z-index.
This happen because of transform: rotateX(10deg); that I put in each element. If I remove this, the problem does not persist:
https://jsfiddle.net/epjfbyax/

As you can see the first option is good on chrome but doesn't work on safari, the second option
is good on safari but not so much on chrome.

This is the CSS of the first link:

```<code>.zone11{
   height: 700px;
    display: flex;
    align-items: center;
    justify-content: center;
    perspective: 1000px;
}

.book11{
    display: flex;
    align-items: center;
    cursor: pointer;
}

.cover11{
    z-index: 1;
    transition: all 3.5s;
}

.back-cover11{
    z-index: -3;
}

.cover11, .back-cover11{
    height: 450px;
    width: 360px;
    background: #3f0035;
    border-radius: 2px 20px 20px 2px;
    position: absolute;
    box-shadow: 1px 1px 10px gray;
    transform: rotateX(10deg);
    transform-origin: center left;
}

.page11{
    height: 430px;
    width: 350px;
    background: white;
    position: absolute;
    border-radius: 2px 10px 10px 2px;
    transform: rotateX(10deg);
    transform-origin: center left;
    z-index: -1;
}

.last-page11{
   height: 430px;
    width: 350px;
    background: white;
    position: absolute;
    border-radius: 2px 10px 10px 2px;
    transform: rotateX(10deg);
    transform-origin: center left;
    z-index: -2;
}

.flipbook-open .cover11{
    transform: rotateX(10deg) rotateY(-180deg);
}

.flipbook-open .page11{
    transform: rotateX(10deg) rotateY(-180deg);
    z-index: 2;
}

.page11:nth-child(2){
    transition-duration: 3s;
}
.page11:nth-child(3){
    transition-duration: 2.6s;
}
.page11:nth-child(4){
    transition-duration: 2.2s;
}
.page11:nth-child(5){
    transition-duration: 1.8s;
}
.page11:nth-child(6){
    transition-duration: 1.4s;
}

.flipbook-open .page11:nth-child(2){
    transition-duration: 6s;
}
.flipbook-open .page11:nth-child(3){
    transition-duration: 5.6s;
}
.flipbook-open .page11:nth-child(4){
    transition-duration: 5.2s;
}
.flipbook-open .page11:nth-child(5){
    transition-duration: 4.8s;
}
.flipbook-open .page11:nth-child(6){
    transition-duration: 4.4s;
}

.last-page11 img{
    height: 410px;
    display: block;
    margin: 10px auto;
    position: relative;
    z-index: -2;
}

.cover11 img{
    height: 430px;
    display: block;
    position: relative;
    margin: 10px auto;
    z-index: 1;

}
</code>```

Does anyone know what this could be due to? Thanks in advance

Body:
i made this flipbook animation that works well on chrome to me.
https://jsfiddle.net/qjnhdavw/
If you open it with safari, as you can see, it doesn't work well.

After some tests, I have seen that only on safari, the cover11 element loses the priority given to it by the z-index.
This happen because of transform: rotateX(10deg); that I put in each element. If I remove this, the problem does not persist:
https://jsfiddle.net/epjfbyax/

As you can see the first option is good on chrome but doesn't work on safari, the second option
is good on safari but not so much on chrome.

This is the CSS of the first link:

.zone11{
   height: 700px;
    display: flex;
    align-items: center;
    justify-content: center;
    perspective: 1000px;
}

.book11{
    display: flex;
    align-items: center;
    cursor: pointer;
}

.cover11{
    z-index: 1;
    transition: all 3.5s;
}

.back-cover11{
    z-index: -3;
}

.cover11, .back-cover11{
    height: 450px;
    width: 360px;
    background: #3f0035;
    border-radius: 2px 20px 20px 2px;
    position: absolute;
    box-shadow: 1px 1px 10px gray;
    transform: rotateX(10deg);
    transform-origin: center left;
}

.page11{
    height: 430px;
    width: 350px;
    background: white;
    position: absolute;
    border-radius: 2px 10px 10px 2px;
    transform: rotateX(10deg);
    transform-origin: center left;
    z-index: -1;
}

.last-page11{
   height: 430px;
    width: 350px;
    background: white;
    position: absolute;
    border-radius: 2px 10px 10px 2px;
    transform: rotateX(10deg);
    transform-origin: center left;
    z-index: -2;
}

.flipbook-open .cover11{
    transform: rotateX(10deg) rotateY(-180deg);
}

.flipbook-open .page11{
    transform: rotateX(10deg) rotateY(-180deg);
    z-index: 2;
}

.page11:nth-child(2){
    transition-duration: 3s;
}
.page11:nth-child(3){
    transition-duration: 2.6s;
}
.page11:nth-child(4){
    transition-duration: 2.2s;
}
.page11:nth-child(5){
    transition-duration: 1.8s;
}
.page11:nth-child(6){
    transition-duration: 1.4s;
}

.flipbook-open .page11:nth-child(2){
    transition-duration: 6s;
}
.flipbook-open .page11:nth-child(3){
    transition-duration: 5.6s;
}
.flipbook-open .page11:nth-child(4){
    transition-duration: 5.2s;
}
.flipbook-open .page11:nth-child(5){
    transition-duration: 4.8s;
}
.flipbook-open .page11:nth-child(6){
    transition-duration: 4.4s;
}

.last-page11 img{
    height: 410px;
    display: block;
    margin: 10px auto;
    position: relative;
    z-index: -2;
}

.cover11 img{
    height: 430px;
    display: block;
    position: relative;
    margin: 10px auto;
    z-index: 1;

}

Does anyone know what this could be due to? Thanks in advance


问:
Is there any way to open componentin NEW TAB which is having data in slideshow?
I've a component with some data as slideshow and i want to open it when i click on 'viewImages'. But it's opening in same page.

\desktop-monitoring\desktop-monitoring.component.html

```<code> <button (click)="viewTotalImages(element, true)" class="btn btn-sm interview">View All Images</button>
</code>```

\desktop-monitoring\desktop-monitoring.component.ts

```<code>  public viewTotalImages(evt: any, isTotal:boolean) {

    this.viewReportData = this.cpesReportForm.value;
    // this.viewReportData.startDate = evt.date;
    // this.viewReportData.endDate = evt.date;
    if(isTotal){
      this.viewReportData.start = this.startDate
      this.viewReportData.end = this.endDate;
    }else{
      this.viewReportData.start = this.datePipe.transform(evt.date.split("/")[2]+"-"+evt.date.split("/")[1]+"-"+evt.date.split("/")[0], 'yyyy-MM-dd');
      this.viewReportData.end = this.datePipe.transform(evt.date.split("/")[2]+"-"+evt.date.split("/")[1]+"-"+evt.date.split("/")[0], 'yyyy-MM-dd');
    }
    this.viewReportData.username = evt.username
    this.viewReportData.manager = evt.manager
    this.desktopService.getImagePathList(this.viewReportData).subscribe
      (data => {
        this.serverData = data;
        const dialogRef = this.dialog.open(DesktopImageSlideShowComponent, {
          height: '98%', width: '98vw', maxWidth: '92vw',position: { top: '10px' },
          disableClose: true,
          autoFocus: true,
          panelClass: 'customStyle',
          data: this.serverData.resp
        });
      })
  }
</code>```

below is the slideshow component

\desktop-monitoring\desktop-image-slide-show\desktop-image-slide-show.component.html

```<code><div align="right">
  <span class="mdi mdi-close-circle" style="cursor:pointer;float:right;text-decoration:underline;color: red;margin-top: 6px;margin-top: -35px; font-size: 20px;"
  (click)="close()"></span>
</div>

<slideshow style="position: relative;
display: block;
margin: auto;
/* height: 104%; */
width: 85%;
overflow: hidden;" class="slide"
[imageUrls]="imageUrlArray"
[autoPlay]="true"
[autoPlayInterval]="4000"
[autoPlayWaitForLazyLoad]="true"></slideshow>
</code>```

\desktop-monitoring\desktop-image-slide-show\desktop-image-slide-show.component.ts

```<code>export class DesktopImageSlideShowComponent implements OnInit {
  imageUrlArray : any[];
  urlList : any;
  constructor(@Inject(MAT_DIALOG_DATA) public data: any, private dialogRef: MatDialogRef<DesktopImageSlideShowComponent>) {
    this.urlList = data;
    this.imageUrlArray = [];
    this.urlList.forEach(element => {
      this.imageUrlArray.push(element);
    });

   }

  ngOnInit() {
  }
  public close() {
    this.dialogRef.close();
  }
}
</code>```

I've tried with window.open(),localstorage and Injectors but i couldn't. FYI I need to open component not link which is having dynamic data.

All suggestions are appreciated.

Body:
I've a component with some data as slideshow and i want to open it when i click on 'viewImages'. But it's opening in same page.

\desktop-monitoring\desktop-monitoring.component.html

 <button (click)="viewTotalImages(element, true)" class="btn btn-sm interview">View All Images</button>

\desktop-monitoring\desktop-monitoring.component.ts

  public viewTotalImages(evt: any, isTotal:boolean) {

    this.viewReportData = this.cpesReportForm.value;
    // this.viewReportData.startDate = evt.date;
    // this.viewReportData.endDate = evt.date;
    if(isTotal){
      this.viewReportData.start = this.startDate
      this.viewReportData.end = this.endDate;
    }else{
      this.viewReportData.start = this.datePipe.transform(evt.date.split("/")[2]+"-"+evt.date.split("/")[1]+"-"+evt.date.split("/")[0], 'yyyy-MM-dd');
      this.viewReportData.end = this.datePipe.transform(evt.date.split("/")[2]+"-"+evt.date.split("/")[1]+"-"+evt.date.split("/")[0], 'yyyy-MM-dd');
    }
    this.viewReportData.username = evt.username
    this.viewReportData.manager = evt.manager
    this.desktopService.getImagePathList(this.viewReportData).subscribe
      (data => {
        this.serverData = data;
        const dialogRef = this.dialog.open(DesktopImageSlideShowComponent, {
          height: '98%', width: '98vw', maxWidth: '92vw',position: { top: '10px' },
          disableClose: true,
          autoFocus: true,
          panelClass: 'customStyle',
          data: this.serverData.resp
        });
      })
  }

below is the slideshow component

\desktop-monitoring\desktop-image-slide-show\desktop-image-slide-show.component.html

<slideshow style="position: relative;
display: block;
margin: auto;
/* height: 104%; */
width: 85%;
overflow: hidden;" class="slide"
[imageUrls]="imageUrlArray"
[autoPlay]="true"
[autoPlayInterval]="4000"
[autoPlayWaitForLazyLoad]="true"></slideshow>

\desktop-monitoring\desktop-image-slide-show\desktop-image-slide-show.component.ts

export class DesktopImageSlideShowComponent implements OnInit {
  imageUrlArray : any[];
  urlList : any;
  constructor(@Inject(MAT_DIALOG_DATA) public data: any, private dialogRef: MatDialogRef<DesktopImageSlideShowComponent>) {
    this.urlList = data;
    this.imageUrlArray = [];
    this.urlList.forEach(element => {
      this.imageUrlArray.push(element);
    });

   }

  ngOnInit() {
  }
  public close() {
    this.dialogRef.close();
  }
}

I've tried with window.open(),localstorage and Injectors but i couldn't. FYI I need to open component not link which is having dynamic data.

All suggestions are appreciated.


问:
Flutter Platform Exception in Google Sign
I have successfully completed the Google sign-in thing in Flutter. But if the user quits logging in I get an error. I couldn't figure out how to check for these errors. The answers I found are very old. Here is my code.

```<code>Future<UserCredential> signInWithGoogle() async {
    final GoogleSignInAccount? googleUser =
        await GoogleSignIn(scopes: <String>["email"]).signIn();

    final GoogleSignInAuthentication googleAuth =
        await googleUser!.authentication;

    final credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    return await FirebaseAuth.instance.signInWithCredential(credential);
  }
</code>```

And my error

Exception has occurred.
PlatformException (PlatformException(sign_in_canceled, com.google.GIDSignIn, The user canceled the sign-in flow., null))

How can i handle that?

Body:
I have successfully completed the Google sign-in thing in Flutter. But if the user quits logging in I get an error. I couldn't figure out how to check for these errors. The answers I found are very old. Here is my code.

Future<UserCredential> signInWithGoogle() async {
    final GoogleSignInAccount? googleUser =
        await GoogleSignIn(scopes: <String>["email"]).signIn();

    final GoogleSignInAuthentication googleAuth =
        await googleUser!.authentication;

    final credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    return await FirebaseAuth.instance.signInWithCredential(credential);
  }

And my error

Exception has occurred.
PlatformException (PlatformException(sign_in_canceled, com.google.GIDSignIn, The user canceled the sign-in flow., null))

How can i handle that?


问:
Enable validation for all fields in backend form creation
In Typo3 v 11.5.21 and Powermail version 10.6.0 By default, only freeform fields such as Text and Textarea allow selection of validation rules in the Extended tab.

This image shows the validation selection field in a text form field.

I've implemented an Powermail extension that introduces a custom PHP validation that's supposed to make it easier for my editors to control certain aspects of a form field. However, my editors would need to use those on other fields, primarily checkboxes, radio buttons and selection fields.

Is there a way to enable validations for those fields, too?


问:
CORS ERROR for HLS nodejs and reactjs, when trying to stream the m3u8 on reactjs
I know questions like this has been already asked but I have try to google it still didn't find the solution don't know what is wrong here, I have a nodejs server that is running on port 3001 and a react server that is running on port 3000. I have a directory in the nodejs where .m3u8 and .ts files exist also I have made that folder static using express

I am trying to stream the video on react on browser but I am getting this error

```<code>Access to XMLHttpRequest at 'http://localhost:3001/post-processing/data/output.m3u8' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

nodejs

```<code>console.log(`Server running on PORT: ${PORT}`)
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
  });

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());

app.use(express.static(__dirname + '/post-processing/data/'))

const server = app.listen(PORT);

new hls(server, {
  provider: {
    exists: (req, cb) => {
      const ext = req.url.split(".").pop();

      if (ext !== "m3u8" && ext !== "ts") {
        return cb(null, true);
      }
      console.log("path join",__dirname + req.url)
      fs.access(__dirname + req.url, fs.constants.F_OK, function (err) {
        if (err) {
          console.log("url", __dirname + req.url);
          console.log("File not exist");
          return cb(null, false);
        }
        cb(null, true);
      });
    },
    getManifestStream: (req, cb) => {
      const stream = fs.createReadStream(__dirname + req.url);
      cb(null, stream);
    },
    getSegmentStream: (req, cb) => {
      const stream = fs.createReadStream(__dirname + req.url);
      cb(null, stream);
    },
  },
});
</code>```

I have try to add this cors still getting same error

```<code>const corsOptions ={
  origin:'*',
  credentials:true,            //access-control-allow-credentials:true
  optionSuccessStatus:200
}

app.use(cors(corsOptions));
</code>```

Reactjs

```<code>function Feed() {
  return (
    <div className="feed">
      <ReactHlsPlayer
        src="http://localhost:3001/post-processing/data/output.m3u8"
        autoPlay={false}
        controls={true}
        width="100%"
        height="auto"
      />
    </div>
  );
}

export default Feed;
</code>```

Body:
I know questions like this has been already asked but I have try to google it still didn't find the solution don't know what is wrong here, I have a nodejs server that is running on port 3001 and a react server that is running on port 3000. I have a directory in the nodejs where .m3u8 and .ts files exist also I have made that folder static using express

I am trying to stream the video on react on browser but I am getting this error

Access to XMLHttpRequest at 'http://localhost:3001/post-processing/data/output.m3u8' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

nodejs

console.log(`Server running on PORT: ${PORT}`)
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
  });

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());

app.use(express.static(__dirname + '/post-processing/data/'))

const server = app.listen(PORT);

new hls(server, {
  provider: {
    exists: (req, cb) => {
      const ext = req.url.split(".").pop();

      if (ext !== "m3u8" && ext !== "ts") {
        return cb(null, true);
      }
      console.log("path join",__dirname + req.url)
      fs.access(__dirname + req.url, fs.constants.F_OK, function (err) {
        if (err) {
          console.log("url", __dirname + req.url);
          console.log("File not exist");
          return cb(null, false);
        }
        cb(null, true);
      });
    },
    getManifestStream: (req, cb) => {
      const stream = fs.createReadStream(__dirname + req.url);
      cb(null, stream);
    },
    getSegmentStream: (req, cb) => {
      const stream = fs.createReadStream(__dirname + req.url);
      cb(null, stream);
    },
  },
});

I have try to add this cors still getting same error

const corsOptions ={
  origin:'*',
  credentials:true,            //access-control-allow-credentials:true
  optionSuccessStatus:200
}

app.use(cors(corsOptions));

Reactjs

function Feed() {
  return (

      <ReactHlsPlayer
        src="http://localhost:3001/post-processing/data/output.m3u8"
        autoPlay={false}
        controls={true}
        width="100%"
        height="auto"
      />

  );
}

export default Feed;


问:
Is there a RFC for SOCKS ver4
While taking a look at the rfc for socks version 5 I was wondering whether there are prior versions to socks5. And there was SOCKS4 but I was not able to find a RFC for SOCKS4 instead I found this document

https://www.openssh.com/txt/socks4.protocol

Which gave the implmentation details of SOCKS4. My question is that is there a RFC seperately for SOCKS4 if not why?

I'm new to networks and it would be great to know the answer for this question.

I want to know whether there is an RFC for SOCKS4

Title: Is there a RFC for SOCKS ver4


问:
gUnicorn/Flask/GAE - two processes started for processing the same http request
I have an app on Google AppEngine (Python39 standard env) running on gUnicorn and Flask. I'm making a request to the server from client-side app for a long-running operation and seeing that the request processed twice. The second process (worker) started after a while (a hour and a half) after the first one has been working.

I'm not sure is it related to gUnicorn specifically or to GAE.

The server controller has logging at the beginning :

```<code>@app.route("/api/campaign/generate", methods=["GET"])
def campaign_generate():
  logging.info('Entering campaign_generate');
  # some very long processing here
</code>```

The controller is called by clicking a button from the UI app. I checked the network in DevTools in the browser that only one request fired. And I can see that there's only one request in server logs at the moment of executing of workers (more on this follow).

The whole app.yaml is like this:

```<code>runtime: python39
default_expiration: 0
instance_class: B2
basic_scaling:
  max_instances: 1
entrypoint: gunicorn -b :$PORT server.server:app --timeout 0 --workers 2
</code>```

So I have 2 workers with infinite timeouts, basic scaling with max instances = 1.
I expect while the app is processing one request for a long-running operation, another worker is available for serving.
I don't expect the second worker will used to processing the same request, it's a nonsense (if only the user won't start another operation from another browser).

Thanks to timeout=0 I expect gUnicorn will wait indefinitely till the controller finishes. And only one thing that can hinder is GAE'e timeout. But thanks to basic-scaling it's 24 hours. So I expect the app should process requests for several hours without problem.

But what I'm seeing instead is that after the processing the request for a while another execution is started. Here's simplified logs I see in Cloud Logging:

```<code>13:00:58 GET /api/campaign/generate
13:00:59 Entering campaign_generate
..skipped
13:39:13 Starting generating zip-archive (it's something that takes a while)
14:25:49 Entering campaign_generate
</code>```

So, at 14:25, 1:25 after the current request came another processing of the same request started!

And now there're two request processings running in parallel.
Needless to say that this increase memory pressure and doubles execution time.

When the first "worker" finished (14:29:28 in our example) its processing, its result isn't being returned to the client. It looks like gUnicorn or GAE simply abandoned the first request. And the client has to wait till the second worker finishes processing.

Why is it happening?
And how can I fix it?

Regarding http requests records in the log.

I did see only one request in Cloud Logging (the first one) when the processing was active, and even after the controller was called for the second time ('Entering campaign_generate' in logs appeared) there was not any new GET-request in the logs. But after that everything completed (actually the second processing returned a response) a mysterious second GET-request appeared. So technically after everything is done, from the server logs' view (Cloud Logging) it looks like there were two subsequent requests from the client. But there weren't! There was only one, and I can see it in the browser's DevTools.

Those two requests have different traceId and requestId http headers.

It's very hard to understand what's going on, I tried running the app locally (on the same data) but it works as intended.

Body:
I have an app on Google AppEngine (Python39 standard env) running on gUnicorn and Flask. I'm making a request to the server from client-side app for a long-running operation and seeing that the request processed twice. The second process (worker) started after a while (a hour and a half) after the first one has been working.

I'm not sure is it related to gUnicorn specifically or to GAE.

The server controller has logging at the beginning :

@app.route("/api/campaign/generate", methods=["GET"])
def campaign_generate():
  logging.info('Entering campaign_generate');
  # some very long processing here

The controller is called by clicking a button from the UI app. I checked the network in DevTools in the browser that only one request fired. And I can see that there's only one request in server logs at the moment of executing of workers (more on this follow).

The whole app.yaml is like this:

runtime: python39
default_expiration: 0
instance_class: B2
basic_scaling:
  max_instances: 1
entrypoint: gunicorn -b :$PORT server.server:app --timeout 0 --workers 2

So I have 2 workers with infinite timeouts, basic scaling with max instances = 1.
I expect while the app is processing one request for a long-running operation, another worker is available for serving.
I don't expect the second worker will used to processing the same request, it's a nonsense (if only the user won't start another operation from another browser).

Thanks to timeout=0 I expect gUnicorn will wait indefinitely till the controller finishes. And only one thing that can hinder is GAE'e timeout. But thanks to basic-scaling it's 24 hours. So I expect the app should process requests for several hours without problem.

But what I'm seeing instead is that after the processing the request for a while another execution is started. Here's simplified logs I see in Cloud Logging:

13:00:58 GET /api/campaign/generate
13:00:59 Entering campaign_generate
..skipped
13:39:13 Starting generating zip-archive (it's something that takes a while)
14:25:49 Entering campaign_generate

So, at 14:25, 1:25 after the current request came another processing of the same request started!

And now there're two request processings running in parallel.
Needless to say that this increase memory pressure and doubles execution time.

When the first "worker" finished (14:29:28 in our example) its processing, its result isn't being returned to the client. It looks like gUnicorn or GAE simply abandoned the first request. And the client has to wait till the second worker finishes processing.

Why is it happening?
And how can I fix it?

Regarding http requests records in the log.

I did see only one request in Cloud Logging (the first one) when the processing was active, and even after the controller was called for the second time ('Entering campaign_generate' in logs appeared) there was not any new GET-request in the logs. But after that everything completed (actually the second processing returned a response) a mysterious second GET-request appeared. So technically after everything is done, from the server logs' view (Cloud Logging) it looks like there were two subsequent requests from the client. But there weren't! There was only one, and I can see it in the browser's DevTools.

Those two requests have different traceId and requestId http headers.

It's very hard to understand what's going on, I tried running the app locally (on the same data) but it works as intended.


问:
How to add more tags to whitelist list of loofah in rails?
Ruby on Rails Version 7.0.4
Ruby Version: 3.1.3

I want to sanitize the content with Rails Loofah gem, it works perfectly fine.
But based on the project needs certain tag and attributes needs to be included while scrubbing the content.

Like  tag,  tag

How can we add additional tags along with the default list that loofah provide.
Using

```<code>Loofah.fragment("<style>{font-family:'Roboto', Arial, sans-serif;}</style>  <script>alert(h1)</script> <a href='https://google.com'>something</a> <div>Later</div>").scrub!(:prune).scrub!(:nofollow).to_s
</code>```

Style Tag is what i need to add in white list, along with other default tags

Body:
Ruby on Rails Version 7.0.4
Ruby Version: 3.1.3

I want to sanitize the content with Rails Loofah gem, it works perfectly fine.
But based on the project needs certain tag and attributes needs to be included while scrubbing the content.

Like  tag,  tag

How can we add additional tags along with the default list that loofah provide.
Using

Loofah.fragment("   something
Later
").scrub!(:prune).scrub!(:nofollow).to_s

Style Tag is what i need to add in white list, along with other default tags


问:
Laggy scroll and low FPS in a JS "zooming" function
JS newbie here.

I've created this CodePen where I tried to emulate an Apple-style "cut-out text" zooming effect, with a vertical scroll increasing the scale of a screening text, that progressively reveals content behind it. The code:

HTML

```<code><section id="screen">
  <h1>BIG TEXT</h1>
</section>

<section id="background">
  </section>
</code>```

CSS

```<code>body {
  margin:0;
  font-family:Helvetica;
  height:300vh;
}

h1 {
  font-size:10vmax;
  line-height:1;
  letter-spacing:-0.05em;
  scale:1;
  margin:0;
  transform: translateX(-1.42%);;
}

section {
  height:100vh;
  width:100vw;
}

#screen {
  text-align:center;
  display:flex;
  justify-content:center;
  align-items:center;
  position:fixed;
  background-color:white;
  mix-blend-mode:screen;
  z-index:1;
}

#background {
  background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/c/c6/Brussels_Zonienwoud.jpg/2560px-Brussels_Zonienwoud.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    position:fixed;
    z-index: -1;
}
</code>```

JS

```<code>const h1 = document.querySelector("h1")

document.addEventListener("scroll",function(){
  //declare variables
  let viewport = window.innerHeight
  let scrolled = window.scrollY
  let pageHeight = document.body.scrollHeight
  let scrollPercentage = scrolled / (pageHeight-viewport) * 100
  //Increase the scale of H1
  h1.style.scale = 1 + scrollPercentage
})
</code>```

The effect works pretty well, but — as soon as I view the result on a pretty big screen (<1280px or so), the scroll tends to get very laggy and slow. The rest of the content scrolls smoothly, it's just this screening div that seems to significantly drop in FPS. The problem is especially visible when the laptop is running on battery.

The phenomenon also tends to appear quite randomly, sometimes it goes very smoothly, sometimes not. Any idea how to increase the smoothness of the navigation, to mitigate framerate drops etc?

Thanks a lot for your help, happy to hear any tips you might have.

I tried looking into debouncing functions, replacing the text with an SVG… didn't solve it on my side. The laggy scroll stills appears from time to time.

Body:
JS newbie here.

I've created this CodePen where I tried to emulate an Apple-style "cut-out text" zooming effect, with a vertical scroll increasing the scale of a screening text, that progressively reveals content behind it. The code:

HTML

BIG TEXT

CSS

body {
  margin:0;
  font-family:Helvetica;
  height:300vh;
}

h1 {
  font-size:10vmax;
  line-height:1;
  letter-spacing:-0.05em;
  scale:1;
  margin:0;
  transform: translateX(-1.42%);;
}

section {
  height:100vh;
  width:100vw;
}

#screen {
  text-align:center;
  display:flex;
  justify-content:center;
  align-items:center;
  position:fixed;
  background-color:white;
  mix-blend-mode:screen;
  z-index:1;
}

#background {
  background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/c/c6/Brussels_Zonienwoud.jpg/2560px-Brussels_Zonienwoud.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    position:fixed;
    z-index: -1;
}

JS

const h1 = document.querySelector("h1")

document.addEventListener("scroll",function(){
  //declare variables
  let viewport = window.innerHeight
  let scrolled = window.scrollY
  let pageHeight = document.body.scrollHeight
  let scrollPercentage = scrolled / (pageHeight-viewport) * 100
  //Increase the scale of H1
  h1.style.scale = 1 + scrollPercentage
})

The effect works pretty well, but — as soon as I view the result on a pretty big screen (<1280px or so), the scroll tends to get very laggy and slow. The rest of the content scrolls smoothly, it's just this screening div that seems to significantly drop in FPS. The problem is especially visible when the laptop is running on battery.

The phenomenon also tends to appear quite randomly, sometimes it goes very smoothly, sometimes not. Any idea how to increase the smoothness of the navigation, to mitigate framerate drops etc?

Thanks a lot for your help, happy to hear any tips you might have.

I tried looking into debouncing functions, replacing the text with an SVG… didn't solve it on my side. The laggy scroll stills appears from time to time.


问:
is there a way to extract the AADHAAR card data from image and display in JSON with masking partial AADHAAR numbers?
I need to provide AADHAAR card photo and need to extract the Data on AADHAAR and display in JSON with masking partial Unique AADHAAR Number</p>
```<code>from PIL import Image
from pytesseract import pytesseract

#Define path to tessaract.exe
path_to_tesseract = r'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'

#Define path to image
path_to_image = 'C:/Users/PJ185101/Documents/images/sample2.jpg'

#Point tessaract_cmd to tessaract.exe
pytesseract.tesseract_cmd = path_to_tesseract

#Open image with PIL
img = Image.open(path_to_image)

#Extract text from image
text = pytesseract.image_to_string(img)

print(text)
</code>```

Body:
I need to provide AADHAAR card photo and need to extract the Data on AADHAAR and display in JSON with masking partial Unique AADHAAR Number

from PIL import Image
from pytesseract import pytesseract

#Define path to tessaract.exe
path_to_tesseract = r'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'

#Define path to image
path_to_image = 'C:/Users/PJ185101/Documents/images/sample2.jpg'

#Point tessaract_cmd to tessaract.exe
pytesseract.tesseract_cmd = path_to_tesseract

#Open image with PIL
img = Image.open(path_to_image)

#Extract text from image
text = pytesseract.image_to_string(img)

print(text)


问:
How to clear terminal in c++ and write to specific location in terminal
I currently have no base code, and please don't recommend the ncurses library.
Here is what I want to do: I want to be able to clear the terminal window like the clear command but then I want to be able to write to any part of the terminal window, like how text editors work.

I know that nobody has asked this question so dont close it


问:
How to send command to teraterm using python script
I am new to python,
I am trying to open tera term and write commands and read the results using python script,(ex: getpl #21)
but I am able to open teraterm but not able to pass commands via python script
please help me

here is my code

p = subprocess.Popen(["C:\\Program Files (x86)\\teraterm\\ttermpro.exe",'/C=9','/BAUD=115200'], stdout=subprocess.PIPE,stdin = subprocess.PIPE)
output = p.communicate()[1]
p=sys.stdout.write("getpl #21")
```

tried this code but not reflecting on tera term

Body:
I am new to python,
I am trying to open tera term and write commands and read the results using python script,(ex: getpl #21)
but I am able to open teraterm but not able to pass commands via python script
please help me

here is my code

p = subprocess.Popen(["C:\\Program Files (x86)\\teraterm\\ttermpro.exe",'/C=9','/BAUD=115200'], stdout=subprocess.PIPE,stdin = subprocess.PIPE)
output = p.communicate()[1]
p=sys.stdout.write("getpl #21")

tried this code but not reflecting on tera term


问:
Pipeline step with powershell have some error
On Jenkinsfile I'm running few git commands using PowerShell,
It seems command are successful but I get strange error.
When I run these command directly with powershell I don't have any issues.
Here is part of the code:

```<code>powershell '''
    Write-Output "git checkout -B ar/2020 ============="
    git checkout -B ar/2020

    Write-Output "git reset --hard HEAD ============="
    git reset --hard HEAD
'''
</code>```

Here is the output:

```<code>09:52:29  git checkout -B ar/2020 =============
09:52:37  Your branch is up to date with 'origin/ar/2020'.
09:52:37  powershell.exe : Reset branch 'ar/2020'
09:52:37  At C:\jenkins\workspace\TEST@tmp\durable-90a62004\powershellWrapper.ps1:3 char:1
09:52:37  + & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Comm ...
09:52:37  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
09:52:37      + CategoryInfo          : NotSpecified: (Reset branch 'ar/2020':String) [], RemoteException
09:52:37      + FullyQualifiedErrorId : NativeCommandError
09:52:37
09:52:37  git reset --hard HEAD =============
09:52:55  HEAD is now at af04dfe66cb Update list files
</code>```

Body:
On Jenkinsfile I'm running few git commands using PowerShell,
It seems command are successful but I get strange error.
When I run these command directly with powershell I don't have any issues.
Here is part of the code:

powershell '''
    Write-Output "git checkout -B ar/2020 ============="
    git checkout -B ar/2020

    Write-Output "git reset --hard HEAD ============="
    git reset --hard HEAD
'''

Here is the output:

09:52:29  git checkout -B ar/2020 =============
09:52:37  Your branch is up to date with 'origin/ar/2020'.
09:52:37  powershell.exe : Reset branch 'ar/2020'
09:52:37  At C:\jenkins\workspace\TEST@tmp\durable-90a62004\powershellWrapper.ps1:3 char:1
09:52:37  + & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Comm ...
09:52:37  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
09:52:37      + CategoryInfo          : NotSpecified: (Reset branch 'ar/2020':String) [], RemoteException
09:52:37      + FullyQualifiedErrorId : NativeCommandError
09:52:37
09:52:37  git reset --hard HEAD =============
09:52:55  HEAD is now at af04dfe66cb Update list files


问:
Running Lighthouse audit programmatically using the Chrome DevTools protocol from Java application
I am trying to run lighthouse audits programmatically from a Java application. I don't want to call an external process to run Puppeteer via node.js. I want everything to be self contained in the Java application.

The Java application uses chrome-devtools-java-client to send devtools protocol messages to a Chromium instance. We embed Chromium as part of our Java application.

My goal is to use that Chromium instance to auto run a lighthouse audit on a URL and send the results back to my Java application.

My method

As lighthouse is part of the devtools-frontend code, I am starting Chromium with the ‘--auto-open-devtools-for-tabs’ command line option and running my own modified devtools-frontend code via the ‘--custom-devtools-frontend’ command line option. The modified devtools-frontend code programmatically runs lighthouse on Chromium startup and then sets the results in DOMStorage. The java application has a listener for the DOMStorage.domStorageItemAdded devtools protocol event and can then extract the lighthouse results.

This all seems to work if the Chromium instance is running headful, however it doesn’t when running headless.

My question is does the ‘--auto-open-devtools-for-tabs’ chromium command line option work in headless mode or is there anything else I may be missing?

Any help, suggestions or pointers greatly appreciated.


问:
Error trying to connect to socket: closing socket - timed out
I have a problem with Extracting the features & Storing data in the list

the code I am using is this:

```<code>#Extracting the features & storing them in a list
legi_features = []
label = 0

for i in range(0, 5000):
url = legiurl['URLs'][i]
legi_features.append(featureExtraction(url,label))
</code>```
```<code>Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
</code>```

The whole code and original project comes from this link: https://github.com/shreyagopal/Phishing-Website-Detection-by-Machine-Learning-Techniques/blob/master/URL%20Feature%20Extraction.ipynb

Any help I would appreciate!

Body:
I have a problem with Extracting the features & Storing data in the list

the code I am using is this:

#Extracting the features & storing them in a list
legi_features = []
label = 0

for i in range(0, 5000):
url = legiurl['URLs'][i]
legi_features.append(featureExtraction(url,label))

Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out
Error trying to connect to socket: closing socket - timed out

The whole code and original project comes from this link: https://github.com/shreyagopal/Phishing-Website-Detection-by-Machine-Learning-Techniques/blob/master/URL%20Feature%20Extraction.ipynb

Any help I would appreciate!


问:
Parquet datatype issue with Spectrum Scan
I am using the COPY function in Redshift to import a Parquet file from one of my S3 buckets, but I get a weird error related with column types:

```<code>> Spectrum Scan Error. File
> 'https://s3....gz.parquet'
> has an incompatible Parquet schema for column
> 's3://...gz.parquet.date'.
> Column type: TIMESTAMP, Parquet schema: optional byte_array date [i:2
> d:1 r:0]...
</code>```

But the table in Redshift does not have any TIMESTAMP column, just a DATE one, which should match with the Parquet data.

What is wrong here?

Body:
I am using the COPY function in Redshift to import a Parquet file from one of my S3 buckets, but I get a weird error related with column types:

> Spectrum Scan Error. File
> 'https://s3....gz.parquet'
> has an incompatible Parquet schema for column
> 's3://...gz.parquet.date'.
> Column type: TIMESTAMP, Parquet schema: optional byte_array date [i:2
> d:1 r:0]...

But the table in Redshift does not have any TIMESTAMP column, just a DATE one, which should match with the Parquet data.

What is wrong here?


问:
Showing popup, based on pages visited on a pre-made website
I want to show a discount popup for the user when he visits 3 specific pages on a particular website. However, I don't know how to reach the whole pages of that website to edit my jquery code.

Or is it possible to use pages without downloading them?

I really appreciate any help you can provide.


问:
Error while using keras in R : (Error in py_call_impl(callable, dots$args, dots$keywords) : InvalidArgumentError: Graph execution error
I'm a graduate student majoring in hydrology who is doing research on artificial intelligence using keras in the r language. An error occurred while training the model with the rnn method. Here is the code. could you give me some advice? Thanks for your help!

```<code>## read input data
setwd("C:/Users/zpdlf/Desktop/Andong_LSTM_n_timesteps_2")

## rainfall
pAD <- read.csv("input_p_AD.csv", sep = ",", as.is = TRUE)
pAD$Date <- as.Date(pAD$Date, "%Y-%m-%d")
ts_pAD <- xts(pAD[, 2], pAD$Date, frequency = 1)

## streamflow
qAD <- read.csv("input_q_AD.csv", sep = ",", as.is = TRUE)
qAD$Date <- as.Date(qAD$Date, "%Y-%m-%d")
ts_qAD <- xts(qAD[, 2], qAD$Date, frequency = 1)

## ave. temp.
taveAD <- read.csv("input_tave_AD.csv", sep = ",", as.is = TRUE)
taveAD$Date <- as.Date(taveAD$Date, "%Y-%m-%d")
ts_taveAD <- xts(taveAD[, 2], taveAD$Date, frequency = 1)

## wind speed
u2AD <- read.csv("input_u2_AD.csv", sep = ",", as.is = TRUE)
u2AD$Date <- as.Date(u2AD$Date, "%Y-%m-%d")
ts_u2AD <- xts(u2AD[, 2], u2AD$Date, frequency = 1)

## make dataframe
df_AD <- as.data.frame(cbind(P = ts_pAD["1977-01-01::2020-12-01"],
                             Q = ts_qAD["1977-01-01::2020-12-01"],
                             Tave = ts_taveAD["1977-01-01::2020-12-01"],
                             u2 = ts_u2AD["1977-01-01::2020-12-01"]))

########################################
## refer to "https://keras.rstudio.com/articles/faq.html#how-can-i-obtain-reproducible-results-using-keras-during-development"
#set.seed(101) ## not work

## 1. input data standadization
dat <- df_AD
dat$Date <- rownames(dat)

## Train, validation and test periods selection
dat_septn <- dat
dat_septn$Date <- as.Date(dat_septn$Date, "%Y-%m-%d")
ts_dat_septn <- xts(dat_septn[, 1:4], dat_septn$Date, frequency = 1)

train_dat_septn <- ts_dat_septn["1977-01-01::2000-12-01"]
valid_dat_septn <- ts_dat_septn["2001-01-01::2010-12-01"]
test_dat_septn <- ts_dat_septn["2011-01-01::2020-12-01"]

## Train, validation and test samples
## In a stateful network, you should only pass inputs with a number of samples that can be divided by the batch size.
## Data standardization having a mean of zero and a standard deviation of 1
## must apply mean and sd for train data to validation and test data(refer to "Deep Learning with R(2018, Chollet and Allaire)")
msd_P = c(mean(train_dat_septn$P), sd(train_dat_septn$P))
msd_Q = c(mean(train_dat_septn$Q), sd(train_dat_septn$Q))
msd_Tave = c(mean(train_dat_septn$Tave), sd(train_dat_septn$Tave))
msd_u2 = c(mean(train_dat_septn$u2), sd(train_dat_septn$u2))

## data standadization
train_dat_temp <- as.data.frame(train_dat_septn)
train_dat_temp$P = (train_dat_temp$P - msd_P[1])/msd_P[2]
train_dat_temp$Q = (train_dat_temp$Q - msd_Q[1])/msd_Q[2]
train_dat_temp$Tave = (train_dat_temp$Tave - msd_Tave[1])/msd_Tave[2]
train_dat_temp$u2 = (train_dat_temp$u2 - msd_u2[1])/msd_u2[2]

valid_dat_temp <- as.data.frame(valid_dat_septn)
valid_dat_temp$P = (valid_dat_temp$P - msd_P[1])/msd_P[2]
valid_dat_temp$Q = (valid_dat_temp$Q - msd_Q[1])/msd_Q[2]
valid_dat_temp$Tave = (valid_dat_temp$Tave - msd_Tave[1])/msd_Tave[2]
valid_dat_temp$u2 = (valid_dat_temp$u2 - msd_u2[1])/msd_u2[2]

test_dat_temp <- as.data.frame(test_dat_septn)
test_dat_temp$P = (test_dat_temp$P - msd_P[1])/msd_P[2]
test_dat_temp$Q = (test_dat_temp$Q - msd_Q[1])/msd_Q[2]
test_dat_temp$Tave = (test_dat_temp$Tave - msd_Tave[1])/msd_Tave[2]
test_dat_temp$u2 = (test_dat_temp$u2 - msd_u2[1])/msd_u2[2]

####################
## 2. set hyper-parameters
## for 3D input tensor data generation

##### test n_timesteps : 1 ~ 10
n_timesteps <- 2 ## size(length) of the hidden state, equals size of predictions ("number of prediction step can be less than batch_size"), 0 makes error due to no data use from current time step, see "https://towardsdatascience.com/how-to-reshape-data-and-do-regression-for-time-series-using-lstm-133dad96cd00"

x_n_features <- 3 ## number of input variables
y_n_features <- 1 ## number of output variables

## for LSTM model
n_units_1 <- 100 ## size of the LSTM layer("it is different from hidden state i.e. n_timesteps")
n_units_2 <- 100 ## size of the LSTM layer("it is different from hidden state i.e. n_timesteps")

##### test batch_size for daily cases
batch_size <- 10 ## number of samples fed to the model in one go(usually 2 squared form), 10 recommended by Le et al.(2019) "Application of Long Short-Term Memory(LSTM) Neural Network for Flooding Forecasting"

dropout <- 0.5 ## fraction of the units to drop for the linear transformation of the inputs
recurrent_dropout <- 0.5 ## fraction of the units to drop for the linear transformation of the recurrent state

## for compile
optimizer_type <- optimizer_adam(learning_rate = 0.001) ## learning rate; 0.0001 recommended by Le et al.(2019) "Application of Long Short-Term Memory(LSTM) Neural Network for Flooding Forecasting"
loss_fn <- "mae" ## refer to "Deep Learning with R(2018, Chollet and Allaire)"
metrics_type <- "mse"

## for fit
n_epochs <- 50 ## number of iteration
patience <- 10 ## parameter(number of epoch) to the early stopping callback; stop trainaing when monitor value is not improved with more than selected number(e.g. 10) of epochs

callbacks_list <- list(
  callback_early_stopping(
    monitor = metrics_type, ## it monitors the metrics
    patience = patience
  ),
  callback_model_checkpoint(
    filepath = "my_model.h5", ## filepath and save model; it use the filepath in setwd()
    monitor = "val_loss", ## if validation loss is not improved than it does not save model so can maintain the best model
    save_best_only = TRUE
  )
)

## set timeseries
df_train = train_dat_temp
df_valid = valid_dat_temp
df_test = test_dat_temp

## 3D input tensor data; 2D output tensor data
## The input has to be a 3-d array of size num_samples, num_timesteps, num_features.
## The output has to be a 2-d array of size num_samples, num_features.
x_train = array(data = cbind(df_train$P, df_train$Tave, df_train$u2),
                dim = c(nrow(df_train), n_timesteps, x_n_features))
y_train = array(data = df_train$Q,
                dim = c(nrow(df_train), y_n_features))

x_valid = array(data = cbind(df_valid$P, df_valid$Tave, df_valid$u2),
                dim = c(nrow(df_valid), n_timesteps, x_n_features))
y_valid = array(data = df_valid$Q,
                dim = c(nrow(df_valid), y_n_features))

x_test = array(data = cbind(df_test$P, df_test$Tave, df_test$u2),
               dim = c(nrow(df_test), n_timesteps, x_n_features))
y_test = array(data = df_test$Q,
               dim = c(nrow(df_test), y_n_features))

## 3. LSTM model
## target array's format needs to be 3-dimensional("target array is for in LSTM model")
## Dimension 1 again is the batch dimension("batch_size"), dimension 2 again corresponds to the number of timesteps ("prediction step"), and dimension 3 is the size of the wrapped layer("number of variables").
## define model
model <- keras_model_sequential()

## use default activation functions in LSTM because they are better than ReLU
model %>%
  layer_lstm(
    units = n_units_1,
    batch_input_shape = c(batch_size, n_timesteps, x_n_features),
    recurrent_dropout = recurrent_dropout,
    return_sequences = TRUE, ## return the full(3D tensor) sequence
    stateful = FALSE) %>% ## If stateful is TRUE, this adds a further tweak where the hidden states get initialized with values from the item at same position in the previous batch.
  layer_dropout(rate = dropout) %>% #### edit ####
layer_lstm(
  units = n_units_2,
  recurrent_dropout = recurrent_dropout,
  return_sequences = FALSE,
  stateful = FALSE) %>%
  layer_dropout(rate = dropout) %>% #### edit ####
layer_dense(units = y_n_features) ## refer to "Deep Learning with R(2018, Chollet and Allaire)"

## compile
model %>% compile(
  optimizer = optimizer_type,
  loss = loss_fn,
  metrics = c(metrics_type)
)

model ## order of output shape is (,,n_units); number of parameters is calculated as 4*(n_units*n_units + n_units*x_n_features + n_units*1), 1 for bias and 41600 parameters for 100 n_units and 3 x_n_features)

## fit
history <- model %>% fit(
  x = x_train,
  y = y_train,
  epochs = n_epochs,
  batch_size = batch_size,
  callbacks = callbacks_list,
  validation_data = list(x_valid, y_valid),
  verbose = 2, # verbose = 0, ## verbose = 0 is for automatic mode
  shuffle = FALSE
)

plot(history)
</code>```

The content of the error is as follows. Any help in resolving the error would be appreciated!

Error in py_call_impl(callable, dots$args, dots$keywords) :
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:
<... omitted ...>ckages\keras\utils\traceback_utils.py", line 92, in error_handler
return fn(*args, **kwargs)
File "C:\Users\zpdlf\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\layers\rnn\lstm.py", line 574, in call
last_output, outputs, states = backend.rnn(
File "C:\Users\zpdlf\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\backend.py", line 4612, in rnn
input_ta = tuple(
File "C:\Users\zpdlf\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\backend.py", line 4613, in
ta.unstack(input_) if not go_backwards else ta
Node: 'sequential/lstm_1/TensorArrayUnstack/TensorListFromTensor'
Specified a list with shape [10,3] from a tensor with shape [8,3]
[[{{node sequential/lstm_1/TensorArrayUnstack/TensorListFromTensor}}]] [Op:__inference_train_function_4388]

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

Body:
I'm a graduate student majoring in hydrology who is doing research on artificial intelligence using keras in the r language. An error occurred while training the model with the rnn method. Here is the code. could you give me some advice? Thanks for your help!

## read input data
setwd("C:/Users/zpdlf/Desktop/Andong_LSTM_n_timesteps_2")

## rainfall
pAD <- read.csv("input_p_AD.csv", sep = ",", as.is = TRUE)
pAD$Date <- as.Date(pAD$Date, "%Y-%m-%d")
ts_pAD <- xts(pAD[, 2], pAD$Date, frequency = 1)

## streamflow
qAD <- read.csv("input_q_AD.csv", sep = ",", as.is = TRUE)
qAD$Date <- as.Date(qAD$Date, "%Y-%m-%d")
ts_qAD <- xts(qAD[, 2], qAD$Date, frequency = 1)

## ave. temp.
taveAD <- read.csv("input_tave_AD.csv", sep = ",", as.is = TRUE)
taveAD$Date <- as.Date(taveAD$Date, "%Y-%m-%d")
ts_taveAD <- xts(taveAD[, 2], taveAD$Date, frequency = 1)

## wind speed
u2AD <- read.csv("input_u2_AD.csv", sep = ",", as.is = TRUE)
u2AD$Date <- as.Date(u2AD$Date, "%Y-%m-%d")
ts_u2AD <- xts(u2AD[, 2], u2AD$Date, frequency = 1)

## make dataframe
df_AD <- as.data.frame(cbind(P = ts_pAD["1977-01-01::2020-12-01"],
                             Q = ts_qAD["1977-01-01::2020-12-01"],
                             Tave = ts_taveAD["1977-01-01::2020-12-01"],
                             u2 = ts_u2AD["1977-01-01::2020-12-01"]))

########################################
## refer to "https://keras.rstudio.com/articles/faq.html#how-can-i-obtain-reproducible-results-using-keras-during-development"
#set.seed(101) ## not work

## 1. input data standadization
dat <- df_AD
dat$Date <- rownames(dat)

## Train, validation and test periods selection
dat_septn <- dat
dat_septn$Date <- as.Date(dat_septn$Date, "%Y-%m-%d")
ts_dat_septn <- xts(dat_septn[, 1:4], dat_septn$Date, frequency = 1)

train_dat_septn <- ts_dat_septn["1977-01-01::2000-12-01"]
valid_dat_septn <- ts_dat_septn["2001-01-01::2010-12-01"]
test_dat_septn <- ts_dat_septn["2011-01-01::2020-12-01"]

## Train, validation and test samples
## In a stateful network, you should only pass inputs with a number of samples that can be divided by the batch size.
## Data standardization having a mean of zero and a standard deviation of 1
## must apply mean and sd for train data to validation and test data(refer to "Deep Learning with R(2018, Chollet and Allaire)")
msd_P = c(mean(train_dat_septn$P), sd(train_dat_septn$P))
msd_Q = c(mean(train_dat_septn$Q), sd(train_dat_septn$Q))
msd_Tave = c(mean(train_dat_septn$Tave), sd(train_dat_septn$Tave))
msd_u2 = c(mean(train_dat_septn$u2), sd(train_dat_septn$u2))

## data standadization
train_dat_temp <- as.data.frame(train_dat_septn)
train_dat_temp$P = (train_dat_temp$P - msd_P[1])/msd_P[2]
train_dat_temp$Q = (train_dat_temp$Q - msd_Q[1])/msd_Q[2]
train_dat_temp$Tave = (train_dat_temp$Tave - msd_Tave[1])/msd_Tave[2]
train_dat_temp$u2 = (train_dat_temp$u2 - msd_u2[1])/msd_u2[2]

valid_dat_temp <- as.data.frame(valid_dat_septn)
valid_dat_temp$P = (valid_dat_temp$P - msd_P[1])/msd_P[2]
valid_dat_temp$Q = (valid_dat_temp$Q - msd_Q[1])/msd_Q[2]
valid_dat_temp$Tave = (valid_dat_temp$Tave - msd_Tave[1])/msd_Tave[2]
valid_dat_temp$u2 = (valid_dat_temp$u2 - msd_u2[1])/msd_u2[2]

test_dat_temp <- as.data.frame(test_dat_septn)
test_dat_temp$P = (test_dat_temp$P - msd_P[1])/msd_P[2]
test_dat_temp$Q = (test_dat_temp$Q - msd_Q[1])/msd_Q[2]
test_dat_temp$Tave = (test_dat_temp$Tave - msd_Tave[1])/msd_Tave[2]
test_dat_temp$u2 = (test_dat_temp$u2 - msd_u2[1])/msd_u2[2]

####################
## 2. set hyper-parameters
## for 3D input tensor data generation

##### test n_timesteps : 1 ~ 10
n_timesteps <- 2 ## size(length) of the hidden state, equals size of predictions ("number of prediction step can be less than batch_size"), 0 makes error due to no data use from current time step, see "https://towardsdatascience.com/how-to-reshape-data-and-do-regression-for-time-series-using-lstm-133dad96cd00"

x_n_features <- 3 ## number of input variables
y_n_features <- 1 ## number of output variables

## for LSTM model
n_units_1 <- 100 ## size of the LSTM layer("it is different from hidden state i.e. n_timesteps")
n_units_2 <- 100 ## size of the LSTM layer("it is different from hidden state i.e. n_timesteps")

##### test batch_size for daily cases
batch_size <- 10 ## number of samples fed to the model in one go(usually 2 squared form), 10 recommended by Le et al.(2019) "Application of Long Short-Term Memory(LSTM) Neural Network for Flooding Forecasting"

dropout <- 0.5 ## fraction of the units to drop for the linear transformation of the inputs
recurrent_dropout <- 0.5 ## fraction of the units to drop for the linear transformation of the recurrent state

## for compile
optimizer_type <- optimizer_adam(learning_rate = 0.001) ## learning rate; 0.0001 recommended by Le et al.(2019) "Application of Long Short-Term Memory(LSTM) Neural Network for Flooding Forecasting"
loss_fn <- "mae" ## refer to "Deep Learning with R(2018, Chollet and Allaire)"
metrics_type <- "mse"

## for fit
n_epochs <- 50 ## number of iteration
patience <- 10 ## parameter(number of epoch) to the early stopping callback; stop trainaing when monitor value is not improved with more than selected number(e.g. 10) of epochs

callbacks_list <- list(
  callback_early_stopping(
    monitor = metrics_type, ## it monitors the metrics
    patience = patience
  ),
  callback_model_checkpoint(
    filepath = "my_model.h5", ## filepath and save model; it use the filepath in setwd()
    monitor = "val_loss", ## if validation loss is not improved than it does not save model so can maintain the best model
    save_best_only = TRUE
  )
)

## set timeseries
df_train = train_dat_temp
df_valid = valid_dat_temp
df_test = test_dat_temp

## 3D input tensor data; 2D output tensor data
## The input has to be a 3-d array of size num_samples, num_timesteps, num_features.
## The output has to be a 2-d array of size num_samples, num_features.
x_train = array(data = cbind(df_train$P, df_train$Tave, df_train$u2),
                dim = c(nrow(df_train), n_timesteps, x_n_features))
y_train = array(data = df_train$Q,
                dim = c(nrow(df_train), y_n_features))

x_valid = array(data = cbind(df_valid$P, df_valid$Tave, df_valid$u2),
                dim = c(nrow(df_valid), n_timesteps, x_n_features))
y_valid = array(data = df_valid$Q,
                dim = c(nrow(df_valid), y_n_features))

x_test = array(data = cbind(df_test$P, df_test$Tave, df_test$u2),
               dim = c(nrow(df_test), n_timesteps, x_n_features))
y_test = array(data = df_test$Q,
               dim = c(nrow(df_test), y_n_features))

## 3. LSTM model
## target array's format needs to be 3-dimensional("target array is for in LSTM model")
## Dimension 1 again is the batch dimension("batch_size"), dimension 2 again corresponds to the number of timesteps ("prediction step"), and dimension 3 is the size of the wrapped layer("number of variables").
## define model
model <- keras_model_sequential()

## use default activation functions in LSTM because they are better than ReLU
model %>%
  layer_lstm(
    units = n_units_1,
    batch_input_shape = c(batch_size, n_timesteps, x_n_features),
    recurrent_dropout = recurrent_dropout,
    return_sequences = TRUE, ## return the full(3D tensor) sequence
    stateful = FALSE) %>% ## If stateful is TRUE, this adds a further tweak where the hidden states get initialized with values from the item at same position in the previous batch.
  layer_dropout(rate = dropout) %>% #### edit ####
layer_lstm(
  units = n_units_2,
  recurrent_dropout = recurrent_dropout,
  return_sequences = FALSE,
  stateful = FALSE) %>%
  layer_dropout(rate = dropout) %>% #### edit ####
layer_dense(units = y_n_features) ## refer to "Deep Learning with R(2018, Chollet and Allaire)"

## compile
model %>% compile(
  optimizer = optimizer_type,
  loss = loss_fn,
  metrics = c(metrics_type)
)

model ## order of output shape is (,,n_units); number of parameters is calculated as 4*(n_units*n_units + n_units*x_n_features + n_units*1), 1 for bias and 41600 parameters for 100 n_units and 3 x_n_features)

## fit
history <- model %>% fit(
  x = x_train,
  y = y_train,
  epochs = n_epochs,
  batch_size = batch_size,
  callbacks = callbacks_list,
  validation_data = list(x_valid, y_valid),
  verbose = 2, # verbose = 0, ## verbose = 0 is for automatic mode
  shuffle = FALSE
)

plot(history)

The content of the error is as follows. Any help in resolving the error would be appreciated!

Error in py_call_impl(callable, dots$args, dots$keywords) :
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:
<... omitted ...>ckages\keras\utils\traceback_utils.py", line 92, in error_handler
return fn(*args, **kwargs)
File "C:\Users\zpdlf\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\layers\rnn\lstm.py", line 574, in call
last_output, outputs, states = backend.rnn(
File "C:\Users\zpdlf\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\backend.py", line 4612, in rnn
input_ta = tuple(
File "C:\Users\zpdlf\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\backend.py", line 4613, in
ta.unstack(input_) if not go_backwards else ta
Node: 'sequential/lstm_1/TensorArrayUnstack/TensorListFromTensor'
Specified a list with shape [10,3] from a tensor with shape [8,3]
[[{{node sequential/lstm_1/TensorArrayUnstack/TensorListFromTensor}}]] [Op:__inference_train_function_4388]


问:
IOS write javascript on web have to use 'completetion(result)'
i ues my iphone want to write js to check in at work evary day

it's my simpe js code

```<code>const glogin = $('.loginBtn.loginBtn--google');
glogin.onclick();
const checkOut = $('#checkOut');
checkOut.click();
</code>```

it's can't use
enter image description here

what can i do ??

i try add completetion(result)

```<code>var result = function(){
const glogin = $('.loginBtn.loginBtn--google'); glogin.onclick();
const checkOut = $('#checkOut'); checkOut.click();
}
completetion(result)
</code>```

also cant use

i want it can use,thanks

Body:
i ues my iphone want to write js to check in at work evary day

it's my simpe js code

const glogin = $('.loginBtn.loginBtn--google');
glogin.onclick();
const checkOut = $('#checkOut');
checkOut.click();

it's can't use
enter image description here

what can i do ??

i try add completetion(result)

var result = function(){
const glogin = $('.loginBtn.loginBtn--google'); glogin.onclick();
const checkOut = $('#checkOut'); checkOut.click();
}
completetion(result)

also cant use

i want it can use,thanks


问:
How can different user like the same post
Hello i have a mern project, in this project i have a social media feature. Like other social media, this one also have post, profil, like, and comment, im currently new to mern and having problem with how the like and dislike work.

I have a SosmedPost model and the idea is to store which user liked the post, using ref and populate. The function and the populate itself its working fine

```<code>const SosmedPostSchema = new mongoose.Schema({
   Username : {
       type : String
   },
   Content : {
       type : String
   },
   Documents : {
       type : String
   },
   Author : {
       type : mongoose.Schema.Types.ObjectId,
       ref : 'sosmedprofiles'
   },
   Comments : [{
       PostedBy : {
              type : mongoose.Schema.Types.ObjectId,
              ref : "sosmedprofiles"
       },
       Text : {
              type : String
       }
   }],
   Likes : [{
          type : mongoose.Schema.Types.ObjectId,
          ref : "sosmedprofiles"
   }]
}, {timestamps : true});
</code>```

This is how i create like and unlike controller

```<code>const likePost = (req, res) => {
  const Id = req.params.id;

  SosmedPostModel.findByIdAndUpdate({ _id : Id}, {
    $push : {Likes : req.body.Likes}
  }, {
    new : true
  }).populate("Likes").exec((err, result) => {
    if (err) {
      return res.status(422).send(err)
    } else {
      res.json(result)
    }
  })
}

const unlikePost = (req, res) => {
  const Id = req.params.id;

  SosmedPostModel.findByIdAndUpdate({ _id : Id}, {
    $pull : {Likes : req.body.Likes}
  }, {
    new : true
  }).exec((err, result) => {
    if (err) {
      return res.status(422).send(err)
    } else {
      res.json(result)
    }
  })
}
</code>```

The trouble is if the user A liked the post A, user B cant like the post A because the post is already liked by the user A.
I need a logic how to make a condition where each user can like the post once. Thanks

Below is the condition i create if the user already like the post in the front end

```<code>{ i.Likes?.length <= 0 ?
  <Button key={index} flex='1' variant='ghost' rightIcon={<AiOutlineLike />} leftIcon=
  {`${Object.keys(i.Likes).length}`} onClick={() => LikePost(i._id)}>Like</Button>
:
 <>
 <Button key={index} flex='1' variant='ghost' rightIcon={<AiFillLike />} leftIcon=
 {`${Object.keys(i.Likes).length}`} onClick={() => UnlikePost(i._id)}>Liked</Button>
 </>
}
</code>```

This is the put axios route :

```<code> const LikePost = (id) => {
      Axios.put(`https://example/socialmedia/${id}/like`, {
        Likes : profileUser._id
      }).then((response) => {
        setLikeCount(response.data);
      })
    }

    const UnlikePost = (id) => {
      Axios.put(`https://example/socialmedia/${id}/unlike`, {
        Likes : profileUser._id
      }).then((response) => {
        setLikeCount(response.data);
      })
    }
</code>```

Body:
Hello i have a mern project, in this project i have a social media feature. Like other social media, this one also have post, profil, like, and comment, im currently new to mern and having problem with how the like and dislike work.

I have a SosmedPost model and the idea is to store which user liked the post, using ref and populate. The function and the populate itself its working fine

const SosmedPostSchema = new mongoose.Schema({
   Username : {
       type : String
   },
   Content : {
       type : String
   },
   Documents : {
       type : String
   },
   Author : {
       type : mongoose.Schema.Types.ObjectId,
       ref : 'sosmedprofiles'
   },
   Comments : [{
       PostedBy : {
              type : mongoose.Schema.Types.ObjectId,
              ref : "sosmedprofiles"
       },
       Text : {
              type : String
       }
   }],
   Likes : [{
          type : mongoose.Schema.Types.ObjectId,
          ref : "sosmedprofiles"
   }]
}, {timestamps : true});

This is how i create like and unlike controller

const likePost = (req, res) => {
  const Id = req.params.id;

  SosmedPostModel.findByIdAndUpdate({ _id : Id}, {
    $push : {Likes : req.body.Likes}
  }, {
    new : true
  }).populate("Likes").exec((err, result) => {
    if (err) {
      return res.status(422).send(err)
    } else {
      res.json(result)
    }
  })
}

const unlikePost = (req, res) => {
  const Id = req.params.id;

  SosmedPostModel.findByIdAndUpdate({ _id : Id}, {
    $pull : {Likes : req.body.Likes}
  }, {
    new : true
  }).exec((err, result) => {
    if (err) {
      return res.status(422).send(err)
    } else {
      res.json(result)
    }
  })
}

The trouble is if the user A liked the post A, user B cant like the post A because the post is already liked by the user A.
I need a logic how to make a condition where each user can like the post once. Thanks

Below is the condition i create if the user already like the post in the front end

{ i.Likes?.length <= 0 ?
  <Button key={index} flex='1' variant='ghost' rightIcon={<AiOutlineLike />} leftIcon=
  {`${Object.keys(i.Likes).length}`} onClick={() => LikePost(i._id)}>Like</Button>
:
 <>
 <Button key={index} flex='1' variant='ghost' rightIcon={<AiFillLike />} leftIcon=
 {`${Object.keys(i.Likes).length}`} onClick={() => UnlikePost(i._id)}>Liked</Button>
 </>
}

This is the put axios route :

 const LikePost = (id) => {
      Axios.put(`https://example/socialmedia/${id}/like`, {
        Likes : profileUser._id
      }).then((response) => {
        setLikeCount(response.data);
      })
    }

    const UnlikePost = (id) => {
      Axios.put(`https://example/socialmedia/${id}/unlike`, {
        Likes : profileUser._id
      }).then((response) => {
        setLikeCount(response.data);
      })
    }


问:
Randomly show custom Ad Screen from API - Flutter
I have a list of ads containing images, videos and details for each ad comes from an Api.
What is the best option to show a custom screen with random ad on a random time for ex: each 1-5 min will show a random ad.

I have tried workmanger but it doesn't seems like the best option.


问:
How do I fetch a the html of a website within a chrome extension
I am trying to do the below

```<code>  fetch("https://www.google.com/search?q=trees&tbm=isch&sxsrf=ALiCzsYCq08DI1a2kANT5mYBvDyYi7keWw%3A1671527330860&source=hp&biw=2025&bih=1279&ei=onuhY7uXMcaA0PEP6t2GuAo&iflsig=AJiK0e8AAAAAY6GJshVTus5cslLxfh_vqy0n5ro5Half&ved=0ahUKEwi78KPG7If8AhVGADQIHequAacQ4dUDCAc&uact=5&oq=trees&gs_lcp=CgNpbWcQAzIICAAQgAQQsQMyCAgAEIAEELEDMggIABCABBCxAzIFCAAQgAQyBQgAEIAEMggIABCABBCxAzIICAAQgAQQsQMyCAgAEIAEELEDMgUIABCABDIFCAAQgAQ6BAgjECc6CAgAELEDEIMBOgsIABCABBCxAxCDAToHCCMQ6gIQJzoFCAAQsQNQAFibFmD8FmgDcAB4AIABN4gBkAOSAQE4mAEAoAEBqgELZ3dzLXdpei1pbWewAQo&sclient=img", {

  })
  .then(response => {
      console.log(response)
  })
</code>```

but this is giving me errors

Access to fetch at 'URL' from origin 'chrome-extension://...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tried using headers with 'Access-Control-Allow-Origin' but this still return the same error. I have also tried using 'no-cors'. This works but then there is no body returned and I need the HTML for parcing.

I also have the below but it did not fix the issue.

```<code>"host_permissions": [
    "https://www.website.com/*"
  ],
</code>```

Body:
I am trying to do the below

  fetch("https://www.google.com/search?q=trees&tbm=isch&sxsrf=ALiCzsYCq08DI1a2kANT5mYBvDyYi7keWw%3A1671527330860&source=hp&biw=2025&bih=1279&ei=onuhY7uXMcaA0PEP6t2GuAo&iflsig=AJiK0e8AAAAAY6GJshVTus5cslLxfh_vqy0n5ro5Half&ved=0ahUKEwi78KPG7If8AhVGADQIHequAacQ4dUDCAc&uact=5&oq=trees&gs_lcp=CgNpbWcQAzIICAAQgAQQsQMyCAgAEIAEELEDMggIABCABBCxAzIFCAAQgAQyBQgAEIAEMggIABCABBCxAzIICAAQgAQQsQMyCAgAEIAEELEDMgUIABCABDIFCAAQgAQ6BAgjECc6CAgAELEDEIMBOgsIABCABBCxAxCDAToHCCMQ6gIQJzoFCAAQsQNQAFibFmD8FmgDcAB4AIABN4gBkAOSAQE4mAEAoAEBqgELZ3dzLXdpei1pbWewAQo&sclient=img", {

  })
  .then(response => {
      console.log(response)
  })

but this is giving me errors

Access to fetch at 'URL' from origin 'chrome-extension://...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tried using headers with 'Access-Control-Allow-Origin' but this still return the same error. I have also tried using 'no-cors'. This works but then there is no body returned and I need the HTML for parcing.

I also have the below but it did not fix the issue.

"host_permissions": [
    "https://www.website.com/*"
  ],


问:
dotnet test is not running on csproj
We are running a local azure devops server. Since the last microsoft patch day the dotnet test fails:

When i start the dotnet test on the server direct the dotnet test fails with the same csproj-file. Do i start the dotnet test without specifying the csproj-file, but in the same folder, it runs and the tests succeed. When i start the command line from visual studio tools it runs. Any ideas?

And here is the YAML:
steps:

task: DotNetCoreCLI@2
displayName: 'dotnet test '
inputs:
command: test
projects: |
**/Test.csproj
arguments: '-c  Release'
testRunTitle: 'Test'
enabled: false
continueOnError: true

Title: dotnet test is not running on csproj


问:
How to apply css for parent div using child div class name
I am trying to add CSS for parent div but it is not working. Parent div is appending dynamic for class content. How to set padding for that div. If anyone knows please help to find the solution.

HTML:

```<code><div> // how to set padding for this div
    <div class="content">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    </div>
</div>
</code>```

CSS:

```<code>.content < div {

  padding:0px !important;

 }
</code>```

Body:
I am trying to add CSS for parent div but it is not working. Parent div is appending dynamic for class content. How to set padding for that div. If anyone knows please help to find the solution.

HTML:

 // how to set padding for this div

    Lorem Ipsum is simply dummy text of the printing and typesetting industry.

CSS:

.content < div {

  padding:0px !important;

 }


问:
How do I configure an Azure APIM Oauth2 service for Azure AD B2C?
I'm exposing an API through Azure API Management. In order to call the API from the developer portal, an Authorization header with a bearer access token, issued by an Azure AD B2C instance, needs to be provided.

In the B2C instance, there is a signup/signin userflow (with connector API integration to load custom claims) that should be triggered by the APIM Oauth2 service configured for the API. This would mean that the user flow is triggered from within the developer portal (try it functionality) and the issued token is used to try out the API.

Who can point me in the right direction to get this working?

Remark: this is not an issue about setting up AAD B2C to get access to the developer portal, it is purely about calling our API from the developer portal (try it)  with a token issued by our aad b2c instance.

I already tried to configure the b2c authorization endpoint with the signup/signin policy passed as query parameter but without success. I would expected is needed to pass in the policy to be used to ensure the right policy is ran ...


问:
How can I make this button to handle screen size with React.js?

How can I make this one using React.js. any Idea?

First, using react.js not react-native.
Second, it is the ability to handle the size with a touch event on mobile.

As a result, I want to implement a gray button at the top of the screen.


问:
Emails with coloured tables / shapes on Iphone Darkmode
We are trying to create a background shape for our emails which is a yellow rectangle with a yellow triangle attached beneath this to look like a speech bubble.
The problem is on Iphone darkmode the tablecell background colour for the triangle turns dark but the triangle doesn't!

This is the code for the triangle

```<code><div style="border:2em solid transparent;border-top-color:red;border-bottom:none;display:inline-block"></div>
<!--[if mso]>
<v:shape path="m,l1000,0 500,1000xe" style="width:64px;height:32px;" fillcolor="red" stroked="f"><o:lock selection="t"/></v:shape>
<![endif]-->
</code>```

But for some reason the triangle doesn't change with dark mode.

Body:
We are trying to create a background shape for our emails which is a yellow rectangle with a yellow triangle attached beneath this to look like a speech bubble.
The problem is on Iphone darkmode the tablecell background colour for the triangle turns dark but the triangle doesn't!

This is the code for the triangle

But for some reason the triangle doesn't change with dark mode.


问:
How to pass data from getStaticProps/getInitialProps to all components with next.js?
How can I get data from API in getStaticProps or getInitialProps method and pass this data context to all components in the tree?

For example, I have the following getStaticProps for some page:

```<code>export const getStaticProps: GetStaticProps = async () => {
  const { content: locales } = await localizationService.getLocales();

  return {
    props: {
      locales,
    },
  };
};
</code>```

Then I get this data in the page:

```<code>export const HomePage: FC<IHomePageProps> = ({ locales }) => {
  return (
    <MainLayout>
      <SomeComponent locales={locales} />
    </MainLayout>
  );
};
</code>```

Where SomeComponent - arbitrary deeply nested component, that contains a <Text /> component inside.
And the <Text /> component somehow uses this locales data

I tried to use react context for that, but it requires default value, which I don't have.

How to avoid many manual passing props locales={locales} to each component?

Thanks in advance for any hints :)

Body:
How can I get data from API in getStaticProps or getInitialProps method and pass this data context to all components in the tree?

For example, I have the following getStaticProps for some page:

export const getStaticProps: GetStaticProps = async () => {
  const { content: locales } = await localizationService.getLocales();

  return {
    props: {
      locales,
    },
  };
};

Then I get this data in the page:

export const HomePage: FC<IHomePageProps> = ({ locales }) => {
  return (
    <MainLayout>
      <SomeComponent locales={locales} />
    </MainLayout>
  );
};

Where SomeComponent - arbitrary deeply nested component, that contains a <Text /> component inside.
And the <Text /> component somehow uses this locales data

I tried to use react context for that, but it requires default value, which I don't have.

How to avoid many manual passing props locales={locales} to each component?

Thanks in advance for any hints :)


问:
How to ensure that maven passes credentials when redirecting?
I have a Java repository whose url is, say a. Access to this repository requires authentication, which is provided by the credentials stored in maven's setting.xml file (~/.m2/settings.xml). When I specify this url in pom.xml for maven's repository, everything works as expected.

```<code><repositories>
    <repository>
      <id>my-internal-site</id>
      <url>a</url>
    </repository>
  </repositories>
</code>```

I also have a url, b, which redirects to a. More specifically, b returns a 302 HTTP response. Now, when I specify b in pom.xml as the repository url, it returns a 400 Authentication Error, which most likely means that the Authentication parameters are missing. So my hypothesis is that maven does not send the authentication details from settings.xml to a on redirection. Is there a way I can enable that? Or is there a fix for this?

Body:
I have a Java repository whose url is, say a. Access to this repository requires authentication, which is provided by the credentials stored in maven's setting.xml file (~/.m2/settings.xml). When I specify this url in pom.xml for maven's repository, everything works as expected.

<repositories>
    <repository>
      <id>my-internal-site</id>
      <url>a</url>
    </repository>
  </repositories>

I also have a url, b, which redirects to a. More specifically, b returns a 302 HTTP response. Now, when I specify b in pom.xml as the repository url, it returns a 400 Authentication Error, which most likely means that the Authentication parameters are missing. So my hypothesis is that maven does not send the authentication details from settings.xml to a on redirection. Is there a way I can enable that? Or is there a fix for this?


问:
How to create a script to run pdfcrop on every pdf in the folder
I'm pretty new to Ubuntu and to .sh scripting in general, so I'm not really sure of which commands can I use in a .sh script and which not, and although I have some time looking I haven't found anything that works for me.

The things is, my desired script would run pdfcrop on every pdf file in the folder it is executed on, then remove every old pdf file and rename the files to remove the "-crop" part.

Is .sh scripting the best way to achieve this? If so, how would you do it?