问:
Order of Allure report Environment property lists
I used allureEnvironmentWriter added some environment properties to allure report like below.

```<code>allureEnvironmentWriter(
        ImmutableMap.<String, String>builder()
        .put("TestEnvironment", param1)
        .put("Browser", param2)
        .put("Timeout", Integer.toString(param3))
        .build()
);
</code>```

Then I copy environment.xml from target/allure-results to allure-results folder in the base dir.
The environment.xml like below:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<environment>
    <parameter>
        <key>TestEnvironment</key>
        <value>onpre</value>
    </parameter>
    <parameter>
        <key>Browser</key>
        <value>Chrome</value>
    </parameter>
    <parameter>
        <key>Timeout</key>
        <value>30</value>
    </parameter>
</environment>
</code>```

My issue is I need to let the Timeout lists bottom. But when I run code on Jenkins pipeline it generated the allure report and the Timeout lists second positon.

How to make it shows the bottom ?

I tried:
create a environment.xml file in allure-results folder. But it doesn't help.

Body:
I used allureEnvironmentWriter added some environment properties to allure report like below.

allureEnvironmentWriter(
        ImmutableMap.<String, String>builder()
        .put("TestEnvironment", param1)
        .put("Browser", param2)
        .put("Timeout", Integer.toString(param3))
        .build()
);

Then I copy environment.xml from target/allure-results to allure-results folder in the base dir.
The environment.xml like below:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<environment>
    <parameter>
        <key>TestEnvironment</key>
        <value>onpre</value>
    </parameter>
    <parameter>
        <key>Browser</key>
        <value>Chrome</value>
    </parameter>
    <parameter>
        <key>Timeout</key>
        <value>30</value>
    </parameter>
</environment>

My issue is I need to let the Timeout lists bottom. But when I run code on Jenkins pipeline it generated the allure report and the Timeout lists second positon.

How to make it shows the bottom ?

I tried:
create a environment.xml file in allure-results folder. But it doesn't help.


来源: stackexchange

问:
Terraformer | The security token included in the request is invalid
I am trying to import a few AWS resources using terraformer.

terraformer import aws --resources lambda --filter Type=lambda;Name=lambda-function-name

But I am getting the following error:

```<code>aws importing... lambda
aws error initializing resources in service lambda, err: operation error Lambda: ListFunctions, https response error StatusCode: 403, RequestID: some-request-id, api
error UnrecognizedClientException: The security token included in the request is invalid.
aws Connecting...
</code>```

My provider configuration is as follows:

```<code>terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  region = "ca-central-1"
}

</code>```

I thought this might be related to incorrect aws credentials.
But I am able to use aws cli successfully in the same terminal window.
I am also able to use terraform plan and terraform apply successfully.
This makes me think that this might be related to terraformer.
I am using terraformer with version v0.8.22

ContentLicense: CC BY-SA 4.0

Body:
I am trying to import a few AWS resources using terraformer.

terraformer import aws --resources lambda --filter Type=lambda;Name=lambda-function-name

But I am getting the following error:

aws importing... lambda
aws error initializing resources in service lambda, err: operation error Lambda: ListFunctions, https response error StatusCode: 403, RequestID: some-request-id, api
error UnrecognizedClientException: The security token included in the request is invalid.
aws Connecting...

My provider configuration is as follows:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  region = "ca-central-1"
}

I thought this might be related to incorrect aws credentials.
But I am able to use aws cli successfully in the same terminal window.
I am also able to use terraform plan and terraform apply successfully.
This makes me think that this might be related to terraformer.
I am using terraformer with version v0.8.22


问:
Delete template should delete TemplateTag and TemplateAttribute entties as well in GraphQL
TemplateEntity{
id
name
}

TemplateTagEntity{
id
templateId
value
}

TemplateAttributeEntity{
id
templateId
ttl
type
}

Delete template should delete TemplateTag and TemplateAttribute entties as well in GraphQL


问:
How do you display an interactive 3D model in android studio?
I've tried to replicate  numerous projects online using opengl, sceneform and javafx to display a 3D model of the human anatomy with the ultimate goal of being able to add pointers to the model but nothing works. Can someone help me find some resources to follow or some tips how to do this? I apologize but im very inexperienced with Kotlin and anything java related and most of my experience programming is in python.

various sites that attempted to show how to display models but most were AR related


问:
state only updates after second click of 'add to cart' button
I am building an ecommerce app using React and Nextjs.
I am also using a Context to store and update cartItems and their quantities.
The issue is that the carItems state only upadtes after second click of the 'add to cart' button.
I have tried console logging before and after the click, the console log displays correct data after first click but the state does not update in the same instance. But then on second click the state is updated with the last item added to cart and ignores the latest item.

Please Help, Thank You.

-------------------Code Below-------------------------

The onAdd Function:

```<code>const Context= createContext({});

export const StateContext=({children}:any)=>{

    const[showCart, setShowCart]=useState(false);
    const[cartItems, setCartItems]=useState([]);
    const[totalPrice, setTotalPrice]=useState(0);
    const[totalQuantities, setTotalQuantities]=useState(0);
    const[qty, setQty]=useState(1);

    let foundProduct:any;
    let index;

    const onAdd=async (product:any, quantity:any)=>{
        // @ts-ignore
        // setCartItems([...cartItems, {product}]);
        // console.log('cartItems',cartItems)
        const checkProductInCart= cartItems.find((item:any)=>item._id===product._id);
        setTotalPrice((prevTotalPrice)=>prevTotalPrice+product.price*quantity);
        setTotalQuantities((prevTotalQuantities)=>prevTotalQuantities+quantity);
        // @ts-ignore

        if(checkProductInCart){
            const updatedCartItems= cartItems?.map((cartProduct:any)=>{
                if(cartProduct._id ===product._id){
                    return{
                        ...cartProduct,
                        quantity: cartProduct.quantity+quantity
                    }
                }
            })
            // @ts-ignore
           await setCartItems(updatedCartItems);
            console.log('updatedCartItems',updatedCartItems)
    } else{
            product.quantity =quantity;

            console.log('jhvjv',...cartItems)
            // @ts-ignore
            // setCartItems([product]);
             setCartItems([...cartItems, {product}]);
            console.log('cart items set',[...cartItems, {product}])
            console.log('cart items',cartItems)
        }
        toast.success(`${qty} ${product.name} added to cart`,)

    }

</code>```

Add To Cart Button:

```<code> <p>{details}</p>
    <p>${price}</p>
    <h3>Quantity:</h3>
    <p className={'quantity-desc'}>
        <span className={'minus'} onClick={() => decQty()}> <AiOutlineMinus/> </span>
        <span className={'num'}> {qty}</span>
        <span className={'plus'} onClick={() => incQty()}> <AiOutlinePlus/> </span>
    </p>
    <div className={'buttons'}>
        <button className={'add-to-cart'} onClick={() => {onAdd(product,qty)
        }}>Add to Cart
        </button>
        <button className={'buy-now'}>Buy Now</button>

    </div>

</div>
</code>```

View of console.logs-

I am unable to figure out what the issue is, maybe useEffect could work but cant use hooks inside the useContext function.

Body:
I am building an ecommerce app using React and Nextjs.
I am also using a Context to store and update cartItems and their quantities.
The issue is that the carItems state only upadtes after second click of the 'add to cart' button.
I have tried console logging before and after the click, the console log displays correct data after first click but the state does not update in the same instance. But then on second click the state is updated with the last item added to cart and ignores the latest item.

Please Help, Thank You.

-------------------Code Below-------------------------

The onAdd Function:

const Context= createContext({});

export const StateContext=({children}:any)=>{

    const[showCart, setShowCart]=useState(false);
    const[cartItems, setCartItems]=useState([]);
    const[totalPrice, setTotalPrice]=useState(0);
    const[totalQuantities, setTotalQuantities]=useState(0);
    const[qty, setQty]=useState(1);

    let foundProduct:any;
    let index;

    const onAdd=async (product:any, quantity:any)=>{
        // @ts-ignore
        // setCartItems([...cartItems, {product}]);
        // console.log('cartItems',cartItems)
        const checkProductInCart= cartItems.find((item:any)=>item._id===product._id);
        setTotalPrice((prevTotalPrice)=>prevTotalPrice+product.price*quantity);
        setTotalQuantities((prevTotalQuantities)=>prevTotalQuantities+quantity);
        // @ts-ignore

        if(checkProductInCart){
            const updatedCartItems= cartItems?.map((cartProduct:any)=>{
                if(cartProduct._id ===product._id){
                    return{
                        ...cartProduct,
                        quantity: cartProduct.quantity+quantity
                    }
                }
            })
            // @ts-ignore
           await setCartItems(updatedCartItems);
            console.log('updatedCartItems',updatedCartItems)
    } else{
            product.quantity =quantity;

            console.log('jhvjv',...cartItems)
            // @ts-ignore
            // setCartItems([product]);
             setCartItems([...cartItems, {product}]);
            console.log('cart items set',[...cartItems, {product}])
            console.log('cart items',cartItems)
        }
        toast.success(`${qty} ${product.name} added to cart`,)

    }

Add To Cart Button:

{details}

${price}

Quantity:

         decQty()}> <AiOutlineMinus/>
         {qty}
         incQty()}> <AiOutlinePlus/>

        <button className={'add-to-cart'} onClick={() => {onAdd(product,qty)
        }}>Add to Cart
        </button>
        <button className={'buy-now'}>Buy Now</button>

View of console.logs-

I am unable to figure out what the issue is, maybe useEffect could work but cant use hooks inside the useContext function.


问:
GRPC Protoc File creation with scaffold
I am kind of new with grpc .net and I have been trying to find out if there is a way to automatically generate all of the protoc file of a database instead of creating it one by one.

I have only tried the implementation with .net rest api scaffold and its not working. hope that I can find a way to scaffold database to grpc protoc file.

Title: GRPC Protoc File creation with scaffold


问:
How can i get the user coordinates correctly?
I'm working on a mobile app that sends the user latitude and longitude among with other parameter to a server. My problem here is that when I click the LocationButton the map updates correctly to my location but the latitude and longitude that I get is the one on the MainScreenViewModel by default. But when I press the button a second time i get the longitude and latitude that is in the simulator (the desired one). The sendAlert function sends the data to the server that is in the images.

```<code>import Foundation
import MapKit
import CoreLocationUI

class MainScreenViewModel: NSObject,ObservableObject, CLLocationManagerDelegate{
    @Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
    let locationManager = CLLocationManager()
    override init(){
        super.init()
        locationManager.delegate = self
    }
    func requestAllowOnceLocationPermission(){
        locationManager.requestLocation()
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let latestLocation = locations.first else{
            return
        }
        DispatchQueue.main.async {
            self.region = MKCoordinateRegion(center: latestLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
        }
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
}

import SwiftUI
import MapKit
import CoreLocationUI
import Firebase
import FirebaseFirestore
import FirebaseAuth

struct MapView: View {
    @StateObject var viewModel = MainScreenViewModel()
    @ObservedObject var service = Service()
    @State private var confirmationMessage = ""
    @State private var showingConfirmation = false
    // MARK: App Storage
    @AppStorage("has_fetch_mr") var haventFetchmr: Bool = true
    @AppStorage("log_status") var logStatus: Bool = false
    @AppStorage("is_google_user") var isGoogleUser: Bool = false
    @AppStorage("user_profile_url") var profileURL: URL?
    @AppStorage("user_name") var userNameStored: String = ""
    @AppStorage("user_UID") var userUID: String = ""
    // MARK: Medical Record Storage
    // MARK: Personal Info
    @AppStorage("full_name") var patientName: String = ""
    @AppStorage("birth_date") var birthDate: String = ""
    @AppStorage("gender") var gender: String = ""
    @AppStorage("age") var age: String = ""
    @AppStorage("marital_Status") var maritalStatus: String = ""
    @AppStorage("address") var address: String = ""
    @AppStorage("phone_number") var cellphoneNumber: String = ""
    // MARK: Family History
    @AppStorage("diabetes") var hasDiabetes: Bool = false
    @AppStorage("obesity") var hasObesity: Bool = false
    @AppStorage("hearth_Disease") var hasHeartDisease: Bool = false
    @AppStorage("hypertension") var hasHypertension: Bool = false
    @AppStorage("lungDisease") var hasLungDisease: Bool = false
    @AppStorage("cancer") var hasCancer: Bool = false
    // MARK: Personal History 1
    @AppStorage("drinking_scale") var drinkingScale: String = ""
    @AppStorage("smoking_Scale") var smokingScale: String = ""
    @AppStorage("fitness_Scale") var fitnesScale: String = ""
    @AppStorage("sleeping_Hours") var sleepingHours: String = ""
    @AppStorage("work_study_hours") var workingStudingHours: String = ""
    @AppStorage("allergies") var allergies: String = ""
    // MARK: Personal History 2
    @AppStorage("illness") var illness: String = ""
    @AppStorage("illness_date") var illnessDate: String = ""
    @AppStorage("treatment") var treatment: String = ""
    @AppStorage("dose_of_medication") var doseOfMedication: String = ""
    var body: some View {
        ZStack(alignment: .top){
            Map(coordinateRegion: $viewModel.region, showsUserLocation: true)
                .tint(.biomedPrimary)
                .ignoresSafeArea()
            LocationButton(.shareMyCurrentLocation){
                print("1ra \($viewModel.region)")
                viewModel.requestAllowOnceLocationPermission()
                let myJSON = [
                    "latitude": "\($viewModel.region.center.latitude.wrappedValue)",
                    "longitude": "\($viewModel.region.center.longitude.wrappedValue)",
                    "patientName": patientName,
                    "patientAge": age,
                    "patiendIllness": illness
                ]
                service.sendAlert(coordinates: myJSON)
                print(myJSON)
                confirmationMessage="Your location has been sent to the Server"
                showingConfirmation.toggle()
            }
            .foregroundColor(.white)
            .cornerRadius(8)
            .labelStyle(.titleOnly)
            .symbolVariant(.fill)
            .tint(.biomedPrimary)
            .padding(.top,20)
        }
        .alert("Alerta", isPresented: $showingConfirmation) {
            Button("OK") {}
        } message: {
            Text(confirmationMessage)
        }
    }
}
</code>```

First Button Click
Second Button Click

Body:
I'm working on a mobile app that sends the user latitude and longitude among with other parameter to a server. My problem here is that when I click the LocationButton the map updates correctly to my location but the latitude and longitude that I get is the one on the MainScreenViewModel by default. But when I press the button a second time i get the longitude and latitude that is in the simulator (the desired one). The sendAlert function sends the data to the server that is in the images.

import Foundation
import MapKit
import CoreLocationUI

class MainScreenViewModel: NSObject,ObservableObject, CLLocationManagerDelegate{
    @Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
    let locationManager = CLLocationManager()
    override init(){
        super.init()
        locationManager.delegate = self
    }
    func requestAllowOnceLocationPermission(){
        locationManager.requestLocation()
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let latestLocation = locations.first else{
            return
        }
        DispatchQueue.main.async {
            self.region = MKCoordinateRegion(center: latestLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
        }
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
}

import SwiftUI
import MapKit
import CoreLocationUI
import Firebase
import FirebaseFirestore
import FirebaseAuth

struct MapView: View {
    @StateObject var viewModel = MainScreenViewModel()
    @ObservedObject var service = Service()
    @State private var confirmationMessage = ""
    @State private var showingConfirmation = false
    // MARK: App Storage
    @AppStorage("has_fetch_mr") var haventFetchmr: Bool = true
    @AppStorage("log_status") var logStatus: Bool = false
    @AppStorage("is_google_user") var isGoogleUser: Bool = false
    @AppStorage("user_profile_url") var profileURL: URL?
    @AppStorage("user_name") var userNameStored: String = ""
    @AppStorage("user_UID") var userUID: String = ""
    // MARK: Medical Record Storage
    // MARK: Personal Info
    @AppStorage("full_name") var patientName: String = ""
    @AppStorage("birth_date") var birthDate: String = ""
    @AppStorage("gender") var gender: String = ""
    @AppStorage("age") var age: String = ""
    @AppStorage("marital_Status") var maritalStatus: String = ""
    @AppStorage("address") var address: String = ""
    @AppStorage("phone_number") var cellphoneNumber: String = ""
    // MARK: Family History
    @AppStorage("diabetes") var hasDiabetes: Bool = false
    @AppStorage("obesity") var hasObesity: Bool = false
    @AppStorage("hearth_Disease") var hasHeartDisease: Bool = false
    @AppStorage("hypertension") var hasHypertension: Bool = false
    @AppStorage("lungDisease") var hasLungDisease: Bool = false
    @AppStorage("cancer") var hasCancer: Bool = false
    // MARK: Personal History 1
    @AppStorage("drinking_scale") var drinkingScale: String = ""
    @AppStorage("smoking_Scale") var smokingScale: String = ""
    @AppStorage("fitness_Scale") var fitnesScale: String = ""
    @AppStorage("sleeping_Hours") var sleepingHours: String = ""
    @AppStorage("work_study_hours") var workingStudingHours: String = ""
    @AppStorage("allergies") var allergies: String = ""
    // MARK: Personal History 2
    @AppStorage("illness") var illness: String = ""
    @AppStorage("illness_date") var illnessDate: String = ""
    @AppStorage("treatment") var treatment: String = ""
    @AppStorage("dose_of_medication") var doseOfMedication: String = ""
    var body: some View {
        ZStack(alignment: .top){
            Map(coordinateRegion: $viewModel.region, showsUserLocation: true)
                .tint(.biomedPrimary)
                .ignoresSafeArea()
            LocationButton(.shareMyCurrentLocation){
                print("1ra \($viewModel.region)")
                viewModel.requestAllowOnceLocationPermission()
                let myJSON = [
                    "latitude": "\($viewModel.region.center.latitude.wrappedValue)",
                    "longitude": "\($viewModel.region.center.longitude.wrappedValue)",
                    "patientName": patientName,
                    "patientAge": age,
                    "patiendIllness": illness
                ]
                service.sendAlert(coordinates: myJSON)
                print(myJSON)
                confirmationMessage="Your location has been sent to the Server"
                showingConfirmation.toggle()
            }
            .foregroundColor(.white)
            .cornerRadius(8)
            .labelStyle(.titleOnly)
            .symbolVariant(.fill)
            .tint(.biomedPrimary)
            .padding(.top,20)
        }
        .alert("Alerta", isPresented: $showingConfirmation) {
            Button("OK") {}
        } message: {
            Text(confirmationMessage)
        }
    }
}

First Button Click
Second Button Click


问:
MFC - A new string is not drawn after ScrollWindow. What could be the cause?
There is a issue with ScrollWindow(). In OnPaint(), there is TextOut(0, 100, L"XXX"), which means the string XXX should be always at coord (0, 100). When I scroll the CChildView with ScrollWindow(), the drawn string moves -- this is expected. But a new string XXX is not drawn at coord (0, 100).

```<code>void CChildView::OnPaint()
{
    CPaintDC dc(this);
    dc.TextOut(0, 100, L"XXX"); // XXX should always locate at (0, 100)
}
</code>```

ScrollWindow(0, -10) scrolls the contents of CChildView down by 10px, and calls OnPaint() indirectly. In this case, the string XXX should move up by 10px, locating at (0, 90), and a new string XXX should be drawn at (0, 100).

But now the problem is, the new string is not drawn at all. What could be the cause?

Body:
There is a issue with ScrollWindow(). In OnPaint(), there is TextOut(0, 100, L"XXX"), which means the string XXX should be always at coord (0, 100). When I scroll the CChildView with ScrollWindow(), the drawn string moves -- this is expected. But a new string XXX is not drawn at coord (0, 100).

void CChildView::OnPaint()
{
    CPaintDC dc(this);
    dc.TextOut(0, 100, L"XXX"); // XXX should always locate at (0, 100)
}

ScrollWindow(0, -10) scrolls the contents of CChildView down by 10px, and calls OnPaint() indirectly. In this case, the string XXX should move up by 10px, locating at (0, 90), and a new string XXX should be drawn at (0, 100).

But now the problem is, the new string is not drawn at all. What could be the cause?


问:
DateTime2 prefixed with "T"
When using Tasks - Generate Scripts... it is now generating the DateTime2 with a Prefix of "T" for the time (example 1) instead of leaving it blank (example 2). How do I remove the Prefix "T" when generating my scripts?

Example 1:
CAST(N'2017-04-18T00:00:00.0000000' AS DateTime2)

Example 2:
CAST(N'2017-04-18 00:00:00.0000000' AS DateTime2)

I have tried generating at a previous version of SQL i.e. 2008 or 2012 to see if it was a versioning issues which still did not work.

Title: DateTime2 prefixed with "T"


问:
URP CommandBuffer in loop memory question
in RenderPass when when i add this part

```<code>for(int i = 1; i < 45; i++)
{
        cmd.Clear();
        cmd.SetGlobalFloat("_FUR_OFFSET", i * inter);
        context.DrawRenderers(renderingData.cullResults,ref layerDrawingSetting,ref filter);
        context.ExecuteCommandBuffer(cmd);
}
</code>```

in Execute() method.

the memory in iphone is increase about 300mb,when i change the number 45 to 100,is increase about 700mb,i don't konw how to release memory in the loop.

i try CommandBufferPool.Release(cmd);
in loop is doesn't work,try cmd.Release(); not working too.
is there someone Please help me figure out this question? thanks a lot.

this is whole code:

```<code>public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag);
            //=============================================================
            //draw objects(e.g. reflective wet ground plane) with lightmode "MobileSSPRWater", which will sample _MobileSSPR_ColorRT
            DrawingSettings baseDrawingSetting, layerDrawingSetting;
            //BaseLayer DrawingSetting
            if (m_ShaderTagIdList.Count > 0)
                baseDrawingSetting = CreateDrawingSettings(m_ShaderTagIdList[0], ref renderingData,
                    renderingData.cameraData.defaultOpaqueSortFlags);
            else return;
            if(m_ShaderTagIdList.Count > 1)
            layerDrawingSetting = CreateDrawingSettings(m_ShaderTagIdList[1], ref renderingData,
                renderingData.cameraData.defaultOpaqueSortFlags);
            else return;

            int layerCount = 45;
            float inter = 1.0f / layerCount;
            //float inter = 1.0f / settings.PassLayerNum;
            //BaseLayer
            cmd.Clear();
            cmd.SetGlobalFloat("_FUR_OFFSET", 0);
            context.DrawRenderers(renderingData.cullResults,ref baseDrawingSetting,ref filter);
            context.ExecuteCommandBuffer(cmd);
            //TransparentLayer
            for(int i = 1; i < layerCount; i++)
            {
                cmd.Clear();
                cmd.SetGlobalFloat("_FUR_OFFSET", i * inter);
                context.DrawRenderers(renderingData.cullResults,ref layerDrawingSetting,ref filter);
                context.ExecuteCommandBuffer(cmd);
            }
            CommandBufferPool.Release(cmd);
        }
</code>```

Body:
in RenderPass when when i add this part

for(int i = 1; i < 45; i++)
{
        cmd.Clear();
        cmd.SetGlobalFloat("_FUR_OFFSET", i * inter);
        context.DrawRenderers(renderingData.cullResults,ref layerDrawingSetting,ref filter);
        context.ExecuteCommandBuffer(cmd);
}

in Execute() method.

the memory in iphone is increase about 300mb,when i change the number 45 to 100,is increase about 700mb,i don't konw how to release memory in the loop.

i try CommandBufferPool.Release(cmd);
in loop is doesn't work,try cmd.Release(); not working too.
is there someone Please help me figure out this question? thanks a lot.

this is whole code:

public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag);
            //=============================================================
            //draw objects(e.g. reflective wet ground plane) with lightmode "MobileSSPRWater", which will sample _MobileSSPR_ColorRT
            DrawingSettings baseDrawingSetting, layerDrawingSetting;
            //BaseLayer DrawingSetting
            if (m_ShaderTagIdList.Count > 0)
                baseDrawingSetting = CreateDrawingSettings(m_ShaderTagIdList[0], ref renderingData,
                    renderingData.cameraData.defaultOpaqueSortFlags);
            else return;
            if(m_ShaderTagIdList.Count > 1)
            layerDrawingSetting = CreateDrawingSettings(m_ShaderTagIdList[1], ref renderingData,
                renderingData.cameraData.defaultOpaqueSortFlags);
            else return;

            int layerCount = 45;
            float inter = 1.0f / layerCount;
            //float inter = 1.0f / settings.PassLayerNum;
            //BaseLayer
            cmd.Clear();
            cmd.SetGlobalFloat("_FUR_OFFSET", 0);
            context.DrawRenderers(renderingData.cullResults,ref baseDrawingSetting,ref filter);
            context.ExecuteCommandBuffer(cmd);
            //TransparentLayer
            for(int i = 1; i < layerCount; i++)
            {
                cmd.Clear();
                cmd.SetGlobalFloat("_FUR_OFFSET", i * inter);
                context.DrawRenderers(renderingData.cullResults,ref layerDrawingSetting,ref filter);
                context.ExecuteCommandBuffer(cmd);
            }
            CommandBufferPool.Release(cmd);
        }


问:
Does torch.utils.data.ConcatDataset preserve individual torch.transforms on the datasets?
If I have two separate datasets declared with separate sets of torch.transforms, and then I concatenate the datasets using torch.utils.data.ConcatDataset to create the final dataset, will the different sets of transforms be preserved when the dataloader calls the images, or will all the images follow only one/common set of torch.transforms?

I have an original dataset, and I am trying to create an augmented dataset using some torch.transforms, and then feed both of them to the network as one. I expect the original images to go through their own transforms, and also separately go through the augmentation transforms to form the augmented dataset, and ultimately unite them to make the final dataset.


问:
How to modify request body in interceptor filter of Quarkus?
I use ContainerResquestFilter and HttpServerRequest to handler filter before run code api.
I need decrypt data and set again to request body
But I don't find any document or function to modify request body?
Please help me to resolve this problem!

Function to modify request body in interceptor of Quarkus


问:
Dynamic input as array of strings using Zod and React Hook Form
On my screen I will can receive emails: string[]. And it will be rendered with the amount of the length of this array {emailsFields.map((field, index) => {...} but using the Zod I have a validation service that you can see below.

```<code>export const emails = validationService
  .string({
    required_error: 'Email is required'
  })
  .email('Must be a valid email')
  .array()
</code>```

Using this emails variable as the name at my Input component name='emails' I use to be controlled. It can be rendered the all emails that I received as the image below.

```<code><TextFieldWithPlusIcon
   key={field.id}
   name="emails"
   label="Corporate email"
   placeholder="name@email.com"
   keyboardType="email-address"
   autoCapitalize="none"
   defaultValue={defaultValues.emails[index]}
   autoCorrect={false}
/>
</code>```

And when I type in one of these inputs, everyone with emails is changed like the other image below.

I found some topics here on Stackoverflow that they say to use like a index in the name property like this name={'[${field.id}].emails'} and it works but the emails that I receive at my component for an example if I receive a array with two strings, two inputs are rendered but without the received values inserted at in the input component. Again like the image below

I tried and it worked but the values in the component aren't rendered.

React-Hook Form with useFieldArray: TextField value does not show up in the console. How can I fix it?

Typescript problem with useFieldArray with property name

Body:
On my screen I will can receive emails: string[]. And it will be rendered with the amount of the length of this array {emailsFields.map((field, index) => {...} but using the Zod I have a validation service that you can see below.

export const emails = validationService
  .string({
    required_error: 'Email is required'
  })
  .email('Must be a valid email')
  .array()

Using this emails variable as the name at my Input component name='emails' I use to be controlled. It can be rendered the all emails that I received as the image below.

<TextFieldWithPlusIcon
   key={field.id}
   name="emails"
   label="Corporate email"
   placeholder="name@email.com"
   keyboardType="email-address"
   autoCapitalize="none"
   defaultValue={defaultValues.emails[index]}
   autoCorrect={false}
/>

And when I type in one of these inputs, everyone with emails is changed like the other image below.

I found some topics here on Stackoverflow that they say to use like a index in the name property like this name={'[${field.id}].emails'} and it works but the emails that I receive at my component for an example if I receive a array with two strings, two inputs are rendered but without the received values inserted at in the input component. Again like the image below

I tried and it worked but the values in the component aren't rendered.

React-Hook Form with useFieldArray: TextField value does not show up in the console. How can I fix it?

Typescript problem with useFieldArray with property name


问:
ecommerce filters with query
i am building ecommerce app using react, redux and express server, i building the filters sidebar and i wanted to ask is there a better way to get data base on query params than what i did?

```<code>const { queryObject } = useSelector((state: RootState) => state.shop);
  const { data, isLoading, error } = useGetProductsQuery(
    new URLSearchParams(queryObject).toString()
  );

</code>```

that my solution, so far i made only the search bar but i am assuming that i will be a bit messy to add more filters to it

Title: ecommerce filters with query

Body:
i am building ecommerce app using react, redux and express server, i building the filters sidebar and i wanted to ask is there a better way to get data base on query params than what i did?

const { queryObject } = useSelector((state: RootState) => state.shop);
  const { data, isLoading, error } = useGetProductsQuery(
    new URLSearchParams(queryObject).toString()
  );

that my solution, so far i made only the search bar but i am assuming that i will be a bit messy to add more filters to it


问:
How to put react bootstrap modal in a separate file
I am trying to put a react-material modal in its own separate files but if I don't, it does not work!

here is the react-bootstrap modal ::

```<code>import React, { useState } from "react";
import Button from "react-bootstrap/Button";
import { Modal, Row, Form } from "react-bootstrap";
//import SimpleModal from "../Components/UI/SimpleModal";   // THIS IS THE SIMPLE MODAL FILE MENTIONED
const Footer = () => {
  return (
    <footer className="py-5 my-5 bg-dark">
      <p className="text-center text-white">Bosky</p>
      <p className="text-center text-white">Linkedin logo</p>
      <p className="text-center text-white">Twitter logo</p>
      <p className="text-center text-white">Facebook logo</p>
      <Row style={{ "padding-left": "100px", "padding-right": "100px" }}>
        render(
        <SimpleModal />)
      </Row>
    </footer>
  );
};

// fix: unable to put this in another file
const SimpleModal = () => {
  const [show, setShow] = useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  return (
    <>
      <Button variant="primary" onClick={handleShow}>
        Email us today
      </Button>

      <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Interested in working with us?</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form>
            <Form.Group className="mb-3" controlId="formBasicEmail">
              <Form.Label>Email address</Form.Label>
              <Form.Control type="email" placeholder="lebrunJames@gmail.com" />
              <Form.Text className="text-muted">
                We'll never share your email with anyone else.
              </Form.Text>
            </Form.Group>

            <Form.Group className="mb-3" controlId="formBasicPassword">
              <Form.Label>Message</Form.Label>
              <Form.Control
                as="textarea"
                placeholder="Hi, you guys are awesome!"
              />
            </Form.Group>

            <Button variant="primary" type="submit">
              Submit
            </Button>
          </Form>
        </Modal.Body>
      </Modal>
    </>
  );
};

export default Footer;
</code>```

here is the code in sandbox:
https://codesandbox.io/s/bosky-active-forked-ttb7qj?file=/src/Components/Footer.js.

How do I put this on a separate file and it still works?

Body:
I am trying to put a react-material modal in its own separate files but if I don't, it does not work!

here is the react-bootstrap modal ::

import React, { useState } from "react";
import Button from "react-bootstrap/Button";
import { Modal, Row, Form } from "react-bootstrap";
//import SimpleModal from "../Components/UI/SimpleModal";   // THIS IS THE SIMPLE MODAL FILE MENTIONED
const Footer = () => {
  return (

Bosky

Linkedin logo

Twitter logo

Facebook logo

      <Row style={{ "padding-left": "100px", "padding-right": "100px" }}>
        render(
        <SimpleModal />)
      </Row>

  );
};

// fix: unable to put this in another file
const SimpleModal = () => {
  const [show, setShow] = useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  return (
    <>
      <Button variant="primary" onClick={handleShow}>
        Email us today
      </Button>

      <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Interested in working with us?</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form>
            <Form.Group className="mb-3" controlId="formBasicEmail">
              <Form.Label>Email address</Form.Label>
              <Form.Control type="email" placeholder="lebrunJames@gmail.com" />
              <Form.Text className="text-muted">
                We'll never share your email with anyone else.
              </Form.Text>
            </Form.Group>

            <Form.Group className="mb-3" controlId="formBasicPassword">
              <Form.Label>Message</Form.Label>
              <Form.Control
                as="textarea"
                placeholder="Hi, you guys are awesome!"
              />
            </Form.Group>

            <Button variant="primary" type="submit">
              Submit
            </Button>
          </Form>
        </Modal.Body>
      </Modal>
    </>
  );
};

export default Footer;

here is the code in sandbox:
https://codesandbox.io/s/bosky-active-forked-ttb7qj?file=/src/Components/Footer.js.

How do I put this on a separate file and it still works?


问:
How to scroll specific item in Singlechildscrollview?
I have a SingleChildScrollView, its scrollDirection is set to Vertical with number children widgets placed inside a ListView.bulder Widget. I want to programmatically scroll to the middle widget in the ListView and when the middle widget is reached(waits 2 seconds).

Scroll specific item in SigleChildScrollView.


问:
Dockerexecutable file not found in $PATH: unknown
I have a docker container, and I am trying to run a maven command on it. The docker container hosts a java app (springboot) on a working directory, so I do this command.

```<code>docker run -w $SERVICE_DIR --name 1234 --rm -v $SERVICE_DIR:$SERVICE_DIR $IMAGE "mvn package"
</code>```

(Keep in mind, the environmental variables $SERVICE_DIR and $IMAGE are set and valid)

and I get the error :

```<code>docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "mvn package": executable file not found in $PATH: unknown.
</code>```

I then try more basic commands, such as mvn --version or even echo hi and I get the same error.

However, when I do the ls command or pwd command like this:

```<code>docker run --name 1234 --rm -v $SERVICE_DIR:$SERVICE_DIR $IMAGE "ls"
</code>```

there are no problems, command runs! I did some googling, and I think I did the order of my commands correctly... Also, I cannot do /bin/bash and run this interactively; I will be running this through a shell script.

Thanks

Body:
I have a docker container, and I am trying to run a maven command on it. The docker container hosts a java app (springboot) on a working directory, so I do this command.

docker run -w $SERVICE_DIR --name 1234 --rm -v $SERVICE_DIR:$SERVICE_DIR $IMAGE "mvn package"

(Keep in mind, the environmental variables $SERVICE_DIR and $IMAGE are set and valid)

and I get the error :

docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "mvn package": executable file not found in $PATH: unknown.

I then try more basic commands, such as mvn --version or even echo hi and I get the same error.

However, when I do the ls command or pwd command like this:

docker run --name 1234 --rm -v $SERVICE_DIR:$SERVICE_DIR $IMAGE "ls"

there are no problems, command runs! I did some googling, and I think I did the order of my commands correctly... Also, I cannot do /bin/bash and run this interactively; I will be running this through a shell script.

Thanks


问:
Trying a VBA script for adding multiple images, title and captions from input sheet in excel sheet. It throws "object not found, compile error"
It highlights the line Set Anglefolder = Angle_Names(i, 1).Value when the error message occurs.

Whole code is very small and simple as below :

```<code>Sub Insert_Multiple_Images()

Sheets("input").Select
Set Angle_Names = Range("A5", Range("A5").End(xlDown))
Set Image_Names = Range("B2", Range("B2").End(xlRight))
Image_Location = Range("B3").Value
Image_Format = ".png"
Dim Anglefolder As String
Dim Imagename As String

Sheets("post_DOE").Select
Set Cell_Reference = Range("A2") ''
For i = 0 To Angle_Names.Rows.Count
    Cell_Reference.Offset(i * 17).Select
    ActiveCell.FormulaR1C1 = Range("A2").Offset(i).Value

    Print #1, i; "current value"
    Set Anglefolder = Angle_Names(i, 1).Value

For j = 0 To Image_Names.Columns.Count
Cell_Reference.Offset((i + 1) * 17, j * 12).Select
ActiveCell.FormulaR1C1 = Range("B2").Offset(i).Value
Set Imagename = Image_Names(0, j)
        Set Image = ActiveSheet.Pictures.Insert(Image_Location + "\Design00" + Anglefolder + "\" + Imagename + Image_Format)
        Image.Top = Cell_Reference.Cells(i, j).Top
        Image.Left = Cell_Reference.Cells(i, j).Left
        Image.ShapeRange.Height = 290
        Image.ShapeRange.Width = 674

    Next j
Next i

End Sub
</code>```

Insert multiple images at fixed location with titles and capttion for all images from an input sheet.

Body:
It highlights the line Set Anglefolder = Angle_Names(i, 1).Value when the error message occurs.

Whole code is very small and simple as below :

Sub Insert_Multiple_Images()

Sheets("input").Select
Set Angle_Names = Range("A5", Range("A5").End(xlDown))
Set Image_Names = Range("B2", Range("B2").End(xlRight))
Image_Location = Range("B3").Value
Image_Format = ".png"
Dim Anglefolder As String
Dim Imagename As String

Sheets("post_DOE").Select
Set Cell_Reference = Range("A2") ''
For i = 0 To Angle_Names.Rows.Count
    Cell_Reference.Offset(i * 17).Select
    ActiveCell.FormulaR1C1 = Range("A2").Offset(i).Value

    Print #1, i; "current value"
    Set Anglefolder = Angle_Names(i, 1).Value

For j = 0 To Image_Names.Columns.Count
Cell_Reference.Offset((i + 1) * 17, j * 12).Select
ActiveCell.FormulaR1C1 = Range("B2").Offset(i).Value
Set Imagename = Image_Names(0, j)
        Set Image = ActiveSheet.Pictures.Insert(Image_Location + "\Design00" + Anglefolder + "\" + Imagename + Image_Format)
        Image.Top = Cell_Reference.Cells(i, j).Top
        Image.Left = Cell_Reference.Cells(i, j).Left
        Image.ShapeRange.Height = 290
        Image.ShapeRange.Width = 674

    Next j
Next i

End Sub

Insert multiple images at fixed location with titles and capttion for all images from an input sheet.


问:
Having the same admob native ad displayed multiple times in a RecyclerView
I have a RecyclerView in which I show an admob native ad after every 10 items. So for example if I have 100 items in a list, then the ad will be shown 10 times. I first generate the native ad object then mix it with the list which is then passed to the RecyclerView adapter. How will ad impression work in this scenario? Will it register an impression if the list is scrolled very fast?
And is a native ad object only limited to one impression which is the first time it's displayed or will each time it is displayed as we scroll all the way down the RecyclerView list be counted as an impression,hence multiple impressions (10 or so). If so,won't this be too much impressions for just one ad,and how will this affect my admob account?</p>


问:
Django Form modifies database, could it be an issue if two people submit a form at the same time
I'm very new to Django and I'm writing an app that gives user the best matching product from the database. I have a model with all the products and their specifications, model for user's preferences and Compatibility model where I have all the product ids and when user submits the form, compatibility column updates, then the table is sorted and gives back 5 top choices. My concern is if it could be an issue if two users submit a form at the exact same time? Could that cause User B getting top products for User A form?

If yes, what would you recommend me to do or what to section in Django documentation could help me to figure it out?


问:
Asyncio with Flask_RESTful
I need to use asyncio with flask_restful.

Since future is tied to an event loop, I need a single event loop that runs forever and it should be accessible through out the flask app.

```<code>#index.py

import asyncio as aio

async def run():
    app.run(port=5001)

if __name__ == "__main__":
    from app import app
    from db import db
    from ma import ma

    @app.before_first_request
    def create_tables():
        db.create_all()

    db.init_app(app)
    ma.init_app(app)

    loop = aio.new_event_loop()
    loop.run_until_complete(run())
    try:
        loop.run_forever()
    finally:
        loop.close()

</code>```

but I am not able to access this loop with

```<code>asyncio.get_running_loop() # within a Resource(flask_restful)
</code>```

since app isn't initiallized yet.

How can I get around this?

Also Currently there is an open issue for async support in flask_restful

But still, is there any workaround to make methods (get, put, post, delete) in Resource(flask_restful) async?

Thank you.

[Edit]
PS. Before putting a negative vote please state your reason in comments.

Title: Asyncio with Flask_RESTful

Body:
I need to use asyncio with flask_restful.

Since future is tied to an event loop, I need a single event loop that runs forever and it should be accessible through out the flask app.

#index.py

import asyncio as aio

async def run():
    app.run(port=5001)

if __name__ == "__main__":
    from app import app
    from db import db
    from ma import ma

    @app.before_first_request
    def create_tables():
        db.create_all()

    db.init_app(app)
    ma.init_app(app)

    loop = aio.new_event_loop()
    loop.run_until_complete(run())
    try:
        loop.run_forever()
    finally:
        loop.close()

but I am not able to access this loop with

asyncio.get_running_loop() # within a Resource(flask_restful)

since app isn't initiallized yet.

How can I get around this?

Also Currently there is an open issue for async support in flask_restful

But still, is there any workaround to make methods (get, put, post, delete) in Resource(flask_restful) async?

Thank you.

[Edit]
PS. Before putting a negative vote please state your reason in comments.


问:
Error on Quarkus GRPC proto file import google/api/annonations
Im using GRPC on quarkus framework. There is error appearing when importing google/api/annotations.proto file. Already cloned googleapis project on my local disk and generated a *.pb file with using protoc generator. Maybe there is something wrong with my importing files. Error is still appearing. Help me what am i doing wrong.
Here is how i import
this is error message when run build quarkus dev
I have search lot more examples how does solve it on Quarkus framework. Found nothing proper solution on Quarkus.</p>


问:
Python - How can i show different things depending on the user type
Depending if the login is an "user" or a admin"
How can i make this so it returns a value that i can then use to print different things?
For example if i input a type of login {user} then it should take the user to a menu showing "(welcome user!)", but if the input is an {admin} then it should take the admin to a menu showing "(welcome admin!)</p>
```<code>class Login():

    def grantAccess():
              <<<<<<<<<<<<<<<<<<<<<<<<<<<< define your function here!
    #please print a statements that says ("this is the admins menu!") for the admins and
    #the users print a statements that says ("this is the users menu!")

#checks on mysql is the user exists
    def userExists(id):
        con = connect()
        sqlSelect = f"""SELECT user FROM table WHERE id= "{id}" """
        cursor = con.cursor()
        cursor.execute(sqlSelect)
        cursor.fetchall()
        if cursor.rowcount == 1 :
            #user exists
            return True
        else:
            #does not exist
            return False
    #for the user login
    #check if user and password are correct
    def correctUsLogin(user, password):
        con = connect()
        sqlSelect = f"""SELECT user, password FROM users WHERE user= "{user}" AND BINARY password= "{password}" """
        cursor = con.cursor()
        cursor.execute(sqlSelect)
        cursor.fetchall()
        if cursor.rowcount == 1 :
            #user and password correct
            return True
        else:
            #user or password incorrect
            return False
    #for the admin login
    def corrrectAdLogin(user, password):
        con = connect()
        sqlSelect = f"""SELECT user, password FROM admins WHERE user = "{user}" AND BINARY password = "{password}" """
        cursor = con.cursor()
        cursor.execute(sqlSelect)
        cursor.fetchall()
        if cursor.rowcount == 1 :
            #user and password correct
            return True
        else:
            #user or password incorrect
            return False

    #login
    def userLogin(user, password):
        #serch in db table "users"<<<
        if Login.correctUsLogin(user, password) == True:
        #here it should grant the access to the users menu                      <<<<<<<<<
        Login.grantAccess()
        else:
            print("ERROR, user or password incorrect")
            input("Press a key to continue...")
            os.system("cls")
            Login.start()

    def adminLogin(user, password):
        #serch in db table "admins"<<<
        if Login.corrrectAdLogin(user, password) == True:
        #here it should grant the access to the administrators menu              <<<<<<<<<
            Login.grantAccess()
        else:
            print("ERROR, user or password incorrect")
            input("Press a key to continue......")
            os.system("cls")
            Login.start()

    #depending on the user inputs do...
    def access(opcion):
        if opcion == "1": #for normal user
            print("---Iniciar sesion---")
            id = input("Ingrese el id: ")
            password = input("Ingrese la password: ")
            Login.userLogin(id, password)

        elif opcion == "3": #for admin
            print("---Iniciar sesion---")
            id = input("Ingrese el id: ")
            password = input("Ingrese la password: ")
            Login.adminLogin(id, password)
    #code starts
    def start():
        print('---Museo "Fósiles" de Magallanes---')
        opcion = input("login user(1) / register(2) / login admin(3): ")
        if opcion != "1" and opcion != "2" and opcion != "3":
            print("ERROR, input a correct option")
            input("Press a key to continue......")
            os.system("cls")
            Login.start()
        else:
            Login.access(opcion)

sorry for my shitty code
and there are things that i might have not translated right, english is not my native language
thanks!
</code>```

Body:
Depending if the login is an "user" or a admin"
How can i make this so it returns a value that i can then use to print different things?
For example if i input a type of login {user} then it should take the user to a menu showing "(welcome user!)", but if the input is an {admin} then it should take the admin to a menu showing "(welcome admin!)

class Login():

    def grantAccess():
              <<<<<<<<<<<<<<<<<<<<<<<<<<<< define your function here!
    #please print a statements that says ("this is the admins menu!") for the admins and
    #the users print a statements that says ("this is the users menu!")

#checks on mysql is the user exists
    def userExists(id):
        con = connect()
        sqlSelect = f"""SELECT user FROM table WHERE id= "{id}" """
        cursor = con.cursor()
        cursor.execute(sqlSelect)
        cursor.fetchall()
        if cursor.rowcount == 1 :
            #user exists
            return True
        else:
            #does not exist
            return False
    #for the user login
    #check if user and password are correct
    def correctUsLogin(user, password):
        con = connect()
        sqlSelect = f"""SELECT user, password FROM users WHERE user= "{user}" AND BINARY password= "{password}" """
        cursor = con.cursor()
        cursor.execute(sqlSelect)
        cursor.fetchall()
        if cursor.rowcount == 1 :
            #user and password correct
            return True
        else:
            #user or password incorrect
            return False
    #for the admin login
    def corrrectAdLogin(user, password):
        con = connect()
        sqlSelect = f"""SELECT user, password FROM admins WHERE user = "{user}" AND BINARY password = "{password}" """
        cursor = con.cursor()
        cursor.execute(sqlSelect)
        cursor.fetchall()
        if cursor.rowcount == 1 :
            #user and password correct
            return True
        else:
            #user or password incorrect
            return False

    #login
    def userLogin(user, password):
        #serch in db table "users"<<<
        if Login.correctUsLogin(user, password) == True:
        #here it should grant the access to the users menu                      <<<<<<<<<
        Login.grantAccess()
        else:
            print("ERROR, user or password incorrect")
            input("Press a key to continue...")
            os.system("cls")
            Login.start()

    def adminLogin(user, password):
        #serch in db table "admins"<<<
        if Login.corrrectAdLogin(user, password) == True:
        #here it should grant the access to the administrators menu              <<<<<<<<<
            Login.grantAccess()
        else:
            print("ERROR, user or password incorrect")
            input("Press a key to continue......")
            os.system("cls")
            Login.start()

    #depending on the user inputs do...
    def access(opcion):
        if opcion == "1": #for normal user
            print("---Iniciar sesion---")
            id = input("Ingrese el id: ")
            password = input("Ingrese la password: ")
            Login.userLogin(id, password)

        elif opcion == "3": #for admin
            print("---Iniciar sesion---")
            id = input("Ingrese el id: ")
            password = input("Ingrese la password: ")
            Login.adminLogin(id, password)
    #code starts
    def start():
        print('---Museo "Fósiles" de Magallanes---')
        opcion = input("login user(1) / register(2) / login admin(3): ")
        if opcion != "1" and opcion != "2" and opcion != "3":
            print("ERROR, input a correct option")
            input("Press a key to continue......")
            os.system("cls")
            Login.start()
        else:
            Login.access(opcion)

sorry for my shitty code
and there are things that i might have not translated right, english is not my native language
thanks!


问:
How to prevent job from killing emr cluster
I use AWS EMR Cluster to run some jobs in Jupyter, but I have a job, always I try run the job's steps, the kernel dies. Already tried to filter some rows, but is not possible to filter any longer without get a bad result.
Already tried change persist(pyspark.storagelevel.memory_only) to memory and disk and disk only, in some way the job don't dies in the first join, but not finish the job anyway.

Always dies in joins steps, the tables have a couple columns (6/8) and like 30 millions rows, is not that heavy to kill a kernel.

PS: Already checked the join cardinality, is 1:1


问:
I am having difficulties getting a curve to fit to my data
So I am trying to do a curve fir and than to a chi sqaure test but my my fir is all wrong.

```<code>import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def gauss (x, amp, mu, sigma) :
    return amp*np.exp(-(x-mu)**2/(2*sigma**2))

n, bins, patches = plt.hist(A_pv, bins=100, range= (-4000,4000))
y = n
x = np.linspace(-2500, 2500, 100)
popt, pcov = curve_fit (gauss, x, y, p0= (700,1,650))
y = gauss (x, popt [0],popt [1],popt [2])
plt.plot (x,y, color='r' ,linestyle='dashed')
print(stats.chisquare(A_pv))
print(n.shape)

</code>```

This is my code and the curve fir I get, but it looks wrong. Also, I was wondering how I could then do a chi_sqaured test afterward using my curve when my curve is only 100 while my observed data is 10000.

I tried to fit a normal distribution and get a chi squared value for my curve but couldn't do either correctly.

Body:
So I am trying to do a curve fir and than to a chi sqaure test but my my fir is all wrong.

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def gauss (x, amp, mu, sigma) :
    return amp*np.exp(-(x-mu)**2/(2*sigma**2))

n, bins, patches = plt.hist(A_pv, bins=100, range= (-4000,4000))
y = n
x = np.linspace(-2500, 2500, 100)
popt, pcov = curve_fit (gauss, x, y, p0= (700,1,650))
y = gauss (x, popt [0],popt [1],popt [2])
plt.plot (x,y, color='r' ,linestyle='dashed')
print(stats.chisquare(A_pv))
print(n.shape)

This is my code and the curve fir I get, but it looks wrong. Also, I was wondering how I could then do a chi_sqaured test afterward using my curve when my curve is only 100 while my observed data is 10000.

I tried to fit a normal distribution and get a chi squared value for my curve but couldn't do either correctly.


问:
0 x 0 matrix when using pairwise t test
I am trying to do a post-hoc test to compare different types of a variable (levels of pollution, which are coded as 1, 2 , 3). When I run the tests it gives me a "0 x 0 matrix" error.

```<code>p.none <- (d$pollute = 1)
p.i <- (d$pollute = 2)
p.m <- (d$pollute = 3)
pairwise.t.test(p.none, p.i, p.adj = "none")
pairwise.t.test(p.none, p.m, p.adj = "none")
</code>```

here is the output of dput(d)

```<code>structure(list(tank.id = 1:60, condition = c("hot_species1",
"cool_species1", "cool_species2", "cool_species1", "hot_species1",
"hot_species2", "cool_species2", "hot_species1", "cool_species2",
"cool_species1", "hot_species2", "hot_species1", "hot_species1",
"hot_species1", "cool_species1", "cool_species2", "cool_species2",
"cool_species2", "cool_species1", "hot_species2", "cool_species2",
"cool_species2", "cool_species1", "cool_species1", "hot_species2",
"cool_species1", "hot_species2", "hot_species2", "cool_species2",
"hot_species2", "cool_species2", "hot_species2", "cool_species1",
"hot_species1", "hot_species1", "cool_species1", "hot_species1",
"hot_species2", "hot_species1", "hot_species1", "hot_species1",
"hot_species1", "hot_species2", "cool_species2", "hot_species2",
"cool_species1", "cool_species1", "hot_species2", "hot_species2",
"cool_species2", "cool_species2", "hot_species2", "cool_species1",
"hot_species1", "cool_species2", "cool_species1", "cool_species2",
"hot_species1", "cool_species1", "hot_species2"), pollute = c(2L,
2L, 2L, 3L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 3L, 1L, 1L, 2L, 1L,
2L, 1L, 2L, 3L, 1L, 2L, 3L, 2L, 2L, 3L, 3L, 1L, 2L, 1L, 1L, 1L,
1L, 3L, 1L, 2L, 2L, 3L, 1L, 3L, 1L, 1L, 3L, 3L, 3L, 3L, 1L, 1L,
2L, 3L, 1L, 2L, 2L, 3L, 2L, 1L, 3L, 1L, 3L), temp = c(2L, 1L,
1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L), species = c(1L, 1L,
2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L), light = c(1395L, 1347L,
1408L, 1441L, 1371L, 1331L, 1418L, 1441L, 1407L, 1349L, 1392L,
1365L, 1356L, 1465L, 1435L, 1420L, 1416L, 1364L, 1405L, 1423L,
1411L, 1423L, 1380L, 1469L, 1421L, 1450L, 1412L, 1380L, 1407L,
1416L, 1359L, 1363L, 1450L, 1377L, 1359L, 1412L, 1374L, 1459L,
1371L, 1368L, 1397L, 1353L, 1404L, 1348L, 1395L, 1373L, 1380L,
1440L, 1376L, 1400L, 1351L, 1348L, 1430L, 1432L, 1387L, 1374L,
1388L, 1410L, 1460L, 1388L), density = c(218L, 257L, 227L, 251L,
213L, 161L, 250L, 208L, 222L, 214L, 223L, 244L, 203L, 235L, 241L,
255L, 260L, 210L, 284L, 242L, 252L, 324L, 230L, 229L, 191L, 314L,
218L, 240L, 297L, 228L, 290L, 328L, 321L, 242L, 200L, 269L, 188L,
199L, 244L, 196L, 234L, 128L, 252L, 239L, 250L, 284L, 209L, 305L,
288L, 193L, 201L, 318L, 262L, 222L, 207L, 253L, 295L, 229L, 326L,
162L)), class = "data.frame", row.names = c(NA, -60L))
</code>```

Title: 0 x 0 matrix when using pairwise t test

Body:
I am trying to do a post-hoc test to compare different types of a variable (levels of pollution, which are coded as 1, 2 , 3). When I run the tests it gives me a "0 x 0 matrix" error.

p.none <- (d$pollute = 1)
p.i <- (d$pollute = 2)
p.m <- (d$pollute = 3)
pairwise.t.test(p.none, p.i, p.adj = "none")
pairwise.t.test(p.none, p.m, p.adj = "none")

here is the output of dput(d)

structure(list(tank.id = 1:60, condition = c("hot_species1",
"cool_species1", "cool_species2", "cool_species1", "hot_species1",
"hot_species2", "cool_species2", "hot_species1", "cool_species2",
"cool_species1", "hot_species2", "hot_species1", "hot_species1",
"hot_species1", "cool_species1", "cool_species2", "cool_species2",
"cool_species2", "cool_species1", "hot_species2", "cool_species2",
"cool_species2", "cool_species1", "cool_species1", "hot_species2",
"cool_species1", "hot_species2", "hot_species2", "cool_species2",
"hot_species2", "cool_species2", "hot_species2", "cool_species1",
"hot_species1", "hot_species1", "cool_species1", "hot_species1",
"hot_species2", "hot_species1", "hot_species1", "hot_species1",
"hot_species1", "hot_species2", "cool_species2", "hot_species2",
"cool_species1", "cool_species1", "hot_species2", "hot_species2",
"cool_species2", "cool_species2", "hot_species2", "cool_species1",
"hot_species1", "cool_species2", "cool_species1", "cool_species2",
"hot_species1", "cool_species1", "hot_species2"), pollute = c(2L,
2L, 2L, 3L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 3L, 1L, 1L, 2L, 1L,
2L, 1L, 2L, 3L, 1L, 2L, 3L, 2L, 2L, 3L, 3L, 1L, 2L, 1L, 1L, 1L,
1L, 3L, 1L, 2L, 2L, 3L, 1L, 3L, 1L, 1L, 3L, 3L, 3L, 3L, 1L, 1L,
2L, 3L, 1L, 2L, 2L, 3L, 2L, 1L, 3L, 1L, 3L), temp = c(2L, 1L,
1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L), species = c(1L, 1L,
2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L), light = c(1395L, 1347L,
1408L, 1441L, 1371L, 1331L, 1418L, 1441L, 1407L, 1349L, 1392L,
1365L, 1356L, 1465L, 1435L, 1420L, 1416L, 1364L, 1405L, 1423L,
1411L, 1423L, 1380L, 1469L, 1421L, 1450L, 1412L, 1380L, 1407L,
1416L, 1359L, 1363L, 1450L, 1377L, 1359L, 1412L, 1374L, 1459L,
1371L, 1368L, 1397L, 1353L, 1404L, 1348L, 1395L, 1373L, 1380L,
1440L, 1376L, 1400L, 1351L, 1348L, 1430L, 1432L, 1387L, 1374L,
1388L, 1410L, 1460L, 1388L), density = c(218L, 257L, 227L, 251L,
213L, 161L, 250L, 208L, 222L, 214L, 223L, 244L, 203L, 235L, 241L,
255L, 260L, 210L, 284L, 242L, 252L, 324L, 230L, 229L, 191L, 314L,
218L, 240L, 297L, 228L, 290L, 328L, 321L, 242L, 200L, 269L, 188L,
199L, 244L, 196L, 234L, 128L, 252L, 239L, 250L, 284L, 209L, 305L,
288L, 193L, 201L, 318L, 262L, 222L, 207L, 253L, 295L, 229L, 326L,
162L)), class = "data.frame", row.names = c(NA, -60L))


问:
How do I change the letter spacing of my code?
I know it's just a matter of preferences. But How do you change the letter spacing of your code? WebStorm seems to put little spacings between letters, which is supposed to improve the readability. The thing is, I don't really like the wide letter spacing. Hope you can help me with this matter.</p>


问:
Could not find a version that satisfies the requirement torch python
I am aware that there are a lot of questions on the forum about this kind of question.
But I am sure that this question is different from others.
I tried to install the module torch with pip install torch on cmd (Windows 10) but did not succeed.

```<code>ERROR: Could not find a version that satisfies the requirement torch (from versions: none)
ERROR: No matching distribution found for torch
</code>```

The package was on pypi.org, I had the latest python version, and I did not typed the command wrongly. So what's wrong?

Body:
I am aware that there are a lot of questions on the forum about this kind of question.
But I am sure that this question is different from others.
I tried to install the module torch with pip install torch on cmd (Windows 10) but did not succeed.

ERROR: Could not find a version that satisfies the requirement torch (from versions: none)
ERROR: No matching distribution found for torch

The package was on pypi.org, I had the latest python version, and I did not typed the command wrongly. So what's wrong?


问:
Update table with join vs WHERE in SQL Server
I have a table with 500k rows, and I have a stored procedure in which I have created a temp table which has a column which is equivalent to the primary key of the actual table.

I want to update my table, and I have tried these two ways. I would like to know which one is better in terms of performance.

```<code>UPDATE LRD --Commented By Vivek
SET LRD.Status = 2
FROM Log_ReminderDetail LRD
JOIN @Result R ON LRD.ReminderPK = R.ReminderPK
</code>```

or

```<code>UPDATE Log_ReminderDetail      --Commented By Vivek
SET Status = 2
WHERE ReminderPK IN (SELECT ReminderPK FROM @Result)
</code>```

I don't see any major difference in the execution plan of both.

Body:
I have a table with 500k rows, and I have a stored procedure in which I have created a temp table which has a column which is equivalent to the primary key of the actual table.

I want to update my table, and I have tried these two ways. I would like to know which one is better in terms of performance.

UPDATE LRD --Commented By Vivek
SET LRD.Status = 2
FROM Log_ReminderDetail LRD
JOIN @Result R ON LRD.ReminderPK = R.ReminderPK

or

UPDATE Log_ReminderDetail      --Commented By Vivek
SET Status = 2
WHERE ReminderPK IN (SELECT ReminderPK FROM @Result)

I don't see any major difference in the execution plan of both.


问:
How to constantly poll the server without causing my computer to crash
I am developing the front-end of a multiplayer Tic Tac Toe game and I want to constantly poll the server for the Tic Tac Toe board. The problem is that doing so causes my CPU usage to spike significantly high. Is there a better way to implement this?</p>
```<code>const grabBoard = (async () => {
     if (boardId != null) {
       if (boardData == null) {
         setIsLoaded(false);
       }
       setBoardData(await getBoard(boardId));
     }
   })
   grabBoard()
 }, )
</code>```

Body:
I am developing the front-end of a multiplayer Tic Tac Toe game and I want to constantly poll the server for the Tic Tac Toe board. The problem is that doing so causes my CPU usage to spike significantly high. Is there a better way to implement this?

const grabBoard = (async () => {
     if (boardId != null) {
       if (boardData == null) {
         setIsLoaded(false);
       }
       setBoardData(await getBoard(boardId));
     }
   })
   grabBoard()
 }, )


问:
How can I add this login/registration form as a menu with Easygui in my existing code in Python?
So I want to add this login/registration form as a menu with Easygui in my existing code but I can't figure out how. It needs to be simple. I tried some things with choiceboxes etc but it didn't worked.

My current code:

```<code>active = True

while active:

    username = enterbox(text2, title)

    menu_choice = choicebox(text, title, menu)

    message = "Geselecteerd: " + menu_choice

    room_choice = choicebox(message, title, rooms)

    message = "Geselecteerd: " + room_choice

    day_choice = choicebox(message, title, days)

    message = "Geselecteerd: " + day_choice

    time_choice = choicebox(message, title, times)

    message = "Geselecteerd: " + time_choice

    active = ynbox("Uw afspraak is bevestigd. Wilt u terug gaan naar het hoofdmenu?", title2, button_text)

    with open("reserveringen.txt", "w") as f:
        f.write(f"Personeelsnummer: {username}\n")
        f.write(f"Vergaderruimte: {room_choice}\n")
        f.write(f"Dag: {day_choice}\n")
        f.write(f"Tijd: {time_choice}\n")

        times.remove(time_choice)
</code>```

The login/registration form that I want to add in my current code as a menu (noob friendly):

```<code>def signup():
    email = input("E-mail: ")
    ww = input("Wachtwoord: ")
    bevestig_ww = input("Wachtwoord bevestigen: ")

    if bevestig_ww == ww:
        enc = bevestig_ww.encode()
        hash1 = hashlib.md5(enc).hexdigest()

        with open("gegevens.txt", "w") as f:
             f.write(email + "\n")
             f.write(hash1)
        f.close()

        print("Registratie gelukt!")

    else:
        print("De wachtwoorden komen niet overeen! \n")

def login():
    email = input("E-mail: ")
    ww = input("Wachtwoord: ")

    auth = ww.encode()
    auth_hash = hashlib.md5(auth).hexdigest()
    with open("gegevens.txt", "r") as f:
        stored_email, stored_ww = f.read().split("\n")
    f.close()

    if email == stored_email and auth_hash == stored_ww:
         print("U bent ingelogd!")

    else:
        print("Inloggen mislukt! \n")

while 1:
    print("********** Login System **********")
    print("1.Signup")
    print("2.Login")
    print("3.Exit")
    ch = int(input("Enter your choice: "))
    if ch == 1:
        signup()
    elif ch == 2:
        login()
    elif ch == 3:
        break
    else:
        print("Wrong Choice!")
</code>```

Body:
So I want to add this login/registration form as a menu with Easygui in my existing code but I can't figure out how. It needs to be simple. I tried some things with choiceboxes etc but it didn't worked.

My current code:

active = True

while active:

    username = enterbox(text2, title)

    menu_choice = choicebox(text, title, menu)

    message = "Geselecteerd: " + menu_choice

    room_choice = choicebox(message, title, rooms)

    message = "Geselecteerd: " + room_choice

    day_choice = choicebox(message, title, days)

    message = "Geselecteerd: " + day_choice

    time_choice = choicebox(message, title, times)

    message = "Geselecteerd: " + time_choice

    active = ynbox("Uw afspraak is bevestigd. Wilt u terug gaan naar het hoofdmenu?", title2, button_text)

    with open("reserveringen.txt", "w") as f:
        f.write(f"Personeelsnummer: {username}\n")
        f.write(f"Vergaderruimte: {room_choice}\n")
        f.write(f"Dag: {day_choice}\n")
        f.write(f"Tijd: {time_choice}\n")

        times.remove(time_choice)

The login/registration form that I want to add in my current code as a menu (noob friendly):

def signup():
    email = input("E-mail: ")
    ww = input("Wachtwoord: ")
    bevestig_ww = input("Wachtwoord bevestigen: ")

    if bevestig_ww == ww:
        enc = bevestig_ww.encode()
        hash1 = hashlib.md5(enc).hexdigest()

        with open("gegevens.txt", "w") as f:
             f.write(email + "\n")
             f.write(hash1)
        f.close()

        print("Registratie gelukt!")

    else:
        print("De wachtwoorden komen niet overeen! \n")

def login():
    email = input("E-mail: ")
    ww = input("Wachtwoord: ")

    auth = ww.encode()
    auth_hash = hashlib.md5(auth).hexdigest()
    with open("gegevens.txt", "r") as f:
        stored_email, stored_ww = f.read().split("\n")
    f.close()

    if email == stored_email and auth_hash == stored_ww:
         print("U bent ingelogd!")

    else:
        print("Inloggen mislukt! \n")

while 1:
    print("********** Login System **********")
    print("1.Signup")
    print("2.Login")
    print("3.Exit")
    ch = int(input("Enter your choice: "))
    if ch == 1:
        signup()
    elif ch == 2:
        login()
    elif ch == 3:
        break
    else:
        print("Wrong Choice!")


问:
Spring thread per model
I have simple setup spring web like the following

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

And here is my controller

```<code>@RestController
@RequestMapping("v1/thread-model")
@CrossOrigin
public class ProductController {
    Logger logger = LoggerFactory.getLogger(ProductController.class);
    @GetMapping
    private String getSingleProductModel() {
        long current = System.currentTimeMillis();
        String msg = "Core: " + Runtime.getRuntime().availableProcessors() + " | Current thread name: " + Thread.currentThread().getName();
        // System.out.println(msg);
        logger.info(msg);
        while(System.currentTimeMillis() < current + 20000) {}
        return "thread model";
    }
}
</code>```

Then when I call 3 requests from javascript

```<code>for(let i = 0; i < 3; i++) {
    fetch("http://localhost:8080/v1/thread-model")
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));
}
</code>```

I would expect it will print down 3 messages at most the same time from my API but in fact it just print one message then 20s later it print two rest message

```<code>2022-12-12 11:17:39.274  INFO 1155 --- [nio-8080-exec-1] c.m.t.controller.ProductController       : Core: 8 | Current thread name: http-nio-8080-exec-1
2022-12-12 11:17:59.210  INFO 1155 --- [nio-8080-exec-3] c.m.t.controller.ProductController       : Core: 8 | Current thread name: http-nio-8080-exec-3
2022-12-12 11:17:59.210  INFO 1155 --- [nio-8080-exec-2] c.m.t.controller.ProductController       : Core: 8 | Current thread name: http-nio-8080-exec-2
</code>```

Something wrong from myside? Why does is behave like this?

Title: Spring thread per model

Body:
I have simple setup spring web like the following

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

And here is my controller

@RestController
@RequestMapping("v1/thread-model")
@CrossOrigin
public class ProductController {
    Logger logger = LoggerFactory.getLogger(ProductController.class);
    @GetMapping
    private String getSingleProductModel() {
        long current = System.currentTimeMillis();
        String msg = "Core: " + Runtime.getRuntime().availableProcessors() + " | Current thread name: " + Thread.currentThread().getName();
        // System.out.println(msg);
        logger.info(msg);
        while(System.currentTimeMillis() < current + 20000) {}
        return "thread model";
    }
}

Then when I call 3 requests from javascript

for(let i = 0; i < 3; i++) {
    fetch("http://localhost:8080/v1/thread-model")
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));
}

I would expect it will print down 3 messages at most the same time from my API but in fact it just print one message then 20s later it print two rest message

2022-12-12 11:17:39.274  INFO 1155 --- [nio-8080-exec-1] c.m.t.controller.ProductController       : Core: 8 | Current thread name: http-nio-8080-exec-1
2022-12-12 11:17:59.210  INFO 1155 --- [nio-8080-exec-3] c.m.t.controller.ProductController       : Core: 8 | Current thread name: http-nio-8080-exec-3
2022-12-12 11:17:59.210  INFO 1155 --- [nio-8080-exec-2] c.m.t.controller.ProductController       : Core: 8 | Current thread name: http-nio-8080-exec-2

Something wrong from myside? Why does is behave like this?


问:
How to write custom validation for this mentioned validation criteria in Laravel 9
I am trying to achieve certain laravel validation criteria which I am having hard time to implement. Please help me in the same. I am using laravel 9 & PHP 8.1

Description:

I have an API which has below mentioned inputs:

a. company_name - required

b. company_number - required as per condition

c. gst_number - required as per condition

d. county - required

e. state - required as per condition

f. source - required

//Scenario #1 - Small intro into Field Condition

where 'company_number' and 'gst_number' are 2 parameter which change from:

a. where both are not required at all

b. where either one of the field being required

c. to one of the either field being mandatory

based on source value entered.

//Scenario #1 - Detailed intro into Field Condition

a. If its source 1 then neither of them is required

b. If its source 2 then either one of them is required but not both & if both are present then it should throw validation error

c. If its any other source value then it should be company_number only and if other one is present then it show validation error

d. Unwanted field should throw validation error

//Scenario #2 - Country State Validation

a. There are 3 countries i.e. x,y,z in which state field is required else not & it should throw validation error if someone mentions it when not required

b. It should validate if the state mentioned belongs to that country or not. I have that state array list of those 3 countries

c. Here country & state are of 2 character in length which is ISO format, thus it should be of 2 digit only & in upper case only.

d. It should properly validate in both the cases of where the state is required & not required when state field is mentioned with blank value.

Now I know the Scenario #2, point 'c' can be done via regex but my main point is how to achieve all this with the all scenario points mentioned such that if all the points of both the scenarios fail then it should that many validation errors together.

//Example #1:

```<code>company_name:    //blank
company_number: 123
gst_number: 456 //This field is not required as per source value, thus it should throw validation error
country: AB   //Country in which state is not required, thus state not required validation should be triggered
state: cde    //This should trigger uppercase only validation & 2 char only validation
source: 3

//Intended output #1:
{
    "status": false,
    "status_code": 400,
    "message": "Request validation error.",
    "company_name": [
        [
            "Please enter company name."
        ]
    ],
    "gst_number": [
        [
            "gst_number is not required in this case"
        ]
    ],
    "state": [
        [
            "State is not required with this country value",
            "State should be of 2 characters only",
            "State should be in capital letters only"
        ]
    ]
}
</code>```

//Example #2:

```<code>company_name: ABC
company_number: //Blank
gst_number:   //Blank
country: AB   //Valid
state: CD    //Valid
source: 2

//Intended output #2:
{
    "status": false,
    "status_code": 400,
    "message": "Request validation error.",
    "company_name": [
        [
            "Please enter either company name or gst_number"
        ]
    ],
    "gst_number": [
        [
            "Please enter either company name or gst_number"
        ]
    ],
    "state": [
        [
            "State is not required with this country value",
            "State should be of 2 characters only",
            "State should be in capital letters only"
        ]
    ]
}
</code>```

//My Problem:

I am facing problem implementing country state mapping validation including its length & casing check. Is it valid country & state or not? Is it the country which can have state value?

Enabling, disabling the company number, gst_number validation depending upon source value.

//My current validation rule:

```<code>$rule = [
      'company_name' => ['required'],
      'country' => ['required', 'string', 'regex:/^[A-Z]{2}+$/', 'exists:table_name,field_name'],
      'company_number'=> ['required_without:gst_number'],
      'gst_number' => ['required_without:company_number', 'regex:/^([0-9]{2}[a-zA-z]{5}[0-9]{4}[a-zA-z]{1}[0-9]{1}Z{1}[0-9A-Za-z]{1})$/'],
      'state' => ['sometimes','regex:/^[A-Z]{2}+$/'],
      'source' => ['required', 'numeric', 'exists:table_name,field_name'],
];
</code>```

Regarding custom validation, I know the commands & how to get started but as I have never used it, it will be helpful if someone gives me example of using it with respective the validation criteria mentioned in this post.

Body:
I am trying to achieve certain laravel validation criteria which I am having hard time to implement. Please help me in the same. I am using laravel 9 & PHP 8.1

Description:

I have an API which has below mentioned inputs:

a. company_name - required

b. company_number - required as per condition

c. gst_number - required as per condition

d. county - required

e. state - required as per condition

f. source - required

//Scenario #1 - Small intro into Field Condition

where 'company_number' and 'gst_number' are 2 parameter which change from:

a. where both are not required at all

b. where either one of the field being required

c. to one of the either field being mandatory

based on source value entered.

//Scenario #1 - Detailed intro into Field Condition

a. If its source 1 then neither of them is required

b. If its source 2 then either one of them is required but not both & if both are present then it should throw validation error

c. If its any other source value then it should be company_number only and if other one is present then it show validation error

d. Unwanted field should throw validation error

//Scenario #2 - Country State Validation

a. There are 3 countries i.e. x,y,z in which state field is required else not & it should throw validation error if someone mentions it when not required

b. It should validate if the state mentioned belongs to that country or not. I have that state array list of those 3 countries

c. Here country & state are of 2 character in length which is ISO format, thus it should be of 2 digit only & in upper case only.

d. It should properly validate in both the cases of where the state is required & not required when state field is mentioned with blank value.

Now I know the Scenario #2, point 'c' can be done via regex but my main point is how to achieve all this with the all scenario points mentioned such that if all the points of both the scenarios fail then it should that many validation errors together.

//Example #1:

company_name:    //blank
company_number: 123
gst_number: 456 //This field is not required as per source value, thus it should throw validation error
country: AB   //Country in which state is not required, thus state not required validation should be triggered
state: cde    //This should trigger uppercase only validation & 2 char only validation
source: 3

//Intended output #1:
{
    "status": false,
    "status_code": 400,
    "message": "Request validation error.",
    "company_name": [
        [
            "Please enter company name."
        ]
    ],
    "gst_number": [
        [
            "gst_number is not required in this case"
        ]
    ],
    "state": [
        [
            "State is not required with this country value",
            "State should be of 2 characters only",
            "State should be in capital letters only"
        ]
    ]
}

//Example #2:

company_name: ABC
company_number: //Blank
gst_number:   //Blank
country: AB   //Valid
state: CD    //Valid
source: 2

//Intended output #2:
{
    "status": false,
    "status_code": 400,
    "message": "Request validation error.",
    "company_name": [
        [
            "Please enter either company name or gst_number"
        ]
    ],
    "gst_number": [
        [
            "Please enter either company name or gst_number"
        ]
    ],
    "state": [
        [
            "State is not required with this country value",
            "State should be of 2 characters only",
            "State should be in capital letters only"
        ]
    ]
}

//My Problem:

I am facing problem implementing country state mapping validation including its length & casing check. Is it valid country & state or not? Is it the country which can have state value?

Enabling, disabling the company number, gst_number validation depending upon source value.

//My current validation rule:

$rule = [
      'company_name' => ['required'],
      'country' => ['required', 'string', 'regex:/^[A-Z]{2}+$/', 'exists:table_name,field_name'],
      'company_number'=> ['required_without:gst_number'],
      'gst_number' => ['required_without:company_number', 'regex:/^([0-9]{2}[a-zA-z]{5}[0-9]{4}[a-zA-z]{1}[0-9]{1}Z{1}[0-9A-Za-z]{1})$/'],
      'state' => ['sometimes','regex:/^[A-Z]{2}+$/'],
      'source' => ['required', 'numeric', 'exists:table_name,field_name'],
];

Regarding custom validation, I know the commands & how to get started but as I have never used it, it will be helpful if someone gives me example of using it with respective the validation criteria mentioned in this post.


问:
How to run python commands in vscode
I'm using mac air m2 now and I'm trying to use python in vscode. I downloaded python from vscode, created a file called 1.py, and entered the command 1 + 1

```<code>[Running] python -u "/Applications/securety/programming/Python coding/1.py"
/bin/sh: python: command not found

[Done] exited with code=127 in 0.009 seconds
</code>```

got this error

How can I fix the error?

I also downloaded python and python extension pack from vs code

Title: How to run python commands in vscode

Body:
I'm using mac air m2 now and I'm trying to use python in vscode. I downloaded python from vscode, created a file called 1.py, and entered the command 1 + 1

[Running] python -u "/Applications/securety/programming/Python coding/1.py"
/bin/sh: python: command not found

[Done] exited with code=127 in 0.009 seconds

got this error

How can I fix the error?

I also downloaded python and python extension pack from vs code


问:
Converting CNG RSA key pair to string and vice versa
I have started working on Windows CNG APIs. I am generating RSA keypair using

```<code>
BCRYPT_ALG_HANDLE alg;
BCryptOpenAlgorithmProvider(out alg, BCRYPT_RSA_ALGORITHM, null, 0);

BCRYPT_KEY_HANDLE key;
BCryptGenerateKeyPair(alg, out key, 2048, 0);

BCryptFinalizeKeyPair(key, 0); //finalize the key so we can use it

DWORD publicKeySize;
BCryptExportKey(key, 0, BCRYPT_RSAPUBLIC_BLOB, null, 0, &publicKeySize, 0);

PUCHAR publicKey= new UCHAR[publicKeySize];
BCryptExportKey(key, 0, BCRYPT_RSAPUBLIC_BLOB, publicKey, publicKeySize, &publicKeySize, 0);
</code>```

The publicKey buffer receives a BCRYPT_RSAKEY_BLOB structure and I am looking for ways to convert this public key (similarly private key) into PKCS#8 PEM string format like -

```<code>-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBqPgVATKFjTkdJfYBrlBvG
baD/LT8Q8WpHJf/FElNo2gL5rriaq/35suCIZxR7N+gdfvr2jCkwKhIDjhlvaUD/
CisvViDJXUEwzsPCPII6Qh5Q75YT3k+qvro06QOtWAo03Sa43lNY74zMgUQrgoog
C+5X1Cszzef40JRUqvctEBshIr02oazk5Mfgm2KoiVUjWl47OeUltL6Fy7jWIkv2
cFo4UabwtvG9gYOovi6svDYs0Z32pVKIOYM0tJ5rzeJd4zibe3JqzlNGWFVok0xg
FRJlVS1zAA73ugFJqr2lzJIaTIQfrPReSSIYpm7i0p/+FEzf9RzWwHuhGN/RR+El
AgMBAAE=
-----END PUBLIC KEY-----
</code>```

The reasons I want to convert key pair to string are: -

I want to save this key pair (in encrypted format) on some server for roaming purpose.

I want to use this key-pair on other platforms using their native crypto library like Apple crypto library, WebCrypto API etc.

Please guide me if there is any standard way to do that, or if there is already a standard library on top of CNG that handles this.

Body:
I have started working on Windows CNG APIs. I am generating RSA keypair using

BCRYPT_ALG_HANDLE alg;
BCryptOpenAlgorithmProvider(out alg, BCRYPT_RSA_ALGORITHM, null, 0);

BCRYPT_KEY_HANDLE key;
BCryptGenerateKeyPair(alg, out key, 2048, 0);

BCryptFinalizeKeyPair(key, 0); //finalize the key so we can use it

DWORD publicKeySize;
BCryptExportKey(key, 0, BCRYPT_RSAPUBLIC_BLOB, null, 0, &publicKeySize, 0);

PUCHAR publicKey= new UCHAR[publicKeySize];
BCryptExportKey(key, 0, BCRYPT_RSAPUBLIC_BLOB, publicKey, publicKeySize, &publicKeySize, 0);

The publicKey buffer receives a BCRYPT_RSAKEY_BLOB structure and I am looking for ways to convert this public key (similarly private key) into PKCS#8 PEM string format like -

-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBqPgVATKFjTkdJfYBrlBvG
baD/LT8Q8WpHJf/FElNo2gL5rriaq/35suCIZxR7N+gdfvr2jCkwKhIDjhlvaUD/
CisvViDJXUEwzsPCPII6Qh5Q75YT3k+qvro06QOtWAo03Sa43lNY74zMgUQrgoog
C+5X1Cszzef40JRUqvctEBshIr02oazk5Mfgm2KoiVUjWl47OeUltL6Fy7jWIkv2
cFo4UabwtvG9gYOovi6svDYs0Z32pVKIOYM0tJ5rzeJd4zibe3JqzlNGWFVok0xg
FRJlVS1zAA73ugFJqr2lzJIaTIQfrPReSSIYpm7i0p/+FEzf9RzWwHuhGN/RR+El
AgMBAAE=
-----END PUBLIC KEY-----

The reasons I want to convert key pair to string are: -

I want to save this key pair (in encrypted format) on some server for roaming purpose.

I want to use this key-pair on other platforms using their native crypto library like Apple crypto library, WebCrypto API etc.

Please guide me if there is any standard way to do that, or if there is already a standard library on top of CNG that handles this.


问:
SpringBoot - Micrometer Composite Registry order changes behavior of /actuator/metrics/ page
I have three micrometer registries created as beans

```<code>0 = {InfluxMeterRegistry@7201}
1 = {AutoConfiguredCompositeMeterRegistry@7339}
2 = {PrometheusMeterRegistry@7330}
</code>```

One of my classes gets injected with the @Primary MeterRegistry (AutoConfiguredCompositeMeterRegistry) . During operation of the application a counter is incremented like so

```<code> Counter.builder("cmp.listener.dispatch.count")
      .tags(commonTags)
      .tag("success", "false")
      .description("Count off failed dispatch by event listener")
      .baseUnit("event")
      .tag("uri", uri)
      .register(meterRegistry).increment();
</code>```

I noticed that the metrics do in-fact get published to their corresponding registries (influx, prometheus). However, on the actuator page /actuator/metrics/cmp.listener.dispatch.count
the counts get reset periodically, almost as if they behave like StepCounter not CumulativeCounter

Sometimes a change in the order of the micrometer registry beans    makes /actuator/metrics/cmp.listener.dispatch.count behave like a CumulativeCounter.

I am super confused - Order should not matter.
Where is the page /actuator/metrics/cmp.listener.dispatch.count getting its metrics from? What am I doing wrong.

Its almost as if InfluxMetricsRegistry wins and makes all counters StepCounters

Looking at the source for MetricEndpoint.java, it streams through the registries in CompositeMeterRegistry and finds the first metric that matches desired name. Which mean the order of Registries matter. However the order of registries is not deterministic since internally the CompositeMeterRegistry stores registries in the IdentityHashMap.

```<code>private volatile Set<CompositeMeterRegistry> parents = Collections.newSetFromMap(new IdentityHashMap<>());
</code>```

So if the MetricEndpoint find first a metric counter from the InfluxRegistry, /metrics endpoint Counters will behave like step counters. If it finds metric in the SimpleMetricRegistry it will behave like CumulativeCounter counter

Body:
I have three micrometer registries created as beans

0 = {InfluxMeterRegistry@7201}
1 = {AutoConfiguredCompositeMeterRegistry@7339}
2 = {PrometheusMeterRegistry@7330}

One of my classes gets injected with the @Primary MeterRegistry (AutoConfiguredCompositeMeterRegistry) . During operation of the application a counter is incremented like so

 Counter.builder("cmp.listener.dispatch.count")
      .tags(commonTags)
      .tag("success", "false")
      .description("Count off failed dispatch by event listener")
      .baseUnit("event")
      .tag("uri", uri)
      .register(meterRegistry).increment();

I noticed that the metrics do in-fact get published to their corresponding registries (influx, prometheus). However, on the actuator page /actuator/metrics/cmp.listener.dispatch.count
the counts get reset periodically, almost as if they behave like StepCounter not CumulativeCounter

Sometimes a change in the order of the micrometer registry beans    makes /actuator/metrics/cmp.listener.dispatch.count behave like a CumulativeCounter.

I am super confused - Order should not matter.
Where is the page /actuator/metrics/cmp.listener.dispatch.count getting its metrics from? What am I doing wrong.

Its almost as if InfluxMetricsRegistry wins and makes all counters StepCounters

Looking at the source for MetricEndpoint.java, it streams through the registries in CompositeMeterRegistry and finds the first metric that matches desired name. Which mean the order of Registries matter. However the order of registries is not deterministic since internally the CompositeMeterRegistry stores registries in the IdentityHashMap.

private volatile Set<CompositeMeterRegistry> parents = Collections.newSetFromMap(new IdentityHashMap<>());

So if the MetricEndpoint find first a metric counter from the InfluxRegistry, /metrics endpoint Counters will behave like step counters. If it finds metric in the SimpleMetricRegistry it will behave like CumulativeCounter counter


问:
How to add class method dynamically through constructor (PHP). N.B: I do not need method in object (ex: $this->$methodName). not like that
```<code>    /**
     * @return string
     */
    public function getCityIdEncryptedAttribute(): string
    {
        return encrypt($this->city_id);
    }
</code>```

I want to generate this method dynamically in the class. not in the object.

```<code>function __construct ($field)
{
     $methodName = $this->_generateMethodName($field);
     $this->{$methodName} = function () use ($field) {
        return encrypt($this->$field);
     };
}

/**
 * @param string $string
 * @return string
 */
private function _generateMethodName(string $string): string//abc_id
{
    $string = str_replace('_', ' ', $string); //abc id
    $string = ucwords($string);//Abd Id
    $string = str_replace(' ', '', $string);//AbcId
    return "get{$string}EncryptedAttribute";
}
</code>```

This approach is giving me getCityIdEncryptedAttribute() method to the object, not to the class.

Body:
    /**
     * @return string
     */
    public function getCityIdEncryptedAttribute(): string
    {
        return encrypt($this->city_id);
    }

I want to generate this method dynamically in the class. not in the object.

function __construct ($field)
{
     $methodName = $this->_generateMethodName($field);
     $this->{$methodName} = function () use ($field) {
        return encrypt($this->$field);
     };
}

/**
 * @param string $string
 * @return string
 */
private function _generateMethodName(string $string): string//abc_id
{
    $string = str_replace('_', ' ', $string); //abc id
    $string = ucwords($string);//Abd Id
    $string = str_replace(' ', '', $string);//AbcId
    return "get{$string}EncryptedAttribute";
}

This approach is giving me getCityIdEncryptedAttribute() method to the object, not to the class.