问:
How can I get this JavaScript to correctly decorate button links on Unbounced landing pages for Google's Cross-Domain Measurement?
I am using a service called Unbounced for my website landing pages. They wrap the CTA buttons on the landing pages, making them indirectly go to their destination.

For example, my CTA button first goes here:

https://www.axelgo.app/drs/clkn/https/go.axel.network/#/signup
...and then redirects to here:

https://go.axel.network/signup

This wouldn't be an issue, except Google's Cross-Domain Measurement works by decorating outbound clicks to pre-specified domains with an '_gl' parameter. Since this link is technically an internal one (axelgo.app) that redirects to the external domain (go.axel.network), it doesn't get decorated.

For another example, this is my expected result when clicking the CTA button:

https://go.axel.network/?_gl=1\*1x93dka\*_ga\*Njk2OTU0MTU1LjE2NjQyMjc5NjA.\*_ga_4YJDRFJTFE*MTY3Mjc2MzMwNC40NC4wLjE2NzI3NjMzMDQuMC4wLjA.signup

...but my result due to the wrapping behavior isthis: https://go.axel.network/signup

I've been playing around with some scripts I found here and here. I'll share these below. They do not work in my case though, and I believe it is because these may have been intended for form submissions and not button clicks? I'm not exactly sure as I don't know much JavaScript.

Here's the code I found of other people working through similar problems:

Example 1:

```<code><script>
  function decorateUrl(urlString) {
    var ga = window[window['GoogleAnalyticsObject']];
    var tracker;
    if (ga && typeof ga.getAll === 'function') {
      tracker = ga.getAll()[0]; // Uses the first tracker created on the page
      urlString = (new window.gaplugins.Linker(tracker)).decorate(urlString);
    }
    return urlString;
  }

  function linkDecorator(){
    if (window.module.lp.form.data.action === 'url') {
      window.module.lp.form.data.url = decorateUrl(window.module.lp.form.data.url)}
  };

  if (document.querySelector('.lp-element.lp-pom-button')) {
    document.querySelector('.lp-element.lp-pom-button').addEventListener('click', linkDecorator);
  }
</script>
</code>```

Example 2:

```<code><script>
  $('.lp-pom-button, .lp-pom-text a, .lp-pom-image a').click(function(event) {
    var parentClass = $(this).parent().attr('class');

    var isFormRedirect =
      parentClass === 'lp-element lp-pom-form' &&
      window.module.lp.form.data.confirmAction === 'url' &&
      lp.jQuery('form').valid() === true;

    if (isFormRedirect) {
      ga(function(tracker) {
        var linker = new window.gaplugins.Linker(tracker);
        window.module.lp.form.data.confirmData = linker.decorate(window.module.lp.form.data.confirmData);
      });
    } else {
      ga('linker:decorate', this);
    }
  });
</script>
</code>```

again, these are not functional when I tried applying them. I don't think they were made for my use case.

Thanks in advance for any support.

Edit: here's a landing page: https://www.axelgo.app/drs/

Body:
I am using a service called Unbounced for my website landing pages. They wrap the CTA buttons on the landing pages, making them indirectly go to their destination.

For example, my CTA button first goes here:

https://www.axelgo.app/drs/clkn/https/go.axel.network/#/signup
...and then redirects to here:

https://go.axel.network/signup

This wouldn't be an issue, except Google's Cross-Domain Measurement works by decorating outbound clicks to pre-specified domains with an '_gl' parameter. Since this link is technically an internal one (axelgo.app) that redirects to the external domain (go.axel.network), it doesn't get decorated.

For another example, this is my expected result when clicking the CTA button:

https://go.axel.network/?_gl=1\*1x93dka\*_ga\*Njk2OTU0MTU1LjE2NjQyMjc5NjA.\*_ga_4YJDRFJTFE*MTY3Mjc2MzMwNC40NC4wLjE2NzI3NjMzMDQuMC4wLjA.signup

...but my result due to the wrapping behavior isthis: https://go.axel.network/signup

I've been playing around with some scripts I found here and here. I'll share these below. They do not work in my case though, and I believe it is because these may have been intended for form submissions and not button clicks? I'm not exactly sure as I don't know much JavaScript.

Here's the code I found of other people working through similar problems:

Example 1:

Example 2:

again, these are not functional when I tried applying them. I don't think they were made for my use case.

Thanks in advance for any support.

Edit: here's a landing page: https://www.axelgo.app/drs/


来源: stackexchange

问:
tkinter: How to have a treeview divided into sections with each section having different columns
I am currently working on adding data from a stored procedure into a dataframe and then outputting the dataframe to a treeview. The columns headers for each query that is run within the stored procedure are different and I have 4 queries running within the stored procedure. I was wondering if there is any way to have it so that once one of the queries data has been printed to the treeview, I can display the next query with its columns headers below the one that came before it. I have attached an image below to give an idea of what I am looking for. If there is a better approach to this I am open to new ideas since I am fairly new to tkinter.

ContentLicense: CC BY-SA 4.0


问:
How to add bootstrap theme to a treeview?
I created a basic UI with tkinter. Applied bootstrap to everything. Everything is working fine except the treeview widget. It is still not getting the styling of the bootstrap theme.

I tried style.configure() method, bootstyle attribute and all, still not working.
(PS: still very much of beginner in the field , so forgive me for my mistakes)

```<code>from tkinter import *
from tkinter import ttk
import mysql.connector
from datetime import date
import ttkbootstrap as tb

def custview():
    temp = tb.Window(themename="darkly")
    temp.title('Customers')
    tree1 = tb.Treeview(temp, column=(
        "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9","c10"), show='headings',bootstyle="info")
    tree1.column("#1", anchor=CENTER, stretch=NO, width=50)
    tree1.heading("#1", text="CID")
    tree1.column("#2", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#2", text="Name")
    tree1.column("#3", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#3", text="Mobile number")
    tree1.column("#4", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#4", text="Address")
    tree1.column("#5", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#5", text="Proof")
    tree1.column("#6", anchor=CENTER, stretch=NO, width=100)
    tree1.heading("#6", text="Payment")
    tree1.column("#7", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#7", text="Checkin")
    tree1.column("#8", anchor=CENTER, stretch=NO, width=100)
    tree1.heading("#8", text="No. of days")
    tree1.column("#9", anchor=CENTER, stretch=NO, width=100)
    tree1.heading("#9", text="Cost")
    tree1.column("#10", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#10", text="Room no")

    tree1.grid(row=0, column=0, padx=(20, 20), pady=(30, 30))

    my_conn.execute("select cust.cid,name,mob,addr,proof,payment,checkin,days,cost,rno from cust,occup where cust.cid=occup.cid")
    rows = my_conn.fetchall()
    for row in rows:
        tree1.insert("", END, values=row)
    exit = Button(temp, text="Close", width=20, command=temp.destroy)
    exit.grid(row=1, column=0, padx=(20, 20), pady=(30, 30))
</code>```

Body:
I created a basic UI with tkinter. Applied bootstrap to everything. Everything is working fine except the treeview widget. It is still not getting the styling of the bootstrap theme.

I tried style.configure() method, bootstyle attribute and all, still not working.
(PS: still very much of beginner in the field , so forgive me for my mistakes)

from tkinter import *
from tkinter import ttk
import mysql.connector
from datetime import date
import ttkbootstrap as tb

def custview():
    temp = tb.Window(themename="darkly")
    temp.title('Customers')
    tree1 = tb.Treeview(temp, column=(
        "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9","c10"), show='headings',bootstyle="info")
    tree1.column("#1", anchor=CENTER, stretch=NO, width=50)
    tree1.heading("#1", text="CID")
    tree1.column("#2", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#2", text="Name")
    tree1.column("#3", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#3", text="Mobile number")
    tree1.column("#4", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#4", text="Address")
    tree1.column("#5", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#5", text="Proof")
    tree1.column("#6", anchor=CENTER, stretch=NO, width=100)
    tree1.heading("#6", text="Payment")
    tree1.column("#7", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#7", text="Checkin")
    tree1.column("#8", anchor=CENTER, stretch=NO, width=100)
    tree1.heading("#8", text="No. of days")
    tree1.column("#9", anchor=CENTER, stretch=NO, width=100)
    tree1.heading("#9", text="Cost")
    tree1.column("#10", anchor=CENTER, stretch=NO, width=150)
    tree1.heading("#10", text="Room no")

    tree1.grid(row=0, column=0, padx=(20, 20), pady=(30, 30))

    my_conn.execute("select cust.cid,name,mob,addr,proof,payment,checkin,days,cost,rno from cust,occup where cust.cid=occup.cid")
    rows = my_conn.fetchall()
    for row in rows:
        tree1.insert("", END, values=row)
    exit = Button(temp, text="Close", width=20, command=temp.destroy)
    exit.grid(row=1, column=0, padx=(20, 20), pady=(30, 30))


问:
How to get declaring KtFile/KtClass using KtCallExpression?
I'm using kotlin compiler to analyze kotlin source file and I need to get where the method is defined using KtCallExpression.
KtCallExpression in question is retrieved from method call.

For better explanation, here's example, if there's source file named Main.kt with contents:

fun main() {
    f1()
    Test.f2()
}

fun f1() {
}

class Test {
    companion object {
        fun f2() {
        }
    }
}
```

when analyzing function main, it will produce 2 KtCallExpression, one for f1() and other for f2()
However I'm not sure how to get file Main.kt from KtCallExpression for f1(), or class Test from KtCallExpression for f2()

I tried to look for its documentations, however Kotlin compiler doesn't contain enough docs. I've also tried bunch of auto completion suggested by Intellij Idea but none of those doesn't seem to lead me to original declaration.

Body:
I'm using kotlin compiler to analyze kotlin source file and I need to get where the method is defined using KtCallExpression.
KtCallExpression in question is retrieved from method call.

For better explanation, here's example, if there's source file named Main.kt with contents:

fun main() {
    f1()
    Test.f2()
}

fun f1() {
}

class Test {
    companion object {
        fun f2() {
        }
    }
}

when analyzing function main, it will produce 2 KtCallExpression, one for f1() and other for f2()
However I'm not sure how to get file Main.kt from KtCallExpression for f1(), or class Test from KtCallExpression for f2()

I tried to look for its documentations, however Kotlin compiler doesn't contain enough docs. I've also tried bunch of auto completion suggested by Intellij Idea but none of those doesn't seem to lead me to original declaration.


问:
Android application Apple sign-in failed with API_KEY_ANDROID_APP_BLOCKED Error
I have implanted Apple sign-in as a social login sign-in option to an Android application on mine. When I try the feature web view displays the following error.

```<code>    {
  "error": {
    "code": 403,
    "message": "Requests from this Android client application <empty> are blocked.",
    "errors": [
      {
        "message": "Requests from this Android client application <empty> are blocked.",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "API_KEY_ANDROID_APP_BLOCKED",
        "domain": "googleapis.com",
        "metadata": {
          "consumer": "projects/736077706434",
          "service": "identitytoolkit.googleapis.com"
        }
      }
    ]
  }
}
</code>```

By looking at this error it seems like the issue is in one of the keys we use for this implementation. But I have check the 4 keys (Services ID, Apple team ID, Key ID, and Private key) that need to provide to the google cloud API config. There is no mismatch. There is a Return URL that need to provide in google cloud API side and in Apple Console side. This is also the same.

Another weird thing is even though it takes so long to load the Apple sign-in web view when I run the application using android studio I was able to sign in to the application. Above error is only visible on the application that I have uploaded to the Google Play internal test. But In both builds, it takes around 2min to load the Apple sign-in WebView. So there must be something going wrong.

Please let me know where should I look into fix this issue.

Body:
I have implanted Apple sign-in as a social login sign-in option to an Android application on mine. When I try the feature web view displays the following error.

    {
  "error": {
    "code": 403,
    "message": "Requests from this Android client application <empty> are blocked.",
    "errors": [
      {
        "message": "Requests from this Android client application <empty> are blocked.",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "API_KEY_ANDROID_APP_BLOCKED",
        "domain": "googleapis.com",
        "metadata": {
          "consumer": "projects/736077706434",
          "service": "identitytoolkit.googleapis.com"
        }
      }
    ]
  }
}

By looking at this error it seems like the issue is in one of the keys we use for this implementation. But I have check the 4 keys (Services ID, Apple team ID, Key ID, and Private key) that need to provide to the google cloud API config. There is no mismatch. There is a Return URL that need to provide in google cloud API side and in Apple Console side. This is also the same.

Another weird thing is even though it takes so long to load the Apple sign-in web view when I run the application using android studio I was able to sign in to the application. Above error is only visible on the application that I have uploaded to the Google Play internal test. But In both builds, it takes around 2min to load the Apple sign-in WebView. So there must be something going wrong.

Please let me know where should I look into fix this issue.


问:
MEAN Stack setting input values from DB
I'm making a little preparations for my MEAN stack exam.
I've built a sort of a To Do list.
I have an update component and I want to set the values in the inputs from the database (Using mongoose).

HTML Component:

```<code><div>
<label>Task Description: </label>
<input type="text" name="task" [(ngModel)]="task.task" />

<label>Date & Time: </label>
<input type="datetime-local" name="dateTime" [(ngModel)]="task.dateTimeCreated" />

<label>Customer: </label>
<select name="customerId" [(ngModel)]="task.customerId" (change)="send()">
    <option selected disabled value="">Select Customer</option>
    <option *ngFor="let c of customers" value={{c._id}}>{{c.name}}</option>
</select>
</code>```

ts component:

```<code>import { Component, Input, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { CustomerModel } from 'src/app/models/customer-model';
import { TaskModel } from 'src/app/models/task-model';
import { DataService } from 'src/app/services/data.service';
import { NotyfService } from 'src/app/services/notyf.service';

@Component({
  selector: 'app-update',
  templateUrl: './update.component.html',
  styleUrls: ['./update.component.css']
  })
export class UpdateComponent implements OnInit {

  // @Input()
  // public task: TaskModel;
  public task = new TaskModel();

  public customers: CustomerModel[] = [];
  public tasks: TaskModel[] = [];

  public constructor(private dataService: DataService, private notyf: NotyfService,
     private router: Router, private route: ActivatedRoute) { }

   public _id = this.route.snapshot.params['_id'];
   public currentTask = this.dataService.getTaskById(this._id);

   public async ngOnInit() {
     try {
       this.customers = await this.dataService.getAllCustomers();
       this.tasks = await this.dataService.getTasksByCustomer();
       console.log(this.currentTask);
         }
     catch (err: any) {
          this.notyf.error(err);
         }
        }

   public async send() {
       try {
        this.task._id = this._id;
        await this.dataService.updateTask(this.task);
        this.notyf.success("Task has been successfully updated");
        this.router.navigateByUrl("/home");
          }
       catch (err: any) {
          this.notyf.error(err);
          }
        }

         }
</code>```

I'm sending the id via the link from my home component (button sending id).

This is the service:

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { first, firstValueFrom, observable } from 'rxjs';
import { CustomerModel } from '../models/customer-model';
import { TaskModel } from '../models/task-model';
import { appConfig } from '../utils/app-config';

@Injectable({
    providedIn: 'root'
  })
export class DataService {

public constructor(private http: HttpClient) { }

// Get all customers:
public async getAllCustomers(): Promise<CustomerModel[]> {
    const observable = this.http.get<CustomerModel[]>(appConfig.customersUrl);
    const customers = await firstValueFrom(observable);
    return customers;
}

// Get all tasks with customers:
public async getTasksByCustomer(): Promise<TaskModel[]> {
    const observable = this.http.get<TaskModel[]>(appConfig.tasksByCustomersUrl);
    const tasks = await firstValueFrom(observable);
    return tasks;
}

// Get task by _id:
public async getTaskById(_id: string): Promise<TaskModel> {
    const observable = this.http.get<TaskModel>(appConfig.tasksUrl + _id);
    const task = await firstValueFrom(observable);
    return task;
}

// Add movie:
public async addTask(task: TaskModel): Promise<void> {
    const observable = this.http.post<TaskModel>(appConfig.tasksUrl, task);
    await firstValueFrom(observable);
}

// Delete movie:
public async deleteTask(taskId: string): Promise<void> {
    const observable = this.http.delete(appConfig.tasksUrl + taskId);
    await firstValueFrom(observable);
}

public async updateStatus(task: TaskModel): Promise<TaskModel> {
    const observable = this.http.put<TaskModel>(appConfig.tasksUrl + task._id, task);
    return await firstValueFrom(observable);

}

public async updateTask(task: TaskModel): Promise<void> {
    const observable = this.http.put<TaskModel>(appConfig.tasksUrl + task._id, task);
    await firstValueFrom(observable);
}
</code>```

}

How is it possible to set the value to the input boxes??

Title: MEAN Stack setting input values from DB

Body:
I'm making a little preparations for my MEAN stack exam.
I've built a sort of a To Do list.
I have an update component and I want to set the values in the inputs from the database (Using mongoose).

HTML Component:

Task Description:
<input type="text" name="task" [(ngModel)]="task.task" />

Date & Time:
<input type="datetime-local" name="dateTime" [(ngModel)]="task.dateTimeCreated" />

Customer:
<select name="customerId" [(ngModel)]="task.customerId" (change)="send()">
    <option selected disabled value="">Select Customer</option>
    <option *ngFor="let c of customers" value={{c._id}}>{{c.name}}</option>
</select>

ts component:

import { Component, Input, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { CustomerModel } from 'src/app/models/customer-model';
import { TaskModel } from 'src/app/models/task-model';
import { DataService } from 'src/app/services/data.service';
import { NotyfService } from 'src/app/services/notyf.service';

@Component({
  selector: 'app-update',
  templateUrl: './update.component.html',
  styleUrls: ['./update.component.css']
  })
export class UpdateComponent implements OnInit {

  // @Input()
  // public task: TaskModel;
  public task = new TaskModel();

  public customers: CustomerModel[] = [];
  public tasks: TaskModel[] = [];

  public constructor(private dataService: DataService, private notyf: NotyfService,
     private router: Router, private route: ActivatedRoute) { }

   public _id = this.route.snapshot.params['_id'];
   public currentTask = this.dataService.getTaskById(this._id);

   public async ngOnInit() {
     try {
       this.customers = await this.dataService.getAllCustomers();
       this.tasks = await this.dataService.getTasksByCustomer();
       console.log(this.currentTask);
         }
     catch (err: any) {
          this.notyf.error(err);
         }
        }

   public async send() {
       try {
        this.task._id = this._id;
        await this.dataService.updateTask(this.task);
        this.notyf.success("Task has been successfully updated");
        this.router.navigateByUrl("/home");
          }
       catch (err: any) {
          this.notyf.error(err);
          }
        }

         }

I'm sending the id via the link from my home component (button sending id).

This is the service:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { first, firstValueFrom, observable } from 'rxjs';
import { CustomerModel } from '../models/customer-model';
import { TaskModel } from '../models/task-model';
import { appConfig } from '../utils/app-config';

@Injectable({
    providedIn: 'root'
  })
export class DataService {

public constructor(private http: HttpClient) { }

// Get all customers:
public async getAllCustomers(): Promise<CustomerModel[]> {
    const observable = this.http.get<CustomerModel[]>(appConfig.customersUrl);
    const customers = await firstValueFrom(observable);
    return customers;
}

// Get all tasks with customers:
public async getTasksByCustomer(): Promise<TaskModel[]> {
    const observable = this.http.get<TaskModel[]>(appConfig.tasksByCustomersUrl);
    const tasks = await firstValueFrom(observable);
    return tasks;
}

// Get task by _id:
public async getTaskById(_id: string): Promise<TaskModel> {
    const observable = this.http.get<TaskModel>(appConfig.tasksUrl + _id);
    const task = await firstValueFrom(observable);
    return task;
}

// Add movie:
public async addTask(task: TaskModel): Promise<void> {
    const observable = this.http.post<TaskModel>(appConfig.tasksUrl, task);
    await firstValueFrom(observable);
}

// Delete movie:
public async deleteTask(taskId: string): Promise<void> {
    const observable = this.http.delete(appConfig.tasksUrl + taskId);
    await firstValueFrom(observable);
}

public async updateStatus(task: TaskModel): Promise<TaskModel> {
    const observable = this.http.put<TaskModel>(appConfig.tasksUrl + task._id, task);
    return await firstValueFrom(observable);

}

public async updateTask(task: TaskModel): Promise<void> {
    const observable = this.http.put<TaskModel>(appConfig.tasksUrl + task._id, task);
    await firstValueFrom(observable);
}

}

How is it possible to set the value to the input boxes??


问:
System.Net.Sockets.SocketException in external code? Source not available
Scratching my head here...

I am using VS 2022 with 4.8 Framework

I am getting a System.Net.Sockets.SocketException: 'An invalid argument was supplied' error when I try to launch my app.

It doesn't show me the line it's caused by or anything. I don't use any networking in my application however I do connect to SQL and Active Directory and am thinking that could be causing it? Not really sure. I am at a total loss is there anything I can do to further identify what's going on?

Thanks


问:
Edit commenting shortcut in jupyter on mac
I use a Mac with a German keyboard. The shortcut function in jupyter cmd + / does not comment out marked lines, however I would really like this function on a shortcut. The main reason for it not working is mainly because on a German keyboard you access / by pressing shift + 7. When pressing cmd + shift + 7 the help section from the mac top bar drops down. When pressing cmd + 7, nothing happens.

In jupyters help section I tried editing the shortcut, but the commenting shortcut was not listed in the editing section.

Has someone a solution for this?


问:
how to switch individual windows (not tabs) when combined with threading
i want to run 4 threads . The chrome will access the url already in file.txt then perform a certain action !! Then I want to switch to chrome1 , chrome2, chrome3 and chrome4 . But I didn't find much documentation about switching windows chrome , mainly about switching tabs .

it looks like the video below.

https://youtu.be/xQQ3nKwhylg

My code :

```<code>from selenium import webdriver
from threading import Thread
import time
from selenium.webdriver.chrome.options import Options

#go url , doing something and switch
def create_chrome_driver_instance(filepath,text):
    chrome_options = webdriver.ChromeOptions()
    # config open chrome theo specific path
    chrome_options.add_argument(r'--user-data-dir=C:\Users\ADMIN\PycharmProjects\pythonProject' + filepath)
    driver = webdriver.Chrome(chrome_options=chrome_options)
    with open(text, "r") as f:
        file_lines1 = f.readlines()
        for line1 in file_lines1:
            driver.get(line1)
            time.sleep(4)
            print(line1)
            #doing something
            #here will switch each one .....

# create a new thread and pass the driver and URL to the thread
thread = Thread(target=create_chrome_driver_instance, args=('Profile 11',"file1.txt"))
thread1 =Thread(target=create_chrome_driver_instance, args=('Profile 12',"file2.txt"))
thread2 = Thread(target=create_chrome_driver_instance, args=('Profile 13',"file3.txt"))
thread3 =Thread(target=create_chrome_driver_instance, args=('Profile 14',"file4.txt"))
# start the thread
thread.start()
thread1.start()
thread2.start()
thread3.start()

# wait for the thread to finish
thread.join()
thread1.join()
thread2.join()
thread3.join()

</code>```

I've searched quite a bit but there doesn't seem to be much documentation on this

Body:
i want to run 4 threads . The chrome will access the url already in file.txt then perform a certain action !! Then I want to switch to chrome1 , chrome2, chrome3 and chrome4 . But I didn't find much documentation about switching windows chrome , mainly about switching tabs .

it looks like the video below.

https://youtu.be/xQQ3nKwhylg

My code :

from selenium import webdriver
from threading import Thread
import time
from selenium.webdriver.chrome.options import Options

#go url , doing something and switch
def create_chrome_driver_instance(filepath,text):
    chrome_options = webdriver.ChromeOptions()
    # config open chrome theo specific path
    chrome_options.add_argument(r'--user-data-dir=C:\Users\ADMIN\PycharmProjects\pythonProject' + filepath)
    driver = webdriver.Chrome(chrome_options=chrome_options)
    with open(text, "r") as f:
        file_lines1 = f.readlines()
        for line1 in file_lines1:
            driver.get(line1)
            time.sleep(4)
            print(line1)
            #doing something
            #here will switch each one .....

# create a new thread and pass the driver and URL to the thread
thread = Thread(target=create_chrome_driver_instance, args=('Profile 11',"file1.txt"))
thread1 =Thread(target=create_chrome_driver_instance, args=('Profile 12',"file2.txt"))
thread2 = Thread(target=create_chrome_driver_instance, args=('Profile 13',"file3.txt"))
thread3 =Thread(target=create_chrome_driver_instance, args=('Profile 14',"file4.txt"))
# start the thread
thread.start()
thread1.start()
thread2.start()
thread3.start()

# wait for the thread to finish
thread.join()
thread1.join()
thread2.join()
thread3.join()

I've searched quite a bit but there doesn't seem to be much documentation on this


问:
How can I mock a method within a method that I am mocking?
I want to test in my MVC app if I can create an object using xUnit. The create method in my repository looks like this:

```<code>
public bool Create(Patient model)
{
    try {
        _db.patients.Add(model);
        saveChanges();
        return true
    } catch {
        return false;
    }
}

public int saveChanges() {
    return db.SaveChanges();
}
</code>```

My test currently looks like this:

```<code>public void CanCreatePatient() {
    using(var mock = AutoMock.GetLoose())
    {
        mock.Mock<IPatientRepo>().Setup(x => x.Create(GetSamplePatient()));
        mock.Mock<IPatientRepo>().Setup(x => x.saveChanges()),Returns(1);

        var cls = mock.Mock.Create<IPatientRepo>();

        var actual = cls.Create(GetSamplePatient());

        Assert.True(actual);
    }
}

</code>```

Im fairly new to xUnit and testing in dotnet. Currently this test always fails because the actual returns false. What can I do to solve this issue?

Body:
I want to test in my MVC app if I can create an object using xUnit. The create method in my repository looks like this:

public bool Create(Patient model)
{
    try {
        _db.patients.Add(model);
        saveChanges();
        return true
    } catch {
        return false;
    }
}

public int saveChanges() {
    return db.SaveChanges();
}

My test currently looks like this:

public void CanCreatePatient() {
    using(var mock = AutoMock.GetLoose())
    {
        mock.Mock<IPatientRepo>().Setup(x => x.Create(GetSamplePatient()));
        mock.Mock<IPatientRepo>().Setup(x => x.saveChanges()),Returns(1);

        var cls = mock.Mock.Create<IPatientRepo>();

        var actual = cls.Create(GetSamplePatient());

        Assert.True(actual);
    }
}

Im fairly new to xUnit and testing in dotnet. Currently this test always fails because the actual returns false. What can I do to solve this issue?


问:
How to find the total amount of unsent logs in Azure OMS Agent?
I'm trying to design a simple maintenance script in bash, and I was searching through Azure OMS Agent docs, and I can't find anything which will allow me to extract a count of backlogged logs. The main reason is that a machine appearing unhealthy can still be told to stay up if it has logs on it not sent to give it time to catch up and send the data; otherwise, it could introduce a drop and create a loss of information.

Any help on this would be greatly appreciated.
Thank You


问:
Handsontable loses CSS after scrolling
The Problem:
I load a large dataset (~1000 rows) and in the afterRender event, I call a function to iterate over the rows and apply styles to cells. This works perfectly on the version I was using (<1).

Using the latest version, I scroll down, and as soon as the first row goes out of the viewport, the CSS disappears. If I click anywhere on the table, it reappears. I understand that this question explains why.

I have tried using a custom renderer but this doesn't work, possibly because I'm using a custom dataSchema. This is the renderer:

```<code>function customRenderer(instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.BaseRenderer.apply(this, arguments);
    td.style.backgroundColor = 'yellow';
}
</code>```

I've tested using the built in renderer which shows the data correctly:

```<code>columns: [{ data: 'SKU1',  type: "text" }],
</code>```

Using my custom renderer shows the CSS but not the data:

```<code>columns: [{ data: 'SKU1',  renderer: 'test' }],
</code>```

This is irrelevant anyway because I won't know the column name at runtime as the dataSchema is dynamic.

I feel that using a custom renderer is overkill in this situation and I think it would be ok if I could just call my CSS binding function after the CSS is removed, but can't find a suitable event to use. Alternatively is it possible to turn off the feature that re-renders the CSS?

Title: Handsontable loses CSS after scrolling

Body:
The Problem:
I load a large dataset (~1000 rows) and in the afterRender event, I call a function to iterate over the rows and apply styles to cells. This works perfectly on the version I was using (<1).

Using the latest version, I scroll down, and as soon as the first row goes out of the viewport, the CSS disappears. If I click anywhere on the table, it reappears. I understand that this question explains why.

I have tried using a custom renderer but this doesn't work, possibly because I'm using a custom dataSchema. This is the renderer:

function customRenderer(instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.BaseRenderer.apply(this, arguments);
    td.style.backgroundColor = 'yellow';
}

I've tested using the built in renderer which shows the data correctly:

columns: [{ data: 'SKU1',  type: "text" }],

Using my custom renderer shows the CSS but not the data:

columns: [{ data: 'SKU1',  renderer: 'test' }],

This is irrelevant anyway because I won't know the column name at runtime as the dataSchema is dynamic.

I feel that using a custom renderer is overkill in this situation and I think it would be ok if I could just call my CSS binding function after the CSS is removed, but can't find a suitable event to use. Alternatively is it possible to turn off the feature that re-renders the CSS?


问:
how to post data in x-www-form-urlencoded format using dart?
I need to post this data in x-www-form-urlencoded format

```<code>Map<String, dynamic> body = {
      'data': [
        {
          'prefix': '225',
          'phone': '1234567890',
          'email': 'test@gmail.com',
          'name': 'test',
          'surname': 'test',
        },
      ],
    };
</code>```

I tried the following approach to convert my data but it returns a syntax error.

```<code>String bodyString = body.entries.map((entry) =>
    '${Uri.encodeQueryComponent(entry.key)}=${Uri.encodeQueryComponent(entry.value.toString())}'
).join('&');
</code>```

but when I use postman like on the picture then everything is finepotman screen shot

post data in x-www-form-urlencoded format

Body:
I need to post this data in x-www-form-urlencoded format

Map<String, dynamic> body = {
      'data': [
        {
          'prefix': '225',
          'phone': '1234567890',
          'email': 'test@gmail.com',
          'name': 'test',
          'surname': 'test',
        },
      ],
    };

I tried the following approach to convert my data but it returns a syntax error.

String bodyString = body.entries.map((entry) =>
    '${Uri.encodeQueryComponent(entry.key)}=${Uri.encodeQueryComponent(entry.value.toString())}'
).join('&');

but when I use postman like on the picture then everything is finepotman screen shot

post data in x-www-form-urlencoded format


问:
ER_CON_COUNT_ERROR: Too many connections error in node-express-mysql
I have following setup,

db.js

```<code>const mysql = require("mysql");
const config = require("../core/config/config.json");

const db = mysql.createPool({
    host: config.mysql.host,
    port: config.mysql.port,
    user: config.mysql.user,
    password: config.mysql.password
});

db.getConnection((err, connection) => {
    if (err) {
        console.error(err);
        return;
    }
    connection.ping();
    connection.release();
    console.log("Database connected !");
});

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

Then I have many query files as shown below,

query1.js

```<code>const mysql = require("../db");

mysql.query("select * from table", [param], (error, results) => {
            if (error) {
                return cb(error);
            }
            return cb(null, results);
});
</code>```

query2.js

```<code>const mysql = require("../db");

mysql.query("select * from table", [param], (error, results) => {
            if (error) {
                return cb(error);
            }
            return cb(null, results);
});
</code>```

query3.js

```<code>const mysql = require("../db");

mysql.query("select * from table", [param], (error, results) => {
            if (error) {
                return cb(error);
            }
            return cb(null, results);
});
</code>```

and so on...

And I get

ER_CON_COUNT_ERROR: Too many connections error in node-mysql

When I deploy this code to AWS-lambda function. (Locally, it works fine).

What should I do it avoid above error with above setup ?

What am I doing wrong ?

Body:
I have following setup,

db.js

const mysql = require("mysql");
const config = require("../core/config/config.json");

const db = mysql.createPool({
    host: config.mysql.host,
    port: config.mysql.port,
    user: config.mysql.user,
    password: config.mysql.password
});

db.getConnection((err, connection) => {
    if (err) {
        console.error(err);
        return;
    }
    connection.ping();
    connection.release();
    console.log("Database connected !");
});

module.exports = db;

Then I have many query files as shown below,

query1.js

const mysql = require("../db");

mysql.query("select * from table", [param], (error, results) => {
            if (error) {
                return cb(error);
            }
            return cb(null, results);
});

query2.js

const mysql = require("../db");

mysql.query("select * from table", [param], (error, results) => {
            if (error) {
                return cb(error);
            }
            return cb(null, results);
});

query3.js

const mysql = require("../db");

mysql.query("select * from table", [param], (error, results) => {
            if (error) {
                return cb(error);
            }
            return cb(null, results);
});

and so on...

And I get

ER_CON_COUNT_ERROR: Too many connections error in node-mysql

When I deploy this code to AWS-lambda function. (Locally, it works fine).

What should I do it avoid above error with above setup ?

What am I doing wrong ?


问:
Error: EISDIR: illegal operation on a directory, read (PHP CODEIGNITER)
I am stuck with this error no matter what directory I am in. I use vercel for deploy, use codeigniter framework

[22:47:40.765] Cloning github.com/johan-sar/myapi.tokojohan.org (Branch: main, Commit: 4119c36)
[22:47:41.978] Cloning completed: 1.213s
[22:47:42.359] Restored build cache
[22:47:42.414] Running "vercel build"
[22:47:43.076] Vercel CLI 28.10.0
[22:47:43.268] WARN! Due to `builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings
[22:47:43.293] > Installing Builder: vercel-php@0.3.1
[22:47:48.575]  Downloading user files
[22:47:48.576]  Downloading PHP runtime files
[22:47:48.580]  Installing Composer dependencies [START]
[22:47:48.815] [3.1MiB/0.00s] No lock file found. Updating dependencies instead of installing from lock file. Use composer update over composer install if you do not have a lock file.
[22:47:48.817] [3.2MiB/0.01s] Loading composer repositories with package information
[22:47:48.828] [3.4MiB/0.02s] Updating dependencies
[22:47:48.839] [3.6MiB/0.03s] Nothing to modify in lock file
[22:47:48.839] [3.6MiB/0.03s] Writing lock file
[22:47:48.839] [3.6MiB/0.03s] Installing dependencies from lock file
[22:47:48.840] [3.7MiB/0.03s] Nothing to install, update or remove
[22:47:48.845] [3.6MiB/0.03s] 1 package suggestions were added by new dependencies, use `composer suggest` to see details.
[22:47:48.845] [3.6MiB/0.03s] Generating autoload files
[22:47:48.846] [3.6MiB/0.03s] Memory usage: 3.63MiB (peak: 3.92MiB), time: 0.03s
[22:47:48.856]  Installing Composer dependencies [DONE]
[22:47:49.067]  Creating lambda
[22:47:52.711] Error: EISDIR: illegal operation on a directory, read```


问:
How can pandas open an excel file, keep the formulas and not change the form of the excel file?
I've been trying to modify an existing dataframe with Python, yet I have an ongoing issue, which is that the syntax I used to make sure the formulas within the Excel are kept is creating a column on my DataFrame.

Here's a way to reproduce what I've been trying to do:

```<code>import pandas as pd
df=pd.DataFrame(columns=["week "+str(i+1) for i in range(0,52)],index=["Objective A","Objective B", "Objective C"])
df.to_excel("Objectifs.xlsx")
</code>```

I've then added, through Excel, a last column, called "sum" which is the sum (through the Excel formula) of the previous rows.

Then, I opened my Excel file like this, to make sure my formula is kept:

```<code>wb=load_workbook(filename=os.path.join(os.path.expanduser("~"),"Documents\\Objectifs.xlsx"))
sheet_name=wb.get_sheet_names()[0]
ws=wb[sheet_name]
df=pd.DataFrame(ws.values)
df.index=df[0]
</code>```

And here I already have to put df.index=df[0] just to make sure the index is indeed the objectives, and not something else. But then, it gets worse when I'm trying to pursue my code:

```<code>week=input("which week to change?")

for objective in df.index[1:]:
    score=input("what is the score of this objective: " + objective + " ?")
    df.loc[[objectif],[week]]=int(score)

df.to_excel(Objectives.xlsx)
</code>```

But this doesn't work as planned at all: the content I'm inputting is going at the end of the excel file instead of the column I've wanted it to be put. The sum formula is kept, but that's the only thing that's working here.

Does anyone have an idea how to fix this?

Originally, I wanted to use pd.read_excel to open my excel file, but since it didn't keep the sum formula, I changed my code, but perhaps this is the reason nothing is working well anymore. Before changing the way to open my formula, the main issue was that the sum was not kept. I'm telling you this just you're wondering where the code is coming from.

Body:
I've been trying to modify an existing dataframe with Python, yet I have an ongoing issue, which is that the syntax I used to make sure the formulas within the Excel are kept is creating a column on my DataFrame.

Here's a way to reproduce what I've been trying to do:

import pandas as pd
df=pd.DataFrame(columns=["week "+str(i+1) for i in range(0,52)],index=["Objective A","Objective B", "Objective C"])
df.to_excel("Objectifs.xlsx")

I've then added, through Excel, a last column, called "sum" which is the sum (through the Excel formula) of the previous rows.

Then, I opened my Excel file like this, to make sure my formula is kept:

wb=load_workbook(filename=os.path.join(os.path.expanduser("~"),"Documents\\Objectifs.xlsx"))
sheet_name=wb.get_sheet_names()[0]
ws=wb[sheet_name]
df=pd.DataFrame(ws.values)
df.index=df[0]

And here I already have to put df.index=df[0] just to make sure the index is indeed the objectives, and not something else. But then, it gets worse when I'm trying to pursue my code:

week=input("which week to change?")

for objective in df.index[1:]:
    score=input("what is the score of this objective: " + objective + " ?")
    df.loc[[objectif],[week]]=int(score)

df.to_excel(Objectives.xlsx)

But this doesn't work as planned at all: the content I'm inputting is going at the end of the excel file instead of the column I've wanted it to be put. The sum formula is kept, but that's the only thing that's working here.

Does anyone have an idea how to fix this?

Originally, I wanted to use pd.read_excel to open my excel file, but since it didn't keep the sum formula, I changed my code, but perhaps this is the reason nothing is working well anymore. Before changing the way to open my formula, the main issue was that the sum was not kept. I'm telling you this just you're wondering where the code is coming from.


问:
Apply jdoc documentation to different branch (or: revert code changes but keep jdoc)
I have a new branch in my code, where a lot of jdoc-comments. were added. However, the code was also automatically reformatted and imports were rearranged.

I'd like to have the documentation in a seperate branch / pull request.

Is there a way to export the jdoc from the solution and then re-apply the exported jdocs to the original code? Or is there another way to achieve this?

original:

```<code>    protected static Random r = new Random();
    private static final String WACHTWOORD_PATTERN = PropertiesFileLoader.getInstance().getProperty("pwd.pattern", "aaaaaann");
    private static final boolean ENKEL_HOOFDLETTERS_TOEGESTAAN = Boolean.parseBoolean(PropertiesFileLoader.getInstance().getProperty("pwd.allUppercaseAllowed", "false"));
    private static final boolean ENKEL_KLEINELETTERS_TOEGESTAAN = Boolean.parseBoolean(PropertiesFileLoader.getInstance().getProperty("pwd.allLowercaseAllowed", "false"));
    private static Integer[] LETTERS_INDICES = null;
    private static final Map<String, String[]> TEKENS_MAP = new HashMap<String, String[]>();

    public static String volgendWachtwoord() {
        String wachtwoord = "";
        for (int i = 0; i < WACHTWOORD_PATTERN.length(); ++i) {
            wachtwoord = wachtwoord + TEKENS_MAP.get(WACHTWOORD_PATTERN.substring(i, i + 1))[r.nextInt(TEKENS_MAP.get(WACHTWOORD_PATTERN.substring(i, i + 1)).length)];
        }
        if (null != LETTERS_INDICES && LETTERS_INDICES.length > 0) {
            if (!ENKEL_HOOFDLETTERS_TOEGESTAAN && wachtwoord.toUpperCase().equals(wachtwoord)) {
                int kleineLetterIndex = r.nextInt(LETTERS_INDICES.length);
                wachtwoord = wachtwoord.substring(0, kleineLetterIndex) + wachtwoord.substring(kleineLetterIndex, kleineLetterIndex + 1).toLowerCase() + (kleineLetterIndex == LETTERS_INDICES.length - 1 ? "" : wachtwoord.substring(kleineLetterIndex + 1));
            }
            if (!ENKEL_KLEINELETTERS_TOEGESTAAN && wachtwoord.toLowerCase().equals(wachtwoord)) {
                int groteLetterIndex = r.nextInt(LETTERS_INDICES.length);
                wachtwoord = wachtwoord.substring(0, groteLetterIndex) + wachtwoord.substring(groteLetterIndex, groteLetterIndex + 1).toUpperCase() + (groteLetterIndex == LETTERS_INDICES.length - 1 ? "" : wachtwoord.substring(groteLetterIndex + 1));
        ...
</code>```

changed:

```<code>    protected static     Random                r                              = new Random();
    private static final String                WACHTWOORD_PATTERN             = PropertiesFileLoader.getInstance().getProperty("pwd.pattern", "aaaaaann");
    private static final boolean               ENKEL_HOOFDLETTERS_TOEGESTAAN  = Boolean.parseBoolean(
            PropertiesFileLoader.getInstance().getProperty("pwd.allUppercaseAllowed", "false"));
    private static final boolean               ENKEL_KLEINELETTERS_TOEGESTAAN = Boolean.parseBoolean(
            PropertiesFileLoader.getInstance().getProperty("pwd.allLowercaseAllowed", "false"));
    private static       Integer[]             LETTERS_INDICES                = null;
    private static final Map<String, String[]> TEKENS_MAP                     = new HashMap<String, String[]>();
    /**
     * It generates a random password based on the pattern and the tokens map
     *
     * @return A random password
     */
    public static String volgendWachtwoord() {
        String wachtwoord = "";
        for (int i = 0; i < WACHTWOORD_PATTERN.length(); ++i) {
            wachtwoord = wachtwoord + TEKENS_MAP.get(WACHTWOORD_PATTERN.substring(i, i + 1))[r.nextInt(TEKENS_MAP.get(WACHTWOORD_PATTERN.substring(i, i + 1)).length)];
        }
        if (null != LETTERS_INDICES && LETTERS_INDICES.length > 0) {
            if (!ENKEL_HOOFDLETTERS_TOEGESTAAN && wachtwoord.toUpperCase().equals(wachtwoord)) {
                int kleineLetterIndex = r.nextInt(LETTERS_INDICES.length);
                wachtwoord = wachtwoord.substring(0, kleineLetterIndex) + wachtwoord.substring(kleineLetterIndex, kleineLetterIndex + 1).toLowerCase() + (
                        kleineLetterIndex == LETTERS_INDICES.length - 1 ? "" : wachtwoord.substring(kleineLetterIndex + 1));
            }
            if (!ENKEL_KLEINELETTERS_TOEGESTAAN && wachtwoord.toLowerCase().equals(wachtwoord)) {
                int groteLetterIndex = r.nextInt(LETTERS_INDICES.length);
                wachtwoord = wachtwoord.substring(0, groteLetterIndex) + wachtwoord.substring(groteLetterIndex, groteLetterIndex + 1).toUpperCase() + (
                        groteLetterIndex == LETTERS_INDICES.length - 1 ? "" : wachtwoord.substring(groteLetterIndex + 1));
        ...
</code>```

Body:
I have a new branch in my code, where a lot of jdoc-comments. were added. However, the code was also automatically reformatted and imports were rearranged.

I'd like to have the documentation in a seperate branch / pull request.

Is there a way to export the jdoc from the solution and then re-apply the exported jdocs to the original code? Or is there another way to achieve this?

original:

    protected static Random r = new Random();
    private static final String WACHTWOORD_PATTERN = PropertiesFileLoader.getInstance().getProperty("pwd.pattern", "aaaaaann");
    private static final boolean ENKEL_HOOFDLETTERS_TOEGESTAAN = Boolean.parseBoolean(PropertiesFileLoader.getInstance().getProperty("pwd.allUppercaseAllowed", "false"));
    private static final boolean ENKEL_KLEINELETTERS_TOEGESTAAN = Boolean.parseBoolean(PropertiesFileLoader.getInstance().getProperty("pwd.allLowercaseAllowed", "false"));
    private static Integer[] LETTERS_INDICES = null;
    private static final Map<String, String[]> TEKENS_MAP = new HashMap<String, String[]>();

    public static String volgendWachtwoord() {
        String wachtwoord = "";
        for (int i = 0; i < WACHTWOORD_PATTERN.length(); ++i) {
            wachtwoord = wachtwoord + TEKENS_MAP.get(WACHTWOORD_PATTERN.substring(i, i + 1))[r.nextInt(TEKENS_MAP.get(WACHTWOORD_PATTERN.substring(i, i + 1)).length)];
        }
        if (null != LETTERS_INDICES && LETTERS_INDICES.length > 0) {
            if (!ENKEL_HOOFDLETTERS_TOEGESTAAN && wachtwoord.toUpperCase().equals(wachtwoord)) {
                int kleineLetterIndex = r.nextInt(LETTERS_INDICES.length);
                wachtwoord = wachtwoord.substring(0, kleineLetterIndex) + wachtwoord.substring(kleineLetterIndex, kleineLetterIndex + 1).toLowerCase() + (kleineLetterIndex == LETTERS_INDICES.length - 1 ? "" : wachtwoord.substring(kleineLetterIndex + 1));
            }
            if (!ENKEL_KLEINELETTERS_TOEGESTAAN && wachtwoord.toLowerCase().equals(wachtwoord)) {
                int groteLetterIndex = r.nextInt(LETTERS_INDICES.length);
                wachtwoord = wachtwoord.substring(0, groteLetterIndex) + wachtwoord.substring(groteLetterIndex, groteLetterIndex + 1).toUpperCase() + (groteLetterIndex == LETTERS_INDICES.length - 1 ? "" : wachtwoord.substring(groteLetterIndex + 1));
        ...

changed:

    protected static     Random                r                              = new Random();
    private static final String                WACHTWOORD_PATTERN             = PropertiesFileLoader.getInstance().getProperty("pwd.pattern", "aaaaaann");
    private static final boolean               ENKEL_HOOFDLETTERS_TOEGESTAAN  = Boolean.parseBoolean(
            PropertiesFileLoader.getInstance().getProperty("pwd.allUppercaseAllowed", "false"));
    private static final boolean               ENKEL_KLEINELETTERS_TOEGESTAAN = Boolean.parseBoolean(
            PropertiesFileLoader.getInstance().getProperty("pwd.allLowercaseAllowed", "false"));
    private static       Integer[]             LETTERS_INDICES                = null;
    private static final Map<String, String[]> TEKENS_MAP                     = new HashMap<String, String[]>();
    /**
     * It generates a random password based on the pattern and the tokens map
     *
     * @return A random password
     */
    public static String volgendWachtwoord() {
        String wachtwoord = "";
        for (int i = 0; i < WACHTWOORD_PATTERN.length(); ++i) {
            wachtwoord = wachtwoord + TEKENS_MAP.get(WACHTWOORD_PATTERN.substring(i, i + 1))[r.nextInt(TEKENS_MAP.get(WACHTWOORD_PATTERN.substring(i, i + 1)).length)];
        }
        if (null != LETTERS_INDICES && LETTERS_INDICES.length > 0) {
            if (!ENKEL_HOOFDLETTERS_TOEGESTAAN && wachtwoord.toUpperCase().equals(wachtwoord)) {
                int kleineLetterIndex = r.nextInt(LETTERS_INDICES.length);
                wachtwoord = wachtwoord.substring(0, kleineLetterIndex) + wachtwoord.substring(kleineLetterIndex, kleineLetterIndex + 1).toLowerCase() + (
                        kleineLetterIndex == LETTERS_INDICES.length - 1 ? "" : wachtwoord.substring(kleineLetterIndex + 1));
            }
            if (!ENKEL_KLEINELETTERS_TOEGESTAAN && wachtwoord.toLowerCase().equals(wachtwoord)) {
                int groteLetterIndex = r.nextInt(LETTERS_INDICES.length);
                wachtwoord = wachtwoord.substring(0, groteLetterIndex) + wachtwoord.substring(groteLetterIndex, groteLetterIndex + 1).toUpperCase() + (
                        groteLetterIndex == LETTERS_INDICES.length - 1 ? "" : wachtwoord.substring(groteLetterIndex + 1));
        ...


问:
Update Choroplethmap scale and hover with dropdown dash
I'm trying to update a choropleth map in dash plotly by using buttons. Changing the values is working. But I am looking for a solution to also update the scale on the side based on the values as well as the description in hoover. For the hoover so far: The value is correct, but the label of the property is not changing.

Maybe someone has a hint for me.

```<code>app = dash.Dash(__name__, external_stylesheets=[dbc.themes.CYBORG])

content = html.Div(id="page-content", children=[], style=CONTENT_STYLE)

app.layout = html.Div([
      dcc.Location(id="url"),
      sidebar,
      content,
      ])

  mydb = psycopg2.connect(
       database="test",
       user='xxxxx',
       password='xxxx',
       host='1xxxxxx',
       port= 'x'
       )

   test=pd.read_sql('''SELECT jsonb_build_object('type', 'FeatureCollection','features',                                                 jsonb_agg(features.feature))FROM (SELECT jsonb_build_object('type','Feature','id', plz1,'geometry',   ST_AsGeoJSON(geom)::jsonb,'properties', to_jsonb(inputs) - 'geom') AS feature FROM (SELECT * FROM plz1) inputs) features;''',mydb)

  #saving the feature collection in a dict
  test_dict=test.iloc[0]['jsonb_build_object']

 #write dict to json
 with open("text.json","w") as outfile:
       json.dump(test_dict,outfile)

 #read json
 with open("test.json")as f:
     data=json.load(f)

 df=pd.read_sql('''SELECT * from kpi_v2''',mydb)

 #choropleth map
 fig = px.choropleth_mapbox(
        data_frame=df,
        geojson=data,
        locations='plz1',
        color='rem',
        featureidkey="properties.plz1",
        range_color=(1, 5),
        color_continuous_scale="Viridis",
        mapbox_style="carto-darkmatter",
        zoom=4, center = {"lat": 51.110924, "lon": 9.682127}
      )

     fig.update_geos(fitbounds="locations")

    fig.update_layout(
       plot_bgcolor='rgba(0,0,0,0)',
       paper_bgcolor='rgba(0,0,0,0)',
       width=300,
       margin=dict(l=70, r=30, t=10, b=10),
       legend_font_color='rgb(100,100,100)',
       updatemenus=[dict(
               type="buttons",
               direction="left",
               buttons=[
                    dict(
                       label="REM",
                       method = "restyle",
                       args = [{'z': [ df["pue"]] }]),
                    dict(
                       method = "restyle",
                       args = [{'z': [ df["erf"] ]}],
                       label = "RAM"
                      )
                    ],
                    pad={"r": 20, "t": 10},
                    showactive=True,
                    xanchor="left",
                    y=1.1,
                    yanchor="top"
                    ), ])

         #creates content based on the link
         @app.callback(
         Output("page-content", "children"),
         [Input("url", "pathname")]
         )

   def render_page_content(pathname):
        if pathname == "/":
                 return [
            html.Div([
                html.Div([
                html.Div(
                   dcc.Graph(id='map',
                            figure=fig),
                            className="six columns",
                            style={"width":600, "margin": 0, 'display': 'inline-block','margin-left':'5em','height':'auto',"background-color":"white","font-color":"red"}
                       ),
        ], className="row",style={"font-color":"red"})
        ]),

        html.Div(
            html.P("",style=footer)
        )

             ]
elif pathname == "/plz1":
    return [
              html.Div([
                html.Div([

        ], className="row")

        ]),

        html.Div(
            html.P("",style=footer)
        )

            ]
elif pathname == "/plz2":
    return [
            html.Div([
                html.Div([

        ]),

        html.Div(
            html.P("",style=footer)
        )

 if __name__=='__main__':
          app.run_server(debug=True)
</code>```

Body:
I'm trying to update a choropleth map in dash plotly by using buttons. Changing the values is working. But I am looking for a solution to also update the scale on the side based on the values as well as the description in hoover. For the hoover so far: The value is correct, but the label of the property is not changing.

Maybe someone has a hint for me.

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.CYBORG])

content = html.Div(id="page-content", children=[], style=CONTENT_STYLE)

app.layout = html.Div([
      dcc.Location(id="url"),
      sidebar,
      content,
      ])

  mydb = psycopg2.connect(
       database="test",
       user='xxxxx',
       password='xxxx',
       host='1xxxxxx',
       port= 'x'
       )

   test=pd.read_sql('''SELECT jsonb_build_object('type', 'FeatureCollection','features',                                                 jsonb_agg(features.feature))FROM (SELECT jsonb_build_object('type','Feature','id', plz1,'geometry',   ST_AsGeoJSON(geom)::jsonb,'properties', to_jsonb(inputs) - 'geom') AS feature FROM (SELECT * FROM plz1) inputs) features;''',mydb)

  #saving the feature collection in a dict
  test_dict=test.iloc[0]['jsonb_build_object']

 #write dict to json
 with open("text.json","w") as outfile:
       json.dump(test_dict,outfile)

 #read json
 with open("test.json")as f:
     data=json.load(f)

 df=pd.read_sql('''SELECT * from kpi_v2''',mydb)

 #choropleth map
 fig = px.choropleth_mapbox(
        data_frame=df,
        geojson=data,
        locations='plz1',
        color='rem',
        featureidkey="properties.plz1",
        range_color=(1, 5),
        color_continuous_scale="Viridis",
        mapbox_style="carto-darkmatter",
        zoom=4, center = {"lat": 51.110924, "lon": 9.682127}
      )

     fig.update_geos(fitbounds="locations")

    fig.update_layout(
       plot_bgcolor='rgba(0,0,0,0)',
       paper_bgcolor='rgba(0,0,0,0)',
       width=300,
       margin=dict(l=70, r=30, t=10, b=10),
       legend_font_color='rgb(100,100,100)',
       updatemenus=[dict(
               type="buttons",
               direction="left",
               buttons=[
                    dict(
                       label="REM",
                       method = "restyle",
                       args = [{'z': [ df["pue"]] }]),
                    dict(
                       method = "restyle",
                       args = [{'z': [ df["erf"] ]}],
                       label = "RAM"
                      )
                    ],
                    pad={"r": 20, "t": 10},
                    showactive=True,
                    xanchor="left",
                    y=1.1,
                    yanchor="top"
                    ), ])

         #creates content based on the link
         @app.callback(
         Output("page-content", "children"),
         [Input("url", "pathname")]
         )

   def render_page_content(pathname):
        if pathname == "/":
                 return [
            html.Div([
                html.Div([
                html.Div(
                   dcc.Graph(id='map',
                            figure=fig),
                            className="six columns",
                            style={"width":600, "margin": 0, 'display': 'inline-block','margin-left':'5em','height':'auto',"background-color":"white","font-color":"red"}
                       ),
        ], className="row",style={"font-color":"red"})
        ]),

        html.Div(
            html.P("",style=footer)
        )

             ]
elif pathname == "/plz1":
    return [
              html.Div([
                html.Div([

        ], className="row")

        ]),

        html.Div(
            html.P("",style=footer)
        )

            ]
elif pathname == "/plz2":
    return [
            html.Div([
                html.Div([

        ]),

        html.Div(
            html.P("",style=footer)
        )

 if __name__=='__main__':
          app.run_server(debug=True)


问:
Is there any way to update the Security Configurations after application is started?
I'm configuring multiple LDAP servers in my application to make it a multi-tenant application. I have my LDAP server configurations in the database. Whenever the application starts it loads all the LDAP configurations and configures them accordingly and I'm able to authenticate a user from different servers.

But I want to update the security configuration whenever a new tenant's LDAP configuration is added to the database. So that the new tenant users will be able to log in to my application. Currently, I have to restart the server to load and configure new LDAP server configurations.

I'm trying to update the AuthenticationManagerBuilder but it throws an exception as expected

```<code>java.lang.IllegalStateException: Cannot apply to already built object
</code>```

I want to know if there is any way to reload/recreate the Security Configurations. So that I don't have to restart the server every time after adding a new tenant's LDAP configurations in the database.

Body:
I'm configuring multiple LDAP servers in my application to make it a multi-tenant application. I have my LDAP server configurations in the database. Whenever the application starts it loads all the LDAP configurations and configures them accordingly and I'm able to authenticate a user from different servers.

But I want to update the security configuration whenever a new tenant's LDAP configuration is added to the database. So that the new tenant users will be able to log in to my application. Currently, I have to restart the server to load and configure new LDAP server configurations.

I'm trying to update the AuthenticationManagerBuilder but it throws an exception as expected

java.lang.IllegalStateException: Cannot apply to already built object

I want to know if there is any way to reload/recreate the Security Configurations. So that I don't have to restart the server every time after adding a new tenant's LDAP configurations in the database.


问:
How to make use of a function(window) js script in react js
I am starting out with react and I came into error i am not able to solve pls look into this.

I am trying convert a vanilla js and css website to a react website but while including the js scripts in react i came across "window" not defined so i made use of useEffect() in react but am not able to access my classie.js script.

```<code>import Layout from '../components/Layout';
import React from 'react';
import classie from '../public/js/classie';

export default function Home() {
  React.useEffect(() => {
    !function(e,n,t){function r(e);e.Modernizr=Modernizr}(window,document);//TRUNCATED DUE TO LACK OF SPACE
  }, []);

  React.useEffect(() => {
    (function(window) {

      'use strict';

      var support = { transitions: Modernizr.csstransitions },
        // transition end event name
        transEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd', 'transition': 'transitionend' },
        transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
        onEndTransition = function( el, callback ) {
          var onEndCallbackFn = function( ev ) {
            if( support.transitions ) {
              if( ev.target != this ) return;
              this.removeEventListener( transEndEventName, onEndCallbackFn );
            }
            if( callback && typeof callback === 'function' ) { callback.call(this); }
          };
          if( support.transitions ) {
            el.addEventListener( transEndEventName, onEndCallbackFn );
          }
          else {
            onEndCallbackFn();
          }
        },
        // the pages wrapper
        stack = document.querySelector('.pages-stack'),
        // the page elements
        pages = [].slice.call(stack.children),
        // total number of page elements
        pagesTotal = pages.length,
        // index of current page
        current = 0,
        // menu button
        menuCtrl = document.querySelector('button.menu-button'),
        // the navigation wrapper
        nav = document.querySelector('.pages-nav'),
        // the menu nav items
        navItems = [].slice.call(nav.querySelectorAll('.link--page')),
        // check if menu is open
        isMenuOpen = false;

      function init() {
        buildStack();
        initEvents();
      }

      function buildStack() {
        var stackPagesIdxs = getStackPagesIdxs();

        // set z-index, opacity, initial transforms to pages and add class page--inactive to all except the current one
        for(var i = 0; i < pagesTotal; ++i) {
          var page = pages[i],
            posIdx = stackPagesIdxs.indexOf(i);

          if( current !== i ) {
            classie.add(page, 'page--inactive');

            if( posIdx !== -1 ) {
              // visible pages in the stack
              page.style.WebkitTransform = 'translate3d(0,100%,0)';
              page.style.transform = 'translate3d(0,100%,0)';
            }
            else {
              // invisible pages in the stack
              page.style.WebkitTransform = 'translate3d(0,75%,-300px)';
              page.style.transform = 'translate3d(0,75%,-300px)';
            }
          }
          else {
            classie.remove(page, 'page--inactive');
          }

          page.style.zIndex = i < current ? parseInt(current - i) : parseInt(pagesTotal + current - i);

          if( posIdx !== -1 ) {
            page.style.opacity = parseFloat(1 - 0.1 * posIdx);
          }
          else {
            page.style.opacity = 0;
          }
        }
      }

      // event binding
      function initEvents() {
        // menu button click
        menuCtrl.addEventListener('click', toggleMenu);

        // navigation menu clicks
        navItems.forEach(function(item) {
          // which page to open?
          var pageid = item.getAttribute('href').slice(1);
          item.addEventListener('click', function(ev) {
            ev.preventDefault();
            openPage(pageid);
          });
        });

        // clicking on a page when the menu is open triggers the menu to close again and open the clicked page
        pages.forEach(function(page) {
          var pageid = page.getAttribute('id');
          page.addEventListener('click', function(ev) {
            if( isMenuOpen ) {
              ev.preventDefault();
              openPage(pageid);
            }
          });
        });

        // keyboard navigation events
        document.addEventListener( 'keydown', function( ev ) {
          if( !isMenuOpen ) return;
          var keyCode = ev.keyCode || ev.which;
          if( keyCode === 27 ) {
            closeMenu();
          }
        } );
      }

      // toggle menu fn
      function toggleMenu() {
        if( isMenuOpen ) {
          closeMenu();
        }
        else {
          openMenu();
          isMenuOpen = true;
        }
      }

      // opens the menu
      function openMenu() {
        // toggle the menu button
        classie.add(menuCtrl, 'menu-button--open')
        // stack gets the class "pages-stack--open" to add the transitions
        classie.add(stack, 'pages-stack--open');
        // reveal the menu
        classie.add(nav, 'pages-nav--open');

        // now set the page transforms
        var stackPagesIdxs = getStackPagesIdxs();
        for(var i = 0, len = stackPagesIdxs.length; i < len; ++i) {
          var page = pages[stackPagesIdxs[i]];
          page.style.WebkitTransform = 'translate3d(0, 75%, ' + parseInt(-1 * 200 - 50*i) + 'px)'; // -200px, -230px, -260px
          page.style.transform = 'translate3d(0, 75%, ' + parseInt(-1 * 200 - 50*i) + 'px)';
        }
      }

      // closes the menu
      function closeMenu() {
        // same as opening the current page again
        openPage();
      }

      // opens a page
      function openPage(id) {
        var futurePage = id ? document.getElementById(id) : pages[current],
          futureCurrent = pages.indexOf(futurePage),
          stackPagesIdxs = getStackPagesIdxs(futureCurrent);

        // set transforms for the new current page
        futurePage.style.WebkitTransform = 'translate3d(0, 0, 0)';
        futurePage.style.transform = 'translate3d(0, 0, 0)';
        futurePage.style.opacity = 1;

        // set transforms for the other items in the stack
        for(var i = 0, len = stackPagesIdxs.length; i < len; ++i) {
          var page = pages[stackPagesIdxs[i]];
          page.style.WebkitTransform = 'translate3d(0,100%,0)';
          page.style.transform = 'translate3d(0,100%,0)';
        }

        // set current
        if( id ) {
          current = futureCurrent;
        }

        // close menu..
        classie.remove(menuCtrl, 'menu-button--open');
        classie.remove(nav, 'pages-nav--open');
        onEndTransition(futurePage, function() {
          classie.remove(stack, 'pages-stack--open');
          // reorganize stack
          buildStack();
          isMenuOpen = false;
        });
      }

      // gets the current stack pages indexes. If any of them is the excludePage then this one is not part of the returned array
      function getStackPagesIdxs(excludePageIdx) {
        var nextStackPageIdx = current + 1 < pagesTotal ? current + 1 : 0,
          nextStackPageIdx_2 = current + 2 < pagesTotal ? current + 2 : 1,
          idxs = [],

          excludeIdx = excludePageIdx || -1;

        if( excludePageIdx != current ) {
          idxs.push(current);
        }
        if( excludePageIdx != nextStackPageIdx ) {
          idxs.push(nextStackPageIdx);
        }
        if( excludePageIdx != nextStackPageIdx_2 ) {
          idxs.push(nextStackPageIdx_2);
        }

        return idxs;
      }

      init();

      //changes to a page such as id="page-manuals" without opening the menu and preserving menu transition functionality
      window.openPageNoTransition = function(id){

        var futurePage = id ? document.getElementById(id) : pages[current],
          futureCurrent = pages.indexOf(futurePage),
          stackPagesIdxs = getStackPagesIdxs(futureCurrent);

        // set transforms for the new current page
        futurePage.style.WebkitTransform = 'translate3d(0, 0, 0)';
        futurePage.style.transform = 'translate3d(0, 0, 0)';
        futurePage.style.opacity = 1;

        classie.remove(futurePage, 'page--inactive');

        // set current
        if( id ) {
          current = futureCurrent;
        }

        buildStack();
      }
    })(window);

  }, []);

  return (

    <>
      <Layout title="Home Page">Home Page</Layout>
    </>

  )
}
</code>```

the above is my layout.js
and below is the classie.js

```<code>( function( window ) {

'use strict';

// class helper functions from bonzo https://github.com/ded/bonzo

function classReg( className ) {
  return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}

// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;

if ( 'classList' in document.documentElement ) {
  hasClass = function( elem, c ) {
    return elem.classList.contains( c );
  };
  addClass = function( elem, c ) {
    elem.classList.add( c );
  };
  removeClass = function( elem, c ) {
    elem.classList.remove( c );
  };
}
else {
  hasClass = function( elem, c ) {
    return classReg( c ).test( elem.className );
  };
  addClass = function( elem, c ) {
    if ( !hasClass( elem, c ) ) {
      elem.className = elem.className + ' ' + c;
    }
  };
  removeClass = function( elem, c ) {
    elem.className = elem.className.replace( classReg( c ), ' ' );
  };
}

function toggleClass( elem, c ) {
  var fn = hasClass( elem, c ) ? removeClass : addClass;
  fn( elem, c );
}

var classie = {
  // full names
  hasClass: hasClass,
  addClass: addClass,
  removeClass: removeClass,
  toggleClass: toggleClass,
  // short names
  has: hasClass,
  add: addClass,
  remove: removeClass,
  toggle: toggleClass
};

// transport
if ( typeof define === 'function' && define.amd ) {
  // AMD
  define( classie );
} else if ( typeof exports === 'object' ) {
  // CommonJS
  module.exports = classie;
} else {
  // browser global
  window.classie = classie;
}

})( window );
</code>```

how do i make use of classie.js in my Layout.js

i tried using useEffect for classie also (just below modernizer) but i encountered the error that classie is not defined in my main useEffect hook after classie.

Body:
I am starting out with react and I came into error i am not able to solve pls look into this.

I am trying convert a vanilla js and css website to a react website but while including the js scripts in react i came across "window" not defined so i made use of useEffect() in react but am not able to access my classie.js script.

import Layout from '../components/Layout';
import React from 'react';
import classie from '../public/js/classie';

export default function Home() {
  React.useEffect(() => {
    !function(e,n,t){function r(e);e.Modernizr=Modernizr}(window,document);//TRUNCATED DUE TO LACK OF SPACE
  }, []);

  React.useEffect(() => {
    (function(window) {

      'use strict';

      var support = { transitions: Modernizr.csstransitions },
        // transition end event name
        transEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd', 'transition': 'transitionend' },
        transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
        onEndTransition = function( el, callback ) {
          var onEndCallbackFn = function( ev ) {
            if( support.transitions ) {
              if( ev.target != this ) return;
              this.removeEventListener( transEndEventName, onEndCallbackFn );
            }
            if( callback && typeof callback === 'function' ) { callback.call(this); }
          };
          if( support.transitions ) {
            el.addEventListener( transEndEventName, onEndCallbackFn );
          }
          else {
            onEndCallbackFn();
          }
        },
        // the pages wrapper
        stack = document.querySelector('.pages-stack'),
        // the page elements
        pages = [].slice.call(stack.children),
        // total number of page elements
        pagesTotal = pages.length,
        // index of current page
        current = 0,
        // menu button
        menuCtrl = document.querySelector('button.menu-button'),
        // the navigation wrapper
        nav = document.querySelector('.pages-nav'),
        // the menu nav items
        navItems = [].slice.call(nav.querySelectorAll('.link--page')),
        // check if menu is open
        isMenuOpen = false;

      function init() {
        buildStack();
        initEvents();
      }

      function buildStack() {
        var stackPagesIdxs = getStackPagesIdxs();

        // set z-index, opacity, initial transforms to pages and add class page--inactive to all except the current one
        for(var i = 0; i < pagesTotal; ++i) {
          var page = pages[i],
            posIdx = stackPagesIdxs.indexOf(i);

          if( current !== i ) {
            classie.add(page, 'page--inactive');

            if( posIdx !== -1 ) {
              // visible pages in the stack
              page.style.WebkitTransform = 'translate3d(0,100%,0)';
              page.style.transform = 'translate3d(0,100%,0)';
            }
            else {
              // invisible pages in the stack
              page.style.WebkitTransform = 'translate3d(0,75%,-300px)';
              page.style.transform = 'translate3d(0,75%,-300px)';
            }
          }
          else {
            classie.remove(page, 'page--inactive');
          }

          page.style.zIndex = i < current ? parseInt(current - i) : parseInt(pagesTotal + current - i);

          if( posIdx !== -1 ) {
            page.style.opacity = parseFloat(1 - 0.1 * posIdx);
          }
          else {
            page.style.opacity = 0;
          }
        }
      }

      // event binding
      function initEvents() {
        // menu button click
        menuCtrl.addEventListener('click', toggleMenu);

        // navigation menu clicks
        navItems.forEach(function(item) {
          // which page to open?
          var pageid = item.getAttribute('href').slice(1);
          item.addEventListener('click', function(ev) {
            ev.preventDefault();
            openPage(pageid);
          });
        });

        // clicking on a page when the menu is open triggers the menu to close again and open the clicked page
        pages.forEach(function(page) {
          var pageid = page.getAttribute('id');
          page.addEventListener('click', function(ev) {
            if( isMenuOpen ) {
              ev.preventDefault();
              openPage(pageid);
            }
          });
        });

        // keyboard navigation events
        document.addEventListener( 'keydown', function( ev ) {
          if( !isMenuOpen ) return;
          var keyCode = ev.keyCode || ev.which;
          if( keyCode === 27 ) {
            closeMenu();
          }
        } );
      }

      // toggle menu fn
      function toggleMenu() {
        if( isMenuOpen ) {
          closeMenu();
        }
        else {
          openMenu();
          isMenuOpen = true;
        }
      }

      // opens the menu
      function openMenu() {
        // toggle the menu button
        classie.add(menuCtrl, 'menu-button--open')
        // stack gets the class "pages-stack--open" to add the transitions
        classie.add(stack, 'pages-stack--open');
        // reveal the menu
        classie.add(nav, 'pages-nav--open');

        // now set the page transforms
        var stackPagesIdxs = getStackPagesIdxs();
        for(var i = 0, len = stackPagesIdxs.length; i < len; ++i) {
          var page = pages[stackPagesIdxs[i]];
          page.style.WebkitTransform = 'translate3d(0, 75%, ' + parseInt(-1 * 200 - 50*i) + 'px)'; // -200px, -230px, -260px
          page.style.transform = 'translate3d(0, 75%, ' + parseInt(-1 * 200 - 50*i) + 'px)';
        }
      }

      // closes the menu
      function closeMenu() {
        // same as opening the current page again
        openPage();
      }

      // opens a page
      function openPage(id) {
        var futurePage = id ? document.getElementById(id) : pages[current],
          futureCurrent = pages.indexOf(futurePage),
          stackPagesIdxs = getStackPagesIdxs(futureCurrent);

        // set transforms for the new current page
        futurePage.style.WebkitTransform = 'translate3d(0, 0, 0)';
        futurePage.style.transform = 'translate3d(0, 0, 0)';
        futurePage.style.opacity = 1;

        // set transforms for the other items in the stack
        for(var i = 0, len = stackPagesIdxs.length; i < len; ++i) {
          var page = pages[stackPagesIdxs[i]];
          page.style.WebkitTransform = 'translate3d(0,100%,0)';
          page.style.transform = 'translate3d(0,100%,0)';
        }

        // set current
        if( id ) {
          current = futureCurrent;
        }

        // close menu..
        classie.remove(menuCtrl, 'menu-button--open');
        classie.remove(nav, 'pages-nav--open');
        onEndTransition(futurePage, function() {
          classie.remove(stack, 'pages-stack--open');
          // reorganize stack
          buildStack();
          isMenuOpen = false;
        });
      }

      // gets the current stack pages indexes. If any of them is the excludePage then this one is not part of the returned array
      function getStackPagesIdxs(excludePageIdx) {
        var nextStackPageIdx = current + 1 < pagesTotal ? current + 1 : 0,
          nextStackPageIdx_2 = current + 2 < pagesTotal ? current + 2 : 1,
          idxs = [],

          excludeIdx = excludePageIdx || -1;

        if( excludePageIdx != current ) {
          idxs.push(current);
        }
        if( excludePageIdx != nextStackPageIdx ) {
          idxs.push(nextStackPageIdx);
        }
        if( excludePageIdx != nextStackPageIdx_2 ) {
          idxs.push(nextStackPageIdx_2);
        }

        return idxs;
      }

      init();

      //changes to a page such as id="page-manuals" without opening the menu and preserving menu transition functionality
      window.openPageNoTransition = function(id){

        var futurePage = id ? document.getElementById(id) : pages[current],
          futureCurrent = pages.indexOf(futurePage),
          stackPagesIdxs = getStackPagesIdxs(futureCurrent);

        // set transforms for the new current page
        futurePage.style.WebkitTransform = 'translate3d(0, 0, 0)';
        futurePage.style.transform = 'translate3d(0, 0, 0)';
        futurePage.style.opacity = 1;

        classie.remove(futurePage, 'page--inactive');

        // set current
        if( id ) {
          current = futureCurrent;
        }

        buildStack();
      }
    })(window);

  }, []);

  return (

    <>
      <Layout title="Home Page">Home Page</Layout>
    </>

  )
}

the above is my layout.js
and below is the classie.js

( function( window ) {

'use strict';

// class helper functions from bonzo https://github.com/ded/bonzo

function classReg( className ) {
  return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}

// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;

if ( 'classList' in document.documentElement ) {
  hasClass = function( elem, c ) {
    return elem.classList.contains( c );
  };
  addClass = function( elem, c ) {
    elem.classList.add( c );
  };
  removeClass = function( elem, c ) {
    elem.classList.remove( c );
  };
}
else {
  hasClass = function( elem, c ) {
    return classReg( c ).test( elem.className );
  };
  addClass = function( elem, c ) {
    if ( !hasClass( elem, c ) ) {
      elem.className = elem.className + ' ' + c;
    }
  };
  removeClass = function( elem, c ) {
    elem.className = elem.className.replace( classReg( c ), ' ' );
  };
}

function toggleClass( elem, c ) {
  var fn = hasClass( elem, c ) ? removeClass : addClass;
  fn( elem, c );
}

var classie = {
  // full names
  hasClass: hasClass,
  addClass: addClass,
  removeClass: removeClass,
  toggleClass: toggleClass,
  // short names
  has: hasClass,
  add: addClass,
  remove: removeClass,
  toggle: toggleClass
};

// transport
if ( typeof define === 'function' && define.amd ) {
  // AMD
  define( classie );
} else if ( typeof exports === 'object' ) {
  // CommonJS
  module.exports = classie;
} else {
  // browser global
  window.classie = classie;
}

})( window );

how do i make use of classie.js in my Layout.js

i tried using useEffect for classie also (just below modernizer) but i encountered the error that classie is not defined in my main useEffect hook after classie.


问:
How would I send mySQL queries/ results from ExpressJS to react?
I'm creating a react program,which I want to connect to a mysql database I created on sql workbench. So far, I created the front end from react, the database from mySQL, and collected information on creating the express, connecting to the database from express, and connecting the react to express. What I need to know now: how would I send data from react to express?

I need to send
1: A query/data values in the query from react to express when trying to insert values to the data base

2: A query/data values in the query from react to express when trying to search for specific values in the data base

3: results of the query (number 2) from express to react, so I can display them on the program.

Havent tried any attempts yet, but this is my first time connecting to a DB from a frontend, so I want to plan before coding, but I struggled to find info on this. Thanks in advance.


问:
Can't use ImageTk in customtkinter
```<code>import tkinter
import customtkinter
from PIL import Image, ImageTk

# create root windows

root = customtkinter.CTk()
# find image

button_1 = ImageTk.PhotoImage(Image.open("icons/bit.ico").resize((20, 20)))

display_button = customtkinter.CTkButton(master=root, image=button_1, text="i am dumb", fg_color="red")

display_button.pack()

root.mainloop()

</code>```

i used the ctkimage but it showed the image including the place where is nothing(sorry for bad english)

i was trying to display a partially transparent color but it showed the whole thing with the side where nothing is drawn when using CTkImage but when i used imageTk from pillow it showed an error

Title: Can't use ImageTk in customtkinter

Body:
import tkinter
import customtkinter
from PIL import Image, ImageTk

# create root windows

root = customtkinter.CTk()
# find image

button_1 = ImageTk.PhotoImage(Image.open("icons/bit.ico").resize((20, 20)))

display_button = customtkinter.CTkButton(master=root, image=button_1, text="i am dumb", fg_color="red")

display_button.pack()

root.mainloop()

i used the ctkimage but it showed the image including the place where is nothing(sorry for bad english)

i was trying to display a partially transparent color but it showed the whole thing with the side where nothing is drawn when using CTkImage but when i used imageTk from pillow it showed an error


问:
How to use multiple Semantics in one tree
What's the best way to use multi Semantics if I don't have access to the first semantics in the widget tree?

Code for example:

```<code>Semantics(
      focused: true,
      child: Container(
        color: Colors.red,
        child: Align(
          child: Semantics(
            header: true,
            child: Text('test semantics'),
          ),
        ),
      ),
    );
</code>```

Body:
What's the best way to use multi Semantics if I don't have access to the first semantics in the widget tree?

Code for example:

Semantics(
      focused: true,
      child: Container(
        color: Colors.red,
        child: Align(
          child: Semantics(
            header: true,
            child: Text('test semantics'),
          ),
        ),
      ),
    );


问:
org.hibernate.MappingException: Could not locate CollectionPersister for role : com.jbk.Entity.Product.productName
Whenever, I try to run below method it is giving above error

```<code>

    public static List<Product> productGettingWithSize(int size) {
        Session session = factory.openSession();
        List<Product> list = null;
        try {
            Criteria criteria = session.createCriteria(Product.class);
            criteria.add(Restrictions.sizeEq("productName", size));
            list = criteria.list();
            if (list.isEmpty()) {
                System.out.println("No Data Found..!!");
            } else {
                System.out.println(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
</code>```

So, here in this code in DB productName is REDMI so, I m passing 5 as an size but, I m not getting the expected output. So could anyone help me regarding this code or Can any anyone Tell how to use Restrictions(Size), all method related to size or can anyone send me the documentation where it is been explained explicitly. Thank You...!!!

Expecting a solution on This..!!

Body:
Whenever, I try to run below method it is giving above error

    public static List<Product> productGettingWithSize(int size) {
        Session session = factory.openSession();
        List<Product> list = null;
        try {
            Criteria criteria = session.createCriteria(Product.class);
            criteria.add(Restrictions.sizeEq("productName", size));
            list = criteria.list();
            if (list.isEmpty()) {
                System.out.println("No Data Found..!!");
            } else {
                System.out.println(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

So, here in this code in DB productName is REDMI so, I m passing 5 as an size but, I m not getting the expected output. So could anyone help me regarding this code or Can any anyone Tell how to use Restrictions(Size), all method related to size or can anyone send me the documentation where it is been explained explicitly. Thank You...!!!

Expecting a solution on This..!!


问:
How to Write API response coming as Byte[] as Pdf file using Javascript or Typescript
is there any Write API response coming as Byte[] as Pdf file using Javascript or Typescript

i tried using

```<code>fs.writeFileSync('FIlename.pdf', apiresponsebody, 'binary')
</code>```

but I am seeing a blank page when I open the saved pdf file
please suggest how to deal with this
At least help me with an example if possible

I even tried npm packages like PDFKit, pdf2html, file-saver etc but all are storing blank pdf file

Body:
is there any Write API response coming as Byte[] as Pdf file using Javascript or Typescript

i tried using

fs.writeFileSync('FIlename.pdf', apiresponsebody, 'binary')

but I am seeing a blank page when I open the saved pdf file
please suggest how to deal with this
At least help me with an example if possible

I even tried npm packages like PDFKit, pdf2html, file-saver etc but all are storing blank pdf file


问:
Uncaught ReferenceError: showNotification is not defined when submitting my form
I'm in the middle of creating a form (dev) where you can enter a Cardknox Transaction API and it will give me a response back whether it went thru or not, , i'm trying to add toast notificatiom, so that when I hit submit it should pop up a notification that it was approved, or error message, etc. however, when I'm trying to hit submit it gives me the below error messages in the consoletoastify error

see my code below

server.js

```<code>const express = require("express");
const request = require("request");

const app = express();
const path = require("path");

app.use(express.static(path.join(__dirname, "server")));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));

app.get("/gatewayjson", (req, res) => {
  const xKey = req.query.xKey;
  const xCommand = req.query.xCommand;
  const xCardNum = req.query.xCardNum;
  const xExp = req.query.xExp;
  const xAmount = req.query.xAmount;
  const xSoftwareName = "Cardknox";
  const xSoftwareVersion = "2.1";
  const xVersion = "5.0.0";

  const body = JSON.stringify({
    xKey: xKey,
    xCommand: xCommand,
    xCardNum: xCardNum,
    xExp: xExp,
    xSoftwareName: xSoftwareName,
    xSoftwareVersion: xSoftwareVersion,
    xVersion: xVersion,
    xAmount: xAmount,
  });

  request(
    {
      url: "https://x1.cardknox.com/gatewayjson",
      method: "POST",
      body: body,
    },
    (error, response, body) => {
      if (error) {
        console.log(error);
      } else {
        console.log(body);

        const responseObject = JSON.parse(body);
        const xRef = responseObject.xRef;

        res.render("template", { xRef: xRef });
      }
    }
  );
});

app.listen(3060, () => {
  console.log("Server listening on port 3060");
});

</code>```

template.ejs

```<code><%- include('partials/head') %>
  <body>
    <script src="toastify.js"></script>
    <form
      action="/gatewayjson"
      method="get"
      onsubmit="showNotification('<%= xRef %>')"
    >
      <label for="xKey">Cardknox Key:</label><br />
      <input type="text" id="xKey" name="xKey" /><br />
      <label for="xCommand">Command:</label><br />
      <input type="text" id="xCommand" name="xCommand" /><br />
      <label for="xCardNum">Card Number:</label><br />
      <input type="text" id="xCardNum" name="xCardNum" /><br />
      <label for="xExp">Expiration Date:</label><br />
      <input type="text" id="xExp" name="xExp" /><br />
      <label for="xAmount">Amount:</label><br />
      <input type="text" id="xAmount" name="xAmount" /><br /><br />
      <input type="submit" value="Submit" />
    </form>
</code>```

toastify.js

```<code>function checkRequiredFields() {
  const requiredFields = document.querySelectorAll("[required]");

  for (let i = 0; i < requiredFields.length; i++) {
    if (!requiredFields[i].value) {
      Toastify({
        text: "Please fill in all the required fields",
        duration: 10000,
        close: true,
        gravity: "top",
        position: "left",
        backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
        stopOnFocus: true,
      }).showToast();
      return false;
    }
  }

  return true;
}

function showNotification(xRef) {
  if (xRef === "") {
    Toastify({
      text: "Error: xRef is missing",
      duration: 10000,
      close: true,
      gravity: "top", // `top` or `bottom`
      position: "left", // `left`, `center` or `right`
      backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
      stopOnFocus: true, // Prevents dismissing of toast on hover
    }).showToast();
  } else {
    Toastify({
      text: "Transaction Approved with xRef: " + xRef,
      duration: 10000,
      close: true,
      gravity: "top",
      position: "left",
      backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
      stopOnFocus: true,
    }).showToast();
  }
}

</code>```

please let me know what's wrong here,  thanks

Body:
I'm in the middle of creating a form (dev) where you can enter a Cardknox Transaction API and it will give me a response back whether it went thru or not, , i'm trying to add toast notificatiom, so that when I hit submit it should pop up a notification that it was approved, or error message, etc. however, when I'm trying to hit submit it gives me the below error messages in the consoletoastify error

see my code below

server.js

const express = require("express");
const request = require("request");

const app = express();
const path = require("path");

app.use(express.static(path.join(__dirname, "server")));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));

app.get("/gatewayjson", (req, res) => {
  const xKey = req.query.xKey;
  const xCommand = req.query.xCommand;
  const xCardNum = req.query.xCardNum;
  const xExp = req.query.xExp;
  const xAmount = req.query.xAmount;
  const xSoftwareName = "Cardknox";
  const xSoftwareVersion = "2.1";
  const xVersion = "5.0.0";

  const body = JSON.stringify({
    xKey: xKey,
    xCommand: xCommand,
    xCardNum: xCardNum,
    xExp: xExp,
    xSoftwareName: xSoftwareName,
    xSoftwareVersion: xSoftwareVersion,
    xVersion: xVersion,
    xAmount: xAmount,
  });

  request(
    {
      url: "https://x1.cardknox.com/gatewayjson",
      method: "POST",
      body: body,
    },
    (error, response, body) => {
      if (error) {
        console.log(error);
      } else {
        console.log(body);

        const responseObject = JSON.parse(body);
        const xRef = responseObject.xRef;

        res.render("template", { xRef: xRef });
      }
    }
  );
});

app.listen(3060, () => {
  console.log("Server listening on port 3060");
});

template.ejs

<%- include('partials/head') %>

    <form
      action="/gatewayjson"
      method="get"
      onsubmit="showNotification('<%= xRef %>')"
    >
      Cardknox Key:

      <input type="text" id="xKey" name="xKey" />

      Command:

      <input type="text" id="xCommand" name="xCommand" />

      Card Number:

      <input type="text" id="xCardNum" name="xCardNum" />

      Expiration Date:

      <input type="text" id="xExp" name="xExp" />

      Amount:

      <input type="text" id="xAmount" name="xAmount" />

      <input type="submit" value="Submit" />
    </form>

toastify.js

function checkRequiredFields() {
  const requiredFields = document.querySelectorAll("[required]");

  for (let i = 0; i < requiredFields.length; i++) {
    if (!requiredFields[i].value) {
      Toastify({
        text: "Please fill in all the required fields",
        duration: 10000,
        close: true,
        gravity: "top",
        position: "left",
        backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
        stopOnFocus: true,
      }).showToast();
      return false;
    }
  }

  return true;
}

function showNotification(xRef) {
  if (xRef === "") {
    Toastify({
      text: "Error: xRef is missing",
      duration: 10000,
      close: true,
      gravity: "top", // `top` or `bottom`
      position: "left", // `left`, `center` or `right`
      backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
      stopOnFocus: true, // Prevents dismissing of toast on hover
    }).showToast();
  } else {
    Toastify({
      text: "Transaction Approved with xRef: " + xRef,
      duration: 10000,
      close: true,
      gravity: "top",
      position: "left",
      backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
      stopOnFocus: true,
    }).showToast();
  }
}

please let me know what's wrong here,  thanks


问:
Physical Mobile Device detected but not listed in Device Selection Spinner Android Studio
I am currently learning flutter in Android Studio. Android Studio detects my physical device connected but does not list it in Device Selection spinner.
Below picture will elaborate my issue further:

As can be seen, Mobile device is listed in Device Manager and in Connected Devices (RED Boxes right side) but in device selection box only Chrome & Windows appear.

I have googled and most close to my problem I found this. But this did not help me to resolve my issue.
Any help will be highly appreciated.

Edit

I further checked and found following symptoms which to best of my knowldege can help to diagnose issue unluckily I myself could'nt figure out

My device manager instead of listing an Android Phone in devices list a USB Device for my Mobile Device (Pic as under)

However, adb does recognises my device and reboots it when i input commandadb reboot (pic attached)