问:
How to manage vector of pointers in C++ where pointer is allocated by Lua
In the simple 2D Game Engine I am working. I want to define and script my entities using Lua and do all the heavy work in C++ (rendering, physics, etc.)

To do this I have basic Entity class:

```<code>class Entity {
    public:
        Entity() {
            alive = true;
            livingCount++;
        }

        void destroy() {
            alive = false;
        }

        bool isAlive() { return alive; }

        ~Entity(){
            // Gets called if I manually call delete entity in EntityManager or if I use smart pointers, but causes seg faults in either case
            std::cout << "Entity destructor called." << std::endl;
            livingCount--;
        }
    private:
        bool alive;
};
</code>```

And the EntityManager singleton which groups all active Entities and is used in main game loop to refresh, update and render entities in this order, here is the EntityManager class:

```<code>class EntityManager {
        public:
            static EntityManager* Instance() {
                if(s_pInstance == 0) {
                    s_pInstance = new EntityManager();
                    return s_pInstance;
                }
                return s_pInstance;
            }
            // Main game loop goes through these and calls refresh(), then update() and finally render() on each frame
            void update(float deltaTime) {
                for (auto& e: entities)
                    e->update(deltaTime);
            }

            void render(float deltaTime) {
                for (auto& e: entities)
                    e->draw(deltaTime);

            }
            // This method causes segfault after entity gets destroyed, it doesn't matter if I use raw pointers or smart, I am still getting segfault here
            void refresh() {
                for (auto& e: entities) {
                    if (!e->isAlive()) {
                        entities.erase(std::remove(entities.begin(), entities.end(), e), entities.end());
                        // Uncommenting this also causes segfault, but if this is commented, Entity* is not freed from the memory, only gets removed from vector
                        // delete e;

                    }
                }
                // Tried doing the same using shared_ptr or even unique_ptr, but every time entity is destroyed this causes segfault as well
                // entities.erase(std::remove_if(std::begin(entities), std::end(entities),
                //     [](std::shared_ptr<Entity> &e) {
                //         return !e->isAlive();
                //     }),
                //     std::end(entities));
            }

            // Add new entity
            // This will become legacy, I am only using this to create entities in C++, but soon they will only be created by Lua and passed to this class
            Entity* addEntity() {
                Entity* entity = new Entity();
                entities.push_back(entity);
                return entity;
            }

            // Add existing entity: for lua
            // I have a feeling this method is not correct
            void addEntity(Entity* entity) {
                entities.push_back(entity);
            }

            const std::vector<Entity*>& getEntities() { return entities; }

        private:
            EntityManager() {}

            static EntityManager* s_pInstance;
            // Probably should use std::shared_ptr<Entity> instead
            // I tried this on Ubuntu and it does seem to solve memory problem and entities get deleted
            // but also getting segfault on Linux and I'm not sure if it's because of this class or
            // my use of unique pointers
            std::vector<Entity*> entities;
    };
</code>```

Now everytime I want to create new Entity, I can do this from Lua script, because I have implemented __index and __gc metamethods for Entity, so this works perfectly:

```<code>testEntity = Entity.create()
testEntity:move(400, 400)
testEntity:scale(2, 2)
testEntity:addSprite("slime", "assets/sprite/slime.png", 32, 32)
testEntity:addAnimation("default", "0", "4")
testEntity:addCollider("enemy", 48, 48)
print("Slime ID: "..testEntity:id())
</code>```

And finally, this is Lua binder for then we want to create new entity, notice how I pass pointer to EntityManager as well, because otherwise game will not update it:

```<code> int Script::lua_createEntity(lua_State *L) {
    Entity* entity = (Entity*)lua_newuserdata(L, sizeof(Entity));
    // Placement new operator takes already allocated memory and calls constructor
    new (entity) Entity();
    // This Entity created in here must be added to EntityManager vector so that game knows about it
    EntityManager::Instance()->addEntity(entity);

    luaL_getmetatable(L, "EntityMetaTable");
    lua_setmetatable(L, -2);
    return 1;
}
</code>```

And this method is bound to __gc metatable, but does not seem to get called at all, I'm not even sure if I want Lua to take care of this:

```<code>// Will be called once lua state is closed
int Script::lua_destroyEntity(lua_State *L) {
    Entity* entity = (Entity*)lua_touserdata(L, -1);
    std::cout << "Lua __gc for Entity called" << std::endl;
    entity->destroy();
    return 0;
}
</code>```

Now, let's say I have an Entity which is also a Projectile, every time Projectile goes off screen, I call entity->destroy() on that Projectile and it's member "isAlive" is marked as "false". This is all done in C++, but projectile gets created by Lua script

So on the next frame, EntityManager refresh() method is invoked and that projectile gets removed correctly from the Vector, but if I try to delete it then to free the memory, it causes segfault, otherwise destructor never gets called.

As I said before, I have tried
std::vectorstd::unique_ptr<Entity> and std::vectorstd::shared_ptr<Entity>, but that also causes segfault in EntityManager refresh method, which makes me think something fundamentally is wrong with how I am dealing with Entity lifetime.

__gc metamethod might not even be needed for me, as I want EntityManager to take care of all active Entities in the game, Lua will only be able to tell it which entity have been marked as destroyed and let C++ take care of deleting it.

Body:
In the simple 2D Game Engine I am working. I want to define and script my entities using Lua and do all the heavy work in C++ (rendering, physics, etc.)

To do this I have basic Entity class:

class Entity {
    public:
        Entity() {
            alive = true;
            livingCount++;
        }

        void destroy() {
            alive = false;
        }

        bool isAlive() { return alive; }

        ~Entity(){
            // Gets called if I manually call delete entity in EntityManager or if I use smart pointers, but causes seg faults in either case
            std::cout << "Entity destructor called." << std::endl;
            livingCount--;
        }
    private:
        bool alive;
};

And the EntityManager singleton which groups all active Entities and is used in main game loop to refresh, update and render entities in this order, here is the EntityManager class:

class EntityManager {
        public:
            static EntityManager* Instance() {
                if(s_pInstance == 0) {
                    s_pInstance = new EntityManager();
                    return s_pInstance;
                }
                return s_pInstance;
            }
            // Main game loop goes through these and calls refresh(), then update() and finally render() on each frame
            void update(float deltaTime) {
                for (auto& e: entities)
                    e->update(deltaTime);
            }

            void render(float deltaTime) {
                for (auto& e: entities)
                    e->draw(deltaTime);

            }
            // This method causes segfault after entity gets destroyed, it doesn't matter if I use raw pointers or smart, I am still getting segfault here
            void refresh() {
                for (auto& e: entities) {
                    if (!e->isAlive()) {
                        entities.erase(std::remove(entities.begin(), entities.end(), e), entities.end());
                        // Uncommenting this also causes segfault, but if this is commented, Entity* is not freed from the memory, only gets removed from vector
                        // delete e;

                    }
                }
                // Tried doing the same using shared_ptr or even unique_ptr, but every time entity is destroyed this causes segfault as well
                // entities.erase(std::remove_if(std::begin(entities), std::end(entities),
                //     [](std::shared_ptr<Entity> &e) {
                //         return !e->isAlive();
                //     }),
                //     std::end(entities));
            }

            // Add new entity
            // This will become legacy, I am only using this to create entities in C++, but soon they will only be created by Lua and passed to this class
            Entity* addEntity() {
                Entity* entity = new Entity();
                entities.push_back(entity);
                return entity;
            }

            // Add existing entity: for lua
            // I have a feeling this method is not correct
            void addEntity(Entity* entity) {
                entities.push_back(entity);
            }

            const std::vector<Entity*>& getEntities() { return entities; }

        private:
            EntityManager() {}

            static EntityManager* s_pInstance;
            // Probably should use std::shared_ptr<Entity> instead
            // I tried this on Ubuntu and it does seem to solve memory problem and entities get deleted
            // but also getting segfault on Linux and I'm not sure if it's because of this class or
            // my use of unique pointers
            std::vector<Entity*> entities;
    };

Now everytime I want to create new Entity, I can do this from Lua script, because I have implemented __index and __gc metamethods for Entity, so this works perfectly:

testEntity = Entity.create()
testEntity:move(400, 400)
testEntity:scale(2, 2)
testEntity:addSprite("slime", "assets/sprite/slime.png", 32, 32)
testEntity:addAnimation("default", "0", "4")
testEntity:addCollider("enemy", 48, 48)
print("Slime ID: "..testEntity:id())

And finally, this is Lua binder for then we want to create new entity, notice how I pass pointer to EntityManager as well, because otherwise game will not update it:

 int Script::lua_createEntity(lua_State *L) {
    Entity* entity = (Entity*)lua_newuserdata(L, sizeof(Entity));
    // Placement new operator takes already allocated memory and calls constructor
    new (entity) Entity();
    // This Entity created in here must be added to EntityManager vector so that game knows about it
    EntityManager::Instance()->addEntity(entity);

    luaL_getmetatable(L, "EntityMetaTable");
    lua_setmetatable(L, -2);
    return 1;
}

And this method is bound to __gc metatable, but does not seem to get called at all, I'm not even sure if I want Lua to take care of this:

// Will be called once lua state is closed
int Script::lua_destroyEntity(lua_State *L) {
    Entity* entity = (Entity*)lua_touserdata(L, -1);
    std::cout << "Lua __gc for Entity called" << std::endl;
    entity->destroy();
    return 0;
}

Now, let's say I have an Entity which is also a Projectile, every time Projectile goes off screen, I call entity->destroy() on that Projectile and it's member "isAlive" is marked as "false". This is all done in C++, but projectile gets created by Lua script

So on the next frame, EntityManager refresh() method is invoked and that projectile gets removed correctly from the Vector, but if I try to delete it then to free the memory, it causes segfault, otherwise destructor never gets called.

As I said before, I have tried
std::vectorstd::unique_ptr<Entity> and std::vectorstd::shared_ptr<Entity>, but that also causes segfault in EntityManager refresh method, which makes me think something fundamentally is wrong with how I am dealing with Entity lifetime.

__gc metamethod might not even be needed for me, as I want EntityManager to take care of all active Entities in the game, Lua will only be able to tell it which entity have been marked as destroyed and let C++ take care of deleting it.


来源: stackexchange

问:
Why is my password reset link logic showing undefined in my Express app?
I am trying to create a route that sends someone a JWT token reset link. The Route that I am having issues with is as follows:

```<code>// REQUIREMENTS
require("dotenv").config();
const express       =   require("express"),
    expressSanitizer=   require("express-sanitizer"),
    router          =   express.Router(),
    passport        =   require("passport"),
    User            =   require("../models/user"),
    middleware      =   require("../middleware"),
    mailchimp       = require('@mailchimp/mailchimp_marketing'),
    request         = require('request'),
    https           = require('https'),
    nodemailer      =   require("nodemailer"),
    jwt             = require('jsonwebtoken');

const JWT_SECRET = "jwt_secret";

router.post('/forgot-password', (req, res, next) =>{
    let userEmail       = req.body.email;
    let link;
    User.findOne({'email': req.query.email}, function(err, username){
        let userEmail = req.body.email;
        if(err) {
          console.log(err);
        }
        var message;
        if(username) {
            console.log(username);
            message = "email exists";
            console.log(message);
            // SEND TOKEN HERE
            const secret = JWT_SECRET + username.password;
            const payload = {
                id: username.id,
                email: userEmail
            };
            let token = jwt.sign(payload, secret, {expiresIn: '15m'});
            // CHECK URL PARAMS
            let link = process.env.URL`/${username.id}/${token}`;
            console.log(link);
            console.log(payload);
            return link, payload;
        }
    });

    let transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        auth: {
            type: 'OAuth2',
            clientId: authClient,
            clientSecret: authCSecret
        }
    });

    // Email Data
    let mailOptions = {
        from: *****, // sender address
        to: userEmail, // list of receivers
        replyTo: *****,
        subject: 'Reset Your Password', // Subject line
        html: '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/><link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"rel="stylesheet"/><link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.0.1/mdb.min.css" rel="stylesheet"/><p class="lead">Hey, it looks like you forgot your password.</p><p class="card-text">Follow the link below to reset your password.<div class="text-center"><a class="btn btn-lg btn-primary my-3" href="'+link+'" target="_blank">click here</a></div></p><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.0.1/mdb.min.js"></script>', // html body
        auth: {
            user: authUser,
            refreshToken: authRefreshToken,
            accessToken: authAccessToken,
            expires: 3599
        }
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
        res.send("A link has been sent to your email.");
    });

});
</code>```

I have confirmed the Nodemailer part works. I am just at a loss why the link is always showing as undefined when in my console it prints out a valid link to follow. All help would be appreciated!

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a route that sends someone a JWT token reset link. The Route that I am having issues with is as follows:

// REQUIREMENTS
require("dotenv").config();
const express       =   require("express"),
    expressSanitizer=   require("express-sanitizer"),
    router          =   express.Router(),
    passport        =   require("passport"),
    User            =   require("../models/user"),
    middleware      =   require("../middleware"),
    mailchimp       = require('@mailchimp/mailchimp_marketing'),
    request         = require('request'),
    https           = require('https'),
    nodemailer      =   require("nodemailer"),
    jwt             = require('jsonwebtoken');

const JWT_SECRET = "jwt_secret";

router.post('/forgot-password', (req, res, next) =>{
    let userEmail       = req.body.email;
    let link;
    User.findOne({'email': req.query.email}, function(err, username){
        let userEmail = req.body.email;
        if(err) {
          console.log(err);
        }
        var message;
        if(username) {
            console.log(username);
            message = "email exists";
            console.log(message);
            // SEND TOKEN HERE
            const secret = JWT_SECRET + username.password;
            const payload = {
                id: username.id,
                email: userEmail
            };
            let token = jwt.sign(payload, secret, {expiresIn: '15m'});
            // CHECK URL PARAMS
            let link = process.env.URL`/${username.id}/${token}`;
            console.log(link);
            console.log(payload);
            return link, payload;
        }
    });

    let transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        auth: {
            type: 'OAuth2',
            clientId: authClient,
            clientSecret: authCSecret
        }
    });

    // Email Data
    let mailOptions = {
        from: *****, // sender address
        to: userEmail, // list of receivers
        replyTo: *****,
        subject: 'Reset Your Password', // Subject line
        html: '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/><link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"rel="stylesheet"/><link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.0.1/mdb.min.css" rel="stylesheet"/>
Hey, it looks like you forgot your password.

Follow the link below to reset your password.
click here

', // html body
        auth: {
            user: authUser,
            refreshToken: authRefreshToken,
            accessToken: authAccessToken,
            expires: 3599
        }
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
        res.send("A link has been sent to your email.");
    });

});

I have confirmed the Nodemailer part works. I am just at a loss why the link is always showing as undefined when in my console it prints out a valid link to follow. All help would be appreciated!


问:
Getting error in initialising the vector in C++
Here is my code:

```<code>#include<iostream>
#include<vector>
using namespace std;
int main(){
    vector<int>v{2,3,4};
    cout<<v[0]; // output should be 2
    return 0;
}
</code>```

I was expecting the ans to be 2 but it is giving error:

```<code>[Running] cd "/Users/harshtayal/Desktop/C++ Learn/" && g++ file.cpp -o file && "/Users/harshtayal/Desktop/C++ Learn/"file
file.cpp:5:17: error: expected ';' at end of declaration
    vector<int>v{2,3,4};
                ^
                ;
1 error generated.
</code>```

It is working when using push_back, but what's the problem in above??

Body:
Here is my code:

#include<iostream>
#include<vector>
using namespace std;
int main(){
    vector<int>v{2,3,4};
    cout<<v[0]; // output should be 2
    return 0;
}

I was expecting the ans to be 2 but it is giving error:

[Running] cd "/Users/harshtayal/Desktop/C++ Learn/" && g++ file.cpp -o file && "/Users/harshtayal/Desktop/C++ Learn/"file
file.cpp:5:17: error: expected ';' at end of declaration
    vector<int>v{2,3,4};
                ^
                ;
1 error generated.

It is working when using push_back, but what's the problem in above??


问:
Styling not refreshing for old visitors on WordPress
I’m working on correcting a styling of an element on an WP-based eCommerce site.

The site has both SCSS and CSS files.

To make things quick, I edited the CSS via Appearance -> Customize ->  Additional CSS.

However, when I was done and published my changes (and solved the issue), only those new to the website sees the difference.

Those who have visited the site prior to the deployment of the solution, still see the distorted number layout

I also suspected that the SCSS gets compiled every refresh but when I checked the File Manager (cPanel), only the CSS files get modified.

I’m feeling this might be a cache-related issue. I have already disabled a cache plugin (WP Rocket). However, the problem still persists.

What possible issue am I experiencing?

Edit: I did try to use Incognito and the change did reflect. However, the users of the site are non-techy people and don't know how to refresh.

The site is using GoDaddy as the host. Is it possible the issue is on that part?

Thank you


问:
Is there wildcards syntax in mongo projections?
I have OpenAPI specs in a mongo database. I want to retrieve only the paths (no other values) and description fields for these paths. Is there a way to do that?

A query like this doesn't work:

```<code>db.specs.find({}, {"paths.*":1})
db.specs.find({}, {"paths.*.description":1})
</code>```

Here is a simplified version of the mongo data(see https://editor.swagger.io/ for the full structure of the document):

[{
  "paths": {
    "/pet": {
      "put": {
        "tags": [
          "pet"
        ],
        "summary": "Update an existing pet",
        "description": "Update an existing pet by Id",
        "operationId": "updatePet",
        "requestBody": {
          "description": "Update an existent pet in the store",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            },
            "application/xml": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            },
            "application/x-www-form-urlencoded": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful operation",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Pet"
                }
              },
              "application/xml": {
                "schema": {
                  "$ref": "#/components/schemas/Pet"
                }
              }
            }
          },
          "400": {
            "description": "Invalid ID supplied"
          },
          "404": {
            "description": "Pet not found"
          },
          "405": {
            "description": "Validation exception"
          }
        }
     }
]
```

Body:
I have OpenAPI specs in a mongo database. I want to retrieve only the paths (no other values) and description fields for these paths. Is there a way to do that?

A query like this doesn't work:

db.specs.find({}, {"paths.*":1})
db.specs.find({}, {"paths.*.description":1})

Here is a simplified version of the mongo data(see https://editor.swagger.io/ for the full structure of the document):

[{
  "paths": {
    "/pet": {
      "put": {
        "tags": [
          "pet"
        ],
        "summary": "Update an existing pet",
        "description": "Update an existing pet by Id",
        "operationId": "updatePet",
        "requestBody": {
          "description": "Update an existent pet in the store",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            },
            "application/xml": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            },
            "application/x-www-form-urlencoded": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful operation",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Pet"
                }
              },
              "application/xml": {
                "schema": {
                  "$ref": "#/components/schemas/Pet"
                }
              }
            }
          },
          "400": {
            "description": "Invalid ID supplied"
          },
          "404": {
            "description": "Pet not found"
          },
          "405": {
            "description": "Validation exception"
          }
        }
     }
]


问:
Can't delete rows on protected list
I have a protected list in sharepoint-excel file, with set unlocked ranges and marked options on editing the list, but I've stumbled upon getting rejected to do actions that I've marked as allowed in options.

My list of options and unlocked ranges:
Options Ranges

My most important question is: where does the "allow users to" apply? To the whole list or just the unlocked ranges?

Becouse, for example, when I try to delete row INSIDE the unlocked range, I cant'!
Selected row
Error

I never used VBA, but open to it if it can be used in this situation, and if it's possible to create VBA script in online version with sharepoint somehow.

Thanks in advance for any suggestions!

Title: Can't delete rows on protected list


问:
Deployment to Azure compute emulator fails silently. What could have happened?
I'm trying run my first Azure web role. Storage Emulator starts, Compute Emulator starts, but the deployment takes a lot of time. VS asks if I want to continue try to deploy. In the Compute Emulator UI states "Role State Unknown". No further information.

What could cause the deployment to the emulator to hang and where can I find more information on what happened?

ContentLicense: CC BY-SA 3.0


问:
Webpack v5 builds with a module parsing error
I'm currently migrating my project from Webpack v4 to v5 and my build finishes with an Error

```<code>@My-MacBook-Pro seacat-webui % node --trace-deprecation node_modules/webpack/bin/webpack.js
assets by status 354 bytes [cached] 1 asset
./src/index.js 2.67 KiB [built] [code generated] [1 error]

ERROR in ./src/index.js 103:1
Module parse failed: Unexpected token (103:1)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| ReactDOM.render((
>   <HashRouter>
|       <Application
|           sidebarItemsOrder={sidebarItemsOrder}

webpack 5.75.0 compiled with 1 error in 252 ms
</code>```

The Error has nothing to do with <HashRouter> itself, the same message appeares pointing the error to <Application ... > if I comment out the hashrouter.

my rules in common.js are

```<code>exports.getRules = function(config) {
    return [
        {
            test: /\.(js)$/,
            use: [{
                loader: 'babel-loader',
                options: { presets: [[
                    '@babel/preset-env',
                    {
                        useBuiltIns: "entry",
                        targets: {
                        esmodules: true,
                        },
                        corejs: {
                            version: "3",
                            proposals: true
                        }
                    }
                ],['@babel/react']], plugins: ["transform-object-rest-spread"] }
            }],
            exclude: '/node_modules/'
        },
        {
            test: /\.(s[ac]|c)ss$/i,
            use: [
                MiniCssExtractPlugin.loader, //extracts CSS into files
                {
                    loader: 'css-loader',  // Second, turn css into commonjs
                    options: { sourceMap: true }
                },
                {
                    loader: 'postcss-loader',
                    options: { sourceMap: true }
                },
                {
                    loader: 'sass-loader', // First, turn sass into css
                    options: { sourceMap: true }
                }
            ],
        },
        {
            test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?.*)?$/,
            type: 'asset/resource',
            generator: {
                filename: 'assets/svg/[name][contenthash:8][ext]'
            }
        },
    ]
</code>```

webpack.build.js is

```<code>// imports
const webpack = require('webpack');
const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InterpolateHtmlPlugin = require('interpolate-html-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const common = require("./common");

// initial extended configuration
let extendedConfig = {
    extraEntries: {},
    extraOutputs: {},
    extraPlugins: [],
    extraOptimization: {},
    extraModule: {
        extraRules: []
    }
};

const listOfRenamedProps = ["extraEntries", "extraOutputs", "extraPlugins", "extraOptimization", "extraModule"];

// load extended configuration
try {
    extendedConfig = { ...extendedConfig, ...require("../../asab-webui.config") };
    console.log("Extended webpack configuration has been loaded.");
} catch {
    console.log("Extended webpack configuration hasn't been found.");
}

module.exports = {
    build: function(config) {
        // version and build date of the app
        const version = common.getVersion();
        const repository = common.getRepository();
        const buildDate = new Date();
        // paths
        const entry_path = path.resolve(config["dirs"]["src"], 'index.js');
        const html_template_path = path.resolve(config["dirs"]["public"], 'index.html');
        // TODO: This is temporary solution. It will be replaced by date-fns.
        let defaultLocales = /cs/; // Default moment locales (needed for backward compatibility)

        const globalVars = new webpack.DefinePlugin(
            common.JSONStringifyValues({
                "__CONFIG__": config["app"],
                "__DEV_CONFIG__": {},
                "__VERSION__": version,
                "__BUILD_DATE__": buildDate,
                "__REPOSITORY__": repository
            })
        );

        const defaultPlugins = [
            new HtmlWebpackPlugin({
                template: html_template_path,
                minify: {
                    removeAttributeQuotes: true,
                    collapseWhitespace: true,
                    removeComments: true
                }
            }),
            new InterpolateHtmlPlugin(
                common.convertKeysForHtml(config["app"])
                // Converts keys like this:
                // "publicUrl" -> "__PUBLIC_URL__"
                // "apiUrl" -> "__API_URL__"
            ),
            new UglifyJsPlugin({
                uglifyOptions: {
                    output: {
                        comments: false
                    }
                }
            }),
            // Extracts file styles.css
            new MiniCssExtractPlugin({ filename: '[name].[contenthash:8].css'}),
            // new MiniCssExtractPlugin({ filename: 'assets/css/[name].css' }),
            // new MiniCssExtractPlugin(),
            // Remove moment locales from bundle except those which are defined as second parameter
            new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, defaultLocales),
        ];

        const filteredExtendedConfig = {...extendedConfig};
        listOfRenamedProps.forEach(prop => delete filteredExtendedConfig[prop]);

        const newModule =  {...extendedConfig.extraModule};
        delete newModule.extraRules;

        return {
            entry: {
                app: entry_path,
                ...extendedConfig.extraEntries
            },
            mode: 'production',
            output: {
                filename: 'assets/js/[name].[contenthash:8].bundle.js',
                chunkFilename: 'assets/js/[name].[contenthash:8].chunk.js',
                path: path.resolve(config["dirs"]["dist"]),
                publicPath: '',
                // assetModuleFilename: "images/[hash][ext][query]",
                ...extendedConfig.extraOutputs
            },
            resolve: config["webpack"]["resolve"],
            module: {
                rules: [
                    ...common.getRules(config),
                    ...extendedConfig.extraModule.extraRules
                ],
                ...newModule
            },
            plugins: [
                globalVars,
                ...defaultPlugins,
                ...extendedConfig.extraPlugins
            ],
            optimization: {
                splitChunks: {
                    chunks: 'all',
                    cacheGroups: {
                        vendor: {
                            name: 'vendors',
                            test: /[\\/]node_modules[\\/]((?!(date-fns)).*)[\\/]/,
                            chunks: 'all',
                            enforce: true
                        },
                        commons: {
                            test: /[\\/]node_modules[\\/]/,
                            name(module, chunks, cacheGroupKey) {
                              const moduleFileName = module
                                .identifier()
                                .split('/')
                                .reduceRight((item) => item);
                              const allChunksNames = chunks.map((item) => item.name).join('~');
                              return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
                            },
                            chunks: 'all',
                        },
                    }
                },
                minimize: true,
                minimizer: [ // Minimizes output javascript
                    `...`,
                    new CssMinimizerPlugin(),
                ],
                ...extendedConfig.extraOptimization
            },
            ...filteredExtendedConfig
        };
    }
}
</code>```

and src/index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Application } from 'asab-webui';
import { HashRouter } from 'react-router-dom';

// Configuration
let ConfigDefaults = {
    ...
};

var modules = [ ... ];

const sidebarItemsOrder = [ ... ];

ReactDOM.render((
    <HashRouter>
        <Application
            sidebarItemsOrder={sidebarItemsOrder}
            configdefaults={ConfigDefaults}
            modules={modules}
            defaultpath={__CONFIG__.defaultpath ? __CONFIG__.defaultpath : "/home"}
            hasSidebar={true}
        />
    </HashRouter>
), document.getElementById('app'));
</code>```

package.json

```<code>{
    "name": "seacat-admin-webui",
    "version": "1.0.0",
    "main": "index.js",
    "scripts": {
        "start": "node ./asab-webui/script/start.js",
        "build": "node ./asab-webui/script/build.js"
    },
    "author": "TeskaLabs Ltd.",
    "license": "GPL-3.0",
    "description": "Web UI for a SeaCat administration",
    "browserslist": [
        "defaults"
    ],
    "devDependencies": {
        "@babel/core": "^7.20.5",
        "@babel/preset-env": "^7.20.2",
        "@babel/preset-react": "^7.18.6",
        "argparse": "^2.0.1",
        "assign-deep": "^1.0.1",
        "autoprefixer": "^10.4.13",
        "babel-loader": "^9.1.0",
        "babel-plugin-transform-object-rest-spread": "^7.0.0-beta.3",
        "babel-polyfill": "^7.0.0-beta.3",
        "css-loader": "^6.7.2",
        "css-mqpacker": "^7.0.0",
        "cssnano": "^5.1.14",
        "file-loader": "^6.2.0",
        "fs-extra": "^10.1.0",
        "html-webpack-plugin": "^5.5.0",
        "interpolate-html-plugin": "^4.0.0",
        "mini-css-extract-plugin": "^2.7.0",
        "optimize-css-assets-webpack-plugin": "^6.0.1",
        "postcss": "^8.4.19",
        "postcss-loader": "^7.0.1",
        "sass": "^1.56.1",
        "sass-loader": "^13.2.0",
        "style-loader": "^3.3.1",
        "uglifyjs-webpack-plugin": "^2.2.0",
        "webpack": "^5.74.0",
        "webpack-cli": "^5.0.0",
        "webpack-dev-server": "^4.11.1",
        "webpack-node-externals": "^3.0.0",
        "window": "^4.2.7"
    },
    "dependencies": {
        "@coreui/icons": "^1.0.1",
        "axios": "^0.21.1",
        "bootstrap": "^4",
        "core-js": "3",
        "css-minimizer-webpack-plugin": "^4.2.2",
        "date-fns": "^2.28.0",
        "file-saver": "^2.0.5",
        "i18next": "^20.1.0",
        "i18next-browser-languagedetector": "^6.1.0",
        "i18next-http-backend": "^1.2.1",
        "react": "^17.0.0",
        "react-content-loader": "^6.1.0",
        "react-dom": "^17.0.0",
        "react-helmet": "^6.1.0",
        "react-hook-form": "7.37.0",
        "react-i18next": "^11.8.12",
        "react-json-view": "^1.21.1",
        "react-redux": "^7.2.0",
        "react-router-dom": "^5.1.2",
        "react-simple-tree-menu": "^1.1.18",
        "reactstrap": "^8.9.0",
        "redux": "^4.0.1"
    }
}
</code>```

from my understanding the error happens for a '.js' file and suggests a loader for such file has not been configured, but there is the 'bable-loader' configured for a .js files which worked fine with webpack v4. The generated .js files are working correctly and are split into chunks. Also, the built application works perfectly fine. I want to get rid of all errors to avoid any further issues in the future.

Body:
I'm currently migrating my project from Webpack v4 to v5 and my build finishes with an Error

@My-MacBook-Pro seacat-webui % node --trace-deprecation node_modules/webpack/bin/webpack.js
assets by status 354 bytes [cached] 1 asset
./src/index.js 2.67 KiB [built] [code generated] [1 error]

ERROR in ./src/index.js 103:1
Module parse failed: Unexpected token (103:1)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| ReactDOM.render((
>   <HashRouter>
|       <Application
|           sidebarItemsOrder={sidebarItemsOrder}

webpack 5.75.0 compiled with 1 error in 252 ms

The Error has nothing to do with <HashRouter> itself, the same message appeares pointing the error to <Application ... > if I comment out the hashrouter.

my rules in common.js are

exports.getRules = function(config) {
    return [
        {
            test: /\.(js)$/,
            use: [{
                loader: 'babel-loader',
                options: { presets: [[
                    '@babel/preset-env',
                    {
                        useBuiltIns: "entry",
                        targets: {
                        esmodules: true,
                        },
                        corejs: {
                            version: "3",
                            proposals: true
                        }
                    }
                ],['@babel/react']], plugins: ["transform-object-rest-spread"] }
            }],
            exclude: '/node_modules/'
        },
        {
            test: /\.(s[ac]|c)ss$/i,
            use: [
                MiniCssExtractPlugin.loader, //extracts CSS into files
                {
                    loader: 'css-loader',  // Second, turn css into commonjs
                    options: { sourceMap: true }
                },
                {
                    loader: 'postcss-loader',
                    options: { sourceMap: true }
                },
                {
                    loader: 'sass-loader', // First, turn sass into css
                    options: { sourceMap: true }
                }
            ],
        },
        {
            test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?.*)?$/,
            type: 'asset/resource',
            generator: {
                filename: 'assets/svg/[name][contenthash:8][ext]'
            }
        },
    ]

webpack.build.js is

// imports
const webpack = require('webpack');
const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InterpolateHtmlPlugin = require('interpolate-html-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const common = require("./common");

// initial extended configuration
let extendedConfig = {
    extraEntries: {},
    extraOutputs: {},
    extraPlugins: [],
    extraOptimization: {},
    extraModule: {
        extraRules: []
    }
};

const listOfRenamedProps = ["extraEntries", "extraOutputs", "extraPlugins", "extraOptimization", "extraModule"];

// load extended configuration
try {
    extendedConfig = { ...extendedConfig, ...require("../../asab-webui.config") };
    console.log("Extended webpack configuration has been loaded.");
} catch {
    console.log("Extended webpack configuration hasn't been found.");
}

module.exports = {
    build: function(config) {
        // version and build date of the app
        const version = common.getVersion();
        const repository = common.getRepository();
        const buildDate = new Date();
        // paths
        const entry_path = path.resolve(config["dirs"]["src"], 'index.js');
        const html_template_path = path.resolve(config["dirs"]["public"], 'index.html');
        // TODO: This is temporary solution. It will be replaced by date-fns.
        let defaultLocales = /cs/; // Default moment locales (needed for backward compatibility)

        const globalVars = new webpack.DefinePlugin(
            common.JSONStringifyValues({
                "__CONFIG__": config["app"],
                "__DEV_CONFIG__": {},
                "__VERSION__": version,
                "__BUILD_DATE__": buildDate,
                "__REPOSITORY__": repository
            })
        );

        const defaultPlugins = [
            new HtmlWebpackPlugin({
                template: html_template_path,
                minify: {
                    removeAttributeQuotes: true,
                    collapseWhitespace: true,
                    removeComments: true
                }
            }),
            new InterpolateHtmlPlugin(
                common.convertKeysForHtml(config["app"])
                // Converts keys like this:
                // "publicUrl" -> "__PUBLIC_URL__"
                // "apiUrl" -> "__API_URL__"
            ),
            new UglifyJsPlugin({
                uglifyOptions: {
                    output: {
                        comments: false
                    }
                }
            }),
            // Extracts file styles.css
            new MiniCssExtractPlugin({ filename: '[name].[contenthash:8].css'}),
            // new MiniCssExtractPlugin({ filename: 'assets/css/[name].css' }),
            // new MiniCssExtractPlugin(),
            // Remove moment locales from bundle except those which are defined as second parameter
            new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, defaultLocales),
        ];

        const filteredExtendedConfig = {...extendedConfig};
        listOfRenamedProps.forEach(prop => delete filteredExtendedConfig[prop]);

        const newModule =  {...extendedConfig.extraModule};
        delete newModule.extraRules;

        return {
            entry: {
                app: entry_path,
                ...extendedConfig.extraEntries
            },
            mode: 'production',
            output: {
                filename: 'assets/js/[name].[contenthash:8].bundle.js',
                chunkFilename: 'assets/js/[name].[contenthash:8].chunk.js',
                path: path.resolve(config["dirs"]["dist"]),
                publicPath: '',
                // assetModuleFilename: "images/[hash][ext][query]",
                ...extendedConfig.extraOutputs
            },
            resolve: config["webpack"]["resolve"],
            module: {
                rules: [
                    ...common.getRules(config),
                    ...extendedConfig.extraModule.extraRules
                ],
                ...newModule
            },
            plugins: [
                globalVars,
                ...defaultPlugins,
                ...extendedConfig.extraPlugins
            ],
            optimization: {
                splitChunks: {
                    chunks: 'all',
                    cacheGroups: {
                        vendor: {
                            name: 'vendors',
                            test: /[\\/]node_modules[\\/]((?!(date-fns)).*)[\\/]/,
                            chunks: 'all',
                            enforce: true
                        },
                        commons: {
                            test: /[\\/]node_modules[\\/]/,
                            name(module, chunks, cacheGroupKey) {
                              const moduleFileName = module
                                .identifier()
                                .split('/')
                                .reduceRight((item) => item);
                              const allChunksNames = chunks.map((item) => item.name).join('~');
                              return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
                            },
                            chunks: 'all',
                        },
                    }
                },
                minimize: true,
                minimizer: [ // Minimizes output javascript
                    `...`,
                    new CssMinimizerPlugin(),
                ],
                ...extendedConfig.extraOptimization
            },
            ...filteredExtendedConfig
        };
    }
}

and src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Application } from 'asab-webui';
import { HashRouter } from 'react-router-dom';

// Configuration
let ConfigDefaults = {
    ...
};

var modules = [ ... ];

const sidebarItemsOrder = [ ... ];

ReactDOM.render((
    <HashRouter>
        <Application
            sidebarItemsOrder={sidebarItemsOrder}
            configdefaults={ConfigDefaults}
            modules={modules}
            defaultpath={__CONFIG__.defaultpath ? __CONFIG__.defaultpath : "/home"}
            hasSidebar={true}
        />
    </HashRouter>
), document.getElementById('app'));

package.json

{
    "name": "seacat-admin-webui",
    "version": "1.0.0",
    "main": "index.js",
    "scripts": {
        "start": "node ./asab-webui/script/start.js",
        "build": "node ./asab-webui/script/build.js"
    },
    "author": "TeskaLabs Ltd.",
    "license": "GPL-3.0",
    "description": "Web UI for a SeaCat administration",
    "browserslist": [
        "defaults"
    ],
    "devDependencies": {
        "@babel/core": "^7.20.5",
        "@babel/preset-env": "^7.20.2",
        "@babel/preset-react": "^7.18.6",
        "argparse": "^2.0.1",
        "assign-deep": "^1.0.1",
        "autoprefixer": "^10.4.13",
        "babel-loader": "^9.1.0",
        "babel-plugin-transform-object-rest-spread": "^7.0.0-beta.3",
        "babel-polyfill": "^7.0.0-beta.3",
        "css-loader": "^6.7.2",
        "css-mqpacker": "^7.0.0",
        "cssnano": "^5.1.14",
        "file-loader": "^6.2.0",
        "fs-extra": "^10.1.0",
        "html-webpack-plugin": "^5.5.0",
        "interpolate-html-plugin": "^4.0.0",
        "mini-css-extract-plugin": "^2.7.0",
        "optimize-css-assets-webpack-plugin": "^6.0.1",
        "postcss": "^8.4.19",
        "postcss-loader": "^7.0.1",
        "sass": "^1.56.1",
        "sass-loader": "^13.2.0",
        "style-loader": "^3.3.1",
        "uglifyjs-webpack-plugin": "^2.2.0",
        "webpack": "^5.74.0",
        "webpack-cli": "^5.0.0",
        "webpack-dev-server": "^4.11.1",
        "webpack-node-externals": "^3.0.0",
        "window": "^4.2.7"
    },
    "dependencies": {
        "@coreui/icons": "^1.0.1",
        "axios": "^0.21.1",
        "bootstrap": "^4",
        "core-js": "3",
        "css-minimizer-webpack-plugin": "^4.2.2",
        "date-fns": "^2.28.0",
        "file-saver": "^2.0.5",
        "i18next": "^20.1.0",
        "i18next-browser-languagedetector": "^6.1.0",
        "i18next-http-backend": "^1.2.1",
        "react": "^17.0.0",
        "react-content-loader": "^6.1.0",
        "react-dom": "^17.0.0",
        "react-helmet": "^6.1.0",
        "react-hook-form": "7.37.0",
        "react-i18next": "^11.8.12",
        "react-json-view": "^1.21.1",
        "react-redux": "^7.2.0",
        "react-router-dom": "^5.1.2",
        "react-simple-tree-menu": "^1.1.18",
        "reactstrap": "^8.9.0",
        "redux": "^4.0.1"
    }
}

from my understanding the error happens for a '.js' file and suggests a loader for such file has not been configured, but there is the 'bable-loader' configured for a .js files which worked fine with webpack v4. The generated .js files are working correctly and are split into chunks. Also, the built application works perfectly fine. I want to get rid of all errors to avoid any further issues in the future.


问:
Can someone explain how do I get current ROWVERSION when using Optimistic locking?
This is the table

```<code>CREATE TABLE my_table (
id INT PRIMARY KEY,
name VARCHAR(255),
version ROWVERSION
</code>```

)

This is when update

```<code>  UPDATE table_name
SET col1 = val1, col2 = val2, ...
WHERE id = some_id AND version = current_version
</code>```

how do I get current_version to compare with version on line 3?

And I try to implemnt optismitc locking with above example, am i doing it right?

```<code> string query = "UPDATE PRODUCT SET stockQuantity =stockQuantity - @value Where ID =@id  AND RowVersion = RowVersion";
</code>```

Body:
This is the table

CREATE TABLE my_table (
id INT PRIMARY KEY,
name VARCHAR(255),
version ROWVERSION

)

This is when update

  UPDATE table_name
SET col1 = val1, col2 = val2, ...
WHERE id = some_id AND version = current_version

how do I get current_version to compare with version on line 3?

And I try to implemnt optismitc locking with above example, am i doing it right?

 string query = "UPDATE PRODUCT SET stockQuantity =stockQuantity - @value Where ID =@id  AND RowVersion = RowVersion";


问:
Testing an API endpoint hosted locally
How can I correctly test an api call if the api call is to a localhost which only runs when I call yarn api in my terminal?

I have some JSON hosted locally (http://localhost:3002/countries) as a part of my project, when writing a test for this what is the correct way to mock/stub it? My react app makes a call to this endpoint to return a list of countries and I'd like to add a test to check the API has been called correctly.

What I have so far is below which I have imported to my test file:

```<code>Countries {
  api() {
    return fetch(`http://localhost:3002/countries`)
    .then((res) => {
        return res.json()
  })
}
</code>```

This doesn't feel correct though as it's on a localhost and my understanding is that I'd want constant datapoints to be used for tests, so would it be more sensible to have something like:

```<code>const countryList{
"Foo" : "Bar",
...
}
</code>```

And then pass this const in to my test file to check for a correct API call?

Title: Testing an API endpoint hosted locally

Body:
How can I correctly test an api call if the api call is to a localhost which only runs when I call yarn api in my terminal?

I have some JSON hosted locally (http://localhost:3002/countries) as a part of my project, when writing a test for this what is the correct way to mock/stub it? My react app makes a call to this endpoint to return a list of countries and I'd like to add a test to check the API has been called correctly.

What I have so far is below which I have imported to my test file:

Countries {
  api() {
    return fetch(`http://localhost:3002/countries`)
    .then((res) => {
        return res.json()
  })
}

This doesn't feel correct though as it's on a localhost and my understanding is that I'd want constant datapoints to be used for tests, so would it be more sensible to have something like:

const countryList{
"Foo" : "Bar",
...
}

And then pass this const in to my test file to check for a correct API call?


问:
Cast a (png/pdf)bytearray to a file js/java
In the Front End we send an id via axios post to the backend to get a (png or pdf) as a  bytearray. Then I would  send the (png or pdf) back via the response. The problem is that I need the (png or pdf) as a file for filepond in js on my frontend.
But i didnt find a suitable way to cast my bytearray into a file.

I tried:

1. MimeType + Blob

Backend (Java):

```<code> String contenType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(byteArray));
 MediaType mimeType=MediaType.parseMediaType(contenType);
 responseContainer = new ResponseContainer("100", "s3 fileDownload was ok", null, true, byteArray);
            return ResponseEntity.ok().contentType(mimeType).body(responseContainer);
</code>```

Frontend (JS):

```<code>///let bytes=new Uint8Array(response.byteArray.length)
for(let i=0;i<bytes.length;i++){
   bytes[i]=response.byteArray[i];
}
let blob=new Blob([bytes],{type: response.mimeType})
let f1=new File([blob],attarray[x].filename,{type: response.mimeType})
this.$refs.pond.addFile(f1);
</code>```

The byteArray coudn't be reconstructed correctly(Uint or for loop or direct, therefor the image/pdf was unusable.

2. BufferedImage

Backend (Java):

```<code>ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
BufferedImage bufferedImage = ImageIO.read(bis);
ImageIO.write(bufferedImage, contenType, new File("test.png"));
File outfile=new File("test.jpg");
ImageIO.write(bufferedImage,contenType,outfile);
</code>```

I don't think that it's usable because we need a path for test.png and it wouldn't be feasible to get a path to the backend from frontend.

3. HTTP/Header/Content-Disposition
According to https://github.com/eligrey/FileSaver.js/wiki/Saving-a-remote-file#using-http-header

It seems that there should be a simple solution for this problem but I am not able to find it, so I am asking for your help.Thanks in advance.

I am using Vue3, Spring, JavaScript, Java, Axios, FilePond

Body:
In the Front End we send an id via axios post to the backend to get a (png or pdf) as a  bytearray. Then I would  send the (png or pdf) back via the response. The problem is that I need the (png or pdf) as a file for filepond in js on my frontend.
But i didnt find a suitable way to cast my bytearray into a file.

I tried:

1. MimeType + Blob

Backend (Java):

 String contenType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(byteArray));
 MediaType mimeType=MediaType.parseMediaType(contenType);
 responseContainer = new ResponseContainer("100", "s3 fileDownload was ok", null, true, byteArray);
            return ResponseEntity.ok().contentType(mimeType).body(responseContainer);

Frontend (JS):

///let bytes=new Uint8Array(response.byteArray.length)
for(let i=0;i<bytes.length;i++){
   bytes[i]=response.byteArray[i];
}
let blob=new Blob([bytes],{type: response.mimeType})
let f1=new File([blob],attarray[x].filename,{type: response.mimeType})
this.$refs.pond.addFile(f1);

The byteArray coudn't be reconstructed correctly(Uint or for loop or direct, therefor the image/pdf was unusable.

2. BufferedImage

Backend (Java):

ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
BufferedImage bufferedImage = ImageIO.read(bis);
ImageIO.write(bufferedImage, contenType, new File("test.png"));
File outfile=new File("test.jpg");
ImageIO.write(bufferedImage,contenType,outfile);

I don't think that it's usable because we need a path for test.png and it wouldn't be feasible to get a path to the backend from frontend.

3. HTTP/Header/Content-Disposition
According to https://github.com/eligrey/FileSaver.js/wiki/Saving-a-remote-file#using-http-header

It seems that there should be a simple solution for this problem but I am not able to find it, so I am asking for your help.Thanks in advance.

I am using Vue3, Spring, JavaScript, Java, Axios, FilePond


问:
How to track components/views that trigger Angular change detection
is there a way to track components that cause change detection?

I tried with Angular DevTools of Chrome, but it is not detailed

Thanks a lot


问:
Google Shared Drives Permissions in a tree structure
For our business we are looking to find out which folders are shared with who. So we can keep it clean and organized.

I've been looking for some code that can help me with this, but the only option available at the moment is Gat+ from GatLabs. Witch isn't free and to be honest I don't want to put everything with a 3rd party.

Doing this manually isn't an option, we have more than 50 shared drive folders with subfolders.

Looked in google admin, google developer but there's no where the option or something of code to retract all of this information.


问:
How to resolve error on ProcessMaker 4.3.0 instllation?
My server specifications:
Centos 7.9
PHP 8.2
Nginx
MySQL 8.0
Composer 2.4.4
Node 16.18.1
NPM 8.19.3
Redis 5
Docker

I have installed all the dependencies required for ProcessMaker 4.3.0 running(mentioned the versions above). After enabling the npm, laravel and artisan horizan server, I hit the URL and get 500 error. On checking the nginx log I get the following error:

[error] 8150#8150: *512 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught ErrorException: file_put_contents(/opt/processmaker-4.3.0/storage/framework/views/ef0f3565ae74afa67f42e441ee3da8cfbe934ae1.php): Failed to open stream: Permission denied in /opt/processmaker-4.3.0/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:187 Stack trace: #0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() #1 /opt/processmaker-4.3.0/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php(187): file_put_contents() #2 /opt/processmaker-4.3.0/vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php(169): Illuminate\Filesystem\Filesystem->put() #3 /opt/processmaker-4.3.0/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(55): Illuminate\View\Compilers\BladeCompiler->compile() #4 /opt/processmaker-4.3.0/vendor/facade/ignition/src/Views/Engines/CompilerEngine.php(37): Illuminate\View\Engines\CompilerEngine->get() #5 /opt/processmaker-4.3.0/vendor/laravel/fram...PHP message: PHP Fatal error:  Uncaught ErrorException: file_put_contents(/opt/processmaker-4.3.0/storage/framework/views/ef0f3565ae74afa67f42e441ee3da8cfbe934ae1.php): Failed to open stream: Permission denied in /opt/processmaker-4.3.0/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:187 Stack trace: #0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() #1 /opt/processmaker-4.3.0/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php(187): file_put_contents() #2 /opt/processmaker-4.3.0/vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php(169): Illuminate\Filesystem\Filesystem->put() #3 /opt/processmaker-4.3.0/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(55): Illuminate\View\Compilers\BladeCompiler->compile() #4 /opt/processmaker-4.3.0/vendor/facade/ignition/src/Views/Engines/CompilerEngine.php(37): Illuminate\View\Engines\CompilerEngine->get

I have already given 755 permission to the storage and vendor folder in processmaker. Also the owner ship and group of all the folders and files is nginx.

Whatelse, could I be missing out?


问:
Google auth redirect is not urlencoded
I'm using express + passport to make use of Google Authentication. Everything works fine on my localhost, but not on the server (express app is served by the App Engine).

The difference is that on localhost I get the correct redirect url, like this

http://localhost:5000/users/google/redirect?code=4%2F0AfgeXvtVTmjgZ21V65thwCtefi_4cpdNxnuXOacPmpjLiWM5d1*******8blw&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=0&prompt=consent

but on the server it is not encoded, so I get this:

https://my-app-url/users/google/redirect?code=4/0AfgeXvv1KIxY2dxzy57_6FbjspdQSxmtP_lrSyLbfTcPB967c*******8QDutF-A&scope=email%20profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email%20openid&authuser=1&hd=cronvall.com&prompt=none

Why is that, and what can I do to fix that?

Title: Google auth redirect is not urlencoded


问:
Python 3 Grocery List
Starting with just an empty dictionary, write a function that creates a grocery list that does the following:

• Add An Item (takes three inputs from the user: the name of the item, price for one item, and the quantity, then add it to the existing list)

• Remove An Item (takes a string input from the user and removes all instances from the list)

• Print Entire List (prints out all the contents of the list)

• Calculate Cost (prints out the total cost of the items in the list)

• Exit (exit the program)

The items are taken as three different data types: string (name), float (price), and int (quantity) and all three attributes are stored as one element in the dictionary. Duplicates are NOT allowed. When an item with the same name is attempted to be added, it will prompt the user to enter a new item again.

When removing an item, it must not be case sensitive when matching with the item in the list for it to be removed (in other words “Eggs” and “eggS” still refer to the same item).

Printing the entire list this time would now include the price and quantity of the items. The Calculate Cost command should also print the entire list first before showing the total cost of the items.

The program should continue running until the user decides the terminate it by doing the Exit command. Otherwise, it should catch all errors whenever possible.

The output of your code should look like this:
first
second

This is what I've come up with but its not like the expected output and some of it are not functioning.

```<code>grocery_list=()
grocery_history=[]
def grocery_add():
    needs_items = True
    while needs_items == True:

        print("ITEM ADD \nGive the following information:")
        name=input("Name: ")
        cost=input("Price: ")
        quantity=input("Quantity: ")
        grocery_list={'item_name':name,'quantity':int(quantity),'cost':float(cost)}
        grocery_history.append(grocery_list)
        break

def remove_items():
    global grocery_list #since we set grocery list to a new list
    item_to_remove = input("Which item do you want to remove? ").lower() #we set input items to lowercase
    newlist = grocery_list.copy() #set grocery list to newlist
    for item in grocery_list:
        if item.lower() == item_to_remove:
            newlist.remove(item) #remove item and its duplicates
    grocery_list = newlist

def display_list():
    print("\n PRINTING GROCERY LIST...  \n")
    for item in grocery_history:
        print(item)

def calculate_cost():
    grand_total=0
    for item in grocery_history:
        item_total=item['quantity']*item['cost']
        grand_total+=item_total
        print("%d %s @ $%f ea $%f" %(item['quantity'],item['name'],item['cost'], item_total))
        item_total=0

    print("TOTAL COST: ",grand_total)

def redo():
    while True:
        text=str(input("\n What would you like to do? \n 1 - Add an Item \n 2 - Remove an Item \n 3 - Print entire List \n 4 - Calculate Cost \n 5 - Exit program \n  \n Choice: "))
        if text == str("1"):
            grocery_add()
            redo()
        if text == str("2"):
            remove_items()
            redo()
        if text == str ("3"):
            display_list()
            continue
        if text == str ("4"):
            calculate_cost()
            redo()
        if text == str("5"):
            print (" \nThank you for shopping!!!\n \nTerminating Program...")
            quit()
        else:
            print("You should choose among the choices to proceed.")
            redo()

        grocery_add(item)

redo()
remove_items()
grocery_add()
display_list()
</code>```

Title: Python 3 Grocery List

Body:
Starting with just an empty dictionary, write a function that creates a grocery list that does the following:

• Add An Item (takes three inputs from the user: the name of the item, price for one item, and the quantity, then add it to the existing list)

• Remove An Item (takes a string input from the user and removes all instances from the list)

• Print Entire List (prints out all the contents of the list)

• Calculate Cost (prints out the total cost of the items in the list)

• Exit (exit the program)

The items are taken as three different data types: string (name), float (price), and int (quantity) and all three attributes are stored as one element in the dictionary. Duplicates are NOT allowed. When an item with the same name is attempted to be added, it will prompt the user to enter a new item again.

When removing an item, it must not be case sensitive when matching with the item in the list for it to be removed (in other words “Eggs” and “eggS” still refer to the same item).

Printing the entire list this time would now include the price and quantity of the items. The Calculate Cost command should also print the entire list first before showing the total cost of the items.

The program should continue running until the user decides the terminate it by doing the Exit command. Otherwise, it should catch all errors whenever possible.

The output of your code should look like this:
first
second

This is what I've come up with but its not like the expected output and some of it are not functioning.

grocery_list=()
grocery_history=[]
def grocery_add():
    needs_items = True
    while needs_items == True:

        print("ITEM ADD \nGive the following information:")
        name=input("Name: ")
        cost=input("Price: ")
        quantity=input("Quantity: ")
        grocery_list={'item_name':name,'quantity':int(quantity),'cost':float(cost)}
        grocery_history.append(grocery_list)
        break

def remove_items():
    global grocery_list #since we set grocery list to a new list
    item_to_remove = input("Which item do you want to remove? ").lower() #we set input items to lowercase
    newlist = grocery_list.copy() #set grocery list to newlist
    for item in grocery_list:
        if item.lower() == item_to_remove:
            newlist.remove(item) #remove item and its duplicates
    grocery_list = newlist

def display_list():
    print("\n PRINTING GROCERY LIST...  \n")
    for item in grocery_history:
        print(item)

def calculate_cost():
    grand_total=0
    for item in grocery_history:
        item_total=item['quantity']*item['cost']
        grand_total+=item_total
        print("%d %s @ $%f ea $%f" %(item['quantity'],item['name'],item['cost'], item_total))
        item_total=0

    print("TOTAL COST: ",grand_total)

def redo():
    while True:
        text=str(input("\n What would you like to do? \n 1 - Add an Item \n 2 - Remove an Item \n 3 - Print entire List \n 4 - Calculate Cost \n 5 - Exit program \n  \n Choice: "))
        if text == str("1"):
            grocery_add()
            redo()
        if text == str("2"):
            remove_items()
            redo()
        if text == str ("3"):
            display_list()
            continue
        if text == str ("4"):
            calculate_cost()
            redo()
        if text == str("5"):
            print (" \nThank you for shopping!!!\n \nTerminating Program...")
            quit()
        else:
            print("You should choose among the choices to proceed.")
            redo()

        grocery_add(item)

redo()
remove_items()
grocery_add()
display_list()


问:
how to connect to office 365 server using nodemailer
const express = require("express");
const nodemailer = require("nodemailer");

const app = express();

```<code>

const mailTransporter = nodemailer.createTransporter({
host: "smtp.office365.com",
port: 587,
auth: {
user: "test@test.com",
pass: "pass@123",
},
})
</code>```

Body:
const express = require("express");
const nodemailer = require("nodemailer");

const app = express();

const mailTransporter = nodemailer.createTransporter({
host: "smtp.office365.com",
port: 587,
auth: {
user: "test@test.com",
pass: "pass@123",
},
})


问:
scoping static_assert for class static member array
I'd like to enforce a compile-time constraint about the length of a class static member variable array using static_assert(). However, the length of the variable named lpfilter[] is not known in the declaration in the header, and only known later in the definition. I'm uncertain how best to implement this static_assert so that it may see the static private array length. I have a workaround using a private scoped function to hold static_asserts, but is there a better way? I'm using clang 15 in C++14 mode.

```<code>//in header
class test
{
private:
    //member constants
    static const float lpfilter[];

    //feels like a workaround
    void testChecker(void);
};
</code>```
```<code>//early in cpp file
const float test::lpfilter[] = {
    #include "a_single_line_lpfilter.csv"
};
</code>```

I've made a few attempts so far. Each build error makes sense:

```<code>//after lpfilter[] definition in cpp file

//error: 'lpfilter' is a private member of 'test'
static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");

//error: redefinition of 'test'
class test
{
static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");
}

//error: expected unqualified-id
test::static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");

//works, but I'd prefer not to have to use a function to do this
void test::testChecker()
{
static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");
}
</code>```

Body:
I'd like to enforce a compile-time constraint about the length of a class static member variable array using static_assert(). However, the length of the variable named lpfilter[] is not known in the declaration in the header, and only known later in the definition. I'm uncertain how best to implement this static_assert so that it may see the static private array length. I have a workaround using a private scoped function to hold static_asserts, but is there a better way? I'm using clang 15 in C++14 mode.

//in header
class test
{
private:
    //member constants
    static const float lpfilter[];

    //feels like a workaround
    void testChecker(void);
};

//early in cpp file
const float test::lpfilter[] = {
    #include "a_single_line_lpfilter.csv"
};

I've made a few attempts so far. Each build error makes sense:

//after lpfilter[] definition in cpp file

//error: 'lpfilter' is a private member of 'test'
static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");

//error: redefinition of 'test'
class test
{
static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");
}

//error: expected unqualified-id
test::static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");

//works, but I'd prefer not to have to use a function to do this
void test::testChecker()
{
static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");
}


问:
DenseNet121 (PyTorch) : On the BatchNorm2d and Global Average Pooling layers
Running the following code

```<code>from torchvision import models
dnet121 = models.densenet121(pretrained = True)
dnet121
</code>```

yields a DenseNet121 description which ends as follows :

Based on this, I would appreciate your assistance of the following:

As per PyTorch BatchNorm2d documentation https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html the BatchNorm2d transform accepts a 4-dim tensor (here with channels C=1024) and outputs a 4-dim tensor. But, as per above image, how does the output 4-dim tensor convert to the 1024 in_features of the Linear layer ? Is it due to a Global Average Pooling layer ?

As per DenseNet official paper https://arxiv.org/pdf/1608.06993.pdf the classifier starts indeed with a Global Average Pooling (GAP) layer, but why can't we see it here?

For the purposes of a task, I would like to replace the GAP layer with a nn.Flatten layer. How can I get code access to the GAP layer though?

Body:
Running the following code

from torchvision import models
dnet121 = models.densenet121(pretrained = True)
dnet121

yields a DenseNet121 description which ends as follows :

Based on this, I would appreciate your assistance of the following:

As per PyTorch BatchNorm2d documentation https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html the BatchNorm2d transform accepts a 4-dim tensor (here with channels C=1024) and outputs a 4-dim tensor. But, as per above image, how does the output 4-dim tensor convert to the 1024 in_features of the Linear layer ? Is it due to a Global Average Pooling layer ?

As per DenseNet official paper https://arxiv.org/pdf/1608.06993.pdf the classifier starts indeed with a Global Average Pooling (GAP) layer, but why can't we see it here?

For the purposes of a task, I would like to replace the GAP layer with a nn.Flatten layer. How can I get code access to the GAP layer though?


问:
Doodle - one vote per participant
I am a little frustrated with the new version of Doodle.
I want to limit the votes of  participants (each participant should be able to select only one time)

In the settings, there is no option about this.

Also, I want each participant to be able to click just "yes" (i.e. check) in an available box (not the options "if need be", "cannot attend" or "pending"

Could you help me, please?

Title: Doodle - one vote per participant


问:
Is one row on correct for 'SELECT (SELECT SUM(t.val)) FROM mytable t'
Postgres and some online SQL engines return just one row for the SELECT:

```<code>CREATE TABLE mytable(val INTEGER);
INSERT INTO mytable VALUES (1), (2), (3), (NULL);

SELECT (SELECT SUM(t.val)) FROM mytable t;
</code>```

The result is:

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

Does it correspond to the SQL spec? Which section on the spec do I need?

Should the subquery be invoked for every table record? Why the result is not several rows like:

```<code>1
2
3
null
</code>```

Body:
Postgres and some online SQL engines return just one row for the SELECT:

CREATE TABLE mytable(val INTEGER);
INSERT INTO mytable VALUES (1), (2), (3), (NULL);

SELECT (SELECT SUM(t.val)) FROM mytable t;

The result is:

6

Does it correspond to the SQL spec? Which section on the spec do I need?

Should the subquery be invoked for every table record? Why the result is not several rows like:

1
2
3
null


问:
What is the equivalent method of ExecuteQuerySegmentedAsync in Azure.Data.Tables?
What is the equivalent method of ExecuteQuerySegmentedAsync in Azure.Data.Tables?

Recently Microsoft azure sdk deprecated Microsoft.Azure.Cosmos.Table package and recommended to use Azure.Data.Tables package.

But, I couldn't find equivalent ExecuteQuerySegmentedAsync method in Azure.Data.Tables package.

Current code using Microsoft.Azure.Cosmos.Table package below:

```<code>var srcTableName = "TestTable";
var tableBatchResults = new List<TableBatchResult>();
CloudTable srcCloudTable = tableClient.GetTableReference(srcTableName);
var tableContinuationToken = new TableContinuationToken();
do
{
     var entities = new List<T>();

     var segment = await srcCloudTable.ExecuteQuerySegmentedAsync<T>(tableQuery, tableContinuationToken);

     entities.AddRange(segment.Results);

}while (tableContinuationToken != null);
</code>```

How to convert this code with Azure.Data.Tables package.

Body:
What is the equivalent method of ExecuteQuerySegmentedAsync in Azure.Data.Tables?

Recently Microsoft azure sdk deprecated Microsoft.Azure.Cosmos.Table package and recommended to use Azure.Data.Tables package.

But, I couldn't find equivalent ExecuteQuerySegmentedAsync method in Azure.Data.Tables package.

Current code using Microsoft.Azure.Cosmos.Table package below:

var srcTableName = "TestTable";
var tableBatchResults = new List<TableBatchResult>();
CloudTable srcCloudTable = tableClient.GetTableReference(srcTableName);
var tableContinuationToken = new TableContinuationToken();
do
{
     var entities = new List<T>();

     var segment = await srcCloudTable.ExecuteQuerySegmentedAsync<T>(tableQuery, tableContinuationToken);

     entities.AddRange(segment.Results);

}while (tableContinuationToken != null);

How to convert this code with Azure.Data.Tables package.


问:
Is there another way not to use ```.get_feature_names_out()```?
Suppose there is a pipeline as follows....
pipe = make_pipline(one-hot,selectkbest,......)

If you want to see only the selected columns...
selected_mask = pipe.named_steps['selectkbest'].get_feature_names_out()

I tried other methods, but I couldn't solve them... Here's how I tried it.

```<code>all_names = pipe.named_steps['onehotencoder'].get_feature_names()
selected_mask = pipe.named_steps['selectkbest'].get_support()
selected_names = all_names[selected_mask]
</code>```

When I did the following sentence...
selected_names = all_names[selected_mask]

Recall the following error:
TypeError: only integer scalar arrays can be converted to a scalar index

How can I solve it?

Body:
Suppose there is a pipeline as follows....
pipe = make_pipline(one-hot,selectkbest,......)

If you want to see only the selected columns...
selected_mask = pipe.named_steps['selectkbest'].get_feature_names_out()

I tried other methods, but I couldn't solve them... Here's how I tried it.

all_names = pipe.named_steps['onehotencoder'].get_feature_names()
selected_mask = pipe.named_steps['selectkbest'].get_support()
selected_names = all_names[selected_mask]

When I did the following sentence...
selected_names = all_names[selected_mask]

Recall the following error:
TypeError: only integer scalar arrays can be converted to a scalar index

How can I solve it?


问:
How to create a link hosted on a local host port with URL argumentls
I want to create a link hosted on a local host port with URL arguments that will be printed in the console like https://127.0.0.1:5555/?port=5555 and it will print the 5555 in my script. How to do that?

I want to store the arguments in variables after I open the URLs


问:
Psexec reg query script is super slow - how can i speed up?
I'm trying to run this script on a list of computers but it is very slow... do you know a way to speed it up? Can anyone help me?
Thanks

psexec @C:\computers.txt reg query "HKEY_LOCAL_MACHINE\SOFTWARE\etc\etc" >> C:\output.csv

psexec @C:\computers.txt reg query "HKEY_LOCAL_MACHINE\SOFTWARE\etc\etc" >> C:\output.csv

This script works fine but it takes hours to end..


问:
How can I crop a shape inside a shape
So there us a billion and one articles about cropping an image inside a shape. But how do I crop a shape inside a shape?

Lets say I have a star shape inside a rectangular shape and I only want to draw the part of the star that's inside the rectangular.

In PowerPoint - how do I crop a shape inside another shape so nothing from the first shape is drawn outside the second shape?

Title: How can I crop a shape inside a shape


问:
Conditional Refresh of Pivot Table in Excel
I have an Excel file with a data set in 'sheet1' that is refreshed every hour. On 'sheet2' I have 24 pivot tables (and corresponding chart), one for each hour. For each pivot table (e.g. 15:00), I want the pivot table to refresh once the data of hour 15 is downloaded. Then, it needs to remain unchanged for 24 hours (as the data refresh overrules all data of previous hour) and update again when the data of hour 15 of the next day is downloaded.

So every hour, the next pivot table in line should be refreshed, while all others remain unchanged, and start again with the first one when a new day has started.

Currently I have set it up like:

In cell A1: Hour of last data as number (e.g. 15, 16, etc.)

VBA code for 'sheet2':

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Workbooks("Filename").Sheets("sheet2").Range("A1") = 15 Then
    Application.EnableEvents = False
    Workbooks("Filename").Sheets("sheet2").PivotTables("Pivot1500").RefreshTable
    Application.EnableEvents = True

End If

End Sub
</code>```

For now I only have VBA code for hour 15, to try this out. But unfortunately, this either results in now refresh of the pivot table, refreshing all other pivot tables as well, or refreshing pivot table 'Pivot1500' even when data of following hours is downloaded and cell A1 is no longer 15.

Any suggestions on how to make this work?

Body:
I have an Excel file with a data set in 'sheet1' that is refreshed every hour. On 'sheet2' I have 24 pivot tables (and corresponding chart), one for each hour. For each pivot table (e.g. 15:00), I want the pivot table to refresh once the data of hour 15 is downloaded. Then, it needs to remain unchanged for 24 hours (as the data refresh overrules all data of previous hour) and update again when the data of hour 15 of the next day is downloaded.

So every hour, the next pivot table in line should be refreshed, while all others remain unchanged, and start again with the first one when a new day has started.

Currently I have set it up like:

In cell A1: Hour of last data as number (e.g. 15, 16, etc.)

VBA code for 'sheet2':

Private Sub Worksheet_Change(ByVal Target As Range)

If Workbooks("Filename").Sheets("sheet2").Range("A1") = 15 Then
    Application.EnableEvents = False
    Workbooks("Filename").Sheets("sheet2").PivotTables("Pivot1500").RefreshTable
    Application.EnableEvents = True

End If

End Sub

For now I only have VBA code for hour 15, to try this out. But unfortunately, this either results in now refresh of the pivot table, refreshing all other pivot tables as well, or refreshing pivot table 'Pivot1500' even when data of following hours is downloaded and cell A1 is no longer 15.

Any suggestions on how to make this work?


问:
Having challenge with xml file
want to print this xml file such that I can be able to loop through it. my aim is to combine it with a csv file having the same column name, before creating a database with this combined file. I'm not allow to use non standard Libraries.

code------

xml_file = ET.parse("E:/Research work/My connect/Sam/CETM50 - 2022_3 - Assignment Data/user_data.xml")

get the parent tag

root = xml_file.getroot()

print the attributes of the first tag

e = ET.tostring(xml_file.getroot(), encoding='unicode', method='xml')
print(e)

output

<user firstName="Jayne" lastName="Wilson" age="69" sex="Female" retired="False" dependants="1" marital_status="divorced" salary="36872" pension="0" company="Wall, Reed and Whitehouse" commute_distance="10.47" address_postcode="TD95 7FL"

Title: Having challenge with xml file


问:
cannot convert value of type 'Binding<Int?>' to expected argument type 'Int' swift
I have some error when i am writing a qr code generator and it said cannot convert value of type 'Binding<Int?>' to expected argument type 'Int, i don't why it have error and i don't know how to solve it, does any expert know how to solve it?

My Code:

```<code>import Foundation
import SwiftUI
import CoreImage.CIFilterBuiltins

struct QRCode: View {
  @State private Second: Int?
  @State var navigated = false

  let seconds: [Int] = [10,20,30,40,50,60]

  var body: some View {
          NavigationView{
               VStack{
                  Picker(selection: $Second, label: Text("Select Seconds"))
                     {
                        Text(""),tag(nil as Int?)
                        Foreach(seconds, id:\.description) {
                        second in Text("\(second)").tag(second as Int?)
                      }
                    }
                 }
                   NavigationLink(destination: Generate(second: Second), isActive: self.navigated)             <-  Error in this part
                  {
                      Text("Complete")
                  }
}
struct QRCode_Previews: PreviewProvider {
  static var previews: some View {
          QRCode()
    }
}

struct Generate: View {
   var second: Int

   let filter = CIFilter.qrCodeGenerator()
   let const = CIContext()

   var body: some View {
      NavigationView{
               Image(uiImage: GenerateSecond(seconds: second))
             }
        }
   func GenerateSecond(seconds: Int)-> UIImage {
        let sec = "\(second)"
        let com = sec.data(using: .utf8)
        filter.setValue(com, forKey: "inputMessage")
        if let qr = filter.outputImage {
              return UIImage(cgImage: qrImage)
              }
        }
        return UIImage(systemName: "xmark") ?? UIImage()
    }
}

</code>```

I Have hightlighted in the code to show where have error, it is in the NavigationLink part has error

Body:
I have some error when i am writing a qr code generator and it said cannot convert value of type 'Binding<Int?>' to expected argument type 'Int, i don't why it have error and i don't know how to solve it, does any expert know how to solve it?

My Code:

import Foundation
import SwiftUI
import CoreImage.CIFilterBuiltins

struct QRCode: View {
  @State private Second: Int?
  @State var navigated = false

  let seconds: [Int] = [10,20,30,40,50,60]

  var body: some View {
          NavigationView{
               VStack{
                  Picker(selection: $Second, label: Text("Select Seconds"))
                     {
                        Text(""),tag(nil as Int?)
                        Foreach(seconds, id:\.description) {
                        second in Text("\(second)").tag(second as Int?)
                      }
                    }
                 }
                   NavigationLink(destination: Generate(second: Second), isActive: self.navigated)             <-  Error in this part
                  {
                      Text("Complete")
                  }
}
struct QRCode_Previews: PreviewProvider {
  static var previews: some View {
          QRCode()
    }
}

struct Generate: View {
   var second: Int

   let filter = CIFilter.qrCodeGenerator()
   let const = CIContext()

   var body: some View {
      NavigationView{
               Image(uiImage: GenerateSecond(seconds: second))
             }
        }
   func GenerateSecond(seconds: Int)-> UIImage {
        let sec = "\(second)"
        let com = sec.data(using: .utf8)
        filter.setValue(com, forKey: "inputMessage")
        if let qr = filter.outputImage {
              return UIImage(cgImage: qrImage)
              }
        }
        return UIImage(systemName: "xmark") ?? UIImage()
    }
}

I Have hightlighted in the code to show where have error, it is in the NavigationLink part has error


问:
symlink in binary `.deb` package
When creating a binary .deb package

```<code>mypkg
  /DEBIAN
    - control
  /path
    /to
      - mypkg.so
</code>```

What is the best way to include a symlink to /path/to/mypkg.so from /some/other/path/mypkg.so?

Guidance from other threads has been to add a (lowercase) debian/links file, which didn't appear to have any effect (no link created on install).

I also tried using dh_link but it appears to expect source (vs binary) packages with a control file at debian/control and errors out with

dh_link: error: "debian/control" not found. Are you sure you are in the correct directory?
```

Title: symlink in binary `.deb` package

Body:
When creating a binary .deb package

mypkg
  /DEBIAN
    - control
  /path
    /to
      - mypkg.so

What is the best way to include a symlink to /path/to/mypkg.so from /some/other/path/mypkg.so?

Guidance from other threads has been to add a (lowercase) debian/links file, which didn't appear to have any effect (no link created on install).

I also tried using dh_link but it appears to expect source (vs binary) packages with a control file at debian/control and errors out with

dh_link: error: "debian/control" not found. Are you sure you are in the correct directory?


问:
SSL PRF incorrect calculation
would greatly appreciate your input on the following:

the TLS PRF implementation https://www.rfc-editor.org/rfc/rfc4346#section-5
with observable wireshark dump

```<code>    pre master secret[48]:
    | 03 03 0f 90 f3 8d af 0c 10 40 81 36 94 16 7d 33 |.........@.6..}3|
    | 88 22 76 2d ff 68 9f 5a a2 33 99 88 3d e6 09 29 |."v-.h.Z.3..=..)|
    | 8e aa 0a 76 93 d6 24 96 1e 13 37 54 77 3f a1 e3 |...v..$...7Tw?..|
    client random[32]:
    | e8 7f 92 a8 0e e3 88 06 76 fa 5a 60 c2 3a e4 b1 |........v.Z`.:..|
    | 88 f5 6b 8a 32 db 99 ec d3 91 ff b2 01 48 e1 d5 |..k.2........H..|
    server random[32]:
    | 61 e1 3d 05 82 83 23 f2 4f 0a 14 9f 87 8c a7 88 |a.=...#.O.......|
    | 2f 4d 69 5b 72 2f e8 a4 c3 6b 1e ae 7d cd 03 9d |/Mi[r/...k..}...|
    tls_hash: hash seed[77]:
    | 6d 61 73 74 65 72 20 73 65 63 72 65 74 e8 7f 92 |master secret...|
    | a8 0e e3 88 06 76 fa 5a 60 c2 3a e4 b1 88 f5 6b |.....v.Z`.:....k|
    | 8a 32 db 99 ec d3 91 ff b2 01 48 e1 d5 61 e1 3d |.2........H..a.=|
    | 05 82 83 23 f2 4f 0a 14 9f 87 8c a7 88 2f 4d 69 |...#.O......./Mi|
    | 5b 72 2f e8 a4 c3 6b 1e ae 7d cd 03 9d          |[r/...k..}...   |
    PRF out[48]:
    | 1b 04 a5 90 67 e8 37 0e 3a a8 c5 62 a6 f4 e9 8a |....g.7.:..b....|
    | 5b ea 69 96 b6 63 c3 34 6f 24 29 f6 a9 d2 e9 4e |[.i..c.4o$)....N|
    | fd 16 ed 93 56 c6 41 29 81 42 c4 d2 fa 86 fa da |....V.A).B......|
</code>```

does not generate the same PRF, could you please correct what I am doing wrong, checked the code 100+ times at this point:

```<code>  function TLS_PRF(secret, label, seed, length) {
    let halfSecretLength = Math.ceil(secret.length / 2)
    let S1 = Buffer.alloc(halfSecretLength)
    secret.copy(S1)
    let S2 = Buffer.alloc(halfSecretLength)
    secret.slice(secret.length - halfSecretLength).copy(S2)

    let P_MD5 = TLS_pHash('md5', S1, Buffer.concat([Buffer.from(label), seed]), length)
    let P_SHA1 = TLS_pHash('sha1', S2, Buffer.concat([Buffer.from(label), seed]), length)

    let RPRF = Buffer.alloc(length)

    RPRF.forEach((value, index) => {
      RPRF[index] = P_MD5[index] ^ P_SHA1[index]
    })

    return RPRF
  }

  function TLS_pHash(algorithm, secret, seed, length) {
    let i = 1
    let A = [seed]
    result = Buffer.alloc(0)

    while(result.length < length) {
      A.push(crypto.createHmac(algorithm, secret).update(A[i - 1]).digest())
      result = Buffer.concat([result, crypto.createHmac(algorithm, secret).update(Buffer.concat([A[i], seed])).digest()])
      i++
    }

    return result.slice(0, length)
  }
</code>```

Title: SSL PRF incorrect calculation

Body:
would greatly appreciate your input on the following:

the TLS PRF implementation https://www.rfc-editor.org/rfc/rfc4346#section-5
with observable wireshark dump

    pre master secret[48]:
    | 03 03 0f 90 f3 8d af 0c 10 40 81 36 94 16 7d 33 |.........@.6..}3|
    | 88 22 76 2d ff 68 9f 5a a2 33 99 88 3d e6 09 29 |."v-.h.Z.3..=..)|
    | 8e aa 0a 76 93 d6 24 96 1e 13 37 54 77 3f a1 e3 |...v..$...7Tw?..|
    client random[32]:
    | e8 7f 92 a8 0e e3 88 06 76 fa 5a 60 c2 3a e4 b1 |........v.Z`.:..|
    | 88 f5 6b 8a 32 db 99 ec d3 91 ff b2 01 48 e1 d5 |..k.2........H..|
    server random[32]:
    | 61 e1 3d 05 82 83 23 f2 4f 0a 14 9f 87 8c a7 88 |a.=...#.O.......|
    | 2f 4d 69 5b 72 2f e8 a4 c3 6b 1e ae 7d cd 03 9d |/Mi[r/...k..}...|
    tls_hash: hash seed[77]:
    | 6d 61 73 74 65 72 20 73 65 63 72 65 74 e8 7f 92 |master secret...|
    | a8 0e e3 88 06 76 fa 5a 60 c2 3a e4 b1 88 f5 6b |.....v.Z`.:....k|
    | 8a 32 db 99 ec d3 91 ff b2 01 48 e1 d5 61 e1 3d |.2........H..a.=|
    | 05 82 83 23 f2 4f 0a 14 9f 87 8c a7 88 2f 4d 69 |...#.O......./Mi|
    | 5b 72 2f e8 a4 c3 6b 1e ae 7d cd 03 9d          |[r/...k..}...   |
    PRF out[48]:
    | 1b 04 a5 90 67 e8 37 0e 3a a8 c5 62 a6 f4 e9 8a |....g.7.:..b....|
    | 5b ea 69 96 b6 63 c3 34 6f 24 29 f6 a9 d2 e9 4e |[.i..c.4o$)....N|
    | fd 16 ed 93 56 c6 41 29 81 42 c4 d2 fa 86 fa da |....V.A).B......|

does not generate the same PRF, could you please correct what I am doing wrong, checked the code 100+ times at this point:

  function TLS_PRF(secret, label, seed, length) {
    let halfSecretLength = Math.ceil(secret.length / 2)
    let S1 = Buffer.alloc(halfSecretLength)
    secret.copy(S1)
    let S2 = Buffer.alloc(halfSecretLength)
    secret.slice(secret.length - halfSecretLength).copy(S2)

    let P_MD5 = TLS_pHash('md5', S1, Buffer.concat([Buffer.from(label), seed]), length)
    let P_SHA1 = TLS_pHash('sha1', S2, Buffer.concat([Buffer.from(label), seed]), length)

    let RPRF = Buffer.alloc(length)

    RPRF.forEach((value, index) => {
      RPRF[index] = P_MD5[index] ^ P_SHA1[index]
    })

    return RPRF
  }

  function TLS_pHash(algorithm, secret, seed, length) {
    let i = 1
    let A = [seed]
    result = Buffer.alloc(0)

    while(result.length < length) {
      A.push(crypto.createHmac(algorithm, secret).update(A[i - 1]).digest())
      result = Buffer.concat([result, crypto.createHmac(algorithm, secret).update(Buffer.concat([A[i], seed])).digest()])
      i++
    }

    return result.slice(0, length)
  }


问:
Python - Custom tkinter - component.setfocus() don't work with customtkinter component like CTkEntry
I have this code and focus dont work with customtkinter

```<code>from tkinter import *
import customtkinter as ctk
import sys

if len(sys.argv) > 1:
    print("Tk Customized from Tom")
    win = ctk.CTk()
    win.geometry("750x250")
    text = ctk.CTkTextbox(win, width=200, height=200)
    text.pack()
    text.insert(INSERT, "Hello World!")
    entry = ctk.CTkEntry(win, width=100)
    entry.pack()
    entry.focus_set()
else:
    print("Standard Tk ")
    win = Tk()
    win.geometry("750x250")
    text = Text(win, width=30, height=10)
    text.insert(INSERT, "Hello World!")
    text.pack()
    entry = Entry(win, width=30)
    entry.pack()
    entry.focus_set()

win.mainloop()
</code>```

py testy.py   -> Start standard Tkinter  Focus is on Entry

py testy.py 1 -> Start with customtkinter objects Focus is NOT on Entry

How can get focus on CTkEntry ?

Body:
I have this code and focus dont work with customtkinter

from tkinter import *
import customtkinter as ctk
import sys

if len(sys.argv) > 1:
    print("Tk Customized from Tom")
    win = ctk.CTk()
    win.geometry("750x250")
    text = ctk.CTkTextbox(win, width=200, height=200)
    text.pack()
    text.insert(INSERT, "Hello World!")
    entry = ctk.CTkEntry(win, width=100)
    entry.pack()
    entry.focus_set()
else:
    print("Standard Tk ")
    win = Tk()
    win.geometry("750x250")
    text = Text(win, width=30, height=10)
    text.insert(INSERT, "Hello World!")
    text.pack()
    entry = Entry(win, width=30)
    entry.pack()
    entry.focus_set()

win.mainloop()

py testy.py   -> Start standard Tkinter  Focus is on Entry

py testy.py 1 -> Start with customtkinter objects Focus is NOT on Entry

How can get focus on CTkEntry ?


问:
How to verify column in a webtable whether it contains value greater than specified value in all the pages using Java selenium
I need to verify the column values in a webtable whether it is greater than a specific value in all the pages

I need a Java method to create step definition method in cucumber BDD


问:
why unity app is crashing on startup adb shows nothing obivous?

I don't know where it is causing

Body: I don't know where it is causing


问:
error I cant build bundle in create new key store please help me
please help me
cant create new key store in build (AAB) in android studio

am trying same fixing but he not fixing the problem