content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
sequence | answers_scores
sequence | non_answers
sequence | non_answers_scores
sequence | tags
sequence | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
java: Visual Studio Code doesn't read file
this program should print the contents of a text file called "a.txt" but with Visual Studio Code it doesn't work, reporting the error below.
I compiled with Jcreator and Geany and compile. Could anyone tell me why it doesn't work on Visual Studio Code?
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main (String args[]) {
//String pathFileName = "inputFile.txt";
//File inputFile = new File(pathFileName);
File inputFile = new File("a.txt");
Scanner scannerDaFile = null;
try {
scannerDaFile = new Scanner (inputFile);
System.out.println("---------------- OUTPUT TEXT: "+inputFile.getName()+" --------------------");
while(scannerDaFile.hasNextLine()) {
System.out.println(scannerDaFile.nextLine());
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if(scannerDaFile!=null) {
scannerDaFile.close();
}
}
}
}
A:
I had the same issue recently and turns out when you run your java from vs code your build is stored somewhere else.
In order to place the txt files where my program can find it I followed the following steps:
Print the execution dir somewhere in your code
System.out.println(System.getProperty("user.dir"));
Open add the txt files or folders into that directory.
A better way to prevent this problem to happen is to use the full path of the files.
| java: Visual Studio Code doesn't read file | this program should print the contents of a text file called "a.txt" but with Visual Studio Code it doesn't work, reporting the error below.
I compiled with Jcreator and Geany and compile. Could anyone tell me why it doesn't work on Visual Studio Code?
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main (String args[]) {
//String pathFileName = "inputFile.txt";
//File inputFile = new File(pathFileName);
File inputFile = new File("a.txt");
Scanner scannerDaFile = null;
try {
scannerDaFile = new Scanner (inputFile);
System.out.println("---------------- OUTPUT TEXT: "+inputFile.getName()+" --------------------");
while(scannerDaFile.hasNextLine()) {
System.out.println(scannerDaFile.nextLine());
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if(scannerDaFile!=null) {
scannerDaFile.close();
}
}
}
}
| [
"I had the same issue recently and turns out when you run your java from vs code your build is stored somewhere else.\nIn order to place the txt files where my program can find it I followed the following steps:\n\nPrint the execution dir somewhere in your code\nSystem.out.println(System.getProperty(\"user.dir\"));\n\nOpen add the txt files or folders into that directory.\n\n\nA better way to prevent this problem to happen is to use the full path of the files.\n"
] | [
0
] | [] | [] | [
"java"
] | stackoverflow_0066136845_java.txt |
Q:
Problem with concurrent program (threads, locks, monitors) The execution doesn't make sense
I have a problem with concurrent program (threads, locks, monitors).
The execution doesn't make sense.
The answers that appears go random in another order that it should and I don't find the error.
All compile and I don't have any sintax error so...
Please help me with this problem.
public class PersonaMonitores extends Thread{
static int id;
static CuentaMonitor cuenta;
public PersonaMonitores(int id, CuentaMonitor cuenta) {
this.id = id;
this.cuenta = cuenta;
}
public void run() {
cuenta.controlIN();
System.out.println("Persona [" + PersonaMonitores.id +"]: Saco dinero");
CuentaMonitor.dinero = CuentaMonitor.dinero - 100;
System.out.println("Quedan: " + CuentaMonitor.dinero + "€ porque Persona [" + PersonaMonitores.id +"] ha sacado dinero");
cuenta.controlOUT();
}
public static void main(String [] args) {
CuentaMonitor cuenta = new CuentaMonitor(1000);
for(int i = 0; i<10; i++) {
new PersonaMonitores(i,cuenta).start();
}
}
}
public class CuentaMonitor{
static int numPersonasSacandoDinero;
static int dinero;
public CuentaMonitor (int dinero) {
this.dinero = dinero;
this.numPersonasSacandoDinero = 0;
}
public synchronized void controlIN() {
while(dinero < 100 || numPersonasSacandoDinero > 0) {
try {
System.out.println("Persona [" + PersonaMonitores.id +"]: Estoy esperando");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
numPersonasSacandoDinero++;
System.out.println("Persona [" + PersonaMonitores.id +"]: Saco dinero");
}
public synchronized void controlOUT() {
System.out.println("Persona [" + PersonaMonitores.id +"]: Aviso para que entre alguien");
this.notifyAll();
numPersonasSacandoDinero--;
}
}
I have a problem with concurrent program (threads, locks, monitors).
The execution doesn't make sense.
The answers that appears go random in another order that it should and I don't find the error.
All compile and I don't have any sintax error so...
Please help me with this problem.
A:
My result of the execution (wrong one) is this:
Persona [3]: Saco dinero
Persona [6]: Saco dinero
Persona [6]: Estoy esperando
Persona [7]: Estoy esperando
Quedan: 900€ porque Persona [7] ha sacado dinero
Persona [8]: Estoy esperando
Persona [9]: Aviso para que entre alguien
Persona [9]: Saco dinero
Persona [9]: Saco dinero
Persona [9]: Estoy esperando
Quedan: 800€ porque Persona [9] ha sacado dinero
Persona [9]: Estoy esperando
Persona [9]: Aviso para que entre alguien
Persona [9]: Saco dinero
Persona [9]: Saco dinero
Persona [9]: Estoy esperando
Quedan: 700€ porque Persona [9] ha sacado dinero
Persona [9]: Estoy esperando
Persona [9]: Estoy esperando
Persona [9]: Estoy esperando
Persona [9]: Estoy esperando
Persona [9]: Aviso para que entre alguien
Persona [9]: Saco dinero
Persona [9]: Saco dinero
Quedan: 600€ porque Persona [9] ha sacado dinero
Persona [9]: Estoy esperando
Persona [9]: Aviso para que entre alguien
Persona [9]: Saco dinero
Persona [9]: Saco dinero
Persona [9]: Estoy esperando
Quedan: 500€ porque Persona [9] ha sacado dinero
Persona [9]: Estoy esperando
Persona [9]: Estoy esperando
Persona [9]: Estoy esperando
Persona [9]: Aviso para que entre alguien
Persona [9]: Saco dinero
Persona [9]: Saco dinero
Persona [9]: Estoy esperando
Quedan: 400€ porque Persona [9] ha sacado dinero
Persona [9]: Estoy esperando
Persona [9]: Estoy esperando
Persona [9]: Estoy esperando
Persona [9]: Aviso para que entre alguien
Persona [9]: Saco dinero
Persona [9]: Saco dinero
Persona [9]: Estoy esperando
Quedan: 300€ porque Persona [9] ha sacado dinero
Persona [9]: Estoy esperando
Persona [9]: Estoy esperando
Persona [9]: Aviso para que entre alguien
Persona [9]: Saco dinero
Persona [9]: Saco dinero
Persona [9]: Estoy esperando
Quedan: 200€ porque Persona [9] ha sacado dinero
Persona [9]: Estoy esperando
Persona [9]: Aviso para que entre alguien
Persona [9]: Saco dinero
Persona [9]: Saco dinero
Persona [9]: Estoy esperando
Quedan: 100€ porque Persona [9] ha sacado dinero
Persona [9]: Aviso para que entre alguien
Persona [9]: Saco dinero
Persona [9]: Saco dinero
Quedan: 0€ porque Persona [9] ha sacado dinero
Persona [9]: Aviso para que entre alguien
And ONE of the good results is:
Persona [0]: Saco dinero
Quedan: 900€ porque Persona [0] ha sacado dinero
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [7]: Saco dinero
Persona [0]: Estoy esperando
Quedan: 800€ porque Persona [7] ha sacado dinero
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [8]: Saco dinero
Persona [0]: Estoy esperando
Quedan: 700€ porque Persona [8] ha sacado dinero
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [9]: Saco dinero
Persona [0]: Estoy esperando
Quedan: 600€ porque Persona [9] ha sacado dinero
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [6]: Saco dinero
Persona [0]: Estoy esperando
Quedan: 500€ porque Persona [6] ha sacado dinero
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [1]: Saco dinero
Persona [0]: Estoy esperando
Quedan: 400€ porque Persona [1] ha sacado dinero
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [5]: Saco dinero
Persona [0]: Estoy esperando
Quedan: 300€ porque Persona [5] ha sacado dinero
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [2]: Saco dinero
Quedan: 200€ porque Persona [2] ha sacado dinero
Persona [0]: Estoy esperando
Persona [0]: Estoy esperando
Persona [4]: Saco dinero
Persona [0]: Estoy esperando
Quedan: 100€ porque Persona [4] ha sacado dinero
Persona [3]: Saco dinero
Quedan: 0€ porque Persona [3] ha sacado dinero
It's like how could the bank account had less money if someone still doesn't have picked up the money of it?
| Problem with concurrent program (threads, locks, monitors) The execution doesn't make sense | I have a problem with concurrent program (threads, locks, monitors).
The execution doesn't make sense.
The answers that appears go random in another order that it should and I don't find the error.
All compile and I don't have any sintax error so...
Please help me with this problem.
public class PersonaMonitores extends Thread{
static int id;
static CuentaMonitor cuenta;
public PersonaMonitores(int id, CuentaMonitor cuenta) {
this.id = id;
this.cuenta = cuenta;
}
public void run() {
cuenta.controlIN();
System.out.println("Persona [" + PersonaMonitores.id +"]: Saco dinero");
CuentaMonitor.dinero = CuentaMonitor.dinero - 100;
System.out.println("Quedan: " + CuentaMonitor.dinero + "€ porque Persona [" + PersonaMonitores.id +"] ha sacado dinero");
cuenta.controlOUT();
}
public static void main(String [] args) {
CuentaMonitor cuenta = new CuentaMonitor(1000);
for(int i = 0; i<10; i++) {
new PersonaMonitores(i,cuenta).start();
}
}
}
public class CuentaMonitor{
static int numPersonasSacandoDinero;
static int dinero;
public CuentaMonitor (int dinero) {
this.dinero = dinero;
this.numPersonasSacandoDinero = 0;
}
public synchronized void controlIN() {
while(dinero < 100 || numPersonasSacandoDinero > 0) {
try {
System.out.println("Persona [" + PersonaMonitores.id +"]: Estoy esperando");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
numPersonasSacandoDinero++;
System.out.println("Persona [" + PersonaMonitores.id +"]: Saco dinero");
}
public synchronized void controlOUT() {
System.out.println("Persona [" + PersonaMonitores.id +"]: Aviso para que entre alguien");
this.notifyAll();
numPersonasSacandoDinero--;
}
}
I have a problem with concurrent program (threads, locks, monitors).
The execution doesn't make sense.
The answers that appears go random in another order that it should and I don't find the error.
All compile and I don't have any sintax error so...
Please help me with this problem.
| [
"My result of the execution (wrong one) is this:\nPersona [3]: Saco dinero\nPersona [6]: Saco dinero\nPersona [6]: Estoy esperando\nPersona [7]: Estoy esperando\nQuedan: 900€ porque Persona [7] ha sacado dinero\nPersona [8]: Estoy esperando\nPersona [9]: Aviso para que entre alguien\nPersona [9]: Saco dinero\nPersona [9]: Saco dinero\nPersona [9]: Estoy esperando\nQuedan: 800€ porque Persona [9] ha sacado dinero\nPersona [9]: Estoy esperando\nPersona [9]: Aviso para que entre alguien\nPersona [9]: Saco dinero\nPersona [9]: Saco dinero\nPersona [9]: Estoy esperando\nQuedan: 700€ porque Persona [9] ha sacado dinero\nPersona [9]: Estoy esperando\nPersona [9]: Estoy esperando\nPersona [9]: Estoy esperando\nPersona [9]: Estoy esperando\nPersona [9]: Aviso para que entre alguien\nPersona [9]: Saco dinero\nPersona [9]: Saco dinero\nQuedan: 600€ porque Persona [9] ha sacado dinero\nPersona [9]: Estoy esperando\nPersona [9]: Aviso para que entre alguien\nPersona [9]: Saco dinero\nPersona [9]: Saco dinero\nPersona [9]: Estoy esperando\nQuedan: 500€ porque Persona [9] ha sacado dinero\nPersona [9]: Estoy esperando\nPersona [9]: Estoy esperando\nPersona [9]: Estoy esperando\nPersona [9]: Aviso para que entre alguien\nPersona [9]: Saco dinero\nPersona [9]: Saco dinero\nPersona [9]: Estoy esperando\nQuedan: 400€ porque Persona [9] ha sacado dinero\nPersona [9]: Estoy esperando\nPersona [9]: Estoy esperando\nPersona [9]: Estoy esperando\nPersona [9]: Aviso para que entre alguien\nPersona [9]: Saco dinero\nPersona [9]: Saco dinero\nPersona [9]: Estoy esperando\nQuedan: 300€ porque Persona [9] ha sacado dinero\nPersona [9]: Estoy esperando\nPersona [9]: Estoy esperando\nPersona [9]: Aviso para que entre alguien\nPersona [9]: Saco dinero\nPersona [9]: Saco dinero\nPersona [9]: Estoy esperando\nQuedan: 200€ porque Persona [9] ha sacado dinero\nPersona [9]: Estoy esperando\nPersona [9]: Aviso para que entre alguien\nPersona [9]: Saco dinero\nPersona [9]: Saco dinero\nPersona [9]: Estoy esperando\nQuedan: 100€ porque Persona [9] ha sacado dinero\nPersona [9]: Aviso para que entre alguien\nPersona [9]: Saco dinero\nPersona [9]: Saco dinero\nQuedan: 0€ porque Persona [9] ha sacado dinero\nPersona [9]: Aviso para que entre alguien\n\nAnd ONE of the good results is:\nPersona [0]: Saco dinero\nQuedan: 900€ porque Persona [0] ha sacado dinero\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [7]: Saco dinero\nPersona [0]: Estoy esperando\nQuedan: 800€ porque Persona [7] ha sacado dinero\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [8]: Saco dinero\nPersona [0]: Estoy esperando\nQuedan: 700€ porque Persona [8] ha sacado dinero\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [9]: Saco dinero\nPersona [0]: Estoy esperando\nQuedan: 600€ porque Persona [9] ha sacado dinero\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [6]: Saco dinero\nPersona [0]: Estoy esperando\nQuedan: 500€ porque Persona [6] ha sacado dinero\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [1]: Saco dinero\nPersona [0]: Estoy esperando\nQuedan: 400€ porque Persona [1] ha sacado dinero\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [5]: Saco dinero\nPersona [0]: Estoy esperando\nQuedan: 300€ porque Persona [5] ha sacado dinero\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [2]: Saco dinero\nQuedan: 200€ porque Persona [2] ha sacado dinero\nPersona [0]: Estoy esperando\nPersona [0]: Estoy esperando\nPersona [4]: Saco dinero\nPersona [0]: Estoy esperando\nQuedan: 100€ porque Persona [4] ha sacado dinero\nPersona [3]: Saco dinero\nQuedan: 0€ porque Persona [3] ha sacado dinero\n\nIt's like how could the bank account had less money if someone still doesn't have picked up the money of it?\n"
] | [
0
] | [] | [] | [
"execution",
"java",
"java_threads",
"locks",
"monitor"
] | stackoverflow_0074671745_execution_java_java_threads_locks_monitor.txt |
Q:
split the file based on header and footer lines
I have a text file structured like this:
[timestamp1] header with space
[timestamp2] data1
[timestamp3] data2
[timestamp4] data3
[timestamp5] ..
[timestamp6] footer with space
[timestamp7] junk
[timestamp8] header with space
[timestamp9] data4
[timestamp10] data5
[timestamp11] ...
[timestamp12] footer with space
[timestamp13] junk
[timestamp14] header with space
[timestamp15] data6
[timestamp16] data7
[timestamp17] data8
[timestamp18] ..
[timestamp19] footer with space
I need to find each part between header and footer and save it in another file. For example the file1 should contain (with or without timestamps; doesn't matter):
data1
data2
data3
..
and the next pack should be saved as file2 and so on.
This seems like a routine process, but I haven't find a solution yet.
I have this sed command that finds the first packet.
sed -n "/header/,/footer/{p;/footer/q}" file
But I don't know how to iterate that over the next matches. Maybe I should delete the first match after copying it to another file and repeat the same command
A:
I would harness GNU AWK for this task following way, let file.txt content be
[timestamp1] header with space
[timestamp2] data1
[timestamp3] data2
[timestamp4] data3
[timestamp5] ..
[timestamp6] footer with space
[timestamp7] junk
[timestamp8] header with space
[timestamp9] data4
[timestamp10] data5
[timestamp11] ...
[timestamp12] footer with space
[timestamp13] junk
[timestamp14] header with space
[timestamp15] data6
[timestamp16] data7
[timestamp17] data8
[timestamp18] ..
[timestamp19] footer with space
then
awk '/header/{c+=1;p=1;next}/footer/{close("file" c);p=0}p{print $0 > ("file" c)}' file.txt
produces file1 with content
[timestamp1] header with space
[timestamp2] data1
[timestamp3] data2
[timestamp4] data3
[timestamp5] ..
and file2 with content
[timestamp8] header with space
[timestamp9] data4
[timestamp10] data5
[timestamp11] ...
and file3 with content
[timestamp15] data6
[timestamp16] data7
[timestamp17] data8
[timestamp18] ..
Explanation: my code has 3 pattern-action pairs, for line containing header I increase counter c by 1 and set flag p to 1 and go to next line so no other action is undertaken, for line cotaining footer I close file named file followed by current counter number and set flag p to 0. For lines where p is set to true I print current line ($0) to file named file followed by current counter number. If required adjust /header/ and /footer/ to contant solely on lines which are header and footer lines.
(tested in GNU Awk 5.0.1)
A:
Using any awk:
$ awk '/footer/{f=0} f{print > out} /header/{close(out); out="file" (++c); f=1}' file
$ head file?*
==> file1 <==
[timestamp2] data1
[timestamp3] data2
[timestamp4] data3
[timestamp5] ..
==> file2 <==
[timestamp9] data4
[timestamp10] data5
[timestamp11] ...
==> file3 <==
[timestamp15] data6
[timestamp16] data7
[timestamp17] data8
[timestamp18] ..
A:
A very naive approach, coded fast, could be improved, but seems to work, in awk:
BEGIN {
i = 0
}
{
if ($0 == "header") {
write = 1
} else if ($0 == "footer") {
write = 0
i = i + 1
} else {
if (write == 1) {
print $0 > "file"i
}
}
}
A:
This might work for you (GNU csplit and sed):
csplit -qf file -b '%d' --supp file '/header/' '{*}' && sed -i '/footer/,$d' file? && rm file0
Use csplit to split file into multiple filen files on header suppressing the matching line.
Use sed to delete footer and any following lines`.
Remove the unwanted file0 file.
Alternative:
sed -En '/header/{x;s/.*/echo $((0&+1))/e;x};/header/,/footer/!b;//b;G;s/(.*)\n/echo "\1" >>file/e' file
A:
Based on THIS REGEX, here is a ruby:
ruby -e 'cnt=1
$<.read.scan(/^.*\bheader\b.*\s+([\s\S]*?)(?=^.*\bfooter\b)/){
|b| File.write("File_#{cnt}.txt", b[0])
cnt+=1
}' file
Produces:
$ head File_*
==> File_1.txt <==
[timestamp2] data1
[timestamp3] data2
[timestamp4] data3
[timestamp5] ..
==> File_2.txt <==
[timestamp9] data4
[timestamp10] data5
[timestamp11] ...
==> File_3.txt <==
[timestamp15] data6
[timestamp16] data7
[timestamp17] data8
[timestamp18] ..
If you want to remove the timestamps:
ruby -e 'cnt=1
$<.read.scan(/^.*\bheader\b.*\s+([\s\S]*?)(?=^.*\bfooter\b)/){ |b|
File.write("File_#{cnt}.txt", b[0].gsub(/^\[[^\]]+\]\s+/,""))
cnt+=1
}' file
$ head File_*
==> File_1.txt <==
data1
data2
data3
..
==> File_2.txt <==
data4
data5
...
==> File_3.txt <==
data6
data7
data8
..
Note: If you want to include the header and/or footer, just move the capture group to include what you want.
| split the file based on header and footer lines | I have a text file structured like this:
[timestamp1] header with space
[timestamp2] data1
[timestamp3] data2
[timestamp4] data3
[timestamp5] ..
[timestamp6] footer with space
[timestamp7] junk
[timestamp8] header with space
[timestamp9] data4
[timestamp10] data5
[timestamp11] ...
[timestamp12] footer with space
[timestamp13] junk
[timestamp14] header with space
[timestamp15] data6
[timestamp16] data7
[timestamp17] data8
[timestamp18] ..
[timestamp19] footer with space
I need to find each part between header and footer and save it in another file. For example the file1 should contain (with or without timestamps; doesn't matter):
data1
data2
data3
..
and the next pack should be saved as file2 and so on.
This seems like a routine process, but I haven't find a solution yet.
I have this sed command that finds the first packet.
sed -n "/header/,/footer/{p;/footer/q}" file
But I don't know how to iterate that over the next matches. Maybe I should delete the first match after copying it to another file and repeat the same command
| [
"I would harness GNU AWK for this task following way, let file.txt content be\n[timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n[timestamp6] footer with space\n[timestamp7] junk\n[timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n[timestamp12] footer with space\n[timestamp13] junk\n[timestamp14] header with space\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n[timestamp19] footer with space\n\nthen\nawk '/header/{c+=1;p=1;next}/footer/{close(\"file\" c);p=0}p{print $0 > (\"file\" c)}' file.txt\n\nproduces file1 with content\n[timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\nand file2 with content\n[timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\nand file3 with content\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n\nExplanation: my code has 3 pattern-action pairs, for line containing header I increase counter c by 1 and set flag p to 1 and go to next line so no other action is undertaken, for line cotaining footer I close file named file followed by current counter number and set flag p to 0. For lines where p is set to true I print current line ($0) to file named file followed by current counter number. If required adjust /header/ and /footer/ to contant solely on lines which are header and footer lines.\n(tested in GNU Awk 5.0.1)\n",
"Using any awk:\n$ awk '/footer/{f=0} f{print > out} /header/{close(out); out=\"file\" (++c); f=1}' file\n\n\n$ head file?*\n==> file1 <==\n[timestamp2] data1\n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> file2 <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> file3 <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n\n",
"A very naive approach, coded fast, could be improved, but seems to work, in awk:\nBEGIN {\n i = 0\n}\n{\n if ($0 == \"header\") {\n write = 1\n } else if ($0 == \"footer\") {\n write = 0\n i = i + 1\n } else {\n if (write == 1) {\n print $0 > \"file\"i\n }\n }\n}\n\n",
"This might work for you (GNU csplit and sed):\ncsplit -qf file -b '%d' --supp file '/header/' '{*}' && sed -i '/footer/,$d' file? && rm file0\n\nUse csplit to split file into multiple filen files on header suppressing the matching line.\nUse sed to delete footer and any following lines`.\nRemove the unwanted file0 file.\n\nAlternative:\nsed -En '/header/{x;s/.*/echo $((0&+1))/e;x};/header/,/footer/!b;//b;G;s/(.*)\\n/echo \"\\1\" >>file/e' file\n\n",
"Based on THIS REGEX, here is a ruby:\nruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){\n |b| File.write(\"File_#{cnt}.txt\", b[0])\n cnt+=1\n}' file \n\nProduces:\n$ head File_*\n==> File_1.txt <==\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> File_2.txt <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> File_3.txt <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n\nIf you want to remove the timestamps:\nruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){ |b| \n File.write(\"File_#{cnt}.txt\", b[0].gsub(/^\\[[^\\]]+\\]\\s+/,\"\"))\n cnt+=1\n}' file \n\n$ head File_*\n==> File_1.txt <==\ndata1 \ndata2\ndata3\n..\n\n==> File_2.txt <==\ndata4\ndata5\n...\n\n==> File_3.txt <==\ndata6\ndata7\ndata8\n..\n\nNote: If you want to include the header and/or footer, just move the capture group to include what you want.\n"
] | [
4,
3,
2,
1,
1
] | [] | [] | [
"awk",
"linux",
"sed",
"split",
"text_processing"
] | stackoverflow_0074664972_awk_linux_sed_split_text_processing.txt |
Q:
fatal error: all goroutines are asleep - deadlock! error GO
I'm new to concurrency in Go so I tried an example with channels and goroutines. I want to have the producer-consumer pattern. The producer function forever gives random strings and the consumer modifies them by making them uppercase. I want to run it for a limited time(2 sec).
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func producer(x []string, c chan string) {
i := 1
for i > 0 {
randomIndex := rand.Intn(len(x))
pick := x[randomIndex]
c <- pick
}
}
func consumer(x string, c chan string) {
x1 := strings.ToUpper(x)
c <- x1
}
func main() {
s := []string{"one", "two", "three", "four"}
c1 := make(chan string)
d1 := make(chan string)
go producer(s, c1)
go consumer(<-c1, d1)
stop := time.After(2000 * time.Millisecond)
for {
select {
case <-stop:
fmt.Println("STOP AFTER 2 SEC!")
return
default:
fmt.Println(<-d1)
time.Sleep(50 * time.Millisecond)
}
}
}
I'm getting only one array element and some errors. What changes need to be made so this example would work?
OUTPUT:
TWO
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
goroutine 6 [chan send]:
main.producer({0xc00004e040, 0x4, 0x0?}, 0x0?)
created by main. main
exit status 2
A:
Your consumer should run in a loop, this has been mentioned already.
Change the first parameter of the consumer so that it is a chan string instead of a string. That way the producer can continuously write to this channel for the consumer to publish on another channel until the time limit expires.
func consumer(consumeChan chan string, outCh chan string) {
for {
select {
case s := <- consumeChan:
s = strings.ToUpper(s)
outCh <- s
}
}
}
Right now in the main func before go consumer() is called you are waiting for the first response to the c1 channel from the producer. Instead of doing that pass in the c1 channel as the first parameter.
func main() {
s := []string{"one", "two", "three", "four"}
c1 := make(chan string)
d1 := make(chan string)
go producer(s, c1)
go consumer(c1, d1)
stop := time.After(2000 * time.Millisecond)
for {
select {
case <-stop:
fmt.Println("STOP AFTER 2 SEC!")
return
case response := <- d1:
fmt.Println(response)
time.Sleep(50 * time.Millisecond)
}
}
}
This should show you continuous writes of random numbers by the producer on the c1 channel, and continuous writes on the d1 channel by the consumer with the text in all uppercase until the 2 seconds is up.
| fatal error: all goroutines are asleep - deadlock! error GO | I'm new to concurrency in Go so I tried an example with channels and goroutines. I want to have the producer-consumer pattern. The producer function forever gives random strings and the consumer modifies them by making them uppercase. I want to run it for a limited time(2 sec).
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func producer(x []string, c chan string) {
i := 1
for i > 0 {
randomIndex := rand.Intn(len(x))
pick := x[randomIndex]
c <- pick
}
}
func consumer(x string, c chan string) {
x1 := strings.ToUpper(x)
c <- x1
}
func main() {
s := []string{"one", "two", "three", "four"}
c1 := make(chan string)
d1 := make(chan string)
go producer(s, c1)
go consumer(<-c1, d1)
stop := time.After(2000 * time.Millisecond)
for {
select {
case <-stop:
fmt.Println("STOP AFTER 2 SEC!")
return
default:
fmt.Println(<-d1)
time.Sleep(50 * time.Millisecond)
}
}
}
I'm getting only one array element and some errors. What changes need to be made so this example would work?
OUTPUT:
TWO
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
goroutine 6 [chan send]:
main.producer({0xc00004e040, 0x4, 0x0?}, 0x0?)
created by main. main
exit status 2
| [
"Your consumer should run in a loop, this has been mentioned already.\nChange the first parameter of the consumer so that it is a chan string instead of a string. That way the producer can continuously write to this channel for the consumer to publish on another channel until the time limit expires.\nfunc consumer(consumeChan chan string, outCh chan string) {\n for {\n select {\n case s := <- consumeChan:\n s = strings.ToUpper(s)\n outCh <- s\n }\n }\n}\n\nRight now in the main func before go consumer() is called you are waiting for the first response to the c1 channel from the producer. Instead of doing that pass in the c1 channel as the first parameter.\nfunc main() {\n s := []string{\"one\", \"two\", \"three\", \"four\"}\n c1 := make(chan string)\n d1 := make(chan string)\n go producer(s, c1)\n go consumer(c1, d1)\n\n stop := time.After(2000 * time.Millisecond)\n for {\n select {\n case <-stop:\n fmt.Println(\"STOP AFTER 2 SEC!\")\n return\n case response := <- d1:\n fmt.Println(response)\n time.Sleep(50 * time.Millisecond)\n }\n }\n}\n\nThis should show you continuous writes of random numbers by the producer on the c1 channel, and continuous writes on the d1 channel by the consumer with the text in all uppercase until the 2 seconds is up.\n"
] | [
1
] | [] | [] | [
"concurrency",
"go"
] | stackoverflow_0074592837_concurrency_go.txt |
Q:
The type or namespace name 'App' could not be found after installing Visual Studio Xaramin and building default app
I installed the latest version of Visual Studio with Xamarin, created a default app, and am getting a compilation error. Why is this not working out of the box? Here is the error:
Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'App' could not be found (are you missing a using directive or an assembly reference?) TestApp.Android C:\Users\matth\source\repos\TestApp\TestApp\TestApp.Android\MainActivity.cs 19 Active
A:
Like Jason said, restoring NuGet packages is a good idea, but I found a solution before trying that. I had to uninstall VS and delete all associated files, then install a different version. Not sure what was causing the issue.
| The type or namespace name 'App' could not be found after installing Visual Studio Xaramin and building default app | I installed the latest version of Visual Studio with Xamarin, created a default app, and am getting a compilation error. Why is this not working out of the box? Here is the error:
Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'App' could not be found (are you missing a using directive or an assembly reference?) TestApp.Android C:\Users\matth\source\repos\TestApp\TestApp\TestApp.Android\MainActivity.cs 19 Active
| [
"Like Jason said, restoring NuGet packages is a good idea, but I found a solution before trying that. I had to uninstall VS and delete all associated files, then install a different version. Not sure what was causing the issue.\n"
] | [
0
] | [] | [] | [
"compiler_errors",
"visual_studio",
"xamarin"
] | stackoverflow_0074671951_compiler_errors_visual_studio_xamarin.txt |
Q:
Question on exponential function and random variable
I am trying to understand the following code. Could someone explain what each step essentially means? (especially the 1st, 2nd and 4th line of code)
X = stats.expon(scale=10)
xs = X.rvs(100000)
plt.figure(figsize=(10, 4))
plt.hist(xs, bins=100, color="navy")
plt.xlim(0, 80);
This was a sample code from a data science course and I am trying to understand the syntax.
A:
This code is using the expon() function from the stats module in the Python library scipy to generate random samples from an exponential distribution with a scale parameter of 10. The expon() function returns an object representing the exponential distribution, which can then be used to generate random samples using the rvs() method.
The first line of code, X = stats.expon(scale=10), creates an exponential distribution object with a scale parameter of 10 and assigns it to the variable X.
The second line, xs = X.rvs(100000), generates 100000 random samples from the exponential distribution represented by X and assigns them to the variable xs.
The last two lines use the plt.hist() and plt.xlim() functions from the matplotlib library to create a histogram of the generated samples and set the x-axis limits to 0 and 80, respectively. These lines create a figure with a size of 10 x 4 inches and plot the samples from the xs variable in a histogram with 100 bins.
You should see something like this (representing exponential distribution)
| Question on exponential function and random variable | I am trying to understand the following code. Could someone explain what each step essentially means? (especially the 1st, 2nd and 4th line of code)
X = stats.expon(scale=10)
xs = X.rvs(100000)
plt.figure(figsize=(10, 4))
plt.hist(xs, bins=100, color="navy")
plt.xlim(0, 80);
This was a sample code from a data science course and I am trying to understand the syntax.
| [
"This code is using the expon() function from the stats module in the Python library scipy to generate random samples from an exponential distribution with a scale parameter of 10. The expon() function returns an object representing the exponential distribution, which can then be used to generate random samples using the rvs() method.\nThe first line of code, X = stats.expon(scale=10), creates an exponential distribution object with a scale parameter of 10 and assigns it to the variable X.\nThe second line, xs = X.rvs(100000), generates 100000 random samples from the exponential distribution represented by X and assigns them to the variable xs.\nThe last two lines use the plt.hist() and plt.xlim() functions from the matplotlib library to create a histogram of the generated samples and set the x-axis limits to 0 and 80, respectively. These lines create a figure with a size of 10 x 4 inches and plot the samples from the xs variable in a histogram with 100 bins.\nYou should see something like this (representing exponential distribution)\n\n"
] | [
2
] | [] | [] | [
"exponential",
"matplotlib",
"python"
] | stackoverflow_0074672077_exponential_matplotlib_python.txt |
Q:
Redirect only root index.php to root in .htaccess, not index.php from subdirectories
I need to make some SEO adjustments on a 10 years old code base so I have to proceed with caution.
The task is to do a 301 redirect of https://www.example.com/index.php to https://www.example.com.
The current rules are these:
DirectoryIndex index.php
RewriteEngine On
RewriteBase /
# Force WWW
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
# Force HTTPS
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
# Add a trailing slash to non-files
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]
# General rules
RewriteRule ^product/(.*)-(.*)/(.*)-(.*)/$ product.php?category_permalink=$1&category_id=$2&product_permalink=$3&product_id=$4 [QSA,L]
RewriteRule ^categories/(.*)-(.*)/page-(.*)/$ categories.php?permalink=$1&category_id=$2&page=$3 [QSA,L]
RewriteRule ^categories/(.*)-(.*)/$ categories.php?permalink=$1&category_id=$2 [QSA,L]
RewriteRule ^categories/$ categories.php [QSA,L]
RewriteRule ^search/(.*)$ search.php?q=$1 [QSA,L]
I tried adding the following rules and it works fine, but it messes up https://www.example.com/admin/ too and the website admin can't login anymore because of that.
RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]
So what I'm trying to figure out is: how can I do the redirect only for the index.php file in the root, not for other subdirectories?
Is this possible?
A:
RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]
The .* subpattern matches any URL-path that precedes index.php, so you basically need to remove that.
However, since you don't appear to be using a front-controller pattern (ie. rewriting the request to /index.php) you don't need the preceding condition.
The following would suffice (placed immediately after the RewriteBase directive and before your existing rules - in order to minimise redirects):
RewriteRule ^index\.php$ https://www.example.com/ [R=301,L]
You will need to clear your browser cache before testing. Preferably test with 302 (temporary) redirects to avoid potential caching issues.
If you wish to make this rule generic and avoid hardcoding the hostname (like your other rules) then you can change it like so:
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+?)\.?$ [NC]
RewriteRule ^index\.php$ https://www.%1/ [R=301,L]
The %1 backreference contains the hostname, less the www. subdomain (if any), as captured in the preceding condition.
You can "simplify" the rule and omit the absolute URL (making it root-relative). For example:
RewriteRule ^index\.php$ / [R=301,L]
However, this will result in two redirects if requesting the non-canonical hostname or protocol (ie. non-www or HTTP). Not that that should necessarily cause a serious issue, particularly if non-canonical requests are rare.
| Redirect only root index.php to root in .htaccess, not index.php from subdirectories | I need to make some SEO adjustments on a 10 years old code base so I have to proceed with caution.
The task is to do a 301 redirect of https://www.example.com/index.php to https://www.example.com.
The current rules are these:
DirectoryIndex index.php
RewriteEngine On
RewriteBase /
# Force WWW
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
# Force HTTPS
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
# Add a trailing slash to non-files
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]
# General rules
RewriteRule ^product/(.*)-(.*)/(.*)-(.*)/$ product.php?category_permalink=$1&category_id=$2&product_permalink=$3&product_id=$4 [QSA,L]
RewriteRule ^categories/(.*)-(.*)/page-(.*)/$ categories.php?permalink=$1&category_id=$2&page=$3 [QSA,L]
RewriteRule ^categories/(.*)-(.*)/$ categories.php?permalink=$1&category_id=$2 [QSA,L]
RewriteRule ^categories/$ categories.php [QSA,L]
RewriteRule ^search/(.*)$ search.php?q=$1 [QSA,L]
I tried adding the following rules and it works fine, but it messes up https://www.example.com/admin/ too and the website admin can't login anymore because of that.
RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]
So what I'm trying to figure out is: how can I do the redirect only for the index.php file in the root, not for other subdirectories?
Is this possible?
| [
"\nRewriteCond %{THE_REQUEST} ^.*/index\\.php\nRewriteRule ^(.*)index.php$ /$1 [R=301,L]\n\n\nThe .* subpattern matches any URL-path that precedes index.php, so you basically need to remove that.\nHowever, since you don't appear to be using a front-controller pattern (ie. rewriting the request to /index.php) you don't need the preceding condition.\nThe following would suffice (placed immediately after the RewriteBase directive and before your existing rules - in order to minimise redirects):\nRewriteRule ^index\\.php$ https://www.example.com/ [R=301,L]\n\nYou will need to clear your browser cache before testing. Preferably test with 302 (temporary) redirects to avoid potential caching issues.\n\nIf you wish to make this rule generic and avoid hardcoding the hostname (like your other rules) then you can change it like so:\nRewriteCond %{HTTP_HOST} ^(?:www\\.)?(.+?)\\.?$ [NC]\nRewriteRule ^index\\.php$ https://www.%1/ [R=301,L]\n\nThe %1 backreference contains the hostname, less the www. subdomain (if any), as captured in the preceding condition.\n\nYou can \"simplify\" the rule and omit the absolute URL (making it root-relative). For example:\nRewriteRule ^index\\.php$ / [R=301,L]\n\nHowever, this will result in two redirects if requesting the non-canonical hostname or protocol (ie. non-www or HTTP). Not that that should necessarily cause a serious issue, particularly if non-canonical requests are rare.\n"
] | [
2
] | [] | [] | [
".htaccess",
"mod_rewrite",
"redirect"
] | stackoverflow_0074670094_.htaccess_mod_rewrite_redirect.txt |
Q:
Return dataframes containing unique column pairs in Pandas?
I am trying to use pandas to select rows based on unique column pairs.
For example with the dataframe below read of of an csv:
col1 col2 col3
0 1 10 [a, b, c, d]
1 1 10 [e, f, g, h]
2 2 11 [a, b, c, d]
3 3 12 [i, j, k, l]
4 3 12 [e, f, g, h]
5 5 14 [a, b, c, d]
6 3 10 [m, n, o, p]
This will give me the unique pairs out of col1, col2
df_unique = df['col1', 'col2'].drop_duplicates()
However, I am not sure about how to use each row in df_unique to return a dataframe containing rows that match.
I believe that I could use merge here, but uncertain about the method to use to go about it.
df.merge(df_unique, on=['col1', 'col2'], how='left')
Something like below but an for loop seems like an inefficient way to do this:
for ['col1','col2'] in df_unique:
df_dict['col1, 'col2'] = df.merge(some_subframe, on=['col1', 'col2'], how='left')
Resulting in dataframes like so:
df_uniq_list[(1,10)]
col1 col2 col3
0 1 10 [a, b, c, d]
1 1 10 [e, f, g, h]
df_uniq_list[(2,11)]
col1 col2 col3
2 2 11 [a, b, c, d]
df_uniq_list[(3,12)]
col1 col2 col3
3 3 12 [i, j, k, l]
4 3 12 [e, f, g, h]
A:
You could try with
df_uniq_list = dict([*df.groupby(['col1','col2'])])
df_uniq_list[(1,10)]
col1 col2 col3
0 1 10 [a, b, c, d]
1 1 10 [e, f, g, h]
| Return dataframes containing unique column pairs in Pandas? | I am trying to use pandas to select rows based on unique column pairs.
For example with the dataframe below read of of an csv:
col1 col2 col3
0 1 10 [a, b, c, d]
1 1 10 [e, f, g, h]
2 2 11 [a, b, c, d]
3 3 12 [i, j, k, l]
4 3 12 [e, f, g, h]
5 5 14 [a, b, c, d]
6 3 10 [m, n, o, p]
This will give me the unique pairs out of col1, col2
df_unique = df['col1', 'col2'].drop_duplicates()
However, I am not sure about how to use each row in df_unique to return a dataframe containing rows that match.
I believe that I could use merge here, but uncertain about the method to use to go about it.
df.merge(df_unique, on=['col1', 'col2'], how='left')
Something like below but an for loop seems like an inefficient way to do this:
for ['col1','col2'] in df_unique:
df_dict['col1, 'col2'] = df.merge(some_subframe, on=['col1', 'col2'], how='left')
Resulting in dataframes like so:
df_uniq_list[(1,10)]
col1 col2 col3
0 1 10 [a, b, c, d]
1 1 10 [e, f, g, h]
df_uniq_list[(2,11)]
col1 col2 col3
2 2 11 [a, b, c, d]
df_uniq_list[(3,12)]
col1 col2 col3
3 3 12 [i, j, k, l]
4 3 12 [e, f, g, h]
| [
"You could try with\ndf_uniq_list = dict([*df.groupby(['col1','col2'])])\ndf_uniq_list[(1,10)]\n col1 col2 col3 \n0 1 10 [a, b, c, d]\n1 1 10 [e, f, g, h]\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"set_comprehension"
] | stackoverflow_0074672035_pandas_python_set_comprehension.txt |
Q:
Use selenium pull the link from an href which is an attribute of a class element that has a random class name?
Here is the element. Be aware I slimmed it down, there is much more in the </div>:
<a class="123abc456def" download="" href="https://www.downloadme.com/1jk43jkls.txt role="menuitem" tabindex="-1"><div></div></a>
The class name is a random string of characters so I cant use that as an identifier.
I want to grab the href link. How can I do that with selenium in python?
I tried the following but they did not work:
link_elm = driver.find_element(By.CSS_SELECTOR, "//download[@href]")
link_elm = driver.find_element(By.XPATH, "//a[@href]")
A:
Figured it out. I used the xpath, searched for an a class element, and then searched for if it contained part of the url. Then I pulled the href link with get_attribute
link = driver.find_element(By.XPATH,"//a[@class and contains(@href, 'downloadme')]").get_attribute("href")
| Use selenium pull the link from an href which is an attribute of a class element that has a random class name? | Here is the element. Be aware I slimmed it down, there is much more in the </div>:
<a class="123abc456def" download="" href="https://www.downloadme.com/1jk43jkls.txt role="menuitem" tabindex="-1"><div></div></a>
The class name is a random string of characters so I cant use that as an identifier.
I want to grab the href link. How can I do that with selenium in python?
I tried the following but they did not work:
link_elm = driver.find_element(By.CSS_SELECTOR, "//download[@href]")
link_elm = driver.find_element(By.XPATH, "//a[@href]")
| [
"Figured it out. I used the xpath, searched for an a class element, and then searched for if it contained part of the url. Then I pulled the href link with get_attribute\nlink = driver.find_element(By.XPATH,\"//a[@class and contains(@href, 'downloadme')]\").get_attribute(\"href\")\n\n"
] | [
0
] | [] | [] | [
"class",
"element",
"href",
"python",
"selenium"
] | stackoverflow_0074672012_class_element_href_python_selenium.txt |
Q:
how to add new data to existing json file in java
i'm trying to add new data to existing json file that named question.json but it's not working! it create a new file, can someone help me please!
mycode: i'm using json-simple1.1
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Main {
public static void writeToJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("question", "q3");
ArrayList<String>anss = new ArrayList<>();
anss.add("a1");
anss.add("a2");
anss.add("a3");
anss.add("a4");
JSONArray arr = new JSONArray();
arr.add(anss.get(0));
arr.add(anss.get(1));
arr.add(anss.get(2));
arr.add(anss.get(3));
jsonObject.put("answers",arr);
jsonObject.put("correct_ans", "2");
jsonObject.put("level", "2");
jsonObject.put("team", "animal");
try {
FileWriter file = new FileWriter("json/quetion.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[]args) {
writeToJson();
}
}
{
"questions":[
{
"question": "q1",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4"
],
"correct_ans": "2",
"level": "1",
"team": "animal"
},
{
"question": "q2",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4"
],
"correct_ans": "1",
"level": "2",
"team": "animal"
}
]
}
this is the json file i want to add what i wrote in the code to this json file but i failed! i need someone to tell me how can i add a new json object like {"question" : "q2" ...} without changing the format of the json file or creating a new json file.
A:
org.json.simple
The structure of your JSON has more levels of nesting than can be observed in your code therefore your result doesn't match.
That's what you have in the JSON:
JSONObject { field : JSONArray [ JSONObject { field : value, field : JSONArray, ... }
I.e. JSONObject which contains a JSONArray which might contain several JSONObjects which in turn contain a JSONArray.
That's how it can be translated into the code (to avoid redundancy logic which for creating a nested JSONObject was extracted into a separate method):
JSONObject root = new JSONObject();
JSONArray questions = new JSONArray();
JSONObject question1 = createQuestion(
"q1", "2", "1", "animal",
"answer1", "answer2", "answer3", "answer4"
);
JSONObject question2 = createQuestion(
"q2", "1", "2", "animal",
"answer1", "answer2", "answer3", "answer4"
);
Collections.addAll(questions, question1, question2);
root.put("questions", questions);
public static JSONObject createQuestion(String questionId,
String correctAnswer,
String level, String team,
String... answers) {
JSONObject question = new JSONObject();
question.put("question", questionId);
JSONArray answersArray = new JSONArray();
Collections.addAll(answersArray, answers);
question.put("answers", answersArray);
question.put("correct_ans", correctAnswer);
question.put("level", level);
question.put("team", team);
return question;
}
That's it.
There's a lot of low-level logic which you can eliminate if you would choose a more mature tool for parsing JSON like Jackson, Gson.
Jackson
Here's an example using Jackson library.
Firstly, let's create two POJO: one representing a single question and another wrapping a list of question. For convince, and also in order to avoid posting boilerplate code, I would use Lombock's.
Question class:
@Builder
@AllArgsConstructor
@Getter
public static class Question {
private String questionId;
private List<String> answers;
private String correctAnswer;
private String level;
private String team;
}
Questions class:
@AllArgsConstructor
@Getter
public static class Questions {
private List<Question> questions;
}
Here's how such objects can be serialized:
Question question3 = Question.builder()
.questionId("q1")
.answers(List.of("answer1", "answer2", "answer3", "answer4"))
.correctAnswer("2")
.level("1")
.team("animal")
.build();
Question question4 = Question.builder()
.questionId("q2")
.answers(List.of("answer1", "answer2", "answer3", "answer4"))
.correctAnswer("1")
.level("2")
.team("animal")
.build();
Questions questions1 = new Questions(List.of(question3, question4));
ObjectMapper mapper = new ObjectMapper();
String json1 = mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(questions1);
System.out.println(json1);
Output:
{
"questions" : [ {
"questionId" : "q1",
"answers" : [ "answer1", "answer2", "answer3", "answer4" ],
"correctAnswer" : "2",
"level" : "1",
"team" : "animal"
}, {
"questionId" : "q2",
"answers" : [ "answer1", "answer2", "answer3", "answer4" ],
"correctAnswer" : "1",
"level" : "2",
"team" : "animal"
} ]
}
| how to add new data to existing json file in java | i'm trying to add new data to existing json file that named question.json but it's not working! it create a new file, can someone help me please!
mycode: i'm using json-simple1.1
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Main {
public static void writeToJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("question", "q3");
ArrayList<String>anss = new ArrayList<>();
anss.add("a1");
anss.add("a2");
anss.add("a3");
anss.add("a4");
JSONArray arr = new JSONArray();
arr.add(anss.get(0));
arr.add(anss.get(1));
arr.add(anss.get(2));
arr.add(anss.get(3));
jsonObject.put("answers",arr);
jsonObject.put("correct_ans", "2");
jsonObject.put("level", "2");
jsonObject.put("team", "animal");
try {
FileWriter file = new FileWriter("json/quetion.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[]args) {
writeToJson();
}
}
{
"questions":[
{
"question": "q1",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4"
],
"correct_ans": "2",
"level": "1",
"team": "animal"
},
{
"question": "q2",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4"
],
"correct_ans": "1",
"level": "2",
"team": "animal"
}
]
}
this is the json file i want to add what i wrote in the code to this json file but i failed! i need someone to tell me how can i add a new json object like {"question" : "q2" ...} without changing the format of the json file or creating a new json file.
| [
"org.json.simple\nThe structure of your JSON has more levels of nesting than can be observed in your code therefore your result doesn't match.\nThat's what you have in the JSON:\nJSONObject { field : JSONArray [ JSONObject { field : value, field : JSONArray, ... }\n\nI.e. JSONObject which contains a JSONArray which might contain several JSONObjects which in turn contain a JSONArray.\nThat's how it can be translated into the code (to avoid redundancy logic which for creating a nested JSONObject was extracted into a separate method):\nJSONObject root = new JSONObject();\nJSONArray questions = new JSONArray();\n \nJSONObject question1 = createQuestion(\n \"q1\", \"2\", \"1\", \"animal\",\n \"answer1\", \"answer2\", \"answer3\", \"answer4\"\n);\nJSONObject question2 = createQuestion(\n \"q2\", \"1\", \"2\", \"animal\",\n \"answer1\", \"answer2\", \"answer3\", \"answer4\"\n);\n \nCollections.addAll(questions, question1, question2);\nroot.put(\"questions\", questions);\n\npublic static JSONObject createQuestion(String questionId,\n String correctAnswer,\n String level, String team,\n String... answers) {\n\n JSONObject question = new JSONObject();\n question.put(\"question\", questionId);\n \n JSONArray answersArray = new JSONArray();\n Collections.addAll(answersArray, answers);\n \n question.put(\"answers\", answersArray);\n question.put(\"correct_ans\", correctAnswer);\n question.put(\"level\", level);\n question.put(\"team\", team);\n \n return question;\n}\n\nThat's it.\nThere's a lot of low-level logic which you can eliminate if you would choose a more mature tool for parsing JSON like Jackson, Gson.\nJackson\nHere's an example using Jackson library.\nFirstly, let's create two POJO: one representing a single question and another wrapping a list of question. For convince, and also in order to avoid posting boilerplate code, I would use Lombock's.\nQuestion class:\n@Builder\n@AllArgsConstructor\n@Getter\npublic static class Question {\n private String questionId;\n private List<String> answers;\n private String correctAnswer;\n private String level;\n private String team;\n}\n\nQuestions class:\n@AllArgsConstructor\n@Getter\npublic static class Questions {\n private List<Question> questions;\n}\n\nHere's how such objects can be serialized:\nQuestion question3 = Question.builder()\n .questionId(\"q1\")\n .answers(List.of(\"answer1\", \"answer2\", \"answer3\", \"answer4\"))\n .correctAnswer(\"2\")\n .level(\"1\")\n .team(\"animal\")\n .build();\n \nQuestion question4 = Question.builder()\n .questionId(\"q2\")\n .answers(List.of(\"answer1\", \"answer2\", \"answer3\", \"answer4\"))\n .correctAnswer(\"1\")\n .level(\"2\")\n .team(\"animal\")\n .build();\n \nQuestions questions1 = new Questions(List.of(question3, question4));\n \nObjectMapper mapper = new ObjectMapper();\nString json1 = mapper\n .writerWithDefaultPrettyPrinter()\n .writeValueAsString(questions1);\n \nSystem.out.println(json1);\n\nOutput:\n{\n \"questions\" : [ {\n \"questionId\" : \"q1\",\n \"answers\" : [ \"answer1\", \"answer2\", \"answer3\", \"answer4\" ],\n \"correctAnswer\" : \"2\",\n \"level\" : \"1\",\n \"team\" : \"animal\"\n }, {\n \"questionId\" : \"q2\",\n \"answers\" : [ \"answer1\", \"answer2\", \"answer3\", \"answer4\" ],\n \"correctAnswer\" : \"1\",\n \"level\" : \"2\",\n \"team\" : \"animal\"\n } ]\n}\n\n"
] | [
0
] | [] | [] | [
"arrays",
"java",
"json",
"oop",
"simplejson"
] | stackoverflow_0074665910_arrays_java_json_oop_simplejson.txt |
Q:
Can't connect Mongo shell to Mongo Atlas M0 using mongodb+srv
I am trying to connect to my MongoDB Atlas Cloud cluster via the mongo+srv connection like so:
mongo "mongodb+srv://cluster0-mhzdc.mongodb.net/test" --username myuser
I am getting this response:
DNSHostNotFound: Failed to look up service "_mongodb._tcp.cluster0-mhzdc.mongodb.net": Undefined error: 0
try 'mongo --help' for more information
I am using the following version of Mongo client:
mongo --version
MongoDB shell version v4.0.5
git version: 3739429dd92b92d1b0ab120911a23d50bf03c412
allocator: system
modules: none
build environment:
distarch: x86_64
target_arch: x86_64
I can't find any resolution online. Any ideas what's wrong? Is this a bug in the given version of the Mongo shell client?
A:
It looks like bug 34117, still unresolved:
https://jira.mongodb.org/browse/SERVER-34117
To work around the bug check if you have a DNS resolver active on your notebook.
On windows:
ipconfig /displayDNS
to see the current DNS resolver cache.
You might even try to erase the cache with the command:
ipconfig /flushdns
and retry.
If you are working on linux ubuntu try the command:
named -v
to check if the DNS resolver software is already installed.
If not:
sudo apt update
sudo apt install bind9 bind9utils bind9-doc bind9-host
to install the needed packages, then start the service:
sudo systemctl start bind9
and retry.
On Mac OSX, the command is:
sudo killall -HUP mDNSResponder;sudo killall mDNSResponderHelper;sudo dscacheutil -flushcache
A:
The same happens to me, but just after i change my internet provider. Before, i could connect to mongo atlas with no problem.
I guess this happens because the DNS resolver of my internet provider could not resolve the uri to connect to mongodb atlas.
The Solution ->
Change de DNS resolver on my PC:
Open the Control Panel.
Click View network status and tasks
Click Change adapter settings on the left portion of the window.
Double-click the icon for the Internet connection you're using.
Click the Properties button.
Click and highlight Internet Protocol Version 4 (TCP/IPv4) and click Properties.
If not already selected, select the Use the following DNS server addresses option.
Enter the new DNS addresses and click OK and close out of all other windows.
I used google public dns 8.8.8.8.
After that i could connect again with my mongo shell ou compass to mongo atlas.
Hope that helps someone..
A:
I also had this problem with Comcast Xfinity. For those running Ubuntu 18.04 or similar, I had to edit (you'll need root permissions) the /etc/dhcp/dhclient.conf file, and add to following line:
supersede domain-name-servers 8.8.8.8, 8.8.4.4;
I hope this helps somebody, took me too long to figure it out. :-)
A:
I spent lot of time to figure the out issue. after the change DNS it worked. thanks
Used google dns servers.
8.8.8.8
8.8.4.4
| Can't connect Mongo shell to Mongo Atlas M0 using mongodb+srv | I am trying to connect to my MongoDB Atlas Cloud cluster via the mongo+srv connection like so:
mongo "mongodb+srv://cluster0-mhzdc.mongodb.net/test" --username myuser
I am getting this response:
DNSHostNotFound: Failed to look up service "_mongodb._tcp.cluster0-mhzdc.mongodb.net": Undefined error: 0
try 'mongo --help' for more information
I am using the following version of Mongo client:
mongo --version
MongoDB shell version v4.0.5
git version: 3739429dd92b92d1b0ab120911a23d50bf03c412
allocator: system
modules: none
build environment:
distarch: x86_64
target_arch: x86_64
I can't find any resolution online. Any ideas what's wrong? Is this a bug in the given version of the Mongo shell client?
| [
"It looks like bug 34117, still unresolved:\nhttps://jira.mongodb.org/browse/SERVER-34117\nTo work around the bug check if you have a DNS resolver active on your notebook.\nOn windows:\nipconfig /displayDNS\n\nto see the current DNS resolver cache.\nYou might even try to erase the cache with the command:\nipconfig /flushdns\n\nand retry.\nIf you are working on linux ubuntu try the command:\nnamed -v\n\nto check if the DNS resolver software is already installed.\nIf not:\nsudo apt update\nsudo apt install bind9 bind9utils bind9-doc bind9-host\n\nto install the needed packages, then start the service:\nsudo systemctl start bind9\n\nand retry.\nOn Mac OSX, the command is:\nsudo killall -HUP mDNSResponder;sudo killall mDNSResponderHelper;sudo dscacheutil -flushcache\n\n",
"The same happens to me, but just after i change my internet provider. Before, i could connect to mongo atlas with no problem.\nI guess this happens because the DNS resolver of my internet provider could not resolve the uri to connect to mongodb atlas.\nThe Solution ->\nChange de DNS resolver on my PC:\n\nOpen the Control Panel.\nClick View network status and tasks\nClick Change adapter settings on the left portion of the window.\nDouble-click the icon for the Internet connection you're using.\nClick the Properties button.\nClick and highlight Internet Protocol Version 4 (TCP/IPv4) and click Properties.\nIf not already selected, select the Use the following DNS server addresses option.\nEnter the new DNS addresses and click OK and close out of all other windows.\n\nI used google public dns 8.8.8.8.\nAfter that i could connect again with my mongo shell ou compass to mongo atlas.\nHope that helps someone..\n",
"I also had this problem with Comcast Xfinity. For those running Ubuntu 18.04 or similar, I had to edit (you'll need root permissions) the /etc/dhcp/dhclient.conf file, and add to following line:\nsupersede domain-name-servers 8.8.8.8, 8.8.4.4;\nI hope this helps somebody, took me too long to figure it out. :-)\n",
"I spent lot of time to figure the out issue. after the change DNS it worked. thanks\nUsed google dns servers.\n\n8.8.8.8\n8.8.4.4\n\n"
] | [
4,
3,
1,
0
] | [] | [] | [
"mongodb"
] | stackoverflow_0055893437_mongodb.txt |
Q:
How do I set the first element in a vector as equal to a structure?
In the program I'm writing, I have a vector whose elements are instances of a struct called "person", and I'm allowing the user to add elements to the vector. I've tried two methods of actually adding elements to the vector so far, and neither of them has worked. I'm storing the user's input in a variable called inputtedPerson that is an instance of "person", and then I'm trying to add that variable to the vector. First I tried Sample.at(0) = inputtedPerson, but that ended up giving me this error when I tried to run the program in GDB.
Then, I tried creating an iterator called iter, setting it to Sample.begin(), and having the program add the element to the beginning of the vector by setting *iter as equal to inputtedPerson. (For every subsequent person that is added, the iterator is incremented by one, such that the people are added in sequential order.) Unfortunately, that produced a segmentation fault error:
What am I doing wrong?
Here's my code:
// DelibDem.cpp : Defines the entry point for the application.
//
#include "DelibDem.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
//initializing variables
using namespace std;
bool continue_ = true;
string name = "";
string partyID = "";
int numD = 0;
int numR = 0;
int difference = 0;
int vectorSize = 0;
int newVectorSize = 0;
int demPos = 0;
int repPos = 0;
struct person{
string Name;
string PartyID;
string equivalentName;
string equivalenceClass;
};
vector<person> Sample;
std::vector<person>::iterator iter = Sample.begin();
int main()
{
//user adds people to the vector
while (continue_ == true) {
string personName;
string personPartyID;
string answer;
person inputtedPerson;
cout << "Enter a person's name: ";
std::getline(cin, personName);
//cout << personName;
cout << "Enter the person's party ID (D or R): ";
std::getline(cin, personPartyID);
//cout << personPartyID;
if (personPartyID == "D") person inputtedPerson = { personName, personPartyID, "", "Republicans" };
else person inputtedPerson = { personName, personPartyID, "", "Democrats" };
*iter = inputtedPerson;
//cout << "{{" << Sample.at(0).Name << ", " << Sample.at(0).PartyID << ", " << Sample.at(0).equivalentName << ", " << Sample.at(0).equivalenceClass << "}\n";
//for (int i = 1; i < Sample.size(); i++) {
// cout << ", {" << Sample.at(i).Name << ", " << Sample.at(i).PartyID << ", " << Sample.at(i).equivalentName << ", " << Sample.at(i).equivalenceClass << "}\n";
//}
//cout << "}";
iter++;
cout << "Do you wish to add more people? (Y/N) ";
cin >> answer;
if (answer == "N") continue_ = false;
cin.ignore();
}
//The number of Democrats in the sample is stored in numD. The number of Republicans is stored in numR.
for (auto& element : Sample)
{
if (element.PartyID == "D") numD++;
else numR++;
}
//print the number of Democrats and Republicans
cout << numD;
cout << numR;
//determine if an equivalence relation exists
if (numD == numR) cout << "An equivalence relation is possible" << endl;
else {
cout << "An equivalence relation is not possible, because ";
if (numD > numR) {
cout << "There are " << numD - numR << " more Democrats than Republicans" << endl;
int difference = numD - numR;
while (difference != 0) {
string specifiedName;
vectorSize = Sample.size();
cout << "Which Democrat do you want to remove from the sample?" << endl;
cin >> specifiedName;
for (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it) //this is the part I'm asking about
{
if (( * it).Name == specifiedName && ( * it).PartyID == "D") {
Sample.erase(it);
break;
}
}
newVectorSize = Sample.size();
if (vectorSize == newVectorSize) cout << "The requested person is not one of the Democrats in the sample. Please try again." << endl;
else difference--;
}
}
else {
cout << "There are " << numR - numD << " more Republicans than Democrats" << endl;
int difference = numR - numD;
while (difference != 0) {
string specifiedName;
vectorSize = Sample.size();
cout << "Which Republican do you want to remove from the sample?" << endl;
cin >> specifiedName;
for (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it)
{
if (( * it).Name == specifiedName && ( * it).PartyID == "R") {
Sample.erase(it);
break;
}
}
newVectorSize = Sample.size();
if (vectorSize == newVectorSize) cout << "The requested person is not one of the Republicans in the sample. Please try again." << endl;
else difference--;
}
}
cout << "The number of Democrats and Republicans is now equal and an equivalence relation is possible." << endl;
}
//print the properties of each element in the sample
for (auto& element : Sample)
{
cout << element.Name << endl;
cout << element.PartyID << endl;
cout << element.equivalentName << endl;
cout << element.equivalenceClass << endl;
cout << "\n";
}
//creating two vectors containing only the Democrats and Republicans, respectively
vector<person> Democrats;
vector<person> Republicans;
for (auto& element : Sample)
{
if (element.PartyID == "D") {
Democrats.at(demPos) = element;
demPos++;
}
else {
Republicans.at(repPos) = element;
repPos++;
}
}
//assigning each Democrat to a Republican and vice versa
std::vector<person>::iterator iterD = Democrats.begin();
std::vector<person>::iterator iterR = Republicans.begin();
for (int i = 0; i < Democrats.size(); i++)
{
(*iterD).equivalentName = (*iterR).Name;
iterD++;
iterR++;
}
iterD = Democrats.begin();
iterR = Republicans.begin();
for (int i = 0; i < Republicans.size(); i++)
{
(*iterR).equivalentName = (*iterD).Name;
iterR++;
iterD++;
}
return 0;
//printing the properties of each element in the sample again
for (auto& element : Sample)
{
cout << element.Name << endl;
cout << element.PartyID << endl;
cout << element.equivalentName << endl;
cout << element.equivalenceClass << endl;
cout << "\n";
}
}
A:
I point some issues with the posted code, addressing the main question as well, and include an alternative solution at the end:
Try not to using namespace std;, as it pollutes your program's namespace (see more here).
Try to declare variables next to their first use.
If possible, prefer local variables to globals. For this example, no global variables are needed.
Always initialize variables, especially locals.
Try to use block braces even for one-line blocks.
Try not to mix std::getline and std::cin >>. For this example, better stick to std::getline (see more here).
Use functions to structure the code, especially if you start repeating a few lines now and then (e.g. print the Sample vector).
If that function is printing an object, it can be implemented as its operator<<.
This is not the correct way to add values to a vector. Notice iter is initialized to Sample.begin(), which happens to be the same as Sample.end() since Sample is empty; so *iter, i.e. dereferencing iter, will be an error.
vector<person> Sample;
std::vector<person>::iterator iter = Sample.begin();
*iter = inputtedPerson;
iter++;
Once you have read the person information, you can use Sample.push_back to add a new person to Sample.
sample.push_back(std::move(p));
The code below is an erase if. It may be more efficient, because it can break earlier, but it is more complex and it doesn't express intent as well.
vectorSize = Sample.size();
for (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it)
{
if (( * it).Name == specifiedName && ( * it).PartyID == "D") {
Sample.erase(it);
break;
}
}
newVectorSize = Sample.size();
if (vectorSize != newVectorSize)
difference--;
std::erase_if gives you the number of erased elements, so you don't need to use neither vectorSize nor newVectorSize.
if (auto no_of_erased_people{
std::erase_if(sample,
[&specifiedName, &party](auto& person) {
return person.Name == specifiedName and person.PartyID == party;
}
)
};
no_of_erased_people != 0) {
difference--;
}
Likewise, the code below is a count if.
for (auto& element : Sample)
{
if (element.PartyID == "D") numD++;
else numR++;
}
You won't get to write many fewer lines, but they, again, should be more readable.
auto numD{ std::ranges::count_if(sample, [](const auto& person) {
return person.is_democrat(); })
};
auto numR{ std::ssize(sample) - numD };
Finally, in order to set the equivalentName for each person, there is no need to create two new vectors, one for democrats and one for republicans. The original sample vector can be partitioned, sorting people from one party before the other. Since you know there are the same number of people from both parties, you can then walk the sample vector with one iterator pointing to the current person of each party, and match them.
auto rep_it{ std::partition(sample.begin(), sample.end(),
[](auto& person) { return person.is_democrat(); }) };
for (auto dem_it{ sample.begin() }; rep_it != sample.end(); ++dem_it, ++rep_it) {
dem_it->equivalentName = rep_it->Name;
rep_it->equivalentName = dem_it->Name;
}
[Demo]
| How do I set the first element in a vector as equal to a structure? | In the program I'm writing, I have a vector whose elements are instances of a struct called "person", and I'm allowing the user to add elements to the vector. I've tried two methods of actually adding elements to the vector so far, and neither of them has worked. I'm storing the user's input in a variable called inputtedPerson that is an instance of "person", and then I'm trying to add that variable to the vector. First I tried Sample.at(0) = inputtedPerson, but that ended up giving me this error when I tried to run the program in GDB.
Then, I tried creating an iterator called iter, setting it to Sample.begin(), and having the program add the element to the beginning of the vector by setting *iter as equal to inputtedPerson. (For every subsequent person that is added, the iterator is incremented by one, such that the people are added in sequential order.) Unfortunately, that produced a segmentation fault error:
What am I doing wrong?
Here's my code:
// DelibDem.cpp : Defines the entry point for the application.
//
#include "DelibDem.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
//initializing variables
using namespace std;
bool continue_ = true;
string name = "";
string partyID = "";
int numD = 0;
int numR = 0;
int difference = 0;
int vectorSize = 0;
int newVectorSize = 0;
int demPos = 0;
int repPos = 0;
struct person{
string Name;
string PartyID;
string equivalentName;
string equivalenceClass;
};
vector<person> Sample;
std::vector<person>::iterator iter = Sample.begin();
int main()
{
//user adds people to the vector
while (continue_ == true) {
string personName;
string personPartyID;
string answer;
person inputtedPerson;
cout << "Enter a person's name: ";
std::getline(cin, personName);
//cout << personName;
cout << "Enter the person's party ID (D or R): ";
std::getline(cin, personPartyID);
//cout << personPartyID;
if (personPartyID == "D") person inputtedPerson = { personName, personPartyID, "", "Republicans" };
else person inputtedPerson = { personName, personPartyID, "", "Democrats" };
*iter = inputtedPerson;
//cout << "{{" << Sample.at(0).Name << ", " << Sample.at(0).PartyID << ", " << Sample.at(0).equivalentName << ", " << Sample.at(0).equivalenceClass << "}\n";
//for (int i = 1; i < Sample.size(); i++) {
// cout << ", {" << Sample.at(i).Name << ", " << Sample.at(i).PartyID << ", " << Sample.at(i).equivalentName << ", " << Sample.at(i).equivalenceClass << "}\n";
//}
//cout << "}";
iter++;
cout << "Do you wish to add more people? (Y/N) ";
cin >> answer;
if (answer == "N") continue_ = false;
cin.ignore();
}
//The number of Democrats in the sample is stored in numD. The number of Republicans is stored in numR.
for (auto& element : Sample)
{
if (element.PartyID == "D") numD++;
else numR++;
}
//print the number of Democrats and Republicans
cout << numD;
cout << numR;
//determine if an equivalence relation exists
if (numD == numR) cout << "An equivalence relation is possible" << endl;
else {
cout << "An equivalence relation is not possible, because ";
if (numD > numR) {
cout << "There are " << numD - numR << " more Democrats than Republicans" << endl;
int difference = numD - numR;
while (difference != 0) {
string specifiedName;
vectorSize = Sample.size();
cout << "Which Democrat do you want to remove from the sample?" << endl;
cin >> specifiedName;
for (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it) //this is the part I'm asking about
{
if (( * it).Name == specifiedName && ( * it).PartyID == "D") {
Sample.erase(it);
break;
}
}
newVectorSize = Sample.size();
if (vectorSize == newVectorSize) cout << "The requested person is not one of the Democrats in the sample. Please try again." << endl;
else difference--;
}
}
else {
cout << "There are " << numR - numD << " more Republicans than Democrats" << endl;
int difference = numR - numD;
while (difference != 0) {
string specifiedName;
vectorSize = Sample.size();
cout << "Which Republican do you want to remove from the sample?" << endl;
cin >> specifiedName;
for (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it)
{
if (( * it).Name == specifiedName && ( * it).PartyID == "R") {
Sample.erase(it);
break;
}
}
newVectorSize = Sample.size();
if (vectorSize == newVectorSize) cout << "The requested person is not one of the Republicans in the sample. Please try again." << endl;
else difference--;
}
}
cout << "The number of Democrats and Republicans is now equal and an equivalence relation is possible." << endl;
}
//print the properties of each element in the sample
for (auto& element : Sample)
{
cout << element.Name << endl;
cout << element.PartyID << endl;
cout << element.equivalentName << endl;
cout << element.equivalenceClass << endl;
cout << "\n";
}
//creating two vectors containing only the Democrats and Republicans, respectively
vector<person> Democrats;
vector<person> Republicans;
for (auto& element : Sample)
{
if (element.PartyID == "D") {
Democrats.at(demPos) = element;
demPos++;
}
else {
Republicans.at(repPos) = element;
repPos++;
}
}
//assigning each Democrat to a Republican and vice versa
std::vector<person>::iterator iterD = Democrats.begin();
std::vector<person>::iterator iterR = Republicans.begin();
for (int i = 0; i < Democrats.size(); i++)
{
(*iterD).equivalentName = (*iterR).Name;
iterD++;
iterR++;
}
iterD = Democrats.begin();
iterR = Republicans.begin();
for (int i = 0; i < Republicans.size(); i++)
{
(*iterR).equivalentName = (*iterD).Name;
iterR++;
iterD++;
}
return 0;
//printing the properties of each element in the sample again
for (auto& element : Sample)
{
cout << element.Name << endl;
cout << element.PartyID << endl;
cout << element.equivalentName << endl;
cout << element.equivalenceClass << endl;
cout << "\n";
}
}
| [
"I point some issues with the posted code, addressing the main question as well, and include an alternative solution at the end:\n\nTry not to using namespace std;, as it pollutes your program's namespace (see more here).\n\nTry to declare variables next to their first use.\nIf possible, prefer local variables to globals. For this example, no global variables are needed.\nAlways initialize variables, especially locals.\n\nTry to use block braces even for one-line blocks.\n\nTry not to mix std::getline and std::cin >>. For this example, better stick to std::getline (see more here).\n\nUse functions to structure the code, especially if you start repeating a few lines now and then (e.g. print the Sample vector).\nIf that function is printing an object, it can be implemented as its operator<<.\n\nThis is not the correct way to add values to a vector. Notice iter is initialized to Sample.begin(), which happens to be the same as Sample.end() since Sample is empty; so *iter, i.e. dereferencing iter, will be an error.\n\n\nvector<person> Sample;\nstd::vector<person>::iterator iter = Sample.begin();\n*iter = inputtedPerson;\niter++;\n\nOnce you have read the person information, you can use Sample.push_back to add a new person to Sample.\nsample.push_back(std::move(p));\n\n\nThe code below is an erase if. It may be more efficient, because it can break earlier, but it is more complex and it doesn't express intent as well.\n\nvectorSize = Sample.size();\nfor (std::vector<person>::iterator it = Sample.begin(); it != Sample.end(); ++it)\n{\n if (( * it).Name == specifiedName && ( * it).PartyID == \"D\") {\n Sample.erase(it);\n break;\n }\n}\nnewVectorSize = Sample.size();\nif (vectorSize != newVectorSize)\n difference--;\n\nstd::erase_if gives you the number of erased elements, so you don't need to use neither vectorSize nor newVectorSize.\nif (auto no_of_erased_people{\n std::erase_if(sample,\n [&specifiedName, &party](auto& person) {\n return person.Name == specifiedName and person.PartyID == party;\n }\n )\n };\n no_of_erased_people != 0) {\n difference--;\n}\n\n\nLikewise, the code below is a count if.\n\nfor (auto& element : Sample)\n{\n if (element.PartyID == \"D\") numD++;\n else numR++;\n}\n\nYou won't get to write many fewer lines, but they, again, should be more readable.\nauto numD{ std::ranges::count_if(sample, [](const auto& person) {\n return person.is_democrat(); })\n};\nauto numR{ std::ssize(sample) - numD };\n\n\nFinally, in order to set the equivalentName for each person, there is no need to create two new vectors, one for democrats and one for republicans. The original sample vector can be partitioned, sorting people from one party before the other. Since you know there are the same number of people from both parties, you can then walk the sample vector with one iterator pointing to the current person of each party, and match them.\n\nauto rep_it{ std::partition(sample.begin(), sample.end(),\n [](auto& person) { return person.is_democrat(); }) };\nfor (auto dem_it{ sample.begin() }; rep_it != sample.end(); ++dem_it, ++rep_it) {\n dem_it->equivalentName = rep_it->Name;\n rep_it->equivalentName = dem_it->Name;\n}\n\n[Demo]\n"
] | [
0
] | [] | [] | [
"c++",
"iterator",
"struct"
] | stackoverflow_0074671124_c++_iterator_struct.txt |
Q:
Sorting a List by frequency of occurrence in a list
I have a list of integers(or could be even strings), which I would like to sort by the frequency of occurrences in Python, for instance:
a = [1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]
Here the element 5 appears 4 times in the list, 4 appears 3 times. So the output sorted list would be :
result = [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
I tried using a.count(), but it gives the number of occurrence of the element.
I would like to sort it. Any idea how to do it ?
Thanks
A:
from collections import Counter
print [item for items, c in Counter(a).most_common() for item in [items] * c]
# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
Or even better (efficient) implementation
from collections import Counter
from itertools import repeat, chain
print list(chain.from_iterable(repeat(i, c) for i,c in Counter(a).most_common()))
# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
Or
from collections import Counter
print sorted(a, key=Counter(a).get, reverse=True)
# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
If you prefer in-place sort
a.sort(key=Counter(a).get, reverse=True)
A:
Using Python 3.3 and the built in sorted function, with the count as the key:
>>> a = [1,1,2,3,3,3,4,4,4,5,5,5,5]
>>> sorted(a,key=a.count)
[2, 1, 1, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]
>>> sorted(a,key=a.count,reverse=True)
[5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
A:
In [15]: a = [1,1,2,3,3,3,4,4,4,5,5,5,5]
In [16]: counts = collections.Counter(a)
In [17]: list(itertools.chain.from_iterable([[k for _ in range(counts[k])] for k in sorted(counts, key=counts.__getitem__, reverse=True)]))
Out[17]: [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
Alternatively:
answer = []
for k in sorted(counts, key=counts.__getitem__, reverse=True):
answer.extend([k for _ in range(counts[k])])
Of course, [k for _ in range(counts[k])] can be replaced with [k]*counts[k].
So line 17 becomes
list(itertools.chain.from_iterable([[k]*counts[k] for k in sorted(counts, key=counts.__getitem__, reverse=True)]))
A:
If you happen to be using numpy already, or if using it is an option, here's another alternative:
In [309]: import numpy as np
In [310]: a = [1, 2, 3, 3, 1, 3, 5, 4, 4, 4, 5, 5, 5]
In [311]: vals, counts = np.unique(a, return_counts=True)
In [312]: order = np.argsort(counts)[::-1]
In [313]: np.repeat(vals[order], counts[order])
Out[313]: array([5, 5, 5, 5, 4, 4, 4, 3, 3, 3, 1, 1, 2])
That result is a numpy array. If you want to end up with a Python list, call the array's tolist() method:
In [314]: np.repeat(vals[order], counts[order]).tolist()
Out[314]: [5, 5, 5, 5, 4, 4, 4, 3, 3, 3, 1, 1, 2]
A:
Not interesting way...
a = [1,1,2,3,3,3,4,4,4,5,5,5,5]
from collections import Counter
result = []
for v, times in sorted(Counter(a).iteritems(), key=lambda x: x[1], reverse=True):
result += [v] * times
One liner:
reduce(lambda a, b: a + [b[0]] * b[1], sorted(Counter(a).iteritems(), key=lambda x: x[1], reverse=True), [])
A:
Occurrence in array and within a sets of equal size:
rev=True
arr = [6, 6, 5, 2, 9, 2, 5, 9, 2, 5, 6, 5, 4, 6, 9, 1, 2, 3, 4, 7 ,8 ,8, 8, 2]
print arr
arr.sort(reverse=rev)
ARR = {}
for n in arr:
if n not in ARR:
ARR[n] = 0
ARR[n] += 1
arr=[]
for k,v in sorted(ARR.iteritems(), key=lambda (k,v): (v,k), reverse=rev):
arr.extend([k]*v)
print arr
Results:
[6, 6, 5, 2, 9, 2, 5, 9, 2, 5, 6, 5, 4, 6, 9, 1, 2, 3, 4, 7, 8, 8, 8, 2]
[2, 2, 2, 2, 2, 6, 6, 6, 6, 5, 5, 5, 5, 9, 9, 9, 8, 8, 8, 4, 4, 7, 3, 1]
A:
Dart Solution
String sortedString = '';
Map map = {};
for (int i = 0; i < s.length; i++) {
map[s[i]] = (map[s[i]] ?? 0) + 1;
// OR
// map.containsKey(s[i])
// ? map.update(s[i], (value) => ++value)
// : map.addAll({s[i]: 1});
}
var sortedByValueMap = Map.fromEntries(
map.entries.toList()..sort((e1, e2) => e1.value.compareTo(e2.value)));
sortedByValueMap.forEach((key, value) {
sortedString += key * value;
});
return sortedString.split('').reversed. Join();
| Sorting a List by frequency of occurrence in a list | I have a list of integers(or could be even strings), which I would like to sort by the frequency of occurrences in Python, for instance:
a = [1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]
Here the element 5 appears 4 times in the list, 4 appears 3 times. So the output sorted list would be :
result = [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
I tried using a.count(), but it gives the number of occurrence of the element.
I would like to sort it. Any idea how to do it ?
Thanks
| [
"from collections import Counter\nprint [item for items, c in Counter(a).most_common() for item in [items] * c]\n# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]\n\nOr even better (efficient) implementation\nfrom collections import Counter\nfrom itertools import repeat, chain\nprint list(chain.from_iterable(repeat(i, c) for i,c in Counter(a).most_common()))\n# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]\n\nOr\nfrom collections import Counter\nprint sorted(a, key=Counter(a).get, reverse=True)\n# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]\n\nIf you prefer in-place sort\na.sort(key=Counter(a).get, reverse=True)\n\n",
"Using Python 3.3 and the built in sorted function, with the count as the key:\n>>> a = [1,1,2,3,3,3,4,4,4,5,5,5,5]\n>>> sorted(a,key=a.count)\n[2, 1, 1, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]\n>>> sorted(a,key=a.count,reverse=True)\n[5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]\n\n",
"In [15]: a = [1,1,2,3,3,3,4,4,4,5,5,5,5]\n\nIn [16]: counts = collections.Counter(a)\n\nIn [17]: list(itertools.chain.from_iterable([[k for _ in range(counts[k])] for k in sorted(counts, key=counts.__getitem__, reverse=True)]))\nOut[17]: [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]\n\nAlternatively:\nanswer = []\nfor k in sorted(counts, key=counts.__getitem__, reverse=True):\n answer.extend([k for _ in range(counts[k])])\n\nOf course, [k for _ in range(counts[k])] can be replaced with [k]*counts[k].\nSo line 17 becomes \nlist(itertools.chain.from_iterable([[k]*counts[k] for k in sorted(counts, key=counts.__getitem__, reverse=True)]))\n\n",
"If you happen to be using numpy already, or if using it is an option, here's another alternative:\nIn [309]: import numpy as np\n\nIn [310]: a = [1, 2, 3, 3, 1, 3, 5, 4, 4, 4, 5, 5, 5]\n\nIn [311]: vals, counts = np.unique(a, return_counts=True)\n\nIn [312]: order = np.argsort(counts)[::-1]\n\nIn [313]: np.repeat(vals[order], counts[order])\nOut[313]: array([5, 5, 5, 5, 4, 4, 4, 3, 3, 3, 1, 1, 2])\n\nThat result is a numpy array. If you want to end up with a Python list, call the array's tolist() method:\nIn [314]: np.repeat(vals[order], counts[order]).tolist()\nOut[314]: [5, 5, 5, 5, 4, 4, 4, 3, 3, 3, 1, 1, 2]\n\n",
"Not interesting way...\na = [1,1,2,3,3,3,4,4,4,5,5,5,5]\n\nfrom collections import Counter\nresult = []\nfor v, times in sorted(Counter(a).iteritems(), key=lambda x: x[1], reverse=True):\n result += [v] * times\n\nOne liner:\nreduce(lambda a, b: a + [b[0]] * b[1], sorted(Counter(a).iteritems(), key=lambda x: x[1], reverse=True), [])\n\n",
"Occurrence in array and within a sets of equal size:\nrev=True\n\narr = [6, 6, 5, 2, 9, 2, 5, 9, 2, 5, 6, 5, 4, 6, 9, 1, 2, 3, 4, 7 ,8 ,8, 8, 2]\nprint arr\n\narr.sort(reverse=rev)\n\nARR = {}\nfor n in arr:\n if n not in ARR:\n ARR[n] = 0\n ARR[n] += 1\n\narr=[]\nfor k,v in sorted(ARR.iteritems(), key=lambda (k,v): (v,k), reverse=rev):\n arr.extend([k]*v)\nprint arr\n\nResults:\n[6, 6, 5, 2, 9, 2, 5, 9, 2, 5, 6, 5, 4, 6, 9, 1, 2, 3, 4, 7, 8, 8, 8, 2]\n[2, 2, 2, 2, 2, 6, 6, 6, 6, 5, 5, 5, 5, 9, 9, 9, 8, 8, 8, 4, 4, 7, 3, 1]\n\n",
"Dart Solution\nString sortedString = '';\nMap map = {};\nfor (int i = 0; i < s.length; i++) {\n map[s[i]] = (map[s[i]] ?? 0) + 1;\n // OR \n // map.containsKey(s[i])\n // ? map.update(s[i], (value) => ++value)\n // : map.addAll({s[i]: 1});\n}\nvar sortedByValueMap = Map.fromEntries(\n map.entries.toList()..sort((e1, e2) => e1.value.compareTo(e2.value)));\nsortedByValueMap.forEach((key, value) {\n sortedString += key * value;\n});\nreturn sortedString.split('').reversed. Join();\n\n"
] | [
37,
8,
3,
1,
0,
0,
0
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0023429426_list_python_sorting.txt |
Q:
MongoDB: when deleting an old collection and inserting a new collection, sometimes the new collection is not saved
There is a form with input text fields, used to define a list of flavors. Submitting the form should delete the old flavor collection and replace it with the new flavor collection.
Example of flavors collection: [{name: vanilla}, {name: chocolate}].
The database is MongoDB, The server side uses Node.JS + Express + Mongoose, The client side uses React.
Sometimes the program works properly, but sometimes after submitting the form several times, the old collection is deleted but the new collection is not saved without any error appearing, and sometimes an error appears that the id is duplicated key.
In some of the answers I found on stackoverflow I read that it should be defined
"{ ordered: false }". I tried, as shown in the attached code, but that didn't solve the problem either.
server side:
flavorsModel.js
import "dotenv/config.js";
import { Schema, model } from "mongoose";
const flavorsSchema = new Schema({
name: {
type: String,
require: true,
},
});
export default model("", flavorsSchema, process.env.MONGODB_COLLECTION_NAME);
flavorsController.js
import flavorsModel from "../models/flavorsModel.js";
export async function loadFlavors(_, res) {
const flavors = await flavorsModel.find().catch((err) => console.log(err));
res.send(flavors);
console.log("flavors loaded", flavors);
}
export async function deleteFlavors() {
await flavorsModel.deleteMany().catch((err) => console.log(err));
console.log("flavors deleted");
}
export async function saveFlavors(req, _) {
const flavors = await flavorsModel
.insertMany(req.body, { ordered: false })
.catch((err) => console.log(err));
console.log("flavors saved", flavors);
}
flavorsRoute.js
import { Router } from "express";
import { loadFlavors, deleteFlavors, saveFlavors} from "../controllers/flavorsController.js";
const router = Router();
router.get("/loadFlavors", loadFlavors);
router.delete("/deleteFlavors", deleteFlavors);
router.post("/saveFlavors", saveFlavors);
export default router;
server.js
import cors from "cors";
import "dotenv/config.js";
import express from "express";
import mongoose from "mongoose";
import flavorsRoute from "./routes/flavorsRoute.js";
const app = express();
const port = process.env.port || 5000;
mongoose
.connect(process.env.MONGODB_URL)
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));
app.use(cors());
app.use("/flavors", flavorsRoute);
app.listen(port, () => {
console.log(`Server on port http://localhost:${port}`);
});
client side:
import axios from "axios";
const baseUrl = "http://localhost:5000/flavors";
const loadFlavors = (setFlavors) => {
axios.get(`${baseUrl}/loadFlavors`).then(({ data }) => {
console.log("data", data);
setFlavors(data);
});
};
const saveFlavors = (flavors) => {
axios
.all([
axios.delete(`${baseUrl}/deleteFlavors`, {}),
axios.post(`${baseUrl}/saveFlavors`, flavors),
])
.catch((err) => console.log(err));
};
export { loadFlavors, saveFlavors };
A:
By using axios.all() you are running the deletion request and the save request in parallel. If you get lucky, the save will happen after the delete, and everything will be fine. If you get unlucky, the save will happen before or during the delete, and cause behavior like you describe.
To run them in order would be something like:
const saveFlavors = async (flavors) => {
await axios.delete(`${baseUrl}/deleteFlavors`, {}).catch((err) => console.log(err));
await axios.post(`${baseUrl}/saveFlavors`, flavors).catch((err) => console.log(err));
};
You will also need to update your backend to send responses from those routes, or the frontend will hang while waiting for a response that isn't coming.
| MongoDB: when deleting an old collection and inserting a new collection, sometimes the new collection is not saved | There is a form with input text fields, used to define a list of flavors. Submitting the form should delete the old flavor collection and replace it with the new flavor collection.
Example of flavors collection: [{name: vanilla}, {name: chocolate}].
The database is MongoDB, The server side uses Node.JS + Express + Mongoose, The client side uses React.
Sometimes the program works properly, but sometimes after submitting the form several times, the old collection is deleted but the new collection is not saved without any error appearing, and sometimes an error appears that the id is duplicated key.
In some of the answers I found on stackoverflow I read that it should be defined
"{ ordered: false }". I tried, as shown in the attached code, but that didn't solve the problem either.
server side:
flavorsModel.js
import "dotenv/config.js";
import { Schema, model } from "mongoose";
const flavorsSchema = new Schema({
name: {
type: String,
require: true,
},
});
export default model("", flavorsSchema, process.env.MONGODB_COLLECTION_NAME);
flavorsController.js
import flavorsModel from "../models/flavorsModel.js";
export async function loadFlavors(_, res) {
const flavors = await flavorsModel.find().catch((err) => console.log(err));
res.send(flavors);
console.log("flavors loaded", flavors);
}
export async function deleteFlavors() {
await flavorsModel.deleteMany().catch((err) => console.log(err));
console.log("flavors deleted");
}
export async function saveFlavors(req, _) {
const flavors = await flavorsModel
.insertMany(req.body, { ordered: false })
.catch((err) => console.log(err));
console.log("flavors saved", flavors);
}
flavorsRoute.js
import { Router } from "express";
import { loadFlavors, deleteFlavors, saveFlavors} from "../controllers/flavorsController.js";
const router = Router();
router.get("/loadFlavors", loadFlavors);
router.delete("/deleteFlavors", deleteFlavors);
router.post("/saveFlavors", saveFlavors);
export default router;
server.js
import cors from "cors";
import "dotenv/config.js";
import express from "express";
import mongoose from "mongoose";
import flavorsRoute from "./routes/flavorsRoute.js";
const app = express();
const port = process.env.port || 5000;
mongoose
.connect(process.env.MONGODB_URL)
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));
app.use(cors());
app.use("/flavors", flavorsRoute);
app.listen(port, () => {
console.log(`Server on port http://localhost:${port}`);
});
client side:
import axios from "axios";
const baseUrl = "http://localhost:5000/flavors";
const loadFlavors = (setFlavors) => {
axios.get(`${baseUrl}/loadFlavors`).then(({ data }) => {
console.log("data", data);
setFlavors(data);
});
};
const saveFlavors = (flavors) => {
axios
.all([
axios.delete(`${baseUrl}/deleteFlavors`, {}),
axios.post(`${baseUrl}/saveFlavors`, flavors),
])
.catch((err) => console.log(err));
};
export { loadFlavors, saveFlavors };
| [
"By using axios.all() you are running the deletion request and the save request in parallel. If you get lucky, the save will happen after the delete, and everything will be fine. If you get unlucky, the save will happen before or during the delete, and cause behavior like you describe.\nTo run them in order would be something like:\nconst saveFlavors = async (flavors) => {\n await axios.delete(`${baseUrl}/deleteFlavors`, {}).catch((err) => console.log(err));\n await axios.post(`${baseUrl}/saveFlavors`, flavors).catch((err) => console.log(err));\n};\n\nYou will also need to update your backend to send responses from those routes, or the frontend will hang while waiting for a response that isn't coming.\n"
] | [
1
] | [] | [] | [
"javascript",
"mongodb",
"mongoose",
"node.js"
] | stackoverflow_0074671911_javascript_mongodb_mongoose_node.js.txt |
Q:
Boost::multiprecision and cardinal_cubic_b_spline
I'm new using the boost::multiprecision library and tried to use it combination with boost::math::interpolators::cardinal_cubic_b_spline however I can't compile the program.
The example code is
#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>
#include <iostream>
#include <boost/multiprecision/gmp.hpp>
using boost::multiprecision::mpf_float_50;
int main() {
std::vector<mpf_float_50> v(10);
mpf_float_50 step(0.01);
for (size_t i = 0; i < v.size(); ++i) {
v.at(i) = sin(i*step);
}
mpf_float_50 leftPoint(0.0);
boost::math::interpolators::cardinal_cubic_b_spline<mpf_float_50> spline(v.begin(), v.end(), leftPoint, step);
mpf_float_50 x(3.1);
mpf_float_50 tmpVal = spline(x);
std::cout << tmpVal << std::endl;
return 0;
}
When change the type of variables to boost::multiprecision::cpp_bin_float_50 the program is working. Also, boost::multiprecision::mpf_float_50 is working in all other examples I have tried.
The error I get is:
/home/..../main.cpp:19:31: required from here
/usr/include/boost/math/interpolators/detail/cardinal_cubic_b_spline_detail.hpp:50:10: error: conversion from ‘expression<boost::multiprecision::detail::function,boost::multiprecision::detail::abs_funct<boost::multiprecision::backends::gmp_float<50> >,boost::multiprecision::detail::expression<boost::multiprecision::detail::subtract_immediates, boost::multiprecision::number<boost::multiprecision::backends::gmp_float<50> >, long unsigned int, void, void>,[...],[...]>’ to non-scalar type ‘expression<boost::multiprecision::detail::subtract_immediates,boost::multiprecision::number<boost::multiprecision::backends::gmp_float<50> >,long unsigned int,[...],[...]>’ requested
The same error appeared for cpp_dec_float_50, mpfr_float_50 etc. I'm not sure what I'm doing wrong.
A:
The selected type. is the GMP backend. To give it the usual operators, it is wrapped in the frontend template number<>:
Live On Coliru
using F = boost::multiprecision::mpf_float_50;
int main() {
F a = 3, b = 2;
F c = b - a;
std::cout << "a:" << a << ", b:" << b << ", c:" << c << std::endl;
b = abs(b - a);
std::cout << "a:" << a << ", b:" << b << ", c:" << c << std::endl;
}
Prints
a:3, b:2, c:-1
a:3, b:1, c:-1
However, the number<> enables expression templates by default. That means, typeof(F{} - F{}) is not necessarily F, but something like:
namespace mp = boost::multiprecision;
using F = mp::mpf_float_50;
int main() {
F a = 3, b = 2;
mp::detail::expression<mp::detail::subtract_immediates, F, F> //
c = b - a;
Template expressions can greatly optimize some code, e.g. by simplifying evaluation of complicated expressions.
However, some generic code doesn't deal well with the expression templates. Therefore you can turn them off:
namespace mp = boost::multiprecision;
using F = mp::number<mp::gmp_float<50>, mp::et_off>;
Now it all compiles, and probably works as it should.
Live On Coliru
#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>
#include <iostream>
#include <boost/multiprecision/gmp.hpp>
namespace mp = boost::multiprecision;
using F = mp::number<mp::gmp_float<50>, mp::et_off>;
int main() {
std::vector<F> v(10);
F step(0.01);
for (size_t i = 0; i < v.size(); ++i) {
v.at(i) = sin(i * step);
}
F leftPoint(0.0);
boost::math::interpolators::cardinal_cubic_b_spline<F> spline(v.begin(), v.end(), leftPoint, step);
F x(3.1);
F tmpVal = spline(x);
std::cout << tmpVal << std::endl;
}
Now printing:
0.0449663
| Boost::multiprecision and cardinal_cubic_b_spline | I'm new using the boost::multiprecision library and tried to use it combination with boost::math::interpolators::cardinal_cubic_b_spline however I can't compile the program.
The example code is
#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>
#include <iostream>
#include <boost/multiprecision/gmp.hpp>
using boost::multiprecision::mpf_float_50;
int main() {
std::vector<mpf_float_50> v(10);
mpf_float_50 step(0.01);
for (size_t i = 0; i < v.size(); ++i) {
v.at(i) = sin(i*step);
}
mpf_float_50 leftPoint(0.0);
boost::math::interpolators::cardinal_cubic_b_spline<mpf_float_50> spline(v.begin(), v.end(), leftPoint, step);
mpf_float_50 x(3.1);
mpf_float_50 tmpVal = spline(x);
std::cout << tmpVal << std::endl;
return 0;
}
When change the type of variables to boost::multiprecision::cpp_bin_float_50 the program is working. Also, boost::multiprecision::mpf_float_50 is working in all other examples I have tried.
The error I get is:
/home/..../main.cpp:19:31: required from here
/usr/include/boost/math/interpolators/detail/cardinal_cubic_b_spline_detail.hpp:50:10: error: conversion from ‘expression<boost::multiprecision::detail::function,boost::multiprecision::detail::abs_funct<boost::multiprecision::backends::gmp_float<50> >,boost::multiprecision::detail::expression<boost::multiprecision::detail::subtract_immediates, boost::multiprecision::number<boost::multiprecision::backends::gmp_float<50> >, long unsigned int, void, void>,[...],[...]>’ to non-scalar type ‘expression<boost::multiprecision::detail::subtract_immediates,boost::multiprecision::number<boost::multiprecision::backends::gmp_float<50> >,long unsigned int,[...],[...]>’ requested
The same error appeared for cpp_dec_float_50, mpfr_float_50 etc. I'm not sure what I'm doing wrong.
| [
"The selected type. is the GMP backend. To give it the usual operators, it is wrapped in the frontend template number<>:\nLive On Coliru\nusing F = boost::multiprecision::mpf_float_50;\n\nint main() {\n F a = 3, b = 2;\n F c = b - a;\n std::cout << \"a:\" << a << \", b:\" << b << \", c:\" << c << std::endl;\n\n b = abs(b - a);\n std::cout << \"a:\" << a << \", b:\" << b << \", c:\" << c << std::endl;\n}\n\nPrints\na:3, b:2, c:-1\na:3, b:1, c:-1\n\nHowever, the number<> enables expression templates by default. That means, typeof(F{} - F{}) is not necessarily F, but something like:\nnamespace mp = boost::multiprecision;\nusing F = mp::mpf_float_50;\n\nint main() {\n F a = 3, b = 2;\n\n mp::detail::expression<mp::detail::subtract_immediates, F, F> //\n c = b - a;\n\nTemplate expressions can greatly optimize some code, e.g. by simplifying evaluation of complicated expressions.\nHowever, some generic code doesn't deal well with the expression templates. Therefore you can turn them off:\nnamespace mp = boost::multiprecision;\nusing F = mp::number<mp::gmp_float<50>, mp::et_off>;\n\nNow it all compiles, and probably works as it should.\nLive On Coliru\n#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>\n#include <iostream>\n#include <boost/multiprecision/gmp.hpp>\n\nnamespace mp = boost::multiprecision;\nusing F = mp::number<mp::gmp_float<50>, mp::et_off>;\n\nint main() {\n std::vector<F> v(10);\n F step(0.01);\n\n for (size_t i = 0; i < v.size(); ++i) {\n v.at(i) = sin(i * step);\n }\n\n F leftPoint(0.0);\n boost::math::interpolators::cardinal_cubic_b_spline<F> spline(v.begin(), v.end(), leftPoint, step);\n\n F x(3.1);\n F tmpVal = spline(x);\n std::cout << tmpVal << std::endl;\n}\n\nNow printing:\n0.0449663\n\n"
] | [
2
] | [
"It looks like the cardinal_cubic_b_spline class expects the type of the elements in the input vector to have the operator- and abs functions defined. The mpf_float_50 type from the boost::multiprecision::gmp library does not have these functions defined. You can fix this by using the cpp_bin_float_50 type, which does have these functions defined. Alternatively, you can define the operator- and abs functions for the mpf_float_50 type yourself.\n"
] | [
-1
] | [
"boost",
"boost_multiprecision",
"c++"
] | stackoverflow_0074671304_boost_boost_multiprecision_c++.txt |
Q:
Editable CSS by editing text on textarea?
How can I make a textarea which has the stylesheet of the web page inside it?
I want to make a web page which a user can customize its <style> settings by editing text inside a textarea.
Here's what I have done so far; inside the <textarea> of this code snippet is the editable text which I intend to make it function as the web page's stylesheet, but I'm not sure how to make it work.
I did many web search looking for solutions, but could not find useful help regarding this particular function. Any help will be appreciated.
function myFunction() {
document.getElementsByTagName("style")[0].innerHTML = "document.getElementById('input').value;";
}
<p>sample text</p>
<textarea id="input" oninput="myFunction()" rows="5">p {
font-family: monospace;
font-size: 15px;
}
</textarea>
A:
You're very close, but your code has 2 problems.
document.getElementsByTagName returns an array, so you need to select the first element of the array using [0].
You are not actually getting the input element, you're just using a string of the code you want to run (i.e. you want to run the code document.getElementById('input').value but you've put quotes around it, which turns it into a string).
This updated version should work:
function myFunction() {
document.getElementsByTagName("style")[0].innerHTML = document.getElementById('input').value;
}
<p>sample text</p>
<textarea id="input" oninput="myFunction()" rows="5">html {
font-family: monospace;
font-size: 15px;
}
</textarea>
A:
Another possibility is to use inline styles with the display style set to "block" and the contenteditable attribute set to "true".
Example:
<div>
<style style="
display: block;
padding: 0 0.5rem;
border: 1px solid black;
border-radius: 4px;
white-space: pre;
font-family: 'Courier New', Courier, monospace;
font-size: small;
"
contenteditable="true">
#myDiv {
height: 100%;
--l1: repeating-linear-gradient(-60deg,
transparent 0,
transparent 5px,
rgba(210, 180, 140, 0.5) 0,
rgba(210, 180, 140, 0.5) 35px);
--l0: repeating-linear-gradient(60deg,
transparent 0,
transparent 5px,
rgba(210, 180, 140, 0.5) 0,
rgba(210, 180, 140, 0.5) 35px);
background: var(--l1), var(--l0);
}
</style>
<div id="myDiv"></div>
</div>
This will directly allow to edit and alter the contents of the style definitions by the user, without the direct possibility to save the modifications.
| Editable CSS by editing text on textarea? | How can I make a textarea which has the stylesheet of the web page inside it?
I want to make a web page which a user can customize its <style> settings by editing text inside a textarea.
Here's what I have done so far; inside the <textarea> of this code snippet is the editable text which I intend to make it function as the web page's stylesheet, but I'm not sure how to make it work.
I did many web search looking for solutions, but could not find useful help regarding this particular function. Any help will be appreciated.
function myFunction() {
document.getElementsByTagName("style")[0].innerHTML = "document.getElementById('input').value;";
}
<p>sample text</p>
<textarea id="input" oninput="myFunction()" rows="5">p {
font-family: monospace;
font-size: 15px;
}
</textarea>
| [
"You're very close, but your code has 2 problems.\n\ndocument.getElementsByTagName returns an array, so you need to select the first element of the array using [0].\nYou are not actually getting the input element, you're just using a string of the code you want to run (i.e. you want to run the code document.getElementById('input').value but you've put quotes around it, which turns it into a string).\n\nThis updated version should work:\n\n\nfunction myFunction() {\n document.getElementsByTagName(\"style\")[0].innerHTML = document.getElementById('input').value;\n}\n<p>sample text</p>\n<textarea id=\"input\" oninput=\"myFunction()\" rows=\"5\">html {\nfont-family: monospace;\nfont-size: 15px;\n}\n</textarea>\n\n\n\n",
"Another possibility is to use inline styles with the display style set to \"block\" and the contenteditable attribute set to \"true\".\nExample:\n<div>\n <style style=\"\n display: block; \n padding: 0 0.5rem; \n border: 1px solid black; \n border-radius: 4px;\n white-space: pre;\n font-family: 'Courier New', Courier, monospace;\n font-size: small;\n \" \n contenteditable=\"true\">\n #myDiv {\n height: 100%;\n --l1: repeating-linear-gradient(-60deg, \n transparent 0, \n transparent 5px, \n rgba(210, 180, 140, 0.5) 0, \n rgba(210, 180, 140, 0.5) 35px);\n --l0: repeating-linear-gradient(60deg,\n transparent 0, \n transparent 5px,\n rgba(210, 180, 140, 0.5) 0, \n rgba(210, 180, 140, 0.5) 35px);\n background: var(--l1), var(--l0);\n }\n </style>\n <div id=\"myDiv\"></div>\n</div>\n\nThis will directly allow to edit and alter the contents of the style definitions by the user, without the direct possibility to save the modifications.\n"
] | [
3,
0
] | [] | [] | [
"css",
"html",
"javascript"
] | stackoverflow_0065071714_css_html_javascript.txt |
Q:
Accessing Environment's value outside of being installed on a View. What does this mean?
I have a view called SurveyView, and it calls a function in MainSurvey class named saveToCoreData. The saveToCoreData function is supposed to save the details to coredata. But everytime I run the app, I get the following warning message in purple color and the data isn't saved at all. The below warning message is shown next to where moc is mentioned in the code. I did try looking around but didn't find any solutions for it.
Accessing Environment<NSManagedObjectContext>'s value outside of being installed on a View. This will always read the default value and will not update.
This is what the code for view looks like.
import SwiftUI
struct SurveyView: View {
@Environment(\.managedObjectContext) var moc
@ObservedObject var mainSurvey: MainSurvey
@State private var survey: String = "4"
@State private var showAlert: Bool = false
@State private var displayNewView: Bool = false
var body: some View {
VStack {
NavigationLink(destination: SampleView(), isActive: self.$displayNewView) { EmptyView() } //To display ContentView() after the user selects "Done" in alert
Text("How was your experience?")
RatingView(rating: $survey)
Button(action: {
self.mainSurvey.saveToCoreData(survey: survey); showAlert = true
}) {
Text("Submit Response")
}
.alert(isPresented: $showAlert){
Alert(title: Text("Thanks!"), message: Text("Thanks again!"), dismissButton: .default(Text("Done"), action: {
self.displayNewView = true
})
)
}
}
.navigationBarBackButtonHidden(true)
}
}
struct RatingView: View {
@Binding var rating: String
var body: some View {
VStack {
Form {
TextField("Rating", text: $rating)
}
}
}
}
This is the code for MainSurvey class
import SwiftUI
import Foundation
class MainSurvey: NSObject, ObservableObject {
@Environment(\.managedObjectContext) var moc
@Published var survey: String!
override init() {
super.init()
}
func saveToCoreData(survey: String) {
let newData = MainStore(context: moc)
newData.uuid = UUID()
newData.rating = self.survey
do {
try moc.save()
print("Sucessfully saved sleeep data")
} catch {
print("Unexpected error saving data: \(error).")
}
}
}
What is it trying to say and how do I fix this?
A:
If SurveyView is the first time you are creating the MainSurvey model, it should be called with @StateObject so that Swift knows what view to keep the ViewModel alive.
Furthermore, the @Environment wrapper is only used for views. Unless you are going to add more logic to the ViewModel, I would move the function and the survey variable to the view instead.
| Accessing Environment's value outside of being installed on a View. What does this mean? | I have a view called SurveyView, and it calls a function in MainSurvey class named saveToCoreData. The saveToCoreData function is supposed to save the details to coredata. But everytime I run the app, I get the following warning message in purple color and the data isn't saved at all. The below warning message is shown next to where moc is mentioned in the code. I did try looking around but didn't find any solutions for it.
Accessing Environment<NSManagedObjectContext>'s value outside of being installed on a View. This will always read the default value and will not update.
This is what the code for view looks like.
import SwiftUI
struct SurveyView: View {
@Environment(\.managedObjectContext) var moc
@ObservedObject var mainSurvey: MainSurvey
@State private var survey: String = "4"
@State private var showAlert: Bool = false
@State private var displayNewView: Bool = false
var body: some View {
VStack {
NavigationLink(destination: SampleView(), isActive: self.$displayNewView) { EmptyView() } //To display ContentView() after the user selects "Done" in alert
Text("How was your experience?")
RatingView(rating: $survey)
Button(action: {
self.mainSurvey.saveToCoreData(survey: survey); showAlert = true
}) {
Text("Submit Response")
}
.alert(isPresented: $showAlert){
Alert(title: Text("Thanks!"), message: Text("Thanks again!"), dismissButton: .default(Text("Done"), action: {
self.displayNewView = true
})
)
}
}
.navigationBarBackButtonHidden(true)
}
}
struct RatingView: View {
@Binding var rating: String
var body: some View {
VStack {
Form {
TextField("Rating", text: $rating)
}
}
}
}
This is the code for MainSurvey class
import SwiftUI
import Foundation
class MainSurvey: NSObject, ObservableObject {
@Environment(\.managedObjectContext) var moc
@Published var survey: String!
override init() {
super.init()
}
func saveToCoreData(survey: String) {
let newData = MainStore(context: moc)
newData.uuid = UUID()
newData.rating = self.survey
do {
try moc.save()
print("Sucessfully saved sleeep data")
} catch {
print("Unexpected error saving data: \(error).")
}
}
}
What is it trying to say and how do I fix this?
| [
"If SurveyView is the first time you are creating the MainSurvey model, it should be called with @StateObject so that Swift knows what view to keep the ViewModel alive.\nFurthermore, the @Environment wrapper is only used for views. Unless you are going to add more logic to the ViewModel, I would move the function and the survey variable to the view instead.\n"
] | [
0
] | [] | [] | [
"core_data",
"swift",
"swiftui",
"view"
] | stackoverflow_0074671908_core_data_swift_swiftui_view.txt |
Q:
using File().byLine() with fold()
I am trying to use the fold operation on a range returned by byLine(). I want the lambda which is passed to fold to be a multi-line function. I have searched google and read the documentation, but cannot find a description as to what the signature of the function should be. I surmize that one of the pair is the accumulated sum and one is the current element. This is what I have but it will not build
auto sum = File( fileName, "r" )
.byLine
.fold!( (a, b)
{
auto len = b.length;
return a + len;
});
The error I get back from dmd is:
main.d(22): Error: no property `fold` for `(File(null, null)).this(fileName, "r").byLine(Flag.no, '\n')` of type `std.stdio.File.ByLineImpl!(char, char)`
So my question is two fold:
Is my use of fold in this case valid?
How do I pass a curley brace lambda to fold?
I have tried searching google and reading the dlang documentation for fold. All documentation uses the shortcut lambda syntax (a, b) => a + b.
A:
import std.algorithm.iteration : fold;
// Import the byLine function from the File module
import std.stdio.File : byLine;
void main() {
string fileName = "some/file/name.txt";
auto sum = File(fileName, "r")
.byLine
.fold!((a, b) => {
// You can define the lambda function using the `{}` syntax
auto len = b.length;
return a + len;
})(0); // Initialize the fold with a value of 0
}
The fold function takes a lambda function as its first argument. This lambda function should have two arguments, the first is the accumulated value (initialized with the value you provide to fold as the second argument), and the second is the current element of the range. In your case, the accumulated value is of type int and the current element is of type string, so the signature of the lambda should be (int a, string b) => return_type.
You can use the {} syntax to define the body of the lambda function if it spans multiple lines.
In your code, you are trying to use the fold function directly on the byLine range, but byLine does not have a fold member function. You need to import the fold function from the std.algorithm.iteration module and use it on the range returned by byLine.
A:
So the way fold works is that it accepts a list of function aliases on how to fold the next element in. if you don't provide it with a starting value, it uses the first element as the starting value. Quoting the documentation (emphasis mine):
The call fold!(fun)(range, seed) first assigns seed to an internal
variable result, also called the accumulator. Then, for each element
x in range, result = fun(result, x) gets evaluated. Finally, result
is returned. The one-argument version fold!(fun)(range) works
similarly, but it uses the first element of the range as the seed
(the range must be non-empty).
The reason why your original code didn't work is because you can't add an integer to a string (the seed was the first line of the file).
The reason why your latest version works (although only on 32-bit machines, since you can't reassign a size_t to an int on 64-bit machines) is because you gave it a starting value of 0 to seed the fold. So that is the correct mechanism to use for your use case.
The documentation is a bit odd, because the function is actually not an eponymous template, so it has two parts to the documentation -- one for the template, and one for the fold function. The fold function doc lists the runtime parameters that are accepted by fold, in this case, the input range and the seed. The documentation link for it is here: https://dlang.org/phobos/std_algorithm_iteration.html#.fold.fold
A:
I was able to tweak the answer provied by Akshay. The following compiled and ran:
module example;
import std.stdio;
import std.algorithm.iteration : fold;
void main() {
string fileName = "test1.txt";
auto sum = File(fileName, "r")
.byLine
.fold!( (a, b) {
// You can define the lambda function using the `{}` syntax
auto len = b.length;
return a + len;
})(0); // Initialize the fold with a value of 0
}
| using File().byLine() with fold() | I am trying to use the fold operation on a range returned by byLine(). I want the lambda which is passed to fold to be a multi-line function. I have searched google and read the documentation, but cannot find a description as to what the signature of the function should be. I surmize that one of the pair is the accumulated sum and one is the current element. This is what I have but it will not build
auto sum = File( fileName, "r" )
.byLine
.fold!( (a, b)
{
auto len = b.length;
return a + len;
});
The error I get back from dmd is:
main.d(22): Error: no property `fold` for `(File(null, null)).this(fileName, "r").byLine(Flag.no, '\n')` of type `std.stdio.File.ByLineImpl!(char, char)`
So my question is two fold:
Is my use of fold in this case valid?
How do I pass a curley brace lambda to fold?
I have tried searching google and reading the dlang documentation for fold. All documentation uses the shortcut lambda syntax (a, b) => a + b.
| [
"import std.algorithm.iteration : fold;\n\n// Import the byLine function from the File module\nimport std.stdio.File : byLine;\n\nvoid main() {\n string fileName = \"some/file/name.txt\";\n auto sum = File(fileName, \"r\")\n .byLine\n .fold!((a, b) => {\n // You can define the lambda function using the `{}` syntax\n auto len = b.length;\n return a + len;\n })(0); // Initialize the fold with a value of 0\n}\n\nThe fold function takes a lambda function as its first argument. This lambda function should have two arguments, the first is the accumulated value (initialized with the value you provide to fold as the second argument), and the second is the current element of the range. In your case, the accumulated value is of type int and the current element is of type string, so the signature of the lambda should be (int a, string b) => return_type.\nYou can use the {} syntax to define the body of the lambda function if it spans multiple lines.\nIn your code, you are trying to use the fold function directly on the byLine range, but byLine does not have a fold member function. You need to import the fold function from the std.algorithm.iteration module and use it on the range returned by byLine.\n",
"So the way fold works is that it accepts a list of function aliases on how to fold the next element in. if you don't provide it with a starting value, it uses the first element as the starting value. Quoting the documentation (emphasis mine):\n\nThe call fold!(fun)(range, seed) first assigns seed to an internal\nvariable result, also called the accumulator. Then, for each element\nx in range, result = fun(result, x) gets evaluated. Finally, result\nis returned. The one-argument version fold!(fun)(range) works\nsimilarly, but it uses the first element of the range as the seed\n(the range must be non-empty).\n\nThe reason why your original code didn't work is because you can't add an integer to a string (the seed was the first line of the file).\nThe reason why your latest version works (although only on 32-bit machines, since you can't reassign a size_t to an int on 64-bit machines) is because you gave it a starting value of 0 to seed the fold. So that is the correct mechanism to use for your use case.\nThe documentation is a bit odd, because the function is actually not an eponymous template, so it has two parts to the documentation -- one for the template, and one for the fold function. The fold function doc lists the runtime parameters that are accepted by fold, in this case, the input range and the seed. The documentation link for it is here: https://dlang.org/phobos/std_algorithm_iteration.html#.fold.fold\n",
"I was able to tweak the answer provied by Akshay. The following compiled and ran:\nmodule example;\n\nimport std.stdio;\nimport std.algorithm.iteration : fold;\n\nvoid main() {\n string fileName = \"test1.txt\";\n auto sum = File(fileName, \"r\")\n .byLine\n .fold!( (a, b) {\n // You can define the lambda function using the `{}` syntax\n auto len = b.length;\n return a + len;\n })(0); // Initialize the fold with a value of 0\n}\n\n\n"
] | [
2,
1,
0
] | [] | [] | [
"d"
] | stackoverflow_0074668853_d.txt |
Q:
Duplicate Output with Entity Framework and LINQ and Foreach Loop
Overview
I have a website I am writing for keeping personal bookmarks. And they are kept in categories. I can print out the links just fine when doing it one way. But when I throw a linq query in the mix, somehow I get duplicates of each link.
Scenarios
First way without duplicates
Now I removed the html code from the loops because it is unimportant.
var categoryContext = new LinkDatabaseEntities();
var linkContext = new LinkDatabaseEntities();
foreach (Category category in categoryContext.Categories)
{
foreach (Link link in linkContext.Links)
{
if (link.CatID.Equals(category.ID))
{
Print Out HTML Code
}
}
}
This code works perfectly. I don't get any duplicates.
Output:
Category 1
Link 1
Link 2
Category 2
Link 1
Link 2
Code that outputs duplicates
Now, the information in the database isn't going to be that big, so I really don't need this for efficiency, I just want to understand what is happening.
var categoryContext = new LinkDatabaseEntities();
var linkContext = new LinkDatabaseEntities();
foreach (Category category in categoryContext.Categories)
{
var links = from link in linkContext.Links
where link.catID == category.ID
select link;
foreach (Link link in links)
{
Print Out HTML Code
}
}
This way has duplicates of every link. I don't understand why this is happening.
Output:
Category 1
Link 1
Link 1
Link 2
Link 2
Category 2
Link 1
Link 1
Link 2
Link 2
If someone could explain why this is happening, I would greatly appreciate it. Thanks
A:
OP:
This way has duplicates of every link. I don't understand why this is happening.
It's happening because you did not use a join, if you don't it mulitplies out the items in A by the count of items in B. A similar issue and solution can be found here.
Navigation properties
This assumes you have correctly defined relationships and foreign keys in your database schema and have corresponding information in your EF code/EDMX.
Considering you are using an ORM, an easier way that doesn't lead to duplicates is to take advantage of the EF Navigation Properties.
Change the following:
var categoryContext = new LinkDatabaseEntities();
var linkContext = new LinkDatabaseEntities();
foreach (Category category in categoryContext.Categories)
{
var links = from link in linkContext.Links
where link.catID == category.ID
select link;
foreach (Link link in links)
{
Print Out HTML Code
}
}
...to:
var categoryContext = new LinkDatabaseEntities();
var linkContext = new LinkDatabaseEntities();
foreach (var category in categoryContext.Categories)
{
foreach (var link in category.Links) // <---- notice the use of the nav property
{
// the above category.Links contains only the links applicable
// for a given category AND NOT all the links found in say a LINKS table
(Print Out HTML Code)
}
}
The above works by taking advantage that EF already knows which Links belong to a given Category because the navigation properties reflect the relationships and foreign keys defined in the database schema.
See also
Relationships, navigation properties, and foreign keys, Learn, Microsoft, retrieved 2022-12-4
| Duplicate Output with Entity Framework and LINQ and Foreach Loop | Overview
I have a website I am writing for keeping personal bookmarks. And they are kept in categories. I can print out the links just fine when doing it one way. But when I throw a linq query in the mix, somehow I get duplicates of each link.
Scenarios
First way without duplicates
Now I removed the html code from the loops because it is unimportant.
var categoryContext = new LinkDatabaseEntities();
var linkContext = new LinkDatabaseEntities();
foreach (Category category in categoryContext.Categories)
{
foreach (Link link in linkContext.Links)
{
if (link.CatID.Equals(category.ID))
{
Print Out HTML Code
}
}
}
This code works perfectly. I don't get any duplicates.
Output:
Category 1
Link 1
Link 2
Category 2
Link 1
Link 2
Code that outputs duplicates
Now, the information in the database isn't going to be that big, so I really don't need this for efficiency, I just want to understand what is happening.
var categoryContext = new LinkDatabaseEntities();
var linkContext = new LinkDatabaseEntities();
foreach (Category category in categoryContext.Categories)
{
var links = from link in linkContext.Links
where link.catID == category.ID
select link;
foreach (Link link in links)
{
Print Out HTML Code
}
}
This way has duplicates of every link. I don't understand why this is happening.
Output:
Category 1
Link 1
Link 1
Link 2
Link 2
Category 2
Link 1
Link 1
Link 2
Link 2
If someone could explain why this is happening, I would greatly appreciate it. Thanks
| [
"OP:\n\nThis way has duplicates of every link. I don't understand why this is happening.\n\nIt's happening because you did not use a join, if you don't it mulitplies out the items in A by the count of items in B. A similar issue and solution can be found here.\nNavigation properties\n\nThis assumes you have correctly defined relationships and foreign keys in your database schema and have corresponding information in your EF code/EDMX.\n\nConsidering you are using an ORM, an easier way that doesn't lead to duplicates is to take advantage of the EF Navigation Properties.\nChange the following:\nvar categoryContext = new LinkDatabaseEntities();\nvar linkContext = new LinkDatabaseEntities();\nforeach (Category category in categoryContext.Categories)\n{\n var links = from link in linkContext.Links\n where link.catID == category.ID\n select link;\n\n foreach (Link link in links)\n {\n Print Out HTML Code\n }\n}\n\n...to:\nvar categoryContext = new LinkDatabaseEntities();\nvar linkContext = new LinkDatabaseEntities();\nforeach (var category in categoryContext.Categories)\n{\n foreach (var link in category.Links) // <---- notice the use of the nav property\n {\n // the above category.Links contains only the links applicable\n // for a given category AND NOT all the links found in say a LINKS table\n\n (Print Out HTML Code)\n }\n}\n\nThe above works by taking advantage that EF already knows which Links belong to a given Category because the navigation properties reflect the relationships and foreign keys defined in the database schema.\nSee also\n\nRelationships, navigation properties, and foreign keys, Learn, Microsoft, retrieved 2022-12-4\n\n"
] | [
1
] | [] | [] | [
"c#",
"entity_framework",
"linq"
] | stackoverflow_0074671952_c#_entity_framework_linq.txt |
Q:
Jest test fail: "● default root route"
I'm trying to write Jest tests for a Fastify project. But I'm stuck with the example code failing with an ambiguous error: "● default root route".
// root.test.ts
import { build } from '../helper'
const app = build()
test('default root route', async () => {
const res = await app.inject({
url: '/'
})
expect(res.json()).toEqual({ root: true })
})
// helper.ts
import Fastify from "fastify"
import fp from "fastify-plugin"
import App from "../src/app"
export function build() {
const app = Fastify()
beforeAll(async () => {
void app.register(fp(App))
await app.ready()
})
afterAll(() => app.close())
return app
}
// console error:
FAIL test/routes/root.test.ts (8.547 s)
● default root route
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.
What am I doing wrong?
A:
After running --detectOpenHandles, Jest reported that open ioredis connections were timing out.
I hooked up ioredis instances to Fastify lifecycle with fastify-redis and the test passed.
| Jest test fail: "● default root route" | I'm trying to write Jest tests for a Fastify project. But I'm stuck with the example code failing with an ambiguous error: "● default root route".
// root.test.ts
import { build } from '../helper'
const app = build()
test('default root route', async () => {
const res = await app.inject({
url: '/'
})
expect(res.json()).toEqual({ root: true })
})
// helper.ts
import Fastify from "fastify"
import fp from "fastify-plugin"
import App from "../src/app"
export function build() {
const app = Fastify()
beforeAll(async () => {
void app.register(fp(App))
await app.ready()
})
afterAll(() => app.close())
return app
}
// console error:
FAIL test/routes/root.test.ts (8.547 s)
● default root route
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.
What am I doing wrong?
| [
"After running --detectOpenHandles, Jest reported that open ioredis connections were timing out.\nI hooked up ioredis instances to Fastify lifecycle with fastify-redis and the test passed.\n"
] | [
0
] | [] | [] | [
"fastify",
"jestjs",
"node.js"
] | stackoverflow_0074661667_fastify_jestjs_node.js.txt |
Q:
How to split a row into 2 rows by setting a delimiter?
How can I split this line: Basis of the Consolidated <> Financial Statements by setting <> as a delimiter and create a new row which should not affect other columns?
The data looks like this.
I need to do this in Python code and I tried this but its not working:
for i in range(len(df5)):
df5['text'].iloc[i]=str(df5['text'].iloc[i])
if((math.isnan(df5['note_number'].iloc[i]==False)):
a=str(df5['text'].iloc[i])
a=a.strip()
u=a.split('<>')
if j<=(len(df5)):
j=i+1
df5['text'].iloc[i]=u[0]
df5['text'].iloc[i]=u[1]
A:
To split a row into two rows by a delimiter such as "<>" in Python, you can use the split() method of the str class. The split() method splits a string into a list of substrings based on the specified delimiter and returns the resulting list.
# Define the row
row = "Basis of the Consolidated<>Financial Statements"
# Split the row into two rows by the "<>" delimiter
rows = row.split("<>")
# Print the resulting list
print(rows) # Output: ['Basis of the Consolidated', 'Financial Statements']
You can then use the rows list to access the two rows separately, for example to add a row or to process them further in your code.
| How to split a row into 2 rows by setting a delimiter? | How can I split this line: Basis of the Consolidated <> Financial Statements by setting <> as a delimiter and create a new row which should not affect other columns?
The data looks like this.
I need to do this in Python code and I tried this but its not working:
for i in range(len(df5)):
df5['text'].iloc[i]=str(df5['text'].iloc[i])
if((math.isnan(df5['note_number'].iloc[i]==False)):
a=str(df5['text'].iloc[i])
a=a.strip()
u=a.split('<>')
if j<=(len(df5)):
j=i+1
df5['text'].iloc[i]=u[0]
df5['text'].iloc[i]=u[1]
| [
"To split a row into two rows by a delimiter such as \"<>\" in Python, you can use the split() method of the str class. The split() method splits a string into a list of substrings based on the specified delimiter and returns the resulting list.\n# Define the row\nrow = \"Basis of the Consolidated<>Financial Statements\"\n\n# Split the row into two rows by the \"<>\" delimiter\nrows = row.split(\"<>\")\n\n# Print the resulting list\nprint(rows) # Output: ['Basis of the Consolidated', 'Financial Statements']\n\nYou can then use the rows list to access the two rows separately, for example to add a row or to process them further in your code.\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074669736_dataframe_pandas_python.txt |
Q:
What can be the reasons of connection refused errors?
I'm trying to write a server program in C,
using another client, I get this error when I try to connect through port 2080 for example.
connection refused
What can be the reasons of this error?
A:
There could be many reasons, but the most common are:
The port is not open on the destination machine.
The port is open on the destination machine, but its backlog of pending connections is full.
A firewall between the client and server is blocking access (also check local firewalls).
After checking for firewalls and that the port is open, use telnet to connect to the ip/port to test connectivity. This removes any potential issues from your application.
A:
The error means the OS of the listening socket recognized the inbound connection request but chose to intentionally reject it.
Assuming an intermediate firewall is not getting in the way, there are only two reasons (that I know of) for the OS to reject an inbound connection request. One reason has already been mentioned several times - the listening port being connected to is not open.
There is another reason that has not been mentioned yet - the listening port is actually open and actively being used, but its backlog of queued inbound connection requests has reached its maximum so there is no room available for the inbound connection request to be queued at that moment. The server code has not called accept() enough times yet to finish clearing out available slots for new queue items.
Wait a moment or so and try the connection again. Unfortunately, there is no way to differentiate between "the port is not open at all" and "the port is open but too busy right now". They both use the same generic error code.
A:
If you try to open a TCP connection to another host and see the error "Connection refused," it means that
You sent a TCP SYN packet to the other host.
Then you received a TCP RST packet in reply.
RST is a bit on the TCP packet which indicates that the connection should be reset. Usually it means that the other host has received your connection attempt and is actively refusing your TCP connection, but sometimes an intervening firewall may block your TCP SYN packet and send a TCP RST back to you.
See https://www.rfc-editor.org/rfc/rfc793 page 69:
SYN-RECEIVED STATE
If the RST bit is set
If this connection was initiated with a passive OPEN (i.e., came
from the LISTEN state), then return this connection to LISTEN state
and return. The user need not be informed. If this connection was
initiated with an active OPEN (i.e., came from SYN-SENT state) then
the connection was refused, signal the user "connection refused". In
either case, all segments on the retransmission queue should be
removed. And in the active OPEN case, enter the CLOSED state and
delete the TCB, and return.
A:
Connection refused means that the port you are trying to connect to is not actually open.
So either you are connecting to the wrong IP address, or to the wrong port, or the server is listening on the wrong port, or is not actually running.
A common mistake is not specifying the port number when binding or connecting in network byte order...
A:
Check at the server side that it is listening at the port 2080.
First try to confirm it on the server machine by issuing telnet to that port:
telnet localhost 2080
If it is listening, it is able to respond.
A:
1.Check your server status.
2.Check the port status.
For example 3306 netstat -nupl|grep 3306.
3.Check your firewalls.
For example add 3306
vim /etc/sysconfig/iptables
# add
-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT
A:
Although it does not seem to be the case for your situation, sometimes a connection refused error can also indicate that there is an ip address conflict on your network. You can search for possible ip conflicts by running:
arp-scan -I eth0 -l | grep <ipaddress>
and
arping <ipaddress>
This AskUbuntu question has some more information also.
A:
I get the same problem with my work computer.
The problem is that when you enter localhost it goes to proxy's address not local address you should bypass it follow this steps
Chrome => Settings => Change proxy settings => LAN Settings => check Bypass proxy server for local addresses.
A:
In Ubuntu, Try
sudo ufw allow <port_number>
to allow firewall access to both of your server and db.
A:
From the standpoint of a Checkpoint firewall, you will see a message from the firewall if you actually choose Reject as an Action thereby exposing to a propective attacker the presence of a firewall in front of the server. The firewall will silently drop all connections that doesn't match the policy. Connection refused almost always comes from the server
A:
In my case, it happens when the site is blocked in my country and I don't use VPN.
For example when I try to access vimeo.com from Indonesia which is blocked.
A:
Check if your application is bind with the port where you are sending the request
Check if the application is accepting connections from the host you are sending the request, maybe you forgot to allow all the incoming connections 0.0.0.0 and by default, it's only allowing connections from 127.0.0.1
| What can be the reasons of connection refused errors? | I'm trying to write a server program in C,
using another client, I get this error when I try to connect through port 2080 for example.
connection refused
What can be the reasons of this error?
| [
"There could be many reasons, but the most common are:\n\nThe port is not open on the destination machine.\nThe port is open on the destination machine, but its backlog of pending connections is full.\nA firewall between the client and server is blocking access (also check local firewalls).\n\nAfter checking for firewalls and that the port is open, use telnet to connect to the ip/port to test connectivity. This removes any potential issues from your application.\n",
"The error means the OS of the listening socket recognized the inbound connection request but chose to intentionally reject it. \nAssuming an intermediate firewall is not getting in the way, there are only two reasons (that I know of) for the OS to reject an inbound connection request. One reason has already been mentioned several times - the listening port being connected to is not open. \nThere is another reason that has not been mentioned yet - the listening port is actually open and actively being used, but its backlog of queued inbound connection requests has reached its maximum so there is no room available for the inbound connection request to be queued at that moment. The server code has not called accept() enough times yet to finish clearing out available slots for new queue items. \nWait a moment or so and try the connection again. Unfortunately, there is no way to differentiate between \"the port is not open at all\" and \"the port is open but too busy right now\". They both use the same generic error code.\n",
"If you try to open a TCP connection to another host and see the error \"Connection refused,\" it means that\n\nYou sent a TCP SYN packet to the other host.\nThen you received a TCP RST packet in reply.\n\nRST is a bit on the TCP packet which indicates that the connection should be reset. Usually it means that the other host has received your connection attempt and is actively refusing your TCP connection, but sometimes an intervening firewall may block your TCP SYN packet and send a TCP RST back to you.\nSee https://www.rfc-editor.org/rfc/rfc793 page 69:\n\nSYN-RECEIVED STATE\nIf the RST bit is set\nIf this connection was initiated with a passive OPEN (i.e., came\nfrom the LISTEN state), then return this connection to LISTEN state\nand return. The user need not be informed. If this connection was\ninitiated with an active OPEN (i.e., came from SYN-SENT state) then\nthe connection was refused, signal the user \"connection refused\". In\neither case, all segments on the retransmission queue should be\nremoved. And in the active OPEN case, enter the CLOSED state and\ndelete the TCB, and return.\n\n",
"Connection refused means that the port you are trying to connect to is not actually open. \nSo either you are connecting to the wrong IP address, or to the wrong port, or the server is listening on the wrong port, or is not actually running.\nA common mistake is not specifying the port number when binding or connecting in network byte order...\n",
"Check at the server side that it is listening at the port 2080.\nFirst try to confirm it on the server machine by issuing telnet to that port: \ntelnet localhost 2080 \nIf it is listening, it is able to respond.\n",
"1.Check your server status.\n2.Check the port status.\nFor example 3306 netstat -nupl|grep 3306.\n3.Check your firewalls.\nFor example add 3306\nvim /etc/sysconfig/iptables\n# add\n-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT\n\n",
"Although it does not seem to be the case for your situation, sometimes a connection refused error can also indicate that there is an ip address conflict on your network. You can search for possible ip conflicts by running:\n arp-scan -I eth0 -l | grep <ipaddress>\n\nand \narping <ipaddress>\n\nThis AskUbuntu question has some more information also.\n",
"I get the same problem with my work computer.\nThe problem is that when you enter localhost it goes to proxy's address not local address you should bypass it follow this steps\nChrome => Settings => Change proxy settings => LAN Settings => check Bypass proxy server for local addresses.\n",
"In Ubuntu, Try\nsudo ufw allow <port_number> \nto allow firewall access to both of your server and db.\n",
"From the standpoint of a Checkpoint firewall, you will see a message from the firewall if you actually choose Reject as an Action thereby exposing to a propective attacker the presence of a firewall in front of the server. The firewall will silently drop all connections that doesn't match the policy. Connection refused almost always comes from the server\n",
"In my case, it happens when the site is blocked in my country and I don't use VPN.\nFor example when I try to access vimeo.com from Indonesia which is blocked.\n",
"\nCheck if your application is bind with the port where you are sending the request\nCheck if the application is accepting connections from the host you are sending the request, maybe you forgot to allow all the incoming connections 0.0.0.0 and by default, it's only allowing connections from 127.0.0.1\n\n"
] | [
133,
84,
40,
23,
7,
3,
1,
1,
1,
0,
0,
0
] | [
"I had the same message with a totally different cause: the wsock32.dll was not found. The ::socket(PF_INET, SOCK_STREAM, 0); call kept returning an INVALID_SOCKET but the reason was that the winsock dll was not loaded.\nIn the end I launched Sysinternals' process monitor and noticed that it searched for the dll 'everywhere' but didn't find it.\nSilent failures are great!\n"
] | [
-1
] | [
"c",
"connection_refused",
"sockets"
] | stackoverflow_0002333400_c_connection_refused_sockets.txt |
Q:
Is it possible to add action hook before vagrant halt/suspend
i would like to trigger action on my VM before the suspend or halt action takes effect.
I see action hook i could use but they are all after the actions are done https://www.vagrantup.com/docs/plugins/action-hooks.html.
Any clues?
A:
I believe most of those hooks are for plugin development - what you're looking at is the vagrant trigger plugin so if you want to have action done before suspend or halt :
Vagrant.configure("2") do |config|
# Your existing Vagrant configuration
...
# run some script before the guest is halted
config.trigger.before :halt do
info "Dumping the database before destroying the VM..."
run_remote "bash /vagrant/cleanup.sh"
end
# run some script before the guest is suspended
config.trigger.before :suspend do
info "Dumping the database before destroying the VM..."
run_remote "bash /vagrant/cleanup.sh"
end
# clean up files on the host after the guest is destroyed
config.trigger.after :destroy do
run "rm -Rf tmp/*"
end
# start apache on the guest after the guest starts
config.trigger.after :up do
run_remote "service apache2 start"
end
end
A:
I think you could also try to use udev events on guest machine.
This one can be done with provisioning when the vagrant up is done for the first time (or later with vagrant provision.
For example I'm restarting php5-fpm after nfs mounts directory with code.
I think you could also use systemd on guest OS (if you're using OS that has systemd of course).
A:
You can have a look at:
https://github.com/lqbweb/vagrant_hook
It is a basic and simple vagrant plugin that proves how to attach to a certain vagrant chain action.
A:
I don't know how to use config.trigger in a plugin instead of a Vagrantfile.
However, I found that the docs is completely wrong, that "after" is incorrect!
Actually, you just need to use prepend:
require_relative "action"
action_hook(:goodhosts, :machine_action_halt) do |hook|
hook.prepend(Action)
end
And this is how integrated version of trigger works:
lib/vagrant/action/builder.rb
lib/vagrant/action/builtin/trigger.rb
Note: the hooks/middlewares are nested, not sequential.
The community version of trigger always uses prepend with "sandwich middleware", i.e. there are operations both before and after the call to the next middleware.
def call(env)
before
@app.call(env)
after
While the integrated version of trigger uses prepend for "before" and append for "after" with "linear middleware", i.e. there are operations only before the call to the next middleware, as if the hooks were sequential.
def call(env)
operation
@app.call(env)
Since provider's actions halt and suspend are middlewares as well (hyperv can be taken as an example), prepended hooks can definitely operate before the halt or suspend action takes effect.
| Is it possible to add action hook before vagrant halt/suspend | i would like to trigger action on my VM before the suspend or halt action takes effect.
I see action hook i could use but they are all after the actions are done https://www.vagrantup.com/docs/plugins/action-hooks.html.
Any clues?
| [
"I believe most of those hooks are for plugin development - what you're looking at is the vagrant trigger plugin so if you want to have action done before suspend or halt :\nVagrant.configure(\"2\") do |config|\n # Your existing Vagrant configuration\n ...\n\n # run some script before the guest is halted\n config.trigger.before :halt do\n info \"Dumping the database before destroying the VM...\"\n run_remote \"bash /vagrant/cleanup.sh\"\n end\n\n # run some script before the guest is suspended\n config.trigger.before :suspend do\n info \"Dumping the database before destroying the VM...\"\n run_remote \"bash /vagrant/cleanup.sh\"\n end\n\n # clean up files on the host after the guest is destroyed\n config.trigger.after :destroy do\n run \"rm -Rf tmp/*\"\n end\n\n # start apache on the guest after the guest starts\n config.trigger.after :up do\n run_remote \"service apache2 start\"\n end\n\nend\n\n",
"I think you could also try to use udev events on guest machine.\nThis one can be done with provisioning when the vagrant up is done for the first time (or later with vagrant provision.\nFor example I'm restarting php5-fpm after nfs mounts directory with code.\nI think you could also use systemd on guest OS (if you're using OS that has systemd of course).\n",
"You can have a look at:\nhttps://github.com/lqbweb/vagrant_hook\nIt is a basic and simple vagrant plugin that proves how to attach to a certain vagrant chain action.\n",
"I don't know how to use config.trigger in a plugin instead of a Vagrantfile.\nHowever, I found that the docs is completely wrong, that \"after\" is incorrect!\nActually, you just need to use prepend:\nrequire_relative \"action\"\naction_hook(:goodhosts, :machine_action_halt) do |hook|\n hook.prepend(Action)\nend\n\nAnd this is how integrated version of trigger works:\n\nlib/vagrant/action/builder.rb\nlib/vagrant/action/builtin/trigger.rb\n\nNote: the hooks/middlewares are nested, not sequential.\nThe community version of trigger always uses prepend with \"sandwich middleware\", i.e. there are operations both before and after the call to the next middleware.\ndef call(env)\n before\n @app.call(env)\n after\n\nWhile the integrated version of trigger uses prepend for \"before\" and append for \"after\" with \"linear middleware\", i.e. there are operations only before the call to the next middleware, as if the hooks were sequential.\ndef call(env)\n operation\n @app.call(env)\n\nSince provider's actions halt and suspend are middlewares as well (hyperv can be taken as an example), prepended hooks can definitely operate before the halt or suspend action takes effect.\n"
] | [
4,
0,
0,
0
] | [] | [] | [
"vagrant"
] | stackoverflow_0035912776_vagrant.txt |
Q:
Cant access container from browser
I'm trying to access the container from my laptop1 which is hosted on my other laptop2 Ubuntu 22.04 LTS.
I'm using putty to access ports. Through putty, I can access port 8080 but can't access other port 8081 where my container is hosted.
Here is my docker-compose file :
docker-compose.yml
A:
Hello please do a netstat(sudo netstat
-lntup)inside your
jenkins container (laptop2) and check wether it's listening on 8081 or not.
If it's listening then may be 3 reason you are unable access your jenkins container from laptop1
Disable ufw(firewall) status and
2.selinux (disable state)
3.if your are using azure, aws Or other cloud services check inbound traffic to allowed on 8081.
| Cant access container from browser | I'm trying to access the container from my laptop1 which is hosted on my other laptop2 Ubuntu 22.04 LTS.
I'm using putty to access ports. Through putty, I can access port 8080 but can't access other port 8081 where my container is hosted.
Here is my docker-compose file :
docker-compose.yml
| [
"Hello please do a netstat(sudo netstat\n-lntup)inside your\njenkins container (laptop2) and check wether it's listening on 8081 or not.\nIf it's listening then may be 3 reason you are unable access your jenkins container from laptop1\n\nDisable ufw(firewall) status and\n\n2.selinux (disable state)\n3.if your are using azure, aws Or other cloud services check inbound traffic to allowed on 8081.\n"
] | [
0
] | [] | [] | [
"devops",
"jenkins"
] | stackoverflow_0074658238_devops_jenkins.txt |
Q:
SoftHSMv2 - How to make created objects survive between sessions?
I open a session
I create an AES key with a label by using C_CreateObject
I can lookup the created object by label by using C_FindObjects.
I close the session.
I open a new session.
I can no longer lookup the created object by label using C_FindObjects.
What am I doing wrong?
Thanks!
A:
Two possibilities come to my mind:
Per PKCS#11 2.40,
Only session objects can be created during a read-only session
Therefore the session of C_CreateObject needs to have been opened with the flags argument set to CKF_SERIAL_SESSION | CKF_RW_SESSION .
The pTemplate argment to C_CreateObject needs to include the CKA_TOKEN attribute so that the newly created key would be a "token object" rather than a "session object".
In PKCS#11, a token object is persistent across sessions whereas a session object is ephemeral and would get dropped once the session is closed.
Hope this helps.
| SoftHSMv2 - How to make created objects survive between sessions? |
I open a session
I create an AES key with a label by using C_CreateObject
I can lookup the created object by label by using C_FindObjects.
I close the session.
I open a new session.
I can no longer lookup the created object by label using C_FindObjects.
What am I doing wrong?
Thanks!
| [
"Two possibilities come to my mind:\n\nPer PKCS#11 2.40,\n\n\nOnly session objects can be created during a read-only session\n\nTherefore the session of C_CreateObject needs to have been opened with the flags argument set to CKF_SERIAL_SESSION | CKF_RW_SESSION .\n\nThe pTemplate argment to C_CreateObject needs to include the CKA_TOKEN attribute so that the newly created key would be a \"token object\" rather than a \"session object\".\n\nIn PKCS#11, a token object is persistent across sessions whereas a session object is ephemeral and would get dropped once the session is closed.\nHope this helps.\n"
] | [
0
] | [] | [] | [
"softhsm"
] | stackoverflow_0071338851_softhsm.txt |
Q:
How to extract an image patch from a slice of NIFTI in R and save as png?
I am trying to extract a 32x32 patch from a slice of 3d NIFTI image and save it as png. I am working in R. The NIFTI image contains 155 slices of 240x240 pixels. I have located the region of interest on the 63rd slice, but when I export it as png, the patch is saved as 480x480 pixels in size by default.
The code is given below, where ROI is a 32x32 area from 58:89 on x position, 95:126 on y and on slice z=63.
library(oro.nifti)
set.seed(123)
arr = array(rnorm(240*240*155), dim = c(240,240,155))
img = oro.nifti::nifti(arr) #create NIFTI
png("C:/Users/Downloads/patchimg.png")
image(img[58:89, 95:126, 63], col=gray(0:64/64), xlab="", ylab="", axes=FALSE, useRaster=TRUE)
dev.off()
Is there another way to do it so the exported png is 32x32? Or is there a more efficient way to do it?
A:
# --- Load libraries
require( imager )
require( ggplot2 )
# --- Get the area of interest as a data frame of x, y, value:
# x y value
#1 1 1 -0.4163
#2 2 1 0.2430
#3 3 1 1.4427
# ...
patch <- as.data.frame( as.cimg( arr[ 58:89, 95:126, 63 ]))
# --- Plot the patch with no legend, no axes, just bare
p <- ggplot( patch, aes( x, y ) ) +
geom_raster( aes( fill = value ) ) +
theme_void() +
theme( legend.position = 'none' )
# --- Display the plot, if you wish
p
# --- Save the plot just created
ggsave(
plot = p, filename = 'patch32x32.png'
, height = 2, width = 2, dpi = 17
)
# When I used dpi=16, the saved patch had dimensions 32x32, but when
# I opened it again using imager::load.image, it put a 1-pixel black
# border around perimeter.
# So, depending on what you are going to do with the saved patch,
# you might use dpi=16 or dpi=17.
# 2 inches high x 16 dots-per-inch ---> 32 dots high
# 2 inches wide x 16 dots-per-inch ---> 32 dots wide
im2 <- load.image( 'patch32x32.png' )
| How to extract an image patch from a slice of NIFTI in R and save as png? | I am trying to extract a 32x32 patch from a slice of 3d NIFTI image and save it as png. I am working in R. The NIFTI image contains 155 slices of 240x240 pixels. I have located the region of interest on the 63rd slice, but when I export it as png, the patch is saved as 480x480 pixels in size by default.
The code is given below, where ROI is a 32x32 area from 58:89 on x position, 95:126 on y and on slice z=63.
library(oro.nifti)
set.seed(123)
arr = array(rnorm(240*240*155), dim = c(240,240,155))
img = oro.nifti::nifti(arr) #create NIFTI
png("C:/Users/Downloads/patchimg.png")
image(img[58:89, 95:126, 63], col=gray(0:64/64), xlab="", ylab="", axes=FALSE, useRaster=TRUE)
dev.off()
Is there another way to do it so the exported png is 32x32? Or is there a more efficient way to do it?
| [
"# --- Load libraries\n\nrequire( imager )\nrequire( ggplot2 )\n\n# --- Get the area of interest as a data frame of x, y, value:\n\n# x y value\n#1 1 1 -0.4163\n#2 2 1 0.2430\n#3 3 1 1.4427\n# ...\n\npatch <- as.data.frame( as.cimg( arr[ 58:89, 95:126, 63 ]))\n\n# --- Plot the patch with no legend, no axes, just bare\n\np <- ggplot( patch, aes( x, y ) ) +\n geom_raster( aes( fill = value ) ) +\n theme_void() +\n theme( legend.position = 'none' )\n\n# --- Display the plot, if you wish\np\n\n\n# --- Save the plot just created\n\nggsave(\n plot = p, filename = 'patch32x32.png'\n , height = 2, width = 2, dpi = 17\n) \n\n# When I used dpi=16, the saved patch had dimensions 32x32, but when\n# I opened it again using imager::load.image, it put a 1-pixel black\n# border around perimeter.\n\n# So, depending on what you are going to do with the saved patch,\n# you might use dpi=16 or dpi=17.\n# 2 inches high x 16 dots-per-inch ---> 32 dots high\n# 2 inches wide x 16 dots-per-inch ---> 32 dots wide\n\n\nim2 <- load.image( 'patch32x32.png' )\n\n\n"
] | [
0
] | [] | [] | [
"image",
"image_processing",
"nifti",
"png",
"r"
] | stackoverflow_0062273259_image_image_processing_nifti_png_r.txt |
Q:
Why javascript doesn't execute the querySelector inside AJAX?
I am trying to handle an HTML part inside the ajax success:function(data){} but for some reason the code won't execute when I am calling it. Below is the code I tried:
$.ajax({
url:"../new/php/posts.php",
method:"POST",
data:{limit:limit, start:start},
cache:false,
success:function(data)
{
//$('#activitystream').append(data);
var data_parse = JSON.parse(data);
for (var i in data_parse){
var divData = '<a id="default-like-'+data_parse[i].ID+'" href="#/" class="post__action post__action--reaction reaction reaction__toggle reaction-toggle--'+data_parse[i].ID+' reaction-emoticon-0 js-reaction-toggle" style="display: none;">\n'+
'<span>Like</span>\n'+
'</a>';
$('#activitystream').append(divData);
}
if(data == '') {
//Do nothing
action = 'active';
}else {
$('#activitystream-loading').css("display", "block");
action = 'inactive';
console.log(action);
console.log(data);
var els1 = document.querySelectorAll(".post__action--reaction");
for (var x = 0; x < els.length; x++){
alert("Hey there")
els1[x].style.display = 'block';
}
}
}
});
So, I also tried two ways. First of all, I tried to execute the code inside the complete:function(){} of AJAX and secondly, I tried to add the code inside this window.onload = function(){} but still nothing happening. There is not even any errors in the console, it just shows nothing. Do you know how can I handle the generated html part? Thanks in advance!
A:
One possible reason why your code is not executing as expected is that you are using the wrong variable name in the for loop. In the line:
for (var x = 0; x < els.length; x++){
you are using the variable "els" instead of "els1". This might be causing the loop to not execute at all, thus leading to no output.
Try changing the variable name in the for loop to match the variable name used earlier in the code, like this:
for (var x = 0; x < els1.length; x++){
This should fix the issue and allow your code to execute properly.
| Why javascript doesn't execute the querySelector inside AJAX? | I am trying to handle an HTML part inside the ajax success:function(data){} but for some reason the code won't execute when I am calling it. Below is the code I tried:
$.ajax({
url:"../new/php/posts.php",
method:"POST",
data:{limit:limit, start:start},
cache:false,
success:function(data)
{
//$('#activitystream').append(data);
var data_parse = JSON.parse(data);
for (var i in data_parse){
var divData = '<a id="default-like-'+data_parse[i].ID+'" href="#/" class="post__action post__action--reaction reaction reaction__toggle reaction-toggle--'+data_parse[i].ID+' reaction-emoticon-0 js-reaction-toggle" style="display: none;">\n'+
'<span>Like</span>\n'+
'</a>';
$('#activitystream').append(divData);
}
if(data == '') {
//Do nothing
action = 'active';
}else {
$('#activitystream-loading').css("display", "block");
action = 'inactive';
console.log(action);
console.log(data);
var els1 = document.querySelectorAll(".post__action--reaction");
for (var x = 0; x < els.length; x++){
alert("Hey there")
els1[x].style.display = 'block';
}
}
}
});
So, I also tried two ways. First of all, I tried to execute the code inside the complete:function(){} of AJAX and secondly, I tried to add the code inside this window.onload = function(){} but still nothing happening. There is not even any errors in the console, it just shows nothing. Do you know how can I handle the generated html part? Thanks in advance!
| [
"One possible reason why your code is not executing as expected is that you are using the wrong variable name in the for loop. In the line:\nfor (var x = 0; x < els.length; x++){\n\nyou are using the variable \"els\" instead of \"els1\". This might be causing the loop to not execute at all, thus leading to no output.\nTry changing the variable name in the for loop to match the variable name used earlier in the code, like this:\nfor (var x = 0; x < els1.length; x++){\n\nThis should fix the issue and allow your code to execute properly.\n"
] | [
1
] | [] | [] | [
"ajax",
"javascript",
"jquery"
] | stackoverflow_0074672152_ajax_javascript_jquery.txt |
Q:
.Net Maui copying assets into appData
Tring to move a PDF file from Resources\Raw to appData directory for App. File becomes corrupted on copy. Obviously I'm missing something.
using the following:
using var stream = await FileSystem.OpenAppPackageFileAsync("CBA2015.pdf");
using var reader = new StreamReader(stream);
if (stream != null)
{
var contents = reader.ReadToEnd();
string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "CBA2015.pdf");
using FileStream outputStream = System.IO.File.OpenWrite(targetFile);
using StreamWriter streamWriter = new StreamWriter(outputStream);
await streamWriter.WriteAsync(contents);
}
A:
To move a file from one directory to another, you can use the File.Move method. This method takes two arguments: the path to the source file and the path to the destination file.
Here is an example of how you can use File.Move to move a file:
string sourceFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "CBA2015.pdf");
string destinationFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "CBA2015_moved.pdf");
System.IO.File.Move(sourceFile, destinationFile);
In this example, the sourceFile is the path to the file you want to move, and the destinationFile is the path to the directory where you want to move the file to. If the file is successfully moved, you should be able to access it at the destinationFile path.
You can also use the File.Copy method to copy the file from one directory to another, instead of moving it. This method takes the same two arguments as File.Move: the path to the source file and the path to the destination file. Here is an example of how you can use File.Copy to copy a file:
string sourceFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "CBA2015.pdf");
string destinationFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "CBA2015_copy.pdf");
System.IO.File.Copy(sourceFile, destinationFile);
In this example, the sourceFile is the path to the file you want to copy, and the destinationFile is the path to the directory where you want to copy the file to. If the file is successfully copied, you should be able to access it at the destinationFile path.
I hope this helps!
A:
This works:
string sourceFile = "CBA2015.pdf";
// Read the source file
//using Stream fileStream = await FileSystem.Current.OpenAppPackageFileAsync(sourceFile);
// using StreamReader reader = new StreamReader(fileStream);
string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "CBA2015.pdf");
using FileStream outputStream = System.IO.File.OpenWrite(targetFile);
using Stream fs = await FileSystem.Current.OpenAppPackageFileAsync(sourceFile);
using BinaryWriter writer = new BinaryWriter(outputStream);
using (BinaryReader reader = new BinaryReader(fs))
{
var bytesRead = 0;
int bufferSize = 1024;
byte[] bytes;
var buffer = new byte[bufferSize];
using (fs)
{
do
{
buffer = reader.ReadBytes(bufferSize);
bytesRead = buffer.Count();
writer.Write(buffer);
}
while (bytesRead > 0);
}
}
| .Net Maui copying assets into appData | Tring to move a PDF file from Resources\Raw to appData directory for App. File becomes corrupted on copy. Obviously I'm missing something.
using the following:
using var stream = await FileSystem.OpenAppPackageFileAsync("CBA2015.pdf");
using var reader = new StreamReader(stream);
if (stream != null)
{
var contents = reader.ReadToEnd();
string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "CBA2015.pdf");
using FileStream outputStream = System.IO.File.OpenWrite(targetFile);
using StreamWriter streamWriter = new StreamWriter(outputStream);
await streamWriter.WriteAsync(contents);
}
| [
"To move a file from one directory to another, you can use the File.Move method. This method takes two arguments: the path to the source file and the path to the destination file.\nHere is an example of how you can use File.Move to move a file:\nstring sourceFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, \"CBA2015.pdf\");\nstring destinationFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, \"CBA2015_moved.pdf\");\n\nSystem.IO.File.Move(sourceFile, destinationFile);\n\n\nIn this example, the sourceFile is the path to the file you want to move, and the destinationFile is the path to the directory where you want to move the file to. If the file is successfully moved, you should be able to access it at the destinationFile path.\nYou can also use the File.Copy method to copy the file from one directory to another, instead of moving it. This method takes the same two arguments as File.Move: the path to the source file and the path to the destination file. Here is an example of how you can use File.Copy to copy a file:\nstring sourceFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, \"CBA2015.pdf\");\nstring destinationFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, \"CBA2015_copy.pdf\");\n\nSystem.IO.File.Copy(sourceFile, destinationFile);\n\n\nIn this example, the sourceFile is the path to the file you want to copy, and the destinationFile is the path to the directory where you want to copy the file to. If the file is successfully copied, you should be able to access it at the destinationFile path.\nI hope this helps!\n",
"This works:\nstring sourceFile = \"CBA2015.pdf\";\n// Read the source file\n//using Stream fileStream = await FileSystem.Current.OpenAppPackageFileAsync(sourceFile);\n// using StreamReader reader = new StreamReader(fileStream);\n string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, \"CBA2015.pdf\");\n using FileStream outputStream = System.IO.File.OpenWrite(targetFile);\n using Stream fs = await FileSystem.Current.OpenAppPackageFileAsync(sourceFile);\n using BinaryWriter writer = new BinaryWriter(outputStream);\n using (BinaryReader reader = new BinaryReader(fs))\n {\n var bytesRead = 0;\n \n int bufferSize = 1024;\n byte[] bytes;\n var buffer = new byte[bufferSize];\n using (fs)\n {\n do\n {\n\n buffer = reader.ReadBytes(bufferSize);\n bytesRead = buffer.Count();\n writer.Write(buffer);\n\n }\n\n while (bytesRead > 0);\n\n }\n }\n\n"
] | [
0,
0
] | [] | [] | [
".net",
"maui"
] | stackoverflow_0074658809_.net_maui.txt |
Q:
How to extract a specific text when web scraping for this situation
I need to scrape texts from a website, but could not figure out a way to scrape a specific text for this situation:
<td valign="top" class="testo_normale">
<font face="Geneva">
<i>W. Richard Bowen</i>
<br>
"Water engineering for the promotion of peace"
<br>
"1(2009)1-6"
<br>
"DOI: "
<br>
"Received:26/08/2008; Accepted: 25/11/2008; "
So in the above example, I want to only get Water engineering and 1(2009)1-6
I tried to do that all day but I either get all the texts having tag <br> :
"W. Richard Bowen"
"Water engineering for the promotion of peace"
"1(2009)1-6"
"DOI: "
"Received:26/08/2008; Accepted: 25/11/2008;"
or I get empty output.
here is website I'm trying to scrape, and a picture of what I want to scrape
This is my code:
from bs4 import BeautifulSoup
import requests
r = requests.get('https://www.deswater.com/vol.php?vol=1&oth=1|1-3|January|2009')
soup = BeautifulSoup(r.content, 'html.parser')
s = soup.find('td', class_='testo_normale')
lines = s.find_all('br')
for line in lines:
print(line.text.strip())
A:
You can apply split() method like:
from bs4 import BeautifulSoup
html ='''
<td valign="top" class="testo_normale">
<font face="Geneva">
<i>W. Richard Bowen</i>
<br>
"Water engineering for the promotion of peace"
<br>
"1(2009)1-6"
<br>
"DOI: "
<br>
"Received:26/08/2008; Accepted: 25/11/2008; "
'''
soup= BeautifulSoup(html, 'lxml')
txt = soup.select_one('.testo_normale font')
print(' '.join(' '.join(txt.get_text(strip=True).split('"')).strip().split(':')[0].split()[3:-1]))
#OR
for u in soup.select('.testo_normale font'):
txt = ' '.join(' '.join(u.get_text(strip=True).split('"')).strip().split(':')[0].split()[3:-1])
print(txt)
Output:
Water engineering for the promotion of peace 1(2009)1-6
Update with full working code:
from bs4 import BeautifulSoup
import requests
r = requests.get('https://www.deswater.com/vol.php?vol=1&oth=1|1-3|January|2009')
soup = BeautifulSoup(r.content, 'html.parser')
for u in soup.select('font[face="Geneva, Arial, Helvetica, san-serif"]')[6:]:
txt = u.contents[2:-1]
for i in txt:
print(i.get_text(strip=True))
Output:
Editorial and Obituary for Sidney Loeb by Miriam Balaban
1(2009)vii-viii
Water engineering for the promotion of peace
1(2009)1-6
Modeling the permeate transient response to perturbations from steady state in a nanofiltration process
1(2009)7-16
Modeling the effect of anti-scalant on CaCO3 precipitation in continuous flow
1(2009)17-24
Alternative primary energy for power desalting plants in Kuwait: the nuclear option I
1(2009)25-41
Alternative primary energy for power desalting plants in Kuwait: the nuclear
option II The steam cycle and its combination with desalting units
1(2009)42-57
Potential applications of quarry dolomite for post treatment of desalinated water
1(2009)58-67
Salinity tolerance evaluation methodology for desalination plant discharge
1(2009)68-74
Studies on a water-based absortion heat transformer for desalination using MED
1(2009)75-81
Estimation of stream compositions in reverse osmosis seawater desalination systems
1(2009)82-87
Genetic algorithm-based optimization of a multi-stage flash desalination plant
1(2009)88-106
Numerical simulation on a dynamic mixing process in ducts of a rotary pressure exchanger for SWRO
1(2009)107-113
Simulation of an autonomous, two-stage solar organic Rankine cycle system for reverse osmosis desalination
1(2009)114-127
Experiment and optimal parameters of a solar heating system study on an absorption solar desalination unit
1(2009)128-138
Roles of various mixed liquor constituents in membrane filtration of activated sludge
1(2009)139-149
Natural organic matter fouling using a cellulose acetate copolymer ultrafiltration membrane
1(2009)150-156
Progress of enzyme immobilization and its potential application
1(2009)157-171
Investigating microbial activities of constructed wetlands with respect to nitrate and sulfate reduction
1(2009)172-179
Membrane fouling caused by soluble microbial products in an activated sludge system under starvation
1(2009)180-185
Characterization of an ultrafiltration membrane modified by sorption of branched polyethyleneimine
1(2009)186-193
Combined humic substance coagulation and membrane filtration under saline conditions
1(2009)194-200
Preparation, characterization and performance of phenolphthalein polyethersulfone ultrafiltration hollow fiber membranes
1(2009)201-207
Application of coagulants in pretreatment of fish wastewater using factorial design
1(2009)208-214
Performance analysis of a trihybrid NF/RO/MSF desalination plant
1(2009)215-222
Nitrogen speciation by microstill flow injection analysis
1(2009)223-231
Wastewater from a mountain village treated with a constructed wetland
1(2009)232-236
The influence of various operating conditions on specific cake resistance in the crossflow microfiltration of yeast suspensions
1(2009)237-247
On-line monitoring of floc formation in various flocculants for piggery wastewater treatment
1(2009)248-258
Rigorous steady-state modeling of MSFBR desalination systems
1(2009)259-276
Detailed numerical simulations of flow mechanics and membrane performance in spacer-filled channels, flat and curved
1(2009)277-288
Removal of polycyclic aromatic hydrocarbons from Ismailia Canal water by chlorine, chlorine dioxide and ozone
1(2009)289-298
Water resources management to satisfy high water demand in the arid Sharm El Sheikh, the Red Sea, Egypt
1(2009)299-306
Effect of storage of NF membranes on fouling deposits and cleaning efficiency
1(2009)307-311
Laboratory studies and CFD modeling of photocatalytic degradation of colored textile wastewater by titania nanoparticles
1(2009)312-317
Startup operation and process control of a two-stage sequencing batch reactor (TSSBR) for biological nitrogen removal via nitrite
1(2009)318-325
A:
To extact ANY text in the position of 'Water engineering' which is what I think you want, you can write a regex function like the following:
import re
def extract_text(string):
pattern = r'<br>\s*(.*?)\s*(?:<br>|<)'
regex = re.compile(pattern)
matches = regex.finditer(string)
texts = []
for match in matches:
texts.append(match.group(1))
return texts
string = """
<td valign="top" class="testo_normale">
<font face="Geneva">
<i>Mariam B</i>
<br>
"some other text"
<br>
"1(2009)1-6"
<br>"""
text = extract_text(string)
print(text)
The regular expression consists of the following parts:
<br>: This matches the tag literally. This indicates that the text we are looking for is preceded by this tag in the string.
\s*: This matches any whitespace characters (space, tab, newline, etc.) zero or more times. This allows the <br> tag to be followed by any amount of whitespace, including none at all.
(.*?): This is a capturing group that matches any sequence of characters (except a newline) zero or more times, as few times as possible. This is the part of the regular expression that actually captures the text we are looking for. The ? after the * makes the * "lazy", which means it will match as few characters as possible. This is necessary to prevent the regular expression from matching too much text.
\s*: This is the same as the second \s* in the pattern, and it allows the text we are looking for to be followed by any amount of whitespace, including none at all.
(?:<br>|<): This is a non-capturing group that matches either a <br> tag or a < character. This indicates that the text we are looking for is followed by one of these two patterns in the string.
This regular expression will match any sequence of characters that is preceded by a <br> tag and followed by a <br> or < tag. For example, in the given string <td valign="top" class="testo_normale"> ... <br>"Water engineering" <br>"1(2009)1-6"<br>", it will match the text Water engineering because it is preceded by <br> and followed by <br>.
Note that this regular expression is not perfect and may not work in all cases. For example, if the text you are looking for contains a < or <br> character, this regular expression will not match it correctly. You may need to adjust the regular expression pattern to handle such cases.
| How to extract a specific text when web scraping for this situation | I need to scrape texts from a website, but could not figure out a way to scrape a specific text for this situation:
<td valign="top" class="testo_normale">
<font face="Geneva">
<i>W. Richard Bowen</i>
<br>
"Water engineering for the promotion of peace"
<br>
"1(2009)1-6"
<br>
"DOI: "
<br>
"Received:26/08/2008; Accepted: 25/11/2008; "
So in the above example, I want to only get Water engineering and 1(2009)1-6
I tried to do that all day but I either get all the texts having tag <br> :
"W. Richard Bowen"
"Water engineering for the promotion of peace"
"1(2009)1-6"
"DOI: "
"Received:26/08/2008; Accepted: 25/11/2008;"
or I get empty output.
here is website I'm trying to scrape, and a picture of what I want to scrape
This is my code:
from bs4 import BeautifulSoup
import requests
r = requests.get('https://www.deswater.com/vol.php?vol=1&oth=1|1-3|January|2009')
soup = BeautifulSoup(r.content, 'html.parser')
s = soup.find('td', class_='testo_normale')
lines = s.find_all('br')
for line in lines:
print(line.text.strip())
| [
"You can apply split() method like:\nfrom bs4 import BeautifulSoup\n\nhtml ='''\n\n<td valign=\"top\" class=\"testo_normale\">\n <font face=\"Geneva\">\n <i>W. Richard Bowen</i>\n <br>\n \"Water engineering for the promotion of peace\" \n <br>\n \"1(2009)1-6\"\n <br>\n \"DOI: \"\n <br>\n \"Received:26/08/2008; Accepted: 25/11/2008; \"\n \n'''\n\nsoup= BeautifulSoup(html, 'lxml')\n\ntxt = soup.select_one('.testo_normale font')\nprint(' '.join(' '.join(txt.get_text(strip=True).split('\"')).strip().split(':')[0].split()[3:-1]))\n\n#OR \n\nfor u in soup.select('.testo_normale font'):\n txt = ' '.join(' '.join(u.get_text(strip=True).split('\"')).strip().split(':')[0].split()[3:-1])\n print(txt)\n\nOutput:\nWater engineering for the promotion of peace 1(2009)1-6\n\nUpdate with full working code:\nfrom bs4 import BeautifulSoup\nimport requests\nr = requests.get('https://www.deswater.com/vol.php?vol=1&oth=1|1-3|January|2009')\nsoup = BeautifulSoup(r.content, 'html.parser')\n\nfor u in soup.select('font[face=\"Geneva, Arial, Helvetica, san-serif\"]')[6:]:\n txt = u.contents[2:-1]\n for i in txt:\n print(i.get_text(strip=True))\n\nOutput:\nEditorial and Obituary for Sidney Loeb by Miriam Balaban\n\n1(2009)vii-viii\nWater engineering for the promotion of peace\n\n1(2009)1-6\nModeling the permeate transient response to perturbations from steady state in a nanofiltration process\n\n1(2009)7-16\nModeling the effect of anti-scalant on CaCO3 precipitation in continuous flow\n\n1(2009)17-24\nAlternative primary energy for power desalting plants in Kuwait: the nuclear option I\n\n1(2009)25-41\nAlternative primary energy for power desalting plants in Kuwait: the nuclear\noption II The steam cycle and its combination with desalting units\n\n1(2009)42-57\nPotential applications of quarry dolomite for post treatment of desalinated water\n\n1(2009)58-67\nSalinity tolerance evaluation methodology for desalination plant discharge\n\n1(2009)68-74\nStudies on a water-based absortion heat transformer for desalination using MED\n\n1(2009)75-81\nEstimation of stream compositions in reverse osmosis seawater desalination systems\n\n1(2009)82-87\nGenetic algorithm-based optimization of a multi-stage flash desalination plant\n\n1(2009)88-106\nNumerical simulation on a dynamic mixing process in ducts of a rotary pressure exchanger for SWRO\n\n1(2009)107-113\nSimulation of an autonomous, two-stage solar organic Rankine cycle system for reverse osmosis desalination\n\n1(2009)114-127\nExperiment and optimal parameters of a solar heating system study on an absorption solar desalination unit\n\n1(2009)128-138\nRoles of various mixed liquor constituents in membrane filtration of activated sludge\n\n1(2009)139-149\nNatural organic matter fouling using a cellulose acetate copolymer ultrafiltration membrane\n\n1(2009)150-156\nProgress of enzyme immobilization and its potential application\n\n1(2009)157-171\nInvestigating microbial activities of constructed wetlands with respect to nitrate and sulfate reduction\n\n1(2009)172-179\nMembrane fouling caused by soluble microbial products in an activated sludge system under starvation\n\n1(2009)180-185\nCharacterization of an ultrafiltration membrane modified by sorption of branched polyethyleneimine\n\n1(2009)186-193\nCombined humic substance coagulation and membrane filtration under saline conditions\n\n1(2009)194-200\nPreparation, characterization and performance of phenolphthalein polyethersulfone ultrafiltration hollow fiber membranes\n\n1(2009)201-207\nApplication of coagulants in pretreatment of fish wastewater using factorial design\n\n1(2009)208-214\nPerformance analysis of a trihybrid NF/RO/MSF desalination plant\n\n1(2009)215-222\nNitrogen speciation by microstill flow injection analysis\n\n1(2009)223-231\nWastewater from a mountain village treated with a constructed wetland\n\n1(2009)232-236\nThe influence of various operating conditions on specific cake resistance in the crossflow microfiltration of yeast suspensions\n\n1(2009)237-247\nOn-line monitoring of floc formation in various flocculants for piggery wastewater treatment\n\n1(2009)248-258\nRigorous steady-state modeling of MSFBR desalination systems\n\n1(2009)259-276\nDetailed numerical simulations of flow mechanics and membrane performance in spacer-filled channels, flat and curved\n\n1(2009)277-288\nRemoval of polycyclic aromatic hydrocarbons from Ismailia Canal water by chlorine, chlorine dioxide and ozone\n\n1(2009)289-298\nWater resources management to satisfy high water demand in the arid Sharm El Sheikh, the Red Sea, Egypt\n\n1(2009)299-306\nEffect of storage of NF membranes on fouling deposits and cleaning efficiency\n\n1(2009)307-311\nLaboratory studies and CFD modeling of photocatalytic degradation of colored textile wastewater by titania nanoparticles\n\n1(2009)312-317\nStartup operation and process control of a two-stage sequencing batch reactor (TSSBR) for biological nitrogen removal via nitrite\n\n1(2009)318-325\n\n",
"To extact ANY text in the position of 'Water engineering' which is what I think you want, you can write a regex function like the following:\nimport re\n\ndef extract_text(string):\n pattern = r'<br>\\s*(.*?)\\s*(?:<br>|<)'\n regex = re.compile(pattern)\n matches = regex.finditer(string)\n texts = []\n for match in matches:\n texts.append(match.group(1))\n return texts\n\nstring = \"\"\"\n<td valign=\"top\" class=\"testo_normale\">\n <font face=\"Geneva\">\n <i>Mariam B</i>\n <br>\n \"some other text\" \n <br>\n \"1(2009)1-6\"\n <br>\"\"\"\n\ntext = extract_text(string)\nprint(text)\n\n\nThe regular expression consists of the following parts:\n<br>: This matches the tag literally. This indicates that the text we are looking for is preceded by this tag in the string.\n\\s*: This matches any whitespace characters (space, tab, newline, etc.) zero or more times. This allows the <br> tag to be followed by any amount of whitespace, including none at all.\n(.*?): This is a capturing group that matches any sequence of characters (except a newline) zero or more times, as few times as possible. This is the part of the regular expression that actually captures the text we are looking for. The ? after the * makes the * \"lazy\", which means it will match as few characters as possible. This is necessary to prevent the regular expression from matching too much text.\n\\s*: This is the same as the second \\s* in the pattern, and it allows the text we are looking for to be followed by any amount of whitespace, including none at all.\n(?:<br>|<): This is a non-capturing group that matches either a <br> tag or a < character. This indicates that the text we are looking for is followed by one of these two patterns in the string.\nThis regular expression will match any sequence of characters that is preceded by a <br> tag and followed by a <br> or < tag. For example, in the given string <td valign=\"top\" class=\"testo_normale\"> ... <br>\"Water engineering\" <br>\"1(2009)1-6\"<br>\", it will match the text Water engineering because it is preceded by <br> and followed by <br>.\nNote that this regular expression is not perfect and may not work in all cases. For example, if the text you are looking for contains a < or <br> character, this regular expression will not match it correctly. You may need to adjust the regular expression pattern to handle such cases.\n"
] | [
1,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074672015_beautifulsoup_python_web_scraping.txt |
Q:
Font weight only work with bold ones. Other doesnt work
I am loading fonts from my local for website. @font-face doesnt work properly. Some font weights doesnt work. Only work bold ones. When I changed font weight for light,lighter,400-500 etc it doesnt work. I'm stuck completely. Anybody help?
My Network:
My Computed:
My Files:
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-thin-webfont.woff2") format("woff2");
font-weight: 100;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-light-webfont.woff2") format("woff2");
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-book-webfont.woff2") format("woff2");
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-medium-webfont.woff2") format("woff2");
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-bold-webfont.woff2") format("woff2");
font-weight: 700;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-ultra-webfont.woff2") format("woff2");
font-weight: 800;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-black-webfont.woff2") format("woff2");
font-weight: 900;
font-style: normal;
}
A:
Search for typos in the @font-face rules
As pointed out by @Peter Constable:
typos in your @font-face rule will break it
font-family: "Gotham Narrow "; /* trailing space - won'work */
Inspect your page via your dev tools
Quite likely, your fonts are not loaded and the bold font you can see is actually a locally installed Gotham.
Check the computed style tab:
Screenshot above: Font is replaced by a locally installed (OS) "Gotham" font – worth mentioning: the browser replaced the intended "Gotham Narrow" with a regular "Gotham" – not condensed. (thanks to @Peter Constable for pointing this out.)
If a font URL is wrong, you'll see a log like this in your console.
Failed to load resource: the server responded with a status of 404 ()
You should also check the network tab for loaded fonts.
Try this example and replace the the src URLs with your paths.
@font-face {
font-family: "Gotham Narrow";
src: url("https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxIIzI.woff2") format("woff2");
font-style: normal;
font-weight: 100;
font-display: swap;
}
@font-face {
font-family: "Gotham Narrow";
src: url("https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK.woff2") format("woff2");
font-style: normal;
font-weight: 400;
font-display: swap;
}
@font-face {
font-family: "Gotham Narrow";
src: url("https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBBc4.woff2") format("woff2");
font-style: normal;
font-weight: 700;
font-display: swap;
}
@font-face {
font-family: "Gotham Narrow";
src: url("https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfBBc4.woff2") format("woff2");
font-style: normal;
font-weight: 900;
font-display: swap;
}
/** wrong url/path */
@font-face {
font-family: "Gotham Narrow";
src: url("https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK-wrong.woff2") format("woff2");
font-style: normal;
font-weight: 1000;
font-display: swap;
}
/* default for body */
body{
font-family: "Gotham Narrow";
font-weight: 400;
font-size:2em;
}
h1{
font-weight: 900
}
h1,h2{
font-size:1.5em
}
h2,
strong{
font-weight: 700
}
.light{
font-weight: 100;
}
.regular{
font-weight: 400;
}
.bold{
font-weight: 900;
}
.heavy{
font-weight: 900;
}
/** doesn't exist **/
.ultra{
font-weight: 1000;
}
<h1>Font weight 900</h1>
<h2>Font weight 700</h2>
<p>Font weight 400 <strong>Font weight 700</strong> <span class="light">Font weight 100</span> <span class="ultra">Font weight 1000 - doesn't exist</span></p>
Make sure your weights and styles are applied
Most browsers will "lazyload" fonts:
If a font isn't used anywhere – it won't be loaded.
I recommend to set the font-weight:400 as a default for your body.
Since you have multiple levels of bold you need to specify, if a <strong> element should use font-weight:700 or font-weight:900 (same for headings like h1-h5)
body{
font-family: "Gotham Narrow";
font-weight: 400;
}
h2,
strong{
font-weight: 700
}
Common mistake: relative paths
Paths might change while compiling your css – e.g. you're combining css snippets via scss/sass.
Corrupted font files – rather rare
Once again – check your dev tools console for logs like these:
Failed to decode downloaded font:
OTS parsing error
These issues usually occur, after file conversions (in less capable applications) like these:
font format conversions (e.g. ttf to woff2)
character subsetting
upload filters (trying to sanitize the uploaded file)
... and sometimes a font file might as well become invalid due to file system corruption.
A:
what I was saying is the following:
@font-face {
font-family: "Gotham Narrow";
src: url("assets-new/font/GothamNarrow-Book.eot") ;
src: url("assets-new/font/GothamNarrow-Book.eot?#iefix")
format("embedded-opentype"),
url("assets-new/font/GothamNarrow-Book.woff2") format("woff2"),
url("assets-new/font/GothamNarrow-Book.woff") format("woff"),
url("assets-new/font/GothamNarrow-Book.ttf") format("truetype"),
url("assets-new/font/GothamNarrow-Book.svg#GothamNarrow-Book") format("svg");
font-style: 400;
font-display: swap;
}
@font-face {
font-family: "Gotham Narrow Medium";
src: url("assets-new/font/GothamNarrow-Medium.eot")
;
src: url("assets-new/font/GothamNarrow-Medium.eot?#iefix")
format("embedded-opentype"),
url("assets-new/font/GothamNarrow-Medium.woff2") format("woff2"),
url("assets-new/font/GothamNarrow-Medium.woff") format("woff"),
url("assets-new/font/GothamNarrow-Medium.ttf") format("truetype"),
url("assets-new/font/GothamNarrow-Medium.svg#GothamNarrow-Medium")
format("svg");
font-style: 500;
font-display: swap;
}
div1 {
font-family: "Gotham Narrow";
}
div2 {
font-family: "Gotham Narrow Medium";
}
You could also use css variables (after font face declaration):
:root {
--font-primary: "Gotham Narrow", sans-serif;
--font-primary-medium: "Gotham Narrow Medium", sans-serif;
}
div1 {
font-family: var(--font-primary);
}
div2 {
font-family: var(--font-primary-medium);
}
A:
There no one solid answer, everyone helped and thanks everybody. I'm writing right solution. First it must be url not local. Second my font files characters had display problems. Downloaded different font files and its ok now.
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Thin.woff2") format("woff2");
font-weight: 100;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Light.woff2") format("woff2");
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Book.woff2") format("woff2");
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Medium.woff2") format("woff2");
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Bold.woff2") format("woff2");
font-weight: 700;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Black.woff2") format("woff2");
font-weight: 800;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Ultra.woff2") format("woff2");
font-weight: 900;
font-style: normal;
}
| Font weight only work with bold ones. Other doesnt work | I am loading fonts from my local for website. @font-face doesnt work properly. Some font weights doesnt work. Only work bold ones. When I changed font weight for light,lighter,400-500 etc it doesnt work. I'm stuck completely. Anybody help?
My Network:
My Computed:
My Files:
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-thin-webfont.woff2") format("woff2");
font-weight: 100;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-light-webfont.woff2") format("woff2");
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-book-webfont.woff2") format("woff2");
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-medium-webfont.woff2") format("woff2");
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-bold-webfont.woff2") format("woff2");
font-weight: 700;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-ultra-webfont.woff2") format("woff2");
font-weight: 800;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-black-webfont.woff2") format("woff2");
font-weight: 900;
font-style: normal;
}
| [
"Search for typos in the @font-face rules\nAs pointed out by @Peter Constable:\ntypos in your @font-face rule will break it\nfont-family: \"Gotham Narrow \"; /* trailing space - won'work */\n\nInspect your page via your dev tools\nQuite likely, your fonts are not loaded and the bold font you can see is actually a locally installed Gotham.\nCheck the computed style tab:\n\nScreenshot above: Font is replaced by a locally installed (OS) \"Gotham\" font – worth mentioning: the browser replaced the intended \"Gotham Narrow\" with a regular \"Gotham\" – not condensed. (thanks to @Peter Constable for pointing this out.)\nIf a font URL is wrong, you'll see a log like this in your console.\n\nFailed to load resource: the server responded with a status of 404 ()\n\nYou should also check the network tab for loaded fonts.\n\nTry this example and replace the the src URLs with your paths.\n\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"https://fonts.gstatic.com/s/roboto/v30/KFOkCnqEu92Fr1MmgVxIIzI.woff2\") format(\"woff2\");\n font-style: normal;\n font-weight: 100;\n font-display: swap;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK.woff2\") format(\"woff2\");\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmWUlfBBc4.woff2\") format(\"woff2\");\n font-style: normal;\n font-weight: 700;\n font-display: swap;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"https://fonts.gstatic.com/s/roboto/v30/KFOlCnqEu92Fr1MmYUtfBBc4.woff2\") format(\"woff2\");\n font-style: normal;\n font-weight: 900;\n font-display: swap;\n}\n/** wrong url/path */\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxK-wrong.woff2\") format(\"woff2\");\n font-style: normal;\n font-weight: 1000;\n font-display: swap;\n}\n\n/* default for body */\nbody{\n font-family: \"Gotham Narrow\";\n font-weight: 400;\n font-size:2em;\n}\n\nh1{\n font-weight: 900\n}\nh1,h2{\n font-size:1.5em\n}\n\nh2,\nstrong{\n font-weight: 700\n}\n\n\n.light{\n font-weight: 100;\n}\n\n.regular{\n font-weight: 400;\n}\n\n.bold{\n font-weight: 900;\n}\n\n.heavy{\n font-weight: 900;\n}\n\n/** doesn't exist **/\n.ultra{\n font-weight: 1000;\n}\n<h1>Font weight 900</h1>\n<h2>Font weight 700</h2>\n<p>Font weight 400 <strong>Font weight 700</strong> <span class=\"light\">Font weight 100</span> <span class=\"ultra\">Font weight 1000 - doesn't exist</span></p>\n\n\n\nMake sure your weights and styles are applied\nMost browsers will \"lazyload\" fonts:\nIf a font isn't used anywhere – it won't be loaded.\nI recommend to set the font-weight:400 as a default for your body.\nSince you have multiple levels of bold you need to specify, if a <strong> element should use font-weight:700 or font-weight:900 (same for headings like h1-h5)\nbody{\n font-family: \"Gotham Narrow\";\n font-weight: 400;\n}\n\nh2,\nstrong{\n font-weight: 700\n}\n\nCommon mistake: relative paths\nPaths might change while compiling your css – e.g. you're combining css snippets via scss/sass.\nCorrupted font files – rather rare\nOnce again – check your dev tools console for logs like these:\n\nFailed to decode downloaded font:\n\n\nOTS parsing error\n\nThese issues usually occur, after file conversions (in less capable applications) like these:\n\nfont format conversions (e.g. ttf to woff2)\ncharacter subsetting\nupload filters (trying to sanitize the uploaded file)\n\n... and sometimes a font file might as well become invalid due to file system corruption.\n",
"what I was saying is the following:\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"assets-new/font/GothamNarrow-Book.eot\") ;\n src: url(\"assets-new/font/GothamNarrow-Book.eot?#iefix\")\n format(\"embedded-opentype\"),\n url(\"assets-new/font/GothamNarrow-Book.woff2\") format(\"woff2\"),\n url(\"assets-new/font/GothamNarrow-Book.woff\") format(\"woff\"),\n url(\"assets-new/font/GothamNarrow-Book.ttf\") format(\"truetype\"),\n url(\"assets-new/font/GothamNarrow-Book.svg#GothamNarrow-Book\") format(\"svg\");\n\n font-style: 400;\n font-display: swap;\n}\n\n@font-face {\n font-family: \"Gotham Narrow Medium\";\n src: url(\"assets-new/font/GothamNarrow-Medium.eot\")\n ;\n src: url(\"assets-new/font/GothamNarrow-Medium.eot?#iefix\")\n format(\"embedded-opentype\"),\n url(\"assets-new/font/GothamNarrow-Medium.woff2\") format(\"woff2\"),\n url(\"assets-new/font/GothamNarrow-Medium.woff\") format(\"woff\"),\n url(\"assets-new/font/GothamNarrow-Medium.ttf\") format(\"truetype\"),\n url(\"assets-new/font/GothamNarrow-Medium.svg#GothamNarrow-Medium\")\n format(\"svg\");\n\n font-style: 500;\n font-display: swap;\n}\n\ndiv1 {\n font-family: \"Gotham Narrow\";\n}\ndiv2 {\n font-family: \"Gotham Narrow Medium\";\n}\n\nYou could also use css variables (after font face declaration):\n:root {\n --font-primary: \"Gotham Narrow\", sans-serif;\n --font-primary-medium: \"Gotham Narrow Medium\", sans-serif;\n\n}\ndiv1 {\n font-family: var(--font-primary);\n}\ndiv2 {\n font-family: var(--font-primary-medium);\n}\n\n",
"There no one solid answer, everyone helped and thanks everybody. I'm writing right solution. First it must be url not local. Second my font files characters had display problems. Downloaded different font files and its ok now.\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Thin.woff2\") format(\"woff2\");\n font-weight: 100;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Light.woff2\") format(\"woff2\");\n font-weight: 300;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Book.woff2\") format(\"woff2\");\n font-weight: 400;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Medium.woff2\") format(\"woff2\");\n font-weight: 500;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Bold.woff2\") format(\"woff2\");\n font-weight: 700;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Black.woff2\") format(\"woff2\");\n font-weight: 800;\n font-style: normal;\n}\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Ultra.woff2\") format(\"woff2\");\n font-weight: 900;\n font-style: normal;\n}\n\n"
] | [
1,
0,
0
] | [] | [] | [
"cross_browser",
"css",
"font_face",
"font_family",
"fonts"
] | stackoverflow_0074655872_cross_browser_css_font_face_font_family_fonts.txt |
Q:
How to display data from another on UI thread
I am working on a winforms application that plots live data from a tcp/ip connection. I am taking input from a thread (let's say input thread) and storing it as a .csv file which is then used to plot the graph with a button press and am able to do so.
I am having a problem with showing messages on a listbox about the input data I am getting from the input thread. As the listbox is in the UI thread, I am not able to access it from the input thread.
So how can I show messages on listbox from the input thread?
public void input(){ myTimer.Interval = Int32.Parse(sampleRatetxt.Text);//taking input in milliseconds
myTimer.Elapsed += TimerEventProcessor;
myTimer.Start();}private void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
byte[] ba = new byte[52];
int num = 0;
{
NetworkStream stm = tcpclient.GetStream();
if (stm.DataAvailable)
{
num = stm.Read(ba);
loglistbox.Items.Add("bytes read: " + num); //cant access listbox
string datastring = Convert.ToHexString(ba);
loglistbox.Items.Add("recived string: " + datastring); //cant access listbox
DataPacket packetNew = new DataPacket(datastring);
loglstbx.Items.Add("recived single packet: " + packetNew.dataPacket); //cant access listbox
loglstbx.Items.Add("frame Length=" + packetNew.frameLength + " | frame ID=" + packetNew.frameID); //cant access listbox
loglstbx.Items.Add("val1: " + packetNew.val[0]+ " val2: " + packetNew.val[1]); //cant access listbox
loglstbx.Items.Add("val3: " + packetNew.val[2]+ " val4: " + packetNew.val[3]); //cant access listbox
//passes the data recieved only if frame Id matches
if (packetNew.frameID == Int32.Parse(serverIDtxt.Text)) ;
rawSeries1 = packetNew.val;
stm.Flush();
}
}
A:
In general, the answer to "how to display data from another thread" is to use BeginInvoke to marshal the data back onto the UI thread before setting any properties on any UI control. This minimal reproducible example leaves out the TcpClient code in order to focus on the question at hand.
public partial class MainForm : Form
{
public MainForm() => InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
input();
}
System.Timers.Timer myTimer = new System.Timers.Timer();
public void input()
{
myTimer.Interval = 500; // Value for test
myTimer.Elapsed += TimerEventProcessor;
myTimer.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
loglistbox.BeginInvoke((MethodInvoker)delegate
{
loglistbox.Items.Add("received single packet: ");
loglistbox.Items.Add($"frame Length = {_rando.Next(10, 21)}");
});
}
// Test data
Random _rando = new Random(1);
}
| How to display data from another on UI thread | I am working on a winforms application that plots live data from a tcp/ip connection. I am taking input from a thread (let's say input thread) and storing it as a .csv file which is then used to plot the graph with a button press and am able to do so.
I am having a problem with showing messages on a listbox about the input data I am getting from the input thread. As the listbox is in the UI thread, I am not able to access it from the input thread.
So how can I show messages on listbox from the input thread?
public void input(){ myTimer.Interval = Int32.Parse(sampleRatetxt.Text);//taking input in milliseconds
myTimer.Elapsed += TimerEventProcessor;
myTimer.Start();}private void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
byte[] ba = new byte[52];
int num = 0;
{
NetworkStream stm = tcpclient.GetStream();
if (stm.DataAvailable)
{
num = stm.Read(ba);
loglistbox.Items.Add("bytes read: " + num); //cant access listbox
string datastring = Convert.ToHexString(ba);
loglistbox.Items.Add("recived string: " + datastring); //cant access listbox
DataPacket packetNew = new DataPacket(datastring);
loglstbx.Items.Add("recived single packet: " + packetNew.dataPacket); //cant access listbox
loglstbx.Items.Add("frame Length=" + packetNew.frameLength + " | frame ID=" + packetNew.frameID); //cant access listbox
loglstbx.Items.Add("val1: " + packetNew.val[0]+ " val2: " + packetNew.val[1]); //cant access listbox
loglstbx.Items.Add("val3: " + packetNew.val[2]+ " val4: " + packetNew.val[3]); //cant access listbox
//passes the data recieved only if frame Id matches
if (packetNew.frameID == Int32.Parse(serverIDtxt.Text)) ;
rawSeries1 = packetNew.val;
stm.Flush();
}
}
| [
"In general, the answer to \"how to display data from another thread\" is to use BeginInvoke to marshal the data back onto the UI thread before setting any properties on any UI control. This minimal reproducible example leaves out the TcpClient code in order to focus on the question at hand.\npublic partial class MainForm : Form\n{\n public MainForm() => InitializeComponent();\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n input();\n }\n System.Timers.Timer myTimer = new System.Timers.Timer();\n public void input()\n {\n myTimer.Interval = 500; // Value for test\n myTimer.Elapsed += TimerEventProcessor;\n myTimer.Start();\n }\n\n private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)\n {\n loglistbox.BeginInvoke((MethodInvoker)delegate\n {\n loglistbox.Items.Add(\"received single packet: \");\n loglistbox.Items.Add($\"frame Length = {_rando.Next(10, 21)}\");\n });\n }\n // Test data\n Random _rando = new Random(1);\n}\n\n\n"
] | [
2
] | [] | [] | [
"c#",
"multithreading",
"winforms"
] | stackoverflow_0074671754_c#_multithreading_winforms.txt |
Q:
PHP Parsing JSON to HTML Table multi dimensional arrays
I have the following JSON Data:
{
"tables": [
{
"name": "PrimaryResult",
"columns": [
{
"name": "TimeGenerated",
"type": "datetime"
},
{
"name": "Computer",
"type": "string"
}
],
"rows": [
[
"2022-12-03T21:58:48.519866Z",
"DESKTOP-KAFCPRF"
],
[
"2022-12-03T21:58:48.5198773Z",
"DESKTOP-KAFCPRF"
]
]
}
]
}
I'm using this to and trying to find a way to parse the columns as tables headers(TH) and the row data as(TR).
This is what I have:
$jsonObjs = json_decode($data, true);
echo "<pre>" . var_dump($jsonObjs) . "</pre>";
foreach($jsonObjs as $a){
foreach($a[0] as $b) {
foreach($b[1] as $key => $value){
echo $key . " : " . $value . "<br />";
}
}
}
but my results are coming up like:
name : Computer
type : string
0 : 2022-12-03T21:58:48.5198773Z
1 : DESKTOP-KAFCPRF
A:
Here is a loop that will go through the columns and rows. From here it's fairly simple to adjust the logic for building a table. If you need any further help, let me know.
foreach($jsonObjs["tables"] as $a)
{
// Columns
foreach($a["columns"] as $key => $value)
{
$cName = $value["name"];
$cType = $value["type"];
echo("Column name is: ".$cName);
echo("Column type is: ".$cType);
}
// Rows:
foreach($a["rows"] as $key => $value)
{
$rValue1 = $value[0];
$rValue2 = $value[1];
echo("Row: " . $rValue1 . " | " . $rValue2);
}
}
| PHP Parsing JSON to HTML Table multi dimensional arrays | I have the following JSON Data:
{
"tables": [
{
"name": "PrimaryResult",
"columns": [
{
"name": "TimeGenerated",
"type": "datetime"
},
{
"name": "Computer",
"type": "string"
}
],
"rows": [
[
"2022-12-03T21:58:48.519866Z",
"DESKTOP-KAFCPRF"
],
[
"2022-12-03T21:58:48.5198773Z",
"DESKTOP-KAFCPRF"
]
]
}
]
}
I'm using this to and trying to find a way to parse the columns as tables headers(TH) and the row data as(TR).
This is what I have:
$jsonObjs = json_decode($data, true);
echo "<pre>" . var_dump($jsonObjs) . "</pre>";
foreach($jsonObjs as $a){
foreach($a[0] as $b) {
foreach($b[1] as $key => $value){
echo $key . " : " . $value . "<br />";
}
}
}
but my results are coming up like:
name : Computer
type : string
0 : 2022-12-03T21:58:48.5198773Z
1 : DESKTOP-KAFCPRF
| [
"Here is a loop that will go through the columns and rows. From here it's fairly simple to adjust the logic for building a table. If you need any further help, let me know.\nforeach($jsonObjs[\"tables\"] as $a)\n {\n // Columns\n foreach($a[\"columns\"] as $key => $value)\n {\n $cName = $value[\"name\"];\n $cType = $value[\"type\"];\n \n echo(\"Column name is: \".$cName);\n echo(\"Column type is: \".$cType);\n }\n \n // Rows:\n foreach($a[\"rows\"] as $key => $value)\n {\n $rValue1 = $value[0];\n $rValue2 = $value[1];\n \n echo(\"Row: \" . $rValue1 . \" | \" . $rValue2);\n }\n }\n\n"
] | [
1
] | [] | [] | [
"arrays",
"json",
"php"
] | stackoverflow_0074672085_arrays_json_php.txt |
Q:
Unable to iterate over nested loop to calculate sum
I am unable find correct logic to find summation. I have binary_values and function as:
binary_values =[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
def f(x):
m = np.matrix([0.5,-0.5, 0.3])
w = m.transpose()
Y = np.dot(x,w)
return Y
f(x)
I have to find summation of
1) f(1,0,0)-f(0,0,0))+(f(1,0,1)-f(0,0,1))+(f(1,1,0)-f(0,1,0))+(f(1,1,1)-f(0,1,1)) #this is for whenever "1" comes in 0th position inside nested loop.
2) (f(0,1,0)-f(0,0,0))+(f(0,1,1)-f(0,0,1))+(f(1,1,0)-f(1,0,0))+(f(1,1,1)-f(1,0,1)) #this is for whenever "1" comes in 1st position
3) (f(0,0,1)-f(0,0,0))+(f(0,1,1)-f(0,1,0))+(f(1,0,1)-f(1,0,0))+(f(1,1,1)-f(1,1,0)) #this is for whenever "1" comes in 2nd position
The code I tried:
sum = 0
for i in binary_values:
for j in i:
if(binary_values[i][0] == 1):
sum = (f(1,0,0)-f(0,0,0))+(f(1,0,1)-f(0,0,1))+(f(1,1,0)-
f(0,1,0))+(f(1,1,1)-f(0,1,1))
elif(binary_values[i][1] == 1):
sum = (f(0,1,0)-f(0,0,0))+(f(0,1,1)-f(0,0,1))+(f(1,1,0)-
f(1,0,0))+(f(1,1,1)-f(1,0,1))
elif(binary_values[i][2] == 1):
sum = (f(0,0,1)-f(0,0,0))+(f(0,1,1)-f(0,1,0))+(f(1,0,1)-
f(1,0,0))+(f(1,1,1)-f(1,1,0))
else:
print("Error")
print(sum)
Please suggest me the better logic
A:
The problem you described is because you do:
for i in binary _values # Will put the value of i to a inner list item like [0,1,1]
then you do:
for j in i # makes j a value inside the inner list like
# 0 - first iteration , 1 - second iteration, 1 - third iteration
and then you try to use i as a position variable for binary_values, but this will not work because i will contain a part of the binary_values list as described.
Does the following code do what you wanted? As well i think if you want to sum up all of them, you will need the += operator to add up the sums... But feel free to describe your problem further and i will edit my answer as well.
Edit Answer (see comments):
import numpy as np
binary_values = [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
def f(x):
m =np.matrix([0.5,-0.5, 0.3])
w = m.transpose()
Y = np.dot(x,w)
return Y[0,0]
sums = {"sum1":0,"sum2":0,"sum3":0,"fullsum1":0,"fullsum2":0,"fullsum3":0,"allsum":0}
for i in binary_values:
if(i[0] == 1):
sums["sum1"] = (f([1,0,0])-f([0,0,0]))+(f([1,0,1])-f([0,0,1]))+(f([1,1,0])-f([0,1,0]))+(f([1,1,1])-f([0,1,1]))
if(i[1] == 1):
sums["sum2"] = (f([0,1,0])-f([0,0,0]))+(f([0,1,1])-f([0,0,1]))+(f([1,1,0])-f([1,0,0]))+(f([1,1,1])-f([1,0,1]))
if(i[2] == 1):
sums["sum3"] = (f([0,0,1])-f([0,0,0]))+(f([0,1,1])-f([0,1,0]))+(f([1,0,1])-f([1,0,0]))+(f([1,1,1])-f([1,1,0]))
sums["fullsum1"] += sums["sum1"]
sums["fullsum2"] += sums["sum2"]
sums["fullsum3"] += sums["sum3"]
sums["allsum"] += sums["sum1"] + sums["sum2"] + sums["sum3"]
print("For:", i)
print(f" Result Sum i[1] = %8.2f ; Result Sum i[2] = %8.2f ; Result Sum i[3] = %8.2f" % (sums["sum1"],sums["sum2"],sums["sum3"]))
print(f" Sum of i[1] = %8.2f ; Sum of i[2] = %8.2f ; Sum of i[3] = %8.2f" % (sums["fullsum1"],sums["fullsum2"],sums["fullsum3"]))
print(f" All sum up = %8.2f" % (sums["allsum"]))
print()
print("Final:")
print(f"Result Sum i[1] = %8.2f ; Result Sum i[2] = %8.2f ; Result Sum i[3] = %8.2f" % (sums["sum1"],sums["sum2"],sums["sum3"]))
print(f" Sum of i[1] = %8.2f ; Sum of i[2] = %8.2f ; Sum of i[3] = %8.2f" % (sums["fullsum1"],sums["fullsum2"],sums["fullsum3"]))
print(f" All sum up = %8.2f" % (sums["allsum"]))
Edit:
There was another mistake, i forget to add to my answer.
In your code you tried to call the function f(x) with 3 values like (1,0,0), but the argument list contains takes only a single value for x. So you could the three values into a single list to pass them in this way... Otherwise it will end up into a:
TypeError: f() takes 1 positional argument but 3 were given
| Unable to iterate over nested loop to calculate sum | I am unable find correct logic to find summation. I have binary_values and function as:
binary_values =[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
def f(x):
m = np.matrix([0.5,-0.5, 0.3])
w = m.transpose()
Y = np.dot(x,w)
return Y
f(x)
I have to find summation of
1) f(1,0,0)-f(0,0,0))+(f(1,0,1)-f(0,0,1))+(f(1,1,0)-f(0,1,0))+(f(1,1,1)-f(0,1,1)) #this is for whenever "1" comes in 0th position inside nested loop.
2) (f(0,1,0)-f(0,0,0))+(f(0,1,1)-f(0,0,1))+(f(1,1,0)-f(1,0,0))+(f(1,1,1)-f(1,0,1)) #this is for whenever "1" comes in 1st position
3) (f(0,0,1)-f(0,0,0))+(f(0,1,1)-f(0,1,0))+(f(1,0,1)-f(1,0,0))+(f(1,1,1)-f(1,1,0)) #this is for whenever "1" comes in 2nd position
The code I tried:
sum = 0
for i in binary_values:
for j in i:
if(binary_values[i][0] == 1):
sum = (f(1,0,0)-f(0,0,0))+(f(1,0,1)-f(0,0,1))+(f(1,1,0)-
f(0,1,0))+(f(1,1,1)-f(0,1,1))
elif(binary_values[i][1] == 1):
sum = (f(0,1,0)-f(0,0,0))+(f(0,1,1)-f(0,0,1))+(f(1,1,0)-
f(1,0,0))+(f(1,1,1)-f(1,0,1))
elif(binary_values[i][2] == 1):
sum = (f(0,0,1)-f(0,0,0))+(f(0,1,1)-f(0,1,0))+(f(1,0,1)-
f(1,0,0))+(f(1,1,1)-f(1,1,0))
else:
print("Error")
print(sum)
Please suggest me the better logic
| [
"The problem you described is because you do:\nfor i in binary _values # Will put the value of i to a inner list item like [0,1,1]\n\nthen you do:\nfor j in i # makes j a value inside the inner list like\n # 0 - first iteration , 1 - second iteration, 1 - third iteration \n\nand then you try to use i as a position variable for binary_values, but this will not work because i will contain a part of the binary_values list as described.\nDoes the following code do what you wanted? As well i think if you want to sum up all of them, you will need the += operator to add up the sums... But feel free to describe your problem further and i will edit my answer as well.\nEdit Answer (see comments):\nimport numpy as np\n\nbinary_values = [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]\n\ndef f(x):\n m =np.matrix([0.5,-0.5, 0.3])\n w = m.transpose()\n Y = np.dot(x,w)\n return Y[0,0]\n\nsums = {\"sum1\":0,\"sum2\":0,\"sum3\":0,\"fullsum1\":0,\"fullsum2\":0,\"fullsum3\":0,\"allsum\":0}\n\nfor i in binary_values:\n if(i[0] == 1):\n sums[\"sum1\"] = (f([1,0,0])-f([0,0,0]))+(f([1,0,1])-f([0,0,1]))+(f([1,1,0])-f([0,1,0]))+(f([1,1,1])-f([0,1,1]))\n if(i[1] == 1):\n sums[\"sum2\"] = (f([0,1,0])-f([0,0,0]))+(f([0,1,1])-f([0,0,1]))+(f([1,1,0])-f([1,0,0]))+(f([1,1,1])-f([1,0,1]))\n if(i[2] == 1):\n sums[\"sum3\"] = (f([0,0,1])-f([0,0,0]))+(f([0,1,1])-f([0,1,0]))+(f([1,0,1])-f([1,0,0]))+(f([1,1,1])-f([1,1,0]))\n\n sums[\"fullsum1\"] += sums[\"sum1\"]\n sums[\"fullsum2\"] += sums[\"sum2\"]\n sums[\"fullsum3\"] += sums[\"sum3\"]\n\n sums[\"allsum\"] += sums[\"sum1\"] + sums[\"sum2\"] + sums[\"sum3\"]\n\n print(\"For:\", i)\n print(f\" Result Sum i[1] = %8.2f ; Result Sum i[2] = %8.2f ; Result Sum i[3] = %8.2f\" % (sums[\"sum1\"],sums[\"sum2\"],sums[\"sum3\"]))\n print(f\" Sum of i[1] = %8.2f ; Sum of i[2] = %8.2f ; Sum of i[3] = %8.2f\" % (sums[\"fullsum1\"],sums[\"fullsum2\"],sums[\"fullsum3\"]))\n print(f\" All sum up = %8.2f\" % (sums[\"allsum\"]))\n print()\n\nprint(\"Final:\")\nprint(f\"Result Sum i[1] = %8.2f ; Result Sum i[2] = %8.2f ; Result Sum i[3] = %8.2f\" % (sums[\"sum1\"],sums[\"sum2\"],sums[\"sum3\"]))\nprint(f\" Sum of i[1] = %8.2f ; Sum of i[2] = %8.2f ; Sum of i[3] = %8.2f\" % (sums[\"fullsum1\"],sums[\"fullsum2\"],sums[\"fullsum3\"]))\nprint(f\" All sum up = %8.2f\" % (sums[\"allsum\"]))\n\nEdit:\nThere was another mistake, i forget to add to my answer.\nIn your code you tried to call the function f(x) with 3 values like (1,0,0), but the argument list contains takes only a single value for x. So you could the three values into a single list to pass them in this way... Otherwise it will end up into a:\nTypeError: f() takes 1 positional argument but 3 were given\n\n"
] | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074671984_numpy_python.txt |
Q:
nightmare do not scrape information
I am building an amazon price tracker, and using node.js with the module nightmare for web scraping.
this is the amazon page that i want to scrape information from https://www.amazon.in//dp/B0BDKD8DVD/.
My code just returns a NULL value instead of returning the price of the product.
This is My app.js code
const express = require("express")
const parser = require("./parser")
const app = express();
app.listen(3000, () => {
console.log("listening on port 3000")
})
app.get("/", (req, res) => {
const ans = parser();
res.send(ans)
})
and this is my parser.js code
const nightmare = require("nightmare")();
async function checkprice() {
const priceString = await nightmare
.goto("https://www.amazon.in/Apple-AirPods-Pro-2nd-Generation/dp/B0BDKD8DVD/ref=sr_1_5")
.wait(".a-offscreen")
.evaluate(() => document.getElementsByClassName("a-price-whole").innerText)
.end
const priceNumber = parseFloat(priceString)
console.log(priceNumber)
return priceNumber
};
module.exports = checkprice;
this is returning NaN and not price.
Any advice could be really helpful. Thankyou.
A:
Your element return Undefined
document.getElementsByClassName("a-price-whole").innerText
Correct one would be
document.getElementsByClassName("a-price-whole")[0].innerText
Take note that their 6 div with this Class Name and that return new line '26,600\n.'
| nightmare do not scrape information | I am building an amazon price tracker, and using node.js with the module nightmare for web scraping.
this is the amazon page that i want to scrape information from https://www.amazon.in//dp/B0BDKD8DVD/.
My code just returns a NULL value instead of returning the price of the product.
This is My app.js code
const express = require("express")
const parser = require("./parser")
const app = express();
app.listen(3000, () => {
console.log("listening on port 3000")
})
app.get("/", (req, res) => {
const ans = parser();
res.send(ans)
})
and this is my parser.js code
const nightmare = require("nightmare")();
async function checkprice() {
const priceString = await nightmare
.goto("https://www.amazon.in/Apple-AirPods-Pro-2nd-Generation/dp/B0BDKD8DVD/ref=sr_1_5")
.wait(".a-offscreen")
.evaluate(() => document.getElementsByClassName("a-price-whole").innerText)
.end
const priceNumber = parseFloat(priceString)
console.log(priceNumber)
return priceNumber
};
module.exports = checkprice;
this is returning NaN and not price.
Any advice could be really helpful. Thankyou.
| [
"Your element return Undefined\ndocument.getElementsByClassName(\"a-price-whole\").innerText\nCorrect one would be\ndocument.getElementsByClassName(\"a-price-whole\")[0].innerText\nTake note that their 6 div with this Class Name and that return new line '26,600\\n.'\n"
] | [
0
] | [] | [] | [
"javascript",
"nightmare",
"node.js",
"node_modules"
] | stackoverflow_0074668276_javascript_nightmare_node.js_node_modules.txt |
Q:
@font-weight only working bold ---font-weight:600---
Font family is running. But font weight doesnt work properly. For example I added font-weight:400 or 100,etc to h3-h4,etc its doesnt work. Only one font weight does work properly and its font-weight:600 I am completely done, I am researching for two days, I'm asking my friends but my problem still here. I think my @font-face's setups are true. Bu I dont know.. Please anyone can help me?
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-thin-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-thin-webfont.woff") format("woff");
font-weight: 100;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-light-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-light-webfont.woff") format("woff");
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-book-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-book-webfont.woff") format("woff");
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-medium-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-medium-webfont.woff") format("woff");
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-bold-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-bold-webfont.woff") format("woff");
font-weight: 700;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-ultra-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-ultra-webfont.woff") format("woff");
font-weight: 800;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-black-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-black-webfont.woff") format("woff");
font-weight: 900;
font-style: normal;
}
A:
Can you try src: url("...") instead of local:
and woff is not really needed, because all browsers supporting woff also support woff2...
@font-face {
font-family: "Gotham Narrow";
src: url("../font/gothamnarrow-thin-webfont.woff2") format("woff2");
font-weight: 100;
font-style: normal;
}
A:
Ok than please try if a google font also not works?
@font-face {
font-family: 'Poppins';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(https://fonts.gstatic.com/s/poppins/v20/pxiByp8kv8JHgFVrLDz8Z1xlFQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
A:
First my font files has issue, some characters are displayed incorrectly. So I download fonts another site and ıts ok now. Second ıt has to be url() not local()
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Thin.woff2") format("woff2");
font-weight: 100;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Light.woff2") format("woff2");
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Book.woff2") format("woff2");
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Medium.woff2") format("woff2");
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Bold.woff2") format("woff2");
font-weight: 700;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Black.woff2") format("woff2");
font-weight: 800;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: url("../font/GothamNarrow-Ultra.woff2") format("woff2");
font-weight: 900;
font-style: normal;
}
| @font-weight only working bold ---font-weight:600--- | Font family is running. But font weight doesnt work properly. For example I added font-weight:400 or 100,etc to h3-h4,etc its doesnt work. Only one font weight does work properly and its font-weight:600 I am completely done, I am researching for two days, I'm asking my friends but my problem still here. I think my @font-face's setups are true. Bu I dont know.. Please anyone can help me?
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-thin-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-thin-webfont.woff") format("woff");
font-weight: 100;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-light-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-light-webfont.woff") format("woff");
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-book-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-book-webfont.woff") format("woff");
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-medium-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-medium-webfont.woff") format("woff");
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-bold-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-bold-webfont.woff") format("woff");
font-weight: 700;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-ultra-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-ultra-webfont.woff") format("woff");
font-weight: 800;
font-style: normal;
}
@font-face {
font-family: "Gotham Narrow";
src: local("../font/gothamnarrow-black-webfont.woff2") format("woff2"),
local("../font/gothamnarrow-black-webfont.woff") format("woff");
font-weight: 900;
font-style: normal;
}
| [
"Can you try src: url(\"...\") instead of local:\nand woff is not really needed, because all browsers supporting woff also support woff2...\n\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/gothamnarrow-thin-webfont.woff2\") format(\"woff2\");\n font-weight: 100;\n font-style: normal;\n}\n\n\n\n",
"Ok than please try if a google font also not works?\n\n\n@font-face {\n font-family: 'Poppins';\n font-style: normal;\n font-weight: 300;\n font-display: swap;\n src: url(https://fonts.gstatic.com/s/poppins/v20/pxiByp8kv8JHgFVrLDz8Z1xlFQ.woff2) format('woff2');\n unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;\n}\n\n\n\n",
"First my font files has issue, some characters are displayed incorrectly. So I download fonts another site and ıts ok now. Second ıt has to be url() not local()\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Thin.woff2\") format(\"woff2\");\n font-weight: 100;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Light.woff2\") format(\"woff2\");\n font-weight: 300;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Book.woff2\") format(\"woff2\");\n font-weight: 400;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Medium.woff2\") format(\"woff2\");\n font-weight: 500;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Bold.woff2\") format(\"woff2\");\n font-weight: 700;\n font-style: normal;\n}\n\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Black.woff2\") format(\"woff2\");\n font-weight: 800;\n font-style: normal;\n}\n@font-face {\n font-family: \"Gotham Narrow\";\n src: url(\"../font/GothamNarrow-Ultra.woff2\") format(\"woff2\");\n font-weight: 900;\n font-style: normal;\n}\n\n"
] | [
1,
1,
0
] | [] | [] | [
"css",
"font_face",
"font_family",
"fonts",
"javascript"
] | stackoverflow_0074662528_css_font_face_font_family_fonts_javascript.txt |
Q:
Error with repository injection in kafka consumer class
Im trying to run a simple spring boot application that just takes a message from kafka and saves in a db2 database.
The problem comes up when im trying to inject my repository in the consumer class!
@Service
@Slf4j
@AllArgsConstructor
public class KafkaConsumer {
private PortalOneRepository portalOneRepository;
private ObjectMapper objectMapper;
@KafkaListener(topics = "topicout")
public void consumeEventHubMessage(String consumerMessage) {
log.info("Received message from kafka queue: {}", consumerMessage);
//Convert string message to java object
try {
DocumentONE[] documentOne = objectMapper.readValue(consumerMessage, DocumentONE[].class);
//Salvar cada mensagem no db2
portalOneRepository.saveAll(Arrays.asList(documentOne));
} catch (JsonProcessingException e) {
log.error("Error receiving message: " + e.getMessage());
}
}
}
And this is my repository:
@Repository
public interface PortalOneRepository extends JpaRepository<DocumentONE, Long> {
}
So after run it shows the following error message:
*************************** APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in
br.examplestream.eventhub.KafkaConsumer required a
bean of type
'br.examplestream.repository.PortalOneRepository'
that could not be found.
Action:
Consider defining a bean of type
'br.examplestream.repository.PortalOneRepository' in
your configuration.
I tried the config solution class but it shows a cyclic dependency injection problem:
> ***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
kafkaConsumer defined in file [Z:\Users\romulo.domingos\IdeaProjects\portal-one-stream\target\classes\br\examplestream\eventhub\KafkaConsumer.class]
┌─────┐
| getPortalOneRepository defined in class path resource [br/examplestream/config/PortalOneConfig.class]
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
This is the config class that i´ve tried :
@Configuration
public class PortalOneConfig {
private PortalOneRepository portalOneRepository;
@Autowired
ApplicationContext context;
@Bean
public PortalOneRepository getPortalOneRepository(){
return context.getBean(PortalOneRepository.class);
}
}
What is the correct way to inject my repository into my consumer class?
A:
Problem solved.
The problem is caused by a property in application.yml file
autoconfigure: delete:
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
After removing the application starts to run normally again.
| Error with repository injection in kafka consumer class | Im trying to run a simple spring boot application that just takes a message from kafka and saves in a db2 database.
The problem comes up when im trying to inject my repository in the consumer class!
@Service
@Slf4j
@AllArgsConstructor
public class KafkaConsumer {
private PortalOneRepository portalOneRepository;
private ObjectMapper objectMapper;
@KafkaListener(topics = "topicout")
public void consumeEventHubMessage(String consumerMessage) {
log.info("Received message from kafka queue: {}", consumerMessage);
//Convert string message to java object
try {
DocumentONE[] documentOne = objectMapper.readValue(consumerMessage, DocumentONE[].class);
//Salvar cada mensagem no db2
portalOneRepository.saveAll(Arrays.asList(documentOne));
} catch (JsonProcessingException e) {
log.error("Error receiving message: " + e.getMessage());
}
}
}
And this is my repository:
@Repository
public interface PortalOneRepository extends JpaRepository<DocumentONE, Long> {
}
So after run it shows the following error message:
*************************** APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in
br.examplestream.eventhub.KafkaConsumer required a
bean of type
'br.examplestream.repository.PortalOneRepository'
that could not be found.
Action:
Consider defining a bean of type
'br.examplestream.repository.PortalOneRepository' in
your configuration.
I tried the config solution class but it shows a cyclic dependency injection problem:
> ***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
kafkaConsumer defined in file [Z:\Users\romulo.domingos\IdeaProjects\portal-one-stream\target\classes\br\examplestream\eventhub\KafkaConsumer.class]
┌─────┐
| getPortalOneRepository defined in class path resource [br/examplestream/config/PortalOneConfig.class]
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
This is the config class that i´ve tried :
@Configuration
public class PortalOneConfig {
private PortalOneRepository portalOneRepository;
@Autowired
ApplicationContext context;
@Bean
public PortalOneRepository getPortalOneRepository(){
return context.getBean(PortalOneRepository.class);
}
}
What is the correct way to inject my repository into my consumer class?
| [
"Problem solved.\nThe problem is caused by a property in application.yml file\nautoconfigure: delete:\n\norg.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration\n\n\nAfter removing the application starts to run normally again.\n"
] | [
0
] | [] | [] | [
"circular_dependency",
"spring_boot"
] | stackoverflow_0074547990_circular_dependency_spring_boot.txt |
Q:
Docker - Bind for 0.0.0.0:3306 failed: port is already allocated
When I run image "mysql" after my container I see this error "Bind for 0.0.0.0:3306 failed: port is already allocated". `it means I have something that uses port 3306.
After running this command,
docker container ls
I clearly see image "mysql/mysql-server:8.0" that uses 3306 port.
If I just delete it with this command,
docker rm -f <container-name>
I can run my"mysql" and everything works fine! But when I stop container and run again I see the same problem, because "mysql/mysql-server:8.0" uses 3306 again. How can I fix this, without removing this image every time running a container?
A:
When a container stops, Docker keeps it around in case you want to look at the logs or the contents of the container file system. If you don't need that and you want Docker to remove the container completely when it stops, you can add the --rm option to the docker run command, like this
docker run --rm -p 3306:3306 mysql
Then, when the container stop, Docker will remove it and free up port 3306, so you can use it again.
| Docker - Bind for 0.0.0.0:3306 failed: port is already allocated | When I run image "mysql" after my container I see this error "Bind for 0.0.0.0:3306 failed: port is already allocated". `it means I have something that uses port 3306.
After running this command,
docker container ls
I clearly see image "mysql/mysql-server:8.0" that uses 3306 port.
If I just delete it with this command,
docker rm -f <container-name>
I can run my"mysql" and everything works fine! But when I stop container and run again I see the same problem, because "mysql/mysql-server:8.0" uses 3306 again. How can I fix this, without removing this image every time running a container?
| [
"When a container stops, Docker keeps it around in case you want to look at the logs or the contents of the container file system. If you don't need that and you want Docker to remove the container completely when it stops, you can add the --rm option to the docker run command, like this\ndocker run --rm -p 3306:3306 mysql\n\nThen, when the container stop, Docker will remove it and free up port 3306, so you can use it again.\n"
] | [
0
] | [] | [] | [
"docker",
"laravel",
"macos",
"mysql"
] | stackoverflow_0074672033_docker_laravel_macos_mysql.txt |
Q:
Undefined Array Key on php
i got an error undefined array key for 'id_post', i use this href for delete method
<?php
require 'koneksi.php';
$blogs = new blog();
$no = 1;
foreach ($blogs->show() as $b) {
?>
<button type="button"><a href="proses.php?aksi=hapus&id=<?= $b['id_post'] ?>">Hapus</a></button>
<?php }; ?>
here the proses.php file
<?php
include 'koneksi.php';
$blog = new blog();
$kat = new kat();
$aksi = $_GET['aksi'];
if ($aksi == "hapus") {
$blog->hapus($_GET['id_post']);
}
and here the function
public function hapus($id_post)
{
$connect = mysqli_connect($this->host, $this->uname, $this->pw, $this->db);
mysqli_query($connect, "DELETE FROM blog WHERE id_post='$id_post'");
}
and i've tried to using something like this on the function but still nothing change
public function hapus($id_post)
{
$connect = mysqli_connect($this->host, $this->uname, $this->pw, $this->db);
if (isset($_GET['id_post'])) {
$id = $_GET[$id_post];
mysqli_query($connect, "DELETE FROM blog WHERE id_post='$id'");
}
}
i've tried the same code before and it's working, but now it's got some error. please give me some enlightenment
| Undefined Array Key on php | i got an error undefined array key for 'id_post', i use this href for delete method
<?php
require 'koneksi.php';
$blogs = new blog();
$no = 1;
foreach ($blogs->show() as $b) {
?>
<button type="button"><a href="proses.php?aksi=hapus&id=<?= $b['id_post'] ?>">Hapus</a></button>
<?php }; ?>
here the proses.php file
<?php
include 'koneksi.php';
$blog = new blog();
$kat = new kat();
$aksi = $_GET['aksi'];
if ($aksi == "hapus") {
$blog->hapus($_GET['id_post']);
}
and here the function
public function hapus($id_post)
{
$connect = mysqli_connect($this->host, $this->uname, $this->pw, $this->db);
mysqli_query($connect, "DELETE FROM blog WHERE id_post='$id_post'");
}
and i've tried to using something like this on the function but still nothing change
public function hapus($id_post)
{
$connect = mysqli_connect($this->host, $this->uname, $this->pw, $this->db);
if (isset($_GET['id_post'])) {
$id = $_GET[$id_post];
mysqli_query($connect, "DELETE FROM blog WHERE id_post='$id'");
}
}
i've tried the same code before and it's working, but now it's got some error. please give me some enlightenment
| [] | [] | [
"The error you're getting is because you're trying to access the id_post key in the $_GET array, but it doesn't exist. This is because you're passing the id parameter as id= in the HTML, but you're trying to access it as $_GET['id_post'] in the PHP code.\nTo fix this, you can either change the HTML to use id_post instead of id, like this:\n<button type=\"button\"><a href=\"proses.php?aksi=hapus&id_post=<?= $b['id_post'] ?>\">Hapus</a></button>\n\nOr you can change the PHP code to use $_GET['id'] instead of $_GET['id_post'], like this:\npublic function hapus($id_post)\n{\n $connect = mysqli_connect($this->host, $this->uname, $this->pw, $this->db);\n mysqli_query($connect, \"DELETE FROM blog WHERE id_post='$_GET['id']'\");\n}\n\nBoth of these changes should fix the error you're seeing. Let me know if you have any other questions.\n"
] | [
-1
] | [
"arrays",
"php"
] | stackoverflow_0074672200_arrays_php.txt |
Q:
SPARQL question matching schema and data in triple
If there is a Class animal in the RDF Store, the properties of animal are NumberOfLegs, height, and age.
There are instance dog and cat, dog.NumberOfLegs = 4, dog.height = 10, dog.age = 2, cat.NumberOfLegs = 4, cat.height = 10, cat.Suppose age=3
The schema will be as follows
ex:animal rdf:type rdf:Class
ex:animal rdfs:subClassof exs:Package_animal
ex:animal.height rdf:type rdf:Property
ex:animal.height rdfs:label "height"
ex:animal.height rdfs:domain exams:Animal
The data will be as follows
ex:dog rdf:type exams:Animal
ex:dog exam:animal.height "10"
ex:dog exam:animal.age "2"
ex:dog exam:animal.NumberOfLegs "4"
ex:cat rdf:type exams:Animal
ex:cat exam:animal.height "10"
ex:cat exam:animal.age "3"
ex:cat exam:animal.NumberOfLegs "4"
I'm not sure if this is grammatically correct, but what I want to do is 1. Use SPARQL to find the properties of the class (for example, animl.height, age, NumberOfLegs). 2. Find an instance called dog and find that
ex:dog rdf:type exams:Animal ex:dog exam:animal.height "10" ex:dog exam:animal.age "2" ex:dog exam:animal.NumberOfLegs "4"
The SPARQL I thought was as follows
SELECT ?s
WHERE{
?P type Property
?s ?P y
?s type dog.
}
A:
This query
SELECT ?propertyName ?value
WHERE
{
ex:dog ?propertyName ?value.
}
will give you this result
propertyName value
rdf:type ex:animal
ex:height "10"
ex:age "2"
ex:NumberOfLegs "4"
You can bound ex:dog URI if you want it in the result
SELECT ?dog ?propertyName ?value
WHERE
{
BIND(ex:dog as ?dog).
?dog rdf:type ex:animal.
?dog ?propertyName ?value.
}
which will yield
dog propertyName value
ex:dog rdf:type ex:animal
ex:dog ex:height "10"
ex:dog ex:age "2"
ex:dog ex:NumberOfLegs "4"
If you want to grab all properties of ex:animal you'd need to change your data.
I edited your question so it contains the data shown below.
For scheme knowledge:
ex:animal rdf:type rdf:Class;
rdfs:subClassof ex:Package_animal.
ex:height rdf:type rdf:Property;
rdfs:label "height";
rdfs:domain ex:animal.
ex:age rdf:type rdf:Property;
rdfs:label "age";
rdfs:domain ex:animal.
ex:NumberOfLegs rdf:type rdf:Property;
rdfs:label "NumberOfLegs";
rdfs:domain ex:animal.
For instances knowledge:
ex:dog rdf:type ex:animal;
ex:height "10";
ex:age "2";
ex:NumberOfLegs "4".
ex:cat rdf:type ex:animal;
ex:height "10";
ex:age "3";
ex:NumberOfLegs "4".
Then you can use this SPARQL query:
SELECT ?dog ?animalPropertyName ?value
WHERE
{
?animalPropertyName rdfs:domain ex:animal.
BIND(ex:dog as ?dog).
?dog ?animalPropertyName ?value.
}
which will yield
dog animalPropertyName value
ex:dog ex:height "10"
ex:dog ex:age "2"
ex:dog ex:NumberOfLegs "4"
| SPARQL question matching schema and data in triple | If there is a Class animal in the RDF Store, the properties of animal are NumberOfLegs, height, and age.
There are instance dog and cat, dog.NumberOfLegs = 4, dog.height = 10, dog.age = 2, cat.NumberOfLegs = 4, cat.height = 10, cat.Suppose age=3
The schema will be as follows
ex:animal rdf:type rdf:Class
ex:animal rdfs:subClassof exs:Package_animal
ex:animal.height rdf:type rdf:Property
ex:animal.height rdfs:label "height"
ex:animal.height rdfs:domain exams:Animal
The data will be as follows
ex:dog rdf:type exams:Animal
ex:dog exam:animal.height "10"
ex:dog exam:animal.age "2"
ex:dog exam:animal.NumberOfLegs "4"
ex:cat rdf:type exams:Animal
ex:cat exam:animal.height "10"
ex:cat exam:animal.age "3"
ex:cat exam:animal.NumberOfLegs "4"
I'm not sure if this is grammatically correct, but what I want to do is 1. Use SPARQL to find the properties of the class (for example, animl.height, age, NumberOfLegs). 2. Find an instance called dog and find that
ex:dog rdf:type exams:Animal ex:dog exam:animal.height "10" ex:dog exam:animal.age "2" ex:dog exam:animal.NumberOfLegs "4"
The SPARQL I thought was as follows
SELECT ?s
WHERE{
?P type Property
?s ?P y
?s type dog.
}
| [
"This query\nSELECT ?propertyName ?value\nWHERE\n{\n ex:dog ?propertyName ?value.\n}\n\nwill give you this result\npropertyName value\nrdf:type ex:animal\nex:height \"10\"\nex:age \"2\"\nex:NumberOfLegs \"4\"\n\nYou can bound ex:dog URI if you want it in the result\nSELECT ?dog ?propertyName ?value\nWHERE\n{\n BIND(ex:dog as ?dog).\n ?dog rdf:type ex:animal.\n ?dog ?propertyName ?value.\n}\n\nwhich will yield\ndog propertyName value\nex:dog rdf:type ex:animal\nex:dog ex:height \"10\"\nex:dog ex:age \"2\"\nex:dog ex:NumberOfLegs \"4\"\n\nIf you want to grab all properties of ex:animal you'd need to change your data.\nI edited your question so it contains the data shown below.\nFor scheme knowledge:\n ex:animal rdf:type rdf:Class;\n rdfs:subClassof ex:Package_animal.\n\n ex:height rdf:type rdf:Property;\n rdfs:label \"height\";\n rdfs:domain ex:animal.\n\n ex:age rdf:type rdf:Property;\n rdfs:label \"age\";\n rdfs:domain ex:animal.\n\n ex:NumberOfLegs rdf:type rdf:Property;\n rdfs:label \"NumberOfLegs\";\n rdfs:domain ex:animal.\n\nFor instances knowledge:\n ex:dog rdf:type ex:animal;\n ex:height \"10\";\n ex:age \"2\";\n ex:NumberOfLegs \"4\".\n\n ex:cat rdf:type ex:animal;\n ex:height \"10\";\n ex:age \"3\";\n ex:NumberOfLegs \"4\".\n\nThen you can use this SPARQL query:\nSELECT ?dog ?animalPropertyName ?value\nWHERE\n{\n ?animalPropertyName rdfs:domain ex:animal.\n \n BIND(ex:dog as ?dog). \n ?dog ?animalPropertyName ?value.\n}\n\nwhich will yield\ndog animalPropertyName value\nex:dog ex:height \"10\"\nex:dog ex:age \"2\"\nex:dog ex:NumberOfLegs \"4\"\n\n"
] | [
0
] | [] | [] | [
"sparql",
"triples",
"triplestore"
] | stackoverflow_0074627369_sparql_triples_triplestore.txt |
Q:
Are these safe to do after the synchronization objects are destroyed?
In a spare-time project of mine, I'm implementing a duplex transcoding framework. The most essential functions I'm writing are Read and Write functions, which are to be called on different threads, to exchange data like Unix Pipe/FIFO.
Because they're on different threads, I need to be sure that they're properly synchronized, and that my use of synchronization APIs are correct.
When encountering EOF, I call pthread_{condvar,mutex}_destroy functions to destroy 2 condition variables and 1 mutex. The 2 condvars are used to blocks the read and write call respectively, until input/output space are available; the mutex is the big mutex that protects the entire duplex object.
The questions are:
Is it safe to signal a condition variable after it had been destroyed?
Is it safe to unlock a mutex after it had been destroyed?
Are there similar guarantees on other threading APIs (such as C11 Threads and C++ Threads)?
A:
Is it safe to signal a condition variable after it had been destroyed?
No. Its docs say:
A destroyed condition variable object can be reinitialized using
pthread_cond_init(); the results of otherwise referencing the object
after it has been destroyed are undefined.
(emphasis added).
Is it safe to unlock a mutex after it had been destroyed?
No. It's docs say:
A destroyed mutex object can be reinitialized using
pthread_mutex_init(); the results of otherwise referencing the
object after it has been destroyed are undefined.
(emphasis added).
Are there similar guarantees on other threading APIs (such as C11
Threads and C++ Threads)?
About using synchronization objects after they have been destroyed? No. Why would there be? These sorts of APIs are for releasing resources. If the synchronization objects rely on resources that require cleanup in the first place, then how does it make sense that they could still function once those resources are released?
Generally speaking, then, before you can tear down synchronization objects such as mutexes and condition variables, you need to ensure that there are no circumstances under which any current thread could attempt to access them again. At least, not until after they have been re-initialized (in a framework where that is even possible). Under some circumstances it is reasonable simply not to tear them down at all. Otherwise, you need to be more creative.
A:
This is not safe. Destroy will destroy any shared memory used by these objects. The solution to your problem is to join all the threads that are using your your mutexes and cond-vars (except one) and only then destroy them.
| Are these safe to do after the synchronization objects are destroyed? | In a spare-time project of mine, I'm implementing a duplex transcoding framework. The most essential functions I'm writing are Read and Write functions, which are to be called on different threads, to exchange data like Unix Pipe/FIFO.
Because they're on different threads, I need to be sure that they're properly synchronized, and that my use of synchronization APIs are correct.
When encountering EOF, I call pthread_{condvar,mutex}_destroy functions to destroy 2 condition variables and 1 mutex. The 2 condvars are used to blocks the read and write call respectively, until input/output space are available; the mutex is the big mutex that protects the entire duplex object.
The questions are:
Is it safe to signal a condition variable after it had been destroyed?
Is it safe to unlock a mutex after it had been destroyed?
Are there similar guarantees on other threading APIs (such as C11 Threads and C++ Threads)?
| [
"\n\nIs it safe to signal a condition variable after it had been destroyed?\n\n\nNo. Its docs say:\n\nA destroyed condition variable object can be reinitialized using\npthread_cond_init(); the results of otherwise referencing the object\nafter it has been destroyed are undefined.\n\n(emphasis added).\n\n\n\nIs it safe to unlock a mutex after it had been destroyed?\n\n\nNo. It's docs say:\n\nA destroyed mutex object can be reinitialized using\npthread_mutex_init(); the results of otherwise referencing the\nobject after it has been destroyed are undefined.\n\n(emphasis added).\n\n\n\nAre there similar guarantees on other threading APIs (such as C11\nThreads and C++ Threads)?\n\n\nAbout using synchronization objects after they have been destroyed? No. Why would there be? These sorts of APIs are for releasing resources. If the synchronization objects rely on resources that require cleanup in the first place, then how does it make sense that they could still function once those resources are released?\nGenerally speaking, then, before you can tear down synchronization objects such as mutexes and condition variables, you need to ensure that there are no circumstances under which any current thread could attempt to access them again. At least, not until after they have been re-initialized (in a framework where that is even possible). Under some circumstances it is reasonable simply not to tear them down at all. Otherwise, you need to be more creative.\n",
"This is not safe. Destroy will destroy any shared memory used by these objects. The solution to your problem is to join all the threads that are using your your mutexes and cond-vars (except one) and only then destroy them.\n"
] | [
2,
1
] | [] | [] | [
"c",
"condition_variable",
"multithreading",
"mutex",
"pthreads"
] | stackoverflow_0074652852_c_condition_variable_multithreading_mutex_pthreads.txt |
Q:
Getting strange and unexpected output from python while loop
I made a simple while loop to increase a number. And then I made a completely separate if condition to print a statement under certain circumstances. I don't understand why the two are being joined together.....
Write a program whose input is two integers. Output the first integer
and subsequent increments of 5 as long as the value is less than or
equal to the second integer.
Ex: If the input is:
-15
10
the output is:
-15 -10 -5 0 5 10
Ex: If the second integer is less than the first as in:
20
5
the output is:
Second integer can't be less than the first.
For coding simplicity, output a space after every integer, including
the last.
My code:
''' Type your code here. '''
firstNum = int(input())
secondNum = int(input())
while firstNum <= secondNum:
print(firstNum, end=" ")
firstNum +=5
if firstNum > secondNum:
print("Second integer can't be less than the first.")
Enter program input (optional)
-15
10
Program output displayed here
-15 -10 -5 0 5 10 Second integer can't be less than the first.
A:
Your while loop is ensuring firstNum > secondNum by the time it finishes running. Then, you check to see if firstNum > secondNum (which it is), and your print statement gets executed.
A:
a = int(input())
b = int(input())
if b < a:
print("Second integer can't be less than the first.",end="")
while a <= b:
print(a, end=" ")
a = a + 5
print("")
| Getting strange and unexpected output from python while loop | I made a simple while loop to increase a number. And then I made a completely separate if condition to print a statement under certain circumstances. I don't understand why the two are being joined together.....
Write a program whose input is two integers. Output the first integer
and subsequent increments of 5 as long as the value is less than or
equal to the second integer.
Ex: If the input is:
-15
10
the output is:
-15 -10 -5 0 5 10
Ex: If the second integer is less than the first as in:
20
5
the output is:
Second integer can't be less than the first.
For coding simplicity, output a space after every integer, including
the last.
My code:
''' Type your code here. '''
firstNum = int(input())
secondNum = int(input())
while firstNum <= secondNum:
print(firstNum, end=" ")
firstNum +=5
if firstNum > secondNum:
print("Second integer can't be less than the first.")
Enter program input (optional)
-15
10
Program output displayed here
-15 -10 -5 0 5 10 Second integer can't be less than the first.
| [
"Your while loop is ensuring firstNum > secondNum by the time it finishes running. Then, you check to see if firstNum > secondNum (which it is), and your print statement gets executed.\n",
"a = int(input())\nb = int(input())\nif b < a:\n print(\"Second integer can't be less than the first.\",end=\"\")\nwhile a <= b:\n print(a, end=\" \")\na = a + 5\nprint(\"\")\n\n"
] | [
2,
0
] | [] | [] | [
"python",
"while_loop"
] | stackoverflow_0072081945_python_while_loop.txt |
Q:
Jquery Move block on mouse move
I need script which would change translateX position depends on mouse position inside of this block.
https://www.peaktwo.com/work/
Here's how it looks on a live website, can't achieve this effect.
Can somebody help to do that on jQuery?
$('.work__main').on("mousemove" ,function(e){
let center = $(window).width()/2;
if ((center - event.pageX) > 0 ) {
$('.work__main').css("transform" , "translateX(-"+ event.pageX/10 +"px)")
} else {
$('.work__main').css("transform" , "translateX(-"+ event.pageX/10 +"px)")
}
});
Here's my code - but when I'm trying to build it like that - when I put my mouse on a center it jumps from one side to another
A:
To fix the issue where the element jumps from one side to another when the mouse is in the center of the screen, you can add an additional check to make sure that the translateX value doesn't exceed a certain threshold.
Here is an example of how you could do that:
$('.work__main').on("mousemove" ,function(e){
let center = $(window).width()/2;
let translateX = -event.pageX / 10; // Calculate the translateX value based on the mouse position
// Limit the translateX value so that it doesn't exceed a certain threshold
if (translateX > 50) {
translateX = 50;
} else if (translateX < -50) {
translateX = -50;
}
// Apply the translateX value to the element
$('.work__main').css("transform" , "translateX(" + translateX + "px)")
});
This will make sure that the element doesn't jump from one side to the other when the mouse is in the center of the screen. You can adjust the threshold value (50 in this example) to your liking.
| Jquery Move block on mouse move | I need script which would change translateX position depends on mouse position inside of this block.
https://www.peaktwo.com/work/
Here's how it looks on a live website, can't achieve this effect.
Can somebody help to do that on jQuery?
$('.work__main').on("mousemove" ,function(e){
let center = $(window).width()/2;
if ((center - event.pageX) > 0 ) {
$('.work__main').css("transform" , "translateX(-"+ event.pageX/10 +"px)")
} else {
$('.work__main').css("transform" , "translateX(-"+ event.pageX/10 +"px)")
}
});
Here's my code - but when I'm trying to build it like that - when I put my mouse on a center it jumps from one side to another
| [
"To fix the issue where the element jumps from one side to another when the mouse is in the center of the screen, you can add an additional check to make sure that the translateX value doesn't exceed a certain threshold.\nHere is an example of how you could do that:\n$('.work__main').on(\"mousemove\" ,function(e){\n let center = $(window).width()/2;\n let translateX = -event.pageX / 10; // Calculate the translateX value based on the mouse position\n\n // Limit the translateX value so that it doesn't exceed a certain threshold\n if (translateX > 50) {\n translateX = 50;\n } else if (translateX < -50) {\n translateX = -50;\n }\n\n // Apply the translateX value to the element\n $('.work__main').css(\"transform\" , \"translateX(\" + translateX + \"px)\")\n});\n\nThis will make sure that the element doesn't jump from one side to the other when the mouse is in the center of the screen. You can adjust the threshold value (50 in this example) to your liking.\n"
] | [
1
] | [] | [] | [
"javascript",
"jquery"
] | stackoverflow_0074672210_javascript_jquery.txt |
Q:
How to add extensions to VS Codium (open source version) from github repos
Lot of VSCode extensions are missing in VSCodium. Looking for a simple way to add the missing extensions from their github repos. Does something like this exist?
I've looked for similar answers but nothing explains a simple way to do this
A:
Found the answer after posting the question
Find the vsix file at https://marketplace.visualstudio.com/, download it
cd ~/Downloads
codium --install-extension clara-copilot-0.0.1.vsix
| How to add extensions to VS Codium (open source version) from github repos | Lot of VSCode extensions are missing in VSCodium. Looking for a simple way to add the missing extensions from their github repos. Does something like this exist?
I've looked for similar answers but nothing explains a simple way to do this
| [
"Found the answer after posting the question\nFind the vsix file at https://marketplace.visualstudio.com/, download it\ncd ~/Downloads\ncodium --install-extension clara-copilot-0.0.1.vsix\n\n"
] | [
0
] | [] | [] | [
"vscodium"
] | stackoverflow_0074672197_vscodium.txt |
Q:
Attaching tabindex to headings
I am currently working on the accesibility of my website, specially for blind people who navigate with screen readers.
I did manage to remove the anchors that should be skipped when navigating with tab by just using tabindex, but I'd like the screen reader software to read a custom text whenever the user navigates to an h1/h2/h3.. tag.
I did try attaching tabindex="1" to the heading tag but It didnt work out.
This is an example of the problem im facing:
List of our services
Web design
Graphic design
Branding
In this current example, the list items are properly read by the screen reader software when navigating with tab because they are anchor tags, but it dodges the "list of our services" heading.
Is there any kind of "alt" attribute that can be attached to headings in order to fix this? If not possible, i'll just add a transparent 1 pixel image before every heading with the alt tag, like this:
<a href="#"><img alt="List of our services" src="/1pixelimage.jpg"></a>
<h2>List of our services</h2>
However, I dont think this is correct and I might be missing the real way to do this.
A:
I was messing up with tabindex value and missing title attribute on headings.
This heading is navigable with tab hotkeys and reproduces audio title for screen readers:
<h2 tabindex="0" title="List of our services">List of our services</h2>
A:
Screen reader users can navigating heading without the need of the tabindex="0". This is a build in feature for screen readers. That is pressing the h key in form modes off. Will navigate to all heading. Pressing the number 1 will navigate to <h1> and 2 will navigate to <h2> and so on if these elements exist on a webpage
Adding the tabindex="0" to heading will not impove the screen reader users experience but will help keyboard users that are not able to navigate heading with the tab key to now access the headings on you page.
I would not advice adding a custome message on your heading elements <h1> <h2> and <h3>. If you want to customise the heading contect I will ask why. Would other uses also find the information provide. Providing a custome message that only screen reader users can see but no other users can cause more harm than good as it could confuse screen reader users who can see. Examples would be
People with low vision
People with cognitive disability
People with other reading disabilities
that use screen readers to help them read the content on a webpage page.
| Attaching tabindex to headings | I am currently working on the accesibility of my website, specially for blind people who navigate with screen readers.
I did manage to remove the anchors that should be skipped when navigating with tab by just using tabindex, but I'd like the screen reader software to read a custom text whenever the user navigates to an h1/h2/h3.. tag.
I did try attaching tabindex="1" to the heading tag but It didnt work out.
This is an example of the problem im facing:
List of our services
Web design
Graphic design
Branding
In this current example, the list items are properly read by the screen reader software when navigating with tab because they are anchor tags, but it dodges the "list of our services" heading.
Is there any kind of "alt" attribute that can be attached to headings in order to fix this? If not possible, i'll just add a transparent 1 pixel image before every heading with the alt tag, like this:
<a href="#"><img alt="List of our services" src="/1pixelimage.jpg"></a>
<h2>List of our services</h2>
However, I dont think this is correct and I might be missing the real way to do this.
| [
"I was messing up with tabindex value and missing title attribute on headings.\nThis heading is navigable with tab hotkeys and reproduces audio title for screen readers:\n<h2 tabindex=\"0\" title=\"List of our services\">List of our services</h2>\n\n",
"Screen reader users can navigating heading without the need of the tabindex=\"0\". This is a build in feature for screen readers. That is pressing the h key in form modes off. Will navigate to all heading. Pressing the number 1 will navigate to <h1> and 2 will navigate to <h2> and so on if these elements exist on a webpage\nAdding the tabindex=\"0\" to heading will not impove the screen reader users experience but will help keyboard users that are not able to navigate heading with the tab key to now access the headings on you page.\nI would not advice adding a custome message on your heading elements <h1> <h2> and <h3>. If you want to customise the heading contect I will ask why. Would other uses also find the information provide. Providing a custome message that only screen reader users can see but no other users can cause more harm than good as it could confuse screen reader users who can see. Examples would be\n\nPeople with low vision\nPeople with cognitive disability\nPeople with other reading disabilities\n\nthat use screen readers to help them read the content on a webpage page.\n"
] | [
1,
0
] | [] | [] | [
"html"
] | stackoverflow_0057891528_html.txt |
Q:
Sorting a Dataframe with alternating positive and negative values in one column
please help me sort df into df1, in other words, I am trying to sort df by col3 ensuring that the values in col3 alternate from positive to negative:
df (original dataframe)
col1 col2 col3
0 1 -1 -38
1 2 -2 45
2 3 -3 79
3 4 -4 -55
4 5 -5 31
5 6 -6 38
6 7 -7 -45
7 8 -8 -79
8 9 -9 55
9 10 -10 -31
10 11 -11 55
11 12 -12 -55
desired dataframe
col1 col2 col3
0 5 -5 31
1 10 -10 -31
2 6 -6 38
3 1 -1 -38
4 2 -2 45
5 7 -7 -45
6 9 -9 55
7 4 -4 -55
8 11 -11 55
9 12 -12 -55
10 3 -3 79
11 8 -8 -79
I tried sorting by col3 and using a lambda function as key and got the below result which is not what I want
`
# first, we need to import the Pandas library
import pandas as pd
# create a sample DataFrame with three columns
df = pd.DataFrame({'col1': [1, 2, 3, 4, 5,6,7,8,9,10,11,12], 'col2': [-1, -2, -3, -4, -5,-6,-7,-8,-9,-10,-11,-12], \
'col3': [-38,45,79,-55,31,38,-45,-79,55,-31,55,-55]})
# sort the 'col3' column in ascending order by the absolute value of each element
df = df.sort_values(by='col3', key=lambda x: abs(x))
`
col1 col2 col3
4 5 -5 31
9 10 -10 -31
0 1 -1 -38
5 6 -6 38
1 2 -2 45
6 7 -7 -45
3 4 -4 -55
8 9 -9 55
10 11 -11 55
11 12 -12 -55
2 3 -3 79
7 8 -8 -79
A:
One way using pandas.DataFrame.groupby then sort_values with multiple colums:
keys = ["abs", "order", "sign"]
s = df["col3"]
df["abs"] = s.abs()
df["order"] = df.groupby(["abs", "col3"]).cumcount()
# If you want positive to come first
df["sign"] = s.lt(0)
# If you want negative to come first
# df["sign"] = s.gt(0)
new_df = df.sort_values(keys).drop(keys, axis=1)
print(new_df)
Output (Positive first):
col1 col2 col3
4 5 -5 31
9 10 -10 -31
5 6 -6 38
0 1 -1 -38
1 2 -2 45
6 7 -7 -45
8 9 -9 55
3 4 -4 -55
10 11 -11 55
11 12 -12 -55
2 3 -3 79
7 8 -8 -79
Output (Negative first):
col1 col2 col3
9 10 -10 -31
4 5 -5 31
0 1 -1 -38
5 6 -6 38
6 7 -7 -45
1 2 -2 45
3 4 -4 -55
8 9 -9 55
11 12 -12 -55
10 11 -11 55
7 8 -8 -79
2 3 -3 79
| Sorting a Dataframe with alternating positive and negative values in one column | please help me sort df into df1, in other words, I am trying to sort df by col3 ensuring that the values in col3 alternate from positive to negative:
df (original dataframe)
col1 col2 col3
0 1 -1 -38
1 2 -2 45
2 3 -3 79
3 4 -4 -55
4 5 -5 31
5 6 -6 38
6 7 -7 -45
7 8 -8 -79
8 9 -9 55
9 10 -10 -31
10 11 -11 55
11 12 -12 -55
desired dataframe
col1 col2 col3
0 5 -5 31
1 10 -10 -31
2 6 -6 38
3 1 -1 -38
4 2 -2 45
5 7 -7 -45
6 9 -9 55
7 4 -4 -55
8 11 -11 55
9 12 -12 -55
10 3 -3 79
11 8 -8 -79
I tried sorting by col3 and using a lambda function as key and got the below result which is not what I want
`
# first, we need to import the Pandas library
import pandas as pd
# create a sample DataFrame with three columns
df = pd.DataFrame({'col1': [1, 2, 3, 4, 5,6,7,8,9,10,11,12], 'col2': [-1, -2, -3, -4, -5,-6,-7,-8,-9,-10,-11,-12], \
'col3': [-38,45,79,-55,31,38,-45,-79,55,-31,55,-55]})
# sort the 'col3' column in ascending order by the absolute value of each element
df = df.sort_values(by='col3', key=lambda x: abs(x))
`
col1 col2 col3
4 5 -5 31
9 10 -10 -31
0 1 -1 -38
5 6 -6 38
1 2 -2 45
6 7 -7 -45
3 4 -4 -55
8 9 -9 55
10 11 -11 55
11 12 -12 -55
2 3 -3 79
7 8 -8 -79
| [
"One way using pandas.DataFrame.groupby then sort_values with multiple colums:\nkeys = [\"abs\", \"order\", \"sign\"]\n\ns = df[\"col3\"]\n\ndf[\"abs\"] = s.abs()\ndf[\"order\"] = df.groupby([\"abs\", \"col3\"]).cumcount()\n\n# If you want positive to come first\ndf[\"sign\"] = s.lt(0)\n\n# If you want negative to come first\n# df[\"sign\"] = s.gt(0)\n\nnew_df = df.sort_values(keys).drop(keys, axis=1)\nprint(new_df)\n\nOutput (Positive first):\n col1 col2 col3\n4 5 -5 31\n9 10 -10 -31\n5 6 -6 38\n0 1 -1 -38\n1 2 -2 45\n6 7 -7 -45\n8 9 -9 55\n3 4 -4 -55\n10 11 -11 55\n11 12 -12 -55\n2 3 -3 79\n7 8 -8 -79\n\nOutput (Negative first):\n col1 col2 col3\n9 10 -10 -31\n4 5 -5 31\n0 1 -1 -38\n5 6 -6 38\n6 7 -7 -45\n1 2 -2 45\n3 4 -4 -55\n8 9 -9 55\n11 12 -12 -55\n10 11 -11 55\n7 8 -8 -79\n2 3 -3 79\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074672188_pandas_python.txt |
Q:
How do i count how many words there are, and ignore same words in a string? (using method)
The code here only shows how many words they are, how do i ignore the words that are the same?
For example, "A long long time ago, I
can still remember", would return 8 instead of 9.
I want it to be a method which takes one parameter s of
type String and returns an int value. And im only allowed to use the bacics, so no hash keys and advance stuff.
public static int mostCommonLetter(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
}
How do i ignore the words that are the same?
A:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String input = "A long long time ago, I can still remember";
String[] words = input.split(" ");
List<String> uniqueWords = new ArrayList<>();
for (String word : words) {
if (!uniqueWords.contains(word)) {
uniqueWords.add(word);
}
}
System.out.println("Number of unique words: " + uniqueWords.size());
}
}
Output: Number of unique words: 8
Basically, what you can do if you're allowed to use data structures like lists and so on, is create a list and put the words of the input sentence in the list if and only if they aren't already there.
A:
General idea:
public int getUniqueWords(String input) {
// Split the string into words using the split() method
String[] words = input.split(" ");
// Create a Set to store the unique words
Set<String> uniqueWords = new HashSet<String>();
// Loop through the words and add them to the Set
for (String word : words) {
uniqueWords.add(word);
}
// Return unique words amount
return uniqueWords.size();
}
Same solution using StreamAPI:
public int getUniqueWords2(String input) {
// here we can safely cast to int, because String can contain at most "max int" chars
return (int) Arrays.stream(input.split(" ")).distinct().count();
}
If it is needed to handle multiple spaces between words, add some cleanup for input:
// remove leading and trailing spaces
cleanInput = input.trim();
// replace multiple spaces with a single space
cleanInput = cleanInput.replaceAll("\\s+", " ");
Considering the requirement "allowed to use the bacics":
hashtable (HashSet) is a basic data structure in algorithms
problem of counting unique items cannot be logically solved without a container holding "aready seen" items, so algorithm could check whether the next item is counted or not
in the role of container in the simplest case could be a list, but that would cause O(n^2) time complexity.
A:
You can use a Set<T> collection type, that can only contains unique values:
public static int getTotalUniqueWords(String input) {
String[] words = input.split(" ");
Set<String> uniqueWords = new HashSet<>();
Collections.addAll(uniqueWords, words);
return uniqueWords.size();
}
or with Streams:
public static long getTotalUniqueWordsStream(String input) {
String[] words = input.split(" ");
return Arrays.stream(words).distinct().count();
}
| How do i count how many words there are, and ignore same words in a string? (using method) | The code here only shows how many words they are, how do i ignore the words that are the same?
For example, "A long long time ago, I
can still remember", would return 8 instead of 9.
I want it to be a method which takes one parameter s of
type String and returns an int value. And im only allowed to use the bacics, so no hash keys and advance stuff.
public static int mostCommonLetter(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
}
How do i ignore the words that are the same?
| [
"import java.util.*;\n\npublic class MyClass {\n public static void main(String args[]) {\n String input = \"A long long time ago, I can still remember\";\n String[] words = input.split(\" \");\n List<String> uniqueWords = new ArrayList<>();\n for (String word : words) {\n if (!uniqueWords.contains(word)) {\n uniqueWords.add(word);\n } \n }\n System.out.println(\"Number of unique words: \" + uniqueWords.size());\n }\n}\n\nOutput: Number of unique words: 8\nBasically, what you can do if you're allowed to use data structures like lists and so on, is create a list and put the words of the input sentence in the list if and only if they aren't already there.\n",
"General idea:\npublic int getUniqueWords(String input) {\n // Split the string into words using the split() method\n String[] words = input.split(\" \");\n\n // Create a Set to store the unique words\n Set<String> uniqueWords = new HashSet<String>();\n\n // Loop through the words and add them to the Set\n for (String word : words) {\n uniqueWords.add(word);\n }\n\n // Return unique words amount\n return uniqueWords.size();\n}\n\nSame solution using StreamAPI:\npublic int getUniqueWords2(String input) {\n // here we can safely cast to int, because String can contain at most \"max int\" chars\n return (int) Arrays.stream(input.split(\" \")).distinct().count();\n}\n\n\nIf it is needed to handle multiple spaces between words, add some cleanup for input:\n// remove leading and trailing spaces\ncleanInput = input.trim();\n\n// replace multiple spaces with a single space\ncleanInput = cleanInput.replaceAll(\"\\\\s+\", \" \"); \n\n\nConsidering the requirement \"allowed to use the bacics\":\n\nhashtable (HashSet) is a basic data structure in algorithms\nproblem of counting unique items cannot be logically solved without a container holding \"aready seen\" items, so algorithm could check whether the next item is counted or not\nin the role of container in the simplest case could be a list, but that would cause O(n^2) time complexity.\n\n",
"You can use a Set<T> collection type, that can only contains unique values:\npublic static int getTotalUniqueWords(String input) {\n String[] words = input.split(\" \");\n Set<String> uniqueWords = new HashSet<>();\n Collections.addAll(uniqueWords, words);\n return uniqueWords.size();\n}\n\nor with Streams:\npublic static long getTotalUniqueWordsStream(String input) {\n String[] words = input.split(\" \");\n return Arrays.stream(words).distinct().count();\n}\n\n"
] | [
1,
1,
0
] | [] | [] | [
"integer",
"java",
"return",
"string"
] | stackoverflow_0074670908_integer_java_return_string.txt |
Q:
Fail Gatsby build if environment variable missing
I have experimented with adding environment variables to my Gatsby project using .env.development and .env.production files and it's working great.
I would like to have my builds fail if one of the environment variables is missing, however I can't seem to see how to enable this functionality.
I have read through the Gatsby environment variables documentation, but can't seem to see how this would work? is this possible?
I believe it uses dotenv/webpack define plugin under the hood.
A:
I’m sure there are other ways to do this, but with some quick tests, this approach seems to be working well for me.
In your gatsby-config.js file, you can choose to explicitly require the dotenv, so you can use those environment variables in your config.
I added the following, and now the Gatsby build will fail unless the specified environment variables are present.
// Load the environment variables, per
// https://www.gatsbyjs.org/docs/environment-variables/#server-side-nodejs
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
})
function checkEnv(envName) {
if (typeof process.env[envName] === 'undefined' || process.env[envName] === '') {
throw `Missing required environment variables: ${envName}`
}
}
try {
checkEnv('NODE_ENV')
checkEnv('EXAMPLE_MISSING_ENV')
checkEnv('EXAMPLE_API_KEY')
} catch (e) {
throw new Error(e)
}
// The rest of the config file
I could imagine customizing this further, ex. logging a warning for a variable with a fallback versus throwing an error for one that is required by your content sourcing plugin or theme. Hope this is helpful as a starting point!
A:
I couldn't find built-in solution for this on Gatsby neither. You may do it manually, but still not too easy.
First problem: If you wanna load your environment from file while running npm script; it can not be loaded right away. But you may trigger a script file, and it can load this environment variables before your check.
lets say build.sh on root directory of project :
source ./.env.development # this line will set env variables
if [ "$API_KEY" = 927349872349798 ] ; then
npm run build
fi
Another problem rises; some developers might want to run it on windows maybe. So better use famous cross-env package.
npm i cross-env
Then everything is ready, add your secure-build :
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write \"**/*.{js,jsx,json,md}\"",
"start": "npm run develop",
"serve": "gatsby serve",
"clean": "gatsby clean",
"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1",
"secure-build": "cross-env-shell \"./build.sh\""
},
And run it :
npm run secure-build
This solution looks too much for me as we created a build.sh and install a new package. Maybe there is cleaner solution. I am not Gatsby Guru after all.
A:
I added env checking to the onPreInit life cycle hook in gatsby-node.ts:
const envVariablesList = [
"ENV1",
"ENV2",
"ENV3",
];
function envVarChecker(vars: string[]): string | undefined {
return vars.find(
(item) => process.env[item] === undefined || process.env[item] === ""
);
}
export const onPreInit: GatsbyNode["onPreInit"] = ({ actions }) => {
const emptyEnv = envVarChecker(envVariablesList);
if (emptyEnv !== undefined) {
throw new Error(`Env variable: ${emptyEnv} is empty!`);
}
};
It fails build almost at the very beginning (during pre-bootstrap phase) if any of the declared variables is missing
| Fail Gatsby build if environment variable missing | I have experimented with adding environment variables to my Gatsby project using .env.development and .env.production files and it's working great.
I would like to have my builds fail if one of the environment variables is missing, however I can't seem to see how to enable this functionality.
I have read through the Gatsby environment variables documentation, but can't seem to see how this would work? is this possible?
I believe it uses dotenv/webpack define plugin under the hood.
| [
"I’m sure there are other ways to do this, but with some quick tests, this approach seems to be working well for me.\nIn your gatsby-config.js file, you can choose to explicitly require the dotenv, so you can use those environment variables in your config.\nI added the following, and now the Gatsby build will fail unless the specified environment variables are present.\n// Load the environment variables, per\n// https://www.gatsbyjs.org/docs/environment-variables/#server-side-nodejs\nrequire('dotenv').config({\n path: `.env.${process.env.NODE_ENV}`,\n})\n\nfunction checkEnv(envName) {\n if (typeof process.env[envName] === 'undefined' || process.env[envName] === '') {\n throw `Missing required environment variables: ${envName}`\n }\n}\n\ntry {\n checkEnv('NODE_ENV')\n checkEnv('EXAMPLE_MISSING_ENV')\n checkEnv('EXAMPLE_API_KEY')\n} catch (e) {\n throw new Error(e)\n}\n\n// The rest of the config file\n\nI could imagine customizing this further, ex. logging a warning for a variable with a fallback versus throwing an error for one that is required by your content sourcing plugin or theme. Hope this is helpful as a starting point!\n",
"I couldn't find built-in solution for this on Gatsby neither. You may do it manually, but still not too easy.\nFirst problem: If you wanna load your environment from file while running npm script; it can not be loaded right away. But you may trigger a script file, and it can load this environment variables before your check.\nlets say build.sh on root directory of project :\nsource ./.env.development # this line will set env variables\nif [ \"$API_KEY\" = 927349872349798 ] ; then\n npm run build\nfi\n\nAnother problem rises; some developers might want to run it on windows maybe. So better use famous cross-env package.\nnpm i cross-env\n\nThen everything is ready, add your secure-build : \n \"scripts\": {\n \"build\": \"gatsby build\",\n \"develop\": \"gatsby develop\",\n \"format\": \"prettier --write \\\"**/*.{js,jsx,json,md}\\\"\",\n \"start\": \"npm run develop\",\n \"serve\": \"gatsby serve\",\n \"clean\": \"gatsby clean\",\n \"test\": \"echo \\\"Write tests! -> https://gatsby.dev/unit-testing\\\" && exit 1\",\n \"secure-build\": \"cross-env-shell \\\"./build.sh\\\"\"\n },\n\n\nAnd run it : \nnpm run secure-build\n\nThis solution looks too much for me as we created a build.sh and install a new package. Maybe there is cleaner solution. I am not Gatsby Guru after all.\n",
"I added env checking to the onPreInit life cycle hook in gatsby-node.ts:\nconst envVariablesList = [\n \"ENV1\",\n \"ENV2\",\n \"ENV3\",\n\n];\n\nfunction envVarChecker(vars: string[]): string | undefined {\n return vars.find(\n (item) => process.env[item] === undefined || process.env[item] === \"\"\n );\n}\n\nexport const onPreInit: GatsbyNode[\"onPreInit\"] = ({ actions }) => {\n const emptyEnv = envVarChecker(envVariablesList);\n if (emptyEnv !== undefined) {\n throw new Error(`Env variable: ${emptyEnv} is empty!`);\n }\n};\n\nIt fails build almost at the very beginning (during pre-bootstrap phase) if any of the declared variables is missing\n"
] | [
3,
1,
0
] | [] | [] | [
"dotenv",
"environment_variables",
"gatsby",
"javascript"
] | stackoverflow_0062345193_dotenv_environment_variables_gatsby_javascript.txt |
Q:
Google Sheets - Convert comma to "#" before generate .CSV
I have the following script in a Google Sheet:
/**
* Create CSV file of Sheet2
* Modified script written by Tanaike
* https://stackoverflow.com/users/7108653/tanaike
*
* Additional Script by AdamD.PE
* version 13.11.2022.1
* https://support.google.com/docs/thread/188230855
*/
/** Date extraction added by Tyrone */
const date = new Date();
/** Extract today's date */
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = `0${month}`;
}
/** Show today's date */
let currentDate = `${day}-${month}-${year}`;
/** Date extraction added by Tyrone */
function sheetToCsvModelo0101() {
var filename = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetName() + "-01" + " - " + currentDate; // CSV file name
filename = filename + '.csv';
var ssid = SpreadsheetApp.getActiveSpreadsheet().getId();
var folders = DriveApp.getFileById(ssid).getParents();
var folder;
if (folders.hasNext()) {
folder = folders.next();
var user = Session.getEffectiveUser().getEmail();
if (!(folder.getOwner().getEmail() == user || folder.getEditors().some(e => e.getEmail() == user))) {
throw new Error("This user has no write permission for the folder.");
}
} else {
throw new Error("This user has no write permission for the folder.");
}
var SelectedRange = "A2:AB3";
var csv = "";
var v = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(SelectedRange).getValues();
v.forEach(function (e) {
csv += e.join(",") + "\n";
});
var newDoc = folder.createFile(filename, csv, MimeType.CSV);
console.log(newDoc.getId()); // You can see the file ID.
}
This script basically creates a .CSV file in the same folder where the worksheet is, using the range defined in var SelectedRange.
This script is applied to a button on the worksheet.
The question is: how do I make every comma typed in this spreadsheet be converted into another sign, like # before generating the .CSV file in the folder?
I would also like to know if instead of generating 1 file in the folder it is possible to generate 2 files, each with a name.
A:
If you are doing this to avoid conflicts between the comma in the cells and the csv delimiter then try doing the csv like this:
function sheetToCsv() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0")
const params = { "method": "GET", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
const url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?gid=" + sh.getSheetId() + "&format=csv";
const r = UrlFetchApp.fetch(url, params);
const csv = r.getContentText();
return csv;
}
And then put it back in a spreadsheet like this:
function csvToSheet(csv) {
const vs = Utilities.parseCsv(csv,',');
const osh = ss.getSheetByName("Sheet1");
osh.getRange(1,1,vs.length,vs[0].length).setValues(vs);
}
A:
In the meantime I've found a solution that almost works the way I'd like.
I created 2 functions, one to convert , to # and another to convert # to , again, then after the .csv file creation is complete the script switches back from # to , .
/**
* Create CSV file of Sheet2
* Modified script written by Tanaike
* https://stackoverflow.com/users/7108653/tanaike
*
* Additional Script by AdamD.PE
* version 13.11.2022.1
* https://support.google.com/docs/thread/188230855
*/
var SelectedRange = "A2:AB3";
function searchAndReplace_ToHash() {
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(SelectedRange).createTextFinder(',').replaceAllWith('#');
}
function searchAndReplace_ToComma() {
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(SelectedRange).createTextFinder('#').replaceAllWith(',');
}
function sheetToCsv_02() {
var filename = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetName() + "-01" + " - " + currentDate; // CSV file name
filename = filename + '.csv';
var ssid = SpreadsheetApp.getActiveSpreadsheet().getId();
searchAndReplace_ToHash()
// I modified below script.
var folders = DriveApp.getFileById(ssid).getParents();
var folder;
if (folders.hasNext()) {
folder = folders.next();
var user = Session.getEffectiveUser().getEmail();
if (!(folder.getOwner().getEmail() == user || folder.getEditors().some(e => e.getEmail() == user))) {
throw new Error("This user has no write permission for the folder.");
}
} else {
throw new Error("This user has no write permission for the folder.");
}
var csv = "";
var v = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(SelectedRange).getValues();
v.forEach(function (e) {
csv += e.join(",") + "\n";
});
var newDoc = folder.createFile(filename, csv, MimeType.CSV);
console.log(newDoc.getId()); // You can see the file ID.
searchAndReplace_ToComma()
}
It solves the problem, but it would be perfect if this change was not visible in the spreadsheet.
Is it possible to make this substitution without displaying it in the spreadsheet?
As for your script suggestion, I would like to change as little as possible in this script I'm using, it works exactly the way I need it to work, except for the fact that the commas of words conflict with the column divisions.
Anyway, thank you very much for all your attention and patience!
| Google Sheets - Convert comma to "#" before generate .CSV | I have the following script in a Google Sheet:
/**
* Create CSV file of Sheet2
* Modified script written by Tanaike
* https://stackoverflow.com/users/7108653/tanaike
*
* Additional Script by AdamD.PE
* version 13.11.2022.1
* https://support.google.com/docs/thread/188230855
*/
/** Date extraction added by Tyrone */
const date = new Date();
/** Extract today's date */
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = `0${month}`;
}
/** Show today's date */
let currentDate = `${day}-${month}-${year}`;
/** Date extraction added by Tyrone */
function sheetToCsvModelo0101() {
var filename = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetName() + "-01" + " - " + currentDate; // CSV file name
filename = filename + '.csv';
var ssid = SpreadsheetApp.getActiveSpreadsheet().getId();
var folders = DriveApp.getFileById(ssid).getParents();
var folder;
if (folders.hasNext()) {
folder = folders.next();
var user = Session.getEffectiveUser().getEmail();
if (!(folder.getOwner().getEmail() == user || folder.getEditors().some(e => e.getEmail() == user))) {
throw new Error("This user has no write permission for the folder.");
}
} else {
throw new Error("This user has no write permission for the folder.");
}
var SelectedRange = "A2:AB3";
var csv = "";
var v = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(SelectedRange).getValues();
v.forEach(function (e) {
csv += e.join(",") + "\n";
});
var newDoc = folder.createFile(filename, csv, MimeType.CSV);
console.log(newDoc.getId()); // You can see the file ID.
}
This script basically creates a .CSV file in the same folder where the worksheet is, using the range defined in var SelectedRange.
This script is applied to a button on the worksheet.
The question is: how do I make every comma typed in this spreadsheet be converted into another sign, like # before generating the .CSV file in the folder?
I would also like to know if instead of generating 1 file in the folder it is possible to generate 2 files, each with a name.
| [
"If you are doing this to avoid conflicts between the comma in the cells and the csv delimiter then try doing the csv like this:\nfunction sheetToCsv() {\n const ss = SpreadsheetApp.getActive();\n const sh = ss.getSheetByName(\"Sheet0\")\n const params = { \"method\": \"GET\", \"headers\": { \"Authorization\": \"Bearer \" + ScriptApp.getOAuthToken() } };\n const url = \"https://docs.google.com/spreadsheets/d/\" + ss.getId() + \"/export?gid=\" + sh.getSheetId() + \"&format=csv\";\n const r = UrlFetchApp.fetch(url, params);\n const csv = r.getContentText();\n return csv;\n}\n\nAnd then put it back in a spreadsheet like this:\nfunction csvToSheet(csv) {\n const vs = Utilities.parseCsv(csv,',');\n const osh = ss.getSheetByName(\"Sheet1\");\n osh.getRange(1,1,vs.length,vs[0].length).setValues(vs);\n}\n\n",
"In the meantime I've found a solution that almost works the way I'd like.\nI created 2 functions, one to convert , to # and another to convert # to , again, then after the .csv file creation is complete the script switches back from # to , .\n/** \n * Create CSV file of Sheet2\n * Modified script written by Tanaike\n * https://stackoverflow.com/users/7108653/tanaike\n * \n * Additional Script by AdamD.PE\n * version 13.11.2022.1\n * https://support.google.com/docs/thread/188230855\n */\n\nvar SelectedRange = \"A2:AB3\";\nfunction searchAndReplace_ToHash() {\n SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(SelectedRange).createTextFinder(',').replaceAllWith('#');\n}\n\nfunction searchAndReplace_ToComma() {\n SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(SelectedRange).createTextFinder('#').replaceAllWith(',');\n}\n\nfunction sheetToCsv_02() {\n var filename = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetName() + \"-01\" + \" - \" + currentDate; // CSV file name\n filename = filename + '.csv';\n var ssid = SpreadsheetApp.getActiveSpreadsheet().getId();\n\nsearchAndReplace_ToHash()\n\n // I modified below script.\n var folders = DriveApp.getFileById(ssid).getParents();\n var folder;\n if (folders.hasNext()) {\n folder = folders.next();\n var user = Session.getEffectiveUser().getEmail();\n if (!(folder.getOwner().getEmail() == user || folder.getEditors().some(e => e.getEmail() == user))) {\n throw new Error(\"This user has no write permission for the folder.\");\n }\n } else {\n throw new Error(\"This user has no write permission for the folder.\");\n }\n var csv = \"\";\n var v = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(SelectedRange).getValues();\n v.forEach(function (e) {\n csv += e.join(\",\") + \"\\n\";\n });\n var newDoc = folder.createFile(filename, csv, MimeType.CSV);\n console.log(newDoc.getId()); // You can see the file ID.\n searchAndReplace_ToComma()\n}\n\nIt solves the problem, but it would be perfect if this change was not visible in the spreadsheet.\nIs it possible to make this substitution without displaying it in the spreadsheet?\nAs for your script suggestion, I would like to change as little as possible in this script I'm using, it works exactly the way I need it to work, except for the fact that the commas of words conflict with the column divisions.\nAnyway, thank you very much for all your attention and patience!\n"
] | [
0,
0
] | [] | [] | [
"google_apps_script",
"google_sheets"
] | stackoverflow_0074670199_google_apps_script_google_sheets.txt |
Q:
pydantic.error_wrappers.ValidationError: 11 validation errors for For Trip type=value_error.missing
Im getting this error with my pydantic schema, but oddly it is generating the object correctly, and sending it to the SQLAlchemy models, then it suddenly throws error for all elements in the model.
response -> id
field required (type=value_error.missing)
response -> date
field required (type=value_error.missing)
response -> time
field required (type=value_error.missing)
response -> price
field required (type=value_error.missing)
response -> distance
field required (type=value_error.missing)
response -> origin_id
field required (type=value_error.missing)
response -> destination_id
field required (type=value_error.missing)
response -> driver_id
field required (type=value_error.missing)
response -> passenger_id
field required (type=value_error.missing)
response -> vehicle_id
field required (type=value_error.missing)
response -> status
field required (type=value_error.missing)
i must say that all the fields should have values. And the error trace do not references any part of my code so i dont even know where to debug. Im a noob in SQLAlchemy/pydantic
here are some parts of the code
class Trip(BaseModel):
id: int
date: str
time: str
price: float
distance: float
origin_id: int
destination_id: int
driver_id: int
passenger_id: int
vehicle_id: int
status: Status
class Config:
orm_mode = True
class TripDB(Base):
__tablename__ = 'trip'
__table_args__ = {'extend_existing': True}
id = Column(Integer, primary_key=True, index=True)
date = Column(DateTime, nullable=False)
time = Column(String(64), nullable=False)
price = Column(Float, nullable=False)
distance = Column(Float, nullable=False)
status = Column(String(64), nullable=False)
origin_id = Column(
Integer, ForeignKey('places.id'), nullable=False)
destination_id = Column(
Integer, ForeignKey('places.id'), nullable=False)
origin = relationship("PlaceDB", foreign_keys=[origin_id])
destination = relationship("PlaceDB", foreign_keys=[destination_id])
driver_id = Column(
Integer, ForeignKey('driver.id'), nullable=False)
vehicle_id = Column(
Integer, ForeignKey('vehicle.id'), nullable=False)
passenger_id = Column(
Integer, ForeignKey('passenger.id'), nullable=False)
def create_trip(trip: Trip, db: Session):
origin = db.query(models.PlaceDB).filter(models.PlaceDB.id == trip.origin_id).first()
destination = db.query(models.PlaceDB).filter(models.PlaceDB.id == trip.destination_id).first()
db_trip = TripDB(
id=(trip.id or None),
date=trip.date or None, time=trip.time or None, price=trip.price or None,
distance=trip.distance or None,
origin_id=trip.origin_id or None, destination_id=(trip.destination_id or None), status=trip.status or None,
driver_id=trip.driver_id or None, passenger_id=trip.passenger_id or None, vehicle_id=trip.vehicle_id or None, origin=origin, destination=destination)
try:
db.add(db_trip)
db.commit()
db.refresh(db_trip)
return db_trip
except:
return "Somethig went wrong"
A:
It seems like a bug on the pydantic model, it happened to me as well, and i was not able to fix it, but indeed if you just skip the type check in the route it works fine
A:
It seems like there is a conflict in your schema and create_trip function. Have you checked whether you are passing the correct param to your schema? You have defined most of the fields as not nullable, and you are passing None as an alternative value in db.add() command.
I had a similar problem with my code, and I figured that naming and type convention between schema and server.py. After matching the field names and type in both file, I resolved the error of the field required (type=value_error.missing).
# project/schema.py
from pydantic import BaseModel
# here I had made mistake by using target_URL in server.py
# variable name and type should be same in both schema and server
class URLBase(BaseModel):
target_url: str
class URL(URLBase):
is_active: bool
clicks: int
class Config:
orm_mode = True
class URLInfo(URL):
url: str
admin_url: str
# project/server.py
@app.post('/url', response_model=schema.URLInfo)
def create_short_url(url: schema.URLBase, db: Session = Depends(get_db)):
if not validators.url(url.target_url):
raise bad_request_message(message="Your provided URL is not valid!")
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "".join(secrets.choice(chars) for _ in range(5))
secret_key = "".join(secrets.choice(chars) for _ in range(8))
db_url = models.URL(target_url=url.target_url, key=key, secret_key=secret_key)
db.add(db_url)
db.commit()
db.refresh(db_url)
db_url.url = key
db_url.admin_url = secret_key
return db_url
A:
Please check the return statement, i had similar issue and got the issue reolved by correcting my return statement. I see return statement missing or wrong in create_trip function.
| pydantic.error_wrappers.ValidationError: 11 validation errors for For Trip type=value_error.missing | Im getting this error with my pydantic schema, but oddly it is generating the object correctly, and sending it to the SQLAlchemy models, then it suddenly throws error for all elements in the model.
response -> id
field required (type=value_error.missing)
response -> date
field required (type=value_error.missing)
response -> time
field required (type=value_error.missing)
response -> price
field required (type=value_error.missing)
response -> distance
field required (type=value_error.missing)
response -> origin_id
field required (type=value_error.missing)
response -> destination_id
field required (type=value_error.missing)
response -> driver_id
field required (type=value_error.missing)
response -> passenger_id
field required (type=value_error.missing)
response -> vehicle_id
field required (type=value_error.missing)
response -> status
field required (type=value_error.missing)
i must say that all the fields should have values. And the error trace do not references any part of my code so i dont even know where to debug. Im a noob in SQLAlchemy/pydantic
here are some parts of the code
class Trip(BaseModel):
id: int
date: str
time: str
price: float
distance: float
origin_id: int
destination_id: int
driver_id: int
passenger_id: int
vehicle_id: int
status: Status
class Config:
orm_mode = True
class TripDB(Base):
__tablename__ = 'trip'
__table_args__ = {'extend_existing': True}
id = Column(Integer, primary_key=True, index=True)
date = Column(DateTime, nullable=False)
time = Column(String(64), nullable=False)
price = Column(Float, nullable=False)
distance = Column(Float, nullable=False)
status = Column(String(64), nullable=False)
origin_id = Column(
Integer, ForeignKey('places.id'), nullable=False)
destination_id = Column(
Integer, ForeignKey('places.id'), nullable=False)
origin = relationship("PlaceDB", foreign_keys=[origin_id])
destination = relationship("PlaceDB", foreign_keys=[destination_id])
driver_id = Column(
Integer, ForeignKey('driver.id'), nullable=False)
vehicle_id = Column(
Integer, ForeignKey('vehicle.id'), nullable=False)
passenger_id = Column(
Integer, ForeignKey('passenger.id'), nullable=False)
def create_trip(trip: Trip, db: Session):
origin = db.query(models.PlaceDB).filter(models.PlaceDB.id == trip.origin_id).first()
destination = db.query(models.PlaceDB).filter(models.PlaceDB.id == trip.destination_id).first()
db_trip = TripDB(
id=(trip.id or None),
date=trip.date or None, time=trip.time or None, price=trip.price or None,
distance=trip.distance or None,
origin_id=trip.origin_id or None, destination_id=(trip.destination_id or None), status=trip.status or None,
driver_id=trip.driver_id or None, passenger_id=trip.passenger_id or None, vehicle_id=trip.vehicle_id or None, origin=origin, destination=destination)
try:
db.add(db_trip)
db.commit()
db.refresh(db_trip)
return db_trip
except:
return "Somethig went wrong"
| [
"It seems like a bug on the pydantic model, it happened to me as well, and i was not able to fix it, but indeed if you just skip the type check in the route it works fine\n",
"It seems like there is a conflict in your schema and create_trip function. Have you checked whether you are passing the correct param to your schema? You have defined most of the fields as not nullable, and you are passing None as an alternative value in db.add() command.\nI had a similar problem with my code, and I figured that naming and type convention between schema and server.py. After matching the field names and type in both file, I resolved the error of the field required (type=value_error.missing).\n# project/schema.py\nfrom pydantic import BaseModel\n\n# here I had made mistake by using target_URL in server.py\n# variable name and type should be same in both schema and server\nclass URLBase(BaseModel):\n target_url: str\n\n\nclass URL(URLBase):\n is_active: bool\n clicks: int\n\n class Config:\n orm_mode = True\n\n\nclass URLInfo(URL):\n url: str\n admin_url: str\n\n# project/server.py\[email protected]('/url', response_model=schema.URLInfo)\ndef create_short_url(url: schema.URLBase, db: Session = Depends(get_db)):\n if not validators.url(url.target_url):\n raise bad_request_message(message=\"Your provided URL is not valid!\")\n chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n key = \"\".join(secrets.choice(chars) for _ in range(5))\n secret_key = \"\".join(secrets.choice(chars) for _ in range(8))\n db_url = models.URL(target_url=url.target_url, key=key, secret_key=secret_key)\n db.add(db_url)\n db.commit()\n db.refresh(db_url)\n db_url.url = key\n db_url.admin_url = secret_key\n\n return db_url\n\n",
"Please check the return statement, i had similar issue and got the issue reolved by correcting my return statement. I see return statement missing or wrong in create_trip function.\n"
] | [
2,
0,
0
] | [] | [] | [
"pydantic",
"python",
"sqlalchemy"
] | stackoverflow_0072476094_pydantic_python_sqlalchemy.txt |
Q:
The Name DoEditButtonChecked does not exist in the current context C#
Very new to all this. Was working on my game in unity and got an error. I tried restarting unity, I tried asking for help in other places, and got no response. I don't really know how to debug it, or really any error.
Library\PackageCache\[email protected]\Editor\SpriteShapeControllerEditor.cs(352,38): error CS0103: The name 'DoEditButtonChecked' does not exist in the current context
A:
I had the same problem and i solved it by updating all the packages from the project direcltly in unity. Go to the manage services window (It is the cloud found in the upper part next to your account), then click the package manager and update all the ones that are not in green. Hope it helps you.
| The Name DoEditButtonChecked does not exist in the current context C# | Very new to all this. Was working on my game in unity and got an error. I tried restarting unity, I tried asking for help in other places, and got no response. I don't really know how to debug it, or really any error.
Library\PackageCache\[email protected]\Editor\SpriteShapeControllerEditor.cs(352,38): error CS0103: The name 'DoEditButtonChecked' does not exist in the current context
| [
"I had the same problem and i solved it by updating all the packages from the project direcltly in unity. Go to the manage services window (It is the cloud found in the upper part next to your account), then click the package manager and update all the ones that are not in green. Hope it helps you.\n"
] | [
0
] | [] | [] | [
"c#",
"unity3d"
] | stackoverflow_0072154634_c#_unity3d.txt |
Q:
How to add two numbers using Console.ReadLine()
I want to add two numbers using Console.ReadLine(), but it gives me the error
Invalid expression term 'int'
Here is my code:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
string number1 = Console.ReadLine();
Console.WriteLine("Enter another number:");
string number2 = Console.ReadLine();
Console.WriteLine("The sum of those numbers is:");
Console.WriteLine(int(number1) + int(number2));
}
}
}
Could you help?
A:
Use the Convert.ToInt32() method to convert from string to int.
Console.WriteLine(Convert.ToInt32(number1) + Convert.ToInt32(number2));
See How can I convert String to Int? for more examples or alternatives.
Note: You write
string s = "42";
int i = int(s); // Compiler error Invalid Expression term
This syntax is used for type casting in languages like Pascal or Python. But in C based languages like C#, C++ or Java you use a different syntax:
string s = "42";
int i = (int)s; // Compiler error invalid cast
Round brackets around the type name, not around the value. This will still not work, though, because there is no direct cast from type string to type int in C#. It would work for different types:
double d = 42d;
int i = (int)d; // Works
| How to add two numbers using Console.ReadLine() | I want to add two numbers using Console.ReadLine(), but it gives me the error
Invalid expression term 'int'
Here is my code:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
string number1 = Console.ReadLine();
Console.WriteLine("Enter another number:");
string number2 = Console.ReadLine();
Console.WriteLine("The sum of those numbers is:");
Console.WriteLine(int(number1) + int(number2));
}
}
}
Could you help?
| [
"Use the Convert.ToInt32() method to convert from string to int.\nConsole.WriteLine(Convert.ToInt32(number1) + Convert.ToInt32(number2));\n\nSee How can I convert String to Int? for more examples or alternatives.\n\nNote: You write\nstring s = \"42\";\nint i = int(s); // Compiler error Invalid Expression term\n\nThis syntax is used for type casting in languages like Pascal or Python. But in C based languages like C#, C++ or Java you use a different syntax:\nstring s = \"42\";\nint i = (int)s; // Compiler error invalid cast\n\nRound brackets around the type name, not around the value. This will still not work, though, because there is no direct cast from type string to type int in C#. It would work for different types:\ndouble d = 42d;\nint i = (int)d; // Works\n\n"
] | [
0
] | [] | [] | [
"addition",
"c#"
] | stackoverflow_0074672252_addition_c#.txt |
Q:
Pagination in Flask
I'm trying to display 5 record per page. However, I not sure how to configure the li class. For instance, click the 2 and it will redirect to next 5 record on second page and click previous it will redirect from 2 to 1 to first page.
manageSmartphone.html
<div class="clearfix">
<div class="hint-text">Showing <b>5</b> out of <b>{{ total }}</b> entries</div>
<ul class="pagination">
<li class="page-item"><a href="#">Previous</a></li>
<li class="page-item active"><a href="#" class="page-link" id="page" name="page">1</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">2</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">3</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">4</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">5</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">Next</a></li>
</ul>
</div>
app.py
@app.route('/manageSmartphone', methods = ['GET','POST'])
def manageSmartphone():
conn = get_db_connection()
page = request.args.get('page', type=int, default=1)
limit= 5
offset = page*limit - limit
smartphones = conn.execute('SELECT * FROM Smartphone').fetchall()
total = len(smartphones)
smartphones = conn.execute("SELECT * FROM Smartphone LIMIT ? OFFSET ?", (limit, offset)).fetchall()
return render_template('manageSmartphone.html', smartphones = smartphones , total = total)
A:
Implementing pagination can be challenging for several reasons,
I would suggest you using the paginate() method of the Flask-SQLAlchemy lib
This method takes a page parameter and a per_page parameter that you can use to specify the current page and the number of records to display per page
Here is an example of how you could use the paginate() method to implement pagination that displays 5 records per page in Flask:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_sqlalchemy import Pagination
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
# Define a model representing a record in the database
class Record(db.Model):
id = db.Column(db.Integer, primary_key=True)
brand = db.Column(db.String(80), nullable=False)
model = db.Column(db.String(80), nullable=False)
price = db.Column(db.Integer, nullable=False)
@app.route('/')
def index():
# Get the current page from the request parameters
page = request.args.get('page', 1, type=int)
# Use the paginate() method to get the records for the current page
records = Record.query.paginate(page=page, per_page=5)
# Render the records on a template
return render_template('index.html', records=records)
| Pagination in Flask | I'm trying to display 5 record per page. However, I not sure how to configure the li class. For instance, click the 2 and it will redirect to next 5 record on second page and click previous it will redirect from 2 to 1 to first page.
manageSmartphone.html
<div class="clearfix">
<div class="hint-text">Showing <b>5</b> out of <b>{{ total }}</b> entries</div>
<ul class="pagination">
<li class="page-item"><a href="#">Previous</a></li>
<li class="page-item active"><a href="#" class="page-link" id="page" name="page">1</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">2</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">3</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">4</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">5</a></li>
<li class="page-item"><a href="#" class="page-link" id="page" name="page">Next</a></li>
</ul>
</div>
app.py
@app.route('/manageSmartphone', methods = ['GET','POST'])
def manageSmartphone():
conn = get_db_connection()
page = request.args.get('page', type=int, default=1)
limit= 5
offset = page*limit - limit
smartphones = conn.execute('SELECT * FROM Smartphone').fetchall()
total = len(smartphones)
smartphones = conn.execute("SELECT * FROM Smartphone LIMIT ? OFFSET ?", (limit, offset)).fetchall()
return render_template('manageSmartphone.html', smartphones = smartphones , total = total)
| [
"Implementing pagination can be challenging for several reasons,\nI would suggest you using the paginate() method of the Flask-SQLAlchemy lib\nThis method takes a page parameter and a per_page parameter that you can use to specify the current page and the number of records to display per page\nHere is an example of how you could use the paginate() method to implement pagination that displays 5 records per page in Flask:\nfrom flask import Flask, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_sqlalchemy import Pagination\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'\ndb = SQLAlchemy(app)\n\n# Define a model representing a record in the database\nclass Record(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n brand = db.Column(db.String(80), nullable=False)\n model = db.Column(db.String(80), nullable=False)\n price = db.Column(db.Integer, nullable=False)\n\[email protected]('/')\ndef index():\n # Get the current page from the request parameters\n page = request.args.get('page', 1, type=int)\n\n # Use the paginate() method to get the records for the current page\n records = Record.query.paginate(page=page, per_page=5)\n\n # Render the records on a template\n return render_template('index.html', records=records)\n\n"
] | [
1
] | [] | [] | [
"flask",
"html",
"python"
] | stackoverflow_0074666012_flask_html_python.txt |
Q:
problem converting LSystems code from p5js to HTML Canvas javascript
I'm trying to convert this Daniel Shiffman tutorial from p5js to html5 canvas without a library:
var angle;
var axiom = "F";
var sentence = axiom;
var len = 100;
var rules = [];
rules[0] = {
a: "F",
b: "FF+[+F-F-F]-[-F+F+F]"
}
function generate() {
len *= 0.5;
var nextSentence = "";
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
var found = false;
for (var j = 0; j < rules.length; j++) {
if (current == rules[j].a) {
found = true;
nextSentence += rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
sentence = nextSentence;
createP(sentence);
turtle();
}
function turtle() {
background(51);
resetMatrix();
translate(width / 2, height);
stroke(255, 100);
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
if (current == "F") {
line(0, 0, 0, -len);
translate(0, -len);
} else if (current == "+") {
rotate(angle);
} else if (current == "-") {
rotate(-angle)
} else if (current == "[") {
push();
} else if (current == "]") {
pop();
}
}
}
function setup() {
createCanvas(400, 400);
angle = radians(25);
background(51);
createP(axiom);
turtle();
var button = createButton("generate");
button.mousePressed(generate);
}
This is my code and there is a problem with it that I am not able to debug... When I run the following code, I get the start of this tree with an error message prompting me to change rotate(-this.angle) to call the context. But when I fix the issue, the tree disappears & the rectangle in the "buildFlower()" function appears... why is this happening? :/ :
My code:
const init = () => {
const html = document.getElementsByTagName("html").item(0),
canvas = document.getElementsByTagName("canvas").item(0),
c = canvas.getContext("2d");
let flower;
const gui = new dat.GUI();
function line(x1, y1, x2, y2, color) {
c.strokeStyle = color;
c.beginPath();
c.moveTo(x1, y1);
c.lineTo(x2, y2);
c.stroke();
}
class Flower {
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.angle = (Math.PI / 180) * 25;
this.axiom = "F";
this.sentence = this.axiom;
this.len = 100;
this.rules = [];
this.rules[0] = {
a: "F",
b: "FF+[+F-F-F]-[-F+F+F]",
};
}
generateLSystem() {
this.len *= 0.5;
let nextSentence = "";
for (let i = 0; i < this.sentence.length; i++) {
let current = this.sentence.charAt(i);
let found = false;
for (let j = 0; j < this.rules.length; j++) {
if (current == this.rules[j].a) {
found = true;
nextSentence += this.rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
this.sentence = nextSentence;
this.turtle();
}
turtle() {
c.resetTransform();
c.translate(100, getResolution().h);
for (let i = 0; i < this.sentence.length; i++) {
let current = [this.sentence.charAt(i)];
if (current == "F") {
line(0, 0, 0, -this.len);
c.translate(0, -this.len);
} else if (current == "+") {
c.rotate(this.angle);
} else if (current == "-") {
// WHEN I CHANGE THE LINE BELOW TO (`c.rotate`) THE ENTIRE THING DISAPPEARS.
rotate(-this.angle);
} else if (current == "[") {
current.push();
} else if (current == "]") {
current.pop();
}
}
}
buildFlower() {
c.beginPath();
c.rect(
getResolution().w / 2 - this.size / 2,
getResolution().h / 2 - this.size / 2,
this.size,
this.size
);
c.stroke();
}
}
const resize = () => {
canvas.width = w = window.innerWidth;
canvas.height = h = window.innerHeight;
console.log(`screen resolution: ${w}px × ${h}px`);
};
const getResolution = () => {
return { w: canvas.width, h: canvas.height };
};
const setup = () => {
c.clearRect(0, 0, getResolution().w, getResolution().h);
flower = new Flower(getResolution().w, getResolution().h, 200);
flower.generateLSystem();
gui.add(flower, "size", 0, 200);
gui.add(flower, "axiom");
};
setup();
const draw = (t) => {
c.fillStyle = "rgba(255, 255, 255, .5)";
c.fillRect(0, 0, w, h);
window.requestAnimationFrame(draw);
};
let w,
h,
last,
i = 0,
start = 0;
window.removeEventListener("load", init);
window.addEventListener("resize", resize);
resize();
window.requestAnimationFrame(draw);
};
window.addEventListener("load", init);
I've been trying for hrs and can't seem to debug :/
A:
General suggestion: work in small sprints and run the code frequently to verify that it behaves as expected. The code here seems like it was built up in just a few long sprints without much validation for each component along the way. This apparently led to a buildup of complexity, causing confusion and subtle bugs.
Try to avoid premature abstractions like excessive functions and classes until the code is working correctly. At that point, the correct abstractions and cut points will be apparent.
Also, minimize the problem space by only introducing "bells and whistles"-type peripheral functionality once the core logic is working. When the basic drawing is failing, functionality like a GUI, resizing, a RAF loop and so forth just get in the way of progress. Add those after the basic drawing works.
The main reason for the disappearing drawing on the canvas is that resize() is called after setup(). When you resize the canvas, it wipes it clean. Call setup() after your initial resize() call:
window.removeEventListener("load", init);
window.addEventListener("resize", resize);
resize(); // <-- wipes the screen
setup(); // <-- draw after resize
window.requestAnimationFrame(draw);
You see a partial drawing showing up because your crash prevents the resize() from executing. This should be a big debug hint: some code after the drawing must be wiping it out.
The translation from p5's push() and pop() to HTML5 canvas doesn't appear correct:
} else if (current == "[") {
current.push();
} else if (current == "]") {
current.pop();
}
current is an array, but we don't want to mess with it. We're supposed to be pushing and popping the canvas context, not an array. These calls are context.save() and context.restore() in HTML5:
} else if (current === "[") {
c.save();
} else if (current === "]") {
c.restore();
}
A strange design choice is:
let current = [this.sentence.charAt(i)];
if (current == "F") {
Here, you've created an array of one element, then used coercion to compare it to a string. Always use === and don't create a one-element array unnecessarily:
// use const instead of let and [i] instead of charAt(i)
const current = this.sentence[i];
if (current === "F") {
I could analyze the design further and do a full rewrite/code review, but I'll leave it at this just to get you moving again and not belabor the point:
const init = () => {
const html = document.getElementsByTagName("html").item(0),
canvas = document.getElementsByTagName("canvas").item(0),
c = canvas.getContext("2d");
let flower;
// const gui = new dat.GUI();
function line(x1, y1, x2, y2, color) {
c.strokeStyle = color;
c.beginPath();
c.moveTo(x1, y1);
c.lineTo(x2, y2);
c.stroke();
}
class Flower {
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.angle = (Math.PI / 180) * 25;
this.axiom = "F";
this.sentence = this.axiom;
this.len = 50;
this.rules = [];
this.rules[0] = {
a: "F",
b: "FF+[+F-F-F]-[-F+F+F]",
};
}
generateLSystem() {
this.len *= 0.5;
let nextSentence = "";
for (let i = 0; i < this.sentence.length; i++) {
let current = this.sentence[i];
let found = false;
for (let j = 0; j < this.rules.length; j++) {
if (current == this.rules[j].a) {
found = true;
nextSentence += this.rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
this.sentence = nextSentence;
this.turtle();
}
turtle() {
c.resetTransform();
c.translate(100, getResolution().h);
for (let i = 0; i < this.sentence.length; i++) {
const current = this.sentence[i];
if (current === "F") {
line(0, 0, 0, -this.len);
c.translate(0, -this.len);
} else if (current === "+") {
c.rotate(this.angle);
} else if (current === "-") {
c.rotate(-this.angle);
} else if (current === "[") {
c.save();
} else if (current === "]") {
c.restore();
}
}
}
buildFlower() {
c.beginPath();
c.rect(
getResolution().w / 2 - this.size / 2,
getResolution().h / 2 - this.size / 2,
this.size,
this.size
);
c.stroke();
}
}
const resize = () => {
canvas.width = w = window.innerWidth;
canvas.height = h = window.innerHeight;
console.log(`screen resolution: ${w}px × ${h}px`);
};
const getResolution = () => {
return { w: canvas.width, h: canvas.height };
};
const setup = () => {
c.clearRect(0, 0, getResolution().w, getResolution().h);
flower = new Flower(getResolution().w, getResolution().h, 200);
flower.generateLSystem();
//gui.add(flower, "size", 0, 200);
//gui.add(flower, "axiom");
};
const draw = (t) => {
c.fillStyle = "rgba(255, 255, 255, .5)";
c.fillRect(0, 0, w, h);
window.requestAnimationFrame(draw);
};
let w,
h,
last,
i = 0,
start = 0;
window.removeEventListener("load", init);
window.addEventListener("resize", resize);
resize();
setup();
window.requestAnimationFrame(draw);
};
window.addEventListener("load", init);
<canvas></canvas>
| problem converting LSystems code from p5js to HTML Canvas javascript | I'm trying to convert this Daniel Shiffman tutorial from p5js to html5 canvas without a library:
var angle;
var axiom = "F";
var sentence = axiom;
var len = 100;
var rules = [];
rules[0] = {
a: "F",
b: "FF+[+F-F-F]-[-F+F+F]"
}
function generate() {
len *= 0.5;
var nextSentence = "";
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
var found = false;
for (var j = 0; j < rules.length; j++) {
if (current == rules[j].a) {
found = true;
nextSentence += rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
sentence = nextSentence;
createP(sentence);
turtle();
}
function turtle() {
background(51);
resetMatrix();
translate(width / 2, height);
stroke(255, 100);
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
if (current == "F") {
line(0, 0, 0, -len);
translate(0, -len);
} else if (current == "+") {
rotate(angle);
} else if (current == "-") {
rotate(-angle)
} else if (current == "[") {
push();
} else if (current == "]") {
pop();
}
}
}
function setup() {
createCanvas(400, 400);
angle = radians(25);
background(51);
createP(axiom);
turtle();
var button = createButton("generate");
button.mousePressed(generate);
}
This is my code and there is a problem with it that I am not able to debug... When I run the following code, I get the start of this tree with an error message prompting me to change rotate(-this.angle) to call the context. But when I fix the issue, the tree disappears & the rectangle in the "buildFlower()" function appears... why is this happening? :/ :
My code:
const init = () => {
const html = document.getElementsByTagName("html").item(0),
canvas = document.getElementsByTagName("canvas").item(0),
c = canvas.getContext("2d");
let flower;
const gui = new dat.GUI();
function line(x1, y1, x2, y2, color) {
c.strokeStyle = color;
c.beginPath();
c.moveTo(x1, y1);
c.lineTo(x2, y2);
c.stroke();
}
class Flower {
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.angle = (Math.PI / 180) * 25;
this.axiom = "F";
this.sentence = this.axiom;
this.len = 100;
this.rules = [];
this.rules[0] = {
a: "F",
b: "FF+[+F-F-F]-[-F+F+F]",
};
}
generateLSystem() {
this.len *= 0.5;
let nextSentence = "";
for (let i = 0; i < this.sentence.length; i++) {
let current = this.sentence.charAt(i);
let found = false;
for (let j = 0; j < this.rules.length; j++) {
if (current == this.rules[j].a) {
found = true;
nextSentence += this.rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
this.sentence = nextSentence;
this.turtle();
}
turtle() {
c.resetTransform();
c.translate(100, getResolution().h);
for (let i = 0; i < this.sentence.length; i++) {
let current = [this.sentence.charAt(i)];
if (current == "F") {
line(0, 0, 0, -this.len);
c.translate(0, -this.len);
} else if (current == "+") {
c.rotate(this.angle);
} else if (current == "-") {
// WHEN I CHANGE THE LINE BELOW TO (`c.rotate`) THE ENTIRE THING DISAPPEARS.
rotate(-this.angle);
} else if (current == "[") {
current.push();
} else if (current == "]") {
current.pop();
}
}
}
buildFlower() {
c.beginPath();
c.rect(
getResolution().w / 2 - this.size / 2,
getResolution().h / 2 - this.size / 2,
this.size,
this.size
);
c.stroke();
}
}
const resize = () => {
canvas.width = w = window.innerWidth;
canvas.height = h = window.innerHeight;
console.log(`screen resolution: ${w}px × ${h}px`);
};
const getResolution = () => {
return { w: canvas.width, h: canvas.height };
};
const setup = () => {
c.clearRect(0, 0, getResolution().w, getResolution().h);
flower = new Flower(getResolution().w, getResolution().h, 200);
flower.generateLSystem();
gui.add(flower, "size", 0, 200);
gui.add(flower, "axiom");
};
setup();
const draw = (t) => {
c.fillStyle = "rgba(255, 255, 255, .5)";
c.fillRect(0, 0, w, h);
window.requestAnimationFrame(draw);
};
let w,
h,
last,
i = 0,
start = 0;
window.removeEventListener("load", init);
window.addEventListener("resize", resize);
resize();
window.requestAnimationFrame(draw);
};
window.addEventListener("load", init);
I've been trying for hrs and can't seem to debug :/
| [
"General suggestion: work in small sprints and run the code frequently to verify that it behaves as expected. The code here seems like it was built up in just a few long sprints without much validation for each component along the way. This apparently led to a buildup of complexity, causing confusion and subtle bugs.\nTry to avoid premature abstractions like excessive functions and classes until the code is working correctly. At that point, the correct abstractions and cut points will be apparent.\nAlso, minimize the problem space by only introducing \"bells and whistles\"-type peripheral functionality once the core logic is working. When the basic drawing is failing, functionality like a GUI, resizing, a RAF loop and so forth just get in the way of progress. Add those after the basic drawing works.\n\nThe main reason for the disappearing drawing on the canvas is that resize() is called after setup(). When you resize the canvas, it wipes it clean. Call setup() after your initial resize() call:\nwindow.removeEventListener(\"load\", init);\nwindow.addEventListener(\"resize\", resize);\nresize(); // <-- wipes the screen\nsetup(); // <-- draw after resize\nwindow.requestAnimationFrame(draw);\n\nYou see a partial drawing showing up because your crash prevents the resize() from executing. This should be a big debug hint: some code after the drawing must be wiping it out.\n\nThe translation from p5's push() and pop() to HTML5 canvas doesn't appear correct:\n} else if (current == \"[\") {\n current.push();\n} else if (current == \"]\") {\n current.pop();\n}\n\ncurrent is an array, but we don't want to mess with it. We're supposed to be pushing and popping the canvas context, not an array. These calls are context.save() and context.restore() in HTML5:\n} else if (current === \"[\") {\n c.save();\n} else if (current === \"]\") {\n c.restore();\n}\n\n\nA strange design choice is:\nlet current = [this.sentence.charAt(i)];\n\nif (current == \"F\") {\n\nHere, you've created an array of one element, then used coercion to compare it to a string. Always use === and don't create a one-element array unnecessarily:\n// use const instead of let and [i] instead of charAt(i)\nconst current = this.sentence[i];\n\nif (current === \"F\") {\n\nI could analyze the design further and do a full rewrite/code review, but I'll leave it at this just to get you moving again and not belabor the point:\n\n\nconst init = () => {\n const html = document.getElementsByTagName(\"html\").item(0),\n canvas = document.getElementsByTagName(\"canvas\").item(0),\n c = canvas.getContext(\"2d\");\n\n let flower;\n// const gui = new dat.GUI();\n\n function line(x1, y1, x2, y2, color) {\n c.strokeStyle = color;\n c.beginPath();\n c.moveTo(x1, y1);\n c.lineTo(x2, y2);\n c.stroke();\n }\n\n class Flower {\n constructor(x, y, size) {\n this.x = x;\n this.y = y;\n this.size = size;\n\n this.angle = (Math.PI / 180) * 25;\n this.axiom = \"F\";\n this.sentence = this.axiom;\n this.len = 50;\n this.rules = [];\n this.rules[0] = {\n a: \"F\",\n b: \"FF+[+F-F-F]-[-F+F+F]\",\n };\n }\n\n generateLSystem() {\n this.len *= 0.5;\n let nextSentence = \"\";\n for (let i = 0; i < this.sentence.length; i++) {\n let current = this.sentence[i];\n let found = false;\n for (let j = 0; j < this.rules.length; j++) {\n if (current == this.rules[j].a) {\n found = true;\n nextSentence += this.rules[j].b;\n break;\n }\n }\n if (!found) {\n nextSentence += current;\n }\n }\n this.sentence = nextSentence;\n this.turtle();\n }\n\n turtle() {\n c.resetTransform();\n c.translate(100, getResolution().h);\n\n for (let i = 0; i < this.sentence.length; i++) {\n const current = this.sentence[i];\n\n if (current === \"F\") {\n line(0, 0, 0, -this.len);\n c.translate(0, -this.len);\n } else if (current === \"+\") {\n c.rotate(this.angle);\n } else if (current === \"-\") {\n c.rotate(-this.angle);\n } else if (current === \"[\") {\n c.save();\n } else if (current === \"]\") {\n c.restore();\n }\n }\n }\n\n buildFlower() {\n c.beginPath();\n c.rect(\n getResolution().w / 2 - this.size / 2,\n getResolution().h / 2 - this.size / 2,\n this.size,\n this.size\n );\n c.stroke();\n }\n }\n\n const resize = () => {\n canvas.width = w = window.innerWidth;\n canvas.height = h = window.innerHeight;\n console.log(`screen resolution: ${w}px × ${h}px`);\n };\n\n const getResolution = () => {\n return { w: canvas.width, h: canvas.height };\n };\n\n const setup = () => {\n c.clearRect(0, 0, getResolution().w, getResolution().h);\n flower = new Flower(getResolution().w, getResolution().h, 200);\n flower.generateLSystem();\n //gui.add(flower, \"size\", 0, 200);\n //gui.add(flower, \"axiom\");\n };\n\n const draw = (t) => {\n c.fillStyle = \"rgba(255, 255, 255, .5)\";\n c.fillRect(0, 0, w, h);\n\n window.requestAnimationFrame(draw);\n };\n\n let w,\n h,\n last,\n i = 0,\n start = 0;\n\n window.removeEventListener(\"load\", init);\n window.addEventListener(\"resize\", resize);\n resize();\n setup();\n window.requestAnimationFrame(draw);\n};\n\nwindow.addEventListener(\"load\", init);\n<canvas></canvas>\n\n\n\n"
] | [
2
] | [] | [] | [
"canvas",
"html5_canvas",
"javascript",
"l_systems",
"p5.js"
] | stackoverflow_0074671468_canvas_html5_canvas_javascript_l_systems_p5.js.txt |
Q:
Python: Print string in reverse
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
then the output is:
ereht olleH
yeH
I have already the code like this. I don't understand what I have done wrong. Please help.
word = str(input())
the_no_word = ['Done', 'done', 'd']
while word == "Done" and word == "done" and word == "d":
break
print(word[-1::-1])
A:
This may work for you:
word = ""
the_no_word = ['Done', 'done', 'd']
while word not in the_no_word:
word = str(input())
print(word[-1::-1])
You need to get the user input into word after every loop and check if word is not in the list of the_no_word. Let me know if this is what you were looking for.
A:
You could do it like this:
while (word := input()) not in ['Done', 'done', 'd']:
print(word[::-1])
A:
var1 = str(input())
bad_word = ['done', 'd', 'Done']
while var1 not in bad_word:
print(var1[::-1])
var1 = str(input())
Just did the problem and used this answer.
A:
This should work for you!
word = str(input())
the_no_word = ['Done', 'done', 'd']
while word not in the_no_word:
print(word[-1::-1])
word = str(input())
| Python: Print string in reverse | Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
then the output is:
ereht olleH
yeH
I have already the code like this. I don't understand what I have done wrong. Please help.
word = str(input())
the_no_word = ['Done', 'done', 'd']
while word == "Done" and word == "done" and word == "d":
break
print(word[-1::-1])
| [
"This may work for you:\nword = \"\"\nthe_no_word = ['Done', 'done', 'd']\nwhile word not in the_no_word:\n word = str(input())\n print(word[-1::-1])\n\nYou need to get the user input into word after every loop and check if word is not in the list of the_no_word. Let me know if this is what you were looking for.\n",
"You could do it like this:\nwhile (word := input()) not in ['Done', 'done', 'd']:\n print(word[::-1])\n\n",
"var1 = str(input())\nbad_word = ['done', 'd', 'Done']\nwhile var1 not in bad_word:\n print(var1[::-1])\n var1 = str(input())\n\nJust did the problem and used this answer.\n",
"This should work for you!\nword = str(input())\nthe_no_word = ['Done', 'done', 'd']\nwhile word not in the_no_word:\n print(word[-1::-1])\nword = str(input())\n\n"
] | [
0,
0,
0,
0
] | [
"string = str(input())\n\nno_words = ['Done','done','d']\nwhile string not in no_words:\n if string in no_words:\n print()\n else:\n print(string[-1::-1])\n string = str(input())\n\n"
] | [
-2
] | [
"performance",
"python",
"python_3.x"
] | stackoverflow_0071360039_performance_python_python_3.x.txt |
Q:
how to test Steam login Unreal Engine game on Linux?
how to test Steam login Unreal Engine game on Linux?
like below:
https://www.youtube.com/watch?v=rWs6SyyVpTE&t=320s
I only find on windows teaching.
On Linux cannot appear Steam.
My Current test Version:
Unreal Engine 5.1.0
Steam API: v020
Steam package versions 1668654564
[localhost-PC localhost]# uname -a
Linux localhost-PC 6.0.8-1-MANJARO #1 SMP PREEMPT_DYNAMIC Thu Nov 10 20:52:34 UTC 2022 x86_64 GNU/Linux
I Enabled plugin
A:
To test Steam login for an Unreal Engine game on Linux, you will first need to have Steam installed on your Linux system. Once Steam is installed, you can launch it and log in to your Steam account as you would on any other platform.
To test the Steam login for your Unreal Engine game, you will need to build and run the game from the Unreal Engine editor. To do this, open the Unreal Engine editor and select the project for your game. Then, select "Build" from the "File" menu, and choose the appropriate build configuration for your game.
Once the build is complete, you can run the game by selecting "Launch" from the "File" menu. When the game launches, you should see the Steam login prompt, and you can log in with your Steam account to test the Steam integration.
If you are having trouble getting the Steam login to work on Linux, you may need to enable the Steam integration in your Unreal Engine project. To do this, open the "Project Settings" window in the Unreal Engine editor, and navigate to the "Plugins" section. From there, you can enable the Steam plugin by checking the box next to it.
Once the Steam plugin is enabled, you should be able to test the Steam login for your Unreal Engine game on Linux. If you continue to have trouble, you may need to consult the Unreal Engine documentation or seek help from the Unreal Engine community forums.
| how to test Steam login Unreal Engine game on Linux? | how to test Steam login Unreal Engine game on Linux?
like below:
https://www.youtube.com/watch?v=rWs6SyyVpTE&t=320s
I only find on windows teaching.
On Linux cannot appear Steam.
My Current test Version:
Unreal Engine 5.1.0
Steam API: v020
Steam package versions 1668654564
[localhost-PC localhost]# uname -a
Linux localhost-PC 6.0.8-1-MANJARO #1 SMP PREEMPT_DYNAMIC Thu Nov 10 20:52:34 UTC 2022 x86_64 GNU/Linux
I Enabled plugin
| [
"To test Steam login for an Unreal Engine game on Linux, you will first need to have Steam installed on your Linux system. Once Steam is installed, you can launch it and log in to your Steam account as you would on any other platform.\nTo test the Steam login for your Unreal Engine game, you will need to build and run the game from the Unreal Engine editor. To do this, open the Unreal Engine editor and select the project for your game. Then, select \"Build\" from the \"File\" menu, and choose the appropriate build configuration for your game.\nOnce the build is complete, you can run the game by selecting \"Launch\" from the \"File\" menu. When the game launches, you should see the Steam login prompt, and you can log in with your Steam account to test the Steam integration.\nIf you are having trouble getting the Steam login to work on Linux, you may need to enable the Steam integration in your Unreal Engine project. To do this, open the \"Project Settings\" window in the Unreal Engine editor, and navigate to the \"Plugins\" section. From there, you can enable the Steam plugin by checking the box next to it.\nOnce the Steam plugin is enabled, you should be able to test the Steam login for your Unreal Engine game on Linux. If you continue to have trouble, you may need to consult the Unreal Engine documentation or seek help from the Unreal Engine community forums.\n"
] | [
0
] | [] | [] | [
"linux",
"steam",
"steamworks_api",
"unreal_engine4",
"unreal_engine5"
] | stackoverflow_0074672254_linux_steam_steamworks_api_unreal_engine4_unreal_engine5.txt |
Q:
In NavigationView, List item appears mid-screen rather than at top when @Environment(\.presentationMode) is defined
I'm facing a weird bug where a list item within a NavigationView appears below a gap. When I scroll, it resets to correct location.
Minimum reproducible example on Xcode 14.1, iOS 16.1.2:
import SwiftUI
@main
struct Test_2022_12_03_02App: App {
var body: some Scene {
WindowGroup {
ListView()
}
}
}
struct ListView: View {
var body: some View {
NavigationView {
NavigationLink(destination: DetailView()) {
Text("Hello")
}
}
.navigationViewStyle(.stack)
}
}
struct DetailView: View {
// If I remove the line below, the bug disappears
@Environment(\.presentationMode) var presentationMode
var members = [1]
var body: some View {
List {
ForEach(members, id:\.self) { member in
Text("World")
}
}
}
}
This bug happens consistently on my phone, but doesn't always happen in simulators. Weirdly my friend's phone also displayed expected behavior with same iOS version.
More notes:
If I remove @Environment(\.presentationMode) var presentationMode the bug disappears. (I need this line for my full app, to be able to return to main screen from the navigation link)
The bug also disappears if in the DetailView, we don't use a List, i.e.
struct DetailView: View {
// If I remove the line below, the bug disappears
@Environment(\.presentationMode) var presentationMode
var members = [1]
var body: some View {
List {
// ForEach(members, id:\.self) { member in
Text("World")
// }
}
}
}
Two questions:
Do you know what's happening? Am I missing something in my code?
If this is a freak bug, how do I find a workaround? Note that I need both the list and the ability to return to main screen in my full app.
Thanks!
A:
NavigationView is deprecated and so is presentationMode. There is bound to be unforeseen bugs using deprecated methods. Use navigation stack instead: https://developer.apple.com/documentation/swiftui/navigationstack
| In NavigationView, List item appears mid-screen rather than at top when @Environment(\.presentationMode) is defined | I'm facing a weird bug where a list item within a NavigationView appears below a gap. When I scroll, it resets to correct location.
Minimum reproducible example on Xcode 14.1, iOS 16.1.2:
import SwiftUI
@main
struct Test_2022_12_03_02App: App {
var body: some Scene {
WindowGroup {
ListView()
}
}
}
struct ListView: View {
var body: some View {
NavigationView {
NavigationLink(destination: DetailView()) {
Text("Hello")
}
}
.navigationViewStyle(.stack)
}
}
struct DetailView: View {
// If I remove the line below, the bug disappears
@Environment(\.presentationMode) var presentationMode
var members = [1]
var body: some View {
List {
ForEach(members, id:\.self) { member in
Text("World")
}
}
}
}
This bug happens consistently on my phone, but doesn't always happen in simulators. Weirdly my friend's phone also displayed expected behavior with same iOS version.
More notes:
If I remove @Environment(\.presentationMode) var presentationMode the bug disappears. (I need this line for my full app, to be able to return to main screen from the navigation link)
The bug also disappears if in the DetailView, we don't use a List, i.e.
struct DetailView: View {
// If I remove the line below, the bug disappears
@Environment(\.presentationMode) var presentationMode
var members = [1]
var body: some View {
List {
// ForEach(members, id:\.self) { member in
Text("World")
// }
}
}
}
Two questions:
Do you know what's happening? Am I missing something in my code?
If this is a freak bug, how do I find a workaround? Note that I need both the list and the ability to return to main screen in my full app.
Thanks!
| [
"NavigationView is deprecated and so is presentationMode. There is bound to be unforeseen bugs using deprecated methods. Use navigation stack instead: https://developer.apple.com/documentation/swiftui/navigationstack\n"
] | [
0
] | [] | [] | [
"swift",
"swiftui",
"swiftui_list",
"swiftui_navigationview"
] | stackoverflow_0074672135_swift_swiftui_swiftui_list_swiftui_navigationview.txt |
Q:
How to remove fractioned Items and add sales to another row
So basically my POS reports don't add up split bills.
If you look at df.Item there are items with fractions (1/2, 1/3, etc). I want to drop those lines but add the sales to the proper row.
Item Outlet1 Outlet2 Outlet3 Outlet4
2 AIR GIN 162.0 NaN 189.0 54.0
3 AIR GIN 1/3 NaN NaN NaN 9.0
4 AIR VODKA 468.0 NaN 585.0 144.0
5 AIR VODKA 1/2 NaN NaN 18.0 NaN
Example output:
Item Outlet1 Outlet2 Outlet3 Outlet4
2 AIR GIN 162.0 NaN 189.0 63.0
3 AIR VODKA 468.0 NaN 603.0 144.0
I'm not sure where to start, New to python.
A:
I'm assuming the data doesn't contain any duplicate items. It looks like it's total sales over a certain period, but just the itemization is messed up.
In that case, you can simply remove the fractions with .str.replace(), then group and sum.
df['Item'] = df['Item'].str.replace(r'\s+\d+/\d+$', '', regex=True)
df.groupby('Item').sum(min_count=1) # `min_count` to respect NaNs
Outlet1 Outlet2 Outlet3 Outlet4
Item
AIR GIN 162.0 NaN 189.0 63.0
AIR VODKA 468.0 NaN 603.0 144.0
Then you can .reset_index() if you want.
P.S. Before your edit, you also had two other columns that weren't really relevant to the problem, but change the process. You could just include them in the groupby:
df.groupby(['Category', 'SubCategory', 'Item'])
| How to remove fractioned Items and add sales to another row | So basically my POS reports don't add up split bills.
If you look at df.Item there are items with fractions (1/2, 1/3, etc). I want to drop those lines but add the sales to the proper row.
Item Outlet1 Outlet2 Outlet3 Outlet4
2 AIR GIN 162.0 NaN 189.0 54.0
3 AIR GIN 1/3 NaN NaN NaN 9.0
4 AIR VODKA 468.0 NaN 585.0 144.0
5 AIR VODKA 1/2 NaN NaN 18.0 NaN
Example output:
Item Outlet1 Outlet2 Outlet3 Outlet4
2 AIR GIN 162.0 NaN 189.0 63.0
3 AIR VODKA 468.0 NaN 603.0 144.0
I'm not sure where to start, New to python.
| [
"I'm assuming the data doesn't contain any duplicate items. It looks like it's total sales over a certain period, but just the itemization is messed up.\nIn that case, you can simply remove the fractions with .str.replace(), then group and sum.\ndf['Item'] = df['Item'].str.replace(r'\\s+\\d+/\\d+$', '', regex=True)\n\ndf.groupby('Item').sum(min_count=1) # `min_count` to respect NaNs\n\n Outlet1 Outlet2 Outlet3 Outlet4\nItem \nAIR GIN 162.0 NaN 189.0 63.0\nAIR VODKA 468.0 NaN 603.0 144.0\n\nThen you can .reset_index() if you want.\n\nP.S. Before your edit, you also had two other columns that weren't really relevant to the problem, but change the process. You could just include them in the groupby:\ndf.groupby(['Category', 'SubCategory', 'Item'])\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074671929_dataframe_pandas_python.txt |
Q:
Scraping Table Data from Multiple URLS, but first link is repeating
I'm looking to iterate through the URL with "count" as variables between 1 and 65.
Right now, I'm close but really struggling to figure out the last piece. I'm receiving the same table (from variable 1) 65 times, instead of receiving the different tables.
import requests
import pandas as pd
url = 'https://basketball.realgm.com/international/stats/2023/Averages/Qualified/All/player/All/desc/{count}'
res = []
for count in range(1, 65):
html = requests.get(url).content
df_list = pd.read_html(html)
df = df_list[-1]
res.append(df)
print(res)
df.to_csv('my data.csv')
Any thoughts?
A:
A few errors:
Your URL was templated incorrectly. It remains at .../{count} literally, without substituting or updating from the loop variable.
If you want to get page 1 to 65, use range(1, 66)
Unless you want to export only the last dataframe, you need to concatenate all of them first
# No count here, we will add it later
url = 'https://basketball.realgm.com/international/stats/2023/Averages/Qualified/All/player/All/desc'
res = []
for count in range(1, 66):
# pd.read_html accepts a URL too so no need to make a separate request
df_list = pd.read_html(f"{url}/{count}")
res.append(df_list[-1])
pd.concat(res).to_csv('my data.csv')
| Scraping Table Data from Multiple URLS, but first link is repeating | I'm looking to iterate through the URL with "count" as variables between 1 and 65.
Right now, I'm close but really struggling to figure out the last piece. I'm receiving the same table (from variable 1) 65 times, instead of receiving the different tables.
import requests
import pandas as pd
url = 'https://basketball.realgm.com/international/stats/2023/Averages/Qualified/All/player/All/desc/{count}'
res = []
for count in range(1, 65):
html = requests.get(url).content
df_list = pd.read_html(html)
df = df_list[-1]
res.append(df)
print(res)
df.to_csv('my data.csv')
Any thoughts?
| [
"A few errors:\n\nYour URL was templated incorrectly. It remains at .../{count} literally, without substituting or updating from the loop variable.\nIf you want to get page 1 to 65, use range(1, 66)\nUnless you want to export only the last dataframe, you need to concatenate all of them first\n\n# No count here, we will add it later\nurl = 'https://basketball.realgm.com/international/stats/2023/Averages/Qualified/All/player/All/desc'\nres = []\n\nfor count in range(1, 66):\n # pd.read_html accepts a URL too so no need to make a separate request\n df_list = pd.read_html(f\"{url}/{count}\")\n res.append(df_list[-1])\n\npd.concat(res).to_csv('my data.csv')\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"loops",
"pandas",
"python",
"python_requests"
] | stackoverflow_0074672238_dataframe_loops_pandas_python_python_requests.txt |
Q:
Discord Js - Bot not sending embed
hi please i need some help the bot is giving an error which is yourid , productownerid , productname is not defined in last steps i tried many codes but no one worked for me if anyone can help me please and thank you
if(interaction.customId == 'evv'){
let yourid = interaction.fields.getTextInputValue('ask_1')
let productownerid = interaction.fields.getTextInputValue('ask_2')
let productname = interaction.fields.getTextInputValue('ask_3')
let evalmsg = interaction.fields.getTextInputValue('ask_4')
const exampleEmbed = new MessageEmbed()
.setColor("RANDOM")
.setFields(
{ name: '**Buyer-Name**', value: `<@${yourid}>`}
{ name: '**Owner Of The Product**', value:`**<@${productownerid}>**`}
{ name: '**Product**', value:`**${productname}**`}
{ name: '**Message**', value: `**${evalmsg}**`}
)
.setFooter(`Requested By ${interaction.user.tag} , ${new Date()}`)
let button25 = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId('1')
.setLabel("تقييم")
.setStyle('PRIMARY')
.setEmoji("")
)
await interaction.guild.channels.cache.get("1048414164932108289").send({embeds: [exampleEmbed],components:[button25]})
}
the error is from here :
if (interaction.customId == '1'){
const exampleEmbed2 = new MessageEmbed()
.setColor("RANDOM")
.setFields(
{ name: '**Buyer-Name**', value: `<@${yourid}>`}
{ name: '**Owner Of The Product**', value:`**<@${productownerid}>**`}
{ name: '**Product**', value:`**${productname}**`}
{ name: '**Message**', value: `**${evalmsg}**`}
{ name: '**Evaluation**', value: `****`}
)
.setFooter(`Requested By ${interaction.user.tag} , ${new Date()}`)
interaction.guild.channels.cache.get("1048414164932108289").send({embeds: [exampleEmbed2],components:[]})
}
})```
A:
It looks like the yourid, productownerid, and productname variables are not defined in the second block of code. These variables were defined in the first block of code, but they are not available outside of that block.
To fix this, you can move the definitions of these variables outside of the first block of code so that they are available in the second block. You could also pass these values as arguments to a function, which can be called in both blocks of code.
Here is an example of how you could move the variable definitions outside of the first block of code:
let yourid;
let productownerid;
let productname;
let evalmsg;
if(interaction.customId == 'evv'){
yourid = interaction.fields.getTextInputValue('ask_1')
productownerid = interaction.fields.getTextInputValue('ask_2')
productname = interaction.fields.getTextInputValue('ask_3')
evalmsg = interaction.fields.getTextInputValue('ask_4')
const exampleEmbed = new MessageEmbed()
.setColor("RANDOM")
.setFields(
{ name: '**Buyer-Name**', value: `<@${yourid}>`}
{ name: '**Owner Of The Product**', value:`**<@${productownerid}>**`}
{ name: '**Product**', value:`**${productname}**`}
{ name: '**Message**', value: `**${evalmsg}**`}
)
.setFooter(`Requested By ${interaction.user.tag} , ${new Date()}`)
let button25 = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId('1')
.setLabel("تقييم")
.setStyle('PRIMARY')
.setEmoji("")
)
await interaction.guild.channels.cache.get("1048414164932108289").send({embeds: [exampleEmbed],components:[button25]})
}
if (interaction.customId == '1'){
const exampleEmbed2 = new MessageEmbed()
.setColor("RANDOM")
.setFields(
{ name: '**Buyer-Name**', value: `<@${yourid}>`}
{ name: '**Owner Of The Product**', value:`**<@${productownerid}>**`}
{ name: '**Product**', value:`**${productname}**`}
{ name: '**Message**', value: `**${evalmsg}**`}
{ name: '**Evaluation**', value: `****`}
)
.setFooter(`Requested By ${interaction.user.tag} , ${new Date()}`)
interaction.guild.channels.cache.get("1048414164932108289").send({embeds: [exampleEmbed2],components:[]})
}
})
I hope this helps! Let me know if you have any other questions.
| Discord Js - Bot not sending embed | hi please i need some help the bot is giving an error which is yourid , productownerid , productname is not defined in last steps i tried many codes but no one worked for me if anyone can help me please and thank you
if(interaction.customId == 'evv'){
let yourid = interaction.fields.getTextInputValue('ask_1')
let productownerid = interaction.fields.getTextInputValue('ask_2')
let productname = interaction.fields.getTextInputValue('ask_3')
let evalmsg = interaction.fields.getTextInputValue('ask_4')
const exampleEmbed = new MessageEmbed()
.setColor("RANDOM")
.setFields(
{ name: '**Buyer-Name**', value: `<@${yourid}>`}
{ name: '**Owner Of The Product**', value:`**<@${productownerid}>**`}
{ name: '**Product**', value:`**${productname}**`}
{ name: '**Message**', value: `**${evalmsg}**`}
)
.setFooter(`Requested By ${interaction.user.tag} , ${new Date()}`)
let button25 = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId('1')
.setLabel("تقييم")
.setStyle('PRIMARY')
.setEmoji("")
)
await interaction.guild.channels.cache.get("1048414164932108289").send({embeds: [exampleEmbed],components:[button25]})
}
the error is from here :
if (interaction.customId == '1'){
const exampleEmbed2 = new MessageEmbed()
.setColor("RANDOM")
.setFields(
{ name: '**Buyer-Name**', value: `<@${yourid}>`}
{ name: '**Owner Of The Product**', value:`**<@${productownerid}>**`}
{ name: '**Product**', value:`**${productname}**`}
{ name: '**Message**', value: `**${evalmsg}**`}
{ name: '**Evaluation**', value: `****`}
)
.setFooter(`Requested By ${interaction.user.tag} , ${new Date()}`)
interaction.guild.channels.cache.get("1048414164932108289").send({embeds: [exampleEmbed2],components:[]})
}
})```
| [
"It looks like the yourid, productownerid, and productname variables are not defined in the second block of code. These variables were defined in the first block of code, but they are not available outside of that block.\nTo fix this, you can move the definitions of these variables outside of the first block of code so that they are available in the second block. You could also pass these values as arguments to a function, which can be called in both blocks of code.\nHere is an example of how you could move the variable definitions outside of the first block of code:\nlet yourid;\nlet productownerid;\nlet productname;\nlet evalmsg;\n\nif(interaction.customId == 'evv'){\n yourid = interaction.fields.getTextInputValue('ask_1')\n productownerid = interaction.fields.getTextInputValue('ask_2')\n productname = interaction.fields.getTextInputValue('ask_3')\n evalmsg = interaction.fields.getTextInputValue('ask_4')\n const exampleEmbed = new MessageEmbed()\n .setColor(\"RANDOM\")\n.setFields(\n{ name: '**Buyer-Name**', value: `<@${yourid}>`}\n{ name: '**Owner Of The Product**', value:`**<@${productownerid}>**`}\n{ name: '**Product**', value:`**${productname}**`}\n{ name: '**Message**', value: `**${evalmsg}**`}\n)\n.setFooter(`Requested By ${interaction.user.tag} , ${new Date()}`)\nlet button25 = new MessageActionRow().addComponents(\n new MessageButton()\n .setCustomId('1')\n .setLabel(\"تقييم\")\n .setStyle('PRIMARY')\n .setEmoji(\"\")\n)\nawait interaction.guild.channels.cache.get(\"1048414164932108289\").send({embeds: [exampleEmbed],components:[button25]}) \n }\n\nif (interaction.customId == '1'){\n const exampleEmbed2 = new MessageEmbed()\n .setColor(\"RANDOM\")\n.setFields(\n{ name: '**Buyer-Name**', value: `<@${yourid}>`}\n{ name: '**Owner Of The Product**', value:`**<@${productownerid}>**`}\n{ name: '**Product**', value:`**${productname}**`}\n{ name: '**Message**', value: `**${evalmsg}**`}\n{ name: '**Evaluation**', value: `****`}\n)\n.setFooter(`Requested By ${interaction.user.tag} , ${new Date()}`)\ninteraction.guild.channels.cache.get(\"1048414164932108289\").send({embeds: [exampleEmbed2],components:[]}) \n}\n})\n\nI hope this helps! Let me know if you have any other questions.\n"
] | [
0
] | [] | [] | [
"bots",
"discord.js",
"javascript",
"node.js"
] | stackoverflow_0074672259_bots_discord.js_javascript_node.js.txt |
Q:
How do I set & fetch Environment variable in AWS Lambda Project in C#
I have created AWS Lambda Project in C# (NOT Serverless Application)
I have defined a Environment variable in aws-lambda-tools-defaults.json as below
"environment-variables": {
"my-api": "http://myapihost.com/api/attendance-backfill"
}
In Function.cs, fetching the value as below
var apiUrl = Environment.GetEnvironmentVariable("my-api").ToString();
but it always coming as null.
How do I set & fetch Environment variable?
Thanks!
As per comment.
A:
It's pretty close but after some digging around I found out how to actually set these for local runs using the Mock Lambda Test Tool. It is, in-fact, inside the launchSettings.json file. You want to drop the settings inside the Mock Lambda Test Tool section of the profiles node, not outside it.
{
"profiles": {
"Mock Lambda Test Tool": {
"commandName": "Executable",
"commandLineArgs": "--port 5050",
"workingDirectory": ".\\bin\\Debug\\netcoreapp2.1",
"executablePath": "C:\\Users\\%USERNAME%\\.dotnet\\tools\\dotnet-lambda-test-tool-2.1.exe",
"environmentVariables": {
"environment": "test"
}
}
}
}
A:
Setting Environment variables docs used
There are two places where you’ll need to set environment variables: development-time and deployment-time. To do this, open the launchSettings.json file from under the Properties folder in the Solution Explorer. Then add the following JSON property:
"environmentVariables": {
"my-api": "something"
}
To set environment variables at deployment-time, you can add these to the aws-lambda-tools-defaults.json file. (Just remember to escape the double quote marks.)
environment-variables, its format is: "<key1>=<value1>;<key2>=<value2>;".
In your case you should have
"environment-variables" : "\"my-api\"=\"http://myapihost.com/api/attendance-backfill\";"
Consuming/fetching the environment variables
Consuming the environment variables as part of the Lambda function’s logic is done intuitively in the C# code, by using the System library aws blog:
System.Environment.GetEnvironmentVariable(<key>);
In your case you can use the following;
var apiUrl = System.Environment.GetEnvironmentVariable("my-api");
In this document it is suggested that your approach for fetching environment variable is correct.
var variableValue = Environment.GetEnvironmentVariable("nameOfVariable");
A:
These solutions worked. Need to set environment variables in two places 1.) deployment purpose and 2.) test locally using mock tool
serverless.template file
launchSettings.json file
| How do I set & fetch Environment variable in AWS Lambda Project in C# | I have created AWS Lambda Project in C# (NOT Serverless Application)
I have defined a Environment variable in aws-lambda-tools-defaults.json as below
"environment-variables": {
"my-api": "http://myapihost.com/api/attendance-backfill"
}
In Function.cs, fetching the value as below
var apiUrl = Environment.GetEnvironmentVariable("my-api").ToString();
but it always coming as null.
How do I set & fetch Environment variable?
Thanks!
As per comment.
| [
"It's pretty close but after some digging around I found out how to actually set these for local runs using the Mock Lambda Test Tool. It is, in-fact, inside the launchSettings.json file. You want to drop the settings inside the Mock Lambda Test Tool section of the profiles node, not outside it.\n{\n \"profiles\": {\n \"Mock Lambda Test Tool\": {\n \"commandName\": \"Executable\",\n \"commandLineArgs\": \"--port 5050\",\n \"workingDirectory\": \".\\\\bin\\\\Debug\\\\netcoreapp2.1\",\n \"executablePath\": \"C:\\\\Users\\\\%USERNAME%\\\\.dotnet\\\\tools\\\\dotnet-lambda-test-tool-2.1.exe\",\n \"environmentVariables\": {\n \"environment\": \"test\"\n }\n }\n }\n}\n\n",
"\nSetting Environment variables docs used\n\nThere are two places where you’ll need to set environment variables: development-time and deployment-time. To do this, open the launchSettings.json file from under the Properties folder in the Solution Explorer. Then add the following JSON property:\n \"environmentVariables\": {\n \"my-api\": \"something\"\n }\n\nTo set environment variables at deployment-time, you can add these to the aws-lambda-tools-defaults.json file. (Just remember to escape the double quote marks.)\n environment-variables, its format is: \"<key1>=<value1>;<key2>=<value2>;\".\n\nIn your case you should have \n \"environment-variables\" : \"\\\"my-api\\\"=\\\"http://myapihost.com/api/attendance-backfill\\\";\"\n\n\nConsuming/fetching the environment variables\nConsuming the environment variables as part of the Lambda function’s logic is done intuitively in the C# code, by using the System library aws blog:\nSystem.Environment.GetEnvironmentVariable(<key>);\n\nIn your case you can use the following;\nvar apiUrl = System.Environment.GetEnvironmentVariable(\"my-api\");\n\n\nIn this document it is suggested that your approach for fetching environment variable is correct.\n var variableValue = Environment.GetEnvironmentVariable(\"nameOfVariable\"); \n\n",
"These solutions worked. Need to set environment variables in two places 1.) deployment purpose and 2.) test locally using mock tool\nserverless.template file\n\nlaunchSettings.json file\n\n"
] | [
25,
10,
0
] | [] | [] | [
"amazon_web_services",
"asp.net_core",
"aws_lambda",
"c#",
"environment_variables"
] | stackoverflow_0054843650_amazon_web_services_asp.net_core_aws_lambda_c#_environment_variables.txt |
Q:
Consume a docker container inside Django docker container? Connecting two docker containers
I have a Django container and I want to consume another DL container inside it? For example, I have a Django app that predicting images classes and I want to make the prediction using a docker container and not a python library. That Django app will be containerised as well. In production, I will have three docker containers: Django container + Postgres container + YoloV5 container. How can I link the Django with the YoloV5 so that the prediction inside the Django will be done using the YoloV5?
I want to connect a deep learning container with Django container to make prediction using the DL container and not a python package.
A:
The easiest way to do this is to make a network call to the other container. You may find it simplest to wrap the YoloV5 code in a very thin web layer, e.g. using Flask, to create an API. Then call that in your Django container when you need it using requests.
A:
As suggested by Nick and others, the solution is: by calling the YoloV5 docker container inside Django container using host.docker.internal. I mean that inside Django container (views.py) I used host.docker.internal to call the YoloV5 container.
| Consume a docker container inside Django docker container? Connecting two docker containers | I have a Django container and I want to consume another DL container inside it? For example, I have a Django app that predicting images classes and I want to make the prediction using a docker container and not a python library. That Django app will be containerised as well. In production, I will have three docker containers: Django container + Postgres container + YoloV5 container. How can I link the Django with the YoloV5 so that the prediction inside the Django will be done using the YoloV5?
I want to connect a deep learning container with Django container to make prediction using the DL container and not a python package.
| [
"The easiest way to do this is to make a network call to the other container. You may find it simplest to wrap the YoloV5 code in a very thin web layer, e.g. using Flask, to create an API. Then call that in your Django container when you need it using requests.\n",
"As suggested by Nick and others, the solution is: by calling the YoloV5 docker container inside Django container using host.docker.internal. I mean that inside Django container (views.py) I used host.docker.internal to call the YoloV5 container.\n"
] | [
0,
0
] | [] | [] | [
"deep_learning",
"django",
"docker",
"docker_compose",
"python"
] | stackoverflow_0074634267_deep_learning_django_docker_docker_compose_python.txt |
Q:
Dynamic Cheerleading Pyramid Formation in Unity/C#
first of all, it is my first question and this is not a "Write my code" post. i need a hint from more experienced programmers or math enthusiasts.
I am trying to do pyramid tower formation in my game. I dont know if its about my math and how bad i am in programming or just my brain died while trying to figure out that. I have wrote several algorithms but nothing worked. I need my objects to position in a pyramid when i collect them. Second one next to first, then 3rd one on top of them. 4th one(index 3 in the pic) needs to go down again etc.. If i've collected 4 object; they should be positioned like 0-1-2-3 in the picture.
Here is what i am trying to implement:
I am nowhere close to this. I am just looping through my list and trying to figure out right now with some x-y offset calculations. I am not sure if i should do it manually with pre-filled Vector3 list.
public void SetFormation(int count)
{
Vector3 pos = Vector3.zero;
for (int i = count; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
GameObject gM = Instantiate(prefab);
gM.transform.SetParent(transform);
gM.transform.position = new Vector3(pos.x, pos.y, 0);
pos += new Vector3(xOffset, 0, 0);
}
pos += new Vector3(0, yOffset, 0);
}
}
A:
Swap the cheerleaders out for acrobats. Instead of a pyramid, the acrobats stack directly on top of each other in columns, standing straight up and down on each others shoulders. The column numbers start on the left, with the leftmost column designated as 1, and increase as you move to the right.
Here are the rules for placing acrobats:
In column 1, you stack 1 acrobat.
In column 2, you stack 2 acrobats.
In column 3, you stack 3 acrobats.
Etc...
This is what it looks like for 9 acrobats:
9
5 8
2 4 7
0 1 3 6
Now imagine the acrobats are insanely strong and can stand off-center so that only one leg is on the person below, opposite leg to opposite shoulder. They all get offset in the same direction, making each column lean to the side.
Each stacked acrobat is offset by exactly half the distance between the acrobats in the bottom row, so it looks like they are standing directly on top of the two acrobats underneath:
9
5 8
2 4 7
0 1 3 6
Look familiar? The pyramid is not really a pyramid, it's a leaning collection of columns!
So the algorithm is simply to keep placing the correct number of acrobats in each column, offsetting each one to the left a half column as you go up. Whenever you reach the top of the column you start a new one and repeat until you've reached the requisite number of acrobats. The starting position of each bottom acrobat in a new column is easy enough to calculate, as it is simply the column number minus one, multiplied by the horizontal offset distance, to the right of the "origin" (bottom left) of the pyramid.
I'm not a Unity programmer, this is written for C# WinForms, but I'm pretty sure you'll be able to understand both the algorithm and the code.
Here's the core part of the program:
private int xOffset = 45;
private int yOffset = 45;
private int cheerleaderRadius = 15;
private int numCheerleaders = 1;
private void MainForm_Paint(object sender, PaintEventArgs e)
{
// set origin at the bottom left of the form
Point origin = new Point(cheerleaderRadius * 2, this.ClientRectangle.Height - (cheerleaderRadius*2));
int currentCheerleader = 1;
int currentColumnNumber = 1;
int cheerleadersInCurrentColumn;
while (currentCheerleader <= numCheerleaders)
{
cheerleadersInCurrentColumn = 1;
Point position = new Point(origin.X + (currentColumnNumber - 1) * xOffset, origin.Y);
while(cheerleadersInCurrentColumn<=currentColumnNumber && currentCheerleader<=numCheerleaders)
{
drawCheerleader(e.Graphics, position, (currentCheerleader - 1));
position.Offset(-xOffset / 2, -yOffset);
cheerleadersInCurrentColumn++;
currentCheerleader++;
}
currentColumnNumber++;
}
}
This is what it looks like in action. Each time the number of cheerleaders is changed, the pyramid below gets redrawn:
Here is the entire C# WinForms program:
public partial class MainForm : Form
{
private int xOffset = 45;
private int yOffset = 45;
private int cheerleaderRadius = 15;
private int numCheerleaders = 1;
private StringFormat sf = new StringFormat();
public MainForm()
{
InitializeComponent();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
this.Paint += MainForm_Paint;
this.SizeChanged += MainForm_SizeChanged;
}
private void MainForm_SizeChanged(object sender, EventArgs e)
{
this.Invalidate();
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
numCheerleaders = (int)numericUpDown1.Value;
this.Invalidate();
}
private void MainForm_Paint(object sender, PaintEventArgs e)
{
// set origin at the bottom left of the form
Point origin = new Point(cheerleaderRadius * 2, this.ClientRectangle.Height - (cheerleaderRadius*2));
int currentCheerleader = 1;
int currentColumnNumber = 1;
int cheerleadersInCurrentColumn;
while (currentCheerleader <= numCheerleaders)
{
cheerleadersInCurrentColumn = 1;
Point position = new Point(origin.X + (currentColumnNumber - 1) * xOffset, origin.Y);
while(cheerleadersInCurrentColumn<=currentColumnNumber && currentCheerleader<=numCheerleaders)
{
drawCheerleader(e.Graphics, position, (currentCheerleader - 1));
position.Offset(-xOffset / 2, -yOffset);
cheerleadersInCurrentColumn++;
currentCheerleader++;
}
currentColumnNumber++;
}
}
private void drawCheerleader(Graphics g, Point pos, int number)
{
RectangleF rc = new RectangleF(pos, new Size(1, 1));
rc.Inflate(cheerleaderRadius, cheerleaderRadius);
g.DrawEllipse(Pens.Black, rc);
g.DrawString(number.ToString(), this.Font, Brushes.Black, rc, sf);
}
}
| Dynamic Cheerleading Pyramid Formation in Unity/C# | first of all, it is my first question and this is not a "Write my code" post. i need a hint from more experienced programmers or math enthusiasts.
I am trying to do pyramid tower formation in my game. I dont know if its about my math and how bad i am in programming or just my brain died while trying to figure out that. I have wrote several algorithms but nothing worked. I need my objects to position in a pyramid when i collect them. Second one next to first, then 3rd one on top of them. 4th one(index 3 in the pic) needs to go down again etc.. If i've collected 4 object; they should be positioned like 0-1-2-3 in the picture.
Here is what i am trying to implement:
I am nowhere close to this. I am just looping through my list and trying to figure out right now with some x-y offset calculations. I am not sure if i should do it manually with pre-filled Vector3 list.
public void SetFormation(int count)
{
Vector3 pos = Vector3.zero;
for (int i = count; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
GameObject gM = Instantiate(prefab);
gM.transform.SetParent(transform);
gM.transform.position = new Vector3(pos.x, pos.y, 0);
pos += new Vector3(xOffset, 0, 0);
}
pos += new Vector3(0, yOffset, 0);
}
}
| [
"Swap the cheerleaders out for acrobats. Instead of a pyramid, the acrobats stack directly on top of each other in columns, standing straight up and down on each others shoulders. The column numbers start on the left, with the leftmost column designated as 1, and increase as you move to the right.\nHere are the rules for placing acrobats:\nIn column 1, you stack 1 acrobat.\nIn column 2, you stack 2 acrobats.\nIn column 3, you stack 3 acrobats.\nEtc...\n\nThis is what it looks like for 9 acrobats:\n 9\n 5 8\n 2 4 7\n0 1 3 6\n\nNow imagine the acrobats are insanely strong and can stand off-center so that only one leg is on the person below, opposite leg to opposite shoulder. They all get offset in the same direction, making each column lean to the side.\nEach stacked acrobat is offset by exactly half the distance between the acrobats in the bottom row, so it looks like they are standing directly on top of the two acrobats underneath:\n 9\n 5 8\n 2 4 7\n0 1 3 6\n\nLook familiar? The pyramid is not really a pyramid, it's a leaning collection of columns!\nSo the algorithm is simply to keep placing the correct number of acrobats in each column, offsetting each one to the left a half column as you go up. Whenever you reach the top of the column you start a new one and repeat until you've reached the requisite number of acrobats. The starting position of each bottom acrobat in a new column is easy enough to calculate, as it is simply the column number minus one, multiplied by the horizontal offset distance, to the right of the \"origin\" (bottom left) of the pyramid.\nI'm not a Unity programmer, this is written for C# WinForms, but I'm pretty sure you'll be able to understand both the algorithm and the code.\nHere's the core part of the program:\nprivate int xOffset = 45;\nprivate int yOffset = 45;\nprivate int cheerleaderRadius = 15;\n\nprivate int numCheerleaders = 1;\n\nprivate void MainForm_Paint(object sender, PaintEventArgs e)\n{\n // set origin at the bottom left of the form\n Point origin = new Point(cheerleaderRadius * 2, this.ClientRectangle.Height - (cheerleaderRadius*2));\n \n int currentCheerleader = 1;\n int currentColumnNumber = 1;\n int cheerleadersInCurrentColumn;\n while (currentCheerleader <= numCheerleaders)\n {\n cheerleadersInCurrentColumn = 1;\n Point position = new Point(origin.X + (currentColumnNumber - 1) * xOffset, origin.Y);\n while(cheerleadersInCurrentColumn<=currentColumnNumber && currentCheerleader<=numCheerleaders)\n {\n drawCheerleader(e.Graphics, position, (currentCheerleader - 1));\n position.Offset(-xOffset / 2, -yOffset);\n cheerleadersInCurrentColumn++;\n currentCheerleader++;\n }\n currentColumnNumber++;\n } \n}\n\nThis is what it looks like in action. Each time the number of cheerleaders is changed, the pyramid below gets redrawn:\n\nHere is the entire C# WinForms program:\npublic partial class MainForm : Form\n{\n \n private int xOffset = 45;\n private int yOffset = 45;\n private int cheerleaderRadius = 15;\n\n private int numCheerleaders = 1;\n \n private StringFormat sf = new StringFormat();\n\n public MainForm()\n {\n InitializeComponent();\n sf.Alignment = StringAlignment.Center;\n sf.LineAlignment = StringAlignment.Center;\n this.Paint += MainForm_Paint;\n this.SizeChanged += MainForm_SizeChanged;\n }\n\n private void MainForm_SizeChanged(object sender, EventArgs e)\n {\n this.Invalidate();\n }\n\n private void numericUpDown1_ValueChanged(object sender, EventArgs e)\n {\n numCheerleaders = (int)numericUpDown1.Value;\n this.Invalidate();\n }\n\n private void MainForm_Paint(object sender, PaintEventArgs e)\n {\n // set origin at the bottom left of the form\n Point origin = new Point(cheerleaderRadius * 2, this.ClientRectangle.Height - (cheerleaderRadius*2));\n \n int currentCheerleader = 1;\n int currentColumnNumber = 1;\n int cheerleadersInCurrentColumn;\n while (currentCheerleader <= numCheerleaders)\n {\n cheerleadersInCurrentColumn = 1;\n Point position = new Point(origin.X + (currentColumnNumber - 1) * xOffset, origin.Y);\n while(cheerleadersInCurrentColumn<=currentColumnNumber && currentCheerleader<=numCheerleaders)\n {\n drawCheerleader(e.Graphics, position, (currentCheerleader - 1));\n position.Offset(-xOffset / 2, -yOffset);\n cheerleadersInCurrentColumn++;\n currentCheerleader++;\n }\n currentColumnNumber++;\n } \n }\n\n private void drawCheerleader(Graphics g, Point pos, int number)\n {\n RectangleF rc = new RectangleF(pos, new Size(1, 1));\n rc.Inflate(cheerleaderRadius, cheerleaderRadius);\n g.DrawEllipse(Pens.Black, rc);\n g.DrawString(number.ToString(), this.Font, Brushes.Black, rc, sf);\n }\n\n}\n\n"
] | [
2
] | [] | [] | [
"algorithm",
"c#",
"game_development",
"sorting",
"unity3d"
] | stackoverflow_0074668397_algorithm_c#_game_development_sorting_unity3d.txt |
Q:
How to Combine multiple arrays and increment the value which have the same key
I wanted to combine multiple arrays and increment the values if they had the same key from an array, although I have no clue and what is the efficient way to merge and increment it using the existing PHP libraries and which of them is the most suitable?
To visualize, I have this multidimensional array with their respective keys
`
Array
(
[0] => Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
[7] => 1
[16] => 1
)
[1] => Array
(
[1] => 1
[3] => 1
[5] => 1
[7] => 1
[15] => 1
[16] => 1
[2] => 1
)
[2] => Array
(
[1] => 1
[2] => 1
[6] => 1
[10] => 1
)
[3] => Array
(
[9] => 1
[14] => 1
[1] => 1
[2] => 1
[4] => 1
)
[4] => Array
(
[2] => 1
[6] => 1
)
[5] => Array
(
[1] => 1
[2] => 1
[3] => 1
[5] => 1
[7] => 1
[10] => 1
[12] => 1
[13] => 1
)
)
`
The expected output that I wanted to see is
`
Array
(
[0] => Array
(
[1] => 5
[2] => 6
[3] => 3
[4] => 2
[5] => 3
[6] => 2
[7] => 3
[9] => 1
[10] => 2
[12] => 1
[13] => 1
[14] => 1
[15] => 1
[16] => 2
)
)
`
I tried examining this piece of code although i have no idea what to do when it consists of multiple multidimensional arrays
`
<?php
$arr1 = [
1 => 199,
2 => 1991
];
$arr2 = [
1 => 199,
2 => 199
];
$allKeys = array_unique(array_merge(array_keys($arr1),array_keys($arr2)));
$result = [];
foreach ($allKeys as $key) {
$result[$key] = [];
if (array_key_exists($key,$arr1)) {
$result[$key][] = $arr1[$key];
}
if (array_key_exists($key,$arr2)) {
$result[$key][] = $arr2[$key];
}
}
$endResult = array_map('array_sum',$result);
print_r($endResult);
`
A:
You don't need the value (key => value) to do this calculation, you can make your tables lighter :)
To combine multiple arrays and increment the values that have the same key in PHP, you can use the array_count_values() function. This function takes an array as input and returns an array that contains the number of occurrences of each value in the input array.
<?php
// Define the arrays to combine
$arr1 = [1, 2, 3];
$arr2 = [2, 3, 4];
$arr3 = [3, 4, 5];
// Combine the arrays using array_count_values()
$counter = array_count_values(array_merge($arr1, $arr2, $arr3));
// Print the resulting counter
print_r($counter);
// Output:
// Array
// (
// [1] => 1
// [2] => 2
// [3] => 3
// [4] => 2
// [5] => 1
// )
?>
| How to Combine multiple arrays and increment the value which have the same key | I wanted to combine multiple arrays and increment the values if they had the same key from an array, although I have no clue and what is the efficient way to merge and increment it using the existing PHP libraries and which of them is the most suitable?
To visualize, I have this multidimensional array with their respective keys
`
Array
(
[0] => Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
[7] => 1
[16] => 1
)
[1] => Array
(
[1] => 1
[3] => 1
[5] => 1
[7] => 1
[15] => 1
[16] => 1
[2] => 1
)
[2] => Array
(
[1] => 1
[2] => 1
[6] => 1
[10] => 1
)
[3] => Array
(
[9] => 1
[14] => 1
[1] => 1
[2] => 1
[4] => 1
)
[4] => Array
(
[2] => 1
[6] => 1
)
[5] => Array
(
[1] => 1
[2] => 1
[3] => 1
[5] => 1
[7] => 1
[10] => 1
[12] => 1
[13] => 1
)
)
`
The expected output that I wanted to see is
`
Array
(
[0] => Array
(
[1] => 5
[2] => 6
[3] => 3
[4] => 2
[5] => 3
[6] => 2
[7] => 3
[9] => 1
[10] => 2
[12] => 1
[13] => 1
[14] => 1
[15] => 1
[16] => 2
)
)
`
I tried examining this piece of code although i have no idea what to do when it consists of multiple multidimensional arrays
`
<?php
$arr1 = [
1 => 199,
2 => 1991
];
$arr2 = [
1 => 199,
2 => 199
];
$allKeys = array_unique(array_merge(array_keys($arr1),array_keys($arr2)));
$result = [];
foreach ($allKeys as $key) {
$result[$key] = [];
if (array_key_exists($key,$arr1)) {
$result[$key][] = $arr1[$key];
}
if (array_key_exists($key,$arr2)) {
$result[$key][] = $arr2[$key];
}
}
$endResult = array_map('array_sum',$result);
print_r($endResult);
`
| [
"You don't need the value (key => value) to do this calculation, you can make your tables lighter :)\nTo combine multiple arrays and increment the values that have the same key in PHP, you can use the array_count_values() function. This function takes an array as input and returns an array that contains the number of occurrences of each value in the input array.\n<?php\n// Define the arrays to combine\n$arr1 = [1, 2, 3];\n$arr2 = [2, 3, 4];\n$arr3 = [3, 4, 5];\n\n// Combine the arrays using array_count_values()\n$counter = array_count_values(array_merge($arr1, $arr2, $arr3));\n\n// Print the resulting counter\nprint_r($counter); \n// Output:\n// Array\n// (\n// [1] => 1\n// [2] => 2\n// [3] => 3\n// [4] => 2\n// [5] => 1\n// )\n?>\n\n"
] | [
0
] | [] | [] | [
"php"
] | stackoverflow_0074665636_php.txt |
Q:
Cloudant from Cloudflare workers giving authentication error
I am using Cloudant as my DB and am looking to use Cloudflare workers as the public-facing interface.
Unfortunately, I've been having a number of errors authenticating to the database using libraries like PouchDB. Instead, I'm trying to get the most basic connection possible and build up from something working.
From a basic curl command on my computer, I can query my view. Attempting to do the same thing from a Worker is giving me an "unauthorized" error.
The specific code (with the username and password obviously masked)
(() => {
// src/index.js
async function handleRequest() {
let results = await fetch("https://<key>:<pass>@<uid>-bluemix.cloudantnosqldb.appdomain.cloud/mnb/_design/score/_view/score?reduce=true&group=true");
results = await results.json();
let str = JSON.stringify(results);
return new Response(str, init);
}
addEventListener("fetch", (event) => {
return event.respondWith(handleRequest());
});
})();
//# sourceMappingURL=index.js.map
The error I'm getting.
{
"error": "unauthorized",
"reason": "one of _view, _design, _reader is required for this request"
}
Is there something I'm not getting with the fetch call?
UPDATE
To confirm, the curl command I used was dead simple
curl https://<key>:<pass>@<uid>-bluemix.cloudantnosqldb.appdomain.cloud/mnb/_design/score/_view/score?reduce=true\&group=true
I cut paste from the worker into the terminal to be sure I didn't have a typo
A:
Try to pass your credentials using the Authorization header in your request.
The following example targets a page protected using Basic Authentication with credentials user / pass.
const b = await fetch('https://authenticationtest.com/HTTPAuth/', {
headers: {
'Authorization': `Basic ${btoa('user:pass')}`
}
})
| Cloudant from Cloudflare workers giving authentication error | I am using Cloudant as my DB and am looking to use Cloudflare workers as the public-facing interface.
Unfortunately, I've been having a number of errors authenticating to the database using libraries like PouchDB. Instead, I'm trying to get the most basic connection possible and build up from something working.
From a basic curl command on my computer, I can query my view. Attempting to do the same thing from a Worker is giving me an "unauthorized" error.
The specific code (with the username and password obviously masked)
(() => {
// src/index.js
async function handleRequest() {
let results = await fetch("https://<key>:<pass>@<uid>-bluemix.cloudantnosqldb.appdomain.cloud/mnb/_design/score/_view/score?reduce=true&group=true");
results = await results.json();
let str = JSON.stringify(results);
return new Response(str, init);
}
addEventListener("fetch", (event) => {
return event.respondWith(handleRequest());
});
})();
//# sourceMappingURL=index.js.map
The error I'm getting.
{
"error": "unauthorized",
"reason": "one of _view, _design, _reader is required for this request"
}
Is there something I'm not getting with the fetch call?
UPDATE
To confirm, the curl command I used was dead simple
curl https://<key>:<pass>@<uid>-bluemix.cloudantnosqldb.appdomain.cloud/mnb/_design/score/_view/score?reduce=true\&group=true
I cut paste from the worker into the terminal to be sure I didn't have a typo
| [
"Try to pass your credentials using the Authorization header in your request.\nThe following example targets a page protected using Basic Authentication with credentials user / pass.\n const b = await fetch('https://authenticationtest.com/HTTPAuth/', { \n headers: {\n 'Authorization': `Basic ${btoa('user:pass')}`\n }\n })\n\n"
] | [
0
] | [] | [] | [
"cloudant",
"cloudflare_workers",
"javascript"
] | stackoverflow_0074579574_cloudant_cloudflare_workers_javascript.txt |
Q:
Invalid Shape Error when trying to leverage Keras's VGG16 pretrained model
I am trying to leverage kera's VGG16 model in my own image classification problem. My code is heavily based upon Francois Chollet's example (Chapter 8 of Deep Learning in Python - code).
I have three classes I'm trying to predict. Directory structure:
data/
training/
class_1
class_2
class_3
Note: this my first time working with Keras so I may just be doing something wrong.
My call to model.fit() fails with: ValueError: Shapes (32, 1) and (32, 3) are incompatible. See the bottom of this question for the full error messages. If I look at the output from .summary() calls, I don't see a layer of dimension (32, 1).
import pathlib
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.utils import image_dataset_from_directory
DATA_DIR = pathlib.Path('./data/')
batch_size = 32
img_width = image_height = 256
train_dataset = image_dataset_from_directory(
DATA_DIR / "training",
image_size=img_width_height,
batch_size=batch_size)
validation_dataset = image_dataset_from_directory(
DATA_DIR / "validation",
image_size=img_width_height,
batch_size=batch_size)
# Found 128400 files belonging to 3 classes.
# Found 15600 files belonging to 3 classes.
vgg16_convolution_base = keras.applications.vgg16.VGG16(
weights="imagenet",
include_top=False,
input_shape=(img_width, image_height, 3))
vgg16_convolution_base.summary()
# block3_conv3 (Conv2D) (None, 64, 64, 256) 590080
# block3_pool (MaxPooling2D) (None, 32, 32, 256) 0
# block4_conv1 (Conv2D) (None, 32, 32, 512) 1180160
# block4_conv2 (Conv2D) (None, 32, 32, 512) 2359808
# block4_conv3 (Conv2D) (None, 32, 32, 512) 2359808
# block4_pool (MaxPooling2D) (None, 16, 16, 512) 0
# block5_conv1 (Conv2D) (None, 16, 16, 512) 2359808
# block5_conv2 (Conv2D) (None, 16, 16, 512) 2359808
# block5_conv3 (Conv2D) (None, 16, 16, 512) 2359808
# block5_pool (MaxPooling2D) (None, 8, 8, 512) 0
def get_features_and_labels(dataset):
all_features = []
all_labels = []
for images, labels in dataset:
preprocessed_images = keras.applications.vgg16.preprocess_input(images)
features = vgg16_convolution_base.predict(preprocessed_images)
all_features.append(features)
all_labels.append(labels)
return np.concatenate(all_features), np.concatenate(all_labels)
train_features, train_labels = get_features_and_labels(train_dataset)
val_features, val_labels = get_features_and_labels(validation_dataset)
print(train_features.shape)
print(train_labels.shape)
# (128400, 8, 8, 512)
# (128400,)
print(val_features.shape)
print(val_labels.shape)
# (15600, 8, 8, 512)
# (15600,)
inputs = keras.Input(shape=(8, 8, 512))
x = layers.Flatten()(inputs)
x = layers.Dense(256)(x)
x = layers.Dropout(0.5)(x)
outputs = layers.Dense(3, activation="softmax")(x)
model = keras.Model(inputs, outputs)
model.compile(loss="categorical_crossentropy",
optimizer="rmsprop",
metrics=["accuracy"])
model.summary()
# input_4 (InputLayer) [(None, 8, 8, 512)] 0
# flatten_1 (Flatten) (None, 32768) 0
# dense_2 (Dense) (None, 256) 8388864
# dropout_1 (Dropout) (None, 256) 0
# dense_3 (Dense) (None, 3) 771
# ================================================================
# Total params: 8,389,635
# Trainable params: 8,389,635
history = model.fit(
train_features, train_labels,
epochs=20,
validation_data=(val_features, val_labels)
My call to model.fit() fails with: ValueError: Shapes (32, 1) and (32, 3) are incompatible
...
File "C:\Users\x\anaconda3\lib\site-packages\keras\losses.py", line 1990, in categorical_crossentropy
return backend.categorical_crossentropy(
File "C:\Users\x\anaconda3\lib\site-packages\keras\backend.py", line 5529, in categorical_crossentropy
target.shape.assert_is_compatible_with(output.shape)
full traceback
A:
The categorical_crossentropy loss for 3 classes together with the batch size of 32 dictate the shape of labels (for each bach) to be (32, 3).
The labels are currently ordinal: 0, 1, and 2. One can use the SparseCategoricalCrossentropy loss for ordinal labels:
loss= tf.keras.losses.SparseCategoricalCrossentropy()
Alternatively, one can still use the categorical_crossentropy loss, but in conjunction with the one-hot encoded labels (1, 0, 0) for 0, (0, 1, 0) for 1, and (0, 0, 1) for 2. The following code snippet can accomplish such an encoding:
#one-hot encoding
num_class = len(set(train_labels))
train_labels=tf.one_hot(indices=train_labels, depth=num_class)
val_labels=tf.one_hot(indices=val_labels, depth=num_class)
The nature of data (ordered or unordered) helps determining whether one-hot encoding is preferred or ordinal.
| Invalid Shape Error when trying to leverage Keras's VGG16 pretrained model | I am trying to leverage kera's VGG16 model in my own image classification problem. My code is heavily based upon Francois Chollet's example (Chapter 8 of Deep Learning in Python - code).
I have three classes I'm trying to predict. Directory structure:
data/
training/
class_1
class_2
class_3
Note: this my first time working with Keras so I may just be doing something wrong.
My call to model.fit() fails with: ValueError: Shapes (32, 1) and (32, 3) are incompatible. See the bottom of this question for the full error messages. If I look at the output from .summary() calls, I don't see a layer of dimension (32, 1).
import pathlib
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.utils import image_dataset_from_directory
DATA_DIR = pathlib.Path('./data/')
batch_size = 32
img_width = image_height = 256
train_dataset = image_dataset_from_directory(
DATA_DIR / "training",
image_size=img_width_height,
batch_size=batch_size)
validation_dataset = image_dataset_from_directory(
DATA_DIR / "validation",
image_size=img_width_height,
batch_size=batch_size)
# Found 128400 files belonging to 3 classes.
# Found 15600 files belonging to 3 classes.
vgg16_convolution_base = keras.applications.vgg16.VGG16(
weights="imagenet",
include_top=False,
input_shape=(img_width, image_height, 3))
vgg16_convolution_base.summary()
# block3_conv3 (Conv2D) (None, 64, 64, 256) 590080
# block3_pool (MaxPooling2D) (None, 32, 32, 256) 0
# block4_conv1 (Conv2D) (None, 32, 32, 512) 1180160
# block4_conv2 (Conv2D) (None, 32, 32, 512) 2359808
# block4_conv3 (Conv2D) (None, 32, 32, 512) 2359808
# block4_pool (MaxPooling2D) (None, 16, 16, 512) 0
# block5_conv1 (Conv2D) (None, 16, 16, 512) 2359808
# block5_conv2 (Conv2D) (None, 16, 16, 512) 2359808
# block5_conv3 (Conv2D) (None, 16, 16, 512) 2359808
# block5_pool (MaxPooling2D) (None, 8, 8, 512) 0
def get_features_and_labels(dataset):
all_features = []
all_labels = []
for images, labels in dataset:
preprocessed_images = keras.applications.vgg16.preprocess_input(images)
features = vgg16_convolution_base.predict(preprocessed_images)
all_features.append(features)
all_labels.append(labels)
return np.concatenate(all_features), np.concatenate(all_labels)
train_features, train_labels = get_features_and_labels(train_dataset)
val_features, val_labels = get_features_and_labels(validation_dataset)
print(train_features.shape)
print(train_labels.shape)
# (128400, 8, 8, 512)
# (128400,)
print(val_features.shape)
print(val_labels.shape)
# (15600, 8, 8, 512)
# (15600,)
inputs = keras.Input(shape=(8, 8, 512))
x = layers.Flatten()(inputs)
x = layers.Dense(256)(x)
x = layers.Dropout(0.5)(x)
outputs = layers.Dense(3, activation="softmax")(x)
model = keras.Model(inputs, outputs)
model.compile(loss="categorical_crossentropy",
optimizer="rmsprop",
metrics=["accuracy"])
model.summary()
# input_4 (InputLayer) [(None, 8, 8, 512)] 0
# flatten_1 (Flatten) (None, 32768) 0
# dense_2 (Dense) (None, 256) 8388864
# dropout_1 (Dropout) (None, 256) 0
# dense_3 (Dense) (None, 3) 771
# ================================================================
# Total params: 8,389,635
# Trainable params: 8,389,635
history = model.fit(
train_features, train_labels,
epochs=20,
validation_data=(val_features, val_labels)
My call to model.fit() fails with: ValueError: Shapes (32, 1) and (32, 3) are incompatible
...
File "C:\Users\x\anaconda3\lib\site-packages\keras\losses.py", line 1990, in categorical_crossentropy
return backend.categorical_crossentropy(
File "C:\Users\x\anaconda3\lib\site-packages\keras\backend.py", line 5529, in categorical_crossentropy
target.shape.assert_is_compatible_with(output.shape)
full traceback
| [
"The categorical_crossentropy loss for 3 classes together with the batch size of 32 dictate the shape of labels (for each bach) to be (32, 3).\nThe labels are currently ordinal: 0, 1, and 2. One can use the SparseCategoricalCrossentropy loss for ordinal labels:\nloss= tf.keras.losses.SparseCategoricalCrossentropy()\n\nAlternatively, one can still use the categorical_crossentropy loss, but in conjunction with the one-hot encoded labels (1, 0, 0) for 0, (0, 1, 0) for 1, and (0, 0, 1) for 2. The following code snippet can accomplish such an encoding:\n#one-hot encoding\nnum_class = len(set(train_labels))\ntrain_labels=tf.one_hot(indices=train_labels, depth=num_class)\nval_labels=tf.one_hot(indices=val_labels, depth=num_class)\n\nThe nature of data (ordered or unordered) helps determining whether one-hot encoding is preferred or ordinal.\n"
] | [
0
] | [] | [] | [
"deep_learning",
"keras",
"python",
"vgg_net"
] | stackoverflow_0074667517_deep_learning_keras_python_vgg_net.txt |
Q:
Strapi: preventing the creation of an entry with the beforeCreate lifecycle hook
Is there a way to prevent strapi from creating an entry with the use of the lifecycle hook beforeCreate, because if a just throw an error, the error is thrown but the entry is still created
Throwing the error doesn't prevent strapi from creating the new entry
What could I do?
thanks in advance
A:
Strapi lifecycles are ok
When you throw an error from, say, beforeCreate, it will prevent strapi from creating the entry
In my case it was not working, because I have the throw Error inside a try-catch block, then the throw error interrupts the try block but not the beforeCreate
I'm using "throw new ForbiddenError(..." because I read it in a forum
I have a try block because I'm reading a table
I had to use a local variable
You know how...
| Strapi: preventing the creation of an entry with the beforeCreate lifecycle hook | Is there a way to prevent strapi from creating an entry with the use of the lifecycle hook beforeCreate, because if a just throw an error, the error is thrown but the entry is still created
Throwing the error doesn't prevent strapi from creating the new entry
What could I do?
thanks in advance
| [
"Strapi lifecycles are ok\nWhen you throw an error from, say, beforeCreate, it will prevent strapi from creating the entry\nIn my case it was not working, because I have the throw Error inside a try-catch block, then the throw error interrupts the try block but not the beforeCreate\nI'm using \"throw new ForbiddenError(...\" because I read it in a forum\nI have a try block because I'm reading a table\nI had to use a local variable\nYou know how...\n"
] | [
0
] | [] | [] | [
"lifecycle",
"strapi"
] | stackoverflow_0074669845_lifecycle_strapi.txt |
Q:
Is a StateObject more performant when instantiated in a View instead of the top-level App?
I've observed performance differences based on the location of my instantiated StateObject. Specifically, I noticed that when my top-level View owns the StateObject, my app's usage on the main thread decreases by ~5%. For some reason, instantiating this StateObject in a SwiftUI App is less performant. My expectation is that performance would be identical since nothing else changed.
While that 5% might not seem like much, the result might be 10-15% higher CPU utilization on some devices. It's worth nothing that in my StateObject, I've defined a CADisplayLink which runs a callback on every frame, so this is where most of the compute gets used.
For some reason, this:
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
MyView()
}
}
}
struct MyView: View {
@StateObject var someStateObject = SomeStateObject()
var body: some View {
Text("Hello World")
}
}
Is more performant than this:
@main
struct MyApp: App {
@StateObject var someStateObject = SomeStateObject()
var body: some Scene {
WindowGroup {
MyView()
}
}
}
struct MyView: View {
var body: some View {
Text("Hello World")
}
}
Is there something about SwiftUI's App that would create these performance differences?
A:
It turned out the issue had to do with CADisplayLink getting called from the App level, rather than the View. The perf issue was fixed once I moved my CADisplayLink to the view.
A:
It's difficult to say without more information about the specifics of your StateObject and the differences in performance you're observing. However, there are a few potential reasons why instantiating a StateObject in a View might lead to better performance than instantiating it in the top-level App:
If the StateObject is only used by a specific View, instantiating it in that View allows SwiftUI to optimize its usage by only initializing the StateObject when it's actually needed. In contrast, if the StateObject is instantiated at the top-level App, it will be initialized even if it's not used by all of the views in your app.
If the StateObject is managing a resource (e.g. a network connection or a file) that is only needed by a specific View, instantiating it in that View allows SwiftUI to release the resource when it's no longer needed. This can help to reduce memory usage and improve performance.
If the StateObject is using a CADisplayLink (which triggers a callback on every frame of the display), instantiating it in a View allows SwiftUI to automatically pause and resume the CADisplayLink as needed, depending on whether the View is visible on the screen. This can help to reduce the amount of processing that's done when the View is not visible, which can improve overall performance.
In general, it's a good idea to think about the scope of your StateObject and where it's used in your app, and instantiate it in the most appropriate place. This can help to optimize its usage and improve performance.
| Is a StateObject more performant when instantiated in a View instead of the top-level App? | I've observed performance differences based on the location of my instantiated StateObject. Specifically, I noticed that when my top-level View owns the StateObject, my app's usage on the main thread decreases by ~5%. For some reason, instantiating this StateObject in a SwiftUI App is less performant. My expectation is that performance would be identical since nothing else changed.
While that 5% might not seem like much, the result might be 10-15% higher CPU utilization on some devices. It's worth nothing that in my StateObject, I've defined a CADisplayLink which runs a callback on every frame, so this is where most of the compute gets used.
For some reason, this:
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
MyView()
}
}
}
struct MyView: View {
@StateObject var someStateObject = SomeStateObject()
var body: some View {
Text("Hello World")
}
}
Is more performant than this:
@main
struct MyApp: App {
@StateObject var someStateObject = SomeStateObject()
var body: some Scene {
WindowGroup {
MyView()
}
}
}
struct MyView: View {
var body: some View {
Text("Hello World")
}
}
Is there something about SwiftUI's App that would create these performance differences?
| [
"It turned out the issue had to do with CADisplayLink getting called from the App level, rather than the View. The perf issue was fixed once I moved my CADisplayLink to the view.\n",
"It's difficult to say without more information about the specifics of your StateObject and the differences in performance you're observing. However, there are a few potential reasons why instantiating a StateObject in a View might lead to better performance than instantiating it in the top-level App:\n\nIf the StateObject is only used by a specific View, instantiating it in that View allows SwiftUI to optimize its usage by only initializing the StateObject when it's actually needed. In contrast, if the StateObject is instantiated at the top-level App, it will be initialized even if it's not used by all of the views in your app.\n\nIf the StateObject is managing a resource (e.g. a network connection or a file) that is only needed by a specific View, instantiating it in that View allows SwiftUI to release the resource when it's no longer needed. This can help to reduce memory usage and improve performance.\n\nIf the StateObject is using a CADisplayLink (which triggers a callback on every frame of the display), instantiating it in a View allows SwiftUI to automatically pause and resume the CADisplayLink as needed, depending on whether the View is visible on the screen. This can help to reduce the amount of processing that's done when the View is not visible, which can improve overall performance.\n\n\nIn general, it's a good idea to think about the scope of your StateObject and where it's used in your app, and instantiate it in the most appropriate place. This can help to optimize its usage and improve performance.\n"
] | [
1,
0
] | [
"It is difficult to say for certain without more information, but there are a few reasons why instantiating a StateObject in a View instead of the top-level App might result in better performance.\nOne possibility is that the App struct is created and initialized when the app launches, whereas the View struct is only created and initialized when it is first displayed. This means that the StateObject in the App example would be created and initialized even if it is never used, whereas in the View example it would only be created and initialized when the View is displayed. This could result in better performance if the StateObject is not used until later in the app.\nAnother possibility is that the App struct is a global object that exists for the lifetime of the app, whereas the View struct is only in scope while the View is being displayed. This means that the StateObject in the App example would continue to exist and potentially consume resources even when it is not being used, whereas in the View example it would be deallocated when the View is no longer displayed. This could result in better performance if the StateObject is only needed for a short period of time.\nOverall, it is generally best to instantiate objects at the lowest level possible, where they are only created and initialized when they are needed, and deallocated when they are no longer needed. This can help to improve performance by reducing unnecessary resource consumption.\n"
] | [
-2
] | [
"swift",
"swiftui"
] | stackoverflow_0074671532_swift_swiftui.txt |
Q:
How to ignore some files and directories using .gitgnore?
I have a directory structured like this:
main_folder
.git
.gitignore
rootfolder
.DS_Store
folder1
.ipynb_checkpoints/filename-checkpoint.csv
abc.txt
def.json
somedir
more.json
folder2
.DS_Store
.ipynb_checkpoints/file-filename2-checkpoint.csv
rty.csv
somedir
uis.py
.ipynb_checkpoints/filename1-checkpoint.csv
.DS_Store
Being in the main_folder, I would like to commit everything, except all folders and files having the DS_Store or ipynb_checkpoints substring.
In this specific case, I would like to commit:
main_folder
rootfolder
folder1
abc.txt
def.json
somedir
more.json
folder2
rty.csv
somedir
uis.py
In .gitignore-file, I have added:
**/checkpoint.csv
**/.DS_Store
But not all checkpoint files have being ignored.
What command lines should I add into my .gitignore file located in main_folder-directory
A:
gitignore file has the functionality you need already built-in. You just need to have the name of the directory in the ignore file and git will ignore all files in that directory and all subdirectories:
checkpoint.csv
.DS_Store
If you want a file to be ignored just in the current directory, you can add "./{file}" to gitignore.
A:
It seems you should be ignoring any file if it's in a directory called .ipynb_checkpoints:
.DS_Store
.ipynb_checkpoints
Please note that the files inside .ipynb_checkpoints folders were previously added to git then you would have to remove them explicitely before ignore will work for them.
BTW. You may want to grab a community .gitignore for python development from https://github.com/github/gitignore/blob/main/Python.gitignore (it includes .ipynb_checkpoints :))
| How to ignore some files and directories using .gitgnore? | I have a directory structured like this:
main_folder
.git
.gitignore
rootfolder
.DS_Store
folder1
.ipynb_checkpoints/filename-checkpoint.csv
abc.txt
def.json
somedir
more.json
folder2
.DS_Store
.ipynb_checkpoints/file-filename2-checkpoint.csv
rty.csv
somedir
uis.py
.ipynb_checkpoints/filename1-checkpoint.csv
.DS_Store
Being in the main_folder, I would like to commit everything, except all folders and files having the DS_Store or ipynb_checkpoints substring.
In this specific case, I would like to commit:
main_folder
rootfolder
folder1
abc.txt
def.json
somedir
more.json
folder2
rty.csv
somedir
uis.py
In .gitignore-file, I have added:
**/checkpoint.csv
**/.DS_Store
But not all checkpoint files have being ignored.
What command lines should I add into my .gitignore file located in main_folder-directory
| [
"gitignore file has the functionality you need already built-in. You just need to have the name of the directory in the ignore file and git will ignore all files in that directory and all subdirectories:\ncheckpoint.csv\n.DS_Store\n\nIf you want a file to be ignored just in the current directory, you can add \"./{file}\" to gitignore.\n",
"It seems you should be ignoring any file if it's in a directory called .ipynb_checkpoints:\n.DS_Store\n.ipynb_checkpoints\n\nPlease note that the files inside .ipynb_checkpoints folders were previously added to git then you would have to remove them explicitely before ignore will work for them.\n\nBTW. You may want to grab a community .gitignore for python development from https://github.com/github/gitignore/blob/main/Python.gitignore (it includes .ipynb_checkpoints :))\n"
] | [
0,
0
] | [] | [] | [
"git",
"github",
"gitignore"
] | stackoverflow_0074647600_git_github_gitignore.txt |
Q:
How do I show only some dates in range on x-axis in ggplot2
When I draw the graph, it is unreadable as in the image because all the dates in the data are written on the x-axis. I am trying to make only some of the dates (eg 90 days apart) written. The data set is from 2012-11-07 to 2022-11-04 so there is a lot of data.
code:
ticker <- "AMAT"
price_data <- returns_long %>% filter(Ticker == ticker, Series == "Close")
price_chart <- ggplot(price_data) +
geom_line(aes(x = Date, y = Value, group=1), color = "#66CC00") +
xlab("Date") +
ylab("Stock Price") +
labs(
title = paste0(price_data$Name[1], " (", ticker, ")"),
subtitle = price_data$Sector[1],
caption = "Source: Yahoo! Finance"
)+
scale_y_continuous(labels = scales::dollar) +
theme(
plot.background = element_rect(fill = "#17202A"),
panel.background = element_rect(fill = "#17202A"),
axis.text.x = element_text(color = "#ffffff", angle = 45, hjust = 1, vjust = 1),
axis.text.y = element_text(color = "#ffffff"),
axis.title.x = element_text(color = "#ffffff"),
axis.title.y = element_text(color = "#ffffff"),
plot.title = element_text(color = "#ffffff"),
plot.subtitle = element_text(color = "#ffffff"),
plot.caption = element_text(color = "#ffffff", face = "italic", size = 6),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(color = "#273746"),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
legend.position = "none",
)
price_chart
A:
Use scale_x_date() with the date_breaks argument. e.g.,
library(ggplot2)
price_chart <- ggplot(price_data) +
geom_line(aes(x = Date, y = Value, group=1), color = "#66CC00") +
labs(
x = "Date",
y = "Stock Price",
title = paste0(price_data$Name[1], " (", ticker, ")"),
subtitle = price_data$Sector[1],
caption = "Source: Yahoo! Finance"
) +
scale_y_continuous(labels = scales::dollar) +
scale_x_date(date_breaks = "90 days") +
theme(
# as in OP
)
You may also want to experiment with the date_labels or labels args. e.g., date_labels = "%b %Y" will give you "May 2012" instead of "2012-05-20"; labels = ~ lubridate::quarter(.x, type = "year.quarter") will give you quarters as "2012.1", "2012.2", etc.
Example data:
set.seed(13)
price_data <- data.frame(
Date = seq(as.Date("2012-11-07"), as.Date("2022-11-04"), by = 1),
Value = 50 + cumsum(rnorm(3650)),
Name = rep("Applied Materials", 3650),
Sector = rep("Information Technology", 3650)
)
| How do I show only some dates in range on x-axis in ggplot2 | When I draw the graph, it is unreadable as in the image because all the dates in the data are written on the x-axis. I am trying to make only some of the dates (eg 90 days apart) written. The data set is from 2012-11-07 to 2022-11-04 so there is a lot of data.
code:
ticker <- "AMAT"
price_data <- returns_long %>% filter(Ticker == ticker, Series == "Close")
price_chart <- ggplot(price_data) +
geom_line(aes(x = Date, y = Value, group=1), color = "#66CC00") +
xlab("Date") +
ylab("Stock Price") +
labs(
title = paste0(price_data$Name[1], " (", ticker, ")"),
subtitle = price_data$Sector[1],
caption = "Source: Yahoo! Finance"
)+
scale_y_continuous(labels = scales::dollar) +
theme(
plot.background = element_rect(fill = "#17202A"),
panel.background = element_rect(fill = "#17202A"),
axis.text.x = element_text(color = "#ffffff", angle = 45, hjust = 1, vjust = 1),
axis.text.y = element_text(color = "#ffffff"),
axis.title.x = element_text(color = "#ffffff"),
axis.title.y = element_text(color = "#ffffff"),
plot.title = element_text(color = "#ffffff"),
plot.subtitle = element_text(color = "#ffffff"),
plot.caption = element_text(color = "#ffffff", face = "italic", size = 6),
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(color = "#273746"),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
legend.position = "none",
)
price_chart
| [
"Use scale_x_date() with the date_breaks argument. e.g.,\nlibrary(ggplot2)\n\nprice_chart <- ggplot(price_data) +\n geom_line(aes(x = Date, y = Value, group=1), color = \"#66CC00\") +\n labs(\n x = \"Date\",\n y = \"Stock Price\",\n title = paste0(price_data$Name[1], \" (\", ticker, \")\"),\n subtitle = price_data$Sector[1],\n caption = \"Source: Yahoo! Finance\"\n ) +\n scale_y_continuous(labels = scales::dollar) +\n scale_x_date(date_breaks = \"90 days\") +\n theme(\n # as in OP\n )\n\n\nYou may also want to experiment with the date_labels or labels args. e.g., date_labels = \"%b %Y\" will give you \"May 2012\" instead of \"2012-05-20\"; labels = ~ lubridate::quarter(.x, type = \"year.quarter\") will give you quarters as \"2012.1\", \"2012.2\", etc.\nExample data:\nset.seed(13)\n\nprice_data <- data.frame(\n Date = seq(as.Date(\"2012-11-07\"), as.Date(\"2022-11-04\"), by = 1),\n Value = 50 + cumsum(rnorm(3650)),\n Name = rep(\"Applied Materials\", 3650),\n Sector = rep(\"Information Technology\", 3650)\n)\n\n"
] | [
0
] | [] | [] | [
"ggplot2",
"r"
] | stackoverflow_0074672205_ggplot2_r.txt |
Q:
Find related items, which have a count-condition
I'd like to create a query scope for my model called Ticket. This Ticket hasMany replies (Model: Reply). And each reply can have a status (Enum Status).
Now I'd like to create a scope on the Ticket model, which should filter all tickets having more than 2 replies in the status UNREAD.
This is my first attempt:
public function scopeEscalatedTickets(Builder $query): Builder
{
return $query->has('replies', function (Builder $q){
$q->whereNot('status', Status::READ);
});
}
But now I'm stuck: How can I create the count-condition so this takes into account that I just want the tickets having more than 2 replies which do not have the Status::READ?
My second thought about using something like
->withCount('replies')->having('replies_count', '>', 2)
does not work too, and inspecting the SQL-query I at least found out that withCount really just counts all the related items and ignores other conditions.
Thanks for your help :-)
A:
To filter tickets based on the number of replies with a given status, you can use the having method on the Builder instance in your scope. This method allows you to add conditions to the query based on the values of aggregate functions, such as the number of replies.
Here is an example of how you can modify your scope to only return tickets that have more than 2 replies with the UNREAD status:
public function scopeEscalatedTickets(Builder $query): Builder
{
return $query->has('replies', function (Builder $q) {
$q->where('status', Status::UNREAD);
})->having('replies_count', '>', 2);
}
This scope will first filter the tickets to only include those that have at least one reply with the UNREAD status, using the has and where methods. Then, it will use the having method to only include tickets that have more than 2 replies that match the condition.
Note that this scope assumes that you have a replies_count column in the tickets table, which holds the number of replies for each ticket. You can generate this column using the withCount method on the Builder instance, like this:
$tickets = Ticket::withCount('replies')->get();
This will attach a replies_count attribute to each ticket in the $tickets collection, which you can use in your scope to filter the tickets based on the number of replies.
I hope this helps! Let me know if you have any other questions.
A:
You can use the whereHas() it will check if the model has the given relationship with a condition :
$query->whereHas('replies', function() {
$query->where('status', Status::UNREAD);
}, '>', 2);
now it will query all ticket that have more than 2 replies and with Status::UNREAD
| Find related items, which have a count-condition | I'd like to create a query scope for my model called Ticket. This Ticket hasMany replies (Model: Reply). And each reply can have a status (Enum Status).
Now I'd like to create a scope on the Ticket model, which should filter all tickets having more than 2 replies in the status UNREAD.
This is my first attempt:
public function scopeEscalatedTickets(Builder $query): Builder
{
return $query->has('replies', function (Builder $q){
$q->whereNot('status', Status::READ);
});
}
But now I'm stuck: How can I create the count-condition so this takes into account that I just want the tickets having more than 2 replies which do not have the Status::READ?
My second thought about using something like
->withCount('replies')->having('replies_count', '>', 2)
does not work too, and inspecting the SQL-query I at least found out that withCount really just counts all the related items and ignores other conditions.
Thanks for your help :-)
| [
"To filter tickets based on the number of replies with a given status, you can use the having method on the Builder instance in your scope. This method allows you to add conditions to the query based on the values of aggregate functions, such as the number of replies.\nHere is an example of how you can modify your scope to only return tickets that have more than 2 replies with the UNREAD status:\n public function scopeEscalatedTickets(Builder $query): Builder\n{\n return $query->has('replies', function (Builder $q) {\n $q->where('status', Status::UNREAD);\n })->having('replies_count', '>', 2);\n}\n\nThis scope will first filter the tickets to only include those that have at least one reply with the UNREAD status, using the has and where methods. Then, it will use the having method to only include tickets that have more than 2 replies that match the condition.\nNote that this scope assumes that you have a replies_count column in the tickets table, which holds the number of replies for each ticket. You can generate this column using the withCount method on the Builder instance, like this:\n$tickets = Ticket::withCount('replies')->get();\n\nThis will attach a replies_count attribute to each ticket in the $tickets collection, which you can use in your scope to filter the tickets based on the number of replies.\nI hope this helps! Let me know if you have any other questions.\n",
"You can use the whereHas() it will check if the model has the given relationship with a condition :\n$query->whereHas('replies', function() {\n $query->where('status', Status::UNREAD);\n}, '>', 2);\n\nnow it will query all ticket that have more than 2 replies and with Status::UNREAD\n"
] | [
0,
0
] | [] | [] | [
"eloquent",
"laravel",
"laravel_9"
] | stackoverflow_0074671078_eloquent_laravel_laravel_9.txt |
Q:
How to search for a specific value with multiples values inside a cell?
I have a spreadsheet in Excel that kinda looks like this:
SubjectID
ValidQuestions
Name
XXX000
10
Python
CCC111 / TTT222
9
Data Structure
.
.
The first column represents the ID code that identifies a certain subject. The second one is the number of valid questions that can be used in a exam. The third one is the name of the subject.
I have another tab that kind looks like this:
SubjectID
ValidQuestions
XXX000
CCC111
But this time, the SubjectId column contains only one value that is not separated by a slash and the ValidQuestions column is empty. I need to fill the second one with values from the first tab. I tried to use VLOOKUP but it's not working. I would appreciate help.
A:
Use VLOOKUP() with wildcard character * (asterisk)
• Formula used in cell F2
=VLOOKUP(E2&"*",$A$2:$C$3,2,0)
You can also use INDEX() & MATCH() with ISNUMBER() & SEARCH()
• Formula used in cell F2
=INDEX($B$2:$B$3,MATCH(TRUE,ISNUMBER(SEARCH(E2,$A$2:$A$3)),0))
A:
If you are on Microsoft-365, then I would recommend to use XLOOKUP().
=XLOOKUP("*"&B9&"*",$A$2:$A$3,$B$2:$B$3,,2)
To make it dynamic spill array use XLOOKUP() with BYROW() function.
=BYROW(B9:B10,LAMBDA(x,XLOOKUP("*"&x&"*",$A$2:$A$3,$B$2:$B$3,,2)))
MAP() could be another alternate. Use-
=MAP(B9:B10,LAMBDA(x,XLOOKUP("*"&x&"*",A2:A3,B2:B3,,2)))
| How to search for a specific value with multiples values inside a cell? | I have a spreadsheet in Excel that kinda looks like this:
SubjectID
ValidQuestions
Name
XXX000
10
Python
CCC111 / TTT222
9
Data Structure
.
.
The first column represents the ID code that identifies a certain subject. The second one is the number of valid questions that can be used in a exam. The third one is the name of the subject.
I have another tab that kind looks like this:
SubjectID
ValidQuestions
XXX000
CCC111
But this time, the SubjectId column contains only one value that is not separated by a slash and the ValidQuestions column is empty. I need to fill the second one with values from the first tab. I tried to use VLOOKUP but it's not working. I would appreciate help.
| [
"Use VLOOKUP() with wildcard character * (asterisk)\n\n• Formula used in cell F2\n=VLOOKUP(E2&\"*\",$A$2:$C$3,2,0)\n\n\nYou can also use INDEX() & MATCH() with ISNUMBER() & SEARCH()\n\n• Formula used in cell F2\n=INDEX($B$2:$B$3,MATCH(TRUE,ISNUMBER(SEARCH(E2,$A$2:$A$3)),0))\n\n\n",
"If you are on Microsoft-365, then I would recommend to use XLOOKUP().\n=XLOOKUP(\"*\"&B9&\"*\",$A$2:$A$3,$B$2:$B$3,,2)\n\nTo make it dynamic spill array use XLOOKUP() with BYROW() function.\n=BYROW(B9:B10,LAMBDA(x,XLOOKUP(\"*\"&x&\"*\",$A$2:$A$3,$B$2:$B$3,,2)))\n\nMAP() could be another alternate. Use-\n=MAP(B9:B10,LAMBDA(x,XLOOKUP(\"*\"&x&\"*\",A2:A3,B2:B3,,2)))\n\n\n"
] | [
0,
0
] | [] | [] | [
"excel",
"excel_formula"
] | stackoverflow_0074670422_excel_excel_formula.txt |
Q:
How to display the entire row of sql statement in TDengine?
I want to view the table creation statement in TDengine, So I execute the following sql:
SHOW CREATE DATABASE
However, it didn't display the entire row. How do I need to adjust it?
A:
From your description, I think this is what you need.
SHOW CREATE DATABASE\G;
| How to display the entire row of sql statement in TDengine? | I want to view the table creation statement in TDengine, So I execute the following sql:
SHOW CREATE DATABASE
However, it didn't display the entire row. How do I need to adjust it?
| [
"From your description, I think this is what you need.\nSHOW CREATE DATABASE\\G;\n\n"
] | [
0
] | [] | [] | [
"sql",
"tdengine"
] | stackoverflow_0074672262_sql_tdengine.txt |
Q:
Spring-boot One-to-One mapping with POST method
Hello I am trying to make a reservation sysytem and create a reservation using a post method and assign one reservation to one item.
Do you have any tips or advices?
@OneToOne(mappedBy = "car")
private Reservation reservation;
@OneToOne(cascade = CascadeType.ALL)
@MapsId
@JoinColumn(name = "fk_car_id")
private Car car;
I think mapping is correct - I have difficulties with creating a post method
@PostMapping("/car/{carId}")
Reservation addReservationWithCar(@RequestBody Reservation reservation, @PathVariable Long carId){
Car car = carRepository.findById(carId);
reservation.assignCar(car);
return reservationRepository.save(reservation);
//return ResponseEntity.status(201).body(this.carTypeRepository.save(carType));
}
A:
It looks like you have mapped your Reservation and Car entities correctly using the @OneToOne annotation. Your addReservationWithCar() method also looks correct.
Here are a few tips to consider:
Make sure to validate the input data from the request body. For example, you can use the @Valid annotation in combination with a BindingResult object to validate the Reservation object before saving it to the repository.
If you want to return the saved Reservation object as part of the response, you can use the ResponseEntity class to create a response with a suitable HTTP status code (e.g. 201 - Created) and the body of the response as the saved Reservation object.
In the addReservationWithCar() method, you can use the orElseThrow() method on the Optional<Car> object returned by carRepository.findById() to either get the Car object or throw an exception if it is not found. This can help prevent errors if the Car with the given carId does not exist.
Here is an example of how you could update your addReservationWithCar() method to incorporate these suggestions:
@PostMapping("/car/{carId}")
ResponseEntity<Reservation> addReservationWithCar(@Valid @RequestBody Reservation reservation, BindingResult bindingResult, @PathVariable Long carId){
if (bindingResult.hasErrors()) {
throw new ValidationException(bindingResult);
}
Car car = carRepository.findById(carId).orElseThrow(() -> new EntityNotFoundException("Car not found with id: " + carId));
reservation.assignCar(car);
Reservation savedReservation = reservationRepository.save(reservation);
return ResponseEntity.status(201).body(savedReservation);
}
I hope this helps! Let me know if you have any other questions.
| Spring-boot One-to-One mapping with POST method | Hello I am trying to make a reservation sysytem and create a reservation using a post method and assign one reservation to one item.
Do you have any tips or advices?
@OneToOne(mappedBy = "car")
private Reservation reservation;
@OneToOne(cascade = CascadeType.ALL)
@MapsId
@JoinColumn(name = "fk_car_id")
private Car car;
I think mapping is correct - I have difficulties with creating a post method
@PostMapping("/car/{carId}")
Reservation addReservationWithCar(@RequestBody Reservation reservation, @PathVariable Long carId){
Car car = carRepository.findById(carId);
reservation.assignCar(car);
return reservationRepository.save(reservation);
//return ResponseEntity.status(201).body(this.carTypeRepository.save(carType));
}
| [
"It looks like you have mapped your Reservation and Car entities correctly using the @OneToOne annotation. Your addReservationWithCar() method also looks correct.\nHere are a few tips to consider:\n\nMake sure to validate the input data from the request body. For example, you can use the @Valid annotation in combination with a BindingResult object to validate the Reservation object before saving it to the repository.\nIf you want to return the saved Reservation object as part of the response, you can use the ResponseEntity class to create a response with a suitable HTTP status code (e.g. 201 - Created) and the body of the response as the saved Reservation object.\nIn the addReservationWithCar() method, you can use the orElseThrow() method on the Optional<Car> object returned by carRepository.findById() to either get the Car object or throw an exception if it is not found. This can help prevent errors if the Car with the given carId does not exist.\n\nHere is an example of how you could update your addReservationWithCar() method to incorporate these suggestions:\n@PostMapping(\"/car/{carId}\")\nResponseEntity<Reservation> addReservationWithCar(@Valid @RequestBody Reservation reservation, BindingResult bindingResult, @PathVariable Long carId){\n if (bindingResult.hasErrors()) {\n throw new ValidationException(bindingResult);\n }\n\n Car car = carRepository.findById(carId).orElseThrow(() -> new EntityNotFoundException(\"Car not found with id: \" + carId));\n reservation.assignCar(car);\n Reservation savedReservation = reservationRepository.save(reservation);\n return ResponseEntity.status(201).body(savedReservation);\n}\n\nI hope this helps! Let me know if you have any other questions.\n"
] | [
0
] | [] | [] | [
"jpa",
"spring",
"spring_boot"
] | stackoverflow_0074672285_jpa_spring_spring_boot.txt |
Q:
Why is the InverseMelScale torchaudio function so slow?
I am currently exploring and learning machine learning for music/audio generation and I am already failing in the first steps.
My idea is to use image-based learning algorithms on audio.
To do so, I want to convert the audio into a MEL spectrogram and then apply the machine learning stuff.
Then, when the model is trained, it obviously should generate music again, which will be MEL spectrogram.
So I have to convert the MEL spectrogram back to audio.
Generating the MEL spectrogram is straight forward using pytorch's torchaudio framwork:
waveform, _ = torchaudio.load(os.path.join(folder, "drums.mp3"), normalize=True, format="mp3")
waveform = waveform.to(device)
mel_spectrogram_transform = torchaudio.transforms.MelSpectrogram(sample_rate=44100, hop_length=512, n_fft=2048, n_mels=512, f_max=16384).to(device)
mel_spectrogram = mel_spectrogram_transform(waveform)
There are some more pre-processing steps in order to be able to save the spectrogram as an image, but I skip it here for brevity.
What makes me headaches is the inverse step. torchaudio has a function for that, InverseMelScale. But it is painstakingly slow. Here is the code:
inverse_melscale_transform = torchaudio.transforms.InverseMelScale(sample_rate=44100, n_mels=512, n_stft=2048 // 2 + 1).to(device)
mel_spectrogram = mel_spectrogram.to(device)
spectrogram = inverse_melscale_transform(mel_spectrogram)
Again, I leave out the some more steps here, e.g., using GriffinLim to get the actual audio from spectrogram.
Here is what I did so far:
I ran the code on my MacBook Pro (Intel), which took forever. I then tested it on a AMD Ryzen server with 256 cores, where I was able to get the result within a couple of minutes. Now my idea was to utilize a GPU, a Titan XP in this case, to get the result even faster, but even after 30 minutes of computing with 100% GPU utilization, there is no result in sight.
What am I doing wrong?
Why is the AMD Ryzen so much faster?
A:
Currently, InverseMelScale is implemented as inference using SGD, that is inside of InverseMelScale, loss function is defined and optimizer run.
This implementation is not only inefficient, but also no accurate.
For the reason this implementation was picked, you can check out https://github.com/pytorch/audio/pull/366.
It is suggested to use L-BFGS-B optimizer
https://github.com/pytorch/audio/issues/2643
| Why is the InverseMelScale torchaudio function so slow? | I am currently exploring and learning machine learning for music/audio generation and I am already failing in the first steps.
My idea is to use image-based learning algorithms on audio.
To do so, I want to convert the audio into a MEL spectrogram and then apply the machine learning stuff.
Then, when the model is trained, it obviously should generate music again, which will be MEL spectrogram.
So I have to convert the MEL spectrogram back to audio.
Generating the MEL spectrogram is straight forward using pytorch's torchaudio framwork:
waveform, _ = torchaudio.load(os.path.join(folder, "drums.mp3"), normalize=True, format="mp3")
waveform = waveform.to(device)
mel_spectrogram_transform = torchaudio.transforms.MelSpectrogram(sample_rate=44100, hop_length=512, n_fft=2048, n_mels=512, f_max=16384).to(device)
mel_spectrogram = mel_spectrogram_transform(waveform)
There are some more pre-processing steps in order to be able to save the spectrogram as an image, but I skip it here for brevity.
What makes me headaches is the inverse step. torchaudio has a function for that, InverseMelScale. But it is painstakingly slow. Here is the code:
inverse_melscale_transform = torchaudio.transforms.InverseMelScale(sample_rate=44100, n_mels=512, n_stft=2048 // 2 + 1).to(device)
mel_spectrogram = mel_spectrogram.to(device)
spectrogram = inverse_melscale_transform(mel_spectrogram)
Again, I leave out the some more steps here, e.g., using GriffinLim to get the actual audio from spectrogram.
Here is what I did so far:
I ran the code on my MacBook Pro (Intel), which took forever. I then tested it on a AMD Ryzen server with 256 cores, where I was able to get the result within a couple of minutes. Now my idea was to utilize a GPU, a Titan XP in this case, to get the result even faster, but even after 30 minutes of computing with 100% GPU utilization, there is no result in sight.
What am I doing wrong?
Why is the AMD Ryzen so much faster?
| [
"Currently, InverseMelScale is implemented as inference using SGD, that is inside of InverseMelScale, loss function is defined and optimizer run.\nThis implementation is not only inefficient, but also no accurate.\nFor the reason this implementation was picked, you can check out https://github.com/pytorch/audio/pull/366.\nIt is suggested to use L-BFGS-B optimizer\nhttps://github.com/pytorch/audio/issues/2643\n"
] | [
0
] | [] | [] | [
"gpu",
"python",
"pytorch",
"spectrogram"
] | stackoverflow_0074447735_gpu_python_pytorch_spectrogram.txt |
Q:
Cloudflare Workers: request is not defined
I am trying to use Cloudflare Workers to auto-select a value on a dropdown based on the user's country (using Cloudflare's request.cf.country).
This is the code I wrote:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
let html_content = ""
html_content += "<p> Detected Country: " + request.cf.country + "</p>"
let html = `${html_content}
<select id="edit-field-country" ><option value="_none"></option><option value="AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="GB">United Kingdom</option></select>
<script>
document.getElementById('edit-field-country').value = request.cf.country;
</script>
`
return new Response(html, {
headers: {
"content-type": "text/html;charset=UTF-8",
},})
}
This part is working well and it's correctly outputting the country code:
<p> Detected Country: " + request.cf.country + "</p>
Unfortunately the auto-selection doesn't work because there's a problem here:
document.getElementById('edit-field-country').value = request.cf.country;
What am I doing wrong?
Should I define request.cf.country earlier?
A:
request.cf.country is not defined in the context you are trying to access it (browser).
Try changing this:
let html = `${html_content}
<select id="edit-field-country" ><option value="_none"></option><option value="AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="GB">United Kingdom</option></select>
<script>
document.getElementById('edit-field-country').value = request.cf.country;
</script>
`
to this instead:
let html = `${html_content}
<select id="edit-field-country" ><option value="_none"></option><option value="AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="GB">United Kingdom</option></select>
<script>
document.getElementById('edit-field-country').value = '${request.cf.country}';
</script>
`
| Cloudflare Workers: request is not defined | I am trying to use Cloudflare Workers to auto-select a value on a dropdown based on the user's country (using Cloudflare's request.cf.country).
This is the code I wrote:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
let html_content = ""
html_content += "<p> Detected Country: " + request.cf.country + "</p>"
let html = `${html_content}
<select id="edit-field-country" ><option value="_none"></option><option value="AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="GB">United Kingdom</option></select>
<script>
document.getElementById('edit-field-country').value = request.cf.country;
</script>
`
return new Response(html, {
headers: {
"content-type": "text/html;charset=UTF-8",
},})
}
This part is working well and it's correctly outputting the country code:
<p> Detected Country: " + request.cf.country + "</p>
Unfortunately the auto-selection doesn't work because there's a problem here:
document.getElementById('edit-field-country').value = request.cf.country;
What am I doing wrong?
Should I define request.cf.country earlier?
| [
"request.cf.country is not defined in the context you are trying to access it (browser).\nTry changing this:\n let html = `${html_content}\n \n<select id=\"edit-field-country\" ><option value=\"_none\"></option><option value=\"AF\">Afghanistan</option><option value=\"AX\">Åland Islands</option><option value=\"GB\">United Kingdom</option></select>\n<script>\n document.getElementById('edit-field-country').value = request.cf.country;\n</script>\n`\n\nto this instead:\n let html = `${html_content}\n \n<select id=\"edit-field-country\" ><option value=\"_none\"></option><option value=\"AF\">Afghanistan</option><option value=\"AX\">Åland Islands</option><option value=\"GB\">United Kingdom</option></select>\n<script>\n document.getElementById('edit-field-country').value = '${request.cf.country}';\n</script>\n`\n\n"
] | [
0
] | [] | [] | [
"cloudflare_workers",
"javascript"
] | stackoverflow_0074031129_cloudflare_workers_javascript.txt |
Q:
Can import dataset into RStudio but can't read file
I can see the table of the data set on the upper right of Data.
My code is currently:
file.exists(C:/Hollywood.xlsx)?
to see if RStudio is picking up on it.
I get an error message of
"Incomplete expression: file.exists(C:Hollywood.xlsx)?"
To take a look at the working directory, I'm doing Session>Set Working Directory>Source File Location and get "The currently active source file is not saved so doesn't have a directory to change into." If I instead try Session>Set Working Directory>To Files Pane Location, I get setwd(~) and the following is what I get and subsequent code I try:
setwd("/Users/FridasSlave/Downloads/Hollywood")
#Error in setwd("/Users/FridasSlave/Downloads/Hollywood") :
# cannot change working directory
getwd(Hollywood)
# Error in getwd(Hollywood) : unused argument (Hollywood)
getwd("Hollywood")
#Error in getwd("Hollywood") : unused argument ("Hollywood")
If I try Session>Set Working Directory>Choose Directory, I can get to my Downloads folder but the individual files are all not there.
What am I doing wrong?
(And yes, I'm very new to R.)
I have all my relevant paths and code above.
A:
Scrolling down the list of problems:
I hope you didn't put a ? at the end of an R command. It's true that it looks like it would be a question if you were talking to a person, but that's not the case.
The argument to file.exists should be a character value. C:/Hollywood.xlsx is not recognized by the R interpreter as a character value because there are no quotes around it. It's possible that at that point you could have gotten success with
file.exists("Hollywood.xlsx") # if it is in the current working directory
From your use of "~" and setwd("/Users/FridasSlave/Downloads/Hollywood") I'm guessing that you are on a Mac. Your question should probably have included that as a specific note. (Which further raises the issue why you would use a Windows file spcification if you are on a Mac?
The reason for the error from setwd("/Users/FridasSlave/Downloads/Hollywood") is not obvious, but maybe you misspelled part of the path or maybe it should have been setwd("/Users/FridasSlave/Downloads/").
Trying getwd(Hollywood) you again failed to include quotes around the argument. And why would you even want an argument if you want information about the current working directory? Should have just been getwd()
| Can import dataset into RStudio but can't read file | I can see the table of the data set on the upper right of Data.
My code is currently:
file.exists(C:/Hollywood.xlsx)?
to see if RStudio is picking up on it.
I get an error message of
"Incomplete expression: file.exists(C:Hollywood.xlsx)?"
To take a look at the working directory, I'm doing Session>Set Working Directory>Source File Location and get "The currently active source file is not saved so doesn't have a directory to change into." If I instead try Session>Set Working Directory>To Files Pane Location, I get setwd(~) and the following is what I get and subsequent code I try:
setwd("/Users/FridasSlave/Downloads/Hollywood")
#Error in setwd("/Users/FridasSlave/Downloads/Hollywood") :
# cannot change working directory
getwd(Hollywood)
# Error in getwd(Hollywood) : unused argument (Hollywood)
getwd("Hollywood")
#Error in getwd("Hollywood") : unused argument ("Hollywood")
If I try Session>Set Working Directory>Choose Directory, I can get to my Downloads folder but the individual files are all not there.
What am I doing wrong?
(And yes, I'm very new to R.)
I have all my relevant paths and code above.
| [
"Scrolling down the list of problems:\n\nI hope you didn't put a ? at the end of an R command. It's true that it looks like it would be a question if you were talking to a person, but that's not the case.\n\nThe argument to file.exists should be a character value. C:/Hollywood.xlsx is not recognized by the R interpreter as a character value because there are no quotes around it. It's possible that at that point you could have gotten success with\nfile.exists(\"Hollywood.xlsx\") # if it is in the current working directory\n\nFrom your use of \"~\" and setwd(\"/Users/FridasSlave/Downloads/Hollywood\") I'm guessing that you are on a Mac. Your question should probably have included that as a specific note. (Which further raises the issue why you would use a Windows file spcification if you are on a Mac?\n\nThe reason for the error from setwd(\"/Users/FridasSlave/Downloads/Hollywood\") is not obvious, but maybe you misspelled part of the path or maybe it should have been setwd(\"/Users/FridasSlave/Downloads/\").\n\nTrying getwd(Hollywood) you again failed to include quotes around the argument. And why would you even want an argument if you want information about the current working directory? Should have just been getwd()\n\n\n"
] | [
0
] | [] | [] | [
"r"
] | stackoverflow_0074672137_r.txt |
Q:
How to speed up dynamic columns with formulas in Power Query
The Question (How do I make it faster)
I have been playing around with Power Query in Excel for over a year now but for the first time, I have a query that takes 20+ minutes to run.
I am sure there is something here I can learn!
While it does currently work I believe if it was well-written it would run much faster.
Data Structure
There are two databases here
Database of Company (Aka attendees) - About 400 rows
Company Title
Rita Book
Paige Turner
Dee End
etc
Database of Events - About 500 rows
An Event can have many Company (Attendees). The database exports this as a comma-separated list in the column [#"Export CSV - Company"]
Event Title
Export CSV - Company
Date
Year
Event 1
Rita Book, Dee End
1/1/2015
2015
Event 2
Paige Turner
2/1/2015
2015
Event 3
Dee End
3/1/2015
2015
Event 4
Rita Book, Paige Turner, Dee End
1/1/2016
2016
etc
...
...
...
Note that I also have a separate query called #"Company Event Count - 1 Years List" which is a list of all years that events have been run.
The Goal
For a visualization, I need to get the data into the following structure:
Company Title
2015
2016
etc
John Smith
10
20
...
Jane Doe
5
14
...
etc
...
...
...
The Code
I have done my best to comment on my code below. Feel free to ask any questions.
let
// This is a function. It was the only way I could figure out how to use [Company Title] from #"Keep only names column" and "currentColumnTitleYearStr" from the dynamically created columns in the same scope
count_table_year_company = (myTbl, yearStr, companyStr) =>
Table.RowCount(
Table.SelectRows(
myTbl,
each Text.Contains([#"Export CSV - Company"], companyStr)
)
),
Source = #"Company 1 - Loaded CSV From Folder", // Grab a list of all Company
#"Keep only names column" = Table.SelectColumns(Source,{"Company Title"}), // Keep only the [Company Title] field
// Dynamically create columns for each year. Example Columns: [Company Title], [2015], [2016], [2017], etc
#"Add Columns for each year" =
List.Accumulate(
#"Company Event Count - 1 Years List", // Get a table of all events
#"Keep only names column",
(state, currentColumnTitleYearStr) => Table.AddColumn(
state,
currentColumnTitleYearStr, // The Year becomes the column title and is also used in filters
let // I hoped that filting the table by Year at this point would mean it only has to do it once per column, instead of once per cell.
eventsThisYearTbl = Table.SelectRows(
#"Event 1 - Loaded CSV From Folder",
each ([Year] = Number.FromText(currentColumnTitleYearStr))
)
in(
// Finally for each cell, calculate the count of events. E.g How many events did 'John Smith' attend in 2015
each count_table_year_company(eventsThisYearTbl, currentColumnTitleYearStr, [Company Title]) //CompanyTitleVar
)
)
),
FinalStep = #"Add Columns for each year"
in
FinalStep
My Theries
I believe one of a few things may be making it slow
I am using "List.Accumulate(" to dynamically create a column for each year. While this does work I think it may be the wrong formula for the job. Especially because the state field which is like a running total of each cell must be a huge number.
I worry that I have an 'each' where I dont need it but I cant seem to remove any. Its my understanding that every 'each' is effectively a nested loop so removing one may have a dramatic impact on performance.
In Conclusion
While it does currently work I know there is something for me to learn here.
Thank you so much any guidance or suggested readings you can provide :)
A:
Does this do what you want? Converts from left to right. If not please explain more clearly
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
SplitNames = Table.TransformColumns(Source,{{"Names", each Text.Split(_,", ")}}),
#"Expanded Names" = Table.ExpandListColumn(SplitNames, "Names"),
#"Removed Columns" = Table.RemoveColumns(#"Expanded Names",{"Event Title", "Date"}),
#"Added Custom" = Table.AddColumn(#"Removed Columns", "Count", each 1),
#"Pivoted Column" = Table.Pivot(Table.TransformColumnTypes(#"Added Custom", {{"Year", type text}}, "en-US"), List.Distinct(Table.TransformColumnTypes(#"Added Custom", {{"Year", type text}}, "en-US")[Year]), "Year", "Count", List.Sum)
in #"Pivoted Column"
| How to speed up dynamic columns with formulas in Power Query | The Question (How do I make it faster)
I have been playing around with Power Query in Excel for over a year now but for the first time, I have a query that takes 20+ minutes to run.
I am sure there is something here I can learn!
While it does currently work I believe if it was well-written it would run much faster.
Data Structure
There are two databases here
Database of Company (Aka attendees) - About 400 rows
Company Title
Rita Book
Paige Turner
Dee End
etc
Database of Events - About 500 rows
An Event can have many Company (Attendees). The database exports this as a comma-separated list in the column [#"Export CSV - Company"]
Event Title
Export CSV - Company
Date
Year
Event 1
Rita Book, Dee End
1/1/2015
2015
Event 2
Paige Turner
2/1/2015
2015
Event 3
Dee End
3/1/2015
2015
Event 4
Rita Book, Paige Turner, Dee End
1/1/2016
2016
etc
...
...
...
Note that I also have a separate query called #"Company Event Count - 1 Years List" which is a list of all years that events have been run.
The Goal
For a visualization, I need to get the data into the following structure:
Company Title
2015
2016
etc
John Smith
10
20
...
Jane Doe
5
14
...
etc
...
...
...
The Code
I have done my best to comment on my code below. Feel free to ask any questions.
let
// This is a function. It was the only way I could figure out how to use [Company Title] from #"Keep only names column" and "currentColumnTitleYearStr" from the dynamically created columns in the same scope
count_table_year_company = (myTbl, yearStr, companyStr) =>
Table.RowCount(
Table.SelectRows(
myTbl,
each Text.Contains([#"Export CSV - Company"], companyStr)
)
),
Source = #"Company 1 - Loaded CSV From Folder", // Grab a list of all Company
#"Keep only names column" = Table.SelectColumns(Source,{"Company Title"}), // Keep only the [Company Title] field
// Dynamically create columns for each year. Example Columns: [Company Title], [2015], [2016], [2017], etc
#"Add Columns for each year" =
List.Accumulate(
#"Company Event Count - 1 Years List", // Get a table of all events
#"Keep only names column",
(state, currentColumnTitleYearStr) => Table.AddColumn(
state,
currentColumnTitleYearStr, // The Year becomes the column title and is also used in filters
let // I hoped that filting the table by Year at this point would mean it only has to do it once per column, instead of once per cell.
eventsThisYearTbl = Table.SelectRows(
#"Event 1 - Loaded CSV From Folder",
each ([Year] = Number.FromText(currentColumnTitleYearStr))
)
in(
// Finally for each cell, calculate the count of events. E.g How many events did 'John Smith' attend in 2015
each count_table_year_company(eventsThisYearTbl, currentColumnTitleYearStr, [Company Title]) //CompanyTitleVar
)
)
),
FinalStep = #"Add Columns for each year"
in
FinalStep
My Theries
I believe one of a few things may be making it slow
I am using "List.Accumulate(" to dynamically create a column for each year. While this does work I think it may be the wrong formula for the job. Especially because the state field which is like a running total of each cell must be a huge number.
I worry that I have an 'each' where I dont need it but I cant seem to remove any. Its my understanding that every 'each' is effectively a nested loop so removing one may have a dramatic impact on performance.
In Conclusion
While it does currently work I know there is something for me to learn here.
Thank you so much any guidance or suggested readings you can provide :)
| [
"Does this do what you want? Converts from left to right. If not please explain more clearly\nlet Source = Excel.CurrentWorkbook(){[Name=\"Table1\"]}[Content],\nSplitNames = Table.TransformColumns(Source,{{\"Names\", each Text.Split(_,\", \")}}),\n#\"Expanded Names\" = Table.ExpandListColumn(SplitNames, \"Names\"),\n#\"Removed Columns\" = Table.RemoveColumns(#\"Expanded Names\",{\"Event Title\", \"Date\"}),\n#\"Added Custom\" = Table.AddColumn(#\"Removed Columns\", \"Count\", each 1),\n#\"Pivoted Column\" = Table.Pivot(Table.TransformColumnTypes(#\"Added Custom\", {{\"Year\", type text}}, \"en-US\"), List.Distinct(Table.TransformColumnTypes(#\"Added Custom\", {{\"Year\", type text}}, \"en-US\")[Year]), \"Year\", \"Count\", List.Sum)\nin #\"Pivoted Column\"\n\n\n"
] | [
1
] | [] | [] | [
"excel",
"performance",
"powerquery"
] | stackoverflow_0074620825_excel_performance_powerquery.txt |
Q:
How can I get the text in a textbox in customtkinter?
I am building a text editor but I can't save the file because I can't get the text within the textbox. Even thought in the entry widget I can use .get() to get the text.
I tried .get() but it displays an error that it isn't an option.
A:
Customtkinter library is still under-development and it's getting updated consistently.
.get() function support was added couple of days ago, you can now use it. Make sure your customtkinter library is up-to-date. (pip3 install customtkinter --upgrade)
Example code:
from pytube import *
from tkinter import *
import customtkinter
def getText():
print(textbox.get('1.0', END))
root = customtkinter.CTk()
textbox = customtkinter.CTkTextbox(root)
button = customtkinter.CTkButton(root, command=getText)
textbox.pack(pady=30, padx=20)
button.pack(pady=30, padx=20)
root.mainloop()
| How can I get the text in a textbox in customtkinter? | I am building a text editor but I can't save the file because I can't get the text within the textbox. Even thought in the entry widget I can use .get() to get the text.
I tried .get() but it displays an error that it isn't an option.
| [
"Customtkinter library is still under-development and it's getting updated consistently.\n.get() function support was added couple of days ago, you can now use it. Make sure your customtkinter library is up-to-date. (pip3 install customtkinter --upgrade)\nExample code:\nfrom pytube import *\nfrom tkinter import *\nimport customtkinter\n\ndef getText():\n print(textbox.get('1.0', END))\n\nroot = customtkinter.CTk()\n\ntextbox = customtkinter.CTkTextbox(root)\nbutton = customtkinter.CTkButton(root, command=getText)\ntextbox.pack(pady=30, padx=20)\nbutton.pack(pady=30, padx=20)\n\nroot.mainloop()\n\n\n"
] | [
0
] | [] | [] | [
"customtkinter",
"python",
"tkinter"
] | stackoverflow_0074616256_customtkinter_python_tkinter.txt |
Q:
What is fatal error C1090: PDB API call failed, error code '3': vc142.pdb?
I set up a new project with Visual Studio 2019 version 16.3.10. When I try to build I get the following error:
EasyTcpStubs.c : fatal error C1090: PDB API call failed, error code '3':
W:\Dropbox\Me (Mine)\TcpToNamedPipe\TcpToNamedPipe\Debug\vc142.pdb
I have searched the internet and this site for any explanation of this error. Maybe I missed it but I could not find anything.
The project is a Console project.
The error occurs without a line number so it does not seem to be the source. I tried another project and it compiles OK (but it is an old project whereas this error is occuring on a brand new project.
Does anyone know something about this?
A:
For me, I stopped Dropbox and it works. It seems that something is using W:\Dropbox\Me (Mine)\TcpToNamedPipe\TcpToNamedPipe\Debug.
A:
In my experience this error is likely due to some permission error. If your project is in Dropbox, OneDrive, etc, most likely you get this error because your Dropbox cannot sync and update files properly. Restart Dropbox and that should fix the issue.
A:
In My case, I suspect it is some type of race condition/lock issue with the code that opens/closes the *.pdb file. In my case I am running /MP (Multiprocessor Compile) so up to 4 *.cpp modules being built at a time. It works fine on a stand alone build machine. But I'm a vendor and must use a VM environment to develop for my customer, and the disk requirements are so large I must place the builds on a network share.
The latency of file I/O access over a network share seems to be the issue.
Thats all I know about the issue at the moment.
As I learn/test discover more, I can improve this answer.
A:
Synology Drive Client (v3.2.0) caused this error for me. Pausing the sync eliminated the error. Thanks to all for the clue of DropBox, OneDrive, etc. causing the issue.
| What is fatal error C1090: PDB API call failed, error code '3': vc142.pdb? | I set up a new project with Visual Studio 2019 version 16.3.10. When I try to build I get the following error:
EasyTcpStubs.c : fatal error C1090: PDB API call failed, error code '3':
W:\Dropbox\Me (Mine)\TcpToNamedPipe\TcpToNamedPipe\Debug\vc142.pdb
I have searched the internet and this site for any explanation of this error. Maybe I missed it but I could not find anything.
The project is a Console project.
The error occurs without a line number so it does not seem to be the source. I tried another project and it compiles OK (but it is an old project whereas this error is occuring on a brand new project.
Does anyone know something about this?
| [
"For me, I stopped Dropbox and it works. It seems that something is using W:\\Dropbox\\Me (Mine)\\TcpToNamedPipe\\TcpToNamedPipe\\Debug.\n",
"In my experience this error is likely due to some permission error. If your project is in Dropbox, OneDrive, etc, most likely you get this error because your Dropbox cannot sync and update files properly. Restart Dropbox and that should fix the issue.\n",
"In My case, I suspect it is some type of race condition/lock issue with the code that opens/closes the *.pdb file. In my case I am running /MP (Multiprocessor Compile) so up to 4 *.cpp modules being built at a time. It works fine on a stand alone build machine. But I'm a vendor and must use a VM environment to develop for my customer, and the disk requirements are so large I must place the builds on a network share.\nThe latency of file I/O access over a network share seems to be the issue.\nThats all I know about the issue at the moment.\nAs I learn/test discover more, I can improve this answer.\n",
"Synology Drive Client (v3.2.0) caused this error for me. Pausing the sync eliminated the error. Thanks to all for the clue of DropBox, OneDrive, etc. causing the issue.\n"
] | [
4,
3,
0,
0
] | [] | [] | [
"visual_studio"
] | stackoverflow_0059380816_visual_studio.txt |
Q:
Is there a better R way to expand a dataframe by a function on rows?
Question:
Below works, but is there a better "R way" of achieving similar result? I am essentially trying to create / distribute groups into individual line items according to a user defined function (currently just using a loop).
Example:
df1 <- data.frame(group = c("A", "B", "C"),
volume = c(200L, 45L, 104L)
)
print(df1)
#> group volume
#> 1 A 200
#> 2 B 45
#> 3 C 104
I want the volume to be broken across multiple rows according to group so that the final result is a dataframe where the new volume (vol2 in the below) would add up to original volume above. In this example, I'm applying integer math with a divisor of 52, so my final result should be:
print(df3)
#> group vol2
#> 1 A 52
#> 2 A 52
#> 3 A 52
#> 4 A 44
#> 21 B 45
#> 31 C 52
#> 32 C 52
This works
The code below DOES get me to the desired result shown above:
div <- 52L
df1$intgr <- df1$volume %/% div
df1$remainder <- df1$volume %% div
print(df1)
#> group volume intgr remainder
#> 1 A 200 3 44
#> 2 B 45 0 45
#> 3 C 104 2 0
df2 <- data.frame()
for (r in 1:nrow(df1)){
if(df1[r,"intgr"] > 0){
for (k in 1:as.integer(df1[r,"intgr"])){
df1[r,"vol2"] <- div
df2 <- rbind(df2, df1[r,])
}
}
if(df1[r,"remainder"]>0){
df1[r, "vol2"] <- as.integer(df1[r, "remainder"])
df2 <- rbind(df2, df1[r,])
}
}
print(df2)
#> group volume intgr remainder vol2
#> 1 A 200 3 44 52
#> 2 A 200 3 44 52
#> 3 A 200 3 44 52
#> 4 A 200 3 44 44
#> 21 B 45 0 45 45
#> 31 C 104 2 0 52
#> 32 C 104 2 0 52
df3 <- subset(df2, select = c("group", "vol2"))
print(df3)
#> group vol2
#> 1 A 52
#> 2 A 52
#> 3 A 52
#> 4 A 44
#> 21 B 45
#> 31 C 52
#> 32 C 52
Being still relatively new to R, I'm just curious if someone knows a better way / function / method that gets to the same place. Seems like there might be. I could potentially have a more complex way of breaking up the rows and I was thinking maybe there's a method that applies a UDF to the dataframe to do something like this. I was searching for "expand group/groups" but was finding mostly "expand.grid" which isn't what I'm doing here.
Thank you for any suggestions!
A:
A quick function to help split each number by the modulus,
fun <- function(num, mod) c(rep(mod, floor(num / mod)), (num-1) %% mod + 1)
fun(200, 52)
# [1] 52 52 52 44
fun(45, 52)
# [1] 45
fun(104, 52)
# [1] 52 52
And we can apply this a number of ways:
dplyr
library(dplyr)
df1 %>%
group_by(group) %>%
summarize(vol2 = fun(volume, 52), .groups = "drop")
# # A tibble: 7 x 2
# group vol2
# <chr> <dbl>
# 1 A 52
# 2 A 52
# 3 A 52
# 4 A 44
# 5 B 45
# 6 C 52
# 7 C 52
base R
do.call(rbind, by(df1, seq(nrow(df1)),
FUN = function(z) data.frame(group = z$group, vol2 = fun(z$volume, 52))))
data.table
library(data.table)
setDT(df1)
df1[, .(vol2 = fun(volume, 52)), by = group]
A:
A tidyverse approach using purrr::pmap and tidyr::unnest_longer may look like so:
library(dplyr, w = FALSE)
library(tidyr)
library(purrr)
div <- 52
df1 |>
mutate(intgr = volume %/% div, remainder = volume %% div, intgr1 = +(remainder > 0)) |>
mutate(vol2 = purrr::pmap(list(intgr, intgr1, remainder), ~ c(rep(div, ..1), rep(..3, ..2)))) |>
tidyr::unnest_longer(vol2) |>
select(-intgr1)
#> # A tibble: 7 × 5
#> group volume intgr remainder vol2
#> <chr> <int> <dbl> <dbl> <dbl>
#> 1 A 200 3 44 52
#> 2 A 200 3 44 52
#> 3 A 200 3 44 52
#> 4 A 200 3 44 44
#> 5 B 45 0 45 45
#> 6 C 104 2 0 52
#> 7 C 104 2 0 52
A:
With data.table and rep:
library(data.table)
setDT(df1)[, .(vol2 = c(rep(52, volume%/%52), (volume%%52)[sign(volume%%52)])), group]
#> group vol2
#> 1: A 52
#> 2: A 52
#> 3: A 52
#> 4: A 44
#> 5: B 45
#> 6: C 52
#> 7: C 52
Or
setDT(df1)[, .(vol2 = c(rep(52, volume%/%52), volume%%52)), group][vol2 != 0]
#> group vol2
#> 1: A 52
#> 2: A 52
#> 3: A 52
#> 4: A 44
#> 5: B 45
#> 6: C 52
#> 7: C 52
A:
Vectorised and without grouping:
df1 <- data.frame(group = c("A", "B", "C"),
volume = c(200L, 45L, 104L))
n <- 52
idx <- df1$volume %/% n + ((sel <- df1$volume %% n) != 0)
out <- df1[rep(seq_len(nrow(df1)), idx),]
out$volume <- n
out$volume[cumsum(idx)[sel != 0]] <- sel[sel != 0]
## group volume
##1 A 52
##1.1 A 52
##1.2 A 52
##1.3 A 44
##2 B 45
##3 C 52
##3.1 C 52
A:
Another base R solution using aggregate :
aggregate(.~group,df1,\(x) c(rep(52, x / 52), (x-1) %% 52 + 1))
group volume
1 A 52, 52, 52, 44
2 B 45
3 C 52, 52, 52
This results in a list column for volume (could be useful)
To transform it to a long dataframe we can either use stack:
with(
aggregate(.~group,df1,\(x) c(rep(52, x / 52), (x-1) %% 52 + 1)),
setNames(stack(setNames(volume,group))[2:1],names(df1))
)
group volume
1 A 52
2 A 52
3 A 52
4 A 44
5 B 45
6 C 52
7 C 52
8 C 52
Or alternatively use unnest from tidyr
library(tidyr)
aggregate(.~group,df1,\(x) c(rep(52, x / 52), (x-1) %% 52 + 1)) %>% unnest(volume)
# A tibble: 8 × 2
group volume
<chr> <dbl>
1 A 52
2 A 52
3 A 52
4 A 44
5 B 45
6 C 52
7 C 52
8 C 52
| Is there a better R way to expand a dataframe by a function on rows? | Question:
Below works, but is there a better "R way" of achieving similar result? I am essentially trying to create / distribute groups into individual line items according to a user defined function (currently just using a loop).
Example:
df1 <- data.frame(group = c("A", "B", "C"),
volume = c(200L, 45L, 104L)
)
print(df1)
#> group volume
#> 1 A 200
#> 2 B 45
#> 3 C 104
I want the volume to be broken across multiple rows according to group so that the final result is a dataframe where the new volume (vol2 in the below) would add up to original volume above. In this example, I'm applying integer math with a divisor of 52, so my final result should be:
print(df3)
#> group vol2
#> 1 A 52
#> 2 A 52
#> 3 A 52
#> 4 A 44
#> 21 B 45
#> 31 C 52
#> 32 C 52
This works
The code below DOES get me to the desired result shown above:
div <- 52L
df1$intgr <- df1$volume %/% div
df1$remainder <- df1$volume %% div
print(df1)
#> group volume intgr remainder
#> 1 A 200 3 44
#> 2 B 45 0 45
#> 3 C 104 2 0
df2 <- data.frame()
for (r in 1:nrow(df1)){
if(df1[r,"intgr"] > 0){
for (k in 1:as.integer(df1[r,"intgr"])){
df1[r,"vol2"] <- div
df2 <- rbind(df2, df1[r,])
}
}
if(df1[r,"remainder"]>0){
df1[r, "vol2"] <- as.integer(df1[r, "remainder"])
df2 <- rbind(df2, df1[r,])
}
}
print(df2)
#> group volume intgr remainder vol2
#> 1 A 200 3 44 52
#> 2 A 200 3 44 52
#> 3 A 200 3 44 52
#> 4 A 200 3 44 44
#> 21 B 45 0 45 45
#> 31 C 104 2 0 52
#> 32 C 104 2 0 52
df3 <- subset(df2, select = c("group", "vol2"))
print(df3)
#> group vol2
#> 1 A 52
#> 2 A 52
#> 3 A 52
#> 4 A 44
#> 21 B 45
#> 31 C 52
#> 32 C 52
Being still relatively new to R, I'm just curious if someone knows a better way / function / method that gets to the same place. Seems like there might be. I could potentially have a more complex way of breaking up the rows and I was thinking maybe there's a method that applies a UDF to the dataframe to do something like this. I was searching for "expand group/groups" but was finding mostly "expand.grid" which isn't what I'm doing here.
Thank you for any suggestions!
| [
"A quick function to help split each number by the modulus,\nfun <- function(num, mod) c(rep(mod, floor(num / mod)), (num-1) %% mod + 1)\nfun(200, 52)\n# [1] 52 52 52 44\nfun(45, 52)\n# [1] 45\nfun(104, 52)\n# [1] 52 52\n\nAnd we can apply this a number of ways:\ndplyr\nlibrary(dplyr)\ndf1 %>%\n group_by(group) %>%\n summarize(vol2 = fun(volume, 52), .groups = \"drop\")\n# # A tibble: 7 x 2\n# group vol2\n# <chr> <dbl>\n# 1 A 52\n# 2 A 52\n# 3 A 52\n# 4 A 44\n# 5 B 45\n# 6 C 52\n# 7 C 52\n\nbase R\ndo.call(rbind, by(df1, seq(nrow(df1)),\n FUN = function(z) data.frame(group = z$group, vol2 = fun(z$volume, 52))))\n\ndata.table\nlibrary(data.table)\nsetDT(df1)\ndf1[, .(vol2 = fun(volume, 52)), by = group]\n\n",
"A tidyverse approach using purrr::pmap and tidyr::unnest_longer may look like so:\nlibrary(dplyr, w = FALSE)\nlibrary(tidyr)\nlibrary(purrr)\n\ndiv <- 52\n\ndf1 |> \n mutate(intgr = volume %/% div, remainder = volume %% div, intgr1 = +(remainder > 0)) |> \n mutate(vol2 = purrr::pmap(list(intgr, intgr1, remainder), ~ c(rep(div, ..1), rep(..3, ..2)))) |> \n tidyr::unnest_longer(vol2) |> \n select(-intgr1)\n#> # A tibble: 7 × 5\n#> group volume intgr remainder vol2\n#> <chr> <int> <dbl> <dbl> <dbl>\n#> 1 A 200 3 44 52\n#> 2 A 200 3 44 52\n#> 3 A 200 3 44 52\n#> 4 A 200 3 44 44\n#> 5 B 45 0 45 45\n#> 6 C 104 2 0 52\n#> 7 C 104 2 0 52\n\n",
"With data.table and rep:\nlibrary(data.table)\n\nsetDT(df1)[, .(vol2 = c(rep(52, volume%/%52), (volume%%52)[sign(volume%%52)])), group]\n#> group vol2\n#> 1: A 52\n#> 2: A 52\n#> 3: A 52\n#> 4: A 44\n#> 5: B 45\n#> 6: C 52\n#> 7: C 52\n\nOr\nsetDT(df1)[, .(vol2 = c(rep(52, volume%/%52), volume%%52)), group][vol2 != 0]\n#> group vol2\n#> 1: A 52\n#> 2: A 52\n#> 3: A 52\n#> 4: A 44\n#> 5: B 45\n#> 6: C 52\n#> 7: C 52\n\n",
"Vectorised and without grouping:\ndf1 <- data.frame(group = c(\"A\", \"B\", \"C\"),\n volume = c(200L, 45L, 104L))\n\nn <- 52\nidx <- df1$volume %/% n + ((sel <- df1$volume %% n) != 0)\nout <- df1[rep(seq_len(nrow(df1)), idx),]\nout$volume <- n\nout$volume[cumsum(idx)[sel != 0]] <- sel[sel != 0]\n## group volume\n##1 A 52\n##1.1 A 52\n##1.2 A 52\n##1.3 A 44\n##2 B 45\n##3 C 52\n##3.1 C 52\n\n",
"Another base R solution using aggregate :\naggregate(.~group,df1,\\(x) c(rep(52, x / 52), (x-1) %% 52 + 1))\n\n group volume\n1 A 52, 52, 52, 44\n2 B 45\n3 C 52, 52, 52\n\nThis results in a list column for volume (could be useful)\nTo transform it to a long dataframe we can either use stack:\n\nwith(\n aggregate(.~group,df1,\\(x) c(rep(52, x / 52), (x-1) %% 52 + 1)),\n setNames(stack(setNames(volume,group))[2:1],names(df1))\n )\n\n group volume\n1 A 52\n2 A 52\n3 A 52\n4 A 44\n5 B 45\n6 C 52\n7 C 52\n8 C 52\n\n\n\nOr alternatively use unnest from tidyr\nlibrary(tidyr)\n\naggregate(.~group,df1,\\(x) c(rep(52, x / 52), (x-1) %% 52 + 1)) %>% unnest(volume)\n\n# A tibble: 8 × 2\n group volume\n <chr> <dbl>\n1 A 52\n2 A 52\n3 A 52\n4 A 44\n5 B 45\n6 C 52\n7 C 52\n8 C 52\n\n"
] | [
8,
3,
3,
2,
1
] | [] | [] | [
"group",
"r"
] | stackoverflow_0074648253_group_r.txt |
Q:
How do I handle a message from a user generated combobox in my main window?
I've created a combobox manually in my main window using CreateWindow(). Because of this it has no ID associated with it only the handle returned by CreateWindow(). When the user makes a selection from the combobox list and the combobox throws a message, how do I handle that in the WinProc WM_COMMAND code since there is no ID associated with the combobox? As far as I can tell, I must know the combobox ID to handle the message. This is especially problematic once I have more than one combobox in the main window. Surely there is something I am missing and there is a simple answer.
A:
Okay. So what Igor Tandetnik stated is the answer.
It does have an ID - whatever you passed for hMenu parameter of CreateWindow...
This is also discussed in the following link.
What is winapi HMENU and how do i use it?
From the above link:
HMENU is a handle to a menu, e.g. as created by LoadMenu (which creates a menu from a specification in a resource).
But, the CreateWindow function re-uses the same argument for two different purposes. With a top-level window it's a menu handle, but with a child window it's the child window id, which should be in 16-bit integer range...
When creating a child window, just cast the id to HMENU.
| How do I handle a message from a user generated combobox in my main window? | I've created a combobox manually in my main window using CreateWindow(). Because of this it has no ID associated with it only the handle returned by CreateWindow(). When the user makes a selection from the combobox list and the combobox throws a message, how do I handle that in the WinProc WM_COMMAND code since there is no ID associated with the combobox? As far as I can tell, I must know the combobox ID to handle the message. This is especially problematic once I have more than one combobox in the main window. Surely there is something I am missing and there is a simple answer.
| [
"Okay. So what Igor Tandetnik stated is the answer.\n\nIt does have an ID - whatever you passed for hMenu parameter of CreateWindow...\n\nThis is also discussed in the following link.\nWhat is winapi HMENU and how do i use it?\nFrom the above link:\n\nHMENU is a handle to a menu, e.g. as created by LoadMenu (which creates a menu from a specification in a resource).\n\n\nBut, the CreateWindow function re-uses the same argument for two different purposes. With a top-level window it's a menu handle, but with a child window it's the child window id, which should be in 16-bit integer range...\n\n\nWhen creating a child window, just cast the id to HMENU.\n\n"
] | [
0
] | [] | [] | [
"visual_c++",
"winapi"
] | stackoverflow_0074672072_visual_c++_winapi.txt |
Q:
Using Powershell [DateTime]::ParseExact - Funny Strings?
Good afternoon Powershell wizards!
I am hoping someone can explain to me how I can fix this issue, and more importantly what the issue actually is!
I'm attempting to fix an old script I wrote years ago that searches for several dates on a files properties and picks one to use for renaming that file.
The issue I'm having is that when I use parseExact it fails for the date strings read from the files... but it works if I manually type the same string into powershell!
Please note that this script is only going to be ran on my PC and only needs to work with dates from my files formats so I'm not too worried about use of $null unless it's related.
See example below:
Write-Host "TEST 1"
$DateTime = [DateTime]::ParseExact("240720211515","ddMMyyyyHHmm",$null)
Write-Host $DateTime # WORKS!
Write-Host "TEST 2"
$DateTime2 = [DateTime]::ParseExact("240720211515","ddMMyyyyHHmm",$null)
Write-Host $DateTime2 # FAILS!
Looks the same right?
Here is a more real world example of what I'm up to that fails
$file = Get-Item "C:\SomeFolder\somefile.jpg"
$shellObject = New-Object -ComObject Shell.Application
$directoryObject = $shellObject.NameSpace( $file.Directory.FullName )
$fileObject = $directoryObject.ParseName( $file.Name )
$property = 'Date taken'
for(
$index = 5;
$directoryObject.GetDetailsOf( $directoryObject.Items, $index ) -ne $property;
++$index) { }
$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)
Write-Host $photoDate # <-- This reads 03/08/2021 09:15
$output = [DateTime]::ParseExact($photoDate,"dd/MM/yyyy HH:mm",$null) # <-- This fails
Write-Host $output
# If i manually type in here it works.... If I copy and paste from the Write-Host it fails...
$someInput = "03/08/2021 09:15"
$workingOutput = [DateTime]::ParseExact($someInput,"dd/MM/yyyy HH:mm",$null)
Write-Host $workingOutput
A:
For anyone else who comes across this, it seems like there are invisible characters being added. Thanks for the spot @SantiagoSquarzon
This fixes it for my particular purposes:
$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)
$utfFree = $photoDate -replace "\u200e|\u200f", ""
A:
I ran into this issue when I started exploring metadata with PowerShell. My solution was to create a regex "inverted whitelist" character class and delete (replace with '') all non-whitelist characters.
But then I learned of an alternate method avaiable to FolderItem obejcts: the ExtenedProperty() method.
Gets the value of a property from an item's property set. The property can be specified either by name or by the property set's format identifier (FMTID) and property identifier (PID).
It's primary strength being the feturn type corresponds to the property value type:
When this method returns, contains the value of the property, if it exists for the specified item. The value will have full typing—for example, dates are returned as dates, not strings.
Using this method to access date properties eliminates string parsing and the issues you encountered:
PS Pictures> $FileInfo = Get-Item "C:\Users\keith\Pictures\Leland\2009\Leland 191.JPG"
PS Pictures> $Shell = New-Object -ComObject shell.application
PS Pictures> $comFolder = $Shell.NameSpace($FileInfo.DirectoryName)
PS Pictures> $comFile = $comFolder.ParseName($FileInfo.Name)
PS Pictures>
PS Pictures> $comFolder.GetDetailsOf($null,12)
Date taken
PS Pictures> $comFolder.GetDetailsOf($comFile,12)
9/5/2009 2:06 PM
PS Pictures> $comFolder.GetDetailsOf($comFile,12).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PS Pictures> $comFile.ExtendedProperty("DateTaken")
PS Pictures> $comFile.ExtendedProperty("System.Photo.DateTaken")
Saturday, September 5, 2009 07:06:41 PM
PS Pictures> $comFile.ExtendedProperty("System.Photo.DateTaken").GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DateTime System.ValueType
It also returns arrays for properties than can contain multiple values (Tags, Contributing Artists, etc/):
PS Pictures> $comFolder.GetDetailsOf($null,18)
Tags
PS Pictures> $comFolder.GetDetailsOf($comFile,18)
Leland; Tim; Jorge
PS Pictures> $comFolder.GetDetailsOf($comFile,18).GetTYpe()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PS Pictures> $comFile.ExtendedProperty("System.KeyWords")
PS Pictures> $comFile.ExtendedProperty("System.Keywords")
Leland
Tim
Jorge
PS Pictures> $comFile.ExtendedProperty("System.Keywords").GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String[] System.Array
But GetDetailsOf() is still useful, particularly for values that use an EnumList:
PS Pictures> $comFolder.GetDetailsOf($null,261)
Flash mode
PS Pictures> $comFolder.GetDetailsOf($comFile,261)
No flash, auto
PS Pictures> $comFile.ExtendedProperty("System.Photo.Flash")
24
A:
Yeah something weird is going on with that string. (paste with control v in the console) It doesn't display right in stackoverflow, but ascii only goes up to code 0x7f (127). You can see the 200e and 200f hex codes. They look like little hooks. (emoji's would require extra handling with the surrogate characters)
$string = '# <-- This reads 03/08/2021 09:15'
function chardump {
param($string)
[char[]]$string |
% { [pscustomobject]@{Char = $_; Code = [int]$_ | % tostring x} }
}
chardump $string
Char Code
---- ----
# 23
20
< 3c
- 2d
- 2d
20
T 54
h 68
i 69
s 73
20
r 72
e 65
a 61
d 64
s 73
20
200e
0 30
3 33
/ 2f
200e
0 30
8 38
/ 2f
200e
2 32
0 30
2 32
1 31
20
200f
200e
0 30
9 39
: 3a
1 31
5 35
chardump $string | ? {[int]('0x' + $_.code) -gt 0x7f}
Char Code
---- ----
200e
200e
200e
200f
200e
| Using Powershell [DateTime]::ParseExact - Funny Strings? | Good afternoon Powershell wizards!
I am hoping someone can explain to me how I can fix this issue, and more importantly what the issue actually is!
I'm attempting to fix an old script I wrote years ago that searches for several dates on a files properties and picks one to use for renaming that file.
The issue I'm having is that when I use parseExact it fails for the date strings read from the files... but it works if I manually type the same string into powershell!
Please note that this script is only going to be ran on my PC and only needs to work with dates from my files formats so I'm not too worried about use of $null unless it's related.
See example below:
Write-Host "TEST 1"
$DateTime = [DateTime]::ParseExact("240720211515","ddMMyyyyHHmm",$null)
Write-Host $DateTime # WORKS!
Write-Host "TEST 2"
$DateTime2 = [DateTime]::ParseExact("240720211515","ddMMyyyyHHmm",$null)
Write-Host $DateTime2 # FAILS!
Looks the same right?
Here is a more real world example of what I'm up to that fails
$file = Get-Item "C:\SomeFolder\somefile.jpg"
$shellObject = New-Object -ComObject Shell.Application
$directoryObject = $shellObject.NameSpace( $file.Directory.FullName )
$fileObject = $directoryObject.ParseName( $file.Name )
$property = 'Date taken'
for(
$index = 5;
$directoryObject.GetDetailsOf( $directoryObject.Items, $index ) -ne $property;
++$index) { }
$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)
Write-Host $photoDate # <-- This reads 03/08/2021 09:15
$output = [DateTime]::ParseExact($photoDate,"dd/MM/yyyy HH:mm",$null) # <-- This fails
Write-Host $output
# If i manually type in here it works.... If I copy and paste from the Write-Host it fails...
$someInput = "03/08/2021 09:15"
$workingOutput = [DateTime]::ParseExact($someInput,"dd/MM/yyyy HH:mm",$null)
Write-Host $workingOutput
| [
"For anyone else who comes across this, it seems like there are invisible characters being added. Thanks for the spot @SantiagoSquarzon\nThis fixes it for my particular purposes:\n$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)\n$utfFree = $photoDate -replace \"\\u200e|\\u200f\", \"\"\n\n",
"I ran into this issue when I started exploring metadata with PowerShell. My solution was to create a regex \"inverted whitelist\" character class and delete (replace with '') all non-whitelist characters.\nBut then I learned of an alternate method avaiable to FolderItem obejcts: the ExtenedProperty() method.\n\nGets the value of a property from an item's property set. The property can be specified either by name or by the property set's format identifier (FMTID) and property identifier (PID).\n\nIt's primary strength being the feturn type corresponds to the property value type:\n\nWhen this method returns, contains the value of the property, if it exists for the specified item. The value will have full typing—for example, dates are returned as dates, not strings.\n\nUsing this method to access date properties eliminates string parsing and the issues you encountered:\nPS Pictures> $FileInfo = Get-Item \"C:\\Users\\keith\\Pictures\\Leland\\2009\\Leland 191.JPG\"\nPS Pictures> $Shell = New-Object -ComObject shell.application\nPS Pictures> $comFolder = $Shell.NameSpace($FileInfo.DirectoryName)\nPS Pictures> $comFile = $comFolder.ParseName($FileInfo.Name)\nPS Pictures>\nPS Pictures> $comFolder.GetDetailsOf($null,12)\nDate taken\nPS Pictures> $comFolder.GetDetailsOf($comFile,12)\n9/5/2009 2:06 PM\nPS Pictures> $comFolder.GetDetailsOf($comFile,12).GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\nPS Pictures> $comFile.ExtendedProperty(\"DateTaken\")\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.DateTaken\")\n\nSaturday, September 5, 2009 07:06:41 PM\n\n\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.DateTaken\").GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True DateTime System.ValueType\n\nIt also returns arrays for properties than can contain multiple values (Tags, Contributing Artists, etc/):\nPS Pictures> $comFolder.GetDetailsOf($null,18)\nTags\nPS Pictures> $comFolder.GetDetailsOf($comFile,18)\nLeland; Tim; Jorge\nPS Pictures> $comFolder.GetDetailsOf($comFile,18).GetTYpe()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\nPS Pictures> $comFile.ExtendedProperty(\"System.KeyWords\")\nPS Pictures> $comFile.ExtendedProperty(\"System.Keywords\")\nLeland\nTim\nJorge\nPS Pictures> $comFile.ExtendedProperty(\"System.Keywords\").GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String[] System.Array\n\n\nBut GetDetailsOf() is still useful, particularly for values that use an EnumList:\nPS Pictures> $comFolder.GetDetailsOf($null,261)\nFlash mode\nPS Pictures> $comFolder.GetDetailsOf($comFile,261)\nNo flash, auto\nPS Pictures> $comFile.ExtendedProperty(\"System.Photo.Flash\")\n24\n\n",
"Yeah something weird is going on with that string. (paste with control v in the console) It doesn't display right in stackoverflow, but ascii only goes up to code 0x7f (127). You can see the 200e and 200f hex codes. They look like little hooks. (emoji's would require extra handling with the surrogate characters)\n$string = '# <-- This reads 03/08/2021 09:15' \nfunction chardump {\n param($string)\n [char[]]$string | \n % { [pscustomobject]@{Char = $_; Code = [int]$_ | % tostring x} }\n}\nchardump $string\n\n\nChar Code\n---- ----\n # 23\n 20\n < 3c\n - 2d\n - 2d\n 20\n T 54\n h 68\n i 69\n s 73\n 20\n r 72\n e 65\n a 61\n d 64\n s 73\n 20\n 200e\n 0 30\n 3 33\n / 2f\n 200e\n 0 30\n 8 38\n / 2f\n 200e\n 2 32\n 0 30\n 2 32\n 1 31\n 20\n 200f\n 200e\n 0 30\n 9 39\n : 3a\n 1 31\n 5 35\n\n\nchardump $string | ? {[int]('0x' + $_.code) -gt 0x7f}\n\nChar Code\n---- ----\n 200e\n 200e\n 200e\n 200f\n 200e\n\n"
] | [
1,
1,
0
] | [] | [] | [
"datetime",
"powershell",
"windows"
] | stackoverflow_0074617304_datetime_powershell_windows.txt |
Q:
TestDome Question: Worker's memory increases constantly even if released?
The question reads:
After client complaints, it is observed that the memory usage of the Worker component constantly increases, even if the memory is supposedly released by the Worker. Fix the issue without changing the public API of TaskResource and Worker.
And the code is:
import java.util.*;
import java.util.HashMap;
public class Worker {
private HashMap<Integer, TaskResource> taskResources = new HashMap<Integer, TaskResource>();
public Iterable<TaskResource> getTaskResources() {
return this.taskResources.values();
}
public TaskResource acquireTaskResource(int id) {
TaskResource w = this.taskResources.getOrDefault(id, null);
if (w == null) {
w = new TaskResource(id);
this.taskResources.put(id, w);
}
return w;
}
public void releaseTaskResource(int id) {
TaskResource w = this.taskResources.getOrDefault(id, null);
if (w == null)
throw new IllegalArgumentException();
w.close();
}
public class TaskResource implements AutoCloseable {
private List<String> taskList = new ArrayList<String>();
private int id;
public int getId() {
return this.id;
}
public List<String> getTasks() {
return this.taskList;
}
public TaskResource(int id) {
this.id = id;
}
public void doTask(String task) {
if (this.taskList == null)
throw new IllegalStateException(this.getClass().getName());
this.taskList.add(task);
}
@Override
public void close() {
this.taskList = null;
}
}
public static void main(String[] args) {
Worker d = new Worker();
d.acquireTaskResource(1).doTask("Task11");
d.acquireTaskResource(2).doTask("Task21");
System.out.println(String.join(", ", d.acquireTaskResource(2).getTasks()));
d.releaseTaskResource(2);
d.acquireTaskResource(1).doTask("Task12");
System.out.println(String.join(", ", d.acquireTaskResource(1).getTasks()));
d.releaseTaskResource(1);
}
}
I'm not really sure where to begin. I don't even understand what the purpose of code like this would even be. Can I get a nudge in the right direction?
A:
Currently, when you release a task resource you do not remove the associated Task from the taskResources HashMap. Thus it will grow forever. Add a line of code to remove it from the Map. Like,
public void releaseTaskResource(int id) {
TaskResource w = this.taskResources.getOrDefault(id, null);
if (w == null) {
throw new IllegalArgumentException();
}
w.close();
this.taskResources.remove(id);
}
| TestDome Question: Worker's memory increases constantly even if released? | The question reads:
After client complaints, it is observed that the memory usage of the Worker component constantly increases, even if the memory is supposedly released by the Worker. Fix the issue without changing the public API of TaskResource and Worker.
And the code is:
import java.util.*;
import java.util.HashMap;
public class Worker {
private HashMap<Integer, TaskResource> taskResources = new HashMap<Integer, TaskResource>();
public Iterable<TaskResource> getTaskResources() {
return this.taskResources.values();
}
public TaskResource acquireTaskResource(int id) {
TaskResource w = this.taskResources.getOrDefault(id, null);
if (w == null) {
w = new TaskResource(id);
this.taskResources.put(id, w);
}
return w;
}
public void releaseTaskResource(int id) {
TaskResource w = this.taskResources.getOrDefault(id, null);
if (w == null)
throw new IllegalArgumentException();
w.close();
}
public class TaskResource implements AutoCloseable {
private List<String> taskList = new ArrayList<String>();
private int id;
public int getId() {
return this.id;
}
public List<String> getTasks() {
return this.taskList;
}
public TaskResource(int id) {
this.id = id;
}
public void doTask(String task) {
if (this.taskList == null)
throw new IllegalStateException(this.getClass().getName());
this.taskList.add(task);
}
@Override
public void close() {
this.taskList = null;
}
}
public static void main(String[] args) {
Worker d = new Worker();
d.acquireTaskResource(1).doTask("Task11");
d.acquireTaskResource(2).doTask("Task21");
System.out.println(String.join(", ", d.acquireTaskResource(2).getTasks()));
d.releaseTaskResource(2);
d.acquireTaskResource(1).doTask("Task12");
System.out.println(String.join(", ", d.acquireTaskResource(1).getTasks()));
d.releaseTaskResource(1);
}
}
I'm not really sure where to begin. I don't even understand what the purpose of code like this would even be. Can I get a nudge in the right direction?
| [
"Currently, when you release a task resource you do not remove the associated Task from the taskResources HashMap. Thus it will grow forever. Add a line of code to remove it from the Map. Like,\npublic void releaseTaskResource(int id) {\n TaskResource w = this.taskResources.getOrDefault(id, null);\n if (w == null) {\n throw new IllegalArgumentException();\n }\n w.close();\n this.taskResources.remove(id);\n}\n\n"
] | [
1
] | [] | [] | [
"java"
] | stackoverflow_0074672337_java.txt |
Q:
isRemoveOnCompletion not work after the animation is completed
I want my moonImageView to keep its last size/dimension after the animation ended; image gets bigger by 1.25 time, but adding isRemoveOnCompletion = false did not help. The size of image returned back after the animation ended.
How may I fix this? Did I misuse it?
//setup
moonImageView.contentMode = .scaleAspectFit
moonImageView.translatesAutoresizingMaskIntoConstraints = false
moonImageView.addTapGesture(tapNumber: 1, target: self, action: #selector(moonClick))
//layout
NSLayoutConstraint.activate([
moonImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
moonImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
moonImageView.widthAnchor.constraint(equalToConstant: 150),
moonImageView.heightAnchor.constraint(equalToConstant: 150)
])
//func
@objc private func moonClick() {
let moonAnimation = CABasicAnimation(keyPath: "transform.scale")
moonAnimation.fromValue = 1
moonAnimation.toValue = 1.25
moonAnimation.duration = 0.25
moonAnimation.isRemovedOnCompletion = false
moonImageView.layer.add(moonAnimation, forKey: nil)
}
A:
Forget the whole isRemovedOnCompletion thing; that's just a canard. Of course the animation should be removed on completion; it's over. The problem is simply that you forgot to the layer's actual transform to the toValue. (The animation is just sort of a visual illusion and has no effect on the layer's actual transform.)
CATransaction.setDisableActions(true)
moonImageView.layer.transform = CATransform3DMakeScale(1.25, 1.25, 1)
| isRemoveOnCompletion not work after the animation is completed | I want my moonImageView to keep its last size/dimension after the animation ended; image gets bigger by 1.25 time, but adding isRemoveOnCompletion = false did not help. The size of image returned back after the animation ended.
How may I fix this? Did I misuse it?
//setup
moonImageView.contentMode = .scaleAspectFit
moonImageView.translatesAutoresizingMaskIntoConstraints = false
moonImageView.addTapGesture(tapNumber: 1, target: self, action: #selector(moonClick))
//layout
NSLayoutConstraint.activate([
moonImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
moonImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
moonImageView.widthAnchor.constraint(equalToConstant: 150),
moonImageView.heightAnchor.constraint(equalToConstant: 150)
])
//func
@objc private func moonClick() {
let moonAnimation = CABasicAnimation(keyPath: "transform.scale")
moonAnimation.fromValue = 1
moonAnimation.toValue = 1.25
moonAnimation.duration = 0.25
moonAnimation.isRemovedOnCompletion = false
moonImageView.layer.add(moonAnimation, forKey: nil)
}
| [
"Forget the whole isRemovedOnCompletion thing; that's just a canard. Of course the animation should be removed on completion; it's over. The problem is simply that you forgot to the layer's actual transform to the toValue. (The animation is just sort of a visual illusion and has no effect on the layer's actual transform.)\nCATransaction.setDisableActions(true)\nmoonImageView.layer.transform = CATransform3DMakeScale(1.25, 1.25, 1)\n\n"
] | [
1
] | [] | [] | [
"core_animation",
"core_graphics",
"swift",
"uikit",
"uiview"
] | stackoverflow_0074670421_core_animation_core_graphics_swift_uikit_uiview.txt |
Q:
Apps Script for Google Sheets: setValues parameters
I've been writing a script to copy some data from an input sheet to a database to keep track of some data. I've managed to successfully write the code for linear arrays (only one row) but when I try to copy an entire 15x15 cells range I get an error stating the parameters are not correct (suggesting the dimension of the arrays are not correct) but I can't seem to understand why.
I tried both copying directly the entire 15x15 range and creating a for loop to copy row by row 15 times but I can't mangage to make it work.
Here is the main structure:
// active spreadsheet and source + target sheets
const activeSheet = SpreadsheetApp.getActiveSpreadsheet();
const srcSheet = activeSheet.getSheetByName('Data Entry');
const dstTOTSheet = activeSheet.getSheetByName('DataBaseTOT');
var firstEmptyRowTOT = dstTOTSheet.getLastRow()+1;
For loop test:
for (var i=0; i=14;i=i+1) {
// source cells
var RoundInfo = srcSheet.getRange(10+i, 2, 1, 15); // 15x15 B10:P24
// target cells
var dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT + i, 21, 1, 15); // I am starting from column 21 because of some other data
// set value
dstTOTRoundInfo.setValues(RoundInfo);
}
Direct 15x15 test:
// source cells
var RoundInfo = srcSheet.getRange("B10:P24"); // 15x15 B10:P24
// target cells
var dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT, 21, 15, 15);
// set value
dstTOTRoundInfo.setValues(RoundInfo);
A:
The error you are receiving is because the condition in the for loop is incorrect. In the condition, you are using the assignment operator = instead of the comparison operator ==. This causes the condition to always evaluate to true, and the loop will run indefinitely. You should change the condition to i < 15 or i <= 14 to fix the error.
Here is an example of the for loop with the correct condition:
for (var i=0; i < 15; i++) {
// source cells
var RoundInfo = srcSheet.getRange(10+i, 2, 1, 15); // 15x15 B10:P24
// target cells
var dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT + i, 21, 1, 15); // I am starting from column 21 because of some other data
// set value
dstTOTRoundInfo.setValues(RoundInfo);
}
Alternatively, you can use the setValues() method to copy the entire range in one call, like this:
// source cells
var RoundInfo = srcSheet.getRange("B10:P24").getValues(); // 15x15 B10:P24
// target cells
var dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT, 21, 15, 15);
// set value
dstTOTRoundInfo.setValues(RoundInfo);
Note that when using setValues(), the input range must be a two-dimensional array, which is why we are using getValues() to convert the range to an array. Also, the target range must have the same dimensions as the input array, which is why we are specifying the dimensions of the range explicitly.
A:
It is actually not that difficult to understand the 2D array concept for spreadsheet, it works like this:
// inner arrary is always one row of values:
// the 1st value (array index: 0) of the inner-array is always the cell value of the 1st column of the given row.
const row_1 = ['row_value_1-1','row_value_2-1','row_value_3-1','row_value_4-1'];
const row_2 = ['row_value_2-1','row_value_2-2','row_value_3-2','row_value_4-2'];
const row_3 = ['row_value_3-1','row_value_2-3','row_value_3-3','row_value_4-3'];
// the outter-array is always the container of every rows you have in range,
// the leangth of rows (which is the leangth of each inner-array) must be the same for this structure to work in spreadsheet.
const data = [
row_1, // the 1st value (array index: 0) of the outter-array is always the 1st row,
row_2, // the 2nd value (array index: 1) of the outter-array is always the 2nd row, etc.
row_3
];
// when you loop over such kind of 2D array, it is easier to understand with a "for... of" loop than the classic "for" loop:
for (const row of data) { // << this means "for each row of the given data"
for (const col of row) { // << this means "for each column of the given row"
// this structure will go through each cell of row 1, than each cell of row 2, etc., until all rows of the given data are iterated.
console.log(col);
}
}
/**output:
row_value_1-1
row_value_2-1
row_value_3-1
row_value_4-1
row_value_2-1
row_value_2-2
row_value_3-2
row_value_4-2
row_value_3-1
row_value_2-3
row_value_3-3
row_value_4-3
*/
// and if you need to works with the indexes of some cell, you can get the index by this:
for (const [rIndex,row] of data.entries()) {
for (const [cIndex,col] of row.entries()) {
console.log(rIndex,cIndex,col);
}
}
/** output:
0 0 row_value_1-1
0 1 row_value_2-1
0 2 row_value_3-1
0 3 row_value_4-1
1 0 row_value_2-1
1 1 row_value_2-2
1 2 row_value_3-2
1 3 row_value_4-2
2 0 row_value_3-1
2 1 row_value_2-3
2 2 row_value_3-3
2 3 row_value_4-3
*/
| Apps Script for Google Sheets: setValues parameters | I've been writing a script to copy some data from an input sheet to a database to keep track of some data. I've managed to successfully write the code for linear arrays (only one row) but when I try to copy an entire 15x15 cells range I get an error stating the parameters are not correct (suggesting the dimension of the arrays are not correct) but I can't seem to understand why.
I tried both copying directly the entire 15x15 range and creating a for loop to copy row by row 15 times but I can't mangage to make it work.
Here is the main structure:
// active spreadsheet and source + target sheets
const activeSheet = SpreadsheetApp.getActiveSpreadsheet();
const srcSheet = activeSheet.getSheetByName('Data Entry');
const dstTOTSheet = activeSheet.getSheetByName('DataBaseTOT');
var firstEmptyRowTOT = dstTOTSheet.getLastRow()+1;
For loop test:
for (var i=0; i=14;i=i+1) {
// source cells
var RoundInfo = srcSheet.getRange(10+i, 2, 1, 15); // 15x15 B10:P24
// target cells
var dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT + i, 21, 1, 15); // I am starting from column 21 because of some other data
// set value
dstTOTRoundInfo.setValues(RoundInfo);
}
Direct 15x15 test:
// source cells
var RoundInfo = srcSheet.getRange("B10:P24"); // 15x15 B10:P24
// target cells
var dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT, 21, 15, 15);
// set value
dstTOTRoundInfo.setValues(RoundInfo);
| [
"The error you are receiving is because the condition in the for loop is incorrect. In the condition, you are using the assignment operator = instead of the comparison operator ==. This causes the condition to always evaluate to true, and the loop will run indefinitely. You should change the condition to i < 15 or i <= 14 to fix the error.\nHere is an example of the for loop with the correct condition:\nfor (var i=0; i < 15; i++) {\n// source cells\nvar RoundInfo = srcSheet.getRange(10+i, 2, 1, 15); // 15x15 B10:P24\n\n// target cells\nvar dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT + i, 21, 1, 15); // I am starting from column 21 because of some other data\n// set value\ndstTOTRoundInfo.setValues(RoundInfo);\n}\n\nAlternatively, you can use the setValues() method to copy the entire range in one call, like this:\n// source cells\nvar RoundInfo = srcSheet.getRange(\"B10:P24\").getValues(); // 15x15 B10:P24\n// target cells\nvar dstTOTRoundInfo = dstTOTSheet.getRange(firstEmptyRowTOT, 21, 15, 15);\n// set value\ndstTOTRoundInfo.setValues(RoundInfo);\n\nNote that when using setValues(), the input range must be a two-dimensional array, which is why we are using getValues() to convert the range to an array. Also, the target range must have the same dimensions as the input array, which is why we are specifying the dimensions of the range explicitly.\n",
"It is actually not that difficult to understand the 2D array concept for spreadsheet, it works like this:\n\n\n// inner arrary is always one row of values:\n// the 1st value (array index: 0) of the inner-array is always the cell value of the 1st column of the given row.\nconst row_1 = ['row_value_1-1','row_value_2-1','row_value_3-1','row_value_4-1'];\nconst row_2 = ['row_value_2-1','row_value_2-2','row_value_3-2','row_value_4-2'];\nconst row_3 = ['row_value_3-1','row_value_2-3','row_value_3-3','row_value_4-3'];\n\n// the outter-array is always the container of every rows you have in range,\n// the leangth of rows (which is the leangth of each inner-array) must be the same for this structure to work in spreadsheet.\nconst data = [\n row_1, // the 1st value (array index: 0) of the outter-array is always the 1st row,\n row_2, // the 2nd value (array index: 1) of the outter-array is always the 2nd row, etc.\n row_3\n ];\n\n// when you loop over such kind of 2D array, it is easier to understand with a \"for... of\" loop than the classic \"for\" loop:\nfor (const row of data) { // << this means \"for each row of the given data\"\n for (const col of row) { // << this means \"for each column of the given row\"\n // this structure will go through each cell of row 1, than each cell of row 2, etc., until all rows of the given data are iterated.\n console.log(col);\n }\n}\n/**output:\nrow_value_1-1\nrow_value_2-1\nrow_value_3-1\nrow_value_4-1\nrow_value_2-1\nrow_value_2-2\nrow_value_3-2\nrow_value_4-2\nrow_value_3-1\nrow_value_2-3\nrow_value_3-3\nrow_value_4-3\n*/\n\n// and if you need to works with the indexes of some cell, you can get the index by this:\nfor (const [rIndex,row] of data.entries()) {\n for (const [cIndex,col] of row.entries()) {\n console.log(rIndex,cIndex,col);\n }\n}\n/** output:\n0 0 row_value_1-1\n0 1 row_value_2-1\n0 2 row_value_3-1\n0 3 row_value_4-1\n1 0 row_value_2-1\n1 1 row_value_2-2\n1 2 row_value_3-2\n1 3 row_value_4-2\n2 0 row_value_3-1\n2 1 row_value_2-3\n2 2 row_value_3-3\n2 3 row_value_4-3\n*/\n\n\n\n"
] | [
0,
0
] | [] | [] | [
"google_apps_script",
"javascript"
] | stackoverflow_0074671511_google_apps_script_javascript.txt |
Q:
Complete the code to return the greatest value
I have an problem to undestand this question for the college. I just want to return the greastest value of this array but I don't undestand how I can do this. If someone explain to me how I solve this question, I really would appreciate.
public class Question1 {
public static void main(String[] args) {
double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};
// code insert here
System.out.println(bigger);
}
}
I try to instance the object, but I was not successful.
public class Question1 {
public static void main(String[] args) {
double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};
double bigger = Useful.bigger(list);
bigger = list;
list = new bigger();
System.out.println(bigger);
}
}
A:
It looks like you're trying to find the largest value in the array list, but your code is not doing that correctly. Here's one way you could do it:
Create a variable bigger that starts with the first value in the array list.
Loop through the rest of the values in the array, comparing each value to the current value of bigger.
If a value is larger than the current value of bigger, update bigger to have that value.
After the loop, bigger will have the largest value in the array.
Here's what that code might look like:
public class Question1 {
public static void main(String[] args) {
double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};
// Step 1: initialize bigger with the first value in the array
double bigger = list[0];
// Step 2-3: loop through the rest of the values in the array,
// comparing each value to bigger and updating bigger if necessary
for (int i = 1; i < list.length; i++) {
if (list[i] > bigger) {
bigger = list[i];
}
}
// Step 4: print out the largest value
System.out.println(bigger);
}
}
You can also use the Math.max method to simplify the code a bit:
public class Question1 {
public static void main(String[] args) {
double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};
// Step 1: initialize bigger with the first value in the array
double bigger = list[0];
// Step 2-3: loop through the rest of the values in the array,
// using Math.max to compare each value to bigger and update bigger if necessary
for (int i = 1; i < list.length; i++) {
bigger = Math.max(bigger, list[i]);
}
// Step 4: print out the largest value
System.out.println(bigger);
}
}
I hope that helps! Let me know if you have any other questions.
| Complete the code to return the greatest value | I have an problem to undestand this question for the college. I just want to return the greastest value of this array but I don't undestand how I can do this. If someone explain to me how I solve this question, I really would appreciate.
public class Question1 {
public static void main(String[] args) {
double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};
// code insert here
System.out.println(bigger);
}
}
I try to instance the object, but I was not successful.
public class Question1 {
public static void main(String[] args) {
double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};
double bigger = Useful.bigger(list);
bigger = list;
list = new bigger();
System.out.println(bigger);
}
}
| [
"It looks like you're trying to find the largest value in the array list, but your code is not doing that correctly. Here's one way you could do it:\n\nCreate a variable bigger that starts with the first value in the array list.\nLoop through the rest of the values in the array, comparing each value to the current value of bigger.\nIf a value is larger than the current value of bigger, update bigger to have that value.\nAfter the loop, bigger will have the largest value in the array.\n\nHere's what that code might look like:\npublic class Question1 {\n public static void main(String[] args) {\n double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};\n\n // Step 1: initialize bigger with the first value in the array\n double bigger = list[0];\n\n // Step 2-3: loop through the rest of the values in the array,\n // comparing each value to bigger and updating bigger if necessary\n for (int i = 1; i < list.length; i++) {\n if (list[i] > bigger) {\n bigger = list[i];\n }\n }\n\n // Step 4: print out the largest value\n System.out.println(bigger);\n }\n}\n\nYou can also use the Math.max method to simplify the code a bit:\npublic class Question1 {\n public static void main(String[] args) {\n double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};\n\n // Step 1: initialize bigger with the first value in the array\n double bigger = list[0];\n\n // Step 2-3: loop through the rest of the values in the array,\n // using Math.max to compare each value to bigger and update bigger if necessary\n for (int i = 1; i < list.length; i++) {\n bigger = Math.max(bigger, list[i]);\n }\n\n // Step 4: print out the largest value\n System.out.println(bigger);\n }\n}\n\nI hope that helps! Let me know if you have any other questions.\n"
] | [
1
] | [] | [] | [
"java",
"oop"
] | stackoverflow_0074672316_java_oop.txt |
Q:
Google Sheet - Reference a folder that is inside the worksheet folder
I am a beginner in creating Scripts in Google Sheets, so I would like some help to reference a folder that is inside the spreadsheet folder.
I would like to create a script that checks if there are more than 3 files in a given folder, if so, I would like it to return an error on the screen.
Important point: the files that need to be checked will always be in a folder that is inside the spreadsheet folder, so I would need to reference this, in the CMD it would be something like .\FolderWithFiles.
In this case, I cannot use the ID a of the folder which I want to be checked, because this is a model worksheet that will be duplicated several times.
Any idea how I can do this?
A:
I believe your goal is as follows.
You want to check the number of files in the folder including the active Spreadsheet you are using.
When the number of files is more than 3, you want to show an error.
In this case, how about the following sample script?
Sample script:
function myFunction() {
const ss = SpreadsheetApp.getActiveSpreadsheet(); // This is your active Spreadsheet.
const parentFolder = DriveApp.getFileById(ss.getId()).getParents();
if (parentFolder.hasNext()) {
const files = parentFolder.next().getFiles();
let count = 0;
while (files.hasNext()) {
const file = files.next();
// console.log(file.getName()); // When you use this line, you can see the filename of the files.
count++;
}
if (count >= 3) {
throw new Error("Your expected error.");
}
} else {
throw new Error("Spreadsheet has no parent folder.");
}
}
When this script is run, the number of files in the folder including the active Spreadsheet is checked. When the number of files is more than 3, an error like Your expected error. occurs.
If you want to use another Spreadsheet instead of the active Spreadsheet, please modify const ss = SpreadsheetApp.getActiveSpreadsheet(); to const ss = SpreadsheetApp.openById("###spreadsheetId###");.
Reference:
getParents()
| Google Sheet - Reference a folder that is inside the worksheet folder | I am a beginner in creating Scripts in Google Sheets, so I would like some help to reference a folder that is inside the spreadsheet folder.
I would like to create a script that checks if there are more than 3 files in a given folder, if so, I would like it to return an error on the screen.
Important point: the files that need to be checked will always be in a folder that is inside the spreadsheet folder, so I would need to reference this, in the CMD it would be something like .\FolderWithFiles.
In this case, I cannot use the ID a of the folder which I want to be checked, because this is a model worksheet that will be duplicated several times.
Any idea how I can do this?
| [
"I believe your goal is as follows.\n\nYou want to check the number of files in the folder including the active Spreadsheet you are using.\nWhen the number of files is more than 3, you want to show an error.\n\nIn this case, how about the following sample script?\nSample script:\nfunction myFunction() {\n const ss = SpreadsheetApp.getActiveSpreadsheet(); // This is your active Spreadsheet.\n const parentFolder = DriveApp.getFileById(ss.getId()).getParents();\n if (parentFolder.hasNext()) {\n const files = parentFolder.next().getFiles();\n let count = 0;\n while (files.hasNext()) {\n const file = files.next();\n // console.log(file.getName()); // When you use this line, you can see the filename of the files.\n count++;\n }\n if (count >= 3) {\n throw new Error(\"Your expected error.\");\n }\n } else {\n throw new Error(\"Spreadsheet has no parent folder.\");\n }\n}\n\n\nWhen this script is run, the number of files in the folder including the active Spreadsheet is checked. When the number of files is more than 3, an error like Your expected error. occurs.\n\nIf you want to use another Spreadsheet instead of the active Spreadsheet, please modify const ss = SpreadsheetApp.getActiveSpreadsheet(); to const ss = SpreadsheetApp.openById(\"###spreadsheetId###\");.\n\n\nReference:\n\ngetParents()\n\n"
] | [
1
] | [] | [] | [
"google_apps_script",
"google_sheets"
] | stackoverflow_0074672300_google_apps_script_google_sheets.txt |
Q:
How to read a big tif file in python?
I'm loading a tiff file from http://oceancolor.gsfc.nasa.gov/DOCS/DistFromCoast/
from PIL import Image
im = Image.open('GMT_intermediate_coast_distance_01d.tif')
The data is large (im.size=(36000, 18000) 1.3GB) and conventional conversion doesn't work; i.e, imarray.shape returns ()
import numpy as np
imarray=np.zeros(im.size)
imarray=np.array(im)
How can I convert this tiff file to a numpy.array?
A:
May you dont have too much Ram for this image.You'll need at least some more than 1.3GB free memory.
I don't know what you're doing with the image and you read the entire into your memory but i recommend you to read it bit by bit if its possible to avoid blowing up your computer.
You can use Image.getdata() which returns one pixel per time.
Also read some more for Image.open on this link :
http://www.pythonware.com/library/pil/handbook/
A:
So far I have tested many alternatives but only gdal worked always even with huge 16bit images.
You can open an image with something like this:
from osgeo import gdal
import numpy as np
ds = gdal.Open("name.tif")
channel = np.array(ds.GetRasterBand(1).ReadAsArray())
A:
I had huge tif files between 1 and 3 GB and managed to finally open them with Image.open() after manually changing the value of MAX_IMAGE_PIXELS inside the Image.py source code to an arbitrarily large number:
from PIL import Image
im = np.asarray(Image.open("location/image.tif")
A:
For Python 32 bit, version 2.7 you are limited by the number of bytes you can add to the stack at a given time. One option is to read in the image in parts and then resize the individual chunks and reassemble them into a image that requires less RAM.
I recommend using the packages libtiff and opencv for that.
import os
os.environ["PATH"] += os.pathsep + "C:\\Program Files (x86)\\GnuWin32\\bin"
import numpy as np
import libtiff
import cv2
tif = libtiff.TIFF.open("HUGETIFFILE.tif", 'r')
width = tif.GetField("ImageWidth")
height = tif.GetField("ImageLength")
bits = tif.GetField('BitsPerSample')
sample_format = tif.GetField('SampleFormat')
ResizeFactor = 10 #Reduce Image Size by 10
Chunks = 8 #Read Image in 8 Chunks to prevent Memory Error (can be increased for
# bigger files)
ReadStrip = tif.ReadEncodedStrip
typ = tif.get_numpy_type(bits, sample_format)
#ReadStrip
newarr = np.zeros((1, width/ResizeFactor), typ)
for ii in range(0,Chunks):
pos = 0
arr = np.empty((height/Chunks, width), typ)
size = arr.nbytes
for strip in range((ii*tif.NumberOfStrips()/Chunks),((ii+1)*tif.NumberOfStrips()/Chunks)):
elem = ReadStrip(strip, arr.ctypes.data + pos, max(size-pos, 0))
pos = pos + elem
resized = cv2.resize(arr, (0,0), fx=float(1)/float(ResizeFactor), fy=float(1)/float(ResizeFactor))
# Now remove the large array to free up Memory for the next chunk
del arr
# Finally recombine the individual resized chunks into the final resized image.
newarr = np.vstack((newarr,resized))
newarr = np.delete(newarr, (0), axis=0)
cv2.imwrite('resized.tif', newarr)
A:
you can try to use 'dask' library:
import dask_image.imread
ds = dask_image.imread.imread('name.tif')
| How to read a big tif file in python? | I'm loading a tiff file from http://oceancolor.gsfc.nasa.gov/DOCS/DistFromCoast/
from PIL import Image
im = Image.open('GMT_intermediate_coast_distance_01d.tif')
The data is large (im.size=(36000, 18000) 1.3GB) and conventional conversion doesn't work; i.e, imarray.shape returns ()
import numpy as np
imarray=np.zeros(im.size)
imarray=np.array(im)
How can I convert this tiff file to a numpy.array?
| [
"May you dont have too much Ram for this image.You'll need at least some more than 1.3GB free memory.\nI don't know what you're doing with the image and you read the entire into your memory but i recommend you to read it bit by bit if its possible to avoid blowing up your computer. \nYou can use Image.getdata() which returns one pixel per time.\nAlso read some more for Image.open on this link : \nhttp://www.pythonware.com/library/pil/handbook/\n",
"So far I have tested many alternatives but only gdal worked always even with huge 16bit images. \nYou can open an image with something like this:\nfrom osgeo import gdal\nimport numpy as np\nds = gdal.Open(\"name.tif\")\nchannel = np.array(ds.GetRasterBand(1).ReadAsArray())\n\n",
"I had huge tif files between 1 and 3 GB and managed to finally open them with Image.open() after manually changing the value of MAX_IMAGE_PIXELS inside the Image.py source code to an arbitrarily large number:\nfrom PIL import Image\nim = np.asarray(Image.open(\"location/image.tif\")\n\n",
"For Python 32 bit, version 2.7 you are limited by the number of bytes you can add to the stack at a given time. One option is to read in the image in parts and then resize the individual chunks and reassemble them into a image that requires less RAM.\nI recommend using the packages libtiff and opencv for that.\nimport os\nos.environ[\"PATH\"] += os.pathsep + \"C:\\\\Program Files (x86)\\\\GnuWin32\\\\bin\"\nimport numpy as np\nimport libtiff\nimport cv2\n\ntif = libtiff.TIFF.open(\"HUGETIFFILE.tif\", 'r')\nwidth = tif.GetField(\"ImageWidth\")\nheight = tif.GetField(\"ImageLength\")\nbits = tif.GetField('BitsPerSample')\nsample_format = tif.GetField('SampleFormat')\n\nResizeFactor = 10 #Reduce Image Size by 10\nChunks = 8 #Read Image in 8 Chunks to prevent Memory Error (can be increased for \n# bigger files)\n\nReadStrip = tif.ReadEncodedStrip\ntyp = tif.get_numpy_type(bits, sample_format)\n\n\n#ReadStrip\nnewarr = np.zeros((1, width/ResizeFactor), typ)\nfor ii in range(0,Chunks):\n pos = 0\n arr = np.empty((height/Chunks, width), typ)\n size = arr.nbytes\n for strip in range((ii*tif.NumberOfStrips()/Chunks),((ii+1)*tif.NumberOfStrips()/Chunks)):\n elem = ReadStrip(strip, arr.ctypes.data + pos, max(size-pos, 0))\n pos = pos + elem\n\n resized = cv2.resize(arr, (0,0), fx=float(1)/float(ResizeFactor), fy=float(1)/float(ResizeFactor))\n\n # Now remove the large array to free up Memory for the next chunk\n del arr\n # Finally recombine the individual resized chunks into the final resized image.\n newarr = np.vstack((newarr,resized))\n\nnewarr = np.delete(newarr, (0), axis=0)\ncv2.imwrite('resized.tif', newarr)\n\n",
"you can try to use 'dask' library:\nimport dask_image.imread\n\nds = dask_image.imread.imread('name.tif')\n\n"
] | [
4,
3,
2,
1,
0
] | [] | [] | [
"numpy",
"python",
"python_imaging_library",
"tiff"
] | stackoverflow_0030465635_numpy_python_python_imaging_library_tiff.txt |
Q:
could not read Username for 'https://gitlab.com': No such device or address on Gitlab CI
I am trying to integrate gitlab CI on my node project, I have SSH access, but my script stop with error :
fatal: could not read Username for 'https://gitlab.com': No such device or address
debug2: channel 0: written 83 to efd 7
debug3: channel 0: will not send data after close
debug2: channel 0: obuf empty
debug2: channel 0: chan_shutdown_write (i3 o1 sock -1 wfd 6 efd 7 [write])
debug2: channel 0: output drain -> closed
debug2: channel 0: almost dead
debug2: channel 0: gc: notify user
debug2: channel 0: gc: user detached
debug2: channel 0: send close
debug3: send packet: type 97
debug2: channel 0: is dead
debug2: channel 0: garbage collecting
debug1: channel 0: free: client-session, nchannels 1
debug3: channel 0: status: The following connections are open:
#0 client-session (t4 r0 i3/0 o3/0 e[write]/0 fd -1/-1/7 sock -1 cc -1)
debug3: send packet: type 1
debug1: fd 0 clearing O_NONBLOCK
debug3: fd 1 is not O_NONBLOCK
debug1: fd 2 clearing O_NONBLOCK
Transferred: sent 3560, received 3156 bytes, in 0.7 seconds
Bytes per second: sent 5437.2, received 4820.2
debug1: Exit status 1
Cleaning up file based variables
00:01 ERROR: Job failed: exit code 1
I already tried
git config --global credential.helper store
git config --global user.password "myPassword"
git config --global user.email "myEmail"
I see that git does not offer a no interaction option...
image: node:latest with debian server
My ssh credentials and access is OK
When I test directly on the server, it still asks for my connection information
it's a private repository
A:
Try changing your repo origin on server using this command:
git remote set-url origin https://username:[email protected]/path_to_your_repo/repo.git
This way it won't ask for credentials while git pull or git push
A:
This solution worked for me from gitlab https://wahlnetwork.com/2020/08/11/using-private-git-repositories-as-terraform-modules/ . In summary I setup a token and I executed the git config command from the pipeline
| could not read Username for 'https://gitlab.com': No such device or address on Gitlab CI | I am trying to integrate gitlab CI on my node project, I have SSH access, but my script stop with error :
fatal: could not read Username for 'https://gitlab.com': No such device or address
debug2: channel 0: written 83 to efd 7
debug3: channel 0: will not send data after close
debug2: channel 0: obuf empty
debug2: channel 0: chan_shutdown_write (i3 o1 sock -1 wfd 6 efd 7 [write])
debug2: channel 0: output drain -> closed
debug2: channel 0: almost dead
debug2: channel 0: gc: notify user
debug2: channel 0: gc: user detached
debug2: channel 0: send close
debug3: send packet: type 97
debug2: channel 0: is dead
debug2: channel 0: garbage collecting
debug1: channel 0: free: client-session, nchannels 1
debug3: channel 0: status: The following connections are open:
#0 client-session (t4 r0 i3/0 o3/0 e[write]/0 fd -1/-1/7 sock -1 cc -1)
debug3: send packet: type 1
debug1: fd 0 clearing O_NONBLOCK
debug3: fd 1 is not O_NONBLOCK
debug1: fd 2 clearing O_NONBLOCK
Transferred: sent 3560, received 3156 bytes, in 0.7 seconds
Bytes per second: sent 5437.2, received 4820.2
debug1: Exit status 1
Cleaning up file based variables
00:01 ERROR: Job failed: exit code 1
I already tried
git config --global credential.helper store
git config --global user.password "myPassword"
git config --global user.email "myEmail"
I see that git does not offer a no interaction option...
image: node:latest with debian server
My ssh credentials and access is OK
When I test directly on the server, it still asks for my connection information
it's a private repository
| [
"Try changing your repo origin on server using this command:\ngit remote set-url origin https://username:[email protected]/path_to_your_repo/repo.git\n\nThis way it won't ask for credentials while git pull or git push\n",
"This solution worked for me from gitlab https://wahlnetwork.com/2020/08/11/using-private-git-repositories-as-terraform-modules/ . In summary I setup a token and I executed the git config command from the pipeline\n"
] | [
12,
0
] | [] | [] | [
"continuous_integration",
"deployment",
"git",
"gitlab_ci",
"node.js"
] | stackoverflow_0068889098_continuous_integration_deployment_git_gitlab_ci_node.js.txt |
Q:
Perform a function after passing validation
I took the script from the Bootstrap 5 documentation and incorporated it into my script.
The validation itself works. However, I don't understand how I can start a function named webShare() in the script if the validation was successful.
function onLoad() {
const forms = document.querySelectorAll('.needs-validation')
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
if (navigator.share === undefined) {
setShareButtonsEnabled(false);
if (window.location.protocol === 'http:') {
// navigator.share() is only available in secure contexts.
window.location.replace(window.location.href.replace(/^http:/, 'https:'));
} else {
logError('Error: You need to use a browser that supports this draft ' +
'proposal.');
}
}
}
window.addEventListener('load', onLoad);
The page should not be reloaded. Only the function "webShare()" must be executed.
Does anyone have a tip for me or a solution?
A:
To execute the webShare() function after successful form validation, you can add a call to webShare() at the end of the if statement that checks the form's validity. Here is an example of how you can do this:
function onLoad() {
const forms = document.querySelectorAll('.needs-validation')
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
} else {
// Call webShare() if the form is valid
webShare();
}
form.classList.add('was-validated')
}, false)
})
if (navigator.share === undefined) {
setShareButtonsEnabled(false);
if (window.location.protocol === 'http:') {
// navigator.share() is only available in secure contexts.
window.location.replace(window.location.href.replace(/^http:/, 'https:'));
} else {
logError('Error: You need to use a browser that supports this draft ' +
'proposal.');
}
}
}
window.addEventListener('load', onLoad);
Note that you need to define the webShare() function before calling it, otherwise you will get an error.
| Perform a function after passing validation | I took the script from the Bootstrap 5 documentation and incorporated it into my script.
The validation itself works. However, I don't understand how I can start a function named webShare() in the script if the validation was successful.
function onLoad() {
const forms = document.querySelectorAll('.needs-validation')
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
if (navigator.share === undefined) {
setShareButtonsEnabled(false);
if (window.location.protocol === 'http:') {
// navigator.share() is only available in secure contexts.
window.location.replace(window.location.href.replace(/^http:/, 'https:'));
} else {
logError('Error: You need to use a browser that supports this draft ' +
'proposal.');
}
}
}
window.addEventListener('load', onLoad);
The page should not be reloaded. Only the function "webShare()" must be executed.
Does anyone have a tip for me or a solution?
| [
"To execute the webShare() function after successful form validation, you can add a call to webShare() at the end of the if statement that checks the form's validity. Here is an example of how you can do this:\nfunction onLoad() {\n const forms = document.querySelectorAll('.needs-validation')\n\n Array.from(forms).forEach(form => {\n form.addEventListener('submit', event => {\n if (!form.checkValidity()) {\n event.preventDefault()\n event.stopPropagation()\n } else {\n // Call webShare() if the form is valid\n webShare();\n }\n form.classList.add('was-validated')\n }, false)\n })\n\n if (navigator.share === undefined) {\n setShareButtonsEnabled(false);\n if (window.location.protocol === 'http:') {\n // navigator.share() is only available in secure contexts.\n window.location.replace(window.location.href.replace(/^http:/, 'https:'));\n } else {\n logError('Error: You need to use a browser that supports this draft ' +\n 'proposal.');\n }\n }\n}\n\nwindow.addEventListener('load', onLoad);\n\nNote that you need to define the webShare() function before calling it, otherwise you will get an error.\n"
] | [
0
] | [] | [] | [
"bootstrap_5",
"forms",
"javascript",
"validation"
] | stackoverflow_0074672354_bootstrap_5_forms_javascript_validation.txt |
Q:
Handling Enter Key in Vue.js
I have a text field and a button.
By default, this button submits a form when someone presses the Enter key on their keyboard.
When someone is typing in the text field, I want to capture each key pressed. If the key is an @ symbol, I want to do something special.
If the key pressed is the Enter key, I want to do something special as well. The latter is the one giving me challenges. Currently, I have this Fiddle, which includes this code:
new Vue({
el: '#myApp',
data: {
emailAddress: '',
log: ''
},
methods: {
validateEmailAddress: function(e) {
if (e.keyCode === 13) {
alert('Enter was pressed');
} else if (e.keyCode === 50) {
alert('@ was pressed');
}
this.log += e.key;
},
postEmailAddress: function() {
this.log += '\n\nPosting';
}
});
In my example, I can't seem to press the Enter key without it submitting the form. Yet, I would expect the validateEmailAddress function to at least fire first so that I could capture it. But, that does not seem to be happening.
What am I doing wrong?
A:
In vue 2, You can catch enter event with v-on:keyup.enter check the documentation:
https://v2.vuejs.org/v2/guide/events.html#Key-Modifiers
I leave a very simple example:
var vm = new Vue({
el: '#app',
data: {msg: ''},
methods: {
onEnter: function() {
this.msg = 'on enter event';
}
}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<input v-on:keyup.enter="onEnter" />
<h1>{{ msg }}</h1>
</div>
Good luck
A:
Event Modifiers
You can refer to event modifiers in vuejs to prevent form submission on enter key.
It is a very common need to call event.preventDefault() or event.stopPropagation() inside event handlers.
Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.
To address this problem, Vue provides event modifiers for v-on. Recall that modifiers are directive postfixes denoted by a dot.
<form v-on:submit.prevent="<method>">
...
</form>
As the documentation states, this is syntactical sugar for e.preventDefault() and will stop the unwanted form submission on press of enter key.
Here is a working fiddle.
new Vue({
el: '#myApp',
data: {
emailAddress: '',
log: ''
},
methods: {
validateEmailAddress: function(e) {
if (e.keyCode === 13) {
alert('Enter was pressed');
} else if (e.keyCode === 50) {
alert('@ was pressed');
}
this.log += e.key;
},
postEmailAddress: function() {
this.log += '\n\nPosting';
},
noop () {
// do nothing ?
}
}
})
html, body, #editor {
margin: 0;
height: 100%;
color: #333;
}
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="myApp" style="padding:2rem; background-color:#fff;">
<form v-on:submit.prevent="noop">
<input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />
<button type="button" v-on:click="postEmailAddress" >Subscribe</button>
<br /><br />
<textarea v-model="log" rows="4"></textarea>
</form>
</div>
A:
This event works to me:
@keyup.enter.native="onEnter".
A:
For enter event handling you can use
@keyup.enter or
@keyup.13
13 is the keycode of enter. For @ key event, the keycode is 50. So you can use @keyup.50.
For example:
<input @keyup.50="atPress()" />
A:
You forget a '}' before the last line (to close the "methods {...").
This code works :
Vue.config.keyCodes.atsign = 50;
new Vue({
el: '#myApp',
data: {
emailAddress: '',
log: ''
},
methods: {
onEnterClick: function() {
alert('Enter was pressed');
},
onAtSignClick: function() {
alert('@ was pressed');
},
postEmailAddress: function() {
this.log += '\n\nPosting';
}
}
})
html, body, #editor {
margin: 0;
height: 100%;
color: #333;
}
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="myApp" style="padding:2rem; background-color:#fff;">
<input type="text" v-model="emailAddress" v-on:keyup.enter="onEnterClick" v-on:keyup.atsign="onAtSignClick" />
<button type="button" v-on:click="postEmailAddress" >Subscribe</button>
<br /><br />
<textarea v-model="log" rows="4"></textarea>
</div>
A:
You can also pass events down into child components with something like this:
<CustomComponent
@keyup.enter="handleKeyUp"
/>
...
<template>
<div>
<input
type="text"
v-on="$listeners"
>
</div>
</template>
<script>
export default {
name: 'CustomComponent',
mounted() {
console.log('listeners', this.$listeners)
},
}
</script>
That works well if you have a pass-through component and want the listeners to go onto a specific element.
A:
you are missing a closing curly bracket for methods
new Vue({
el: '#myApp',
data: {
emailAddress: '',
log: ''
},
methods: {
validateEmailAddress: function(e) {
if (e.keyCode === 13) {
alert('Enter was pressed');
} else if (e.keyCode === 50) {
alert('@ was pressed');
}
this.log += e.key;
},
postEmailAddress: function() {
this.log += '\n\nPosting';
}
}//add this closing bracket and everything is fine
});
A:
This is how you would write it in Vue3 with Composition API.
<script setup>
function callOnEnter() {
console.log("Enter key pressed");
}
</script>
<template>
<input type="text" @keyup.enter="callOnEnter" />
</template>
More details are available here: https://vuejs.org/guide/essentials/event-handling.html#key-modifiers
| Handling Enter Key in Vue.js | I have a text field and a button.
By default, this button submits a form when someone presses the Enter key on their keyboard.
When someone is typing in the text field, I want to capture each key pressed. If the key is an @ symbol, I want to do something special.
If the key pressed is the Enter key, I want to do something special as well. The latter is the one giving me challenges. Currently, I have this Fiddle, which includes this code:
new Vue({
el: '#myApp',
data: {
emailAddress: '',
log: ''
},
methods: {
validateEmailAddress: function(e) {
if (e.keyCode === 13) {
alert('Enter was pressed');
} else if (e.keyCode === 50) {
alert('@ was pressed');
}
this.log += e.key;
},
postEmailAddress: function() {
this.log += '\n\nPosting';
}
});
In my example, I can't seem to press the Enter key without it submitting the form. Yet, I would expect the validateEmailAddress function to at least fire first so that I could capture it. But, that does not seem to be happening.
What am I doing wrong?
| [
"In vue 2, You can catch enter event with v-on:keyup.enter check the documentation:\n\nhttps://v2.vuejs.org/v2/guide/events.html#Key-Modifiers\n\nI leave a very simple example:\n\n\nvar vm = new Vue({\n el: '#app',\n data: {msg: ''},\n methods: {\n onEnter: function() {\n this.msg = 'on enter event';\n }\n }\n});\n<script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js\"></script>\n\n<div id=\"app\">\n <input v-on:keyup.enter=\"onEnter\" />\n <h1>{{ msg }}</h1>\n</div>\n\n\n\nGood luck\n",
"Event Modifiers\nYou can refer to event modifiers in vuejs to prevent form submission on enter key.\n\nIt is a very common need to call event.preventDefault() or event.stopPropagation() inside event handlers.\n\n\nAlthough we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.\n\n\nTo address this problem, Vue provides event modifiers for v-on. Recall that modifiers are directive postfixes denoted by a dot.\n\n<form v-on:submit.prevent=\"<method>\">\n ...\n</form>\n\nAs the documentation states, this is syntactical sugar for e.preventDefault() and will stop the unwanted form submission on press of enter key.\nHere is a working fiddle.\n\n\nnew Vue({\n el: '#myApp',\n data: {\n emailAddress: '',\n log: ''\n },\n methods: {\n validateEmailAddress: function(e) {\n if (e.keyCode === 13) {\n alert('Enter was pressed');\n } else if (e.keyCode === 50) {\n alert('@ was pressed');\n } \n this.log += e.key;\n },\n \n postEmailAddress: function() {\n this.log += '\\n\\nPosting';\n },\n noop () {\n // do nothing ?\n }\n }\n})\nhtml, body, #editor {\n margin: 0;\n height: 100%;\n color: #333;\n}\n<script src=\"https://unpkg.com/[email protected]/dist/vue.js\"></script>\n<div id=\"myApp\" style=\"padding:2rem; background-color:#fff;\">\n<form v-on:submit.prevent=\"noop\">\n <input type=\"text\" v-model=\"emailAddress\" v-on:keyup=\"validateEmailAddress\" />\n <button type=\"button\" v-on:click=\"postEmailAddress\" >Subscribe</button> \n <br /><br />\n \n <textarea v-model=\"log\" rows=\"4\"></textarea> \n</form>\n</div>\n\n\n\n",
"This event works to me:\[email protected]=\"onEnter\".\n\n",
"For enter event handling you can use\n\[email protected] or\[email protected]\n\n13 is the keycode of enter. For @ key event, the keycode is 50. So you can use @keyup.50.\nFor example:\n<input @keyup.50=\"atPress()\" />\n\n",
"You forget a '}' before the last line (to close the \"methods {...\").\nThis code works :\n\n\nVue.config.keyCodes.atsign = 50;\r\n\r\nnew Vue({\r\n el: '#myApp',\r\n data: {\r\n emailAddress: '',\r\n log: ''\r\n },\r\n methods: {\r\n \r\n onEnterClick: function() {\r\n alert('Enter was pressed');\r\n },\r\n \r\n onAtSignClick: function() {\r\n alert('@ was pressed');\r\n },\r\n \r\n postEmailAddress: function() {\r\n this.log += '\\n\\nPosting';\r\n }\r\n }\r\n})\nhtml, body, #editor {\r\n margin: 0;\r\n height: 100%;\r\n color: #333;\r\n}\n<script src=\"https://vuejs.org/js/vue.min.js\"></script>\r\n\r\n<div id=\"myApp\" style=\"padding:2rem; background-color:#fff;\">\r\n\r\n <input type=\"text\" v-model=\"emailAddress\" v-on:keyup.enter=\"onEnterClick\" v-on:keyup.atsign=\"onAtSignClick\" />\r\n \r\n <button type=\"button\" v-on:click=\"postEmailAddress\" >Subscribe</button> \r\n <br /><br />\r\n \r\n <textarea v-model=\"log\" rows=\"4\"></textarea>\r\n</div>\n\n\n\n",
"You can also pass events down into child components with something like this:\n<CustomComponent\n @keyup.enter=\"handleKeyUp\"\n/>\n\n...\n<template>\n <div>\n <input\n type=\"text\"\n v-on=\"$listeners\"\n >\n </div>\n</template>\n\n<script>\nexport default {\n name: 'CustomComponent',\n\n mounted() {\n console.log('listeners', this.$listeners)\n },\n}\n</script>\n\nThat works well if you have a pass-through component and want the listeners to go onto a specific element.\n",
"you are missing a closing curly bracket for methods\nnew Vue({\n el: '#myApp',\n data: {\n emailAddress: '',\n log: ''\n },\n methods: {\n validateEmailAddress: function(e) {\n if (e.keyCode === 13) {\n alert('Enter was pressed');\n } else if (e.keyCode === 50) {\n alert('@ was pressed');\n } \n this.log += e.key;\n },\n\n postEmailAddress: function() {\n this.log += '\\n\\nPosting';\n }\n }//add this closing bracket and everything is fine\n});\n\n",
"This is how you would write it in Vue3 with Composition API.\n<script setup>\nfunction callOnEnter() {\n console.log(\"Enter key pressed\");\n}\n</script>\n\n<template>\n <input type=\"text\" @keyup.enter=\"callOnEnter\" />\n</template>\n\nMore details are available here: https://vuejs.org/guide/essentials/event-handling.html#key-modifiers\n"
] | [
232,
78,
35,
34,
23,
16,
1,
0
] | [] | [] | [
"javascript",
"vue.js"
] | stackoverflow_0042951967_javascript_vue.js.txt |
Q:
Playing a local video in a SpriteKit scene
Working on taking around 23 ".mov" files - short animations - that will piece together to make a children's book, with a choose-your-own-adventure style to it.
I feel like I have a decent grasp on what needs to be done on a macro sense, present the video in a scene, once the video finishes create x number of buttons that will launch the user into the next chapter/scene. Furtherdown the road will add some simple animations and music/sound as well.
However, I am having some issues with playing the videos, I was successful in creating a scene with a screenshot as the background which had a button to launch the next scene, but for adding the video, I am both lost and having a hard time finding resources on the topic.
Apple Dev's solution is to use:
let sample = SKVideoNode(fileNamed: "sample.mov")
sample.position = CGPoint(x: frame.midX,
y: frame.midY)
addChild(sample)
sample.play()
I tried this, albeit probably improperly, in my GameScene.swift file.
import SpriteKit
import GameplayKit
class GameScene: SKScene {
private var label : SKVideoNode?
override func didMove(to view: SKView) {
let sample = SKVideoNode(fileNamed: "V1.mov")
sample.position = CGPoint(x: frame.midX,
y: frame.midY)
addChild(sample)
sample.play()
}
}
I was hoping this would be - and who knows, maybe it still is, my golden egg of a solution, cause then the rest would really be just a copy and paste session with multiple scenes, but I was not able to get the video to load.
Do I need to further connect the SKVideoNode to the "V1.mov" file?
Furthermore, I think some of my confusion stems from whether or not I implement the video programatically or through the .sks / storyboard files, is one easier than the other?
Also am aware that this question may be more-so to do with something very rudimentary that I've brushed over in my learning process, and if that is the case, I apologize for my over zealousness :p
Appreciate any advice you folks can give would be greatly appreciated:)
UPDATE:
Okay, so here is the code I have so far which works, it is the skeleton framework for the book I am making, it's a choose your own adventure, so each scene has multiple options to take you to other scenes:
import SpriteKit
import Foundation
import SceneKit
class v1Scene: SKScene {
var trashButtonNode:SKSpriteNode!
var bikeButtonNode:SKSpriteNode!
var backButtonNode:SKSpriteNode!
override func didMove(to view: SKView) {
trashButtonNode = (self.childNode(withName: "trashButton") as? SKSpriteNode)
bikeButtonNode = (self.childNode(withName: "bikeButton") as? SKSpriteNode)
backButtonNode = (self.childNode(withName: "backButton") as? SKSpriteNode)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let v2Scene = v2Scene(fileNamed: "v2Scene")
let v3Scene = v3Scene(fileNamed: "v3Scene")
let MainMenu = MainMenu(fileNamed: "MainMenu")
if let location = touch?.location(in: self) {
let nodesArray = self.nodes(at: location)
if nodesArray.first?.name == "trashButton" {
let transistion = SKTransition.fade(withDuration: 2)
self.view?.presentScene(v2Scene!, transition: transistion)
} else if nodesArray.first?.name == "bikeButton" {
let transistion = SKTransition.fade(withDuration: 2)
self.view?.presentScene(v3Scene!, transition: transistion)
} else if nodesArray.first?.name == "backButton" {
let transistion = SKTransition.fade(withDuration: 2)
self.view?.presentScene(MainMenu!, transition: transistion)
}
}
}
}
What I am trying to achieve is that when the "trashButton" is clicked, v2Scene is launched and a video automatically plays. Each video is a "page" in a book, so need to assign each video to a scene.
The files are in a folder in my project and the Assets.xcasstes folder, although, the .mov files do not seem to work in that folder.
Thanks,
Owen
A:
Because the video files are in their own folder, you won't be able to use the SKVideoNode init that takes a file name. You must use the init that takes a URL as an argument.
To get the URL for a video file, you must call the Bundle class's url function, supplying the file name, extension, and the name of the path to the folder where your video files are.
The following code shows what you need to do to create a video node from a file in the app bundle, using the V1.mov file from your question as the example:
let bundle = Bundle.main
if let videoURL = bundle.url(forResource: "V1",
withExtension: "mov",
subdirectory "FolderName" {
sample = SKVideoNode(url: videoURL)
}
FolderName is the folder where the video files are.
Make sure the folder with the video files is in the app target's Copy Bundle Resources build phase. The folder must be in this build phase for Xcode to copy it to the app bundle when it builds the project. Take the following steps to view the build phases for a target:
Open the project editor by selecting the project file on the left side of the project window.
Select the target on the left side of the project editor.
Click the Build Phases button at the top of the project editor.
| Playing a local video in a SpriteKit scene | Working on taking around 23 ".mov" files - short animations - that will piece together to make a children's book, with a choose-your-own-adventure style to it.
I feel like I have a decent grasp on what needs to be done on a macro sense, present the video in a scene, once the video finishes create x number of buttons that will launch the user into the next chapter/scene. Furtherdown the road will add some simple animations and music/sound as well.
However, I am having some issues with playing the videos, I was successful in creating a scene with a screenshot as the background which had a button to launch the next scene, but for adding the video, I am both lost and having a hard time finding resources on the topic.
Apple Dev's solution is to use:
let sample = SKVideoNode(fileNamed: "sample.mov")
sample.position = CGPoint(x: frame.midX,
y: frame.midY)
addChild(sample)
sample.play()
I tried this, albeit probably improperly, in my GameScene.swift file.
import SpriteKit
import GameplayKit
class GameScene: SKScene {
private var label : SKVideoNode?
override func didMove(to view: SKView) {
let sample = SKVideoNode(fileNamed: "V1.mov")
sample.position = CGPoint(x: frame.midX,
y: frame.midY)
addChild(sample)
sample.play()
}
}
I was hoping this would be - and who knows, maybe it still is, my golden egg of a solution, cause then the rest would really be just a copy and paste session with multiple scenes, but I was not able to get the video to load.
Do I need to further connect the SKVideoNode to the "V1.mov" file?
Furthermore, I think some of my confusion stems from whether or not I implement the video programatically or through the .sks / storyboard files, is one easier than the other?
Also am aware that this question may be more-so to do with something very rudimentary that I've brushed over in my learning process, and if that is the case, I apologize for my over zealousness :p
Appreciate any advice you folks can give would be greatly appreciated:)
UPDATE:
Okay, so here is the code I have so far which works, it is the skeleton framework for the book I am making, it's a choose your own adventure, so each scene has multiple options to take you to other scenes:
import SpriteKit
import Foundation
import SceneKit
class v1Scene: SKScene {
var trashButtonNode:SKSpriteNode!
var bikeButtonNode:SKSpriteNode!
var backButtonNode:SKSpriteNode!
override func didMove(to view: SKView) {
trashButtonNode = (self.childNode(withName: "trashButton") as? SKSpriteNode)
bikeButtonNode = (self.childNode(withName: "bikeButton") as? SKSpriteNode)
backButtonNode = (self.childNode(withName: "backButton") as? SKSpriteNode)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let v2Scene = v2Scene(fileNamed: "v2Scene")
let v3Scene = v3Scene(fileNamed: "v3Scene")
let MainMenu = MainMenu(fileNamed: "MainMenu")
if let location = touch?.location(in: self) {
let nodesArray = self.nodes(at: location)
if nodesArray.first?.name == "trashButton" {
let transistion = SKTransition.fade(withDuration: 2)
self.view?.presentScene(v2Scene!, transition: transistion)
} else if nodesArray.first?.name == "bikeButton" {
let transistion = SKTransition.fade(withDuration: 2)
self.view?.presentScene(v3Scene!, transition: transistion)
} else if nodesArray.first?.name == "backButton" {
let transistion = SKTransition.fade(withDuration: 2)
self.view?.presentScene(MainMenu!, transition: transistion)
}
}
}
}
What I am trying to achieve is that when the "trashButton" is clicked, v2Scene is launched and a video automatically plays. Each video is a "page" in a book, so need to assign each video to a scene.
The files are in a folder in my project and the Assets.xcasstes folder, although, the .mov files do not seem to work in that folder.
Thanks,
Owen
| [
"Because the video files are in their own folder, you won't be able to use the SKVideoNode init that takes a file name. You must use the init that takes a URL as an argument.\nTo get the URL for a video file, you must call the Bundle class's url function, supplying the file name, extension, and the name of the path to the folder where your video files are.\nThe following code shows what you need to do to create a video node from a file in the app bundle, using the V1.mov file from your question as the example:\nlet bundle = Bundle.main\nif let videoURL = bundle.url(forResource: \"V1\", \n withExtension: \"mov\", \n subdirectory \"FolderName\" {\n\n sample = SKVideoNode(url: videoURL)\n}\n\nFolderName is the folder where the video files are.\nMake sure the folder with the video files is in the app target's Copy Bundle Resources build phase. The folder must be in this build phase for Xcode to copy it to the app bundle when it builds the project. Take the following steps to view the build phases for a target:\n\nOpen the project editor by selecting the project file on the left side of the project window.\nSelect the target on the left side of the project editor.\nClick the Build Phases button at the top of the project editor.\n\n"
] | [
0
] | [] | [] | [
"skvideonode",
"sprite_kit",
"swift"
] | stackoverflow_0074644107_skvideonode_sprite_kit_swift.txt |
Q:
Conditional event binding - vuejs
In my scenario I have mouseover and mouseout events that I want to bind to conditionally (e.g only if user is on a device that has a mouse).
I realize I can have the condition in the event handler itself but that would still be allocating the memory for the event handlers which is unnecessary.
Is there a way to make the event binding itself conditional?
(to be clear, what I'd like is to be able to short-circuit the event subscription so the underlying addEventListener operation never happens if the condition is false)
A:
Update (February 2021)
Several solutions seem to be accepted on Github, whereas my original answer is not. I'm rounding them up here for convenience:
Solution 1a (see Engin Yapici's answer below):
v-on="enableClick ? { click: clickHandler } : {}"
Solution 1b (see Heals Legodi's answer below):
v-on="enableClick ? { click: () => clickHandler(params) } : {}"
Solution 2a (see rvy's answer below and this working demo)
@[eventName]="clickHandler"
Solution 2b (from coyotte508's comment; 2a without the computed property):
@[isClickable&&`click`]="clickHandler"
Solution 3 (mentioned here; seems to be compatible with event modifiers):
@click="enableClick && clickHandler"
Original answer
This works as of Vue 2.6:
<div
@mouseover="enableMouseover ? mouseoverHandler : null"
@click="enableClick ? clickHandler : null"
...
>
While an event resolves to null, the binding will be removed.
https://github.com/vuejs/vue/issues/7349#issuecomment-458405684
Comments on original answer
It seems to be something I came up with accidentally by misunderstanding that Github thread. But I know from my own testing that it definitely worked back when I posted it. And people continued to upvote it right up to when I made this edit, implying the solution still had some merit. So give it a try if you like.
But after a downvote and a couple of negative comments, I felt the need to improve my answer to save future readers potential headaches. Note that pretty much all the answers to this question refer to the same Github thread, so if you've got time, you might want to go right to the source to learn more. There are many options discussed there, and I suspect more will continue to be posted over time.
A:
Following this discussion it appears the best way to achieve this is to bind v-on to a specification object containing the events you are interested in subscribing to and place your conditionals there like so:
<div v-on="{ mouseover: condition ? handler : null, click: ... }">
Some notes:
Passing null for a handler means the underlying addEventLisetener
will not happen - which is what we want
This means grouping all the event subscriptions into one v-on
attribute rather then splitting it into separate and explicit
bindings (<div @mouseover='...' @click='...'/>)
If this is a long living component and the underlying data changes
frequently (leading to rebinding) you should be paying attention
to the disposal of the subscriptions (i.e the corresponding removeEventListener) as subscriptions made in one bind pass
will not be disposed of on subsequent ones. Evaluate as per your
use case...
A:
This is what I'm using:
v-on="condition ? { click: handler } : {}" (Reference)
I get Invalid handler for event "click": got null with v-on="{ click: condition ? handler : null }"
A:
If you get the 'Invalid handler for event "click": got null' error and your handler function expects some parameters then you should wrap your handler in a function.
So this >
v-on="condition ? { blur: () => handler(params) } : {}"
Instead of
v-on="condition ? { click: handler(params) } : {}"
A:
Even more simpler would be to use render functions for that. You won't need to be manually removing the listeners and taking care of them. Also uses simple JS syntax with no mixins.
new Vue({
el: "#app",
data: () => ({
counter: 0
}),
methods: {
handleClick() {
this.counter++;
}
},
render(h) {
return h(
"div",
IS_MOBILE_DEVICE
? {}
: {
on: { click: this.handleClick }
},
this.counter
);
}
});
Full example: https://codesandbox.io/s/nw6vyo6knj
A:
If you want to do something like that you could just apply the event listener manually by adding a ref on the element you want to apply the event to, then using that to bind the event listener in the mounted hook if the condition is met:
Markup
<button ref="button">
Mouse Over Me
</button>
Vue Instance
new Vue({
el: '#app',
mounted() {
let hasMouse = true;
// If the user has a mouse, add the event listeners
if (hasMouse) {
let button = this.$refs.button
button.addEventListener('mouseover', e => {
this.mouseover = true
})
button.addEventListener('mouseout', e => {
this.mouseover = false
})
}
},
data: {
mouseover: false
}
})
Here's a JSFiddle for that: https://jsfiddle.net/0fderek6/
If you don't like that approach, you could also use a directive and place the conditional in there, you could then place that in a mixin to make it reusable:
Mixin
const mouseEvents = {
directives: {
mouseEvents: {
bind(el, binding, vnode) {
let hasMouse = true;
if (hasMouse) {
el.addEventListener('mouseover', e => {
vnode.context.mouseover = true
})
el.addEventListener('mouseout', e => {
vnode.context.mouseover = false
})
}
}
}
},
data: {
mouseover: false
}
}
Vue Instance
new Vue({
el: '#app',
mixins: [mouseEvents]
})
Markup
<button v-mouse-events>
Mouse Over Me
</button>
Here's the JSFiddle for that: https://jsfiddle.net/nq6x5qeq/
EDIT
If you like the directive approach, all you need to do is add an unbind hook to remove the listener, you can then have the binding arg be the event type and the binding value be the handler:
Vue.directive('mouse', {
bind(el, binding) {
if (hasMouse) {
console.log(binding.arg + ' added')
// bind the event listener to the element
el.addEventListener(binding.arg, binding.value)
}
},
unbind(el, binding) {
if (hasMouse) {
console.log(binding.arg + ' removed')
el.removeEventListener(binding.arg, binding.value)
}
}
});
Now all you need to do is add each listener exactly like you would with v-bind:
<div v-mouse:mouseover="mouseOverFunction"></div>
Here's the JSFiddle to show you how that works: https://jsfiddle.net/59ym6hdb/
A:
If you need to use a .stop modifier, then none of the listed solutions will work. But it is actually easy, just implement whatever the modifier does in the event handler itself.
In the template: @click="clickHandler" (yes, always attached!)
Then for your handler:
function clickHandler(event) {
if (whateverCondition) {
event.stopPropagation()
…
}
}
A:
Refer to this by Evan You
<div v-on="{ mouseover: condition ? handler : null }">
should work and be clean.
A:
I needed to conditionally bind multiple events so I managed by doing this:
v-on="isEnabled ? {mouseenter:open, mouseleave:close, touchend:toggle} : null"
A:
Conditional event binding works as follows:
<div @[event]="handler" />
While event resolves to null, the binding will be removed.
(directly from https://github.com/vuejs/vue/issues/7349#issuecomment-458405684 )
Example:
<template>
...
<span @[mayclick]="onClick">...</span>
...
</template>
<script>
export default {
...
computed: {
mayclick: function() {
return this.isClickable ? "click" : null;
}
},
methods: {
onClick: function (message) {
...
}
}
}
A:
I am unable to comment on answers so I am adding my own.
Solution 3 from the approved answer does not work - parentheses are missing.
The correct syntax in this case would be:
@click="enableClick && clickHandler()"
Here is working example
A:
None of the above solutions work, when you want to make the handler dependent on a condition, that uses props passed to the slot by the child.
In that case the below syntax can be used:
:[enableClick?`onClick`:``]="clickHandler"
where enableClick is a prop received from the children as described here:
https://vuejs.org/guide/components/slots.html#scoped-slots
and onClick is the event name (click) prefixed with on in camelCase
e.g.:
<MyComponent v-slot="{ enableClick }">
<OtherComponent :[enableClick?`onClick`:``]="clickHandler" />
</MyComponent>
and inside MyComponent template:
<div>
<slot :enableClick="isClickEnabled()"></slot>
</div>
| Conditional event binding - vuejs | In my scenario I have mouseover and mouseout events that I want to bind to conditionally (e.g only if user is on a device that has a mouse).
I realize I can have the condition in the event handler itself but that would still be allocating the memory for the event handlers which is unnecessary.
Is there a way to make the event binding itself conditional?
(to be clear, what I'd like is to be able to short-circuit the event subscription so the underlying addEventListener operation never happens if the condition is false)
| [
"Update (February 2021)\nSeveral solutions seem to be accepted on Github, whereas my original answer is not. I'm rounding them up here for convenience:\nSolution 1a (see Engin Yapici's answer below):\nv-on=\"enableClick ? { click: clickHandler } : {}\"\n\nSolution 1b (see Heals Legodi's answer below):\nv-on=\"enableClick ? { click: () => clickHandler(params) } : {}\"\n\nSolution 2a (see rvy's answer below and this working demo)\n@[eventName]=\"clickHandler\"\n\nSolution 2b (from coyotte508's comment; 2a without the computed property):\n@[isClickable&&`click`]=\"clickHandler\"\n\nSolution 3 (mentioned here; seems to be compatible with event modifiers):\n@click=\"enableClick && clickHandler\"\n\nOriginal answer\n\nThis works as of Vue 2.6:\n<div\n @mouseover=\"enableMouseover ? mouseoverHandler : null\"\n @click=\"enableClick ? clickHandler : null\"\n ...\n>\n\n\nWhile an event resolves to null, the binding will be removed.\n\nhttps://github.com/vuejs/vue/issues/7349#issuecomment-458405684\n\nComments on original answer\nIt seems to be something I came up with accidentally by misunderstanding that Github thread. But I know from my own testing that it definitely worked back when I posted it. And people continued to upvote it right up to when I made this edit, implying the solution still had some merit. So give it a try if you like.\nBut after a downvote and a couple of negative comments, I felt the need to improve my answer to save future readers potential headaches. Note that pretty much all the answers to this question refer to the same Github thread, so if you've got time, you might want to go right to the source to learn more. There are many options discussed there, and I suspect more will continue to be posted over time.\n",
"Following this discussion it appears the best way to achieve this is to bind v-on to a specification object containing the events you are interested in subscribing to and place your conditionals there like so:\n<div v-on=\"{ mouseover: condition ? handler : null, click: ... }\">\nSome notes:\n\nPassing null for a handler means the underlying addEventLisetener\nwill not happen - which is what we want\nThis means grouping all the event subscriptions into one v-on\nattribute rather then splitting it into separate and explicit\nbindings (<div @mouseover='...' @click='...'/>)\nIf this is a long living component and the underlying data changes\nfrequently (leading to rebinding) you should be paying attention\nto the disposal of the subscriptions (i.e the corresponding removeEventListener) as subscriptions made in one bind pass\nwill not be disposed of on subsequent ones. Evaluate as per your\nuse case...\n\n",
"This is what I'm using: \nv-on=\"condition ? { click: handler } : {}\" (Reference)\nI get Invalid handler for event \"click\": got null with v-on=\"{ click: condition ? handler : null }\"\n",
"If you get the 'Invalid handler for event \"click\": got null' error and your handler function expects some parameters then you should wrap your handler in a function.\nSo this >\nv-on=\"condition ? { blur: () => handler(params) } : {}\"\n\nInstead of\nv-on=\"condition ? { click: handler(params) } : {}\"\n\n",
"Even more simpler would be to use render functions for that. You won't need to be manually removing the listeners and taking care of them. Also uses simple JS syntax with no mixins.\nnew Vue({\n el: \"#app\",\n data: () => ({\n counter: 0\n }),\n methods: {\n handleClick() {\n this.counter++;\n }\n },\n render(h) {\n return h(\n \"div\",\n IS_MOBILE_DEVICE\n ? {}\n : {\n on: { click: this.handleClick }\n },\n this.counter\n );\n }\n});\n\nFull example: https://codesandbox.io/s/nw6vyo6knj\n",
"If you want to do something like that you could just apply the event listener manually by adding a ref on the element you want to apply the event to, then using that to bind the event listener in the mounted hook if the condition is met:\nMarkup\n<button ref=\"button\">\n Mouse Over Me\n</button>\n\nVue Instance\nnew Vue({\n el: '#app',\n mounted() {\n let hasMouse = true;\n\n // If the user has a mouse, add the event listeners\n if (hasMouse) {\n let button = this.$refs.button\n\n button.addEventListener('mouseover', e => {\n this.mouseover = true\n })\n\n button.addEventListener('mouseout', e => {\n this.mouseover = false\n })\n }\n\n },\n data: {\n mouseover: false\n }\n})\n\nHere's a JSFiddle for that: https://jsfiddle.net/0fderek6/\nIf you don't like that approach, you could also use a directive and place the conditional in there, you could then place that in a mixin to make it reusable:\nMixin\nconst mouseEvents = {\n directives: {\n mouseEvents: {\n bind(el, binding, vnode) {\n let hasMouse = true;\n\n if (hasMouse) {\n el.addEventListener('mouseover', e => {\n vnode.context.mouseover = true\n })\n\n el.addEventListener('mouseout', e => {\n vnode.context.mouseover = false\n })\n }\n }\n }\n },\n data: {\n mouseover: false\n }\n}\n\nVue Instance\nnew Vue({\n el: '#app',\n mixins: [mouseEvents]\n})\n\nMarkup\n<button v-mouse-events>\n Mouse Over Me\n</button>\n\nHere's the JSFiddle for that: https://jsfiddle.net/nq6x5qeq/\nEDIT\nIf you like the directive approach, all you need to do is add an unbind hook to remove the listener, you can then have the binding arg be the event type and the binding value be the handler:\nVue.directive('mouse', {\n bind(el, binding) {\n if (hasMouse) {\n console.log(binding.arg + ' added')\n // bind the event listener to the element\n el.addEventListener(binding.arg, binding.value)\n }\n },\n unbind(el, binding) {\n if (hasMouse) {\n console.log(binding.arg + ' removed')\n el.removeEventListener(binding.arg, binding.value)\n }\n }\n});\n\nNow all you need to do is add each listener exactly like you would with v-bind:\n<div v-mouse:mouseover=\"mouseOverFunction\"></div>\n\nHere's the JSFiddle to show you how that works: https://jsfiddle.net/59ym6hdb/\n",
"If you need to use a .stop modifier, then none of the listed solutions will work. But it is actually easy, just implement whatever the modifier does in the event handler itself.\nIn the template: @click=\"clickHandler\" (yes, always attached!)\nThen for your handler:\nfunction clickHandler(event) {\n if (whateverCondition) {\n event.stopPropagation()\n …\n }\n}\n\n",
"Refer to this by Evan You\n<div v-on=\"{ mouseover: condition ? handler : null }\">\n\nshould work and be clean.\n",
"I needed to conditionally bind multiple events so I managed by doing this:\nv-on=\"isEnabled ? {mouseenter:open, mouseleave:close, touchend:toggle} : null\"\n",
"Conditional event binding works as follows:\n<div @[event]=\"handler\" />\n\nWhile event resolves to null, the binding will be removed.\n(directly from https://github.com/vuejs/vue/issues/7349#issuecomment-458405684 )\nExample:\n<template>\n ...\n <span @[mayclick]=\"onClick\">...</span>\n ...\n</template>\n\n<script>\nexport default {\n ...\n computed: {\n mayclick: function() {\n return this.isClickable ? \"click\" : null;\n }\n },\n methods: {\n onClick: function (message) {\n ...\n }\n }\n}\n\n",
"I am unable to comment on answers so I am adding my own.\nSolution 3 from the approved answer does not work - parentheses are missing.\nThe correct syntax in this case would be:\n@click=\"enableClick && clickHandler()\"\n\nHere is working example\n",
"None of the above solutions work, when you want to make the handler dependent on a condition, that uses props passed to the slot by the child.\nIn that case the below syntax can be used:\n:[enableClick?`onClick`:``]=\"clickHandler\"\n\nwhere enableClick is a prop received from the children as described here:\nhttps://vuejs.org/guide/components/slots.html#scoped-slots\nand onClick is the event name (click) prefixed with on in camelCase\ne.g.:\n<MyComponent v-slot=\"{ enableClick }\">\n <OtherComponent :[enableClick?`onClick`:``]=\"clickHandler\" />\n</MyComponent>\n\nand inside MyComponent template:\n<div>\n <slot :enableClick=\"isClickEnabled()\"></slot>\n</div>\n\n"
] | [
104,
29,
21,
7,
5,
3,
3,
2,
2,
1,
0,
0
] | [] | [] | [
"events",
"vue.js"
] | stackoverflow_0048042274_events_vue.js.txt |
Q:
Is there a React way of updating a loading state with every iteration of a map loop?
I have a component that calls a method which in the background computes a heavy calculation with a map function (not fetching anything), and I'm looking to insert a callback function in there to update the DOM with the loading percentage of the computation with every iteration of the map function.
Basically, I'm trying to update the DOM with the loadingPercentage variable in the following code. Console.log statement outputs the correct percentages.
`
useEffect(() => {
const frames: AnimationFrame[] = getAnimationFrames(
(loadingPercentage: number) => {
console.log(loadingPercentage);
// Here's the part I'm trying to insert something to update the DOM
}
);
setFrames(frames.map((frame) => frame.analysis));
setBoards(frames.map((frame) => frame.board));
}, []);
`
I'm trying to get the percentage on the DOM as follows:
<div>{loadingPercentage}</div>
//Not updating at all...
In case it could be useful, the heavy computation I mentioned in this case is getAnimationFrames() which is located in a non-react typescript file as such:
export const getAnimationFrames = (
loading?: Function,
pgn: string = defaultPgn
) => {
const history = getHistoryFromPgn(pgn);
const totalMoves = history.length;
let loadingPercentage = 0;
let moveNo = 0;
const animationFrames: AnimationFrame[] = history.map((move) => {
const animationFrame = getAnimationFrame(move);
moveNo++;
loadingPercentage = (moveNo * 100) / totalMoves;
if (loading) {
**loading(loadingPercentage);**
}
return animationFrame;
});
return animationFrames;
};
What I tried:
Making a state variable like const [loadingPercentage, setLoadingPercentage] = useState(0) and add it as a dependency to the useEffect hook but the getAnimationFrames function must be called only once so that didn't make a lot of sense.
Removing the getAnimationFrames function, and instead of using a loop I tried to get useEffect to behave like a loop by adding getAnimationFrame in the useEffect function to push the frames to an array with each component load, with the loadingPercentage as a dependency of useEffect. This seemed like it almost worked but eventually it started giving too many renders error.
Tried const loadingPercentage = useRef(0);, and updated loadingPercentage.current with loadingPercentage value at every iteration. This did not update the DOM as expected.
Tried abandoning React all together and did document.getElementById('loadingDiv').innerText = loadingPercentage. Seems like this is very easy to do with Vanilla JS, but cannot get it to work in React.
Let me know if you have any ideas.
Thank you!
A:
You can model your state to incorperate loadingPercentage and pass setState into getAnimationFrames function:
type FrameState = { animationFrames: AnimationFrame[], loadingPercentage: number };
const [frames, setFrames] = useState<FrameState>({ animationFrames: [], loadingPercentage: 0 })
useEffect(() => {
heavyComputation(frames, setFrames)
}, []);
function heavyComputation(frames, setFrames) {
for (let index = 0; index < 100; index++) {
if(100 % index) {
setFrames({...frames, loadingPercentage: index})
}
}
}
setState will update loadingPercentage, and in the dom, you can reflect that update.
Just an idea, see if it suits your implementation.
A:
import { useState, useEffect } from 'react';
import { getAnimationFrame, getHistoryFromPgn } from './chess/chessApi';
const defaultPgn =
'1. Nf3 Nf6 2. c4 g6 3. Nc3 Bg7 4. d4 O-O 5. Bf4 d5 6. Qb3 dxc4 7. Qxc4 c6 8. e4 Nbd7 9. Rd1 Nb6 10. Qc5 Bg4 11. Bg5 Na4 12. Qa3 Nxc3 13. bxc3 Nxe4 14. Bxe7 Qb6 15. Bc4 Nxc3 16. Bc5 Rfe8+ 17. Kf1 Be6 18. Bxb6 Bxc4+ 19. Kg1 Ne2+ 20. Kf1 Nxd4+ 21. Kg1 Ne2+ 22. Kf1 Nc3+ 23. Kg1 axb6 24. Qb4 Ra4 25. Qxb6 Nxd1 26. h3 Rxa2 27. Kh2 Nxf2 28. Re1 Rxe1 29. Qd8+ Bf8 30. Nxe1 Bd5 31. Nf3 Ne4 32. Qb8 b5 33. h4 h5 34. Ne5 Kg7 35. Kg1 Bc5+ 36. Kf1 Ng3+ 37. Ke1 Bb4+ 38. Kd1 Bb3+ 39. Kc1 Ne2+ 40. Kb1 Nc3+ 41. Kc1 Rc2# 0-1';
const history = getHistoryFromPgn(defaultPgn);
export default function App() {
const [state, setState] = useState(0);
useEffect(() => {
heavyComputation();
}, []);
const sleep = (milliseconds: number) => {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
};
async function heavyComputation() {
for (let index = 0; index < history.length; index++) {
getAnimationFrame(history[index]);
await sleep(0);
setState(index);
}
}
return <div className='App'>{state}</div>;
Putting an await sleep(0) between the loop ticks has worked out, from this point it will be easy to compute a loadingPercentage and update the DOM with it.
Thank you Enfield li for the answer!
| Is there a React way of updating a loading state with every iteration of a map loop? | I have a component that calls a method which in the background computes a heavy calculation with a map function (not fetching anything), and I'm looking to insert a callback function in there to update the DOM with the loading percentage of the computation with every iteration of the map function.
Basically, I'm trying to update the DOM with the loadingPercentage variable in the following code. Console.log statement outputs the correct percentages.
`
useEffect(() => {
const frames: AnimationFrame[] = getAnimationFrames(
(loadingPercentage: number) => {
console.log(loadingPercentage);
// Here's the part I'm trying to insert something to update the DOM
}
);
setFrames(frames.map((frame) => frame.analysis));
setBoards(frames.map((frame) => frame.board));
}, []);
`
I'm trying to get the percentage on the DOM as follows:
<div>{loadingPercentage}</div>
//Not updating at all...
In case it could be useful, the heavy computation I mentioned in this case is getAnimationFrames() which is located in a non-react typescript file as such:
export const getAnimationFrames = (
loading?: Function,
pgn: string = defaultPgn
) => {
const history = getHistoryFromPgn(pgn);
const totalMoves = history.length;
let loadingPercentage = 0;
let moveNo = 0;
const animationFrames: AnimationFrame[] = history.map((move) => {
const animationFrame = getAnimationFrame(move);
moveNo++;
loadingPercentage = (moveNo * 100) / totalMoves;
if (loading) {
**loading(loadingPercentage);**
}
return animationFrame;
});
return animationFrames;
};
What I tried:
Making a state variable like const [loadingPercentage, setLoadingPercentage] = useState(0) and add it as a dependency to the useEffect hook but the getAnimationFrames function must be called only once so that didn't make a lot of sense.
Removing the getAnimationFrames function, and instead of using a loop I tried to get useEffect to behave like a loop by adding getAnimationFrame in the useEffect function to push the frames to an array with each component load, with the loadingPercentage as a dependency of useEffect. This seemed like it almost worked but eventually it started giving too many renders error.
Tried const loadingPercentage = useRef(0);, and updated loadingPercentage.current with loadingPercentage value at every iteration. This did not update the DOM as expected.
Tried abandoning React all together and did document.getElementById('loadingDiv').innerText = loadingPercentage. Seems like this is very easy to do with Vanilla JS, but cannot get it to work in React.
Let me know if you have any ideas.
Thank you!
| [
"You can model your state to incorperate loadingPercentage and pass setState into getAnimationFrames function:\ntype FrameState = { animationFrames: AnimationFrame[], loadingPercentage: number };\n\nconst [frames, setFrames] = useState<FrameState>({ animationFrames: [], loadingPercentage: 0 })\n\nuseEffect(() => {\n heavyComputation(frames, setFrames)\n}, []);\n\nfunction heavyComputation(frames, setFrames) {\n for (let index = 0; index < 100; index++) { \n if(100 % index) {\n setFrames({...frames, loadingPercentage: index}) \n } \n }\n}\n\nsetState will update loadingPercentage, and in the dom, you can reflect that update.\nJust an idea, see if it suits your implementation.\n",
" import { useState, useEffect } from 'react';\nimport { getAnimationFrame, getHistoryFromPgn } from './chess/chessApi';\nconst defaultPgn =\n '1. Nf3 Nf6 2. c4 g6 3. Nc3 Bg7 4. d4 O-O 5. Bf4 d5 6. Qb3 dxc4 7. Qxc4 c6 8. e4 Nbd7 9. Rd1 Nb6 10. Qc5 Bg4 11. Bg5 Na4 12. Qa3 Nxc3 13. bxc3 Nxe4 14. Bxe7 Qb6 15. Bc4 Nxc3 16. Bc5 Rfe8+ 17. Kf1 Be6 18. Bxb6 Bxc4+ 19. Kg1 Ne2+ 20. Kf1 Nxd4+ 21. Kg1 Ne2+ 22. Kf1 Nc3+ 23. Kg1 axb6 24. Qb4 Ra4 25. Qxb6 Nxd1 26. h3 Rxa2 27. Kh2 Nxf2 28. Re1 Rxe1 29. Qd8+ Bf8 30. Nxe1 Bd5 31. Nf3 Ne4 32. Qb8 b5 33. h4 h5 34. Ne5 Kg7 35. Kg1 Bc5+ 36. Kf1 Ng3+ 37. Ke1 Bb4+ 38. Kd1 Bb3+ 39. Kc1 Ne2+ 40. Kb1 Nc3+ 41. Kc1 Rc2# 0-1';\n\nconst history = getHistoryFromPgn(defaultPgn);\n\nexport default function App() {\n const [state, setState] = useState(0);\n\n useEffect(() => {\n heavyComputation();\n }, []);\n\n const sleep = (milliseconds: number) => {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n };\n\n async function heavyComputation() {\n for (let index = 0; index < history.length; index++) {\n getAnimationFrame(history[index]);\n await sleep(0);\n setState(index);\n }\n }\n\n return <div className='App'>{state}</div>;\n\n\nPutting an await sleep(0) between the loop ticks has worked out, from this point it will be easy to compute a loadingPercentage and update the DOM with it.\n\nThank you Enfield li for the answer!\n\n"
] | [
1,
0
] | [] | [] | [
"frontend",
"reactjs",
"typescript"
] | stackoverflow_0074671260_frontend_reactjs_typescript.txt |
Q:
Blinking box when I attempt to execute my code
I am new to programming, and I am working with web scraping YouTube video using pytube. When I execute the code below, I get the boldly lined box. It seems to want some input but I'm not sure what to do next.
When I press 'enter' without typing anything else, I get the following error message:
https://www.youtube.com/RJH6_fx9aT8
---------------------------------------------------------------------------
RegexMatchError Traceback (most recent call last)
<ipython-input-4-724a0c70ced1> in <module>
1 link = input ('https://www.youtube.com/RJH6_fx9aT8')
----> 2 yt = YouTube(link)
2 frames
/usr/local/lib/python3.7/dist-packages/pytube/helpers.py in regex_search(pattern, string, group)
32 results = regex.search(string)
33 if not results:
---> 34 raise RegexMatchError(caller="regex_search", pattern=pattern)
35
36 logger.debug("matched regex search: %s", pattern)
RegexMatchError: regex_search: could not find match for (?:v=|\/)([0-9A-Za-z_-]{11}).*
A:
https://www.youtube.com/RJH6_fx9aT8 isn't a valid YouTube URL, but https://www.youtube.com/watch?v=RJH6_fx9aT8 is a valid YouTube URL.
| Blinking box when I attempt to execute my code | I am new to programming, and I am working with web scraping YouTube video using pytube. When I execute the code below, I get the boldly lined box. It seems to want some input but I'm not sure what to do next.
When I press 'enter' without typing anything else, I get the following error message:
https://www.youtube.com/RJH6_fx9aT8
---------------------------------------------------------------------------
RegexMatchError Traceback (most recent call last)
<ipython-input-4-724a0c70ced1> in <module>
1 link = input ('https://www.youtube.com/RJH6_fx9aT8')
----> 2 yt = YouTube(link)
2 frames
/usr/local/lib/python3.7/dist-packages/pytube/helpers.py in regex_search(pattern, string, group)
32 results = regex.search(string)
33 if not results:
---> 34 raise RegexMatchError(caller="regex_search", pattern=pattern)
35
36 logger.debug("matched regex search: %s", pattern)
RegexMatchError: regex_search: could not find match for (?:v=|\/)([0-9A-Za-z_-]{11}).*
| [
"https://www.youtube.com/RJH6_fx9aT8 isn't a valid YouTube URL, but https://www.youtube.com/watch?v=RJH6_fx9aT8 is a valid YouTube URL.\n"
] | [
0
] | [] | [] | [
"python",
"pytube",
"web_scraping",
"youtube"
] | stackoverflow_0074324936_python_pytube_web_scraping_youtube.txt |
Q:
How to remove the red color indictors at the beginning of all the code?
When I updated Visual Studio Code, I am getting this annoying red indicator/highlighting before every line of code. Before the update, didn't have this issue. Does anyone know what is this and how to get rid of it?
I tried resetting and changing the theme but it didn't work.
A:
I think this extension is causing your problem:
https://marketplace.visualstudio.com/items?itemName=oderwat.indent-rainbow
Try to disable/uninstall the "Indent-Rainbow" extension if it is installed.
For the "Trailing Spaces" extension, you can disable the highlighting option by adding this line to the settings.json file.
{
"trailing-spaces.highlightCurrentLine": false
}
You can find more settings here:
https://marketplace.visualstudio.com/items?itemName=shardulm94.trailing-spaces
A:
I had the same problem and I thought it must be some extension causing this and so I took a deeper look at all my extensions.
In my case there was an extension called 'trailing spaces' which was causing this.
the red highlighting disappeared as soon as I uninstalled it.
Try doing the same and if it doesn't work try to take a look at all of your extensions. (An easier way to do that would be to go over the extensions tab on the left navigation bar in settings menu).
A:
On the bottom bar, to the right, just beside the "Ln XX and Col XX" you can choose "Select Indentation" to indent using spaces or tabs. Change that configuration or choose "detect indentation from content" and will solve the red background.
A:
I just had to change the tab size from 4 to 2 (as configured within my eslint setup)
A:
For my case it was an extension called Bracket Pair Colorizer
A:
I kept the Indent Rainbow extension, but added this to my settings.json to disable the red highlights:
"indentRainbow.ignoreErrorLanguages": [
"markdown",
"python"
| How to remove the red color indictors at the beginning of all the code? | When I updated Visual Studio Code, I am getting this annoying red indicator/highlighting before every line of code. Before the update, didn't have this issue. Does anyone know what is this and how to get rid of it?
I tried resetting and changing the theme but it didn't work.
| [
"I think this extension is causing your problem:\nhttps://marketplace.visualstudio.com/items?itemName=oderwat.indent-rainbow\nTry to disable/uninstall the \"Indent-Rainbow\" extension if it is installed.\nFor the \"Trailing Spaces\" extension, you can disable the highlighting option by adding this line to the settings.json file.\n{\n \"trailing-spaces.highlightCurrentLine\": false \n}\n\nYou can find more settings here:\nhttps://marketplace.visualstudio.com/items?itemName=shardulm94.trailing-spaces\n",
"I had the same problem and I thought it must be some extension causing this and so I took a deeper look at all my extensions.\nIn my case there was an extension called 'trailing spaces' which was causing this.\nthe red highlighting disappeared as soon as I uninstalled it.\nTry doing the same and if it doesn't work try to take a look at all of your extensions. (An easier way to do that would be to go over the extensions tab on the left navigation bar in settings menu).\n",
"On the bottom bar, to the right, just beside the \"Ln XX and Col XX\" you can choose \"Select Indentation\" to indent using spaces or tabs. Change that configuration or choose \"detect indentation from content\" and will solve the red background.\n",
"I just had to change the tab size from 4 to 2 (as configured within my eslint setup)\n",
"For my case it was an extension called Bracket Pair Colorizer\n",
"I kept the Indent Rainbow extension, but added this to my settings.json to disable the red highlights:\n \"indentRainbow.ignoreErrorLanguages\": [\n \"markdown\",\n \"python\"\n\n"
] | [
5,
2,
1,
1,
0,
0
] | [] | [] | [
"visual_studio_code",
"vscode_settings"
] | stackoverflow_0059090648_visual_studio_code_vscode_settings.txt |
Q:
What is the recommended approach to encrypt existing parameters?
I have few hundreds, if not thousands, entries in the parameter store on one of my AWS accounts. At the moment they are just plain strings. I would like to encrypt them using the default KMS key but so far the only way I found to do this involves deleting the existing parameter. I also need to encrypt all the versions of existing parameters.
Is there a way to do this without deleting parameters?
A:
I know you can update an existing String parameter to become a SecureString.
aws ssm put-parameter --name "test" --value "param" --type String
aws ssm put-parameter --name "test" --value "param" --type SecureString --overwrite
However, I don't think there is a way to edit the parameter version history to encrypt previous version values.
If it is unacceptable that the parameter history is unencrypted, I think you will need to write a script to delete each parameter and replace it with a SecureString parameter.
| What is the recommended approach to encrypt existing parameters? | I have few hundreds, if not thousands, entries in the parameter store on one of my AWS accounts. At the moment they are just plain strings. I would like to encrypt them using the default KMS key but so far the only way I found to do this involves deleting the existing parameter. I also need to encrypt all the versions of existing parameters.
Is there a way to do this without deleting parameters?
| [
"I know you can update an existing String parameter to become a SecureString.\naws ssm put-parameter --name \"test\" --value \"param\" --type String\naws ssm put-parameter --name \"test\" --value \"param\" --type SecureString --overwrite\n\nHowever, I don't think there is a way to edit the parameter version history to encrypt previous version values.\nIf it is unacceptable that the parameter history is unencrypted, I think you will need to write a script to delete each parameter and replace it with a SecureString parameter.\n"
] | [
0
] | [] | [] | [
"aws_systems_manager"
] | stackoverflow_0071173850_aws_systems_manager.txt |
Q:
While playing unity games, not able to hear any sound/music
I managed to play games in unity editor, that ultimately is going to be integrated in a React Native app.
Actual:
No sound/music when game is played both in Unity editor and android devices.
Expected:
Sound/music plays both on unity player and in an application.
What I found out:
If I open GameManager from a game scene, there is listed all missing audioClips. When I play a game, I get following warning,
PlayOneShot was called with a null AudioClip.
Attached is how GamaeManager looks like currently.
I have opened GameScene.unity file in a text editor, and then looked for AudioSource: tag and found entries like
m_audioClip: {fileID: 8300000, guid: ee59e26e7f152024e8eecxxxxxxxxx, type: 3}
I then have verified that, an audio asset with such guid exist.
Further investigation led me to following SO question which indicates similar issue as mine and has something to do with fileID getting reset to 0.
I however, being a newbie to Unity, cannot possibly understand the dynamics of it, why and how fileID got reset.
Please help me to fix the audio issue both in Unity player and eventually for android devices.
A:
(unless i don't get your question)
You can probably just reassign the audio clips in the editor by dragging the clips overtop the inputs for them, if they're in your assets folder
| While playing unity games, not able to hear any sound/music | I managed to play games in unity editor, that ultimately is going to be integrated in a React Native app.
Actual:
No sound/music when game is played both in Unity editor and android devices.
Expected:
Sound/music plays both on unity player and in an application.
What I found out:
If I open GameManager from a game scene, there is listed all missing audioClips. When I play a game, I get following warning,
PlayOneShot was called with a null AudioClip.
Attached is how GamaeManager looks like currently.
I have opened GameScene.unity file in a text editor, and then looked for AudioSource: tag and found entries like
m_audioClip: {fileID: 8300000, guid: ee59e26e7f152024e8eecxxxxxxxxx, type: 3}
I then have verified that, an audio asset with such guid exist.
Further investigation led me to following SO question which indicates similar issue as mine and has something to do with fileID getting reset to 0.
I however, being a newbie to Unity, cannot possibly understand the dynamics of it, why and how fileID got reset.
Please help me to fix the audio issue both in Unity player and eventually for android devices.
| [
"(unless i don't get your question)\nYou can probably just reassign the audio clips in the editor by dragging the clips overtop the inputs for them, if they're in your assets folder\n\n"
] | [
0
] | [] | [] | [
"android",
"audio",
"game_development",
"unity3d"
] | stackoverflow_0074672240_android_audio_game_development_unity3d.txt |
Q:
How to work with environment variables on Windows/Linux..?
I am trying to work with an OpenAI library (https://github.com/orhanerday/open-ai) that uses environment variables for key storage, but it doesn't seem to be finding the key when I run it.
On my local Windows machine I ran the following command: setx OPENAI_API_KEY “mykey”
On the Linux web server I ran the following command: export OPENAI_API_KEY=mykey
Now on the server when I run the following, I see the correct key value printed back to me: printenv OPENAI_API_KEY
In my script I'm using $open_ai_key = getenv('OPENAI_API_KEY'); but I'm getting no value back..??
Any information on how I can resolve this would be greatly appreciated. Thanks!
A:
It sounds like the environment variable you set is not being recognized by the script you're running. There are a few possible reasons for this.
First, you need to make sure that the environment variable is being set in the correct environment. When you run the setx or export command, it sets the environment variable for the current shell session. This means that the variable will only be available to processes that are started after the command is run. If you're running your script as a service or in a different shell session, it will not have access to the environment variable.
To fix this, you can either run your script in the same shell session where you set the environment variable, or you can set the variable globally on your system so that it is available to all processes. To set the variable globally on Windows, you can use the setx command with the -m flag:
setx -m OPENAI_API_KEY mykey
On Linux, you can set the variable in the /etc/environment file:
echo 'OPENAI_API_KEY=mykey' >> /etc/environment
After setting the variable, you will need to restart any services or processes that need to use it for the changes to take effect.
Another possible issue is that the script is not accessing the environment variable correctly. In the code, you will need to use the getenv() function to retrieve the value of the environment variable. For example:
$apiKey = getenv('OPENAI_API_KEY');
Make sure the script is using this function to retrieve the API key, and that the variable name is spelled correctly.
I hope this helps! Let me know if you have any other questions.
| How to work with environment variables on Windows/Linux..? | I am trying to work with an OpenAI library (https://github.com/orhanerday/open-ai) that uses environment variables for key storage, but it doesn't seem to be finding the key when I run it.
On my local Windows machine I ran the following command: setx OPENAI_API_KEY “mykey”
On the Linux web server I ran the following command: export OPENAI_API_KEY=mykey
Now on the server when I run the following, I see the correct key value printed back to me: printenv OPENAI_API_KEY
In my script I'm using $open_ai_key = getenv('OPENAI_API_KEY'); but I'm getting no value back..??
Any information on how I can resolve this would be greatly appreciated. Thanks!
| [
"It sounds like the environment variable you set is not being recognized by the script you're running. There are a few possible reasons for this.\nFirst, you need to make sure that the environment variable is being set in the correct environment. When you run the setx or export command, it sets the environment variable for the current shell session. This means that the variable will only be available to processes that are started after the command is run. If you're running your script as a service or in a different shell session, it will not have access to the environment variable.\nTo fix this, you can either run your script in the same shell session where you set the environment variable, or you can set the variable globally on your system so that it is available to all processes. To set the variable globally on Windows, you can use the setx command with the -m flag:\nsetx -m OPENAI_API_KEY mykey\nOn Linux, you can set the variable in the /etc/environment file:\necho 'OPENAI_API_KEY=mykey' >> /etc/environment\nAfter setting the variable, you will need to restart any services or processes that need to use it for the changes to take effect.\nAnother possible issue is that the script is not accessing the environment variable correctly. In the code, you will need to use the getenv() function to retrieve the value of the environment variable. For example:\n$apiKey = getenv('OPENAI_API_KEY');\nMake sure the script is using this function to retrieve the API key, and that the variable name is spelled correctly.\nI hope this helps! Let me know if you have any other questions.\n"
] | [
0
] | [] | [] | [
"environment_variables",
"php"
] | stackoverflow_0074672366_environment_variables_php.txt |
Q:
How can I use dcast based on multiple columns?
I have data on this form in a data.table DT:
DT = data.table(
year=c('1981', '1981', '1981', '2005', '2005', '2005'),
value=c(2, 8, 16, 3, 9, 27),
order =c(1,2,3,1,2,3))
year
value
order
'1981'
2
1
'1981'
8
2
'1981'
16
3
'2005'
3
1
'2005'
9
2
'2005'
27
3
And I want to create new columns based first on the order within a specific year, but then sequentially on the order if I shift it. As you can see value=16 which starts as order=3 on row 1, is logged as order = 2 on row 2, etc.
year
order1
order2
order3
'1981'
2
8
16
'1981'
8
16
NA
'1981'
16
NA
NA
'2005'
3
9
27
'2005'
9
27
NA
'2005'
27
NA
NA
If I wanted it just by order, and get rows 1 and 4 as output, I could do:
dcast(DT, year ~ order, value.var = c('value'))
But how can I cast based on order while incorporating this reordering?
I could perhaps create new columns indicating the new shifted order, using:
DT[,order_2:= c(NA,1,2,NA,1,2)]
DT[,order_3:= c(NA,NA,1,NA,NA,1)]
But then how do I do casting on all three columns?
Is there a more elegant way than just casting 3 times and then joining the results?
A:
You don't necessarily need dcast, try this:
DT[, lapply(seq_along(value), \(v) {l <- length(value); `length<-`(value[v:l], l)}), by=year]
# year V1 V2 V3
# 1: 1981 2 8 16
# 2: 1981 8 16 NA
# 3: 1981 16 NA NA
# 4: 2005 3 9 27
# 5: 2005 9 27 NA
# 6: 2005 27 NA NA
A:
We could use shift with transpose
library(data.table)
DT[, setNames(transpose(shift(value, n = seq_len(.N)-1, type = "lead")),
paste0("order", order)), year]
-output
year order1 order2 order3
1: 1981 2 8 16
2: 1981 8 16 NA
3: 1981 16 NA NA
4: 2005 3 9 27
5: 2005 9 27 NA
6: 2005 27 NA NA
A:
Here's a dcast, a little bit of other work to get it right:
library(data.table)
dcast(year + order ~ paste0("order", ord2),
data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)],
value.var = "i.value"
)[, order := NULL
][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns("^order"), by = .(year)][]
dcast(year + order ~ paste0("order", ord2), data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)], value.var = "i.value")[, order := NULL][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns("^order"), by = .(year)][]
# year order1 order2 order3
# <char> <num> <num> <num>
# 1: 1981 2 8 16
# 2: 1981 8 16 NA
# 3: 1981 16 NA NA
# 4: 2005 3 9 27
# 5: 2005 9 27 NA
# 6: 2005 27 NA NA
Caveat: with this sample data, it is significantly slower than the other two answers. It is offered primarily to show that while it may be possible, it is not always the most efficient path:
bench::mark(
jay.sf = DT[, lapply(seq_along(value), \(v) {l <- length(value); `length<-`(value[v:l], l)}), by=year],
akrun = DT[, setNames(transpose(shift(value, n = seq_len(.N)-1, type = "lead")), paste0("order", order)), year],
r2evans = dcast(year + order ~ paste0("order", ord2), data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)], value.var = "i.value")[, order := NULL][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns("^order"), by = .(year)][],
check = FALSE)
# # A tibble: 3 x 13
# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc
# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list>
# 1 jay.sf 225.2us 266.15us 3642. 48.6KB 5.38 1354 2 372ms <NULL> <Rprofmem [11 x 3]> <bench_tm [1,356]> <tibble [1,356 x 3]>
# 2 akrun 262.9us 307.4us 3149. 48.6KB 2.41 1305 1 414ms <NULL> <Rprofmem [12 x 3]> <bench_tm [1,306]> <tibble [1,306 x 3]>
# 3 r2evans 2.74ms 2.99ms 330. 453.3KB 2.30 143 1 434ms <NULL> <Rprofmem [91 x 3]> <bench_tm [144]> <tibble [144 x 3]>
| How can I use dcast based on multiple columns? | I have data on this form in a data.table DT:
DT = data.table(
year=c('1981', '1981', '1981', '2005', '2005', '2005'),
value=c(2, 8, 16, 3, 9, 27),
order =c(1,2,3,1,2,3))
year
value
order
'1981'
2
1
'1981'
8
2
'1981'
16
3
'2005'
3
1
'2005'
9
2
'2005'
27
3
And I want to create new columns based first on the order within a specific year, but then sequentially on the order if I shift it. As you can see value=16 which starts as order=3 on row 1, is logged as order = 2 on row 2, etc.
year
order1
order2
order3
'1981'
2
8
16
'1981'
8
16
NA
'1981'
16
NA
NA
'2005'
3
9
27
'2005'
9
27
NA
'2005'
27
NA
NA
If I wanted it just by order, and get rows 1 and 4 as output, I could do:
dcast(DT, year ~ order, value.var = c('value'))
But how can I cast based on order while incorporating this reordering?
I could perhaps create new columns indicating the new shifted order, using:
DT[,order_2:= c(NA,1,2,NA,1,2)]
DT[,order_3:= c(NA,NA,1,NA,NA,1)]
But then how do I do casting on all three columns?
Is there a more elegant way than just casting 3 times and then joining the results?
| [
"You don't necessarily need dcast, try this:\nDT[, lapply(seq_along(value), \\(v) {l <- length(value); `length<-`(value[v:l], l)}), by=year]\n# year V1 V2 V3\n# 1: 1981 2 8 16\n# 2: 1981 8 16 NA\n# 3: 1981 16 NA NA\n# 4: 2005 3 9 27\n# 5: 2005 9 27 NA\n# 6: 2005 27 NA NA\n\n",
"We could use shift with transpose\nlibrary(data.table)\nDT[, setNames(transpose(shift(value, n = seq_len(.N)-1, type = \"lead\")), \n paste0(\"order\", order)), year]\n\n-output\n year order1 order2 order3\n1: 1981 2 8 16\n2: 1981 8 16 NA\n3: 1981 16 NA NA\n4: 2005 3 9 27\n5: 2005 9 27 NA\n6: 2005 27 NA NA\n\n",
"Here's a dcast, a little bit of other work to get it right:\nlibrary(data.table)\ndcast(year + order ~ paste0(\"order\", ord2),\n data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)],\n value.var = \"i.value\"\n )[, order := NULL\n ][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns(\"^order\"), by = .(year)][]\ndcast(year + order ~ paste0(\"order\", ord2), data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)], value.var = \"i.value\")[, order := NULL][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns(\"^order\"), by = .(year)][]\n# year order1 order2 order3\n# <char> <num> <num> <num>\n# 1: 1981 2 8 16\n# 2: 1981 8 16 NA\n# 3: 1981 16 NA NA\n# 4: 2005 3 9 27\n# 5: 2005 9 27 NA\n# 6: 2005 27 NA NA\n\nCaveat: with this sample data, it is significantly slower than the other two answers. It is offered primarily to show that while it may be possible, it is not always the most efficient path:\nbench::mark(\n jay.sf = DT[, lapply(seq_along(value), \\(v) {l <- length(value); `length<-`(value[v:l], l)}), by=year],\n akrun = DT[, setNames(transpose(shift(value, n = seq_len(.N)-1, type = \"lead\")), paste0(\"order\", order)), year],\n r2evans = dcast(year + order ~ paste0(\"order\", ord2), data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)], value.var = \"i.value\")[, order := NULL][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns(\"^order\"), by = .(year)][],\n check = FALSE)\n# # A tibble: 3 x 13\n# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc \n# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list> \n# 1 jay.sf 225.2us 266.15us 3642. 48.6KB 5.38 1354 2 372ms <NULL> <Rprofmem [11 x 3]> <bench_tm [1,356]> <tibble [1,356 x 3]>\n# 2 akrun 262.9us 307.4us 3149. 48.6KB 2.41 1305 1 414ms <NULL> <Rprofmem [12 x 3]> <bench_tm [1,306]> <tibble [1,306 x 3]>\n# 3 r2evans 2.74ms 2.99ms 330. 453.3KB 2.30 143 1 434ms <NULL> <Rprofmem [91 x 3]> <bench_tm [144]> <tibble [144 x 3]> \n\n"
] | [
4,
1,
1
] | [] | [] | [
"data.table",
"data_wrangling",
"dcast",
"r",
"reshape"
] | stackoverflow_0074665337_data.table_data_wrangling_dcast_r_reshape.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.