问:
JavaFx Application Class not found in Gradle jar
I am trying to build a jar with the following build.gradle:

```<code>plugins {
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.10'
}

application {
    mainClass.set("edu.hm.dako.auditLogServer.AdminGuiStarter")
}

jar.enabled = true

javafx {
    version = "18"
    modules = ['javafx.controls', 'javafx.fxml']
}

sourceSets {
    main {
        resources {
            srcDirs = ["src/main/java"]
            includes = ["**/*.fxml"]
        }
    }
}

dependencies {

    implementation project(':common')
    implementation project(':communication')
    implementation 'org.openjfx:javafx:18'
    implementation group: 'org.apache.commons', name: 'commons-configuration2', version: '2.8.0'
    implementation group: 'commons-beanutils', name: 'commons-beanutils', version: '1.9.4'
}

repositories {
    mavenCentral()
}

jar {
    manifest {
        attributes "Main-Class": "edu.hm.dako.auditLogServer.AdminGuiStarter"
    }
    archiveBaseName = 'AdminGradle'
    archiveVersion =  '0.1.0'
}

</code>```

The Main class of the project is following:

```<code>package edu.hm.dako.auditLogServer;

import java.io.IOException;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class AdminGuiStarter extends Application{

    @Override
    public void start(Stage stage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("AdminGui.fxml"));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    // bitte über gradle starten, da sonst JavaFx Runtime components fehlen
    public static void main(String[] args) {
        launch();
    }

}
</code>```

When I then try to execute the jar, I get this error: java.lang.NoClassDefFoundError: javafx/application/Application

How can I fix this so that the jar will execute successful? When I run the Application via Gradle run, everything works fine.

Body:
I am trying to build a jar with the following build.gradle:

plugins {
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.10'
}

application {
    mainClass.set("edu.hm.dako.auditLogServer.AdminGuiStarter")
}

jar.enabled = true

javafx {
    version = "18"
    modules = ['javafx.controls', 'javafx.fxml']
}

sourceSets {
    main {
        resources {
            srcDirs = ["src/main/java"]
            includes = ["**/*.fxml"]
        }
    }
}

dependencies {

    implementation project(':common')
    implementation project(':communication')
    implementation 'org.openjfx:javafx:18'
    implementation group: 'org.apache.commons', name: 'commons-configuration2', version: '2.8.0'
    implementation group: 'commons-beanutils', name: 'commons-beanutils', version: '1.9.4'
}

repositories {
    mavenCentral()
}

jar {
    manifest {
        attributes "Main-Class": "edu.hm.dako.auditLogServer.AdminGuiStarter"
    }
    archiveBaseName = 'AdminGradle'
    archiveVersion =  '0.1.0'
}

The Main class of the project is following:

package edu.hm.dako.auditLogServer;

import java.io.IOException;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class AdminGuiStarter extends Application{

    @Override
    public void start(Stage stage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("AdminGui.fxml"));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    // bitte über gradle starten, da sonst JavaFx Runtime components fehlen
    public static void main(String[] args) {
        launch();
    }

}

When I then try to execute the jar, I get this error: java.lang.NoClassDefFoundError: javafx/application/Application

How can I fix this so that the jar will execute successful? When I run the Application via Gradle run, everything works fine.


来源: stackexchange

问:
How to apply a discount only on the second cart item in Woocommerce *(quantity)*
How to apply a discount only on the second cart item in Woocommerce (quantity)

I want to make a 15% discount on the second item that someone adds to the cart even if its the same product

I found this code here at stackoverflow by @LoicTheAztec, but i it doesnt apply on the sencond item with the same product's quantity..

```<code>add_action( 'woocommerce_before_calculate_totals', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Initialising
    $count = 0;
    $percentage = 3; // 3 %

    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        $count++;
        if( 2 == $count){ // Second item only
            $price = $cart_item['data']->get_price(); // product price
            $discounted_price = $price * (1 - ($percentage / 100)); // calculation

            // Set the new price
            $cart_item['data']->set_price( $discounted_price );
            break; // stop the loop
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to apply a discount only on the second cart item in Woocommerce (quantity)

I want to make a 15% discount on the second item that someone adds to the cart even if its the same product

I found this code here at stackoverflow by @LoicTheAztec, but i it doesnt apply on the sencond item with the same product's quantity..

add_action( 'woocommerce_before_calculate_totals', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Initialising
    $count = 0;
    $percentage = 3; // 3 %

    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        $count++;
        if( 2 == $count){ // Second item only
            $price = $cart_item['data']->get_price(); // product price
            $discounted_price = $price * (1 - ($percentage / 100)); // calculation

            // Set the new price
            $cart_item['data']->set_price( $discounted_price );
            break; // stop the loop
        }
    }
}


问:
Which method is better and more efficient to get CPU ID
I received the ID and UUID of the processor from the following two methods
Now my question is, which method is better for long time ?

```<code> import subprocess
 current_machine_id = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')
 [1].strip()
 print(current_machine_id)
</code>```

and

```<code> import wmi
 c = wmi.WMI()
 for s in c.Win32_Processor():
    print (s.ProcessorId)
</code>```

Body:
I received the ID and UUID of the processor from the following two methods
Now my question is, which method is better for long time ?

 import subprocess
 current_machine_id = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')
 [1].strip()
 print(current_machine_id)

and

 import wmi
 c = wmi.WMI()
 for s in c.Win32_Processor():
    print (s.ProcessorId)


问:
How to stub query helper method Mongoose?
I'm using Sinon to test my Express/Typescript application. In Mongoose I have models with query helper methods to make query chains.

I have this schema

```<code>export const articuloSchema = new Schema({
    _id: { type: String, default: v4 },
    numeroInventario: { type: String, required: true, unique: true },
    descripcion: { type: String, trim: true },
}, {
    versionKey: false,
    query: {
        paginate(page: number, limit: number) {
            return this.skip(page - 1).limit(limit);
        }
    }
});

export type ArticuloType = InferSchemaType<typeof articuloSchema>;

export const Articulo = mongoose.model('Articulo', articuloSchema);
</code>```

and I want to fake my query helper method with Sinon like this

```<code>const getMultipleArticulos (): ArticuloType[] => {
    const arr:ArticuloType = []
    for (let i = 0; i < 5; i++) {
        arr.push({
            numeroInventario: i,
            descripcion: 'string'
        })
    }
    return arr;
}
it('Should return a list of items that belong to a user', function (done) {
    const paginateFake = sinon.fake.resolves(getMultipleArticulos());
    sinon.replace(Articulo, 'paginate', paginateFake);
    chai.request(app)
        .get(`/api/v1/users/${userId}/articulos`)
        .end((err, res) => {
            expect(err).to.be.null;
            expect(res).to.have.status(200);
            // more expects
            done();
        });
});
</code>```

The problem is that I cannot stub those methods, it says that it can't stub non existent property of 'paginate' (which is the query helper method I added to my model).

Body:
I'm using Sinon to test my Express/Typescript application. In Mongoose I have models with query helper methods to make query chains.

I have this schema

export const articuloSchema = new Schema({
    _id: { type: String, default: v4 },
    numeroInventario: { type: String, required: true, unique: true },
    descripcion: { type: String, trim: true },
}, {
    versionKey: false,
    query: {
        paginate(page: number, limit: number) {
            return this.skip(page - 1).limit(limit);
        }
    }
});

export type ArticuloType = InferSchemaType<typeof articuloSchema>;

export const Articulo = mongoose.model('Articulo', articuloSchema);

and I want to fake my query helper method with Sinon like this

const getMultipleArticulos (): ArticuloType[] => {
    const arr:ArticuloType = []
    for (let i = 0; i < 5; i++) {
        arr.push({
            numeroInventario: i,
            descripcion: 'string'
        })
    }
    return arr;
}
it('Should return a list of items that belong to a user', function (done) {
    const paginateFake = sinon.fake.resolves(getMultipleArticulos());
    sinon.replace(Articulo, 'paginate', paginateFake);
    chai.request(app)
        .get(`/api/v1/users/${userId}/articulos`)
        .end((err, res) => {
            expect(err).to.be.null;
            expect(res).to.have.status(200);
            // more expects
            done();
        });
});

The problem is that I cannot stub those methods, it says that it can't stub non existent property of 'paginate' (which is the query helper method I added to my model).


问:
Change dropdown into text input
I'm trying to change the input from a dropdown into a text field when a specific option in the dropdown is selected. I did something similar to this (changed a color picker to a text field and vise versa) and it worked but I can't get it to work here with this.

```<code><select id="iconAdd" name="iconAdd" class="form-control form-control-sm" {% if userPermStageFlagsEdit != true %} disabled {%endif %}>
       <option>{{ item['icon'] }}</option>
       <option>New Icon</option>
       {% for icon in iconList %}
           {% if icon['icon'] != item['icon'] %}
               <option>{{ icon['icon'] }}</option>
           {% endif %}
       {% endfor %}
</select>

document.getElementById('iconAdd').addEventListener('change', function(){
    isNew = document.getElementById('iconAdd');

    if(isNew.value == 'New Icon'){
        alert("New Icon Selected");
        isNew.type = 'text';
    }
});
</code>```

When I debug this in the browser the browser doesn't complain or see any errors, but the dropdown field never turns into a text input.

Title: Change dropdown into text input

Body:
I'm trying to change the input from a dropdown into a text field when a specific option in the dropdown is selected. I did something similar to this (changed a color picker to a text field and vise versa) and it worked but I can't get it to work here with this.

<select id="iconAdd" name="iconAdd" class="form-control form-control-sm" {% if userPermStageFlagsEdit != true %} disabled {%endif %}>
       <option>{{ item['icon'] }}</option>
       <option>New Icon</option>
       {% for icon in iconList %}
           {% if icon['icon'] != item['icon'] %}
               <option>{{ icon['icon'] }}</option>
           {% endif %}
       {% endfor %}
</select>

document.getElementById('iconAdd').addEventListener('change', function(){
    isNew = document.getElementById('iconAdd');

    if(isNew.value == 'New Icon'){
        alert("New Icon Selected");
        isNew.type = 'text';
    }
});

When I debug this in the browser the browser doesn't complain or see any errors, but the dropdown field never turns into a text input.


问:
How do I encrypt a ConfigurationSection in ASP.NET Core 7.0?
I have a project with an appsettings.Development.json file, to which I've added the following section:

```<code>"ConnectionStrings": {
    "Database one": "<Host...;Username=...;Password=...;etc.>"
}
</code>```

When I search the internet for instructions on how to encrypt the ConnectionStrings section, I keep finding instructions that try to call functions that my IDE (VSCode) doesn't recognize (it doesn't even suggest that I must download a NuGet or import a using), which leads me to believe that it's all outdated, just as this person did. But what confuses me is that even the Microsoft documentation (see this link and this link), which is supposed to be up to date, is instructing me to use the functions that VSCode doesn't recognize, such as OpenExeConfiguration, SectionInformation, IsProtected, and ProtectSection.

Below is my best attempt at creating working code from the examples I've found, but it doesn't work yet because VSCode is still unable to recognize SectionInformation and ProtectSection:

```<code>public void ProtectSection(ConfigurationManager cManager)
{
    try
    {
        var section = cManager.GetSection("ConnectionStrings") as ConfigurationSection;

        if (!section.SectionInformation.IsProtected)
        {
            section.ProtectSection("ConnectionStrings");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
</code>```

Body:
I have a project with an appsettings.Development.json file, to which I've added the following section:

"ConnectionStrings": {
    "Database one": "<Host...;Username=...;Password=...;etc.>"
}

When I search the internet for instructions on how to encrypt the ConnectionStrings section, I keep finding instructions that try to call functions that my IDE (VSCode) doesn't recognize (it doesn't even suggest that I must download a NuGet or import a using), which leads me to believe that it's all outdated, just as this person did. But what confuses me is that even the Microsoft documentation (see this link and this link), which is supposed to be up to date, is instructing me to use the functions that VSCode doesn't recognize, such as OpenExeConfiguration, SectionInformation, IsProtected, and ProtectSection.

Below is my best attempt at creating working code from the examples I've found, but it doesn't work yet because VSCode is still unable to recognize SectionInformation and ProtectSection:

public void ProtectSection(ConfigurationManager cManager)
{
    try
    {
        var section = cManager.GetSection("ConnectionStrings") as ConfigurationSection;

        if (!section.SectionInformation.IsProtected)
        {
            section.ProtectSection("ConnectionStrings");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}


问:
DRF getting unneccessary data while querying
I have Category model and am querying through this model to list all categories. Im using django-silk to see how many queries got executed. It shows, category and Accounts. Accounts model has no relation with Catgeory. Below are the results.

It shows accounts on the list of queries

Im not requesting any data from Accounts Model.

#Views.py

```<code>class ListCategory(generics.ListAPIView):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
</code>```

#Serializer.py

```<code>class CategorySerializer(ModelSerializer):
    class Meta:
        model = Category
        fields = [
            "category_name",
            "slug",
            "title",
            "description",
            "category_image",
        ]
</code>```

#Models.py

```<code>
class Category(models.Model):
    category_name = models.CharField(max_length=15, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    title = models.CharField(max_length=25)
    description = models.CharField(max_length=300)
    category_image = models.ImageField(upload_to="photos/category")

    class Meta:
        verbose_name_plural = "Category"

    def __str__(self):
        return self.category_name
</code>```

It's not only limited to this API, In all API it shows account. I have exactly no idea why this happens.

Body:
I have Category model and am querying through this model to list all categories. Im using django-silk to see how many queries got executed. It shows, category and Accounts. Accounts model has no relation with Catgeory. Below are the results.

It shows accounts on the list of queries

Im not requesting any data from Accounts Model.

#Views.py

class ListCategory(generics.ListAPIView):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

#Serializer.py

class CategorySerializer(ModelSerializer):
    class Meta:
        model = Category
        fields = [
            "category_name",
            "slug",
            "title",
            "description",
            "category_image",
        ]

#Models.py

class Category(models.Model):
    category_name = models.CharField(max_length=15, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    title = models.CharField(max_length=25)
    description = models.CharField(max_length=300)
    category_image = models.ImageField(upload_to="photos/category")

    class Meta:
        verbose_name_plural = "Category"

    def __str__(self):
        return self.category_name

It's not only limited to this API, In all API it shows account. I have exactly no idea why this happens.


问:
Calling a function in main window with a button created in subwindow PyQt5
I am trying to make GUI application, using Pyqt5. The app has 2 windows: Main window with table widget and start button, and Subwindow that works like a stopwatch, with time as self.label and 2 buttons: "done" and "not done".
I want to make a function that checks which button in stopwatch (subwindow): "done" or "not done" was pressed and returns this information to a specific cell in table widget (main window).

To define a specific cell I created a global variable, which counts the number of both buttons presses.
This is the code:

```<code>global i
a = 0

class Stoper(QMdiSubWindow):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Stoper")
        self.setGeometry(100, 100, 400, 500)
        self.UiComponents()
        self.show()

    def UiComponents(self):
        self.count = 0
        self.flag = False
        self.label = QLabel(self)
        self.label.setGeometry(75, 100, 250, 70)
        self.label.setStyleSheet("border : 4px solid black;")
        self.label.setText(str(self.count))
        start = QPushButton("Start (S)", self)
        start.setGeometry(125, 250, 150, 40)
        start.pressed.connect(self.Start)
        done = QPushButton("Done (Space)", self)
        done.setGeometry(125, 300, 150, 40)
        done.pressed.connect(self.Done)
        done.pressed.connect(M.statusdone)
        ndone = QPushButton("Not Done (D)", self)
        ndone.setGeometry(125, 350, 150, 40)
        ndone.pressed.connect(self.Ndone)
        ndone.pressed.connect(M.statusndone)
        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(100)

    def showTime(self):
        if self.flag:
            self.count+= 1

        text = str(self.count / 10)+"/"+str(i)+".0"
        self.label.setText(text)
        if self.count >= i*10:
            self.label.setStyleSheet("background : light green;")

    def Start(self):
        self.flag = True

    def Done(self):
        self.flag = False
        self.count = 0
        self.label.setText(str(self.count)+"/"+str(i)+".0")
        self.label.setStyleSheet("border : 4px solid black;")
        global a
        a+= 1
        if a>=10:
            self.close()

    def Ndone(self):
        self.flag = False
        self.count = 0
        self.label.setText(str(self.count)+"/"+str(i)+".0")
        self.label.setStyleSheet("border : 4px solid black;")
        global a
        a+=1
        if a>=10:
            self.close()

class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'Window'
        self.left = 0
        self.top = 0
        self.width = 620
        self.height = 700
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.tab_widget = MyTabWidget(self)
        self.setCentralWidget(self.tab_widget)
        self.show()
</code>```

I created 3 tabs in main window, but since it is not the problem with the tabs, I skipped this part of code

```<code>class MyTabWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        self.table = QTableWidget(self.tab3)
        self.table.move(20,80)
        self.table.setRowCount(10)
        self.table.setColumnCount(4)
        self.table.setColumnWidth(0,50)

        self.Load_data = QtWidgets.QPushButton(self.tab3)
        self.Load_data.setGeometry(QtCore.QRect(200, 10, 200, 50))
        self.Load_data.setText('&Start')
        self.Load_data.clicked.connect(self.show_Stoper)
        self.Load_data.clicked.connect(self.progress)

    def statusdone(self):
        self.table.setItem(a-1, 0, QTableWidgetItem("done"))
        self.table.setItem(a, 0, QTableWidgetItem("..."))

    def statusndone(self):
        self.table.setItem(a-1, 0, QTableWidgetItem("not done"))
        self.table.setItem(a, 0, QTableWidgetItem("..."))

    def show_Stoper(self):
        self.w = Stoper()
        self.w.show()

    def progress(self):
        global a
        self.table.setItem(a, 0, QTableWidgetItem("..."))

M = MyTabWidget()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
</code>```

As you can see, I made a function statusdone and statusndone, which i want to call with a buttons in stopwatch called "Stoper". To make it work, I have created Instance of a class MyTabWidget. Unfortunately it only gives me error in this line:
MyTabWidget.init() missing 1 required positional argument: 'parent'
When i delete 'parent' from def init  and 'super', it returns error:
QWidget: Must construct a QApplication before a QWidget
What should I do to make it work. Do I have to modify the classes?

Body:
I am trying to make GUI application, using Pyqt5. The app has 2 windows: Main window with table widget and start button, and Subwindow that works like a stopwatch, with time as self.label and 2 buttons: "done" and "not done".
I want to make a function that checks which button in stopwatch (subwindow): "done" or "not done" was pressed and returns this information to a specific cell in table widget (main window).

To define a specific cell I created a global variable, which counts the number of both buttons presses.
This is the code:

global i
a = 0

class Stoper(QMdiSubWindow):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Stoper")
        self.setGeometry(100, 100, 400, 500)
        self.UiComponents()
        self.show()

    def UiComponents(self):
        self.count = 0
        self.flag = False
        self.label = QLabel(self)
        self.label.setGeometry(75, 100, 250, 70)
        self.label.setStyleSheet("border : 4px solid black;")
        self.label.setText(str(self.count))
        start = QPushButton("Start (S)", self)
        start.setGeometry(125, 250, 150, 40)
        start.pressed.connect(self.Start)
        done = QPushButton("Done (Space)", self)
        done.setGeometry(125, 300, 150, 40)
        done.pressed.connect(self.Done)
        done.pressed.connect(M.statusdone)
        ndone = QPushButton("Not Done (D)", self)
        ndone.setGeometry(125, 350, 150, 40)
        ndone.pressed.connect(self.Ndone)
        ndone.pressed.connect(M.statusndone)
        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(100)

    def showTime(self):
        if self.flag:
            self.count+= 1

        text = str(self.count / 10)+"/"+str(i)+".0"
        self.label.setText(text)
        if self.count >= i*10:
            self.label.setStyleSheet("background : light green;")

    def Start(self):
        self.flag = True

    def Done(self):
        self.flag = False
        self.count = 0
        self.label.setText(str(self.count)+"/"+str(i)+".0")
        self.label.setStyleSheet("border : 4px solid black;")
        global a
        a+= 1
        if a>=10:
            self.close()

    def Ndone(self):
        self.flag = False
        self.count = 0
        self.label.setText(str(self.count)+"/"+str(i)+".0")
        self.label.setStyleSheet("border : 4px solid black;")
        global a
        a+=1
        if a>=10:
            self.close()

class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'Window'
        self.left = 0
        self.top = 0
        self.width = 620
        self.height = 700
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.tab_widget = MyTabWidget(self)
        self.setCentralWidget(self.tab_widget)
        self.show()

I created 3 tabs in main window, but since it is not the problem with the tabs, I skipped this part of code

class MyTabWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        self.table = QTableWidget(self.tab3)
        self.table.move(20,80)
        self.table.setRowCount(10)
        self.table.setColumnCount(4)
        self.table.setColumnWidth(0,50)

        self.Load_data = QtWidgets.QPushButton(self.tab3)
        self.Load_data.setGeometry(QtCore.QRect(200, 10, 200, 50))
        self.Load_data.setText('&Start')
        self.Load_data.clicked.connect(self.show_Stoper)
        self.Load_data.clicked.connect(self.progress)

    def statusdone(self):
        self.table.setItem(a-1, 0, QTableWidgetItem("done"))
        self.table.setItem(a, 0, QTableWidgetItem("..."))

    def statusndone(self):
        self.table.setItem(a-1, 0, QTableWidgetItem("not done"))
        self.table.setItem(a, 0, QTableWidgetItem("..."))

    def show_Stoper(self):
        self.w = Stoper()
        self.w.show()

    def progress(self):
        global a
        self.table.setItem(a, 0, QTableWidgetItem("..."))

M = MyTabWidget()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

As you can see, I made a function statusdone and statusndone, which i want to call with a buttons in stopwatch called "Stoper". To make it work, I have created Instance of a class MyTabWidget. Unfortunately it only gives me error in this line:
MyTabWidget.init() missing 1 required positional argument: 'parent'
When i delete 'parent' from def init  and 'super', it returns error:
QWidget: Must construct a QApplication before a QWidget
What should I do to make it work. Do I have to modify the classes?


问:
Pointer to a temporary but still works?
The problem with the following is that the function returns a pointer to a temporary. However it builds and runs fine here, Qt Creator on macOS.

```<code>const char* get_str()
{
    QByteArray arr("Some text");
    return arr.constData();
}

int main()
{
    const char *s = get_str();
    printf("%s\n", s);
    return 0;
}
</code>```

How can I make it fail? Or is this one of those undefined behavior cases?

I think by doing printf("%s\n", get_str()); we escape the problem, right?

Title: Pointer to a temporary but still works?

Body:
The problem with the following is that the function returns a pointer to a temporary. However it builds and runs fine here, Qt Creator on macOS.

const char* get_str()
{
    QByteArray arr("Some text");
    return arr.constData();
}

int main()
{
    const char *s = get_str();
    printf("%s\n", s);
    return 0;
}

How can I make it fail? Or is this one of those undefined behavior cases?

I think by doing printf("%s\n", get_str()); we escape the problem, right?


问:
what should i do for the code that gives the number of green apples
```<code>import cv2
image = cv2.imread('elma.png')
originalResim=image.copy()
image_hsv = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
low_apple_red = (160, 153, 153)
high_apple_red = (180, 255, 255)
low_apple_raw = (0,150,150)
high_apple_raw = (15,255,255)

mask_red = cv2.inRange(image_hsv,low_apple_red,high_apple_red)
mask_raw = cv2.inRange(image_hsv,low_apple_raw,high_apple_raw)
mask = mask_red+mask_raw
cnts,_ = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
number=0
for i,c in enumerate(cnts):
    ((x, y), r) = cv2.minEnclosingCircle(c)
    if r>34:
        number+=1
        cv2.circle(image,(int(x),int(y)),int(r),(255,0,0),2)
        cv2.putText(image,"${}".format(number),(int(x)-10,int(y)),cv2.FONT_HERSHEY_SIMPLEX,0.6,(200,0,0),2)
    else:continue
cv2.imshow("OriginalElma",originalResim)
cv2.imshow("CerceveliElma",image)
#cv2.imshow("HSV Format",image_hsv)
#cv2.imshow("MaskeliResim",mask)
cv2.waitKey(0)
</code>```

it works for red apple but i try hsv code for green apple it doesn't work!!!

original images :
enter image description here

enter image description here

Body:
import cv2
image = cv2.imread('elma.png')
originalResim=image.copy()
image_hsv = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
low_apple_red = (160, 153, 153)
high_apple_red = (180, 255, 255)
low_apple_raw = (0,150,150)
high_apple_raw = (15,255,255)

mask_red = cv2.inRange(image_hsv,low_apple_red,high_apple_red)
mask_raw = cv2.inRange(image_hsv,low_apple_raw,high_apple_raw)
mask = mask_red+mask_raw
cnts,_ = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
number=0
for i,c in enumerate(cnts):
    ((x, y), r) = cv2.minEnclosingCircle(c)
    if r>34:
        number+=1
        cv2.circle(image,(int(x),int(y)),int(r),(255,0,0),2)
        cv2.putText(image,"${}".format(number),(int(x)-10,int(y)),cv2.FONT_HERSHEY_SIMPLEX,0.6,(200,0,0),2)
    else:continue
cv2.imshow("OriginalElma",originalResim)
cv2.imshow("CerceveliElma",image)
#cv2.imshow("HSV Format",image_hsv)
#cv2.imshow("MaskeliResim",mask)
cv2.waitKey(0)

it works for red apple but i try hsv code for green apple it doesn't work!!!

original images :
enter image description here

enter image description here


问:
Application not displaying a 404 Not Found Page for ASP.NET Core 6.0 MVC when using identityserver 4
I am using IdenitityServer 4 to hendle my users, However, when a user browses a URL that does not exist, it redirects them to the login page instead of /not-found page. What am I missing?

Program.cs

```<code>// IdentityServer4 configurations
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "cookies";
    options.DefaultChallengeScheme = "oidc";
}).AddCookie("cookies", c => c.ExpireTimeSpan = TimeSpan.FromHours(8))
.AddOpenIdConnect("oidc", options =>
{
    options.Authority = builder.Configuration["ServiceUrls:IdentityApi"];
    options.GetClaimsFromUserInfoEndpoint = true;
    options.ClientId = "WebClient";
    options.ClientSecret = "secret";
    options.ResponseType = "code";
    options.ClaimActions.MapJsonKey("role", "role", "role");
    options.ClaimActions.MapJsonKey("sub", "sub", "sub");
    options.TokenValidationParameters.NameClaimType = "name";
    options.TokenValidationParameters.RoleClaimType = "role";
    options.Scope.Add("admin");
    options.SaveTokens = true;
});

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

//Hnadle unhandled exceptions 500 erros
app.UseExceptionHandler("/server-error");
//Handle 404 erros
app.Use(async (ctx, next) =>
{
    await next();
    if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
    {
        ctx.Request.Path = "/not-found";
        await next();
    }
});
</code>```

HomeController.cs

```<code>[HttpGet]
[Route("not-found")]
public IActionResult PageNotFound()
{
    return View();
}
</code>```

Body:
I am using IdenitityServer 4 to hendle my users, However, when a user browses a URL that does not exist, it redirects them to the login page instead of /not-found page. What am I missing?

Program.cs

// IdentityServer4 configurations
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "cookies";
    options.DefaultChallengeScheme = "oidc";
}).AddCookie("cookies", c => c.ExpireTimeSpan = TimeSpan.FromHours(8))
.AddOpenIdConnect("oidc", options =>
{
    options.Authority = builder.Configuration["ServiceUrls:IdentityApi"];
    options.GetClaimsFromUserInfoEndpoint = true;
    options.ClientId = "WebClient";
    options.ClientSecret = "secret";
    options.ResponseType = "code";
    options.ClaimActions.MapJsonKey("role", "role", "role");
    options.ClaimActions.MapJsonKey("sub", "sub", "sub");
    options.TokenValidationParameters.NameClaimType = "name";
    options.TokenValidationParameters.RoleClaimType = "role";
    options.Scope.Add("admin");
    options.SaveTokens = true;
});

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

//Hnadle unhandled exceptions 500 erros
app.UseExceptionHandler("/server-error");
//Handle 404 erros
app.Use(async (ctx, next) =>
{
    await next();
    if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
    {
        ctx.Request.Path = "/not-found";
        await next();
    }
});

HomeController.cs

[HttpGet]
[Route("not-found")]
public IActionResult PageNotFound()
{
    return View();
}


问:
Nextjs - Implementing next-auth middleware in addition to nextjs middleware
I need the nextjs middleware to run for two different paths:

First, to protect against unauthorized access which is achieved using next-auth.

Second, to redirect authorized users from certain pages e.g. if an authorized user lands on anything under the auth namespace, then redirect to them to the dashboard. (I know I can do this on the client, but its much cleaner on the middleware level, imo).

Problem is that it looks like next-auth takes over the entire middleware logic:

import { withAuth } from "next-auth/middleware"

export default withAuth(
  function middleware(req) {
    console.log(req.nextauth.token)
  },
  {
    callbacks: {
      authorized: ({ token }) => token?.role === "admin",
    },
  }
)

export const config = { matcher: ["/dashboard/:path*", "/auth/:path*"] };

```

Is it possible to move this logic to a regular nextjs middleware? If not, how is it possible to implement logic unrelated next-auth, but in addition to it?

Body:
I need the nextjs middleware to run for two different paths:

First, to protect against unauthorized access which is achieved using next-auth.

Second, to redirect authorized users from certain pages e.g. if an authorized user lands on anything under the auth namespace, then redirect to them to the dashboard. (I know I can do this on the client, but its much cleaner on the middleware level, imo).

Problem is that it looks like next-auth takes over the entire middleware logic:

import { withAuth } from "next-auth/middleware"

export default withAuth(
  function middleware(req) {
    console.log(req.nextauth.token)
  },
  {
    callbacks: {
      authorized: ({ token }) => token?.role === "admin",
    },
  }
)

export const config = { matcher: ["/dashboard/:path*", "/auth/:path*"] };

Is it possible to move this logic to a regular nextjs middleware? If not, how is it possible to implement logic unrelated next-auth, but in addition to it?


问:
php API in android is realtime to access with volley?
i want to use volley to access my PHP API in realtime

is that even possible?

can i reflect database changes in my application in realtime like we can do in firebase ?


问:
In ColdFusion do I add to the title tag from a document that is "Included"?
I have an index page that calls several includes using variables. Part of my site has an inventory section. I would like to insert the name of the inventory item into the title tag. From the index, I can tailor the title tag in the header to show the section and categories, but since the query for the individual item is in the included file, that variable doesn't exist yet when the index comes up. I tried to use the cfhtmlhead from the inventory page, but it neither adds to nor replaces the title that is called in the index.cfm page. Here is my code, but it doesn't work.

```<code><cfhtmlhead text="<title>xxxx</title>"></cfhtmlhead>
</code>```

I guess, I could pass the inventory item name in the URL, but most items have spaces in them and then I have to deal with that too.

Thanks,
Kirk

cfhtmlhead doesn't seem to work when it is in cfincludes

Body:
I have an index page that calls several includes using variables. Part of my site has an inventory section. I would like to insert the name of the inventory item into the title tag. From the index, I can tailor the title tag in the header to show the section and categories, but since the query for the individual item is in the included file, that variable doesn't exist yet when the index comes up. I tried to use the cfhtmlhead from the inventory page, but it neither adds to nor replaces the title that is called in the index.cfm page. Here is my code, but it doesn't work.

<cfhtmlhead text="<title>xxxx</title>"></cfhtmlhead>

I guess, I could pass the inventory item name in the URL, but most items have spaces in them and then I have to deal with that too.

Thanks,
Kirk

cfhtmlhead doesn't seem to work when it is in cfincludes


问:
ASP.NET WebAPI. Do not persist sessions
I have an ASP.NET 6 WebAPI application.
I've implemented login functionality, which boils down to calling:

```<code>await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
</code>```

It sets a cookie with key .AspNetCore.Cookies and value of ID of the user session.

Somehow these sessions are persisted across WebAPI restarts. User agent with this cookie is still logged in when sending HTTP requests to WebAPI after restart. Where these sessions are persisted? Is there a way to disable this behaviour?

For clarity: I'm not using .AspNetCore.Session-related functionality, we're speaking solely on .AspNetCore.Cookies based user authentication.

Thanks in advance.

Title: ASP.NET WebAPI. Do not persist sessions

Body:
I have an ASP.NET 6 WebAPI application.
I've implemented login functionality, which boils down to calling:

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);

It sets a cookie with key .AspNetCore.Cookies and value of ID of the user session.

Somehow these sessions are persisted across WebAPI restarts. User agent with this cookie is still logged in when sending HTTP requests to WebAPI after restart. Where these sessions are persisted? Is there a way to disable this behaviour?

For clarity: I'm not using .AspNetCore.Session-related functionality, we're speaking solely on .AspNetCore.Cookies based user authentication.

Thanks in advance.


问:
ASP.NET webforms 4.8 implement multi-lang website
I want to change the lang between english and arabic using webforms and ASP.NET . I already created 2 resource files and added them to assembly.

I tried to implement this code:

```<code>        protected void ddLang_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["Lang"] = ddLang.SelectedValue;
            loadString();
        }

        private void loadString()
        {

            Thread.CurrentThread.CurrentCulture = new CultureInfo(Session["Lang"].ToString());
            rm = new ResourceManager("WebPortal2020.App_GlobalResources.Lang", Assembly.GetExecutingAssembly()); //we configure resource manages for mapping with resource files in App_GlobalResources folder.
            ci = Thread.CurrentThread.CurrentCulture;
            LblDashboard.Text = rm.GetString("Dashboard", ci); //Name is the resource manager string name that should mathch with Name solumn of resorce files and if that matches then the value against the name will be translated as mentioned for each languages.

        }
</code>```

andf i defined the Dashboard key in both eng and arabic rscr file.

Bu ti am getting this error :

Body:
I want to change the lang between english and arabic using webforms and ASP.NET . I already created 2 resource files and added them to assembly.

I tried to implement this code:

        protected void ddLang_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["Lang"] = ddLang.SelectedValue;
            loadString();
        }

        private void loadString()
        {

            Thread.CurrentThread.CurrentCulture = new CultureInfo(Session["Lang"].ToString());
            rm = new ResourceManager("WebPortal2020.App_GlobalResources.Lang", Assembly.GetExecutingAssembly()); //we configure resource manages for mapping with resource files in App_GlobalResources folder.
            ci = Thread.CurrentThread.CurrentCulture;
            LblDashboard.Text = rm.GetString("Dashboard", ci); //Name is the resource manager string name that should mathch with Name solumn of resorce files and if that matches then the value against the name will be translated as mentioned for each languages.

        }

andf i defined the Dashboard key in both eng and arabic rscr file.

Bu ti am getting this error :


问:
Warning: Prop `id` did not match. shown when using the CreatableSelect in Nextjs
Error Message From Console

image of error here

I use the CreatableSelect component from the react-select module to create my search bar.

this is my code

```<code><CreatableSelect
   id={"search-bar"}
   defaultValue={{
      label: wordEntered || "Enter your search keyword",
   }}
   options={[
      ...filteredData.map((item) => {
         return {
            value: item,
            label: item.name,
         }
      })
   ]}
   components={{
      DropdownIndicator: () => null,
      IndicatorSeparator: () => null,
      NoOptionsMessage: () => (
         <span className={"mx-2"}>
            Press Enter to Search for {wordEntered}
         </span>
      ),
   }}

   onInputChange={(value) => {
      setWordEntered(value)
   }}
   onChange={(value) => {
      goToSearch(value.value)
   }}
   getOptionLabel={(option) => {
      return (
         <>
            {wordEntered && wordEntered.length > 0 && <span>
               Search for {option.value}
            </span>}
            {(!wordEntered || !wordEntered.length) && <span>
               Enter your search keyword
            </span>}
         </>
      )
   }}
/>
</code>```

My Main Issue is that I have no idea why there is a change in the value between server and client.

A description to the issue might help me solve it, thank you in adv. :)

I was expecting a problem with the assignable id prop however when I tried to statically type it, and call it "search-bar" that didn't work.

Body:
Error Message From Console

image of error here

I use the CreatableSelect component from the react-select module to create my search bar.

this is my code

<CreatableSelect
   id={"search-bar"}
   defaultValue={{
      label: wordEntered || "Enter your search keyword",
   }}
   options={[
      ...filteredData.map((item) => {
         return {
            value: item,
            label: item.name,
         }
      })
   ]}
   components={{
      DropdownIndicator: () => null,
      IndicatorSeparator: () => null,
      NoOptionsMessage: () => (

            Press Enter to Search for {wordEntered}

      ),
   }}

   onInputChange={(value) => {
      setWordEntered(value)
   }}
   onChange={(value) => {
      goToSearch(value.value)
   }}
   getOptionLabel={(option) => {
      return (
         <>
            {wordEntered && wordEntered.length > 0 &&
               Search for {option.value}
            }
            {(!wordEntered || !wordEntered.length) &&
               Enter your search keyword
            }
         </>
      )
   }}
/>

My Main Issue is that I have no idea why there is a change in the value between server and client.

A description to the issue might help me solve it, thank you in adv. :)

I was expecting a problem with the assignable id prop however when I tried to statically type it, and call it "search-bar" that didn't work.


问:
Spring Security FilterChain Not getting executed in Order
Requirements:
user will be able to login to the system through two different login urls

admin users will login -> /admin_login

guest users will login -> /guset_login
different authentication source for both the users

question:
when login through admin user, able to see all the admin pages and everything working fine
but trying to access guest user pages giving 404(not found) error, it should redirect to guest user login page

same when login through guest user , able to see all the pages accessible to guest user, but while accessing admin user pages it giving 404 error. it should redirect to admin login page

SecurityConfigone Class:

```<code>package com.securityexample;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.securityexample.providers.GuestAuthenticationProvider;
import com.securityexample.providers.MyCustomAuthenticationProvider;

@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfigOrder1 {

    @Autowired
    MyCustomAuthenticationProvider myCustomeAuthenticationProvider;

    @Bean
    public SecurityFilterChain filterChainApp1(HttpSecurity http) throws Exception {
        http.authenticationProvider(myCustomeAuthenticationProvider);

        http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAuthority("ADMIN").and().formLogin()
                .loginPage("/admin_login").loginProcessingUrl("/admin/process-login")
                .failureUrl("/admin_login?error=error").defaultSuccessUrl("/admin/page1").usernameParameter("username")
                .passwordParameter("password").and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/admin/logout"))
                .logoutSuccessUrl("/admin_login?logout=true").deleteCookies("JSESSIONID").and().exceptionHandling()
                .accessDeniedPage("/access-denied").and().csrf().disable();

        return http.build();
    }

}

</code>```

SecurityConfigClass2

```<code>
package com.securityexample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.securityexample.providers.GuestAuthenticationProvider;

@Configuration
@EnableWebSecurity
@Order(2)
public class SecurityConfigOrder2 {
    @Autowired
    GuestAuthenticationProvider guestAuthenticationProvider;

    @Bean
    public SecurityFilterChain filterChaninApp2(HttpSecurity http) throws Exception {

        http.authenticationProvider(guestAuthenticationProvider);

        http.antMatcher("/guest/**").authorizeRequests().anyRequest().hasAuthority("GUEST_USER").and().formLogin()
                .loginPage("/guest_login").loginProcessingUrl("/guest/process-login")
                .failureUrl("/guest_login?error=error").defaultSuccessUrl("/guest/page1").usernameParameter("username")
                .passwordParameter("otp").and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/guest/logout"))
                .logoutSuccessUrl("/guest_login?logout=true").deleteCookies("JSESSIONID").and().exceptionHandling()
                .accessDeniedPage("/access-denied").and().csrf().disable();

        return http.build();
    }
}

</code>```

please need help, if anybody could help ?

getting error while accessing guest user pages if login as admin user
and vice versa.

```<code>
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Dec 27 22:26:41 IST 2022
There was an unexpected error (type=Not Found, status=404).
No message available

</code>```

Body:
Requirements:
user will be able to login to the system through two different login urls

admin users will login -> /admin_login

guest users will login -> /guset_login
different authentication source for both the users

question:
when login through admin user, able to see all the admin pages and everything working fine
but trying to access guest user pages giving 404(not found) error, it should redirect to guest user login page

same when login through guest user , able to see all the pages accessible to guest user, but while accessing admin user pages it giving 404 error. it should redirect to admin login page

SecurityConfigone Class:

package com.securityexample;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.securityexample.providers.GuestAuthenticationProvider;
import com.securityexample.providers.MyCustomAuthenticationProvider;

@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfigOrder1 {

    @Autowired
    MyCustomAuthenticationProvider myCustomeAuthenticationProvider;

    @Bean
    public SecurityFilterChain filterChainApp1(HttpSecurity http) throws Exception {
        http.authenticationProvider(myCustomeAuthenticationProvider);

        http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAuthority("ADMIN").and().formLogin()
                .loginPage("/admin_login").loginProcessingUrl("/admin/process-login")
                .failureUrl("/admin_login?error=error").defaultSuccessUrl("/admin/page1").usernameParameter("username")
                .passwordParameter("password").and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/admin/logout"))
                .logoutSuccessUrl("/admin_login?logout=true").deleteCookies("JSESSIONID").and().exceptionHandling()
                .accessDeniedPage("/access-denied").and().csrf().disable();

        return http.build();
    }

}

SecurityConfigClass2

package com.securityexample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.securityexample.providers.GuestAuthenticationProvider;

@Configuration
@EnableWebSecurity
@Order(2)
public class SecurityConfigOrder2 {
    @Autowired
    GuestAuthenticationProvider guestAuthenticationProvider;

    @Bean
    public SecurityFilterChain filterChaninApp2(HttpSecurity http) throws Exception {

        http.authenticationProvider(guestAuthenticationProvider);

        http.antMatcher("/guest/**").authorizeRequests().anyRequest().hasAuthority("GUEST_USER").and().formLogin()
                .loginPage("/guest_login").loginProcessingUrl("/guest/process-login")
                .failureUrl("/guest_login?error=error").defaultSuccessUrl("/guest/page1").usernameParameter("username")
                .passwordParameter("otp").and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/guest/logout"))
                .logoutSuccessUrl("/guest_login?logout=true").deleteCookies("JSESSIONID").and().exceptionHandling()
                .accessDeniedPage("/access-denied").and().csrf().disable();

        return http.build();
    }
}

please need help, if anybody could help ?

getting error while accessing guest user pages if login as admin user
and vice versa.

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Dec 27 22:26:41 IST 2022
There was an unexpected error (type=Not Found, status=404).
No message available


问:
How to replace node-fetch with a runtime agnostic/worker fetch dependency?
I have a dependency that's using node-fetch. The dependency itself checks for the existence of the library or falls back to global fetch. In dev I'd like to use node-fetch since I'm in Node however when I build for deploy to a Cloudflare worker I'd like it to be stripped from the build process entirely.</p>


问:
How to extract the transformations that have been applied to an image from a psd file using python?
I have a psd file that contains several layers. In this file, I have applied a rotation and a translation. Then I want to extract the parameters of these transformations using python But I could not get this information.

Thanks for your help.


问:
Iteration over collection VS using enumerator
```<code>var range = Enumerable.Range(0, 1000);

foreach (var i in new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 })
{
    foreach (var r in range)
    {
        var d = range.Contains(i);
    }
}
</code>```

Given that 'range' variable content is available from memory what would be the best choice?

To keep iterator var range = Enumerable.Range(0, 1000); and have it work over 10 times

To convert into a collection var range = Enumerable.Range(0, 1000).ToArray(); and call Contains on an already created collection

Body:
var range = Enumerable.Range(0, 1000);

foreach (var i in new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 })
{
    foreach (var r in range)
    {
        var d = range.Contains(i);
    }
}

Given that 'range' variable content is available from memory what would be the best choice?

To keep iterator var range = Enumerable.Range(0, 1000); and have it work over 10 times

To convert into a collection var range = Enumerable.Range(0, 1000).ToArray(); and call Contains on an already created collection


Title: How to update Iceberg table storing time series data

Body:
I'm trying to apply some updates to an Iceberg table using pyspark. The original data in the table is:

+-------------------+---+---+
|               time|  A|  B|
+-------------------+---+---+
|2022-12-01 00:00:00|  1|  6|
|2022-12-02 00:00:00|  2|  7|
|2022-12-03 00:00:00|  3|  8|
|2022-12-04 00:00:00|  4|  9|
|2022-12-05 00:00:00|  5| 10|
+-------------------+---+---+

And the update (stored as a temporary view) is:

+-------------------+---+---+
|               time|  A|  C|
+-------------------+---+---+
|2022-12-04 00:00:00| 40| 90|
|2022-12-05 00:00:00| 50|100|
+-------------------+---+---+

I'd like to end up with:

+-------------------+----+---+----+
|               time|   A|  B|   C|
+-------------------+----+---+----+
|2022-12-01 00:00:00|   1|  6| NaN|
|2022-12-02 00:00:00|   2|  7| NaN|
|2022-12-03 00:00:00|   3|  8| NaN|
|2022-12-04 00:00:00|  40|  9|  90|
|2022-12-05 00:00:00|  50| 10| 100|
+-------------------+----+---+----+

As per the docs, I've tried the query:

spark.sql("MERGE INTO db.data d USING update u ON d.time = u.time"
          " WHEN MATCHED THEN UPDATE SET * WHEN NOT MATCHED THEN INSERT *")

but it fails because the update doesn't contain column B. Also, even if the update did contain column B, column C wouldn't get added in the result, because it isn't in the original table. Is there anything I can do to get the behaviour I'm after?

Thanks for any help.


问:
How to move data from sign up form to other screen using callback function with model
I have created a signup form and client want that data to show on other screen with callback function.
Below is requirement. Anyoneplease guide me how can I achive the below thing in flutter

No database integration needed. I just need you to create a widget with a callback function in parameter that will return all data when signup button is clicked. Data needs to be in a model.


问:
Inserting or removing line(s) inside a folded region causes it to unfold
When I have the same document open in two different editors, if I fold a region inside one editor and insert or remove a line in the folded region with the other editor, it causes the folded region in the first editor to unfold. Other changes do not seem to cause the unfold.

Same problem in monaco editor and can't find an option to disable it.
How do I prevent it?


问:
Angular: How can I access a file that has been created by Webpack in runtime on an Angular dev server
thank you for your time.
I need help with my angular app.
I have a custom webpack config where I group a bunch of json files to one and save it as a new json file:

new MergeJsonWebpackPlugin({
  output: {
    groupBy: [
      { pattern: './i18n/en/*.json', fileName: './i18n/en.json' },
      // jhipster-needle-i18n-language-webpack - JHipster will add/remove languages in this array
    ],
  },
})
```

Later in this webpack file I want to access this new json file.

But im not able to access './i18n/en.json' because I am on a angular development server.
To build the app first with ng build is no option for me.

Is there a way to access this file on a dev server?

Body:
thank you for your time.
I need help with my angular app.
I have a custom webpack config where I group a bunch of json files to one and save it as a new json file:

new MergeJsonWebpackPlugin({
  output: {
    groupBy: [
      { pattern: './i18n/en/*.json', fileName: './i18n/en.json' },
      // jhipster-needle-i18n-language-webpack - JHipster will add/remove languages in this array
    ],
  },
})

Later in this webpack file I want to access this new json file.

But im not able to access './i18n/en.json' because I am on a angular development server.
To build the app first with ng build is no option for me.

Is there a way to access this file on a dev server?


问:
Learning-curve for classification in python
To plot the learning-curve in a regression problem, we should use 'RMSE' as a measure of analysis, like:

```<code>def plot_learning_curves(model, X_train, y_train, X_val, y_val):
    plt.figure(figsize=(15, 5))
    train_errors, val_errors = [], []
    for m in range(5, len(X_train)):
        model.fit(X_train[:m], y_train[:m])
        y_train_predict = model.predict(X_train[:m])
        y_val_predict = model.predict(X_val)
        train_errors.append(metrics.mean_squared_error(y_train_predict, y_train[:m]))
        val_errors.append(metrics.mean_squared_error(y_val_predict, y_val))
    plt.plot(np.sqrt(train_errors), "r-+", linewidth=1, label="training data")
    plt.plot(np.sqrt(val_errors), "b-", linewidth=1, label="validation data")
    plt.legend(loc="upper right", fontsize=10)
    plt.xlabel("Size", fontsize=10)
    plt.ylabel("RMSE", fontsize=10)
    plt.title("Learning Curves")
    plt.show()
</code>```

However, I would like to have a learning curve for the classification problem, and I know that we should use accuracy as a metric for analysis instead of 'RMSE'.

So far, I've only found snippet codes for this problem using the 'learning-curve' class in sklearn , like:

```<code>from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit

def plot_learning_curve(estimator, X, y, ax=None, cv=None, n_jobs=4, train_sizes=np.linspace(.1, 1.0, 5)):

train_sizes, train_scores, test_scores = \
    learning_curve(estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)

# Plot learning curve
ax.set_xlabel("Training examples")
ax.set_ylabel("Score")
ax.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score")
ax.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score")
ax.legend(loc="best")

return plt
</code>```

However, as you can see in this solution, we need to pass the x and y datasets and it uses cross-validation to split them into train and test datasets.

But, I've already split my dataset and applied a lot of preprocessing to x-train and x-test.

So, I intend to use my train and test dataset just like the code I wrote for the regression problem, which is based on the "RMSE" metric (without using the "learning-curve" class in sklearn).

Body:
To plot the learning-curve in a regression problem, we should use 'RMSE' as a measure of analysis, like:

def plot_learning_curves(model, X_train, y_train, X_val, y_val):
    plt.figure(figsize=(15, 5))
    train_errors, val_errors = [], []
    for m in range(5, len(X_train)):
        model.fit(X_train[:m], y_train[:m])
        y_train_predict = model.predict(X_train[:m])
        y_val_predict = model.predict(X_val)
        train_errors.append(metrics.mean_squared_error(y_train_predict, y_train[:m]))
        val_errors.append(metrics.mean_squared_error(y_val_predict, y_val))
    plt.plot(np.sqrt(train_errors), "r-+", linewidth=1, label="training data")
    plt.plot(np.sqrt(val_errors), "b-", linewidth=1, label="validation data")
    plt.legend(loc="upper right", fontsize=10)
    plt.xlabel("Size", fontsize=10)
    plt.ylabel("RMSE", fontsize=10)
    plt.title("Learning Curves")
    plt.show()

However, I would like to have a learning curve for the classification problem, and I know that we should use accuracy as a metric for analysis instead of 'RMSE'.

So far, I've only found snippet codes for this problem using the 'learning-curve' class in sklearn , like:

from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit

def plot_learning_curve(estimator, X, y, ax=None, cv=None, n_jobs=4, train_sizes=np.linspace(.1, 1.0, 5)):

train_sizes, train_scores, test_scores = \
    learning_curve(estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)

# Plot learning curve
ax.set_xlabel("Training examples")
ax.set_ylabel("Score")
ax.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score")
ax.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score")
ax.legend(loc="best")

return plt

However, as you can see in this solution, we need to pass the x and y datasets and it uses cross-validation to split them into train and test datasets.

But, I've already split my dataset and applied a lot of preprocessing to x-train and x-test.

So, I intend to use my train and test dataset just like the code I wrote for the regression problem, which is based on the "RMSE" metric (without using the "learning-curve" class in sklearn).


问:
A standalone Rasp pi running a web server. Possible?
I have a rasp pi 3 which controls an irrigation system. The pi is headless, and is controlled via the home network by running a Tomcat server, which creates a UI. Mostly, the irrigation system is automatic, but I can log in to the Tomcat server to see the log of its activities, or change settings, or update the planting plan or manually control the sprinklers.

Now I'd like something similar, but in a place where there is no internet available. That is, I'd like to use the pi as a standalone web server, so that I can access the UI using a browser on my phone. I've looked through the rasp pi documentation, but it describes setting up access points, which seem to depend on a wired connection between the pi and the router. I've read about connecting via SSH to a standalone setup, but that article said that support for a standalone server isn't available.

Is what I'm looking for possible?

Thanks,

John


问:
Problem with data persisting when returning after navigating a fragment
I am repeating the process of adding and completing the list on the detail screen.

The problem is that the previous list remains intact in the newly created detail fragment.

For example, if i made 3 lists in the previous detail screen, adding data in the new detail screen will add them to a list of size 3.

I've tried various things, but I still don't know what could be the cause.

Fragment

```<code>class WriteDetailFragment :  Fragment() {
    ...
    private val viewModel: WriteDetailViewModel by viewModels {
        WriteDetailViewModelFactory(
            (requireActivity().application as WorkoutApplication).writeDetailRepo
        )
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentWriteDetailBinding.inflate(inflater, container, false)

        binding.apply {
            adapter = DetailAdapter()
            rv.adapter = adapter
            rv.itemAnimator = null

            // add set
            addSet.setOnClickListener {
                viewModel.addSet()
            }
            // complete
            complete.setOnClickListener {
                findNavController().navigate(R.id.action_writeDetailFragment_to_addRoutineFragment)
            }
        }

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.items.collect { list ->
                    adapter.submitList(list)
                }
            }
        }
    }
}
</code>```

ViewModel

```<code>class WriteDetailViewModel(
    private val repository: WriteDetailRepository
    ): ViewModel() {

    private var _items: MutableStateFlow<List<WorkoutSetInfo>> = MutableStateFlow(listOf())
    val items = _items.asStateFlow()

    fun addSet() {
        viewModelScope.launch(Dispatchers.IO) {
            repository.add()
            _items.value = repository.getList()
        }
    }
}
</code>```

Repository

```<code>class WriteDetailRepository(val dao: WorkoutDao) {
    private var setInfoList = ArrayList<WorkoutSetInfo>()
    private lateinit var updatedList: List<WorkoutSetInfo>

    fun add() {
        val item = WorkoutSetInfo(set = setInfoList.size + 1)
        setInfoList.add(item)
        updatedList = setInfoList.toList()
    }
    fun getList() : List<WorkoutSetInfo> = updatedList
}
</code>```

Body:
I am repeating the process of adding and completing the list on the detail screen.

The problem is that the previous list remains intact in the newly created detail fragment.

For example, if i made 3 lists in the previous detail screen, adding data in the new detail screen will add them to a list of size 3.

I've tried various things, but I still don't know what could be the cause.

Fragment

class WriteDetailFragment :  Fragment() {
    ...
    private val viewModel: WriteDetailViewModel by viewModels {
        WriteDetailViewModelFactory(
            (requireActivity().application as WorkoutApplication).writeDetailRepo
        )
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentWriteDetailBinding.inflate(inflater, container, false)

        binding.apply {
            adapter = DetailAdapter()
            rv.adapter = adapter
            rv.itemAnimator = null

            // add set
            addSet.setOnClickListener {
                viewModel.addSet()
            }
            // complete
            complete.setOnClickListener {
                findNavController().navigate(R.id.action_writeDetailFragment_to_addRoutineFragment)
            }
        }

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.items.collect { list ->
                    adapter.submitList(list)
                }
            }
        }
    }
}

ViewModel

class WriteDetailViewModel(
    private val repository: WriteDetailRepository
    ): ViewModel() {

    private var _items: MutableStateFlow<List<WorkoutSetInfo>> = MutableStateFlow(listOf())
    val items = _items.asStateFlow()

    fun addSet() {
        viewModelScope.launch(Dispatchers.IO) {
            repository.add()
            _items.value = repository.getList()
        }
    }
}

Repository

class WriteDetailRepository(val dao: WorkoutDao) {
    private var setInfoList = ArrayList<WorkoutSetInfo>()
    private lateinit var updatedList: List<WorkoutSetInfo>

    fun add() {
        val item = WorkoutSetInfo(set = setInfoList.size + 1)
        setInfoList.add(item)
        updatedList = setInfoList.toList()
    }
    fun getList() : List<WorkoutSetInfo> = updatedList
}


问:
How to start elasticsearch via systemctl 8.5v by using systemctl? in linux

I have tried to install older version with sudo but it is not working, but we have removed elastic search by using "yum remove elasticsearch" and I have tried to use 8.5 version but unable to start.
any help is very much appriciated. Thank you in advance.


问:
how get all tables where name of table between a date
I have an api that allows get all tables that are between two specific dates ,at first i tried to put query parameters comme ci-dessous

I used enrich mediator to display table to the do substring
this my code

```<code>        <inSequence>
            <script language="js"><![CDATA[var table = mc.getProperty('query.param.table');
table =table.toString();
mc.setProperty('table',table);]]></script>
            <property expression="get-property('table')" name="uri.var.table" scope="default" type="STRING"/>
            <call>
                <endpoint>
                    <http method="get" uri-template="http://ITMTNF3RRJSJ:8290/services/studenttest/readtable?table={uri.var.table}">
                        <suspendOnFailure>
                            <initialDuration>-1</initialDuration>
                            <progressionFactor>-1</progressionFactor>
                            <maximumDuration>0</maximumDuration>
                        </suspendOnFailure>
                        <markForSuspension>
                            <retriesBeforeSuspension>0</retriesBeforeSuspension>
                        </markForSuspension>
                    </http>
                </endpoint>
            </call>
            <enrich>
                <source clone="true" type="inline">
                    {"nomtable":""
                    }
                </source>
                <target action="child" xpath="json-eval($.tables)"/>
            </enrich>
            <enrich>
                <source clone="true" property="uri.var.table" type="property"/>
                <target xpath="json-eval($.tables.nomtable)"/>
            </enrich>
               <iterate expression="//tables">
                <target>
                    <sequence>
            <property expression="json-eval($.tables.nomtable)" name="nomtable" scope="default" type="STRING"/>
            <log level="custom">
                <property expression="get-property('nomtable')" name="m"/>
            </log>
                        <script language="js"><![CDATA[var str = mc.getProperty('nomtable');
var annee= str.substr(1, 4);
annee==annee.toString();
var mois=str.substr(5, 2);
var jour=str.substr(7, 2);
mc.setProperty('annee',annee);
mc.setProperty('mois',mois);
mc.setProperty('jour',jour);]]></script>
                        <log level="custom">
                            <property expression="get-property('annee')" name="annee" />
                        </log>
                        <log level="custom">
                            <property expression="get-property('mois')" name="mois" />
                        </log>
                        <log level="custom">
                            <property expression="get-property('jour')" name="jour" />
                        </log>
                    </sequence>
                </target>
            </iterate>
            <property name="messageType" scope="axis2" type="STRING" value="application/json"/>
            <property name="ContentType" scope="axis2" type="STRING" value="application/json"/>
            <respond/>
</code>```

but i have the  result

 INFO {LogMediator} - m = `20221018`,`20221211`  INFO {LogMediator} - {api:student} annee = 2022 mois = 10 jour = 18

the problem i have two name of table as a date 20221018and 20221211i want extract annee mois and jour of the two table  but i can't browse both tables .

Body:
I have an api that allows get all tables that are between two specific dates ,at first i tried to put query parameters comme ci-dessous

I used enrich mediator to display table to the do substring
this my code

        <inSequence>

            <property expression="get-property('table')" name="uri.var.table" scope="default" type="STRING"/>
            <call>
                <endpoint>
                    <http method="get" uri-template="http://ITMTNF3RRJSJ:8290/services/studenttest/readtable?table={uri.var.table}">
                        <suspendOnFailure>
                            <initialDuration>-1</initialDuration>
                            <progressionFactor>-1</progressionFactor>
                            <maximumDuration>0</maximumDuration>
                        </suspendOnFailure>
                        <markForSuspension>
                            <retriesBeforeSuspension>0</retriesBeforeSuspension>
                        </markForSuspension>
                    </http>
                </endpoint>
            </call>
            <enrich>
                <source clone="true" type="inline">
                    {"nomtable":""
                    }
                </source>
                <target action="child" xpath="json-eval($.tables)"/>
            </enrich>
            <enrich>
                <source clone="true" property="uri.var.table" type="property"/>
                <target xpath="json-eval($.tables.nomtable)"/>
            </enrich>
               <iterate expression="//tables">
                <target>
                    <sequence>
            <property expression="json-eval($.tables.nomtable)" name="nomtable" scope="default" type="STRING"/>
            <log level="custom">
                <property expression="get-property('nomtable')" name="m"/>
            </log>

                        <log level="custom">
                            <property expression="get-property('annee')" name="annee" />
                        </log>
                        <log level="custom">
                            <property expression="get-property('mois')" name="mois" />
                        </log>
                        <log level="custom">
                            <property expression="get-property('jour')" name="jour" />
                        </log>
                    </sequence>
                </target>
            </iterate>
            <property name="messageType" scope="axis2" type="STRING" value="application/json"/>
            <property name="ContentType" scope="axis2" type="STRING" value="application/json"/>
            <respond/>

but i have the  result

 INFO {LogMediator} - m = `20221018`,`20221211`  INFO {LogMediator} - {api:student} annee = 2022 mois = 10 jour = 18

the problem i have two name of table as a date 20221018and 20221211i want extract annee mois and jour of the two table  but i can't browse both tables .


问:
Why Laravel adldap2 does not work when using SSL?
Using adldap2, I can contact to LDAP server without SSL on port 389.

But as soon as I change

use_ssl to true and LDAP_PORT to 636, in ldap.php, it gives me Error 500.

(I also add the LDAP_USERNAME and LDAP_PASSWORD in the .env file)

The error 500 looks like it came from IIS and not Laravel itself, but there is nothing in the logs of IIS and the only log in Laravel is just saying

Can't contact LDAP server at... C:\...Guard.php

How can I check why it's happening? Could it be related to a certificate?


问:
Unable to put a quote at the end of a variable value Bash
I'm getting the URL from the curl respond and assigning it to a variable. After that, I try to wrap the variable in different ways in single quotes inside which the URL is located to make a curl request. But when I try to do this, the second quote goes to the beginning of the string and not to the end of the variable value

EXAMPLE:

```<code>request1=$(curl ...)
echo $request1
https://exapmle.com/....realybigurl
# try wrap url
echo "'"$requestq1"'" # or "'""$request1""'" or \'"$request1"\'
#and getting
**'**https://example.com/auth/realms/blabla.....
.....redirect_uri=https......
**'**scope=openid
</code>```

The second quote goes to the beginning of the new line, not the end of variable. how to put it there?
but the interesting thing is that this request works fine in git-bash but not in linux console (bash version 4.4 and 5.0.17)

Body:
I'm getting the URL from the curl respond and assigning it to a variable. After that, I try to wrap the variable in different ways in single quotes inside which the URL is located to make a curl request. But when I try to do this, the second quote goes to the beginning of the string and not to the end of the variable value

EXAMPLE:

request1=$(curl ...)
echo $request1
https://exapmle.com/....realybigurl
# try wrap url
echo "'"$requestq1"'" # or "'""$request1""'" or \'"$request1"\'
#and getting
**'**https://example.com/auth/realms/blabla.....
.....redirect_uri=https......
**'**scope=openid

The second quote goes to the beginning of the new line, not the end of variable. how to put it there?
but the interesting thing is that this request works fine in git-bash but not in linux console (bash version 4.4 and 5.0.17)


问:
innerHTML for new elements works only once
i'm trying to create a table of clients but every time i create a new client its being created with the values of the first client.

it seems that the elements are deleted and recreated agein and agein.

99% of the code scoped into arrow function exept for the customers array which is global.

HTML:

```<code>        <table class="customersTable">
          <thead>
            <tr class="headingRow">
              <th>
                <input
                  type="checkbox"
                  name="masterCheckBox"
                  class="masterCheckBox"
                />
              </th>
              <th>מספר סידורי</th>
              <th>מספר לקוח</th>
              <th>איש קשר</th>
              <th>בית העסק</th>
              <th>עיר</th>
              <th>רחוב ומספר</th>
              <th>קומה</th>
              <th>כניסה</th>
              <th>טלפון</th>
              <th>אימייל</th>
              <th>הערות</th>
            </tr>
          </thead>
          <tbody class="customersTbody"></tbody>
        </table>
</code>```

javascript:
create elements function

```<code>createRow = () => {
  const Row = document.createElement(`tr`);
  const checkBoxTD = document.createElement(`td`);
  const serialNumberTD = document.createElement(`td`);
  const uniqueIDTD = document.createElement(`td`);
  const contactNameTD = document.createElement(`td`)
  const businnesNameTD = document.createElement(`td`);
  const cityTD = document.createElement(`td`);
  const streetAndNumberTD = document.createElement(`td`);
  const floorTD = document.createElement(`td`);
  const entranceTD = document.createElement(`td`);
  const emailTD = document.createElement(`td`);
  const phoneTD = document.createElement(`td`);
  const textAreaTD = document.createElement(`td`);

  return {
    Row,
    checkBoxTD,
    serialNumberTD,
    uniqueIDTD,
    contactNameTD,
    businnesNameTD,
    cityTD,
    streetAndNumberTD,
    floorTD,
    entranceTD,
    emailTD,
    phoneTD,
    textAreaTD,
  };
};
</code>```

inject values function

```<code>injectRowValues = () => {
  const createdRowElements = createRow();
  const dataArray = convertAndLoad();
  const uniqueID = generateID();
  const customersTbody = document.querySelector(`.customersTbody`);

  let checkBoxTD = createdRowElements.checkBoxTD;
  let serialNumberTD = createdRowElements.serialNumberTD;
  let uniqueIDTD = createdRowElements.uniqueIDTD;
  let contactNameTD = createdRowElements.contactNameTD;
  let businnesNameTD = createdRowElements.businnesNameTD;
  let cityTD = createdRowElements.cityTD;
  let streetAndNumberTD = createdRowElements.streetAndNumberTD;
  let floorTD = createdRowElements.floorTD;
  let entranceTD = createdRowElements.entranceTD;
  let phoneTD = createdRowElements.phoneTD;
  let emailTD = createdRowElements.emailTD;
  let textAreaTD = createdRowElements.textAreaTD;

  for (let i = 0; i < customers.length ; i++) {
    console.log(customers);
    checkBoxTD.innerHTML = `<input type="checkbox" name="masterCheckBox" class="masterCheckBox" />`;
    serialNumberTD.innerHTML = customersTbody.childNodes.length;
    uniqueIDTD.innerHTML = uniqueID;
    contactNameTD.innerHTML = dataArray[customers.length - customers.length].contactInput;
    businnesNameTD.innerHTML = dataArray[i].businnesNameInput;
    cityTD.innerHTML = dataArray[i].cityInput;
    streetAndNumberTD.innerText = dataArray[i].streetAndNumberInput;
    floorTD.innerHTML = dataArray[i].floorInput;
    entranceTD.innerHTML = dataArray[i].entranceInput;
    emailTD.innerHTML = dataArray[i].emailInput.toLowerCase();
    phoneTD.innerText = `${dataArray[i].phoneInput1} \n ${dataArray[i].phoneInput2}`;
    textAreaTD.innerText = dataArray[i].addCustomerTextArea;
     console.log(customers);

    return {
      checkBoxTD,
      serialNumberTD,
      uniqueIDTD,
      contactNameTD,
      businnesNameTD,
      cityTD,
      streetAndNumberTD,
      floorTD,
      entranceTD,
      emailTD,
      phoneTD,
      textAreaTD,
    };
  }
};
</code>```

append function

```<code>appendRow = () => {
  const createdRowElement = createRow();
  const createdRowElements = injectRowValues();
  const customersTbody = document.querySelector(`.customersTbody`);

  customersTbody.append(createdRowElement.Row);
  createdRowElement.Row.append(
    createdRowElements.checkBoxTD,
    createdRowElements.serialNumberTD,
    createdRowElements.uniqueIDTD,
    createdRowElements.contactNameTD,
    createdRowElements.businnesNameTD,
    createdRowElements.cityTD,
    createdRowElements.streetAndNumberTD,
    createdRowElements.floorTD,
    createdRowElements.entranceTD,
    createdRowElements.phoneTD,
    createdRowElements.emailTD,
    createdRowElements.textAreaTD
  )
  closeModal();
};
</code>```

Body:
i'm trying to create a table of clients but every time i create a new client its being created with the values of the first client.

it seems that the elements are deleted and recreated agein and agein.

99% of the code scoped into arrow function exept for the customers array which is global.

HTML:

                <input
                  type="checkbox"
                  name="masterCheckBox"
                  class="masterCheckBox"
                />

              מספר סידורי
              מספר לקוח
              איש קשר
              בית העסק
              עיר
              רחוב ומספר
              קומה
              כניסה
              טלפון
              אימייל
              הערות

javascript:
create elements function

createRow = () => {
  const Row = document.createElement(`tr`);
  const checkBoxTD = document.createElement(`td`);
  const serialNumberTD = document.createElement(`td`);
  const uniqueIDTD = document.createElement(`td`);
  const contactNameTD = document.createElement(`td`)
  const businnesNameTD = document.createElement(`td`);
  const cityTD = document.createElement(`td`);
  const streetAndNumberTD = document.createElement(`td`);
  const floorTD = document.createElement(`td`);
  const entranceTD = document.createElement(`td`);
  const emailTD = document.createElement(`td`);
  const phoneTD = document.createElement(`td`);
  const textAreaTD = document.createElement(`td`);

  return {
    Row,
    checkBoxTD,
    serialNumberTD,
    uniqueIDTD,
    contactNameTD,
    businnesNameTD,
    cityTD,
    streetAndNumberTD,
    floorTD,
    entranceTD,
    emailTD,
    phoneTD,
    textAreaTD,
  };
};

inject values function

injectRowValues = () => {
  const createdRowElements = createRow();
  const dataArray = convertAndLoad();
  const uniqueID = generateID();
  const customersTbody = document.querySelector(`.customersTbody`);

  let checkBoxTD = createdRowElements.checkBoxTD;
  let serialNumberTD = createdRowElements.serialNumberTD;
  let uniqueIDTD = createdRowElements.uniqueIDTD;
  let contactNameTD = createdRowElements.contactNameTD;
  let businnesNameTD = createdRowElements.businnesNameTD;
  let cityTD = createdRowElements.cityTD;
  let streetAndNumberTD = createdRowElements.streetAndNumberTD;
  let floorTD = createdRowElements.floorTD;
  let entranceTD = createdRowElements.entranceTD;
  let phoneTD = createdRowElements.phoneTD;
  let emailTD = createdRowElements.emailTD;
  let textAreaTD = createdRowElements.textAreaTD;

  for (let i = 0; i < customers.length ; i++) {
    console.log(customers);
    checkBoxTD.innerHTML = `<input type="checkbox" name="masterCheckBox" class="masterCheckBox" />`;
    serialNumberTD.innerHTML = customersTbody.childNodes.length;
    uniqueIDTD.innerHTML = uniqueID;
    contactNameTD.innerHTML = dataArray[customers.length - customers.length].contactInput;
    businnesNameTD.innerHTML = dataArray[i].businnesNameInput;
    cityTD.innerHTML = dataArray[i].cityInput;
    streetAndNumberTD.innerText = dataArray[i].streetAndNumberInput;
    floorTD.innerHTML = dataArray[i].floorInput;
    entranceTD.innerHTML = dataArray[i].entranceInput;
    emailTD.innerHTML = dataArray[i].emailInput.toLowerCase();
    phoneTD.innerText = `${dataArray[i].phoneInput1} \n ${dataArray[i].phoneInput2}`;
    textAreaTD.innerText = dataArray[i].addCustomerTextArea;
     console.log(customers);

    return {
      checkBoxTD,
      serialNumberTD,
      uniqueIDTD,
      contactNameTD,
      businnesNameTD,
      cityTD,
      streetAndNumberTD,
      floorTD,
      entranceTD,
      emailTD,
      phoneTD,
      textAreaTD,
    };
  }
};

append function

appendRow = () => {
  const createdRowElement = createRow();
  const createdRowElements = injectRowValues();
  const customersTbody = document.querySelector(`.customersTbody`);

  customersTbody.append(createdRowElement.Row);
  createdRowElement.Row.append(
    createdRowElements.checkBoxTD,
    createdRowElements.serialNumberTD,
    createdRowElements.uniqueIDTD,
    createdRowElements.contactNameTD,
    createdRowElements.businnesNameTD,
    createdRowElements.cityTD,
    createdRowElements.streetAndNumberTD,
    createdRowElements.floorTD,
    createdRowElements.entranceTD,
    createdRowElements.phoneTD,
    createdRowElements.emailTD,
    createdRowElements.textAreaTD
  )
  closeModal();
};


问:
How to make PyCharm go to an open web browser (and if the browser is closed, open it)
every1,

I'm a Python newbie and I want:

1) to make Python open Chrome (or Firefox) if they are off and just focus on it if it is already open.

2) Then I would need to copy the url that's in the address bar.

Can anyone, please, help me with item #1 (and 2# if ever possible)?

Thanks in advance!

Lincoln

I have tried the lines of code below, but it maximizes the PyCharm window instead of the browser, which is right behind the Pycharm window.

I expected the code would go (focus) to the web browser, but it stays in the Pycharm window.

```<code>import pyautogui
window = pyautogui.getActiveWindow()
window. Maximize()
</code>```

Body:
every1,

I'm a Python newbie and I want:

1) to make Python open Chrome (or Firefox) if they are off and just focus on it if it is already open.

2) Then I would need to copy the url that's in the address bar.

Can anyone, please, help me with item #1 (and 2# if ever possible)?

Thanks in advance!

Lincoln

I have tried the lines of code below, but it maximizes the PyCharm window instead of the browser, which is right behind the Pycharm window.

I expected the code would go (focus) to the web browser, but it stays in the Pycharm window.

import pyautogui
window = pyautogui.getActiveWindow()
window. Maximize()


问:
Passing global props through _app.tsx in Nextjs
in _app.tsx I have the following code:

```<code>export default function App({ Component, pageProps }: AppProps) {
  const [notification, setNotification] = useState<Notification | null>(null);

  return (
    <>
      {notification && (
        <Notification type={notification.type} message={notification.message} />
      )}
      <Component {...pageProps} setNotification={setNotification} />
    </>
  );
}

</code>```

By passing setNotification as a prop, any page in my NextApp can programmatically render a notification to the page.

Is this considered bad practice? At first I was going to do this using React Context, but found that this was simpler.

Furthermore, what if more such global data is needed? Would it be okay to pass it through this way?

Body:
in _app.tsx I have the following code:

export default function App({ Component, pageProps }: AppProps) {
  const [notification, setNotification] = useState<Notification | null>(null);

  return (
    <>
      {notification && (
        <Notification type={notification.type} message={notification.message} />
      )}
      <Component {...pageProps} setNotification={setNotification} />
    </>
  );
}

By passing setNotification as a prop, any page in my NextApp can programmatically render a notification to the page.

Is this considered bad practice? At first I was going to do this using React Context, but found that this was simpler.

Furthermore, what if more such global data is needed? Would it be okay to pass it through this way?


问:
How to relativize compiler and linker argument paths in binaries produced by swift-fronted / clang
In order to achieve deterministic builds, and to enable debugger on the developer's machine to load modules which were downloaded from module cache produced by CI, one of the techniques outlined in this article is to use -oso_prefix linker flag, which makes all paths used in the arguments to the linker, to be stored in the produced binary as relativized against the oso prefix path.

The problem, however, is that

passing the -Wl,-oso_prefix,/path/to/my/project/root/ into OTHER_LDFLAGS build setting does not affect static libraries (*.a) and *.swiftmodule / *.swiftinterface / *.swiftdoc swift / clang compiler artifacts - they still contain absolute paths that include /path/to/my/project/root/.

-Wl,-oso_prefix,/path/to/my/project/root/ is only passed by Xcode from OTHER_LDFLAGS in arguments to the linker when a dynamic binary gets linked (either app binary or dynamic framework), however, that's not the intended outcome.

Adding this flag to OTHER_CFLAGS and/or OTHER_SWIFT_FLAGS causes clang/swiftc to trow an error.

How one can pass oso_prefix to the compiler to retrieve all artifacts with paths being encoded as relative?

UPD: I submitted the issue to apple/swift.git.


问:
django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.AppName' after upgrade to django 4
I have upgraded a django app which worked ok for years on django 3 to 4.1.4 and now it fails an error.
I anonymized the names.

In settings I have:
INSTALLED_APPS = [
'foldername'

I've figured out that I needed to add Meta.app_label, can someone confirm?

So in foldername/apps.py I have now this:
class MyApp(AppConfig):
name = 'apps.MyApp'
class Meta:
app_label = 'apps.MyApp'

I'm not sure if the name needs to be apps.MyApp or just MyApp. I also have seen others posted to have foldername.apps.MyApp and have put the full name into INSTALLED_APP= (not just project/folder name). I wonder what's right.

Well, when I run: python manage.py, I get the stack trace:

....bla bla... strack trace ends with...
django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.MyApp'. Check that 'foldername.apps.MyApp.name' is correct.

Can anyone spot the problem?

I have spent so much time and don't know what to try. I've tried so much and rolled back again. Any feedback will make me happy at this point! :-)

David

Tried various combinations of: foldername.apps.MyApp (short, medium, long version) in name= in app_label, in moduleName and in INSTALLED_APPS.

Tried adding in models.ypy:

class BaseModel(models.Model):
class Meta:
abstract = True  # specify this model as an Abstract Model
app_label = 'apps.MyApp'

... and then let all models extend from it. I read about this in a forum as solution.


问:
insertion in the description of external affiliate product url in the single_product.php page of woocommerce
```<code>add_filter( 'the_content', 'shorten_product_long_descrition', 20 );
function shorten_product_long_descrition( $content ){
 global $product;
// Get product id
 $product_id = $product->get_id();

 // Get url
 $url = $product->add_to_cart_url();
 // Only for single product pages
 if( ! is_product() ) return $content;

 // Set the limit of words
 $limit = 13;

 if (str_word_count($content, 0) > $limit) {
     $arr = str_word_count($content, 2);
     $pos = array_keys($arr);
     $text = '<p>' . substr($content, 0, $pos[$limit]) . "..<a href='" . $url . "' class='goto_more_offer_tab button'>...continua la lettura</a></p>";
     $content = force_balance_tags($text); // needded
 }
 return $content;
}
</code>```

The code works, in the single product page it displays the url ($url), but when I open the home page of the website I no longer see the content.
What am I doing wrong?
thank you

Body:
add_filter( 'the_content', 'shorten_product_long_descrition', 20 );
function shorten_product_long_descrition( $content ){
 global $product;
// Get product id
 $product_id = $product->get_id();

 // Get url
 $url = $product->add_to_cart_url();
 // Only for single product pages
 if( ! is_product() ) return $content;

 // Set the limit of words
 $limit = 13;

 if (str_word_count($content, 0) > $limit) {
     $arr = str_word_count($content, 2);
     $pos = array_keys($arr);
     $text = '
' . substr($content, 0, $pos[$limit]) . ".....continua la lettura
";
     $content = force_balance_tags($text); // needded
 }
 return $content;
}

The code works, in the single product page it displays the url ($url), but when I open the home page of the website I no longer see the content.
What am I doing wrong?
thank you


问:
Material design breakpoints
breakpoints table

In material design 3, there are 3 breakpoints, measured in dp.

If I want to use them in CSS, how should I do? Do I need JS to detect the screen density and use the formula

```<code>px = dp * (dpi / 160)
</code>```

or does 500 dp simply equal to 500px?

Also, in the table I don't understand the utility of the Portrait and Landscape columns.

Title: Material design breakpoints

Body:
breakpoints table

In material design 3, there are 3 breakpoints, measured in dp.

If I want to use them in CSS, how should I do? Do I need JS to detect the screen density and use the formula

px = dp * (dpi / 160)

or does 500 dp simply equal to 500px?

Also, in the table I don't understand the utility of the Portrait and Landscape columns.