问:
My dashboard disappear when i added the line and donut graph init?
I working on a custom website with mern stack I downloaded chart.js and react-chartjs-2 and import line,donut chart from it but when I enter into my code its disappear I don't know why

I simply just only add static data in line chart when i remove the component of  linechart my dashboard become shown/

Here is my dashboard code via save in Dashboard.js component

```<code>import React from 'react'
import Slider from './Slider.js'
import "./dashboard.css"
import { Typography } from '@mui/material'
import { Link } from 'react-router-dom'
import { Doughnut,Line } from 'react-chartjs-2'
const Dashboard = () => {

  const lineState = {
    labels: ["Initial Amount", "Amount Earned"],
    lineState: [
      {
        label: "TOTAL AMOUNT",
        backgroundColor: ["tomato"],
        hoverBackgroundColor: ["rgb(197, 72, 49)"],
        data: [0, 4000],
      },
    ],
  };
  return (
    <div className='dashboard'>
    <Slider/>
    <div className='dashboardContainer'>
      <Typography component="h1">Dashboard</Typography>
      <div className='dashboardSummary'>
        <div>
          <p>
            Total Amount <br/> rs2000
          </p>
        </div>
        <div className='dashboardSummaryBox2'>
            <Link to="/admin/products">
              <p>Product</p>
              <p>50</p>
            </Link>
            <Link to="/admin/products">
              <p>Orders</p>
              <p>80</p>
            </Link>
            <Link to="/admin/users">
              <p>Users</p>
              <p>2</p>
            </Link>
        </div>
      </div>

      <div className="lineChart">
          <Line data={lineState} /> when I added this its disappear note that if I remove data={linestate} its still diappearing
        </div>

    </div>
    </div>
  )
}

export default Dashboard
</code>```

Here is my App.js code

```<code>import './App.css';
import {useEffect,useState} from "react"
import Header from "./component/layout/Header/Header.js"
import Footer from "./component/layout/Footer/Footer.js"
import {BrowserRouter as Router,Route,  Routes} from "react-router-dom"
import webFont from "webfontloader"
import React from 'react';
import Home from './component/layout/Home/Home';

import ProductDetaileNew from './component/product/ProductDetaileNew';
import Search from './component/product/Search';
import TestProduct from './component/product/TestProduct';
import Products from './component/product/Products';
import LoginSignUp from './component/User/LoginSignUp';
import { createBrowserHistory } from 'history'
import store from './store'
import { loadUser } from './actions/userAction';
import UserOptions from './component/layout/Header/UserOptions'
import { useSelector } from 'react-redux';
import Profile from '../src/component/User/Profile'
import UpdatedProfile from '../src/component/User/UpdatedProfile'
//import ProtectedRoute from './component/Route/ProtectedRoute';
import UpdatePassword from '../src/component/User/UpdatePassword'
import ForgotPassword from '../src/component/User/ForgotPassword'
import ResetPassword from '../src/component/User/ResetPassword'
import Cart from './component/Cart/Cart'
import Shipping from "./component/Cart/Shipping.js"
import ConfirmOrder from "./component/Cart/ConfirmOrder"
import Payment from './component/Cart/Payment';
import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import axios from "axios";
import Good from './component/Cart/Good';
import OrderSuccess from './component/Cart/OrderSuccess';
import MyOrders from './component/orders/MyOrders';
import OrderDetails from './component/orders/OrderDetails';
import Dashboard from './component/admin/Dashboard.js';
import ProductList from './component/admin/ProductList'
function App() {

  const {isAuthenticated,user}=useSelector(state=>state.user)

  const [stripeApiKey, setStripeApiKey] = useState("");

  async function getStripeApiKey() {
    const { data } = await axios.get("/api/v1/stripeapikey");

    console.log(stripeApiKey);

    setStripeApiKey(data.stripeApiKey);
  }

  useEffect(()=>{
    webFont.load({
      google:{
        families:["Roboto","Droid Sans","chilanka"]
      }
    });
    store.dispatch(loadUser())
    getStripeApiKey();

  },[]);
  return (
   <Router>

    <Header/>
    {isAuthenticated && <UserOptions user={user} />}

    <Routes >
        <Route path='/' element={<Home/>}/>
        <Route path='/product/:id' element={<ProductDetaileNew/>}/>
        <Route path='/products/product/:id' element={<ProductDetaileNew/>}/>
        <Route path='/products' element={<Products/>}/>
        <Route path='/products/:keyword' element={<Products/>}/>
        <Route path='/search' element={<Search/>}/>
        <Route path='/login' element={<LoginSignUp/>}/>
       {/* <Route path='/account' element={<Profile/>}/>*/}
        {isAuthenticated && <Route path='/account' element={<Profile/>}/> }
        {isAuthenticated && <Route path='/me/update' element={<UpdatedProfile/>}/> }
        {isAuthenticated && <Route path='/password/update' element={<UpdatePassword/>}/> }
        {isAuthenticated && <Route path='/shipping' element={<Shipping/>}/> }
        {isAuthenticated && <Route path='/order/confirm' element={<ConfirmOrder/>}/> }
        {isAuthenticated && <Route path='/process/payment' element={<Good/>}/> }
        {isAuthenticated && <Route path='/success' element={<OrderSuccess/>}/> }
        {isAuthenticated && <Route path='/orders' element={<MyOrders/>}/> }
        {isAuthenticated && <Route path='/order/:id' element={<OrderDetails/>}/> }
        {isAuthenticated && user.role=="admin" && <Route path='/admin/dashboard' element={<Dashboard/>}/> }
        {isAuthenticated && user.role=="user" && <Route path='/admin/dashboard' element={<Profile/>}/> }
        {isAuthenticated && user.role=="admin" && <Route path='/admin/products' element={<ProductList/>}/> }
        <Route path='/password/forgot' element={<ForgotPassword/>}/>
        <Route path='/password/reset/:token' element={<ResetPassword/>}/>
        <Route path='/cart' element={<Cart/>}/>

        </Routes>

    <Footer/>
   </Router>
  );
}

export default App;
</code>```

Body:
I working on a custom website with mern stack I downloaded chart.js and react-chartjs-2 and import line,donut chart from it but when I enter into my code its disappear I don't know why

I simply just only add static data in line chart when i remove the component of  linechart my dashboard become shown/

Here is my dashboard code via save in Dashboard.js component

import React from 'react'
import Slider from './Slider.js'
import "./dashboard.css"
import { Typography } from '@mui/material'
import { Link } from 'react-router-dom'
import { Doughnut,Line } from 'react-chartjs-2'
const Dashboard = () => {

  const lineState = {
    labels: ["Initial Amount", "Amount Earned"],
    lineState: [
      {
        label: "TOTAL AMOUNT",
        backgroundColor: ["tomato"],
        hoverBackgroundColor: ["rgb(197, 72, 49)"],
        data: [0, 4000],
      },
    ],
  };
  return (

    <Slider/>

      <Typography component="h1">Dashboard</Typography>

            Total Amount
 rs2000

            <Link to="/admin/products">

Product

50

            </Link>
            <Link to="/admin/products">

Orders

80

            </Link>
            <Link to="/admin/users">

Users

2

            </Link>

          <Line data={lineState} /> when I added this its disappear note that if I remove data={linestate} its still diappearing

  )
}

export default Dashboard

Here is my App.js code

import './App.css';
import {useEffect,useState} from "react"
import Header from "./component/layout/Header/Header.js"
import Footer from "./component/layout/Footer/Footer.js"
import {BrowserRouter as Router,Route,  Routes} from "react-router-dom"
import webFont from "webfontloader"
import React from 'react';
import Home from './component/layout/Home/Home';

import ProductDetaileNew from './component/product/ProductDetaileNew';
import Search from './component/product/Search';
import TestProduct from './component/product/TestProduct';
import Products from './component/product/Products';
import LoginSignUp from './component/User/LoginSignUp';
import { createBrowserHistory } from 'history'
import store from './store'
import { loadUser } from './actions/userAction';
import UserOptions from './component/layout/Header/UserOptions'
import { useSelector } from 'react-redux';
import Profile from '../src/component/User/Profile'
import UpdatedProfile from '../src/component/User/UpdatedProfile'
//import ProtectedRoute from './component/Route/ProtectedRoute';
import UpdatePassword from '../src/component/User/UpdatePassword'
import ForgotPassword from '../src/component/User/ForgotPassword'
import ResetPassword from '../src/component/User/ResetPassword'
import Cart from './component/Cart/Cart'
import Shipping from "./component/Cart/Shipping.js"
import ConfirmOrder from "./component/Cart/ConfirmOrder"
import Payment from './component/Cart/Payment';
import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import axios from "axios";
import Good from './component/Cart/Good';
import OrderSuccess from './component/Cart/OrderSuccess';
import MyOrders from './component/orders/MyOrders';
import OrderDetails from './component/orders/OrderDetails';
import Dashboard from './component/admin/Dashboard.js';
import ProductList from './component/admin/ProductList'
function App() {

  const {isAuthenticated,user}=useSelector(state=>state.user)

  const [stripeApiKey, setStripeApiKey] = useState("");

  async function getStripeApiKey() {
    const { data } = await axios.get("/api/v1/stripeapikey");

    console.log(stripeApiKey);

    setStripeApiKey(data.stripeApiKey);
  }

  useEffect(()=>{
    webFont.load({
      google:{
        families:["Roboto","Droid Sans","chilanka"]
      }
    });
    store.dispatch(loadUser())
    getStripeApiKey();

  },[]);
  return (
   <Router>

    {isAuthenticated && <UserOptions user={user} />}

    <Routes >
        <Route path='/' element={<Home/>}/>
        <Route path='/product/:id' element={<ProductDetaileNew/>}/>
        <Route path='/products/product/:id' element={<ProductDetaileNew/>}/>
        <Route path='/products' element={<Products/>}/>
        <Route path='/products/:keyword' element={<Products/>}/>
        <Route path='/search' element={<Search/>}/>
        <Route path='/login' element={<LoginSignUp/>}/>
       {/* <Route path='/account' element={<Profile/>}/>*/}
        {isAuthenticated && <Route path='/account' element={<Profile/>}/> }
        {isAuthenticated && <Route path='/me/update' element={<UpdatedProfile/>}/> }
        {isAuthenticated && <Route path='/password/update' element={<UpdatePassword/>}/> }
        {isAuthenticated && <Route path='/shipping' element={<Shipping/>}/> }
        {isAuthenticated && <Route path='/order/confirm' element={<ConfirmOrder/>}/> }
        {isAuthenticated && <Route path='/process/payment' element={<Good/>}/> }
        {isAuthenticated && <Route path='/success' element={<OrderSuccess/>}/> }
        {isAuthenticated && <Route path='/orders' element={<MyOrders/>}/> }
        {isAuthenticated && <Route path='/order/:id' element={<OrderDetails/>}/> }
        {isAuthenticated && user.role=="admin" && <Route path='/admin/dashboard' element={<Dashboard/>}/> }
        {isAuthenticated && user.role=="user" && <Route path='/admin/dashboard' element={<Profile/>}/> }
        {isAuthenticated && user.role=="admin" && <Route path='/admin/products' element={<ProductList/>}/> }
        <Route path='/password/forgot' element={<ForgotPassword/>}/>
        <Route path='/password/reset/:token' element={<ResetPassword/>}/>
        <Route path='/cart' element={<Cart/>}/>

        </Routes>

   </Router>
  );
}

export default App;


来源: stackexchange

问:
Hexmap plot using Holoviews and Datashader
I would like to create a hex-map preferably using Holoviews and or Hvplot coupled with datashader from geospatial data.

Here are downsampled Latitude and Longitude pairs as csv: https://pastebin.com/U7pKMe4r

What I achieved so far:

```<code>import numpy as np
import pandas as pd
import os
import holoviews as hv
import hvplot.pandas
import geoviews as gv
from holoviews import opts
from holoviews.operation.datashader import datashade
hv.output(backend='bokeh')

# the dataframe (as csv from pastebin)
df.head()

|    |   sensor_id |     lat |     lon | city   |
|---:|------------:|--------:|--------:|:-------|
|  0 |       30527 | 42.7771 | 23.1471 |        |
|  1 |       64777 | 42.4855 | 23.4072 |        |
|  2 |       21671 | 52.242  |  8.168  |        |
|  3 |       11642 | 50.93   |  6.918  |        |
|  4 |       61391 | 52.892  |  5.738  |        |
</code>```

The plot looks like:

```<code>tiles = gv.HexTiles(df.loc[:, ['lon', 'lat']]).opts(gv.opts(alpha=0.2,
                                                            responsive=True))
points = gv.Points(df.loc[:, ['lon', 'lat']]).opts(gv.opts(alpha=0.2,
                                                           size=1,
                                                           color="black"))
plot_all = (gv.tile_sources.Wikipedia * tiles*points)
plot_all.opts(gv.opts(global_extent=True,
                             width=800,
                             height=475))
</code>```

The issues I face and do not know how to solve:

The hextiles do not scale with the zoom level. I could not find corresponding examples or any hints in the [docu] (https://holoviews.org/reference_manual/holoviews.element.html?highlight=hextiles#holoviews.element.HexTiles.sample) how this could be done dynamically (has to depend on zoom level)

I would like to define a custom function which does determine the scale of the hextiles to a reasonable size. E.g. I would like to be able to zoom up to e.g. city level.

Any hints are highly appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I would like to create a hex-map preferably using Holoviews and or Hvplot coupled with datashader from geospatial data.

Here are downsampled Latitude and Longitude pairs as csv: https://pastebin.com/U7pKMe4r

What I achieved so far:

import numpy as np
import pandas as pd
import os
import holoviews as hv
import hvplot.pandas
import geoviews as gv
from holoviews import opts
from holoviews.operation.datashader import datashade
hv.output(backend='bokeh')

# the dataframe (as csv from pastebin)
df.head()

|    |   sensor_id |     lat |     lon | city   |
|---:|------------:|--------:|--------:|:-------|
|  0 |       30527 | 42.7771 | 23.1471 |        |
|  1 |       64777 | 42.4855 | 23.4072 |        |
|  2 |       21671 | 52.242  |  8.168  |        |
|  3 |       11642 | 50.93   |  6.918  |        |
|  4 |       61391 | 52.892  |  5.738  |        |

The plot looks like:

tiles = gv.HexTiles(df.loc[:, ['lon', 'lat']]).opts(gv.opts(alpha=0.2,
                                                            responsive=True))
points = gv.Points(df.loc[:, ['lon', 'lat']]).opts(gv.opts(alpha=0.2,
                                                           size=1,
                                                           color="black"))
plot_all = (gv.tile_sources.Wikipedia * tiles*points)
plot_all.opts(gv.opts(global_extent=True,
                             width=800,
                             height=475))

The issues I face and do not know how to solve:

The hextiles do not scale with the zoom level. I could not find corresponding examples or any hints in the [docu] (https://holoviews.org/reference_manual/holoviews.element.html?highlight=hextiles#holoviews.element.HexTiles.sample) how this could be done dynamically (has to depend on zoom level)

I would like to define a custom function which does determine the scale of the hextiles to a reasonable size. E.g. I would like to be able to zoom up to e.g. city level.

Any hints are highly appreciated.


问:
How to right join table in typeorm OnetoMany and ManytoOne relation
I have two tables 1. patient 2. patientPayment and I have to fetch all patient where any patientPayment exist.

This is how schema looks -

Patient Entity

```<code>@Entity()
export class Patient extends EntityHelper {
  @PrimaryGeneratedColumn()
  id: number;

  @ApiProperty({ example: 'Patient Name' })
  @Column('text', { nullable: false })
  name: string;

  @OneToMany(() => PatientPayment, (patientPayment) => patientPayment.patient, {
    onDelete: 'CASCADE', // <---- HERE
    onUpdate: 'CASCADE',
  })
  patientPayment: PatientPayment[];
}
</code>```

PatientPayment Entity

```<code>@Entity()
export class PatientPayment extends EntityHelper {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(() => Patient, (patient) => patient.patientPayment, {
    onDelete: 'CASCADE', // <---- HERE
  })
  patient: Patient;

  @Column({ nullable: true })
  paymentIntent: string;
}
</code>```

I have tried these in query builder -

```<code>const result = await this.patientRepository
      .createQueryBuilder('patient')
      .leftJoinAndSelect('patient.patientPayment', 'patientPayment')
      // .where('patient.patientPayment =:patient', {
      //   patient: Not(IsNull()),
      // })
      .offset(offset)
      .limit(limit)
      .orderBy('patient.id', 'DESC')
      .getManyAndCount();
</code>```

The above query returns all patients but i only need where is any payment made. I don't know How to query these please help.

Body:
I have two tables 1. patient 2. patientPayment and I have to fetch all patient where any patientPayment exist.

This is how schema looks -

Patient Entity

@Entity()
export class Patient extends EntityHelper {
  @PrimaryGeneratedColumn()
  id: number;

  @ApiProperty({ example: 'Patient Name' })
  @Column('text', { nullable: false })
  name: string;

  @OneToMany(() => PatientPayment, (patientPayment) => patientPayment.patient, {
    onDelete: 'CASCADE', // <---- HERE
    onUpdate: 'CASCADE',
  })
  patientPayment: PatientPayment[];
}

PatientPayment Entity

@Entity()
export class PatientPayment extends EntityHelper {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(() => Patient, (patient) => patient.patientPayment, {
    onDelete: 'CASCADE', // <---- HERE
  })
  patient: Patient;

  @Column({ nullable: true })
  paymentIntent: string;
}

I have tried these in query builder -

const result = await this.patientRepository
      .createQueryBuilder('patient')
      .leftJoinAndSelect('patient.patientPayment', 'patientPayment')
      // .where('patient.patientPayment =:patient', {
      //   patient: Not(IsNull()),
      // })
      .offset(offset)
      .limit(limit)
      .orderBy('patient.id', 'DESC')
      .getManyAndCount();

The above query returns all patients but i only need where is any payment made. I don't know How to query these please help.


问:
ModuleNotFoundError: No module named 'fabric.client'
I am making a Degree verification app on fabric and I am running into this error "ModuleNotFoundError: No module named 'fabric.client'". I tried googling it but I could not find any solution. I have fabric installed and I installed "pip install fabric-sdk-py" and still no luck. please help.

```<code>from flask import Flask, request, jsonify
from jsonschema import validate
***from fabric.client import Client*** //This is the part that is causing me errors

# Import the Student class and the db object
from myapp import Student, db
</code>```

I have all the required installations done. But I can't seem to figure out why it is not working

Body:
I am making a Degree verification app on fabric and I am running into this error "ModuleNotFoundError: No module named 'fabric.client'". I tried googling it but I could not find any solution. I have fabric installed and I installed "pip install fabric-sdk-py" and still no luck. please help.

from flask import Flask, request, jsonify
from jsonschema import validate
***from fabric.client import Client*** //This is the part that is causing me errors

# Import the Student class and the db object
from myapp import Student, db

I have all the required installations done. But I can't seem to figure out why it is not working


问:
AWS SDK for javascript returning 'ReferenceError: debugId is not defined'
I'm trying get my AWS Credentials with the help of the AssumeRoleWithSAMLCommand from the AWS SDK for Javascript. I installed for that only the aws-sdk/client-sts with 'yard add @aws-sdk/client-sts'. STS is already configured on the AWS console for that. The code should normaly be fine, however I get the error message:

```<code>ReferenceError: debugId is not defined
    at resolveEndpoint (resolveEndpoint.js:7:1)
    at Object.defaultEndpointResolver [as endpointProvider] (endpointResolver.js:4:27)
    at getEndpointFromInstructions (getEndpointFromInstructions.js:8:1)
    at async endpointMiddleware.js:4:1
    at async loggerMiddleware.js:2:1
    at async AssumeRole (dqmain.a683294d4e4212de8108.hot-update.js:385:22)
</code>```

Here is my code:

```<code>export const stsClient = new STSClient({
  region: 'eu-west-1',
})

export const AssumeRole = async () => {
  const params = {
    PrincipalArn: SAMLobj.roles[0].principalArn,
    RoleArn: SAMLobj.roles[0].roleArn,
    SAMLAssertion: SAMLobj.document,
    DurationSeconds: 28800,
  }
  try {
    const response = await stsClient.send(new AssumeRoleWithSAMLCommand(params))

    return {
      accessKeyId: response.Credentials?.AccessKeyId,
      secretAccessKey: response.Credentials?.SecretAccessKey,
      sessionToken: response.Credentials?.SessionToken,
    }
  } catch (error) {
      console.log(error)
  }
}
</code>```

My other commands are working fine but this one has problems somehow.
I already tryed to reinstall the package but it doesn't help at all.

Body:
I'm trying get my AWS Credentials with the help of the AssumeRoleWithSAMLCommand from the AWS SDK for Javascript. I installed for that only the aws-sdk/client-sts with 'yard add @aws-sdk/client-sts'. STS is already configured on the AWS console for that. The code should normaly be fine, however I get the error message:

ReferenceError: debugId is not defined
    at resolveEndpoint (resolveEndpoint.js:7:1)
    at Object.defaultEndpointResolver [as endpointProvider] (endpointResolver.js:4:27)
    at getEndpointFromInstructions (getEndpointFromInstructions.js:8:1)
    at async endpointMiddleware.js:4:1
    at async loggerMiddleware.js:2:1
    at async AssumeRole (dqmain.a683294d4e4212de8108.hot-update.js:385:22)

Here is my code:

export const stsClient = new STSClient({
  region: 'eu-west-1',
})

export const AssumeRole = async () => {
  const params = {
    PrincipalArn: SAMLobj.roles[0].principalArn,
    RoleArn: SAMLobj.roles[0].roleArn,
    SAMLAssertion: SAMLobj.document,
    DurationSeconds: 28800,
  }
  try {
    const response = await stsClient.send(new AssumeRoleWithSAMLCommand(params))

    return {
      accessKeyId: response.Credentials?.AccessKeyId,
      secretAccessKey: response.Credentials?.SecretAccessKey,
      sessionToken: response.Credentials?.SessionToken,
    }
  } catch (error) {
      console.log(error)
  }
}

My other commands are working fine but this one has problems somehow.
I already tryed to reinstall the package but it doesn't help at all.


问:
Vertical images change to horizontal when converted to PDF Python Pillow
i want to print all picures in a folder into a PDF.
I take pictures with my phone and need to convert them into a PDF that i can send to other people.

Because the both Windows and Adobe Print to PDF mess up the cronological oder of the pictures

i wanted to create it on my own.

My problem is every time i try to convert a vertical image it get rotated to horizontal.

My first attempt was this.

```<code>import os
from PIL import Image

current_dir = os.getcwd()

pdf_filename = 'Auskundung.pdf'

pdf_path = os.path.join(current_dir, pdf_filename)

image_filenames = os.listdir(current_dir)

images = []

for filename in image_filenames:
    if filename.endswith('.jpg') or filename.endswith('.png'):
        image = Image.open(os.path.join(current_dir, filename))
        images.append(image)

images[0].save(pdf_path, "PDF" ,resolution=100.0, save_all=True, append_images=images[1:])

print("PDF erstellt!")
</code>```

Horizontal pictures convert as they should but vertical pictures get turned 90° to be horizonal.

I tried to get around this by turing the pictures before saving them.

```<code>import os
from PIL import Image

folder_path = os.getcwd()

for file in os.listdir(folder_path):
    if file.endswith(".png") or file.endswith(".jpg"):
        image = Image.open(os.path.join(folder_path, file))

        if image.width < image.height:
            image = image.rotate(270, expand=True)

        pdf_file = file.split('.')[0] + '.pdf'
        image.save(os.path.join(folder_path, pdf_file))
</code>```

This however did nothing.
As soon as i swap the < for a > thogh, it rotates all pictures horizontal and vertical ones leading me to belive the vertical pictures get autorotated to horizontal right after opening.

But i dont know how to combat this.

I just want all picutes in that Folder to get converted to a single PDF.

Pictues should be in chronological order, oldest first. (That already works becasue of the picutes being named by date i suppose)

Pictures need to keep their original orientation.

Body:
i want to print all picures in a folder into a PDF.
I take pictures with my phone and need to convert them into a PDF that i can send to other people.

Because the both Windows and Adobe Print to PDF mess up the cronological oder of the pictures

i wanted to create it on my own.

My problem is every time i try to convert a vertical image it get rotated to horizontal.

My first attempt was this.

import os
from PIL import Image

current_dir = os.getcwd()

pdf_filename = 'Auskundung.pdf'

pdf_path = os.path.join(current_dir, pdf_filename)

image_filenames = os.listdir(current_dir)

images = []

for filename in image_filenames:
    if filename.endswith('.jpg') or filename.endswith('.png'):
        image = Image.open(os.path.join(current_dir, filename))
        images.append(image)

images[0].save(pdf_path, "PDF" ,resolution=100.0, save_all=True, append_images=images[1:])

print("PDF erstellt!")

Horizontal pictures convert as they should but vertical pictures get turned 90° to be horizonal.

I tried to get around this by turing the pictures before saving them.

import os
from PIL import Image

folder_path = os.getcwd()

for file in os.listdir(folder_path):
    if file.endswith(".png") or file.endswith(".jpg"):
        image = Image.open(os.path.join(folder_path, file))

        if image.width < image.height:
            image = image.rotate(270, expand=True)

        pdf_file = file.split('.')[0] + '.pdf'
        image.save(os.path.join(folder_path, pdf_file))

This however did nothing.
As soon as i swap the < for a > thogh, it rotates all pictures horizontal and vertical ones leading me to belive the vertical pictures get autorotated to horizontal right after opening.

But i dont know how to combat this.

I just want all picutes in that Folder to get converted to a single PDF.

Pictues should be in chronological order, oldest first. (That already works becasue of the picutes being named by date i suppose)

Pictures need to keep their original orientation.


问:
How do I blit somthing off the edge of the screen and have it shown in pygame?
I just want to know if you can blit an image off the side of the window in pygame.

I can't find out how. :(


问:
Parallel processing in Node.js
I'm trying to write a node code that will read multiple json files from directory and insert mapped data into mongodb collection. In order to speed up the process, I have follwed following steps:

Put all filename inside Array.

Make Segment based on CPU length.

Create Worker thread read these file and store into MongoDB collection

Returning the combined result as a JSON result

Below Code Sample

readFiles.js

```<code>const {Worker} = require('worker_threads');
const os = require('os');
const cpuCount = os.cpus().length;
const path = require('path');
const workerPath = path.resolve('./worker.js');
const fileArray = ['D:/jsonFiles/abc_1310202220102022.json', 'D:/jsonFiles/def_1310202220102022.json', 'D:/jsonFiles/ghi_1310202220102022.json'];
let failureCount = 0;
let successCount = 0;
let failureMessage = [];
const splitRecords = (files, done) => {
  const segmentSize = Math.ceil(files.length/cpuCount);
  const segments = [];
  for (let segmentIndex=0; segmentIndex<cpuCount;segmentIndex++) {
    const start = segmentIndex * segmentSize; //0 * 60
    const end = start + segmentSize; // 0 + 60
    const segment = files.slice(start,end);
    segments.push(segment);
  }
  const finalSegments = [];
  segments.forEach((seg)=>{
    if(seg.length>0) {
      finalSegments.push(seg);
    }
  });
  done (finalSegments);
}

const createWorker = (records) => {
  return new Promise((resolve, reject) => {
    let workerData = {'records': records};
    const worker = new Worker(workerPath, {workerData});
    worker.on('message', function(data) {
      failureCount += data.failureCount;
      successCount += data.successCount;
      failureMessage.push(data.detailError);
      resolve({
            "failureCount":failureCount, "successCount":successCount,
            "failureMessage":failureMessage
        });
    });
    worker.on('error', function(dataErr) {
      resolve(dataErr)
    });
  })
}

(async () => {
    if (fileArray.length > 0) {
        let segmentArray = [];
        splitRecords(fileArray, (data) => {
            segmentArray = data;
        });
        if (segmentArray.length > 0) {
            segmentArray.forEach(async (list) => {
                createWorker(list);
            }
        }
    }
})();
</code>```

Worker.js

```<code>const mongoose = require('mongoose');
require('../config/mongoconfig')(mongoose);
const { workerData, isMainThread, parentPort } = require('worker_threads');
const axios = require('axios');
const Blog = require('../models/blogs');
let failureCount = 0;
let successCount = 0;
let detailsFailure = [];
var fs = require('fs');

const getFeatured = async function(imageURL) {
  return new Promise(async(resolve, reject) => {
    var url = cmsconfig.channelsUrl
    let options = {
      method: 'post',
      url: 'http://10.65.32.90:2045/v1/imageupload',
      headers: {},
      data: { imageUrl:imageURL}
    }
    await axios(options)
    .then(async function (response) {
      if (typeof response.data.url !== 'undefined') {
        resolve(response.data.url);
      } else {
        resolve();
      }
    })
    .catch(function (error) {
      resolve();
    })
  });
};
const mappingData = async (jsonPayload) => {
  return new Promise(async(resolve, reject) => {
      await Promise.all([jsonPayload["data"].forEach(async function (item) {
          let blogPayload = {};
          blogPayload["post_title"] = item.post_title;
          blogPayload["category"] = item.category;
          blogPayload["sub_category"] = item.sub_category;
          blogPayload["contents"] = item.contents;
          blogPayload["featured_image"] = await getFeatured(item.featured_image); // uploading file into AWS cloud and return url
          blogPayload["author"] = item.author;
          const newBlog = new Blog(blogPayload);
          await newBlog.save((idbErr) => {
              if (idbErr) {
                 failureCount += 1;
                 detailsFailure.push(idbErr);
              } else {
                 successCount += 1;
              }
          });
      })]);
  resolve({"successCount": successCount, "failureCount": failureCount, "detailError": detailsFailure});
  });
};
async () => {
  console.log("Worker started");
  if (!isMainThread ) {
    console.log("Inside not equal MainThread");
    const items = workerData.records;
    console.log("items length" + items.length);
    for (const dbData of items) {
      fs.readFile(dbData, async function(err, fileData) {
        if (err) throw err;
        let payload = JSON.parse(fileData.toString());
        let mappingResult = await mappingData(payload);
        parentPort.postMessage(mappingResult);
      });
    }
  } else {
    console.log("Outside MainThread");
  }
})();
</code>```

Problems:

When I run code CPU Utilization is two high

MongoDB connection is also two high.

Throwing multiple MongoDB connection issue

Title: Parallel processing in Node.js

Body:
I'm trying to write a node code that will read multiple json files from directory and insert mapped data into mongodb collection. In order to speed up the process, I have follwed following steps:

Put all filename inside Array.

Make Segment based on CPU length.

Create Worker thread read these file and store into MongoDB collection

Returning the combined result as a JSON result

Below Code Sample

readFiles.js

const {Worker} = require('worker_threads');
const os = require('os');
const cpuCount = os.cpus().length;
const path = require('path');
const workerPath = path.resolve('./worker.js');
const fileArray = ['D:/jsonFiles/abc_1310202220102022.json', 'D:/jsonFiles/def_1310202220102022.json', 'D:/jsonFiles/ghi_1310202220102022.json'];
let failureCount = 0;
let successCount = 0;
let failureMessage = [];
const splitRecords = (files, done) => {
  const segmentSize = Math.ceil(files.length/cpuCount);
  const segments = [];
  for (let segmentIndex=0; segmentIndex<cpuCount;segmentIndex++) {
    const start = segmentIndex * segmentSize; //0 * 60
    const end = start + segmentSize; // 0 + 60
    const segment = files.slice(start,end);
    segments.push(segment);
  }
  const finalSegments = [];
  segments.forEach((seg)=>{
    if(seg.length>0) {
      finalSegments.push(seg);
    }
  });
  done (finalSegments);
}

const createWorker = (records) => {
  return new Promise((resolve, reject) => {
    let workerData = {'records': records};
    const worker = new Worker(workerPath, {workerData});
    worker.on('message', function(data) {
      failureCount += data.failureCount;
      successCount += data.successCount;
      failureMessage.push(data.detailError);
      resolve({
            "failureCount":failureCount, "successCount":successCount,
            "failureMessage":failureMessage
        });
    });
    worker.on('error', function(dataErr) {
      resolve(dataErr)
    });
  })
}

(async () => {
    if (fileArray.length > 0) {
        let segmentArray = [];
        splitRecords(fileArray, (data) => {
            segmentArray = data;
        });
        if (segmentArray.length > 0) {
            segmentArray.forEach(async (list) => {
                createWorker(list);
            }
        }
    }
})();

Worker.js

const mongoose = require('mongoose');
require('../config/mongoconfig')(mongoose);
const { workerData, isMainThread, parentPort } = require('worker_threads');
const axios = require('axios');
const Blog = require('../models/blogs');
let failureCount = 0;
let successCount = 0;
let detailsFailure = [];
var fs = require('fs');

const getFeatured = async function(imageURL) {
  return new Promise(async(resolve, reject) => {
    var url = cmsconfig.channelsUrl
    let options = {
      method: 'post',
      url: 'http://10.65.32.90:2045/v1/imageupload',
      headers: {},
      data: { imageUrl:imageURL}
    }
    await axios(options)
    .then(async function (response) {
      if (typeof response.data.url !== 'undefined') {
        resolve(response.data.url);
      } else {
        resolve();
      }
    })
    .catch(function (error) {
      resolve();
    })
  });
};
const mappingData = async (jsonPayload) => {
  return new Promise(async(resolve, reject) => {
      await Promise.all([jsonPayload["data"].forEach(async function (item) {
          let blogPayload = {};
          blogPayload["post_title"] = item.post_title;
          blogPayload["category"] = item.category;
          blogPayload["sub_category"] = item.sub_category;
          blogPayload["contents"] = item.contents;
          blogPayload["featured_image"] = await getFeatured(item.featured_image); // uploading file into AWS cloud and return url
          blogPayload["author"] = item.author;
          const newBlog = new Blog(blogPayload);
          await newBlog.save((idbErr) => {
              if (idbErr) {
                 failureCount += 1;
                 detailsFailure.push(idbErr);
              } else {
                 successCount += 1;
              }
          });
      })]);
  resolve({"successCount": successCount, "failureCount": failureCount, "detailError": detailsFailure});
  });
};
async () => {
  console.log("Worker started");
  if (!isMainThread ) {
    console.log("Inside not equal MainThread");
    const items = workerData.records;
    console.log("items length" + items.length);
    for (const dbData of items) {
      fs.readFile(dbData, async function(err, fileData) {
        if (err) throw err;
        let payload = JSON.parse(fileData.toString());
        let mappingResult = await mappingData(payload);
        parentPort.postMessage(mappingResult);
      });
    }
  } else {
    console.log("Outside MainThread");
  }
})();

Problems:

When I run code CPU Utilization is two high

MongoDB connection is also two high.

Throwing multiple MongoDB connection issue


问:
Delay in loading console output
My Jenkins job has around 25000 lines of console output

If I open the job and choose the option as 'Show in Plain Text', complete output is displayed within seconds.

But, if I choose the option console output, it takes several around 10 mins to display the complete output.

Can someone explain, why does it take so much time for Jenkins to display the content in console output.

Title: Delay in loading console output


问:
How to make a carousel show adjacent images parts
I am trying to replicate a carousel from this website https://www.zarbees.com/our-story/ which is on the bottom portion of the page above its footer section.

The problem I am having is to:

Make adjacent images portion display on left and right when toggling next slide.

Live sandbox code https://235v3c.csb.app/

I have found some solutions and added to my code, here is what I made so far:

```<code><div class="container-fluid">
      <div class="row carousel slide container h-25 my-5 overflow-hidden" data-bs-ride="carousel" id="zb-carousel">
        <div class="col-12 text-center carousel-inner row justify-content-around">
          <!-- carousel items section -->
          <div class="col-lg-4 carousel-item active">
            <img alt="..." class="img-fluid d-block container px-1 rounded-4" src="https://marvel-b1-cdn.bc0a.com/f00000000271831/www.zarbees.com/static/458456bbccdf98784747d0e20576ee6b/5fd6b/OurStoryPage%24slides%24default%24image.jpg" />
            <span class="fw-bold"> 1 / 4</span>
          </div>

          <div class="col-lg-4 carousel-item"><img alt="..." class="img-fluid d-block container px-1 rounded-4" src="https://marvel-b1-cdn.bc0a.com/f00000000271831/www.zarbees.com/static/84471847ff79d9a6de0a9b2ca0cfcc16/5fd6b/OurStoryPage%24slides%249bbc3649-1bf1-4b24-a272-bc85a3be726a%24image.jpg" />
            <span class="fw-bold"> 2 / 4</span>
          </div>

          <div class="col-lg-4 carousel-item"><img alt="..." class="img-fluid d-block container px-1 rounded-4 fw-bold" src="https://marvel-b1-cdn.bc0a.com/f00000000271831/www.zarbees.com/static/fe4aa0b4fd24ab42e4ea7e741df8b790/5fd6b/OurStoryPage%24slides%24c9cd465b-44ce-4cc4-8117-32d19c585677%24image.jpg" />
            <span class="fw-bold"> 3 / 4</span>
          </div>

          <div class="col-lg-4 carousel-item"><img alt="..." class="img-fluid d-block container px-1 rounded-4 fw-bold" src="https://marvel-b1-cdn.bc0a.com/f00000000271831/www.zarbees.com/static/d6c20efa278252b4d8f7d6b8f9067b9d/bbe0c/OurStoryPage%24slides%2431406a19-a2e0-42c0-a54f-bbe0bd2c8c29%24image.jpg" />
            <span class="fw-bold"> 4 / 4</span>
          </div>

        </div>
        <!-- carousel control buttons | prev | next | -->
        <div class="d-flex flex-row-reverse">
          <button class="carousel-control-prev-icon bg-transparent border border-primary rounded-5 w-5 h-5 mx-2 position-relative end-0 ms-2" data-bs-slide="next" data-bs-target="#zb-carousel" type="button">
            <svg class="position-absolute top-50 start-50 translate-middle" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right" viewBox="0 0 16 16">
              <path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"/>
            </svg>
          </button>
          <button class="carousel-control-next-icon bg-transparent border border-primary rounded-5 w-5 h-5 mx-2 position-relative end-0 me-2" data-bs-slide="prev" data-bs-target="#zb-carousel" type="button">
            <svg class="position-absolute top-50 start-50 translate-middle" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right" viewBox="0 0 16 16">
              <path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/>
            </svg>
          </button>
        </div>
      </div>
    </div>

    <script type="module">

          const zbCarouselId = document.querySelector('#zb-carousel')
          const zbCarousel = new bootstrap.Carousel(zbCarouselId);
          const carouselSlides = document.querySelectorAll('.carousel.carousel-item');

          slides.forEach((el) => {
              // number of slides per carousel-item
              const minPerSlide = carouselSlides.length;
              let next = el.nextElementSibling;
              for (let i = 1; i < minPerSlide; i++) {
                  if (!next) {
                      // wrap carousel by using first child
                      next = carouselSlides[0];
                  }
                  let cloneChild = next.cloneNode(true);
                  el.appendChild(cloneChild.children[0]);
                  next = next.nextElementSibling;
              }
          })

        </script>

    <style>

          .carousel-inner:before {
              position:absolute;
              top:0;
              bottom: 0;
              right: 100%;
              left: 0;
              content:"";
              /* display:block; */
              background-color: #fff;
              z-index: 2;
          }
          .carousel-inner:after {
              position:absolute;
              top:0;
              bottom:0;
              right: 0;
              left: 100%;
              content:"";
              /* display:block; */
              background-color:#fff;
              z-index: 2;
          }
        </style>

</code>```

Body:
I am trying to replicate a carousel from this website https://www.zarbees.com/our-story/ which is on the bottom portion of the page above its footer section.

The problem I am having is to:

Make adjacent images portion display on left and right when toggling next slide.

Live sandbox code https://235v3c.csb.app/

I have found some solutions and added to my code, here is what I made so far:

             1 / 4

             2 / 4

             3 / 4

             4 / 4

          <button class="carousel-control-prev-icon bg-transparent border border-primary rounded-5 w-5 h-5 mx-2 position-relative end-0 ms-2" data-bs-slide="next" data-bs-target="#zb-carousel" type="button">
            <svg class="position-absolute top-50 start-50 translate-middle" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right" viewBox="0 0 16 16">
              <path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"/>
            </svg>
          </button>
          <button class="carousel-control-next-icon bg-transparent border border-primary rounded-5 w-5 h-5 mx-2 position-relative end-0 me-2" data-bs-slide="prev" data-bs-target="#zb-carousel" type="button">
            <svg class="position-absolute top-50 start-50 translate-middle" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right" viewBox="0 0 16 16">
              <path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/>
            </svg>
          </button>


问:
onBlur event props to component (typescript)
now, I am currently implementing duplicate validation.

I want to use useDebounce.ts, but I'm not familiar with the typescript type yet.

So I want to use the onBlur event to run the duplicate validation API as soon as the input is focused out.

Currently, I make input as a common component and use it as follows.

The function I want to deliver to onBlur as props is as follows.

However, passing the handleDoubleCheckID function to onBlur props does not work as follows

I want to know what's problem.


问:
Excel wrong macro locked sheet with password
After modifying the macro (one line) I run it, all looks good until I want to make some changes on sheet. When I try to unlock it the Excel demands a password which I did not set.

Line before:

```<code>Worksheets("ALL").Protect
</code>```

Line after:

```<code>Worksheets("ALL").Protect EnableAutoFilter = True, AllowSorting:=True
</code>```

What password was set?

Body:
After modifying the macro (one line) I run it, all looks good until I want to make some changes on sheet. When I try to unlock it the Excel demands a password which I did not set.

Line before:

Worksheets("ALL").Protect

Line after:

Worksheets("ALL").Protect EnableAutoFilter = True, AllowSorting:=True

What password was set?


问:
Asynchronous commands with tkinter, updating GUI after completion
I am trying to figure out what the best practice is to execute a parallel function with tkinter, that when completed, changes the GUI, without blocking the mainloop while running.

The specific case is the following, I am trying to check if a file exist, and if it does, do some checks on the content. Based on the result, I want to update the GUI to indicate the result of the check. But as the file is on a network location, it can take some time to complete the check, and I don't want to block the program while the check is performed.

I found an example at https://www.oreilly.com/library/view/python-cookbook/0596001673/ch09s07.html that I could probably make work for this purpose, but is this still a valid way of doing it, or are there better?

UPDATE: I updated the code based on the response from TheLizzard. Would this be a valid implementation? Seems to be working from what I can tell.

```<code>import threading
import tkinter as tk
import os
import time

class GUI:
    """Main GUI"""

    def __init__(self):
        """Start the GUI"""

        self.gui_root = tk.Tk()
        self.gui_root.minsize(300, 50)

        # Button to show test if GUI is responsive while checking for file
        self.button = tk.Button(self.gui_root, text="Button", command=lambda: print("text"))
        self.button.pack()

        self.label = tk.Label(self.gui_root, text="This is a label")
        self.label.pack()

        self.check_has_completed = False
        self.result = None

        new_check = threading.Thread(target=find_file, args=(self,))
        new_check.start()

        self.check_for_file()

    def check_for_file(self):
        """Check if the file exist"""
        if self.check_has_completed:
            print(f"Done with the check, result were: {self.result}")
            if self.result:
                self.label.configure(text="Found file and passed test")
            else:
                self.label.configure(text="Didn't find file, or test was not passed")
            return None
        self.gui_root.after(500, self.check_for_file)
        print(f"Response pending...")

def find_file(_gui: GUI):
    """Dummy function, check if a file exist, and if it does, do some work with it, and return result"""
    print("Check started")
    potential_path = os.path.join(os.getcwd(), "Test file.txt")
    time.sleep(5)  # Dummy to simulate processing time
    if os.path.isfile(potential_path):
        # Do some checks here, then return boolean if checks passed
        if True:
            _gui.result = True
            _gui.check_has_completed = True
            return True

    # Return false if file was found, or checks didn't pass
    _gui.result = False
    _gui.check_has_completed = True
    return False

if __name__ == '__main__':
    gui = GUI()
    gui.gui_root.mainloop()
</code>```

Body:
I am trying to figure out what the best practice is to execute a parallel function with tkinter, that when completed, changes the GUI, without blocking the mainloop while running.

The specific case is the following, I am trying to check if a file exist, and if it does, do some checks on the content. Based on the result, I want to update the GUI to indicate the result of the check. But as the file is on a network location, it can take some time to complete the check, and I don't want to block the program while the check is performed.

I found an example at https://www.oreilly.com/library/view/python-cookbook/0596001673/ch09s07.html that I could probably make work for this purpose, but is this still a valid way of doing it, or are there better?

UPDATE: I updated the code based on the response from TheLizzard. Would this be a valid implementation? Seems to be working from what I can tell.

import threading
import tkinter as tk
import os
import time

class GUI:
    """Main GUI"""

    def __init__(self):
        """Start the GUI"""

        self.gui_root = tk.Tk()
        self.gui_root.minsize(300, 50)

        # Button to show test if GUI is responsive while checking for file
        self.button = tk.Button(self.gui_root, text="Button", command=lambda: print("text"))
        self.button.pack()

        self.label = tk.Label(self.gui_root, text="This is a label")
        self.label.pack()

        self.check_has_completed = False
        self.result = None

        new_check = threading.Thread(target=find_file, args=(self,))
        new_check.start()

        self.check_for_file()

    def check_for_file(self):
        """Check if the file exist"""
        if self.check_has_completed:
            print(f"Done with the check, result were: {self.result}")
            if self.result:
                self.label.configure(text="Found file and passed test")
            else:
                self.label.configure(text="Didn't find file, or test was not passed")
            return None
        self.gui_root.after(500, self.check_for_file)
        print(f"Response pending...")

def find_file(_gui: GUI):
    """Dummy function, check if a file exist, and if it does, do some work with it, and return result"""
    print("Check started")
    potential_path = os.path.join(os.getcwd(), "Test file.txt")
    time.sleep(5)  # Dummy to simulate processing time
    if os.path.isfile(potential_path):
        # Do some checks here, then return boolean if checks passed
        if True:
            _gui.result = True
            _gui.check_has_completed = True
            return True

    # Return false if file was found, or checks didn't pass
    _gui.result = False
    _gui.check_has_completed = True
    return False

if __name__ == '__main__':
    gui = GUI()
    gui.gui_root.mainloop()


问:
./Scripts/PodsLicenseCheck.sh: line 8: /usr/local/opt/ruby/bin/ad_licenselint: No such file or directory
Application build successfully but if application run then this error

produce ./Scripts/PodsLicenseCheck.sh: line 8:
/usr/local/opt/ruby/bin/ad_licenselint: No such file or directory

I tried pod reinstalled , and apply these commands ,

```<code>sudo gem install -n /usr/local/bin ruby,
sudo gem install -n /usr/local/bin cocoapods,
</code>```

But not resolved error

Body:
Application build successfully but if application run then this error

produce ./Scripts/PodsLicenseCheck.sh: line 8:
/usr/local/opt/ruby/bin/ad_licenselint: No such file or directory

I tried pod reinstalled , and apply these commands ,

sudo gem install -n /usr/local/bin ruby,
sudo gem install -n /usr/local/bin cocoapods,

But not resolved error


问:
React Material UI Select Dropdown

While clicking on the dropdown it opens above the dropdown it should be down but I cannot fix the style.

Please help me on that

```<code>import * as React from 'react';
import Box from '@mui/material/Box';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select, {SelectChangeEvent} from '@mui/material/Select';

export default function DropDownSelect({data}: any) {
  const [age, setAge] = React.useState('');

  const handleChange = (event: SelectChangeEvent) => {
    setAge(event.target.value);
  };

  return (
    <Box sx={{Width: 30}}>
      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">Select</InputLabel>
        <Select
          sx={{
            width: '100%',
            height: 50,
            borderColor: 'red',
          }}
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="age"
          onChange={handleChange}>
          {data.map((option: any) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </Box>
  );
}
</code>```

Help me with style part not able to fix the design issue

Title: React Material UI Select Dropdown

Body:
While clicking on the dropdown it opens above the dropdown it should be down but I cannot fix the style.

Please help me on that

import * as React from 'react';
import Box from '@mui/material/Box';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select, {SelectChangeEvent} from '@mui/material/Select';

export default function DropDownSelect({data}: any) {
  const [age, setAge] = React.useState('');

  const handleChange = (event: SelectChangeEvent) => {
    setAge(event.target.value);
  };

  return (
    <Box sx={{Width: 30}}>
      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">Select</InputLabel>
        <Select
          sx={{
            width: '100%',
            height: 50,
            borderColor: 'red',
          }}
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="age"
          onChange={handleChange}>
          {data.map((option: any) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </Box>
  );
}

Help me with style part not able to fix the design issue


问:
addEventListener on modal event not working in pure javascript
I'm trying to refactor js script without using jquery. And the most difficult part, to me, is to understand why addEventListener is not equivalent to $().on(). I need to add some listeners to a modal which is loaded after the DOM is built. So I did:

```<code>document.addEventListener("DOMContentLoaded", function(){

    document.getElementById('form-modal').addEventListener('show.bs.modal', function () {
       // Here the js logic relevant to the modal
       console.log('loaded by pure js')
    })

    $('#form-modal').on('show.bs.modal', function () {
        console.log('with help of jquery');
    })

});
</code>```

Why the pure javascript doesn't work while the jquery does? What am I missin?

Body:
I'm trying to refactor js script without using jquery. And the most difficult part, to me, is to understand why addEventListener is not equivalent to $().on(). I need to add some listeners to a modal which is loaded after the DOM is built. So I did:

document.addEventListener("DOMContentLoaded", function(){

    document.getElementById('form-modal').addEventListener('show.bs.modal', function () {
       // Here the js logic relevant to the modal
       console.log('loaded by pure js')
    })

    $('#form-modal').on('show.bs.modal', function () {
        console.log('with help of jquery');
    })

});

Why the pure javascript doesn't work while the jquery does? What am I missin?


问:
Linux complier can not link my two cpp files
I have 4 files node.hpp, node.cpp, linked_list.hpp and linked_list.cpp. There codes are respectively below.

```<code>#ifndef NODE
#define NODE

template <typename T>
struct Node {
    T        data;
    Node<T>* next;

    Node(const T& data);
    Node(const T& data, const Node<T>* next);
};

#endif  // NODE

</code>```
```<code>#include "node.hpp"

template <typename T>
Node<T>::Node(const T& data) : data(data), next(nullptr) {}

template <typename T>
Node<T>::Node(const T& data, const Node<T>* next) : data(data), next(next) {}
</code>```
```<code>#ifndef LINKED_LIST
#define LINKED_LIST

#include <cstddef>

#include "node.hpp"

template <typename T>
class LinkedList {
public:

    LinkedList();
    LinkedList(const T& data);
    LinkedList(const LinkedList& other);

    ~LinkedList();

    void push_front(const T& data);
    void push_back(const T& data);
    void pop_front();
    void pop_back();

    T front() const;
    T back() const;

    T    get(const int& index) const;
    void set(const int& index, const T& data);

    void insert(const size_t& index, const T& data);
    void remove(const size_t& index);
    int  getSize() const;

    bool isEmpty() const;
    void clear();

    void print() const;

    LinkedList& operator=(const LinkedList& other);
    bool        operator==(const LinkedList& other) const;
    bool        operator!=(const LinkedList& other) const;
    T           operator[](const size_t& index) const;
    T&          operator[](const size_t& index);

private:

    Node<T>* head;
    size_t   size = 0;
};

#endif  // LINKED_LIST

</code>```
```<code>#include "linked_list.hpp"

#include <iostream>

template <typename T>
LinkedList<T>::LinkedList() : head(nullptr), size(0) {}

template <typename T>
LinkedList<T>::LinkedList(const T& data) : head(new Node<T>(data)), size(1) {}

template <typename T>
LinkedList<T>::LinkedList(const LinkedList& other) {
    this->head = nullptr;
    this->size = 0;

    Node<T>* current = other.head;
    while (current != nullptr) {
        this->push_back(current->data);
        current = current->next;
        size++;
    }
}

template <typename T>
LinkedList<T>::~LinkedList() {
    this->clear();
}

template <typename T>
LinkedList<T>& LinkedList<T>::operator=(const LinkedList& other) {
    if (this == &other) return *this;

    this->clear();

    Node<T>* current = other.head;
    while (current != nullptr) {
        this->push_back(current->data);
        current = current->next;
    }

    return *this;
}

template <typename T>
bool LinkedList<T>::operator==(const LinkedList& other) const {
    if (size != other.size) return false;

    Node<T>* current1 = head;
    Node<T>* current2 = other.head;
    while (current1 != nullptr) {
        if (current1->data != current2->data) return false;
        current1 = current1->next;
        current2 = current2->next;
    }
    return true;
}

template <typename T>
bool LinkedList<T>::operator!=(const LinkedList& other) const {
    return !(*this == other);
}

template <typename T>
void LinkedList<T>::push_front(const T& data) {
    Node<T>* newNode = new Node<T>(data);
    newNode->next    = head;
    head             = newNode;
    ++size;
}

template <typename T>
void LinkedList<T>::push_back(const T& data) {
    if (head == nullptr)
        head = new Node<T>(data);
    else {
        Node<T>* current = head;
        while (current->next != nullptr) current = current->next;
        current->next = new Node<T>(data);
    }
    ++size;
}

template <typename T>
void LinkedList<T>::pop_front() {
    if (head == nullptr) return;

    Node<T>* temp = head;
    head          = head->next;
    delete temp;
    --size;
}

template <typename T>
void LinkedList<T>::pop_back() {
    if (this->head == nullptr) return;

    if (this->head->next == nullptr) {
        delete this->head;
        this->head = nullptr;
    } else {
        Node<T>* current = this->head;
        while (current->next->next != nullptr) current = current->next;
        delete current->next;
        current->next = nullptr;
    }
    --size;
}

template <typename T>
T LinkedList<T>::front() const {
    return this->head->data;
}

template <typename T>
T LinkedList<T>::back() const {
    Node<T>* current = this->head;
    while (current->next != nullptr) current = current->next;
    return current->data;
}

template <typename T>
T LinkedList<T>::get(const int& index) const {
    if (index < 0 || index >= size) return T();
    Node<T>* current = this->head;
    for (int i = 0; i < index; ++i) current = current->next;
    return current->data;
}

template <typename T>
void LinkedList<T>::set(const int& index, const T& data) {
    if (index < 0 || index >= size) return;
    Node<T>* current = this->head;
    for (int i = 0; i < index; ++i) current = current->next;
    current->data = data;
}

template <typename T>
void LinkedList<T>::insert(const size_t& index, const T& data) {
    if (index < 0 || index > size) return;

    if (index == 0)
        push_front(data);
    else {
        Node<T>* current = this->head;

        for (size_t i = 0; i < index - 1; ++i) current = current->next;

        Node<T>* newNode = new Node<T>(data);
        newNode->next    = current->next;
        current->next    = newNode;
        ++size;
    }
}

template <typename T>
void LinkedList<T>::remove(const size_t& index) {
    if (index < 0 || index >= size) return;

    if (index == 0)
        pop_front();
    else {
        Node<T>* current = this->head;
        for (size_t i = 0; i + 1 < index; ++i) current = current->next;

        Node<T>* temp = current->next;
        current->next = current->next->next;
        delete temp;
        --size;
    }
}

template <typename T>
int LinkedList<T>::getSize() const {
    return size;
}

template <typename T>
bool LinkedList<T>::isEmpty() const {
    return size == 0;
}

template <typename T>
void LinkedList<T>::clear() {
    while (this->head != nullptr) pop_front();
}

template <typename T>
void LinkedList<T>::print() const {
    Node<T>* current = this->head;
    while (current != nullptr) {
        std::cout << current->data << " ";
        current = current->next;
    }
    std::cout << std::endl;
}

template <typename T>
T LinkedList<T>::operator[](const size_t& index) const {
    return get(index);
}

template <typename T>
T& LinkedList<T>::operator[](const size_t& index) {
    if (index < 0 || index >= size) return T();

    Node<T>* current = this->head;
    for (int i = 0; i < index; ++i) current = current->next;

    return current->data;
}

int main() {
    LinkedList<int> list;
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    list.push_back(4);

    list.print();

    list.remove(2);

    list.print();

    return 0;
}
</code>```

makefile is,

```<code>linked_list:
    g++ linked_list.cpp node.cpp -Wall -o linked_list
    ./linked_list
    rm ./linked_list
</code>```

The compiler gives following errors,

```<code>make linked_list
g++ linked_list.cpp node.cpp -Wall -o linked_list
/usr/bin/ld: /tmp/ccV1cNdz.o: in function `LinkedList<int>::push_back(int const&)':
/media/meesumaliqazalbash/Personal/Data-Structures/cpp/linked_list.cpp:74: undefined reference to `Node<int>::Node(int const&)'
/usr/bin/ld: /media/meesumaliqazalbash/Personal/Data-Structures/cpp/linked_list.cpp:78: undefined reference to `Node<int>::Node(int const&)'
collect2: error: ld returned 1 exit status
make: *** [makefile:17: linked_list] Error 1
</code>```

I have tried altering the command and there is no success.

```<code>linked_list:
    g++ -c node.cpp -Wall -o node.o
    g++ -c linked_list.cpp -Wall -o linked_list.o
    g++ node.o linked_list.o -Wall -O -o linked_list -g
    ./linked_list
    rm ./linked_list
</code>```

Error

```<code>make linked_list
g++ -c node.cpp -Wall -o node.o
g++ -c linked_list.cpp -Wall -o linked_list.o
g++ node.o linked_list.o -Wall -O -o linked_list -g
/usr/bin/ld: linked_list.o: in function `LinkedList<int>::push_back(int const&)':
linked_list.cpp:(.text._ZN10LinkedListIiE9push_backERKi[_ZN10LinkedListIiE9push_backERKi]+0x3b): undefined reference to `Node<int>::Node(int const&)'
/usr/bin/ld: linked_list.cpp:(.text._ZN10LinkedListIiE9push_backERKi[_ZN10LinkedListIiE9push_backERKi]+0x86): undefined reference to `Node<int>::Node(int const&)'
collect2: error: ld returned 1 exit status
make: *** [makefile:19: linked_list] Error 1
</code>```

I made a raytracer a month ago and there I was linking multiple files and it shows no problem. I guess there maybe some issue with my VSCode settings.

This is task.json.

```<code>{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": ["$gcc"],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}
</code>```

This is settings.json.

```<code>{
    "files.associations": {
        "array": "cpp",
        "atomic": "cpp",
        "bit": "cpp",
        "*.tcc": "cpp",
        "compare": "cpp",
        "list": "cpp",
        "string": "cpp",
        "unordered_map": "cpp",
        "vector": "cpp",
        "algorithm": "cpp",
        "chrono": "cpp",
        "functional": "cpp",
        "memory": "cpp",
        "memory_resource": "cpp",
        "optional": "cpp",
        "random": "cpp",
        "ratio": "cpp",
        "system_error": "cpp",
        "tuple": "cpp",
        "type_traits": "cpp",
        "cmath": "cpp",
        "fstream": "cpp",
        "future": "cpp",
        "iomanip": "cpp",
        "istream": "cpp",
        "limits": "cpp",
        "numeric": "cpp",
        "ostream": "cpp",
        "sstream": "cpp",
        "stdexcept": "cpp",
        "stop_token": "cpp",
        "streambuf": "cpp",
        "string_view": "cpp",
        "thread": "cpp",
        "utility": "cpp",
        "typeinfo": "cpp",
        "valarray": "cpp",
        "variant": "cpp",
        "*.inc": "cpp",
        "iostream": "cpp",
        "bitset": "cpp",
        "cctype": "cpp",
        "clocale": "cpp",
        "codecvt": "cpp",
        "concepts": "cpp",
        "condition_variable": "cpp",
        "cstdarg": "cpp",
        "cstddef": "cpp",
        "cstdint": "cpp",
        "cstdio": "cpp",
        "cstdlib": "cpp",
        "cstring": "cpp",
        "ctime": "cpp",
        "cwchar": "cpp",
        "cwctype": "cpp",
        "deque": "cpp",
        "map": "cpp",
        "set": "cpp",
        "unordered_set": "cpp",
        "exception": "cpp",
        "iterator": "cpp",
        "source_location": "cpp",
        "initializer_list": "cpp",
        "iosfwd": "cpp",
        "mutex": "cpp",
        "new": "cpp",
        "numbers": "cpp",
        "semaphore": "cpp",
        "cinttypes": "cpp"
    }
}
</code>```

Body:
I have 4 files node.hpp, node.cpp, linked_list.hpp and linked_list.cpp. There codes are respectively below.

#ifndef NODE
#define NODE

template <typename T>
struct Node {
    T        data;
    Node<T>* next;

    Node(const T& data);
    Node(const T& data, const Node<T>* next);
};

#endif  // NODE

#include "node.hpp"

template <typename T>
Node<T>::Node(const T& data) : data(data), next(nullptr) {}

template <typename T>
Node<T>::Node(const T& data, const Node<T>* next) : data(data), next(next) {}

#ifndef LINKED_LIST
#define LINKED_LIST

#include <cstddef>

#include "node.hpp"

template <typename T>
class LinkedList {
public:

    LinkedList();
    LinkedList(const T& data);
    LinkedList(const LinkedList& other);

    ~LinkedList();

    void push_front(const T& data);
    void push_back(const T& data);
    void pop_front();
    void pop_back();

    T front() const;
    T back() const;

    T    get(const int& index) const;
    void set(const int& index, const T& data);

    void insert(const size_t& index, const T& data);
    void remove(const size_t& index);
    int  getSize() const;

    bool isEmpty() const;
    void clear();

    void print() const;

    LinkedList& operator=(const LinkedList& other);
    bool        operator==(const LinkedList& other) const;
    bool        operator!=(const LinkedList& other) const;
    T           operator[](const size_t& index) const;
    T&          operator[](const size_t& index);

private:

    Node<T>* head;
    size_t   size = 0;
};

#endif  // LINKED_LIST

#include "linked_list.hpp"

#include <iostream>

template <typename T>
LinkedList<T>::LinkedList() : head(nullptr), size(0) {}

template <typename T>
LinkedList<T>::LinkedList(const T& data) : head(new Node<T>(data)), size(1) {}

template <typename T>
LinkedList<T>::LinkedList(const LinkedList& other) {
    this->head = nullptr;
    this->size = 0;

    Node<T>* current = other.head;
    while (current != nullptr) {
        this->push_back(current->data);
        current = current->next;
        size++;
    }
}

template <typename T>
LinkedList<T>::~LinkedList() {
    this->clear();
}

template <typename T>
LinkedList<T>& LinkedList<T>::operator=(const LinkedList& other) {
    if (this == &other) return *this;

    this->clear();

    Node<T>* current = other.head;
    while (current != nullptr) {
        this->push_back(current->data);
        current = current->next;
    }

    return *this;
}

template <typename T>
bool LinkedList<T>::operator==(const LinkedList& other) const {
    if (size != other.size) return false;

    Node<T>* current1 = head;
    Node<T>* current2 = other.head;
    while (current1 != nullptr) {
        if (current1->data != current2->data) return false;
        current1 = current1->next;
        current2 = current2->next;
    }
    return true;
}

template <typename T>
bool LinkedList<T>::operator!=(const LinkedList& other) const {
    return !(*this == other);
}

template <typename T>
void LinkedList<T>::push_front(const T& data) {
    Node<T>* newNode = new Node<T>(data);
    newNode->next    = head;
    head             = newNode;
    ++size;
}

template <typename T>
void LinkedList<T>::push_back(const T& data) {
    if (head == nullptr)
        head = new Node<T>(data);
    else {
        Node<T>* current = head;
        while (current->next != nullptr) current = current->next;
        current->next = new Node<T>(data);
    }
    ++size;
}

template <typename T>
void LinkedList<T>::pop_front() {
    if (head == nullptr) return;

    Node<T>* temp = head;
    head          = head->next;
    delete temp;
    --size;
}

template <typename T>
void LinkedList<T>::pop_back() {
    if (this->head == nullptr) return;

    if (this->head->next == nullptr) {
        delete this->head;
        this->head = nullptr;
    } else {
        Node<T>* current = this->head;
        while (current->next->next != nullptr) current = current->next;
        delete current->next;
        current->next = nullptr;
    }
    --size;
}

template <typename T>
T LinkedList<T>::front() const {
    return this->head->data;
}

template <typename T>
T LinkedList<T>::back() const {
    Node<T>* current = this->head;
    while (current->next != nullptr) current = current->next;
    return current->data;
}

template <typename T>
T LinkedList<T>::get(const int& index) const {
    if (index < 0 || index >= size) return T();
    Node<T>* current = this->head;
    for (int i = 0; i < index; ++i) current = current->next;
    return current->data;
}

template <typename T>
void LinkedList<T>::set(const int& index, const T& data) {
    if (index < 0 || index >= size) return;
    Node<T>* current = this->head;
    for (int i = 0; i < index; ++i) current = current->next;
    current->data = data;
}

template <typename T>
void LinkedList<T>::insert(const size_t& index, const T& data) {
    if (index < 0 || index > size) return;

    if (index == 0)
        push_front(data);
    else {
        Node<T>* current = this->head;

        for (size_t i = 0; i < index - 1; ++i) current = current->next;

        Node<T>* newNode = new Node<T>(data);
        newNode->next    = current->next;
        current->next    = newNode;
        ++size;
    }
}

template <typename T>
void LinkedList<T>::remove(const size_t& index) {
    if (index < 0 || index >= size) return;

    if (index == 0)
        pop_front();
    else {
        Node<T>* current = this->head;
        for (size_t i = 0; i + 1 < index; ++i) current = current->next;

        Node<T>* temp = current->next;
        current->next = current->next->next;
        delete temp;
        --size;
    }
}

template <typename T>
int LinkedList<T>::getSize() const {
    return size;
}

template <typename T>
bool LinkedList<T>::isEmpty() const {
    return size == 0;
}

template <typename T>
void LinkedList<T>::clear() {
    while (this->head != nullptr) pop_front();
}

template <typename T>
void LinkedList<T>::print() const {
    Node<T>* current = this->head;
    while (current != nullptr) {
        std::cout << current->data << " ";
        current = current->next;
    }
    std::cout << std::endl;
}

template <typename T>
T LinkedList<T>::operator[](const size_t& index) const {
    return get(index);
}

template <typename T>
T& LinkedList<T>::operator[](const size_t& index) {
    if (index < 0 || index >= size) return T();

    Node<T>* current = this->head;
    for (int i = 0; i < index; ++i) current = current->next;

    return current->data;
}

int main() {
    LinkedList<int> list;
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    list.push_back(4);

    list.print();

    list.remove(2);

    list.print();

    return 0;
}

makefile is,

linked_list:
    g++ linked_list.cpp node.cpp -Wall -o linked_list
    ./linked_list
    rm ./linked_list

The compiler gives following errors,

make linked_list
g++ linked_list.cpp node.cpp -Wall -o linked_list
/usr/bin/ld: /tmp/ccV1cNdz.o: in function `LinkedList<int>::push_back(int const&)':
/media/meesumaliqazalbash/Personal/Data-Structures/cpp/linked_list.cpp:74: undefined reference to `Node<int>::Node(int const&)'
/usr/bin/ld: /media/meesumaliqazalbash/Personal/Data-Structures/cpp/linked_list.cpp:78: undefined reference to `Node<int>::Node(int const&)'
collect2: error: ld returned 1 exit status
make: *** [makefile:17: linked_list] Error 1

I have tried altering the command and there is no success.

linked_list:
    g++ -c node.cpp -Wall -o node.o
    g++ -c linked_list.cpp -Wall -o linked_list.o
    g++ node.o linked_list.o -Wall -O -o linked_list -g
    ./linked_list
    rm ./linked_list

Error

make linked_list
g++ -c node.cpp -Wall -o node.o
g++ -c linked_list.cpp -Wall -o linked_list.o
g++ node.o linked_list.o -Wall -O -o linked_list -g
/usr/bin/ld: linked_list.o: in function `LinkedList<int>::push_back(int const&)':
linked_list.cpp:(.text._ZN10LinkedListIiE9push_backERKi[_ZN10LinkedListIiE9push_backERKi]+0x3b): undefined reference to `Node<int>::Node(int const&)'
/usr/bin/ld: linked_list.cpp:(.text._ZN10LinkedListIiE9push_backERKi[_ZN10LinkedListIiE9push_backERKi]+0x86): undefined reference to `Node<int>::Node(int const&)'
collect2: error: ld returned 1 exit status
make: *** [makefile:19: linked_list] Error 1

I made a raytracer a month ago and there I was linking multiple files and it shows no problem. I guess there maybe some issue with my VSCode settings.

This is task.json.

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": ["$gcc"],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

This is settings.json.

{
    "files.associations": {
        "array": "cpp",
        "atomic": "cpp",
        "bit": "cpp",
        "*.tcc": "cpp",
        "compare": "cpp",
        "list": "cpp",
        "string": "cpp",
        "unordered_map": "cpp",
        "vector": "cpp",
        "algorithm": "cpp",
        "chrono": "cpp",
        "functional": "cpp",
        "memory": "cpp",
        "memory_resource": "cpp",
        "optional": "cpp",
        "random": "cpp",
        "ratio": "cpp",
        "system_error": "cpp",
        "tuple": "cpp",
        "type_traits": "cpp",
        "cmath": "cpp",
        "fstream": "cpp",
        "future": "cpp",
        "iomanip": "cpp",
        "istream": "cpp",
        "limits": "cpp",
        "numeric": "cpp",
        "ostream": "cpp",
        "sstream": "cpp",
        "stdexcept": "cpp",
        "stop_token": "cpp",
        "streambuf": "cpp",
        "string_view": "cpp",
        "thread": "cpp",
        "utility": "cpp",
        "typeinfo": "cpp",
        "valarray": "cpp",
        "variant": "cpp",
        "*.inc": "cpp",
        "iostream": "cpp",
        "bitset": "cpp",
        "cctype": "cpp",
        "clocale": "cpp",
        "codecvt": "cpp",
        "concepts": "cpp",
        "condition_variable": "cpp",
        "cstdarg": "cpp",
        "cstddef": "cpp",
        "cstdint": "cpp",
        "cstdio": "cpp",
        "cstdlib": "cpp",
        "cstring": "cpp",
        "ctime": "cpp",
        "cwchar": "cpp",
        "cwctype": "cpp",
        "deque": "cpp",
        "map": "cpp",
        "set": "cpp",
        "unordered_set": "cpp",
        "exception": "cpp",
        "iterator": "cpp",
        "source_location": "cpp",
        "initializer_list": "cpp",
        "iosfwd": "cpp",
        "mutex": "cpp",
        "new": "cpp",
        "numbers": "cpp",
        "semaphore": "cpp",
        "cinttypes": "cpp"
    }
}


问:
How to modify RedisClusterRequestTTL to an RedisCluster instance in redis-py-cluster

class RedisCluster(Redis):
"""
If a command is implemented over the one in Redis then it requires some changes compared to
the regular implementation of the method.
"""
RedisClusterRequestTTL = 16
```
<p>RedisClusterRequestTTL is a constant which control the num of retry time.</p>
<pre class="lang-py prettyprint-override"><code>
ttl = int(self.RedisClusterRequestTTL)
connection_error_retry_counter = 0
while ttl > 0:
    ttl -= 1
    connection = None
    try:
        if asking:
            node = self.connection_pool.nodes.nodes[redirect_addr]
            connection = self.connection_pool.get_connection_by_node(node)
        elif try_random_node:
            connection = self.connection_pool.get_random_connection()
            try_random_node = False
</code>```

I'd like to know that if there was a possible way that we can modify this to reducing the retry time to avoid too-much-retry on race-condition？

```<code>redis-py-cluster==2.1.0
</code>```

i noticed that cluster_down_retry_attempts is a possible way which outside the while loop which could control retry times. Im look forward to change RedisClusterRequestTTL in someway (16 is too much)

Body:
class RedisCluster(Redis):
"""
If a command is implemented over the one in Redis then it requires some changes compared to
the regular implementation of the method.
"""
RedisClusterRequestTTL = 16

RedisClusterRequestTTL is a constant which control the num of retry time.

ttl = int(self.RedisClusterRequestTTL)
connection_error_retry_counter = 0
while ttl > 0:
    ttl -= 1
    connection = None
    try:
        if asking:
            node = self.connection_pool.nodes.nodes[redirect_addr]
            connection = self.connection_pool.get_connection_by_node(node)
        elif try_random_node:
            connection = self.connection_pool.get_random_connection()
            try_random_node = False

I'd like to know that if there was a possible way that we can modify this to reducing the retry time to avoid too-much-retry on race-condition？

redis-py-cluster==2.1.0

i noticed that cluster_down_retry_attempts is a possible way which outside the while loop which could control retry times. Im look forward to change RedisClusterRequestTTL in someway (16 is too much)


问:
Popup alert message box
When executing this code I get a pop-up, how to make it so that YES option is always selected in or nullify it completely ?

There are already data in the sheet. Do you want to replace them ?

```<code> ActiveSheet.PivotTables("Tabela").ChangePivotCache ActiveWorkbook.PivotCaches. _
                Create(SourceType:=xlDatabase, SourceData:= _
                "'" + cell.Value + "'!R10C2:R80C11" _
                , Version:=6)
</code>```

Expects the code in VBA to automatically select "YES".

Title: Popup alert message box

Body:
When executing this code I get a pop-up, how to make it so that YES option is always selected in or nullify it completely ?

There are already data in the sheet. Do you want to replace them ?

 ActiveSheet.PivotTables("Tabela").ChangePivotCache ActiveWorkbook.PivotCaches. _
                Create(SourceType:=xlDatabase, SourceData:= _
                "'" + cell.Value + "'!R10C2:R80C11" _
                , Version:=6)

Expects the code in VBA to automatically select "YES".


问:
How to combine prettier and eslint on line length?
I am getting this now that I changed to "printWidth": 1000, and added the eslint rule:

```<code>"max-len": ["error", { "code": 72, "ignoreUrls": true }],
</code>```

How do I set the width to 72 and not have it have this flash and revert back to the error state?

My eslint also has "extends": ["prettier"],.

Body:
I am getting this now that I changed to "printWidth": 1000, and added the eslint rule:

"max-len": ["error", { "code": 72, "ignoreUrls": true }],

How do I set the width to 72 and not have it have this flash and revert back to the error state?

My eslint also has "extends": ["prettier"],.


问:
Go Lang: gomobile bind optimize code built for armv7-a and arm64-v8a
I am struggling to build Go Lang into .so with binding to AAR file.

This is code I use for building

```<code>    CGO_ENABLED=1 \
        gomobile bind \
        -target=android/arm \
        -ldflags="-w -s" \
        -o export.aar \
        -v
</code>```

My goal is to speedup **Go Lang **code I have. I can't share code, nor discuss what it does.

```<code>Processing of same code on i7: 6 CPU, 12vCPU takes 100ms
While on ARMv7, 2GB ram, Android 9: 4-5 sec.
</code>```

I tried lots of things, like making code single threaded, instead of multi threaded as it is now, didn't help.

Are there any optimizations which I can enable just for ARM CPU-us?

I want to try -ffast-math. I tried on C++ code which I have as dependency .so libs, didn't helped.

P.S. I just thought about go build -gcflags '-m' checking which variables escape from stack to heap. I am not sure how good would be if I figure out which variables to fix, if fix is posible.

Body:
I am struggling to build Go Lang into .so with binding to AAR file.

This is code I use for building

    CGO_ENABLED=1 \
        gomobile bind \
        -target=android/arm \
        -ldflags="-w -s" \
        -o export.aar \
        -v

My goal is to speedup **Go Lang **code I have. I can't share code, nor discuss what it does.

Processing of same code on i7: 6 CPU, 12vCPU takes 100ms
While on ARMv7, 2GB ram, Android 9: 4-5 sec.

I tried lots of things, like making code single threaded, instead of multi threaded as it is now, didn't help.

Are there any optimizations which I can enable just for ARM CPU-us?

I want to try -ffast-math. I tried on C++ code which I have as dependency .so libs, didn't helped.

P.S. I just thought about go build -gcflags '-m' checking which variables escape from stack to heap. I am not sure how good would be if I figure out which variables to fix, if fix is posible.


问:
Toggle button inabilitates Userinterfaceonly protection
I'm having a really strange problem with a Macro Excel.
So, when opening my workbook I protect every Worksheet with Userinterfaceonly:=true Password:="XXX"
I have been using my program as normally until today.
Today I have introduced a Toggle button to hide the Userform on my worksheet because some of my Userforms are quite big.
I have seen that if i make the userform dissapear, then appear again and clik on any command button, the code that goes to another sheet to change any cell or do anything triggers an Error.
This did not happen before adding this toggle button.

EDIT: I will try to explain better the working of the program. One of the buttons of the Userform goes to another hidden sheet, makes visible some rows (i do not want the user to be able to see those cells full of data), takes some data and come backs to the original sheet to use it.
Until now it has been working perfectly because on opening the workbook i protect every sheet using Userinterfaceonlye:=True so vba can do things like these without triggering errors.

Basically, the line that throws the error is this, when the sheet is NOT VISIBLE.

```<code>Sheet("2ndSheet").Columns("A1:B2").Entirecolumn.hidden = false
</code>```

As I say, I have been working with this code for months and this exact part of the code never triggered errors. Now, when i make the Userform invisible and then visible using the Toggle button, then try to run the code, it throws this error:

```<code>Error 1004: cannot assign hidden property of range class
</code>```

The togglebutton works like this, on the active worksheet:

```<code>Private sub Togglebutton_Click()
If togglebutton = true then
Myuserform.hide
Else
Myuserform.show vbmodeless
End if
End sub
</code>```

Uppon more investigation it has broken the WHOLE program, not only the previous error triggered. I have restored the previous version and i will try to find another way to hide the userforms and not F*CK up my whole program...

FINAL EDIT: I have added a toggle button to the Userform itself which function is to minimize the userform and make it as little as possible. Clicking on it again will maximize the userform and show the user the different buttons. This way my program still works and i am able to make the Userforms small so my users have no problems with it. However, I still do not know why a toggle button that hides the Userform broke my program...

Body:
I'm having a really strange problem with a Macro Excel.
So, when opening my workbook I protect every Worksheet with Userinterfaceonly:=true Password:="XXX"
I have been using my program as normally until today.
Today I have introduced a Toggle button to hide the Userform on my worksheet because some of my Userforms are quite big.
I have seen that if i make the userform dissapear, then appear again and clik on any command button, the code that goes to another sheet to change any cell or do anything triggers an Error.
This did not happen before adding this toggle button.

EDIT: I will try to explain better the working of the program. One of the buttons of the Userform goes to another hidden sheet, makes visible some rows (i do not want the user to be able to see those cells full of data), takes some data and come backs to the original sheet to use it.
Until now it has been working perfectly because on opening the workbook i protect every sheet using Userinterfaceonlye:=True so vba can do things like these without triggering errors.

Basically, the line that throws the error is this, when the sheet is NOT VISIBLE.

Sheet("2ndSheet").Columns("A1:B2").Entirecolumn.hidden = false

As I say, I have been working with this code for months and this exact part of the code never triggered errors. Now, when i make the Userform invisible and then visible using the Toggle button, then try to run the code, it throws this error:

Error 1004: cannot assign hidden property of range class

The togglebutton works like this, on the active worksheet:

Private sub Togglebutton_Click()
If togglebutton = true then
Myuserform.hide
Else
Myuserform.show vbmodeless
End if
End sub

Uppon more investigation it has broken the WHOLE program, not only the previous error triggered. I have restored the previous version and i will try to find another way to hide the userforms and not F*CK up my whole program...

FINAL EDIT: I have added a toggle button to the Userform itself which function is to minimize the userform and make it as little as possible. Clicking on it again will maximize the userform and show the user the different buttons. This way my program still works and i am able to make the Userforms small so my users have no problems with it. However, I still do not know why a toggle button that hides the Userform broke my program...


问:
W2ui grid Return custom error mesage isted of data from remote url
I'm using W2ui grid version 2 and trying to return an custom error message instead of record data.

The JSON I'm sending back to grid is

```<code>{error:true, message:"Test"}
</code>```

but grid is not showing my message instead it is showing "HTTP error. See console for more details." in message poup. How can I change this message?

Body:
I'm using W2ui grid version 2 and trying to return an custom error message instead of record data.

The JSON I'm sending back to grid is

{error:true, message:"Test"}

but grid is not showing my message instead it is showing "HTTP error. See console for more details." in message poup. How can I change this message?


问:
SEMTIMEDOP LINUX
HOW TO INITIALIZE THE timespec ARGUMENT IN SEMTIMEDOP and how to use the fonction?</p>
```<code>int semtimedop(int semid, struct sembuf *sops, unsigned nsops,struct timespec *timeout);
</code>```

Title: SEMTIMEDOP LINUX

Body:
HOW TO INITIALIZE THE timespec ARGUMENT IN SEMTIMEDOP and how to use the fonction?

int semtimedop(int semid, struct sembuf *sops, unsigned nsops,struct timespec *timeout);


问:
Postgres: operator does not exist: bigint = character varying when query input parameter is null
Query:

```<code>ReadAllQuery(referenceClass=AdditionalSupplementFields sql="SELECT * from AGX_ADDITIONAL_SUPP_FIELDS  WHERE
DB_COLUMN = ? AND FK_SUPP_FIELD_REC_ID = ?")

Call: SELECT * from AGX_ADDITIONAL_SUPP_FIELDS  WHERE DB_COLUMN = ADD_TEXT_FIELD_10 AND FK_SUPP_FIELD_REC_ID = null
    bind => [2 parameters bound]
</code>```

Exception:

```<code>javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: operator does not exist: bigint = character varying
  Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
  Position: 89
Error Code: 0
Call: SELECT * from AGX_ADDITIONAL_SUPP_FIELDS  WHERE DB_COLUMN = ADD_TEXT_FIELD_10 AND FK_SUPP_FIELD_REC_ID = null
    bind => [2 parameters bound]
Query: ReadAllQuery(referenceClass=AdditionalSupplementFields sql="SELECT * from AGX_ADDITIONAL_SUPP_FIELDS  WHERE
DB_COLUMN = ? AND FK_SUPP_FIELD_REC_ID = ?")
</code>```

I have tried below solution but it is not working:

```<code>SELECT *
from AGX_ADDITIONAL_SUPP_FIELDS
WHERE DB_COLUMN = ?1
  AND FK_SUPP_FIELD_REC_ID = coalesce (?2,null)
</code>```

Body:
Query:

ReadAllQuery(referenceClass=AdditionalSupplementFields sql="SELECT * from AGX_ADDITIONAL_SUPP_FIELDS  WHERE
DB_COLUMN = ? AND FK_SUPP_FIELD_REC_ID = ?")

Call: SELECT * from AGX_ADDITIONAL_SUPP_FIELDS  WHERE DB_COLUMN = ADD_TEXT_FIELD_10 AND FK_SUPP_FIELD_REC_ID = null
    bind => [2 parameters bound]

Exception:

javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: operator does not exist: bigint = character varying
  Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
  Position: 89
Error Code: 0
Call: SELECT * from AGX_ADDITIONAL_SUPP_FIELDS  WHERE DB_COLUMN = ADD_TEXT_FIELD_10 AND FK_SUPP_FIELD_REC_ID = null
    bind => [2 parameters bound]
Query: ReadAllQuery(referenceClass=AdditionalSupplementFields sql="SELECT * from AGX_ADDITIONAL_SUPP_FIELDS  WHERE
DB_COLUMN = ? AND FK_SUPP_FIELD_REC_ID = ?")

I have tried below solution but it is not working:

SELECT *
from AGX_ADDITIONAL_SUPP_FIELDS
WHERE DB_COLUMN = ?1
  AND FK_SUPP_FIELD_REC_ID = coalesce (?2,null)


问:
OpenLayers image geo reference
I'm trying to georeference an OpenLayers imagelayer by constructing a bounding box from a known position. The user draws a line on an image, and specifies a length in centimeters. I use an arbitrary position on the map, calculate centimeters per pixel of the drawn line and construct a top left corner by moving that point left and up, and a bottom right corner by moving that point right and down. This works flawlessly except that the positions produce different results depending on the longitude of the position. I would expect the image to be the same size across the world but it gets squished differently on different parts of the world.

I'm moving the position by adding cm lengths to the web mercator coordinates. I know about web mercator distortion and the factor calculation of 1/cos(latitude) for longitude, but that factor produces a value that is way to big to account for the subtle squishing of the image.

I need a factor calculation that makes sure that every pixel on the image stays square.

The code I use to calculate the bounding box is as follows:

```<code>// Fetching width and height
const img = await this.geoImage.getImage();
const {width, height} = img;

// Get length of the drawn line in centimeters
const length = this.geoImage.getLineLength();
// Get line coordinates
const coordinates = this.geoImage.getReferenceLine().getGeometry().getCoordinates();
const [[x1, y1], [x2, y2]] = coordinates;

// Calculate the distance in pixels of the line on the image
const pixelDistance = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
// Calculate centimeters per pixel
const centimetersPerPixel = (length * 100) / pixelDistance;

// Construct top left position
const tl = this.geoImage.getCenter().clone();
tl.move(-(width / 2 * centimetersPerPixel), -(height / 2 * centimetersPerPixel));

// Construct bottom right position
const br = this.geoImage.getCenter().clone();
br.move((width / 2 * centimetersPerPixel), (height / 2 * centimetersPerPixel));

// Create extent
const extent = [...tl.toMercator(), ...br.toMercator()];
</code>```

And this is the code for moving a position:

```<code>/**
* Move the position in centimeters
* @param x
* @param y
*/
public move(x: number, y: number): void {
    // Web mercator coordinates
    const metricPoint = this.getCoordinates();

    metricPoint[0] += x;
    metricPoint[1] += y;

    // Set web mercator coordinates
    this.setCoordinates(metricPoint);
}
</code>```

Title: OpenLayers image geo reference

Body:
I'm trying to georeference an OpenLayers imagelayer by constructing a bounding box from a known position. The user draws a line on an image, and specifies a length in centimeters. I use an arbitrary position on the map, calculate centimeters per pixel of the drawn line and construct a top left corner by moving that point left and up, and a bottom right corner by moving that point right and down. This works flawlessly except that the positions produce different results depending on the longitude of the position. I would expect the image to be the same size across the world but it gets squished differently on different parts of the world.

I'm moving the position by adding cm lengths to the web mercator coordinates. I know about web mercator distortion and the factor calculation of 1/cos(latitude) for longitude, but that factor produces a value that is way to big to account for the subtle squishing of the image.

I need a factor calculation that makes sure that every pixel on the image stays square.

The code I use to calculate the bounding box is as follows:

// Fetching width and height
const img = await this.geoImage.getImage();
const {width, height} = img;

// Get length of the drawn line in centimeters
const length = this.geoImage.getLineLength();
// Get line coordinates
const coordinates = this.geoImage.getReferenceLine().getGeometry().getCoordinates();
const [[x1, y1], [x2, y2]] = coordinates;

// Calculate the distance in pixels of the line on the image
const pixelDistance = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
// Calculate centimeters per pixel
const centimetersPerPixel = (length * 100) / pixelDistance;

// Construct top left position
const tl = this.geoImage.getCenter().clone();
tl.move(-(width / 2 * centimetersPerPixel), -(height / 2 * centimetersPerPixel));

// Construct bottom right position
const br = this.geoImage.getCenter().clone();
br.move((width / 2 * centimetersPerPixel), (height / 2 * centimetersPerPixel));

// Create extent
const extent = [...tl.toMercator(), ...br.toMercator()];

And this is the code for moving a position:

/**
* Move the position in centimeters
* @param x
* @param y
*/
public move(x: number, y: number): void {
    // Web mercator coordinates
    const metricPoint = this.getCoordinates();

    metricPoint[0] += x;
    metricPoint[1] += y;

    // Set web mercator coordinates
    this.setCoordinates(metricPoint);
}