问:
How to use google workload identity federation to trigger cloud function (http) from AWS?
I am trying to trigger cloud function (authorized) from AWS EC2 Instance ( service ) and I am trying to use Google workload identity federation for this.

I have been successful in listing cloud storage buckets using workload identity federation following this youtube video but I am unable to apply the same login for cloud function invokation.

I have followed below steps:

Created an AWS EC2 Instance with an IAM role.

Created GCP workload identity federation pool.

Created a service account with permission to call the mentioned cloud function.

Generated a clientLibraryConfig.json file by binding WIF pool with Service account.

I don't have an organization so I am unable to allow federation in organization policies ( is it possible to do it without this )

I am trying to use node js at the to trigger cloud function following is my code:

```<code>function main(
) {

  const {GoogleAuth} = require('google-auth-library');
  const auth = new GoogleAuth();
  const url = 'https://us-central1-multi-service-app-js.cloudfunctions.net/helloHttp',
  const targetAudience = 'https://us-central1-multi-service-app-js.cloudfunctions.net/helloHttp'

    const client = await auth.getIdTokenClient(targetAudience);
    const res = await client.request({url});
    console.info(res.data);
  }

  request().catch(err => {
    console.error(err.message);
    process.exitCode = 1;
  });
}

main();

</code>```

and I am getting following error:

```<code>Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.

</code>```

I have already set GOOGLE_APPLICATION_CREDENTIALS to clientLibraryConfig.json & GOOGLE_CLOUD_PROJECT env variables using export but I still get this error.

========================================

Update:
I tried to use deployment manager api with workload identity federation to deploy 2 compute instance resources and it worked.
I was earlier also able to list buckets using WIF but the cloud function api does not work, I even tried to use python sdk for calling cloud function api using WIF but I got following error:

```<code>google.auth.exceptions.RefreshError: ('Unable to acquire impersonated credentials', '{\n  "error": {\n    "code": 400,\n    "message": "Request contains an invalid argument.",\n    "status": "INVALID_ARGUMENT"\n  }\n}\n')
</code>```

my best guess is since cloud function requires fetching ID Token before it can call the cloud function url, the fetching ID token part of the api is failing and since it is failing for both node sdk and python sdk I am suspecting that there is a bug in {GoogleAuth} of 'google-auth-library' which is only affecting the id token fetch part of the api.

I have opened following ticket with GCP for this issue: link

Body:
I am trying to trigger cloud function (authorized) from AWS EC2 Instance ( service ) and I am trying to use Google workload identity federation for this.

I have been successful in listing cloud storage buckets using workload identity federation following this youtube video but I am unable to apply the same login for cloud function invokation.

I have followed below steps:

Created an AWS EC2 Instance with an IAM role.

Created GCP workload identity federation pool.

Created a service account with permission to call the mentioned cloud function.

Generated a clientLibraryConfig.json file by binding WIF pool with Service account.

I don't have an organization so I am unable to allow federation in organization policies ( is it possible to do it without this )

I am trying to use node js at the to trigger cloud function following is my code:

function main(
) {

  const {GoogleAuth} = require('google-auth-library');
  const auth = new GoogleAuth();
  const url = 'https://us-central1-multi-service-app-js.cloudfunctions.net/helloHttp',
  const targetAudience = 'https://us-central1-multi-service-app-js.cloudfunctions.net/helloHttp'

    const client = await auth.getIdTokenClient(targetAudience);
    const res = await client.request({url});
    console.info(res.data);
  }

  request().catch(err => {
    console.error(err.message);
    process.exitCode = 1;
  });
}

main();

and I am getting following error:

Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.

I have already set GOOGLE_APPLICATION_CREDENTIALS to clientLibraryConfig.json & GOOGLE_CLOUD_PROJECT env variables using export but I still get this error.

========================================

Update:
I tried to use deployment manager api with workload identity federation to deploy 2 compute instance resources and it worked.
I was earlier also able to list buckets using WIF but the cloud function api does not work, I even tried to use python sdk for calling cloud function api using WIF but I got following error:

google.auth.exceptions.RefreshError: ('Unable to acquire impersonated credentials', '{\n  "error": {\n    "code": 400,\n    "message": "Request contains an invalid argument.",\n    "status": "INVALID_ARGUMENT"\n  }\n}\n')

my best guess is since cloud function requires fetching ID Token before it can call the cloud function url, the fetching ID token part of the api is failing and since it is failing for both node sdk and python sdk I am suspecting that there is a bug in {GoogleAuth} of 'google-auth-library' which is only affecting the id token fetch part of the api.

I have opened following ticket with GCP for this issue: link


来源: stackexchange

问:
How to change phone number voice app configuration from Twiml app to Twilio Studio Flow using REST Api
Preconditions

I have phone number(PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)

I have TwiML Application (APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)

Phone number voice app connected to TwiML app

I have Studio Flow (FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)

Question:
How can I replace the phone number's voice app configuration with studio flow, using REST API or programmatically?

Basically from this one

I want to get this one

ContentLicense: CC BY-SA 4.0


问:
How to use two functions as conditions in if else statement javascript
Problem

I'm trying to use two functions as conditions within an if else statement.

Then, upon either of them returning true, they carry out a desired process.

However, I can only get them to work independently, not as part of the if else statement.

What I've got

Currently, they work fine independently:

let input = document.querySelector('searchBox');

searchBox.addEventListener('keyup', (e) => {
    if(e.keyCode === 13) {
  alert(e.target.value);
  return true;
  }
})

$("#searchBtn").click(function(){
alert("Button clicked");
//alert("Button clicked");
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="search-bar" class="input-group custom-search">
                        <input id="searchBox" type="text" value="" class="form-control custom-search-input" placeholder="Search for product/material" >
                        <button id="searchBtn" class="btn btn-primary custom-search-botton" type="submit" >Search</button>
                    </div></code>```

What's not working
However, I'm trying to get them running as part of an if else statement. This is what I've got, but it's not turning over...

function enterPressed() {
  $(document).on('keypress', function(e) { //enter button
    if (e.which == 13) {
      alert('You pressed enter!');
      return true;
    }
  })
}

function buttonClicked() {
  //a button (equivalent to buttonClicked)
  $("#searchBtn").click(function() {
    alert('You clicked the button!')
    return true;
  })
}

function start() {
  if (enterPressed == true || buttonClicked == true) {
    alert('You entered some information!!')
  }
}

enterPressed();
buttonClicked();
start();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search-bar" class="input-group custom-search">
  <input id="searchBox" type="text" value="" class="form-control custom-search-input" placeholder="Search for product/material">
  <button id="searchBtn" class="btn btn-primary custom-search-botton" type="submit">Search</button>
</div></code>```

Body:
Problem

I'm trying to use two functions as conditions within an if else statement.

Then, upon either of them returning true, they carry out a desired process.

However, I can only get them to work independently, not as part of the if else statement.

What I've got

Currently, they work fine independently:

let input = document.querySelector('searchBox');

searchBox.addEventListener('keyup', (e) => {
    if(e.keyCode === 13) {
  alert(e.target.value);
  return true;
  }
})

$("#searchBtn").click(function(){
alert("Button clicked");
//alert("Button clicked");
})

                        <input id="searchBox" type="text" value="" class="form-control custom-search-input" placeholder="Search for product/material" >
                        <button id="searchBtn" class="btn btn-primary custom-search-botton" type="submit" >Search</button>

What's not working
However, I'm trying to get them running as part of an if else statement. This is what I've got, but it's not turning over...

function enterPressed() {
  $(document).on('keypress', function(e) { //enter button
    if (e.which == 13) {
      alert('You pressed enter!');
      return true;
    }
  })
}

function buttonClicked() {
  //a button (equivalent to buttonClicked)
  $("#searchBtn").click(function() {
    alert('You clicked the button!')
    return true;
  })
}

function start() {
  if (enterPressed == true || buttonClicked == true) {
    alert('You entered some information!!')
  }
}

enterPressed();
buttonClicked();
start();

  <input id="searchBox" type="text" value="" class="form-control custom-search-input" placeholder="Search for product/material">
  <button id="searchBtn" class="btn btn-primary custom-search-botton" type="submit">Search</button>


问:
Implement hierarchical ML model architecture in google cloud (vertex ai)
I want to ask if it is possible to implement a complex hierarchical end to end deep learning architecture with google cloud and vertex ai. I have two models, detection and classification models. The prediction results of the first base model will be fed to the second classification model. So, how can I implement this in google cloud and vertex ai? how to deploy both models to on end point with custom logic to implement the hierarchical architecture?

Thanks

I read some articles describing the custom containers and custom prediction routines but none were related to the issue


问:
Pycharm not adding external modules and terminal not working
I've just started with Python and wanted to install some extra modules, but after having installed the Pip, I tried to install the modules, which were successfully added on the cmp, but no trace of them on pycharm.
Furthermore, on the pycharm terminal, an error occurs. Here's a pic. It's in Italian. I'll write the translation after.

It says:

Install the most recent version of PowerShell for new functions and
improvements. https://ahttps://aka.ms/PSWindows

[error:]

impossible to load the file C:\Users\supoo\venv\Scripts\activate.ps1.
The execution of the script is disabled in the system in use. for more
information, see about_Execution_Policies at
https://go.microsoft.com/fwlink/?LinkID=135170.

+ CategoryInfo     : error of protection: (:) [],
ParentContainsErrorRecordException

+ FullyQualifiedErrorId : UnauthorizedAccess

I know the answer is probably something dumb, but it's all day I try to figure this out.


问:
How can I replace the empty axes of plt.subplots() with the existing ones?
I use a python library wfdb which offer a plot function:wfdb.plot_items().
This function can return matplotlib axes objects.

And I create a empty matplotlib axes object by plt.subplots(), then try to replace this empty axes with the return axes of wfdb.plot_items() by assigning(=).

codes:

record = wfdb.rdrecord('a103l', pn_dir='challenge-2015/training/')
wfdb_fig, wfdb_axes = wfdb.plot_items(signal=record.p_signal, title='Record a103l from PhysioNet Challenge 2015', return_fig_axes=True)
print(f"type of wfdb_fig:{type(wfdb_fig)}, length of wfdb_axes:{len(wfdb_axes)}, type of wfdb_axes[0]:{type(wfdb_axes[0])}")

record_sum = record.p_signal.sum(axis=1)
fig, ax = plt.subplots(4,1)
ax[0] = wfdb_axes[0]
ax[1] = wfdb_axes[1]
ax[2] = wfdb_axes[2]
ax[3].plot(record_mean)
```

output of codes: type of wfdb_fig:<class 'matplotlib.figure.Figure'>, length of wfdb_axes:3, type of wfdb_axes[0]:<class 'matplotlib.axes._subplots.AxesSubplot'>

output image of codes

output image of wfdb.plot_items()

As image shows, it's not working(assign(=))

My question is: What's the correct way to replace the empty axes of plt.subplots() with the existing ones?

Body:
I use a python library wfdb which offer a plot function:wfdb.plot_items().
This function can return matplotlib axes objects.

And I create a empty matplotlib axes object by plt.subplots(), then try to replace this empty axes with the return axes of wfdb.plot_items() by assigning(=).

codes:

record = wfdb.rdrecord('a103l', pn_dir='challenge-2015/training/')
wfdb_fig, wfdb_axes = wfdb.plot_items(signal=record.p_signal, title='Record a103l from PhysioNet Challenge 2015', return_fig_axes=True)
print(f"type of wfdb_fig:{type(wfdb_fig)}, length of wfdb_axes:{len(wfdb_axes)}, type of wfdb_axes[0]:{type(wfdb_axes[0])}")

record_sum = record.p_signal.sum(axis=1)
fig, ax = plt.subplots(4,1)
ax[0] = wfdb_axes[0]
ax[1] = wfdb_axes[1]
ax[2] = wfdb_axes[2]
ax[3].plot(record_mean)

output of codes: type of wfdb_fig:<class 'matplotlib.figure.Figure'>, length of wfdb_axes:3, type of wfdb_axes[0]:<class 'matplotlib.axes._subplots.AxesSubplot'>

output image of codes

output image of wfdb.plot_items()

As image shows, it's not working(assign(=))

My question is: What's the correct way to replace the empty axes of plt.subplots() with the existing ones?


问:
how to get boxes from pyTorch
I'm very beginner on Pytorch.

I found this code (see https://pytorch.org/tutorials/intermediate/realtime_rpi.html)

```<code>
import torch
import numpy as np
from torchvision import models, transforms

import cv2
from PIL import Image

torch.backends.quantized.engine = 'qnnpack'

cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 224)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 224)
cap.set(cv2.CAP_PROP_FPS, 36)

preprocess = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

net = models.quantization.mobilenet_v2(pretrained=True, quantize=True)
# jit model to take it from ~20fps to ~30fps
net = torch.jit.script(net)

started = time.time()
last_logged = time.time()
frame_count = 0

with torch.no_grad():
    while True:
        # read frame
        ret, image = cap.read()
        if not ret:
            raise RuntimeError("failed to read frame")

        # convert opencv output from BGR to RGB
        image = image[:, :, [2, 1, 0]]
        permuted = image

        # preprocess
        input_tensor = preprocess(image)

        # create a mini-batch as expected by the model
        input_batch = input_tensor.unsqueeze(0)

        # run model
        output = net(input_batch)
        # do something with output ...

        # log model performance
        frame_count += 1
        now = time.time()
        if now - last_logged > 1:
            print(f"{frame_count / (now-last_logged)} fps")
            last_logged = now
            frame_count = 0
</code>```

Is not clear to me how to retrive boundery boxes. Can you help me?

I try to get boundary boxes and items name (classes) to use on OpenCV cv2.show()

Title: how to get boxes from pyTorch

Body:
I'm very beginner on Pytorch.

I found this code (see https://pytorch.org/tutorials/intermediate/realtime_rpi.html)

import torch
import numpy as np
from torchvision import models, transforms

import cv2
from PIL import Image

torch.backends.quantized.engine = 'qnnpack'

cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 224)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 224)
cap.set(cv2.CAP_PROP_FPS, 36)

preprocess = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

net = models.quantization.mobilenet_v2(pretrained=True, quantize=True)
# jit model to take it from ~20fps to ~30fps
net = torch.jit.script(net)

started = time.time()
last_logged = time.time()
frame_count = 0

with torch.no_grad():
    while True:
        # read frame
        ret, image = cap.read()
        if not ret:
            raise RuntimeError("failed to read frame")

        # convert opencv output from BGR to RGB
        image = image[:, :, [2, 1, 0]]
        permuted = image

        # preprocess
        input_tensor = preprocess(image)

        # create a mini-batch as expected by the model
        input_batch = input_tensor.unsqueeze(0)

        # run model
        output = net(input_batch)
        # do something with output ...

        # log model performance
        frame_count += 1
        now = time.time()
        if now - last_logged > 1:
            print(f"{frame_count / (now-last_logged)} fps")
            last_logged = now
            frame_count = 0

Is not clear to me how to retrive boundery boxes. Can you help me?

I try to get boundary boxes and items name (classes) to use on OpenCV cv2.show()


问:
ReCaptcha solved detection
I'm trying to make a function to wait a google v2 recaptcha being solved manually but for unknown reason my script don't detect somes div of the captcha.

I expect to detect when the captcha have the green check

```<code>if (await page.$(".g-recaptcha") !== null) {
    await page.waitForSelector(".g-recaptcha", { visible: true });
    await page.waitForSelector(".rc-anchor-center-item", { visible: true }); // Block here
    console.log("");
    console.log("Captcha detected, awaiting to be solved...");
    await page.waitForSelector(".recaptcha-checkbox-checked", { visible: true, timeout: 0 });
    console.log("Captcha solved!");
}
</code>```

Title: ReCaptcha solved detection

Body:
I'm trying to make a function to wait a google v2 recaptcha being solved manually but for unknown reason my script don't detect somes div of the captcha.

I expect to detect when the captcha have the green check

if (await page.$(".g-recaptcha") !== null) {
    await page.waitForSelector(".g-recaptcha", { visible: true });
    await page.waitForSelector(".rc-anchor-center-item", { visible: true }); // Block here
    console.log("");
    console.log("Captcha detected, awaiting to be solved...");
    await page.waitForSelector(".recaptcha-checkbox-checked", { visible: true, timeout: 0 });
    console.log("Captcha solved!");
}


问:
ShareArrayBuffer is not defined - error with Vuejs, Webpack Encore and Symfony
I have made a Symfony application in which I use a VueJs component using Webpack Encore to send videos. I need to compress the video before sending it to the server. For that, I try to use ffmep.wasm :

<template>
    <input type="file" accept="video/mp4" @change="transcode($event)">
</template>

```
<p>But I get an error when I run the compression:</p>
<blockquote>
<p>sharedarraybuffer is not defined</p>
</blockquote>
<p>On github it explains that I need to add headers to the server like this (for express.js).</p>
<pre class="lang-js prettyprint-override"><code>const express = require('express');
const app = express();

app.use((_, res, next) => {
  res.header('Cross-Origin-Opener-Policy', 'same-origin');
  res.header('Cross-Origin-Embedder-Policy', 'require-corp');
  next();
});
</code>```

Since I use Webpack Encore, I went to see how I can fix the problem with Webpack and I found this.

module.exports = {
  //...
  devServer: {
    headers: {
      'X-Custom-Foo': 'bar',
    },
  },
};
```

But I can't adapt this solution with Webpack Encore. Has anyone experienced this problem before?

Body:
I have made a Symfony application in which I use a VueJs component using Webpack Encore to send videos. I need to compress the video before sending it to the server. For that, I try to use ffmep.wasm :

<template>
    <input type="file" accept="video/mp4" @change="transcode($event)">
</template>

But I get an error when I run the compression:

sharedarraybuffer is not defined

On github it explains that I need to add headers to the server like this (for express.js).

const express = require('express');
const app = express();

app.use((_, res, next) => {
  res.header('Cross-Origin-Opener-Policy', 'same-origin');
  res.header('Cross-Origin-Embedder-Policy', 'require-corp');
  next();
});

Since I use Webpack Encore, I went to see how I can fix the problem with Webpack and I found this.

module.exports = {
  //...
  devServer: {
    headers: {
      'X-Custom-Foo': 'bar',
    },
  },
};

But I can't adapt this solution with Webpack Encore. Has anyone experienced this problem before?


问:
I want to make an open source idea plugin, but I have encountered some problems in ideas and implementation
If this plugin is successfully produced, I will put it on my github and open source it to the world. If there is already a similar plugin on github, please let me know. I hope to learn about its plugin code.
Regarding this open source idea plugin, my thoughts are as follows:
I can run any project through this idea plugin, and all requests sent by this project will be forwarded by this idea plugin to a remote server I specify. At the same time, all responses received from the remote server will be returned to the project by the idea plugin.

I know how to make an idea plugin, but not how to make my idea plugin do this.
Please provide some ideas and implementation methods.


问:
express sessionstate which i create is undefined after every making request
I'm making a website by express js with view as handlebars. I use express-session to save cart information. I have the problem that every time I request to add product to cart, my req.session.cart is undefined so it is always created new req.session.cart and every time I add product to cart only 1 product can be added. But when i run it on post man, it works as expected

cartController.js

```<code>const {add, initCart, cartDetail} = require('../../services/cartService')

const getCart = async(req, res)=>{
  console.log('get cart',req.session)
  console.log(req.session.cart)
  console.log(req.session.test)
  res.json(await cartDetail(req.session.cart));
}

const addItemToCart = (req, res)=>{
  console.log('Vao add to cart ')
  console.log(req.body)

  const {productId} = req.body;
  req.session.test = 'test';
  if(req.session.cart){
    console.log('da co cart')
  }
  if(!req.session.cart){
    req.session.cart = initCart();
  }

  console.log(' before add item to cart',req.session)
  add(productId, req.session.cart)
  console.log(req.session.cart)
  console.log(' after add item to cart',req.session)
  res.json(req.session.cart)

}

module.exports = {
  getCart,
  addItemToCart
}
</code>```

cartService.js

```<code>const {getSpecificProductById}= require('./productService')

exports.add = (productId, cart)=>{
  const foundProduct = cart.products.find(product=>product.id === productId);
  if(foundProduct){
    foundProduct.quantity = foundProduct.quantity+1;
  }else{
    cart.products.push({id: productId, quantity: 1});
  }
}

exports.cartDetail = async(cart)=>{
  const cartDetails = {...cart};
  cartDetails.products  = await Promise.all(cartDetails.products.map(async product=>{
    const productInfo = await getSpecificProductById(product.id);
    return {
      ...product,
      name: productInfo.name,
      price: productInfo.price,
      image: productInfo.image,
    }
  }))

  return cartDetails;
}

exports.initCart = ()=>(
  {
    products: []
  }
)
</code>```

app.js

```<code>const hbs  = require('hbs')
var indexRouter = require("./routes/home");
var usersRouter = require("./routes/users");
const {aboutRouter} = require("./routes/aboutRouter")
const {shoppingCartRouter} = require("./routes/shoppingCartRouter")
const {checkoutRouter} = require("./routes/checkoutRouter")
const productRouter = require('./routes/productRouter')
const authRouter = require("./auth/authRouter");
const profileRouter = require("./routes/profileRouter")
const authApiRouter = require('./auth/api')
const productApiRouter = require('./routes/APIRoutes/productApiRouter');
const cartApiRouter = require('./routes/APIRoutes/cartApiRouter');

const session = require("express-session");
const passport = require('./auth/passport/index')

const MySQLStore = require('connect-mysql')(session)
const options = {
  config:{
    host:'localhost',
    user:'root',
    password: '280502',
    database: 'session-db'
  }
}

const paginate = require('express-paginate')

const cors = require('cors')

var app = express();

// view engine setup

app.use(cors())
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
hbs.registerPartials(__dirname + '/views/partials');
hbs.handlebars.registerHelper("minus", (a,b)=>{
  return a-b
})
var blocks = {};

hbs.handlebars.registerHelper('extend', function(name, context) {
  var block = blocks[name];
  if (!block) {
    block = blocks[name] = [];
  }

  block.push(context.fn(this)); // for older versions of handlebars, use block.push(context(this));
});

hbs.handlebars.registerHelper('block', function(name) {
  var val = (blocks[name] || []).join('\n');

  // clear the block
  blocks[name] = [];
  return val;
});

app.use(paginate.middleware(5, 20))
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(session({
  secret: 'very secret keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: {
    httpOnly: false,
    secure: false,
    maxAge: 1000 * 60 * 60 * 24 * 3,
    expires: 1000 * 60 * 60 * 24 * 3,
  },
  store: new MySQLStore(options)
}))
app.use(passport.authenticate('session'));
app.use((req,res,next)=>{
  res.locals.user = req.user
  next();
});

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/about", aboutRouter);
app.use("/products", productRouter)
app.use("/api/products", productApiRouter)
app.use("/auth", authRouter);

//api
app.use('/api/auth',authApiRouter);
app.use("/cart", shoppingCartRouter)

app.use("/api/cart", cartApiRouter);
app.use("/checkout", checkoutRouter)
app.use("/profile", profileRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
</code>```

This is my first time having this problem. It took up a lot of my time. Can anyone help me to solve this problem. Thanks everyone

Body:
I'm making a website by express js with view as handlebars. I use express-session to save cart information. I have the problem that every time I request to add product to cart, my req.session.cart is undefined so it is always created new req.session.cart and every time I add product to cart only 1 product can be added. But when i run it on post man, it works as expected

cartController.js

const {add, initCart, cartDetail} = require('../../services/cartService')

const getCart = async(req, res)=>{
  console.log('get cart',req.session)
  console.log(req.session.cart)
  console.log(req.session.test)
  res.json(await cartDetail(req.session.cart));
}

const addItemToCart = (req, res)=>{
  console.log('Vao add to cart ')
  console.log(req.body)

  const {productId} = req.body;
  req.session.test = 'test';
  if(req.session.cart){
    console.log('da co cart')
  }
  if(!req.session.cart){
    req.session.cart = initCart();
  }

  console.log(' before add item to cart',req.session)
  add(productId, req.session.cart)
  console.log(req.session.cart)
  console.log(' after add item to cart',req.session)
  res.json(req.session.cart)

}

module.exports = {
  getCart,
  addItemToCart
}

cartService.js

const {getSpecificProductById}= require('./productService')

exports.add = (productId, cart)=>{
  const foundProduct = cart.products.find(product=>product.id === productId);
  if(foundProduct){
    foundProduct.quantity = foundProduct.quantity+1;
  }else{
    cart.products.push({id: productId, quantity: 1});
  }
}

exports.cartDetail = async(cart)=>{
  const cartDetails = {...cart};
  cartDetails.products  = await Promise.all(cartDetails.products.map(async product=>{
    const productInfo = await getSpecificProductById(product.id);
    return {
      ...product,
      name: productInfo.name,
      price: productInfo.price,
      image: productInfo.image,
    }
  }))

  return cartDetails;
}

exports.initCart = ()=>(
  {
    products: []
  }
)

app.js

const hbs  = require('hbs')
var indexRouter = require("./routes/home");
var usersRouter = require("./routes/users");
const {aboutRouter} = require("./routes/aboutRouter")
const {shoppingCartRouter} = require("./routes/shoppingCartRouter")
const {checkoutRouter} = require("./routes/checkoutRouter")
const productRouter = require('./routes/productRouter')
const authRouter = require("./auth/authRouter");
const profileRouter = require("./routes/profileRouter")
const authApiRouter = require('./auth/api')
const productApiRouter = require('./routes/APIRoutes/productApiRouter');
const cartApiRouter = require('./routes/APIRoutes/cartApiRouter');

const session = require("express-session");
const passport = require('./auth/passport/index')

const MySQLStore = require('connect-mysql')(session)
const options = {
  config:{
    host:'localhost',
    user:'root',
    password: '280502',
    database: 'session-db'
  }
}

const paginate = require('express-paginate')

const cors = require('cors')

var app = express();

// view engine setup

app.use(cors())
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
hbs.registerPartials(__dirname + '/views/partials');
hbs.handlebars.registerHelper("minus", (a,b)=>{
  return a-b
})
var blocks = {};

hbs.handlebars.registerHelper('extend', function(name, context) {
  var block = blocks[name];
  if (!block) {
    block = blocks[name] = [];
  }

  block.push(context.fn(this)); // for older versions of handlebars, use block.push(context(this));
});

hbs.handlebars.registerHelper('block', function(name) {
  var val = (blocks[name] || []).join('\n');

  // clear the block
  blocks[name] = [];
  return val;
});

app.use(paginate.middleware(5, 20))
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(session({
  secret: 'very secret keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: {
    httpOnly: false,
    secure: false,
    maxAge: 1000 * 60 * 60 * 24 * 3,
    expires: 1000 * 60 * 60 * 24 * 3,
  },
  store: new MySQLStore(options)
}))
app.use(passport.authenticate('session'));
app.use((req,res,next)=>{
  res.locals.user = req.user
  next();
});

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/about", aboutRouter);
app.use("/products", productRouter)
app.use("/api/products", productApiRouter)
app.use("/auth", authRouter);

//api
app.use('/api/auth',authApiRouter);
app.use("/cart", shoppingCartRouter)

app.use("/api/cart", cartApiRouter);
app.use("/checkout", checkoutRouter)
app.use("/profile", profileRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;

This is my first time having this problem. It took up a lot of my time. Can anyone help me to solve this problem. Thanks everyone


问:
I am seeing this - System.Reflection.TargetInvocationException: '
I am trying to run below line and seeing file not found error. I am able to launch the url in chrome though, help is appriciated.

```<code>var restClient = new RestClient("https://reqres.in/");
            var restRequest = new RestRequest("/api/users?page=2",Method.Get);
</code>```

I am expecting it to launch API succesfully.

Body:
I am trying to run below line and seeing file not found error. I am able to launch the url in chrome though, help is appriciated.

var restClient = new RestClient("https://reqres.in/");
            var restRequest = new RestRequest("/api/users?page=2",Method.Get);

I am expecting it to launch API succesfully.


问:
Yii2 translate a module from outside
If you have a yii2 module installed by composer how can you add a new language without touching the module itself (since touching anything in vendor/ is quite a bad practice)?

Let's say you have a module vbt-cron which already have an English an a Hungarian language files inside and it's configured like this:

```<code>\Yii::$app->i18n->translations['vbt-cron'] = [
    'class' => '\yii\i18n\PhpMessageSource',
    'sourceLanguage' => 'en-US',
    'basePath' => '@sharkom/cron/messages',
];
</code>```

Your app is in Italian so you want to translate the module externally, yii message extracted the strings from the module, you added it to the config:

```<code>'vbt-cron' => [
    'class' => 'yii\i18n\PhpMessageSource',
    'basePath' => '@app/messages',
    'fileMap' => [
        'vbt-cron'     => 'vbt-cron.php'
    ],
]
</code>```

but it doesn't work because yii only look for translations inside the module messages folder:

The message file for category 'vbt-cron' does not exist: vendor/sharkom/yii2-cron/messages/it-IT/vbt-cron.php Fallback file does not exist as well: vendor/sharkom/yii2-cron/messages/it/vbt-cron.php

So, how can you make yii look inside the app messages folder as well?

P.S. I'm looking for a generic answer, not for a way to translate the specific module used as example here.

Title: Yii2 translate a module from outside

Body:
If you have a yii2 module installed by composer how can you add a new language without touching the module itself (since touching anything in vendor/ is quite a bad practice)?

Let's say you have a module vbt-cron which already have an English an a Hungarian language files inside and it's configured like this:

\Yii::$app->i18n->translations['vbt-cron'] = [
    'class' => '\yii\i18n\PhpMessageSource',
    'sourceLanguage' => 'en-US',
    'basePath' => '@sharkom/cron/messages',
];

Your app is in Italian so you want to translate the module externally, yii message extracted the strings from the module, you added it to the config:

'vbt-cron' => [
    'class' => 'yii\i18n\PhpMessageSource',
    'basePath' => '@app/messages',
    'fileMap' => [
        'vbt-cron'     => 'vbt-cron.php'
    ],
]

but it doesn't work because yii only look for translations inside the module messages folder:

The message file for category 'vbt-cron' does not exist: vendor/sharkom/yii2-cron/messages/it-IT/vbt-cron.php Fallback file does not exist as well: vendor/sharkom/yii2-cron/messages/it/vbt-cron.php

So, how can you make yii look inside the app messages folder as well?

P.S. I'm looking for a generic answer, not for a way to translate the specific module used as example here.


问:
CS50w - Project 1 - 404 page shown instead of search page
I try to solve cs50w project 1. But I faced an error in the project.

This is the layout.html file. I have a form action: go to search, and the name is q
enter image description here

```<code><form action="{% url 'search' %}" method="POST">
    {% csrf_token %}
    <input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
</code>```

urls.py

```<code>urlpatterns = [
    path("", views.index, name="index"),
    path("<str:title>/", views.title, name="title"),
    path("search/", views.search, name="search"),
]
</code>```

views.py

```<code>def search(request):
    if request.method == "POST":
        entry_search = request.POST['q']
        html_content = markdown2.markdown(util.get_entry(entry_search))
        if html_content is not None:
            return render(request, "encyclopedia/title.html", {
                "content": html_content,
                "title": entry_search,
            })
</code>```

When I start my project and type something in the search bar, it sends me to the error.html page.
enter image description here
But it needs to take me to the title.html page.

Can you help me with this problem?

I need to face with title.html page, but it redirects to error.html

Body:
I try to solve cs50w project 1. But I faced an error in the project.

This is the layout.html file. I have a form action: go to search, and the name is q
enter image description here

<form action="{% url 'search' %}" method="POST">
    {% csrf_token %}
    <input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>

urls.py

urlpatterns = [
    path("", views.index, name="index"),
    path("<str:title>/", views.title, name="title"),
    path("search/", views.search, name="search"),
]

views.py

def search(request):
    if request.method == "POST":
        entry_search = request.POST['q']
        html_content = markdown2.markdown(util.get_entry(entry_search))
        if html_content is not None:
            return render(request, "encyclopedia/title.html", {
                "content": html_content,
                "title": entry_search,
            })

When I start my project and type something in the search bar, it sends me to the error.html page.
enter image description here
But it needs to take me to the title.html page.

Can you help me with this problem?

I need to face with title.html page, but it redirects to error.html


问:
I have this error 'NoneType' object has no attribute 'find_all'. how i can fix this error
When i scraping the data and after call code write at the end of the coding i face this error 'NoneType' object has no attribute 'find_all. this happend when i use the for i in range(1, 51)
and the use i in the uri at that time the error comes.

```<code>for i in range(1, 51):
  uri='https://books.toscrape.com/catalogue/page-{i}.html'
  page=requests.get(uri)
  soup=BeautifulSoup(page.content,'html.parser')
  lists=soup.find('ol')
  articles=lists.find_all('article')
  with open('Books Scrapping.csv', 'w', encoding='utf8') as f:
    thewriter=writer(f)
    header=['Titile', 'Stars', 'Price']
    thewriter.writerow(header)
    for article in articles:
      image=article.find('img')
      title=image.attrs['alt']
      stars=article.find('p')
      stars=stars['class'][1]
      price=article.find('p', class_='price_color').text
      price=float(price[1:])
      info=[title, stars, price]
      thewriter.writerow(info)
</code>```

I try some many time but i cant some this error

Body:
When i scraping the data and after call code write at the end of the coding i face this error 'NoneType' object has no attribute 'find_all. this happend when i use the for i in range(1, 51)
and the use i in the uri at that time the error comes.

for i in range(1, 51):
  uri='https://books.toscrape.com/catalogue/page-{i}.html'
  page=requests.get(uri)
  soup=BeautifulSoup(page.content,'html.parser')
  lists=soup.find('ol')
  articles=lists.find_all('article')
  with open('Books Scrapping.csv', 'w', encoding='utf8') as f:
    thewriter=writer(f)
    header=['Titile', 'Stars', 'Price']
    thewriter.writerow(header)
    for article in articles:
      image=article.find('img')
      title=image.attrs['alt']
      stars=article.find('p')
      stars=stars['class'][1]
      price=article.find('p', class_='price_color').text
      price=float(price[1:])
      info=[title, stars, price]
      thewriter.writerow(info)

I try some many time but i cant some this error


问:
How to create Google Chat API configuration with terraform?
I would like to create a chatbot within my organization using Google Chat API as a terraform resource.

I can create it on the console but I would like to provision it as a terraform resource. I couldn't find a google chat api resource or anything similar in the hashicorp/google provider, although I'm fairly new to GCP.


问:
SSH multiplexing hangs
can someone explain to me how exactly this works.

I have this config in ~/.ssh/config

host *
    ControlMaster auto
    ControlPersist yes
    ControlPath ~/.ssh/muxmasters/%C
```

First time I ssh, takes some time to connect, after that if I exit and ssh again it is faster, and that's what I need.

The problem happens when I exist the ssh connection, and after 5 minutes, if I try to ssh again it hangs like minutes and then I get the ssh connection, when exiting I checked the socket file and it is there, so I dont actually understand how this works.

Not sure if there is a way to keep that speed forever or maybe hours?

Thanks.

Title: SSH multiplexing hangs

Body:
can someone explain to me how exactly this works.

I have this config in ~/.ssh/config

host *
    ControlMaster auto
    ControlPersist yes
    ControlPath ~/.ssh/muxmasters/%C

First time I ssh, takes some time to connect, after that if I exit and ssh again it is faster, and that's what I need.

The problem happens when I exist the ssh connection, and after 5 minutes, if I try to ssh again it hangs like minutes and then I get the ssh connection, when exiting I checked the socket file and it is there, so I dont actually understand how this works.

Not sure if there is a way to keep that speed forever or maybe hours?

Thanks.


问:
Sequlize not really awaiting
i have two tables [ Cart, Product ] which connected with third table called products_carts with many to many relationship
i have two issues here ..
= first issue is when editing the cart
i am changing the products related to this cart by using

```<code>await cart.setProducts(products);
</code>```

and after that i am sending a response contains the new cart so the frontend can edit and do his job (btw i am not sure if it is recommended to return the edited model or not [ to be more specific shoud editing api return only message or message and updated model?  ] )
but the issue is that the products_carts dont update immediately and in the cart i am getting the previous cart_products

I tried Products_Carts.sync()
but that failed

Title: Sequlize not really awaiting

Body:
i have two tables [ Cart, Product ] which connected with third table called products_carts with many to many relationship
i have two issues here ..
= first issue is when editing the cart
i am changing the products related to this cart by using

await cart.setProducts(products);

and after that i am sending a response contains the new cart so the frontend can edit and do his job (btw i am not sure if it is recommended to return the edited model or not [ to be more specific shoud editing api return only message or message and updated model?  ] )
but the issue is that the products_carts dont update immediately and in the cart i am getting the previous cart_products

I tried Products_Carts.sync()
but that failed


问:
How to set two primary key in SQL Server?
I'm making my first project in SQL. A database for an hardware store. I need to make more than one relation to other table from a single table (need more than one primary key).

When I try to create two PRIMARY KEY it has no error, but when I try to make the connections to other tables, those other tables don't recognize those keys.

```<code>CREATE TABLE Product
(
    IDProduct int NOT NULL,
    Part nchar(16) CHECK (Part IN ('CPU', 'CPUCooler', 'Motherboard', 'Storage', 'Memory', 'GraphicCard', 'Case', 'PSU')),
    Quantity tinyint,
    Disponibility bit NOT NULL ,
    Price smallmoney NOT NULl,
    OrderID int FOREIGN KEY REFERENCES Encomenda(IDEncomenda),
    PRIMARY KEY (IDProduct, Part)
)
</code>```

I try to do more tables but it didn't work. I search everywhere and didn't find the solution. I saw my teacher doing it but he don't reply to our class for some time now.

I'm expecting to have two PRIMARY KEY inside a table or be able to create a relation with other table.

Body:
I'm making my first project in SQL. A database for an hardware store. I need to make more than one relation to other table from a single table (need more than one primary key).

When I try to create two PRIMARY KEY it has no error, but when I try to make the connections to other tables, those other tables don't recognize those keys.

CREATE TABLE Product
(
    IDProduct int NOT NULL,
    Part nchar(16) CHECK (Part IN ('CPU', 'CPUCooler', 'Motherboard', 'Storage', 'Memory', 'GraphicCard', 'Case', 'PSU')),
    Quantity tinyint,
    Disponibility bit NOT NULL ,
    Price smallmoney NOT NULl,
    OrderID int FOREIGN KEY REFERENCES Encomenda(IDEncomenda),
    PRIMARY KEY (IDProduct, Part)
)

I try to do more tables but it didn't work. I search everywhere and didn't find the solution. I saw my teacher doing it but he don't reply to our class for some time now.

I'm expecting to have two PRIMARY KEY inside a table or be able to create a relation with other table.


问:
Connecting MongoDb with node for the very first time
I'm connecting mongodb with node js and getting such error</p>
```<code>MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at Connection.openUri (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\connection.js:825:32)
    at C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:419:10
    at C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:1272:10)
    at Mongoose.connect (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:418:20)
    at connect_db (C:\Users\Dell\OneDrive\Desktop\New folder\db.js:5:36)
    at Object.<anonymous> (C:\Users\Dell\OneDrive\Desktop\New folder\app.js:7:1)
    at Module._compile (node:internal/modules/cjs/loader:1159:14) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}
</code>```

Body:
I'm connecting mongodb with node js and getting such error

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at Connection.openUri (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\connection.js:825:32)
    at C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:419:10
    at C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:1272:10)
    at Mongoose.connect (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:418:20)
    at connect_db (C:\Users\Dell\OneDrive\Desktop\New folder\db.js:5:36)
    at Object.<anonymous> (C:\Users\Dell\OneDrive\Desktop\New folder\app.js:7:1)
    at Module._compile (node:internal/modules/cjs/loader:1159:14) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}


问:
CronTab not run
I installed CroneTab, open the editor using crontab -e
and for executing the following statement python3.8 i.pyc every 5 min I wrote

```<code> 5 * * * * #!/usr/bin/python3.8 i.pyc
</code>```

Then, I made sure that no error using sudo less /var/spool/mail/root and saw the crone job in the list with sudo grep CRON /var/log/cron

But unfortunately, the corn is not running, I don't see the output file but if I write python3.8 i.pyc  without the crone, the statement works well.

What I missed ?

Title: CronTab not run

Body:
I installed CroneTab, open the editor using crontab -e
and for executing the following statement python3.8 i.pyc every 5 min I wrote

 5 * * * * #!/usr/bin/python3.8 i.pyc

Then, I made sure that no error using sudo less /var/spool/mail/root and saw the crone job in the list with sudo grep CRON /var/log/cron

But unfortunately, the corn is not running, I don't see the output file but if I write python3.8 i.pyc  without the crone, the statement works well.

What I missed ?


问:
Xcode don't terminate "Run(Build) Pre-action" and execute main.cpp for debug
thank you for your help, I use "Build Pre-action" or "Run Pre-action" in Xcode. My goal is to execute another server-like program before executing main.cpp, and not to close it. But every time I check the log, I found that after successfully executing pre-action script and printing out the log, it will immediately terminate the program, print out the closing log, and then execute main.cpp, but this is not what I want.

I have to execute main.cpp to communicate while the pre-action code is executing, and every time I execute main.cpp, I must re-execute the pre-action code.

Is there any good way? Or is my setting wrong? thanks


问:
How do I make a copy of a list in lower?
I need to do a copy of a list in lower, but I don't want to do it with a loop.
Something like this:

I try doing this:
`

```<code>new_users = ["moresede", "renerico", "antoniogr01", "darknight", "admin"]
new_users_lower = new_user[:].lower()
</code>```

`

Body:
I need to do a copy of a list in lower, but I don't want to do it with a loop.
Something like this:

I try doing this:
`

new_users = ["moresede", "renerico", "antoniogr01", "darknight", "admin"]
new_users_lower = new_user[:].lower()

`


问:
Stuck on Value Function Iteration simulation
I am trying to simulate a model that solves elastic labor supply in macroeconomics—trying to do it by Value Function Iteration. However, I am getting an error that says

```<code>runfile('C:/Users/sence/untitled0.py', wdir='C:/Users/sence')
C:\Users\sence\untitled0.py:52: RuntimeWarning: invalid value encountered in subtract
      if np.max(np.abs(V - V_new)) < tol:
</code>```

My code is the following.

```<code>import numpy as np
import matplotlib.pyplot as plt

# Set parameters
beta = 0.95  # discount factor
rho = 0.1  # utility weight on leisure
alpha = 0.3  # capital share
k_min = 0  # minimum capital level
k_max = 10  # maximum capital level
n_min = 0  # minimum labor supply
n_max = 1  # maximum labor supply
tol = 1e-6  # convergence tolerance

# Define grid over capital
num_points = 100
k_grid = np.linspace(k_min, k_max, num_points)

# Initialize value function
V = np.zeros(num_points)

# Iterate over value function
while True:
    # Initialize value function for this iteration
    V_new = np.zeros(num_points)

    # Iterate over capital levels
    for i, k in enumerate(k_grid[:-1]):
        # Initialize maximum value and optimal labor supply
        max_value = -np.inf
        opt_n = n_min

        # Iterate over labor supply levels
        for n in np.linspace(n_min, n_max, num_points):
            # Compute consumption
            c = k * alpha * n * (1 - alpha) - k_grid[i + 1]

            # Compute value at this point
            if c > 0 and 0 < n < 1:
                value = np.log(c) + rho * np.log(1 - n) + beta * V[i + 1]
            else:
                value = -np.inf

            # Update maximum value and optimal labor supply
            if value > max_value:
                max_value = value
                opt_n = n

        # Update value function for this iteration
        V_new[i] = max_value

    # Check for convergence
    if np.max(np.abs(V - V_new)) < tol:
        break
    else:
        V = V_new

# Compute policy functions
c_policy = k_grid[:-1] * alpha * opt_n * (1 - alpha) - k_grid[1:]
n_policy = opt_n

# Plot policy functions
plt.plot(k_grid, k_grid, 'k--', label='45 degree line')
plt.plot(k_grid[:-1], c_policy, label='Consumption')
plt.plot(k_grid, n_policy, label='Labor supply')
plt.xlabel('Capital')
plt.ylabel('Policy function')
plt.legend()
plt.show()

k_path = [5]  # start at k0 = 5
for t in range(20):
    # Compute consumption
    c = k_path[-1] * alpha * n_policy * (1 - alpha) - k_path[-1]
    k_path.append(k_path[-1] * (1 - n_policy) + c)

plt.plot(k_path)
plt.xlabel('Time')
plt.ylabel('Capital')
plt.show()
</code>```

I don't know where I made a mistake. I solved the model correctly, and everything should work smoothly, yet I keep getting errors. Any help would be appreciated. I am unable to solve it on my own.

Body:
I am trying to simulate a model that solves elastic labor supply in macroeconomics—trying to do it by Value Function Iteration. However, I am getting an error that says

runfile('C:/Users/sence/untitled0.py', wdir='C:/Users/sence')
C:\Users\sence\untitled0.py:52: RuntimeWarning: invalid value encountered in subtract
      if np.max(np.abs(V - V_new)) < tol:

My code is the following.

import numpy as np
import matplotlib.pyplot as plt

# Set parameters
beta = 0.95  # discount factor
rho = 0.1  # utility weight on leisure
alpha = 0.3  # capital share
k_min = 0  # minimum capital level
k_max = 10  # maximum capital level
n_min = 0  # minimum labor supply
n_max = 1  # maximum labor supply
tol = 1e-6  # convergence tolerance

# Define grid over capital
num_points = 100
k_grid = np.linspace(k_min, k_max, num_points)

# Initialize value function
V = np.zeros(num_points)

# Iterate over value function
while True:
    # Initialize value function for this iteration
    V_new = np.zeros(num_points)

    # Iterate over capital levels
    for i, k in enumerate(k_grid[:-1]):
        # Initialize maximum value and optimal labor supply
        max_value = -np.inf
        opt_n = n_min

        # Iterate over labor supply levels
        for n in np.linspace(n_min, n_max, num_points):
            # Compute consumption
            c = k * alpha * n * (1 - alpha) - k_grid[i + 1]

            # Compute value at this point
            if c > 0 and 0 < n < 1:
                value = np.log(c) + rho * np.log(1 - n) + beta * V[i + 1]
            else:
                value = -np.inf

            # Update maximum value and optimal labor supply
            if value > max_value:
                max_value = value
                opt_n = n

        # Update value function for this iteration
        V_new[i] = max_value

    # Check for convergence
    if np.max(np.abs(V - V_new)) < tol:
        break
    else:
        V = V_new

# Compute policy functions
c_policy = k_grid[:-1] * alpha * opt_n * (1 - alpha) - k_grid[1:]
n_policy = opt_n

# Plot policy functions
plt.plot(k_grid, k_grid, 'k--', label='45 degree line')
plt.plot(k_grid[:-1], c_policy, label='Consumption')
plt.plot(k_grid, n_policy, label='Labor supply')
plt.xlabel('Capital')
plt.ylabel('Policy function')
plt.legend()
plt.show()

k_path = [5]  # start at k0 = 5
for t in range(20):
    # Compute consumption
    c = k_path[-1] * alpha * n_policy * (1 - alpha) - k_path[-1]
    k_path.append(k_path[-1] * (1 - n_policy) + c)

plt.plot(k_path)
plt.xlabel('Time')
plt.ylabel('Capital')
plt.show()

I don't know where I made a mistake. I solved the model correctly, and everything should work smoothly, yet I keep getting errors. Any help would be appreciated. I am unable to solve it on my own.


问:
I need help giving function to my edit button when clicked to edit the shopping list item, then saving changes
after searching, I don't know where to start to give edit button functionality so the code that I did try, I've already deleted. My delete button is fully functional by the way. I thought an if else statement would work but I yielded no results.

```<code>

// submit event
</code>```

type here

```<code>
//create form

const form = document["addItem"]
const div = document.querySelector('#todos')
const ul = document.querySelector('#list');

form.addEventListener("submit", (e) => {
 e.preventDefault();
    // addItem event handler for submit event on submit
      const typedInput = document.getElementById("title").value
      console.log(typedInput)
      const list = document.getElementById("list")
      document.addEventListener("click", addItem);

      // created elements and appended to list to display on the website
      const div = document.createElement("div")
      const ul = document.createElement("list");
      const li = document.createElement("li");
      div.appendChild(document.createTextNode(typedInput));
      ul.appendChild(li);
      li.appendChild(div);
      // added button to represent the edit button when clicked
      const button = document.createElement("button");
      button.name = "edit";
      li.appendChild(button).textContent = "edit"

// added newButton to store delete button, appended to the parentElement to remove the list item
//after submission
      const newButton = document.createElement("button");
      newButton.name = "removeItem";
      li.appendChild(newButton).textContent = "X"
      document.getElementById('list').appendChild(li);
      newButton.addEventListener("click", function(){
          this.parentNode.remove();

      })
     })
</code>```

Body:
after searching, I don't know where to start to give edit button functionality so the code that I did try, I've already deleted. My delete button is fully functional by the way. I thought an if else statement would work but I yielded no results.

// submit event

type here

//create form

const form = document["addItem"]
const div = document.querySelector('#todos')
const ul = document.querySelector('#list');

form.addEventListener("submit", (e) => {
 e.preventDefault();
    // addItem event handler for submit event on submit
      const typedInput = document.getElementById("title").value
      console.log(typedInput)
      const list = document.getElementById("list")
      document.addEventListener("click", addItem);

      // created elements and appended to list to display on the website
      const div = document.createElement("div")
      const ul = document.createElement("list");
      const li = document.createElement("li");
      div.appendChild(document.createTextNode(typedInput));
      ul.appendChild(li);
      li.appendChild(div);
      // added button to represent the edit button when clicked
      const button = document.createElement("button");
      button.name = "edit";
      li.appendChild(button).textContent = "edit"

// added newButton to store delete button, appended to the parentElement to remove the list item
//after submission
      const newButton = document.createElement("button");
      newButton.name = "removeItem";
      li.appendChild(newButton).textContent = "X"
      document.getElementById('list').appendChild(li);
      newButton.addEventListener("click", function(){
          this.parentNode.remove();

      })
     })


问:
How do I upload an image for tooting on Mastodon when the image file name or description contain non-ascii characters?
I want to toot an image where the local file name contains non-ascii (utf8) characters, or where the description contains non-ascii (utf8) characters.

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Mastodon::Client;
use HTML::Entities;

my $client = Mastodon::Client->new(
    client_id => "...",
    client_secret => "...",
    access_token => "...",
    instance => "mstdn.io",
    name => 'PerlBot',
    coerce_entities => 1,
);

$client->upload_media('logo.png',
    {
        'description' => "Für mich",   # 400 Bad request
#        'description' => encode_entities("Für mich"),   # 500 internal server error
#        'description' => 'only ascii',   # ok
    },
);
```

If the description contains e.g., an ü, I get a HTTP 400 bad request error. If I HTML-encode the entities, I get a HTTP 500 internal server error. It works when the description contains only ASCII characters, but that's really inconvenient.

Same thing with the local image file name; if I have e.g., "lögö.png" instead of "logo.png" I also get the HTTP 400 error.

The official API documentation doesn't say anything about character encodings, and neither does the Mastodon::Client documentation.

How can I toot file where the name and the description contain non-ASCII characters, in particular utf8 characters?

Body:
I want to toot an image where the local file name contains non-ascii (utf8) characters, or where the description contains non-ascii (utf8) characters.

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Mastodon::Client;
use HTML::Entities;

my $client = Mastodon::Client->new(
    client_id => "...",
    client_secret => "...",
    access_token => "...",
    instance => "mstdn.io",
    name => 'PerlBot',
    coerce_entities => 1,
);

$client->upload_media('logo.png',
    {
        'description' => "Für mich",   # 400 Bad request
#        'description' => encode_entities("Für mich"),   # 500 internal server error
#        'description' => 'only ascii',   # ok
    },
);

If the description contains e.g., an ü, I get a HTTP 400 bad request error. If I HTML-encode the entities, I get a HTTP 500 internal server error. It works when the description contains only ASCII characters, but that's really inconvenient.

Same thing with the local image file name; if I have e.g., "lögö.png" instead of "logo.png" I also get the HTTP 400 error.

The official API documentation doesn't say anything about character encodings, and neither does the Mastodon::Client documentation.

How can I toot file where the name and the description contain non-ASCII characters, in particular utf8 characters?


问:
Laravel 9 and jQuery only showing data of datatable first row
I have a datatable list with different categories. I created an edit button on every row using "foreach", the button popups a modal that shows a form with the data of every category. In this form I have 2 dropdowns, the first shows the sections to which each category belongs and the second droopdown should show every category that belongs to that section. I created a jQuery that updates the second dropdown to show that categories, the problem is it will only work with the first row of the datatable.

This is the button that triggers the jquery

```<code><a class="updateLevel" catId="{{ $category['id'] }}" data-bs-toggle="modal" href="#edit{{$category['id']}}"><i class="mdi mdi-pencil-outline" style="font-size:22px;"></i></a>
</code>```

This is the jQuery

```<code>    $(document).on("click",".updateLevel",function(){
        var catId = $(this).attr('catId');
        alert(catId);
        $.ajax({
            headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            type:'get',
            url:'append-categories-level',
            data:{catId:catId},
            success:function(resp){
                // alert(resp);
                $("#appendCategoriesLevel").html(resp);
            },error:function(){
                alert("Error");
            }
        });
    });
</code>```

And this is the function in the controller I am using

```<code>    // Append Level
    public function appendCategoriesLevel(Request $request){

        if($request->ajax()){
            $catId= $request->catId;
            $category = Category::find($catId);
            $getCategories = Category::where(['parent_id'=>0,'section_id'=>$category['section_id']])->get()->toArray();
            echo "```"; print_r($getCategories);
            return view('admin.categories.append_categories_level')->with(compact('getCategories'));
        }
    }
```
<p>Here is the dropdown HTML</p>
```

    Nivel
    <select name="parent_id" id="parent_id" class="form-control">
        <option value="0">Principal</option>
        @if(!empty($getCategories))
            @foreach($getCategories as $category)
                <option value="{{ $category['id'] }}">{{ $category['category_name'] }}</option>
            @endforeach
        @endif
    </select>

```
<p>This is my datatable</p>
```

                                ID
                                Categoría
                                Categoría Padre
                                Sección
                                URL
                                Estado
                                Acción

                            @foreach($categories as $category)
                            @if(isset($category['parentcategory']['category_name'])&&!empty($category['parentcategory']['category_name']))
                                @php $parent_category = $category['parentcategory']['category_name']; @endphp
                            @else
                                @php $parent_category = "Ninguno"; @endphp
                            @endif

                                {{ $category['id'] }}
                                {{ $category['category_name'] }}
                                {{ $parent_category }}
                                {{ $category['section']['name'] }}
                                {{ $category['url'] }}

                                @if($category['status']==1)  @else  @endif

                                    @include('admin.categories.edit')

                            @endforeach

```
<p>I tried debugging my code, and saw that I am getting the values for each one of the datatable rows</p>
<p>For example this would be for the first row (Which is working fine and populating the dropdown)</p>
``````Array
(
    [0] => Array
        (
            [id] => 1
            [parent_id] => 0
            [section_id] => 2
            [category_name] => Ropa Mujeres
            [description] => Ropa para Mujeres
            [category_image] =>
            [category_discount] => 0
            [url] => womensclothing
            [meta_title] => womensclothing
            [meta_description] => womensclothing
            [meta_keywords] => womens clothing
            [status] => 1
            [created_at] =>
            [updated_at] => 2022-12-22T22:08:27.000000Z
        )

    [1] => Array
        (
            [id] => 2
            [parent_id] => 0
            [section_id] => 2
            [category_name] => Accesorios
            [description] => Accesorios de Mujer
            [category_image] =>
            [category_discount] => 0
            [url] => womensaccesories
            [meta_title] => womensaccesories
            [meta_description] => womensaccesories
            [meta_keywords] => womens accesories
            [status] => 1
            [created_at] =>
            [updated_at] => 2022-12-22T21:50:19.000000Z
        )

    [2] => Array
        (
            [id] => 3
            [parent_id] => 0
            [section_id] => 2
            [category_name] => Zapatos
            [description] => Zapatos de Mujer
            [category_image] =>
            [category_discount] => 0
            [url] => womensshoes
            [meta_title] => womensshoes
            [meta_description] => womensshoes
            [meta_keywords] => womens shoes
            [status] => 1
            [created_at] =>
            [updated_at] => 2022-12-22T14:31:06.000000Z
        )

)
<div class="mb-1">
    <label class="form-label" for="parent_id">Nivel</label>
    <select name="parent_id" id="parent_id" class="form-control">
        <option value="0">Principal</option>
                                    <option value="1">Ropa Mujeres</option>
                            <option value="2">Accesorios</option>
                            <option value="3">Zapatos</option>
                        </select>
</div>
</code>```

and this would be for the row number 5 which is not populating the dropdown

```<code>```Array
(
    [0] => Array
        (
            [id] => 4
            [parent_id] => 0
            [section_id] => 1
            [category_name] => Ropa Hombres
            [description] => Ropa para Hombres
            [category_image] =>
            [category_discount] => 0
            [url] => mensclothing
            [meta_title] => mensclothing
            [meta_description] => mensclothing
            [meta_keywords] => mens clothing
            [status] => 1
            [created_at] => 2022-12-22T02:54:20.000000Z
            [updated_at] => 2022-12-22T22:08:37.000000Z
        )

    [1] => Array
        (
            [id] => 5
            [parent_id] => 0
            [section_id] => 1
            [category_name] => Accesorios Hombres
            [description] => Accesorios para hombre
            [category_image] =>
            [category_discount] => 0
            [url] => accesorioshombre
            [meta_title] => accesorioshombre
            [meta_description] => accesorioshombre
            [meta_keywords] => accesorios hombre
            [status] => 1
            [created_at] => 2022-12-23T02:03:29.000000Z
            [updated_at] => 2022-12-23T02:03:29.000000Z
        )

)

    Nivel
    <select name="parent_id" id="parent_id" class="form-control">
        <option value="0">Principal</option>
                                    <option value="4">Ropa Hombres</option>
                            <option value="5">Accesorios Hombres</option>
                        </select>

```
<p>Here is the controller</p>
```public function appendCategoriesLevel(Request $request){

    if($request->ajax()){
        $catId= $request->catId;
        $category = Category::find($catId);
        $getCategories = Category::where(['parent_id'=>0,'section_id'=>$category['section_id']])->get()->toArray();
        echo "```"; print_r($getCategories);
        return view('admin.categories.append_categories_level')->with(compact('getCategories'));
    }
}
</code>```

Here is what I get when I click on the first row

and this is in the first row

Clearly, I am getting the data, but they are only populating for the first row. I also tried adding an else statement to the dropdown html to see if its empty and it is for every row except the first one.

Body:
I have a datatable list with different categories. I created an edit button on every row using "foreach", the button popups a modal that shows a form with the data of every category. In this form I have 2 dropdowns, the first shows the sections to which each category belongs and the second droopdown should show every category that belongs to that section. I created a jQuery that updates the second dropdown to show that categories, the problem is it will only work with the first row of the datatable.

This is the button that triggers the jquery

This is the jQuery

    $(document).on("click",".updateLevel",function(){
        var catId = $(this).attr('catId');
        alert(catId);
        $.ajax({
            headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            type:'get',
            url:'append-categories-level',
            data:{catId:catId},
            success:function(resp){
                // alert(resp);
                $("#appendCategoriesLevel").html(resp);
            },error:function(){
                alert("Error");
            }
        });
    });

And this is the function in the controller I am using

    // Append Level
    public function appendCategoriesLevel(Request $request){

        if($request->ajax()){
            $catId= $request->catId;
            $category = Category::find($catId);
            $getCategories = Category::where(['parent_id'=>0,'section_id'=>$category['section_id']])->get()->toArray();
            echo "
"; print_r($getCategories);
            return view('admin.categories.append_categories_level')->with(compact('getCategories'));
        }
    }

Here is the dropdown HTML

    Nivel
    <select name="parent_id" id="parent_id" class="form-control">
        <option value="0">Principal</option>
        @if(!empty($getCategories))
            @foreach($getCategories as $category)
                <option value="{{ $category['id'] }}">{{ $category['category_name'] }}</option>
            @endforeach
        @endif
    </select>

This is my datatable

                                ID
                                Categoría
                                Categoría Padre
                                Sección
                                URL
                                Estado
                                Acción

                            @foreach($categories as $category)
                            @if(isset($category['parentcategory']['category_name'])&&!empty($category['parentcategory']['category_name']))
                                @php $parent_category = $category['parentcategory']['category_name']; @endphp
                            @else
                                @php $parent_category = "Ninguno"; @endphp
                            @endif

                                {{ $category['id'] }}
                                {{ $category['category_name'] }}
                                {{ $parent_category }}
                                {{ $category['section']['name'] }}
                                {{ $category['url'] }}

                                @if($category['status']==1)  @else  @endif

                                    @include('admin.categories.edit')

                            @endforeach

I tried debugging my code, and saw that I am getting the values for each one of the datatable rows

For example this would be for the first row (Which is working fine and populating the dropdown)

Array
(
    [0] => Array
        (
            [id] => 1
            [parent_id] => 0
            [section_id] => 2
            [category_name] => Ropa Mujeres
            [description] => Ropa para Mujeres
            [category_image] =>
            [category_discount] => 0
            [url] => womensclothing
            [meta_title] => womensclothing
            [meta_description] => womensclothing
            [meta_keywords] => womens clothing
            [status] => 1
            [created_at] =>
            [updated_at] => 2022-12-22T22:08:27.000000Z
        )

    [1] => Array
        (
            [id] => 2
            [parent_id] => 0
            [section_id] => 2
            [category_name] => Accesorios
            [description] => Accesorios de Mujer
            [category_image] =>
            [category_discount] => 0
            [url] => womensaccesories
            [meta_title] => womensaccesories
            [meta_description] => womensaccesories
            [meta_keywords] => womens accesories
            [status] => 1
            [created_at] =>
            [updated_at] => 2022-12-22T21:50:19.000000Z
        )

    [2] => Array
        (
            [id] => 3
            [parent_id] => 0
            [section_id] => 2
            [category_name] => Zapatos
            [description] => Zapatos de Mujer
            [category_image] =>
            [category_discount] => 0
            [url] => womensshoes
            [meta_title] => womensshoes
            [meta_description] => womensshoes
            [meta_keywords] => womens shoes
            [status] => 1
            [created_at] =>
            [updated_at] => 2022-12-22T14:31:06.000000Z
        )

)

    Nivel
    <select name="parent_id" id="parent_id" class="form-control">
        <option value="0">Principal</option>
                                    <option value="1">Ropa Mujeres</option>
                            <option value="2">Accesorios</option>
                            <option value="3">Zapatos</option>
                        </select>

and this would be for the row number 5 which is not populating the dropdown

Array
(
    [0] => Array
        (
            [id] => 4
            [parent_id] => 0
            [section_id] => 1
            [category_name] => Ropa Hombres
            [description] => Ropa para Hombres
            [category_image] =>
            [category_discount] => 0
            [url] => mensclothing
            [meta_title] => mensclothing
            [meta_description] => mensclothing
            [meta_keywords] => mens clothing
            [status] => 1
            [created_at] => 2022-12-22T02:54:20.000000Z
            [updated_at] => 2022-12-22T22:08:37.000000Z
        )

    [1] => Array
        (
            [id] => 5
            [parent_id] => 0
            [section_id] => 1
            [category_name] => Accesorios Hombres
            [description] => Accesorios para hombre
            [category_image] =>
            [category_discount] => 0
            [url] => accesorioshombre
            [meta_title] => accesorioshombre
            [meta_description] => accesorioshombre
            [meta_keywords] => accesorios hombre
            [status] => 1
            [created_at] => 2022-12-23T02:03:29.000000Z
            [updated_at] => 2022-12-23T02:03:29.000000Z
        )

)

    Nivel
    <select name="parent_id" id="parent_id" class="form-control">
        <option value="0">Principal</option>
                                    <option value="4">Ropa Hombres</option>
                            <option value="5">Accesorios Hombres</option>
                        </select>

Here is the controller

public function appendCategoriesLevel(Request $request){

    if($request->ajax()){
        $catId= $request->catId;
        $category = Category::find($catId);
        $getCategories = Category::where(['parent_id'=>0,'section_id'=>$category['section_id']])->get()->toArray();
        echo "
"; print_r($getCategories);
        return view('admin.categories.append_categories_level')->with(compact('getCategories'));
    }
}

Here is what I get when I click on the first row

and this is in the first row

Clearly, I am getting the data, but they are only populating for the first row. I also tried adding an else statement to the dropdown html to see if its empty and it is for every row except the first one.


问:
how to bind Id or group of two concatenated SelectListItem separate to check item of which group selected

var Warehouse = new SelectListGroup() { Name = "گدام" };
var SalesVehicle = new SelectListGroup() { Name = "موتر پخش" };

var Warehouselist = _context.Warehouses.Select(y => new SelectListItem()
{
    Text = y.Name + " (گدام) ",
    Value = y.Id.ToString(),
    Group = Warehouse
}).ToList().Concat(_context.SalesVehicles.Select(y => new
    SelectListItem()
    {
        Text = y.VehicleName + "(موتر پخش)",
        Value = y.Id.ToString(),
        Group = SalesVehicle
    })).ToList();
```

When I bind the Id I do not know that this Id belongs to which group warehouse or sale vehicle so there is conflict with Id!

Body:
var Warehouse = new SelectListGroup() { Name = "گدام" };
var SalesVehicle = new SelectListGroup() { Name = "موتر پخش" };

var Warehouselist = _context.Warehouses.Select(y => new SelectListItem()
{
    Text = y.Name + " (گدام) ",
    Value = y.Id.ToString(),
    Group = Warehouse
}).ToList().Concat(_context.SalesVehicles.Select(y => new
    SelectListItem()
    {
        Text = y.VehicleName + "(موتر پخش)",
        Value = y.Id.ToString(),
        Group = SalesVehicle
    })).ToList();

When I bind the Id I do not know that this Id belongs to which group warehouse or sale vehicle so there is conflict with Id!


问:
Images aren't appearing on screen in react
I'm trying to render images on the screen to make an image slider, but the photos aren't appearing. The code will be provided below.</p>
```<code>import service1 from './../assets/service1.jpg'
import service2 from './../assets/service2.jpg'
import service3 from './../assets/service3.jpg'

    const slides = [
      {
    url: { service1 }

    },
      {
    url: { service2 }
    },
      {
    url: { service3 }
    },
    ];

return (
  <div className="max-w-[1400px] h-[580px] w-full m-auto py-16 px-4 relative">
    <div
      className="w-full h-full rounded-2xl bg-center bg-cover duration-500"
      style={{ backgroundImage: `url(${slides[0].url})` }}
    ></div>
  </div>
);

</code>```

Body:
I'm trying to render images on the screen to make an image slider, but the photos aren't appearing. The code will be provided below.

import service1 from './../assets/service1.jpg'
import service2 from './../assets/service2.jpg'
import service3 from './../assets/service3.jpg'

    const slides = [
      {
    url: { service1 }

    },
      {
    url: { service2 }
    },
      {
    url: { service3 }
    },
    ];

return (

    <div
      className="w-full h-full rounded-2xl bg-center bg-cover duration-500"
      style={{ backgroundImage: `url(${slides[0].url})` }}
    >

);


问:
I can't use coordinate values in list for hough line function
I want to use the Hough line function. When I look at my list, yes, I found the coordinate values of the edges, but when I want to plot it in a for loop, I get an error. Here is the error message: TypeError: 'numpy.ndarray' object is not callable

```<code>import cv2
import numpy as np

img = cv2.imread("a.png")

img = cv2.resize(img,(640,480))

# cap = cv2.VideoCapture(0)

while True:
    # ret, frame = cap.read()
    # frame = cv2.flip(frame,1)

    # print(frame.shape)    # 480,640

    ycrbc = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)

    minYCrCb = np.array([0,140,90],np.uint8)
    maxYCrCb = np.array([230,170,120],np.uint8)
    imgeYCrCb = cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)
    skinRegionYCrCb = cv2.inRange(imgeYCrCb,minYCrCb,maxYCrCb)
    skinYCrCb = cv2.bitwise_and(img, img, mask = skinRegionYCrCb)
    median_ycrcb = cv2.medianBlur(skinYCrCb, 3)

    _, esik = cv2.threshold(median_ycrcb, 20, 255, cv2.THRESH_BINARY)
    median_binary = cv2.medianBlur(esik, 7)

    gray = cv2.cvtColor(median_binary, cv2.COLOR_BGR2GRAY)

    contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    areas = [cv2.contourArea(c) for c in contours]
    max_index = np.argmax(areas)
    x,y,w,h = cv2.boundingRect(contours[max_index])

    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    mask = np.zeros_like(gray_img)
    mask[y:h, x:w] = 255

    masked_image = cv2.bitwise_and(gray_img, mask)
    edges = cv2.Canny(gray,75,250)
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, 50)

    print(lines)

    for line in lines:
        x1, y1, x2, y2 = line[0]
        cv2.line(img(x1, y1), (x2, y2), (0,255,0), 2)

    # height, width = h, w
    # region_of_interest_vertices = [(width/4, 11*height/12), (width/4, 13*height/16), (3*width/4, 13*height/16), (3*width/4, 11*height/12)]

    cv2.imshow("ycrbc",ycrbc)
    cv2.imshow("skinYCrCb",median_ycrcb)
    cv2.imshow("binary goruntu", esik)
    cv2.imshow("median_binary", median_binary)
    cv2.imshow("Kesilmis Goruntu",masked_image)
    cv2.imshow("Edges",edges)

    if cv2.waitKey(5) & 0xFF == ord("q"):
        break

# cap.release()
cv2.destroyAllWindows()

</code>```

I want to draw the edges, then I will try to produce results from the output I get

Body:
I want to use the Hough line function. When I look at my list, yes, I found the coordinate values of the edges, but when I want to plot it in a for loop, I get an error. Here is the error message: TypeError: 'numpy.ndarray' object is not callable

import cv2
import numpy as np

img = cv2.imread("a.png")

img = cv2.resize(img,(640,480))

# cap = cv2.VideoCapture(0)

while True:
    # ret, frame = cap.read()
    # frame = cv2.flip(frame,1)

    # print(frame.shape)    # 480,640

    ycrbc = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)

    minYCrCb = np.array([0,140,90],np.uint8)
    maxYCrCb = np.array([230,170,120],np.uint8)
    imgeYCrCb = cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)
    skinRegionYCrCb = cv2.inRange(imgeYCrCb,minYCrCb,maxYCrCb)
    skinYCrCb = cv2.bitwise_and(img, img, mask = skinRegionYCrCb)
    median_ycrcb = cv2.medianBlur(skinYCrCb, 3)

    _, esik = cv2.threshold(median_ycrcb, 20, 255, cv2.THRESH_BINARY)
    median_binary = cv2.medianBlur(esik, 7)

    gray = cv2.cvtColor(median_binary, cv2.COLOR_BGR2GRAY)

    contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    areas = [cv2.contourArea(c) for c in contours]
    max_index = np.argmax(areas)
    x,y,w,h = cv2.boundingRect(contours[max_index])

    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    mask = np.zeros_like(gray_img)
    mask[y:h, x:w] = 255

    masked_image = cv2.bitwise_and(gray_img, mask)
    edges = cv2.Canny(gray,75,250)
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, 50)

    print(lines)

    for line in lines:
        x1, y1, x2, y2 = line[0]
        cv2.line(img(x1, y1), (x2, y2), (0,255,0), 2)

    # height, width = h, w
    # region_of_interest_vertices = [(width/4, 11*height/12), (width/4, 13*height/16), (3*width/4, 13*height/16), (3*width/4, 11*height/12)]

    cv2.imshow("ycrbc",ycrbc)
    cv2.imshow("skinYCrCb",median_ycrcb)
    cv2.imshow("binary goruntu", esik)
    cv2.imshow("median_binary", median_binary)
    cv2.imshow("Kesilmis Goruntu",masked_image)
    cv2.imshow("Edges",edges)

    if cv2.waitKey(5) & 0xFF == ord("q"):
        break

# cap.release()
cv2.destroyAllWindows()

I want to draw the edges, then I will try to produce results from the output I get


问:
File conversion - From Dataframe to Fixed Width File
I'm reading a Fixed Width Text file and loading into a Dataframe, From the df i'm repositioning columns so I can write to a file with Fixed Width columns. Any ideas what im doing wrong?

#Read File from Target Directory

```<code>    for file in fileNames:
        if file.is_file():
            print(file.name)

#FWF to read file
transfile = pd.read_fwf(file , skiprows=1, skipfooter=1, header=None, converters={0:str, 1:str}, keep_default_na=False,
widths=[
12,#ID  index1
12,#SURNAME  index2
7,#FIRSTNAME  index3
1,#MIDDLEINITIAL  index4
1,#GENDER  index5
8,#BIRTHDATE  index6
1,#Filler  index7....

# Create a DataFrame object
df = pd.DataFrame(columns=[
'recordType', 'ID','SURNAME','FIRSTNAME'...

#Paddle to Fixed Width per Column
df['DI']=tc61[0]
df['SURNAME']=tc61[1]
df['FIRSTNAME']=tc61[2]
df['MIDDLEINITIAL']=tc61[3]
df['GENDER']=tc61[4]
df['ID']=df['ID'].str.ljust(12," ").replace(np.nan, ' ')
df['SURNAME']=df['SURNAME'].str.ljust(12," ").replace(np.nan, ' ')
df['FIRSTNAME']=df['FIRSTNAME'].str.ljust(7," ").replace(np.nan, ' ')
df['MIDDLEINITIAL']=df['MIDDLEINITIAL'].str.ljust(1," ").replace(np.nan, ' ')
#Join all columns
fixedWidthFile = order[order.columns[0:]].apply(lambda x:''.join(x.dropna().astype(str)),axis=1)
#Last step is to write to text File file = open("file.txt", "w+")
content = str(fixedWidthFile)
file.write(content)
file.close()
file = open("file.txt", "r")
content = file.read()
print("\nContent in file.txt:\n", content)
file.close()```

```

Body:
I'm reading a Fixed Width Text file and loading into a Dataframe, From the df i'm repositioning columns so I can write to a file with Fixed Width columns. Any ideas what im doing wrong?

#Read File from Target Directory

    for file in fileNames:
        if file.is_file():
            print(file.name)

#FWF to read file
transfile = pd.read_fwf(file , skiprows=1, skipfooter=1, header=None, converters={0:str, 1:str}, keep_default_na=False,
widths=[
12,#ID  index1
12,#SURNAME  index2
7,#FIRSTNAME  index3
1,#MIDDLEINITIAL  index4
1,#GENDER  index5
8,#BIRTHDATE  index6
1,#Filler  index7....

# Create a DataFrame object
df = pd.DataFrame(columns=[
'recordType', 'ID','SURNAME','FIRSTNAME'...

#Paddle to Fixed Width per Column
df['DI']=tc61[0]
df['SURNAME']=tc61[1]
df['FIRSTNAME']=tc61[2]
df['MIDDLEINITIAL']=tc61[3]
df['GENDER']=tc61[4]
df['ID']=df['ID'].str.ljust(12," ").replace(np.nan, ' ')
df['SURNAME']=df['SURNAME'].str.ljust(12," ").replace(np.nan, ' ')
df['FIRSTNAME']=df['FIRSTNAME'].str.ljust(7," ").replace(np.nan, ' ')
df['MIDDLEINITIAL']=df['MIDDLEINITIAL'].str.ljust(1," ").replace(np.nan, ' ')
#Join all columns
fixedWidthFile = order[order.columns[0:]].apply(lambda x:''.join(x.dropna().astype(str)),axis=1)
#Last step is to write to text File file = open("file.txt", "w+")
content = str(fixedWidthFile)
file.write(content)
file.close()
file = open("file.txt", "r")
content = file.read()
print("\nContent in file.txt:\n", content)
file.close()```


问:
Python Script returns falsely created output video
I'm attempting to develop a python script that creates an output video with a randomly chosen video from a folder and an inserted text.
As soon as I run the script, the Output Video includes a background video and text. Unfortunately, the text only includes the path name to the script and not the inserted text.
Changing the inserted text won't solve anything. Thanks in advance!</p>
```<code>import random
import cv2
import os

# Set the font and font scale for the text
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 1

# Set the thickness of the text
thickness = 2

# Set the text color to white
color = (255, 255, 255)

# Set the text font to Times New Roman
font_face = cv2.FONT_HERSHEY_TRIPLEX

# Read in the inserted text
text = input("Lorem Ipsum. Ipsum Lorem")

# Split the text into individual sentences
sentences = text.split(".")

# Create a list of videos in the folder
video_files = [f for f in os.listdir(".") if f.endswith(".mp4")]

# Choose a random video from the list
random_video = random.choice(video_files)

# Open the video using cv2
video = cv2.VideoCapture(random_video)

# Get the width and height of the video frame
frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Set the output video file name
output_video = "overlayed_" + random_video

# Create a VideoWriter object for writing the output video
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_video, fourcc, 20.0, (frame_width, frame_height))

# Read frames from the video until it is completed
while video.isOpened():
    ret, frame = video.read()
    if ret:
        # Calculate the y-coordinate for the text block
        text_y = int(frame_height * 0.5)

        # Add each sentence to the frame, with a new line for each sentence
        for i, sentence in enumerate(sentences):
            text_size = cv2.getTextSize(sentence, font_face, font_scale, thickness)[0]
            text_x = int((frame_width - text_size[0]) / 2)
            text_y += text_size[1] + 10
            cv2.putText(frame, sentence, (text_x, text_y), font_face, font_scale, color, thickness)

        # Write the frame to the output video
        out.write(frame)
    else:
        break

# Release the video and VideoWriter objects
video.release()
out.release()

# Display a message indicating that the output video has been created
print(f"The output video with overlaid text has been saved as '{output_video}'.")
</code>```

Body:
I'm attempting to develop a python script that creates an output video with a randomly chosen video from a folder and an inserted text.
As soon as I run the script, the Output Video includes a background video and text. Unfortunately, the text only includes the path name to the script and not the inserted text.
Changing the inserted text won't solve anything. Thanks in advance!

import random
import cv2
import os

# Set the font and font scale for the text
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 1

# Set the thickness of the text
thickness = 2

# Set the text color to white
color = (255, 255, 255)

# Set the text font to Times New Roman
font_face = cv2.FONT_HERSHEY_TRIPLEX

# Read in the inserted text
text = input("Lorem Ipsum. Ipsum Lorem")

# Split the text into individual sentences
sentences = text.split(".")

# Create a list of videos in the folder
video_files = [f for f in os.listdir(".") if f.endswith(".mp4")]

# Choose a random video from the list
random_video = random.choice(video_files)

# Open the video using cv2
video = cv2.VideoCapture(random_video)

# Get the width and height of the video frame
frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Set the output video file name
output_video = "overlayed_" + random_video

# Create a VideoWriter object for writing the output video
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_video, fourcc, 20.0, (frame_width, frame_height))

# Read frames from the video until it is completed
while video.isOpened():
    ret, frame = video.read()
    if ret:
        # Calculate the y-coordinate for the text block
        text_y = int(frame_height * 0.5)

        # Add each sentence to the frame, with a new line for each sentence
        for i, sentence in enumerate(sentences):
            text_size = cv2.getTextSize(sentence, font_face, font_scale, thickness)[0]
            text_x = int((frame_width - text_size[0]) / 2)
            text_y += text_size[1] + 10
            cv2.putText(frame, sentence, (text_x, text_y), font_face, font_scale, color, thickness)

        # Write the frame to the output video
        out.write(frame)
    else:
        break

# Release the video and VideoWriter objects
video.release()
out.release()

# Display a message indicating that the output video has been created
print(f"The output video with overlaid text has been saved as '{output_video}'.")


问:
check the value of a model input QGIS
I am making a graphical modeler in QGIS and I want to know if the value of an input can be checked.

This is to see if the user has filled in that value or left it empty. I have put the entry that is not mandatory.

Can this be checked and if it is null do one thing and if it is not null do something else?

enter image description here

Currently, if the user does not enter a variable in that field (although it is not required), it gives the following error: "Could not load source layer for INPUT: not found".

I have tried the "Conditional branch" tool, but I don't get out of here.

enter image description here

Title: check the value of a model input QGIS


问:
fatal: No rebase in progress? - github

i'm getting fatal: No rebase in progress? when i use git rebase --abort or git rebase --continue

error: src refspec master does not match any

error: failed to push some refs to 'https://github.com/url'

i tried this to push files into the same repository and i got these errors
error: src refspec master does not match any
error: failed to push some refs to 'https://github.com/rishikaponna/WD-L6'

Title: fatal: No rebase in progress? - github


问:
How does Stripe instantly update when a timestamp is reached?
I am trying to understand how a service like Stripe is able to instantly update when a timestamp, such as a subscription end date, is reached. I'm guessing it's not just a matter of having a timer with a callback function, since that would likely be too inefficient and unreliable given the immense number of subscriptions they manage.

I'm somewhat familiar with concepts such as Polling, Pub/Sub, and triggers; but I'm not sure if they're relevant in this case. Polling makes no sense as it would require constant requests to the database. I'm not familiar with triggers that can activate upon a timestamp being reached, and my research suggested this is true. Pub/Sub appears to be the most likely implementation approach I can think of, however, I cannot seem to figure out how it would be done.

I'm wondering if anyone has insights on how this might be implemented, possibly with the use of a queue or some other mechanism. Any thoughts or pointers in the right direction would be greatly appreciated.


问:
What makes `git reset --hard` not getting me back to the last commit?
Starting from commit A, I did some changes on the files. Before a mass renaming*, I did commit B. After that I wanted to redo it again so I did git reset --hard. I expected it to be exactly what I got when I just committed B. The folders with old name are retrieved with their files, which is expected. But:

The files aren't changed like when I did B

All folders with new name I created when mass renaming aren't deleted. They are all empty

git log shows that the HEAD is on commit B. Do you know what happens?

*The PowerShell command I use is:

```<code>ls -recurse | Where-Object {$_.name -match '[\d.*]'} | Rename-Item -newnam { $_.Name -replace '\d(.*)', '4$1' }
</code>```

Body:
Starting from commit A, I did some changes on the files. Before a mass renaming*, I did commit B. After that I wanted to redo it again so I did git reset --hard. I expected it to be exactly what I got when I just committed B. The folders with old name are retrieved with their files, which is expected. But:

The files aren't changed like when I did B

All folders with new name I created when mass renaming aren't deleted. They are all empty

git log shows that the HEAD is on commit B. Do you know what happens?

*The PowerShell command I use is:

ls -recurse | Where-Object {$_.name -match '[\d.*]'} | Rename-Item -newnam { $_.Name -replace '\d(.*)', '4$1' }