content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
UseState doesn´t update a new array in the object
I want to initiate a constant with useState, but after using this hook a part of object from http request is getting lost.
This is my code:
const createBlankGroups =(caunt)=>{
const blankGroups ={
[uuid()]:{
name: 'Teams',
items: teams //teams are taken from database with http request
}
};
let letter = 'A'
for(let i =0; i < caunt;i++){
blankGroups[uuid()] = {
name: 'Gruppe ' + letter,
items: []
};
letter = String.fromCharCode(letter.charCodeAt(0)+1 )
}
console.log(blankGroups)
return(blankGroups);
}
const tempGroups = createBlankGroups(3)
console.log(tempGroups) // at this step the teams are still in object (img1)
const[columns,setColumns]= useState(tempGroups);
console.log(columns); //here the array is empty (img 2)
img1
img2
After reserch i find a lot about useState and what it can read the unknown types of objeject, but i still dont understand how to initiate it another way.
A:
You can use useEffect, to update the columns
useEffect(() => {
const tempGroups = createBlankGroups(3)
setColumns(tempGroups);
},[])
|
UseState doesn´t update a new array in the object
|
I want to initiate a constant with useState, but after using this hook a part of object from http request is getting lost.
This is my code:
const createBlankGroups =(caunt)=>{
const blankGroups ={
[uuid()]:{
name: 'Teams',
items: teams //teams are taken from database with http request
}
};
let letter = 'A'
for(let i =0; i < caunt;i++){
blankGroups[uuid()] = {
name: 'Gruppe ' + letter,
items: []
};
letter = String.fromCharCode(letter.charCodeAt(0)+1 )
}
console.log(blankGroups)
return(blankGroups);
}
const tempGroups = createBlankGroups(3)
console.log(tempGroups) // at this step the teams are still in object (img1)
const[columns,setColumns]= useState(tempGroups);
console.log(columns); //here the array is empty (img 2)
img1
img2
After reserch i find a lot about useState and what it can read the unknown types of objeject, but i still dont understand how to initiate it another way.
|
[
"You can use useEffect, to update the columns\n useEffect(() => {\n const tempGroups = createBlankGroups(3)\n setColumns(tempGroups);\n\n},[])\n\n"
] |
[
0
] |
[] |
[] |
[
"object",
"react_hooks",
"reactjs"
] |
stackoverflow_0074662070_object_react_hooks_reactjs.txt
|
Q:
trouble deploying to GCP Functions -GcfJarLauncher class not found
I am trying to deploy a simple Rest API to Google Cloud Functions. Per this documentation, I need the target to always be org.springframework.cloud.function.adapter.gcp.GcfJarLauncher
However when I deploy it using the provided code, I get:
ERROR: (gcloud.alpha.functions.deploy) OperationError: code=3, message=Build failed:
build succeeded but did not produce the class "org.springframework.cloud.function.adapter.gcp.GcfJarLauncher"
specified as the function target: Error: class not found: org.springframework.cloud.function.adapter.gcp.GcfJarLauncher;
Error ID: d818fd83
Here is the code I am running in the Cloud CLI:
gcloud alpha functions deploy function-sample-gcp-http --entry-point org.springframework.cloud.function.adapter.gcp.GcfJarLauncher --runtime java11 --trigger-http --source target/deploy --memory 512MB
Here my code repo but I will include some relevant bits below
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.divr-fx-test</groupId>
<artifactId>divr-function</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>divr-function</name>
<description>Function testing for DIVR</description>
<properties>
<java.version>11</java.version>
<spring-cloud-function.version>4.0.0-SNAPSHOT</spring-cloud-function.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-web</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-function-web</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-dependencies</artifactId>
<version>3.2.8</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.google.cloud.functions</groupId>
<artifactId>functions-framework-api</artifactId>
<version>1.0.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-adapter-gcp</artifactId>
<version>3.2.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.mypackage.MyClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<outputDirectory>target/deploy</outputDirectory>
</configuration>
</plugin>
<plugin>
<groupId>com.google.cloud.functions</groupId>
<artifactId>function-maven-plugin</artifactId>
<version>0.9.1</version>
<configuration
<functionTarget>org.springframework.cloud.function.adapter.gcp.GcfJarLauncher</functionTarget>
<port>8080</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
Main:
package com.fkgcp;
import java.util.function.Function;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DivrFunctionApplication {
public static void main(String[] args) {
SpringApplication.run(DivrFunctionApplication.class, args);
}
// this part I don't actually want to use, but it is present
// in every tutorial, so I included it to see if it would be
// triggered instead of my REST functions
@Bean
public Function<String, String> uppercase() {
return value -> value.toUpperCase();
}
}
Also, I added a MANIFEST.MF, is it in the right location?
divr-function/src/main/resources/META-INF/MANIFEST.MF
Contents:
Main-Class: com.fkgcp.DivrFunctionApplication
What am I missing?
A:
It looks like the error you are seeing is caused by the fact that the org.springframework.cloud.function.adapter.gcp.GcfJarLauncher class is not found in the target/deploy directory. This is likely because the class is not included in your built JAR file.
To fix this issue, you will need to make sure that the GcfJarLauncher class is included in your built JAR file. You can do this by adding the spring-cloud-function-adapter-gcp dependency to your pom.xml file, and then specifying the GcfJarLauncher class as the entry point for your JAR file.
Here's an example of how you can do this:
<!-- Add the spring-cloud-function-adapter-gcp dependency -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-adapter-gcp</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<!-- Set the GcfJarLauncher class as the entry point for the JAR file -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>org.springframework.cloud.function.adapter.gcp.GcfJarLauncher</mainClass>
</configuration>
</plugin>
</plugins>
</build>
With these changes in place, the GcfJarLauncher class will be included in your built JAR file, and you should be able to deploy your function without encountering the class not found error.
|
trouble deploying to GCP Functions -GcfJarLauncher class not found
|
I am trying to deploy a simple Rest API to Google Cloud Functions. Per this documentation, I need the target to always be org.springframework.cloud.function.adapter.gcp.GcfJarLauncher
However when I deploy it using the provided code, I get:
ERROR: (gcloud.alpha.functions.deploy) OperationError: code=3, message=Build failed:
build succeeded but did not produce the class "org.springframework.cloud.function.adapter.gcp.GcfJarLauncher"
specified as the function target: Error: class not found: org.springframework.cloud.function.adapter.gcp.GcfJarLauncher;
Error ID: d818fd83
Here is the code I am running in the Cloud CLI:
gcloud alpha functions deploy function-sample-gcp-http --entry-point org.springframework.cloud.function.adapter.gcp.GcfJarLauncher --runtime java11 --trigger-http --source target/deploy --memory 512MB
Here my code repo but I will include some relevant bits below
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.divr-fx-test</groupId>
<artifactId>divr-function</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>divr-function</name>
<description>Function testing for DIVR</description>
<properties>
<java.version>11</java.version>
<spring-cloud-function.version>4.0.0-SNAPSHOT</spring-cloud-function.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-web</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-function-web</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-dependencies</artifactId>
<version>3.2.8</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.google.cloud.functions</groupId>
<artifactId>functions-framework-api</artifactId>
<version>1.0.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-adapter-gcp</artifactId>
<version>3.2.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.mypackage.MyClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<outputDirectory>target/deploy</outputDirectory>
</configuration>
</plugin>
<plugin>
<groupId>com.google.cloud.functions</groupId>
<artifactId>function-maven-plugin</artifactId>
<version>0.9.1</version>
<configuration
<functionTarget>org.springframework.cloud.function.adapter.gcp.GcfJarLauncher</functionTarget>
<port>8080</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
Main:
package com.fkgcp;
import java.util.function.Function;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DivrFunctionApplication {
public static void main(String[] args) {
SpringApplication.run(DivrFunctionApplication.class, args);
}
// this part I don't actually want to use, but it is present
// in every tutorial, so I included it to see if it would be
// triggered instead of my REST functions
@Bean
public Function<String, String> uppercase() {
return value -> value.toUpperCase();
}
}
Also, I added a MANIFEST.MF, is it in the right location?
divr-function/src/main/resources/META-INF/MANIFEST.MF
Contents:
Main-Class: com.fkgcp.DivrFunctionApplication
What am I missing?
|
[
"It looks like the error you are seeing is caused by the fact that the org.springframework.cloud.function.adapter.gcp.GcfJarLauncher class is not found in the target/deploy directory. This is likely because the class is not included in your built JAR file.\nTo fix this issue, you will need to make sure that the GcfJarLauncher class is included in your built JAR file. You can do this by adding the spring-cloud-function-adapter-gcp dependency to your pom.xml file, and then specifying the GcfJarLauncher class as the entry point for your JAR file.\nHere's an example of how you can do this:\n<!-- Add the spring-cloud-function-adapter-gcp dependency -->\n<dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-function-adapter-gcp</artifactId>\n <version>3.2.8.RELEASE</version>\n</dependency>\n\n<!-- Set the GcfJarLauncher class as the entry point for the JAR file -->\n<build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n<configuration>\n <mainClass>org.springframework.cloud.function.adapter.gcp.GcfJarLauncher</mainClass>\n</configuration>\n</plugin>\n</plugins>\n</build>\n\nWith these changes in place, the GcfJarLauncher class will be included in your built JAR file, and you should be able to deploy your function without encountering the class not found error.\n"
] |
[
0
] |
[] |
[] |
[
"google_cloud_functions",
"google_cloud_platform",
"java",
"microservices"
] |
stackoverflow_0074617862_google_cloud_functions_google_cloud_platform_java_microservices.txt
|
Q:
Create Border Radius Upisde Down
i don't know how to make this type of corner?
i want to create corner like this:-Image Of Border Radius
i wan to add it into the footer
A:
You could put the red and white backgrounds on in before and after pseudo elements.
If you give them z-index: -1 as in this snippet they will sit behind the actual element.
This snippet puts the red onto the before element, making that the same size as the actual element, and puts the white onto the after element, making it <whatever size you want, probably a % of the whole height> and with rounded bottom corners.
Note that the pseudo elements are positioned absolute so they don't affect the layout of other elements, and they are put top and left of the actual element (which has had position relative set).
body {
margin: 0;
}
.mydiv {
width: 100vw;
height: 300px;
/* for demo */
position: relative;
}
.mydiv::after,
.mydiv::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
z-index: -1;
}
.mydiv::before {
background: red;
height: 100%;
}
.mydiv::after {
height: 20%;
background: white;
border-radius: 0 0 30px 30px;
}
<div class="mydiv"></div>
|
Create Border Radius Upisde Down
|
i don't know how to make this type of corner?
i want to create corner like this:-Image Of Border Radius
i wan to add it into the footer
|
[
"You could put the red and white backgrounds on in before and after pseudo elements.\nIf you give them z-index: -1 as in this snippet they will sit behind the actual element.\nThis snippet puts the red onto the before element, making that the same size as the actual element, and puts the white onto the after element, making it <whatever size you want, probably a % of the whole height> and with rounded bottom corners.\nNote that the pseudo elements are positioned absolute so they don't affect the layout of other elements, and they are put top and left of the actual element (which has had position relative set).\n\n\nbody {\n margin: 0;\n}\n\n.mydiv {\n width: 100vw;\n height: 300px;\n /* for demo */\n position: relative;\n}\n\n.mydiv::after,\n.mydiv::before {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n z-index: -1;\n}\n\n.mydiv::before {\n background: red;\n height: 100%;\n}\n\n.mydiv::after {\n height: 20%;\n background: white;\n border-radius: 0 0 30px 30px;\n}\n<div class=\"mydiv\"></div>\n\n\n\n"
] |
[
0
] |
[] |
[] |
[
"css",
"html"
] |
stackoverflow_0074664189_css_html.txt
|
Q:
PyQT5 ui file, does not load properly from the executable file
I am building a PyQt5 application by constructing the interfaces with the designer and the exporting to .ui files. The latter are then loaded by my main class. Here is an example of my source code under the name main.py:
main.py
import os.path
import PyQt5.QtWidgets as qtw
from PyQt5.uic import loadUi
import sys
class MainUI(qtw.QMainWindow):
def __init__(self, parent=None):
super(MainUI, self).__init__()
self._ui_path = os.path.dirname(os.path.abspath(__file__))
loadUi(os.path.join(self._ui_path, 'main.ui'), self)
if __name__ == "__main__":
# Create the application
app = qtw.QApplication(sys.argv)
# Create and show the application's main window
win = MainUI()
win.show()
sys.exit(app.exec())
main.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>320</width>
<height>240</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>110</x>
<y>100</y>
<width>88</width>
<height>27</height>
</rect>
</property>
<property name="text">
<string>ok</string>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>320</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
I generate an executable with pyinstaller by giving pyinstaller -F -w main.py.
In the beginning the executable should be in the same folder with the ui. I have changed loadUI following the answer here.
When I run the executable now it gives me an error message with the following traceback:
Traceback (most recent call last):
File "main.py", line 17, in <module>
win = MainUI()
File "main.py", line 11, in __init__
loadUi(os.path.join(self._ui_path, 'main.ui'), self)
File "PyQt5\uic\__init__.py", line 238, in loadUi
File "PyQt5\uic\Loader\loader.py", line 66, in loadUi
File "PyQt5\uic\uiparser.py", line 1020, in parse
File "xml\etree\ElementTree.py", line 1202, in parse
File "xml\etree\ElementTree.py", line 584, in parse
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\username\\AppData\\Local\\Temp\\_MEI187162\\main.ui'
What has happened is that after running the .exe file, a temporary directory is created having some dll files, and the program tries to locate the .ui file there, without success. What can be done to direct the executable to the place where the .ui file is?
A:
Add this somewhere at the top of your program:
import sys
import os
if getattr(sys, 'frozen', False):
RELATIVE_PATH = os.path.dirname(sys.executable)
else:
RELATIVE_PATH = os.path.dirname(__file__)
Then when you go to call loadUi():
self._ui_path = RELATIVE_PATH + "/ui_path" # Update this as needed
loadUi(os.path.join(self._ui_path, 'main.ui'), self)
When programs are compiled and ran elsewhere the directories can get a little weird. See if this works for you, if not, let me know and I can help out further.
A:
I turn back from PyQt5 version 5.15.7 to version 5.15.1 by command "pip install PyQt5==5.15.1". My problem resolved.
My Code Goes like this
from PyQt5.QtWidgets import QApplication
from PyQt5 import uic
class UI(QWidget):
def __init__(self):
super(UI,self).__init__()
# loading the ui file with uic module
uic.loadUi("*xxxxxx*.ui", self)
app = QApplication([])
window = UI()
window.show()
app.exec()
|
PyQT5 ui file, does not load properly from the executable file
|
I am building a PyQt5 application by constructing the interfaces with the designer and the exporting to .ui files. The latter are then loaded by my main class. Here is an example of my source code under the name main.py:
main.py
import os.path
import PyQt5.QtWidgets as qtw
from PyQt5.uic import loadUi
import sys
class MainUI(qtw.QMainWindow):
def __init__(self, parent=None):
super(MainUI, self).__init__()
self._ui_path = os.path.dirname(os.path.abspath(__file__))
loadUi(os.path.join(self._ui_path, 'main.ui'), self)
if __name__ == "__main__":
# Create the application
app = qtw.QApplication(sys.argv)
# Create and show the application's main window
win = MainUI()
win.show()
sys.exit(app.exec())
main.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>320</width>
<height>240</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>110</x>
<y>100</y>
<width>88</width>
<height>27</height>
</rect>
</property>
<property name="text">
<string>ok</string>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>320</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
I generate an executable with pyinstaller by giving pyinstaller -F -w main.py.
In the beginning the executable should be in the same folder with the ui. I have changed loadUI following the answer here.
When I run the executable now it gives me an error message with the following traceback:
Traceback (most recent call last):
File "main.py", line 17, in <module>
win = MainUI()
File "main.py", line 11, in __init__
loadUi(os.path.join(self._ui_path, 'main.ui'), self)
File "PyQt5\uic\__init__.py", line 238, in loadUi
File "PyQt5\uic\Loader\loader.py", line 66, in loadUi
File "PyQt5\uic\uiparser.py", line 1020, in parse
File "xml\etree\ElementTree.py", line 1202, in parse
File "xml\etree\ElementTree.py", line 584, in parse
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\username\\AppData\\Local\\Temp\\_MEI187162\\main.ui'
What has happened is that after running the .exe file, a temporary directory is created having some dll files, and the program tries to locate the .ui file there, without success. What can be done to direct the executable to the place where the .ui file is?
|
[
"Add this somewhere at the top of your program:\nimport sys\nimport os\n\nif getattr(sys, 'frozen', False):\n RELATIVE_PATH = os.path.dirname(sys.executable)\nelse:\n RELATIVE_PATH = os.path.dirname(__file__)\n\nThen when you go to call loadUi():\nself._ui_path = RELATIVE_PATH + \"/ui_path\" # Update this as needed\n\nloadUi(os.path.join(self._ui_path, 'main.ui'), self)\n\nWhen programs are compiled and ran elsewhere the directories can get a little weird. See if this works for you, if not, let me know and I can help out further.\n",
"I turn back from PyQt5 version 5.15.7 to version 5.15.1 by command \"pip install PyQt5==5.15.1\". My problem resolved.\nMy Code Goes like this\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5 import uic\n\n\nclass UI(QWidget):\n def __init__(self):\n super(UI,self).__init__()\n\n # loading the ui file with uic module\n uic.loadUi(\"*xxxxxx*.ui\", self)\n\n\napp = QApplication([])\nwindow = UI()\nwindow.show()\napp.exec()\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"pyqt5",
"python"
] |
stackoverflow_0071398328_pyqt5_python.txt
|
Q:
yarn install wont run on my project keeps telling me that it couldn't find the binary react-script start
my package.json
the error i get
all my scripts dont work it keeps throwing the same error everytime.
i have cloned the repo in a different location and reinstalled the dependencies but still yarn start wont run.
what could be the problem?
A:
try running your project with this yarn run start or just add react-scripts with yarn using this command yarn add react-scripts because maybe react-scripts is not installed for some reason
|
yarn install wont run on my project keeps telling me that it couldn't find the binary react-script start
|
my package.json
the error i get
all my scripts dont work it keeps throwing the same error everytime.
i have cloned the repo in a different location and reinstalled the dependencies but still yarn start wont run.
what could be the problem?
|
[
"try running your project with this yarn run start or just add react-scripts with yarn using this command yarn add react-scripts because maybe react-scripts is not installed for some reason\n"
] |
[
0
] |
[] |
[] |
[
"firebase",
"reactjs",
"visual_studio_code",
"yarn_lock.json"
] |
stackoverflow_0074664343_firebase_reactjs_visual_studio_code_yarn_lock.json.txt
|
Q:
Set line-height as a percentage relative to the parent element
I have a responsive element where it's width and height will both scale. Inside this I have some text which I want to center vertically.
How can I set the text's line-height to be the same as it's parent if I don't know the parent's height?
line-height: 100% is relative to the font's regular height so this doesn't help...
A:
Here's another way to center an element vertically. I came across this technique some time ago. Basically it uses a pseudo element and vertical-align: middle.
.block::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
}
A:
Since it's 2019 already, you could also use flexbox to achieve this :)
To do so, add the following classes to the parent element:
display: flex;
flex-direction: column;
justify-content: center;
See this Fiddle
A:
I'd try putting the text inside another element, of which you know (or set) the size. Then setting relative positioning to it, top, left 50% and negative left and right margins.
See this Fiddle
The only problem is that this relies on a known/fixed textblock. If the text is variable, I'm afraid you will have to resort to using Javascript..
A:
Regarding hyperlinks:
I was having this problem regarding links in main menu. And since it was <a> in <li> tags I needed some surface for the links to be clickable/touchable(see touch target size).
So what I did was for the <ul> I set a fixed height(through it's parent in this case), the <li>-s are a percentage of it and the <a>-s have a min-height and line-height properties set to them and it's easy from there to set the top. The code:
.menu-header-main-container{
position: fixed;
top: 0;
bottom: 160px;
}
.menu-header-main-container ul.menu {
height: 100%; }
.menu-header-main-container ul.menu li {
height: 33.33%;
max-height: 110px; }
.menu-header-main-container ul.menu li a {
line-height: 40px;
min-height: 40px;
top: calc(50% - 20px);
position: relative; } }
A:
You cannot set the line-height to 100% of the parent element's height with only CSS. Rather, you can use CSS to center an element vertically.
.parent {
height:150px;
position:relative;
border:1px solid #FDD;
}
.position-center {
position:absolute;
top:50%;
transform:translateY(-50%);
}
<div class="parent">
<span class="position-center">I am vertically centered element</span>
</div>
A:
Wow, 2022 and I don't think we have a decent way to do this still. What I used to do and I think is the less painful idea is to use a table for layout. Tables will naturally center text vertically, or you can use "vertical-align"
<table style="width: 100%; height: 100%; text-align: center">
<tr><td>Your text</td></tr>
</table>
Not great, but at least you can center text without ever having to specify fixed heights.
|
Set line-height as a percentage relative to the parent element
|
I have a responsive element where it's width and height will both scale. Inside this I have some text which I want to center vertically.
How can I set the text's line-height to be the same as it's parent if I don't know the parent's height?
line-height: 100% is relative to the font's regular height so this doesn't help...
|
[
"Here's another way to center an element vertically. I came across this technique some time ago. Basically it uses a pseudo element and vertical-align: middle.\n.block::before {\n content: '';\n display: inline-block;\n height: 100%;\n vertical-align: middle;\n margin-right: -0.25em; /* Adjusts for spacing */\n}\n\n/* The element to be centered, can\n also be of any width and height */ \n.centered {\n display: inline-block;\n vertical-align: middle;\n width: 300px;\n}\n\n",
"Since it's 2019 already, you could also use flexbox to achieve this :)\nTo do so, add the following classes to the parent element:\ndisplay: flex;\nflex-direction: column;\njustify-content: center;\n\nSee this Fiddle\n",
"I'd try putting the text inside another element, of which you know (or set) the size. Then setting relative positioning to it, top, left 50% and negative left and right margins.\nSee this Fiddle \nThe only problem is that this relies on a known/fixed textblock. If the text is variable, I'm afraid you will have to resort to using Javascript..\n",
"Regarding hyperlinks:\nI was having this problem regarding links in main menu. And since it was <a> in <li> tags I needed some surface for the links to be clickable/touchable(see touch target size). \nSo what I did was for the <ul> I set a fixed height(through it's parent in this case), the <li>-s are a percentage of it and the <a>-s have a min-height and line-height properties set to them and it's easy from there to set the top. The code:\n.menu-header-main-container{\nposition: fixed;\ntop: 0;\nbottom: 160px;\n} \n.menu-header-main-container ul.menu {\n height: 100%; }\n .menu-header-main-container ul.menu li {\n height: 33.33%;\n max-height: 110px; }\n .menu-header-main-container ul.menu li a {\n line-height: 40px;\n min-height: 40px;\n top: calc(50% - 20px);\n position: relative; } }\n\n",
"You cannot set the line-height to 100% of the parent element's height with only CSS. Rather, you can use CSS to center an element vertically.\n\n\n.parent {\n height:150px;\n position:relative;\n border:1px solid #FDD;\n}\n.position-center {\n position:absolute;\n top:50%;\n transform:translateY(-50%);\n}\n<div class=\"parent\">\n <span class=\"position-center\">I am vertically centered element</span>\n</div>\n\n\n\n",
"Wow, 2022 and I don't think we have a decent way to do this still. What I used to do and I think is the less painful idea is to use a table for layout. Tables will naturally center text vertically, or you can use \"vertical-align\"\n <table style=\"width: 100%; height: 100%; text-align: center\">\n <tr><td>Your text</td></tr>\n </table>\n\nNot great, but at least you can center text without ever having to specify fixed heights.\n"
] |
[
89,
19,
1,
1,
0,
0
] |
[] |
[] |
[
"css"
] |
stackoverflow_0012686065_css.txt
|
Q:
C_CPP.intellisense disabled. How to enable again
An extension I had tried in Visual-Studio code appears to have disabled C/C++ intellisense. It can't be turned on again. Modifying the setting in the settings dialog has no effect [evidence: switch source/header leads to a pop up message stating C_CPP.intellisense is set to disabled.].
Spent now several hours on this, the setting even survives uninstalling the software, purging all (known) vs-code related directories or starting a thermonuclear war.
I am getting a bit desperate here. Here are my questions:
Is there a way to wipe everything (short of reinstalling the entire machine)?
Where is the authoritative setting for C-CPP.intellisense? Entry occurs in several locations (User/Remote/....). Is there a priority?
What other mechanisms could interfere with this setting?
Any help is greatly appreciated.
A:
Maybe the effect involved from default setting.json in below directory
C:\Users\chanli\AppData\Roaming\Code\User\settings.json
try add
"C_Cpp.intelliSenseEngine": "Default"
A:
settings -> in search bar search this: C_Cpp.intelliSenseEngine
for me it was "disable" . for solve error set it "default".
after that in any .cpp file click on yellow lamp and change the compiler path to C:\ .... \gcc.exe ( i think any of them are ok to choose )
sorry for my bad english
|
C_CPP.intellisense disabled. How to enable again
|
An extension I had tried in Visual-Studio code appears to have disabled C/C++ intellisense. It can't be turned on again. Modifying the setting in the settings dialog has no effect [evidence: switch source/header leads to a pop up message stating C_CPP.intellisense is set to disabled.].
Spent now several hours on this, the setting even survives uninstalling the software, purging all (known) vs-code related directories or starting a thermonuclear war.
I am getting a bit desperate here. Here are my questions:
Is there a way to wipe everything (short of reinstalling the entire machine)?
Where is the authoritative setting for C-CPP.intellisense? Entry occurs in several locations (User/Remote/....). Is there a priority?
What other mechanisms could interfere with this setting?
Any help is greatly appreciated.
|
[
"Maybe the effect involved from default setting.json in below directory\nC:\\Users\\chanli\\AppData\\Roaming\\Code\\User\\settings.json\ntry add\n\"C_Cpp.intelliSenseEngine\": \"Default\"\n",
"settings -> in search bar search this: C_Cpp.intelliSenseEngine\nfor me it was \"disable\" . for solve error set it \"default\".\nafter that in any .cpp file click on yellow lamp and change the compiler path to C:\\ .... \\gcc.exe ( i think any of them are ok to choose )\nsorry for my bad english\n"
] |
[
1,
0
] |
[] |
[] |
[
"intellisense"
] |
stackoverflow_0066889739_intellisense.txt
|
Q:
python automating data collection issue
Is there any wrong with my code here, when I want to automate collecting some data from the web:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests
from bs4 import BeautifulSoup
od = input('Origin Destination: ')
dp = input('Departure Periode: ')
#op = input('Observation Periode: ')
try:
driver = webdriver.Chrome()
driver.get("http://infare.net/login.aspx")
username= driver.find_element(By.NAME,"loxLogin$UserName")
username.send_keys("username")
password= driver.find_element(By.NAME,"loxLogin$Password")
password.send_keys("password")
login= driver.find_element(By.CLASS_NAME,"LoginSplashButtonStyle")
login.click()
finally:
secure_url = 'http://infare.net/Pages/Analysis/DataDisplay.aspx'
driver.get(secure_url)
req = requests.get(secure_url)
soup = BeautifulSoup(req.text,'html.parser')
#dropdown rute
dropdownbox = driver.find_elements(by=By.TAG_NAME, value="option")
i=0
while i < len(dropdownbox):
if(dropdownbox[i].text == od):
dropdownbox[i].click()
i = i + 1
#departure periode
departure= driver.find_element(By.NAME,"ctl00$cntMain$ucDeparturePeriod$txtDeparturePeriod")
departure.send_keys(dp)
#export.button
search = driver.find_element(By.ID,"ctl00_cntMain_btnSearch")
search.click()
export = driver.find_element(By.NAME,"ctl00$cntMain$btnExport")
export.click()
Can somebody can help? I am newbie on this really
When I run it the browser opens and runs automatically but at the end the browser closes and the process stops with the error message:
"DevTools listening on ws://127.0.0.1:53392/devtools/browser/e110e02e-1957-4409-ae91-f2924ec0af01
[13472:15756:1203/121855.696:ERROR:util.cc(133)] Can't create base directory: C:\Program Files\Google\GoogleUpdater"
process
All processes:
login success
choose the "Data" menu success
data menu
until this process wont run as i expected
Option
My expectation from this code is: It should automatically click on search button to show the data as per option and click on the export button to download the data as csv file.
A:
It looks like there may be a problem with the finally clause in your code. The finally clause is executed whether or not an exception is thrown in the try clause, and it is typically used to clean up resources, such as closing open files or network connections. In your code, the finally clause is executing even when the try clause is successful, which may cause issues.
One way to fix this issue is to move the code in the finally clause to after the try clause, and remove the finally clause entirely. This will ensure that the code in the finally clause is only executed if an exception is thrown in the try clause. Here is an example of how you could modify your code to fix this issue:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests
from bs4 import BeautifulSoup
od = input('Origin Destination: ')
dp = input('Departure Periode: ')
#op = input('Observation Periode: ')
try:
driver = webdriver.Chrome()
driver.get("http://infare.net/login.aspx")
username= driver.find_element(By.NAME,"loxLogin$UserName")
username.send_keys("username")
password= driver.find_element(By.NAME,"loxLogin$Password")
password.send_keys("password")
login= driver.find_element(By.CLASS_NAME,"LoginSplashButtonStyle")
login.click()
except Exception:
# Handle any exceptions thrown in the try clause here.
pass
# Move code from the finally clause here.
secure_url = 'http://infare.net/Pages/Analysis/DataDisplay.aspx'
driver.get(secure_url)
req = requests.get(secure_url)
soup = BeautifulSoup(req.text,'html.parser')
#dropdown rute
dropdownbox = ...
|
python automating data collection issue
|
Is there any wrong with my code here, when I want to automate collecting some data from the web:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests
from bs4 import BeautifulSoup
od = input('Origin Destination: ')
dp = input('Departure Periode: ')
#op = input('Observation Periode: ')
try:
driver = webdriver.Chrome()
driver.get("http://infare.net/login.aspx")
username= driver.find_element(By.NAME,"loxLogin$UserName")
username.send_keys("username")
password= driver.find_element(By.NAME,"loxLogin$Password")
password.send_keys("password")
login= driver.find_element(By.CLASS_NAME,"LoginSplashButtonStyle")
login.click()
finally:
secure_url = 'http://infare.net/Pages/Analysis/DataDisplay.aspx'
driver.get(secure_url)
req = requests.get(secure_url)
soup = BeautifulSoup(req.text,'html.parser')
#dropdown rute
dropdownbox = driver.find_elements(by=By.TAG_NAME, value="option")
i=0
while i < len(dropdownbox):
if(dropdownbox[i].text == od):
dropdownbox[i].click()
i = i + 1
#departure periode
departure= driver.find_element(By.NAME,"ctl00$cntMain$ucDeparturePeriod$txtDeparturePeriod")
departure.send_keys(dp)
#export.button
search = driver.find_element(By.ID,"ctl00_cntMain_btnSearch")
search.click()
export = driver.find_element(By.NAME,"ctl00$cntMain$btnExport")
export.click()
Can somebody can help? I am newbie on this really
When I run it the browser opens and runs automatically but at the end the browser closes and the process stops with the error message:
"DevTools listening on ws://127.0.0.1:53392/devtools/browser/e110e02e-1957-4409-ae91-f2924ec0af01
[13472:15756:1203/121855.696:ERROR:util.cc(133)] Can't create base directory: C:\Program Files\Google\GoogleUpdater"
process
All processes:
login success
choose the "Data" menu success
data menu
until this process wont run as i expected
Option
My expectation from this code is: It should automatically click on search button to show the data as per option and click on the export button to download the data as csv file.
|
[
"It looks like there may be a problem with the finally clause in your code. The finally clause is executed whether or not an exception is thrown in the try clause, and it is typically used to clean up resources, such as closing open files or network connections. In your code, the finally clause is executing even when the try clause is successful, which may cause issues.\nOne way to fix this issue is to move the code in the finally clause to after the try clause, and remove the finally clause entirely. This will ensure that the code in the finally clause is only executed if an exception is thrown in the try clause. Here is an example of how you could modify your code to fix this issue:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport requests\nfrom bs4 import BeautifulSoup\n\nod = input('Origin Destination: ')\ndp = input('Departure Periode: ')\n#op = input('Observation Periode: ')\ntry:\n driver = webdriver.Chrome()\n driver.get(\"http://infare.net/login.aspx\")\n username= driver.find_element(By.NAME,\"loxLogin$UserName\")\n username.send_keys(\"username\")\n password= driver.find_element(By.NAME,\"loxLogin$Password\")\n password.send_keys(\"password\")\n login= driver.find_element(By.CLASS_NAME,\"LoginSplashButtonStyle\")\n login.click()\n\nexcept Exception:\n # Handle any exceptions thrown in the try clause here.\n pass\n\n# Move code from the finally clause here.\nsecure_url = 'http://infare.net/Pages/Analysis/DataDisplay.aspx'\ndriver.get(secure_url)\nreq = requests.get(secure_url)\nsoup = BeautifulSoup(req.text,'html.parser')\n\n#dropdown rute \ndropdownbox = ...\n\n"
] |
[
0
] |
[] |
[] |
[
"forum",
"html",
"python",
"web_scraping"
] |
stackoverflow_0074664317_forum_html_python_web_scraping.txt
|
Q:
How can I make a statement go through even though there's a needed break statement?
My instructions are to help a child their way home. For example if the input is:
R
-JOHN
-L
-KING
-L
-SCHOOL
this means that to get to school from his has he had to turn right on john, left on king, and left to school
The output needs to help him find his way back home an example of this is:
R
KING
-R
-JOHN
-L
-HOME
This means that to get to his house from school he has to turn right on king, right on john, and left to home.
My problem is: I can't seem to try to incorporate all of the restrictions into the output. For the new directions home, I have to get rid of the first destination "school" and do opposite directions from the streets from there. So I tried that and it didn't work, but also, how can I figure out how to print out the directions with home? No directions print when HOME is printed...
directions = []
counter = 0
while True:
direction = input("Enter L or R for the direction: ")
street = input("Enter the street name: ")
if street == "SCHOOL":
break
directions.append((direction, street))
counter += 1
if counter == 3:
break
reversed_directions = []
for direction, street in directions:
if direction == "L":
direction = "R"
elif direction == "R":
direction = "L"
reversed_directions.append((direction, street))
#It was working until I added in this bit
del reversed_directions[0]
reversed_directions.insert(2, "HOME")
print("Original directions:",directions)
print("New directions:",reversed_directions[::-1])
A:
Firstly, you are checking if street is school way early before even appending it. This causes your loop to break and the data for school direction isn't updated.
Next, you don't need to reverse your list again in the end since it is already in the order you require. So remove [::-1]. Here's the fixed code:
directions = []
counter = 0
while True:
direction = input("Enter L or R for the direction: ")
street = input("Enter the street name: ")
directions.append((direction, street))
counter += 1
if counter == 3 or street.casefold == "school":
break
reversed_directions = []
for direction, street in directions:
if direction == "L":
direction = "R"
elif direction == "R":
direction = "L"
reversed_directions.append((direction, street))
del reversed_directions[0]
if directions[0][0] == "L": # update Left or right based on first value
reversed_directions.insert(2, ("R", "HOME"))
else:
reversed_directions.insert(2, ("L", "HOME"))
# used f-strings for ease
print(f"Original directions: {directions}")
print(f"New directions: {reversed_directions}")
Input: [("R", "JOHN"), ("L", "KING"), ("L", "SCHOOL")]
Output:
>>> Original directions: [('R', 'JOHN'), ('L', 'KING'), ('L', 'SCHOOL')]
>>> New directions: [('R', 'KING'), ('R', 'SCHOOL'), ('L', 'HOME')]
|
How can I make a statement go through even though there's a needed break statement?
|
My instructions are to help a child their way home. For example if the input is:
R
-JOHN
-L
-KING
-L
-SCHOOL
this means that to get to school from his has he had to turn right on john, left on king, and left to school
The output needs to help him find his way back home an example of this is:
R
KING
-R
-JOHN
-L
-HOME
This means that to get to his house from school he has to turn right on king, right on john, and left to home.
My problem is: I can't seem to try to incorporate all of the restrictions into the output. For the new directions home, I have to get rid of the first destination "school" and do opposite directions from the streets from there. So I tried that and it didn't work, but also, how can I figure out how to print out the directions with home? No directions print when HOME is printed...
directions = []
counter = 0
while True:
direction = input("Enter L or R for the direction: ")
street = input("Enter the street name: ")
if street == "SCHOOL":
break
directions.append((direction, street))
counter += 1
if counter == 3:
break
reversed_directions = []
for direction, street in directions:
if direction == "L":
direction = "R"
elif direction == "R":
direction = "L"
reversed_directions.append((direction, street))
#It was working until I added in this bit
del reversed_directions[0]
reversed_directions.insert(2, "HOME")
print("Original directions:",directions)
print("New directions:",reversed_directions[::-1])
|
[
"Firstly, you are checking if street is school way early before even appending it. This causes your loop to break and the data for school direction isn't updated.\nNext, you don't need to reverse your list again in the end since it is already in the order you require. So remove [::-1]. Here's the fixed code:\ndirections = []\ncounter = 0\nwhile True:\n direction = input(\"Enter L or R for the direction: \")\n street = input(\"Enter the street name: \")\n directions.append((direction, street))\n counter += 1\n if counter == 3 or street.casefold == \"school\":\n break\n\nreversed_directions = []\nfor direction, street in directions:\n if direction == \"L\":\n direction = \"R\"\n elif direction == \"R\":\n direction = \"L\"\n reversed_directions.append((direction, street))\n\ndel reversed_directions[0]\nif directions[0][0] == \"L\": # update Left or right based on first value\n reversed_directions.insert(2, (\"R\", \"HOME\"))\nelse:\n reversed_directions.insert(2, (\"L\", \"HOME\"))\n# used f-strings for ease\nprint(f\"Original directions: {directions}\")\nprint(f\"New directions: {reversed_directions}\")\n\nInput: [(\"R\", \"JOHN\"), (\"L\", \"KING\"), (\"L\", \"SCHOOL\")]\nOutput:\n>>> Original directions: [('R', 'JOHN'), ('L', 'KING'), ('L', 'SCHOOL')]\n>>> New directions: [('R', 'KING'), ('R', 'SCHOOL'), ('L', 'HOME')]\n\n"
] |
[
0
] |
[] |
[] |
[
"counter",
"list",
"python"
] |
stackoverflow_0074664350_counter_list_python.txt
|
Q:
Using multiple datasets in Gridspec
I am trying to create subplot inside a subplot, and I have found some code which can do this using the gridspec method. I have managed to fix the code so the figures are displayed as I want, but I can't figure out how to get a different dataset in each sub-figure.
This is what I have:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(10, 8))
outer = gridspec.GridSpec(2, 2, wspace=0.1, hspace=0.1)
for i in range(4):
inner = gridspec.GridSpecFromSubplotSpec(4, 1,
subplot_spec=outer[i], wspace=0.1, hspace=0.1)
for j in range(4):
ax = plt.Subplot(fig, inner[j])
a = ax.plot(df)
t.set_ha('center')
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
I have tried multiple options to achieve what I want without success.
IF anyone could help with this I would appreciate it.
Thanks.
A:
I have managed to solve my problem now. What I did was, instead of trying to put multple ax.plot() lines or putting multiple DataFrames inside ax.plot(df1, df2, df3) etc. I created a list which I put inside the For Loop. I also created a column variable to go in the "inner loop".
If using Nested Loops like this, the value that changes horizontally must go in the outer loop while the value that changes vertically must go in the inner loop.
In my case, the first subplot contains four different columns from the same DataFrame, the second contains four different columns for another DataFrame, and so on.
This is how it is implemented in the code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
residual_list = (['df_168h', 'residuals_168', 'residuals_168_d', 'residuals_168_weekend'])
fig = plt.figure(figsize=(10, 8))
outer = gridspec.GridSpec(2, 2, wspace=0.1, hspace=0.1)
for i, s in zip(range(4), residual_list):
inner = gridspec.GridSpecFromSubplotSpec(4, 1,
subplot_spec=outer[i], wspace=0.1, hspace=0.1)
for j, column in zip(range(4), df_168h):
ax = plt.Subplot(fig, inner[j])
a = ax.plot(locals()[s][column])
t.set_ha('center')
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
|
Using multiple datasets in Gridspec
|
I am trying to create subplot inside a subplot, and I have found some code which can do this using the gridspec method. I have managed to fix the code so the figures are displayed as I want, but I can't figure out how to get a different dataset in each sub-figure.
This is what I have:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(10, 8))
outer = gridspec.GridSpec(2, 2, wspace=0.1, hspace=0.1)
for i in range(4):
inner = gridspec.GridSpecFromSubplotSpec(4, 1,
subplot_spec=outer[i], wspace=0.1, hspace=0.1)
for j in range(4):
ax = plt.Subplot(fig, inner[j])
a = ax.plot(df)
t.set_ha('center')
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
I have tried multiple options to achieve what I want without success.
IF anyone could help with this I would appreciate it.
Thanks.
|
[
"I have managed to solve my problem now. What I did was, instead of trying to put multple ax.plot() lines or putting multiple DataFrames inside ax.plot(df1, df2, df3) etc. I created a list which I put inside the For Loop. I also created a column variable to go in the \"inner loop\".\nIf using Nested Loops like this, the value that changes horizontally must go in the outer loop while the value that changes vertically must go in the inner loop.\nIn my case, the first subplot contains four different columns from the same DataFrame, the second contains four different columns for another DataFrame, and so on.\nThis is how it is implemented in the code:\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nresidual_list = (['df_168h', 'residuals_168', 'residuals_168_d', 'residuals_168_weekend'])\n\nfig = plt.figure(figsize=(10, 8))\nouter = gridspec.GridSpec(2, 2, wspace=0.1, hspace=0.1)\n\n\nfor i, s in zip(range(4), residual_list):\n inner = gridspec.GridSpecFromSubplotSpec(4, 1,\n subplot_spec=outer[i], wspace=0.1, hspace=0.1)\n\n for j, column in zip(range(4), df_168h):\n ax = plt.Subplot(fig, inner[j])\n a = ax.plot(locals()[s][column])\n t.set_ha('center')\n ax.set_xticks([])\n ax.set_yticks([])\n fig.add_subplot(ax)\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"subplot"
] |
stackoverflow_0074661191_python_subplot.txt
|
Q:
How to install OpenCV in Mac M1?
My goal is to install $ pip install opencv-python in Mac M1. The problem is I don't know opencv, so I would like to learn from the Getting Started Page. However, the very first code of opencv throws me an error.
What I've did:
$ pip install opencv-python -> same error
$ pip uninstall opencv-python -> $ pip install opencv-contrib-python -> same error.
import cv2 as cv
import sys
img = cv.imread(cv.samples.findFile("starry_night.jpg"))
if img is None:
sys.exit("Could not read the image.")
cv.imshow("Display window", img)
k = cv.waitKey(0)
if k == ord("s"):
cv.imwrite("starry_night.png", img)
error
[ WARN:[email protected]] global /Users/xperience/actions-runner/_work/opencv-python/opencv-python/opencv/modules/core/src/utils/samples.cpp (61) findFile cv::samples::findFile('starry_night.jpg') => ''
---------------------------------------------------------------------------
error Traceback (most recent call last)
Cell In [1], line 3
1 import cv2 as cv
2 import sys
----> 3 img = cv.imread(cv.samples.findFile("starry_night.jpg"))
4 if img is None:
5 sys.exit("Could not read the image.")
error: OpenCV(4.6.0) /Users/xperience/actions-runner/_work/opencv-python/opencv-python/opencv/modules/core/src/utils/samples.cpp:64: error: (-2:Unspecified error) OpenCV samples: Can't find required data file: starry_night.jpg in function 'findFile'
A:
It looks like the cv.imread() function is unable to find the image file "starry_night.jpg" in your current directory. This is likely because the findFile() function is returning an empty string, which indicates that the file could not be found.
To fix this issue, you will need to make sure that the "starry_night.jpg" file exists in your current working directory. You can verify this by running ls in your terminal to list all files in the current directory, or by using the os.path.exists() function in Python to check if the file exists.
Once you have confirmed that the file exists in your current directory, you can try modifying the code to specify the full path to the image file instead of relying on the findFile() function. For example:
import cv2 as cv
import os
# Replace "/path/to/image/file" with the full path to your "starry_night.jpg" file
img_path = "/path/to/image/file/starry_night.jpg"
# Check if the file exists
if not os.path.exists(img_path):
sys.exit("Error: File not found.")
# Read the image file
img = cv.imread(img_path)
# Check if the image was successfully read
if img is None:
sys.exit("Error: Could not read the image.")
# Display the image
cv.imshow("Display window", img)
# Wait for a key press and save the image if "s" is pressed
k = cv.waitKey(0)
...
|
How to install OpenCV in Mac M1?
|
My goal is to install $ pip install opencv-python in Mac M1. The problem is I don't know opencv, so I would like to learn from the Getting Started Page. However, the very first code of opencv throws me an error.
What I've did:
$ pip install opencv-python -> same error
$ pip uninstall opencv-python -> $ pip install opencv-contrib-python -> same error.
import cv2 as cv
import sys
img = cv.imread(cv.samples.findFile("starry_night.jpg"))
if img is None:
sys.exit("Could not read the image.")
cv.imshow("Display window", img)
k = cv.waitKey(0)
if k == ord("s"):
cv.imwrite("starry_night.png", img)
error
[ WARN:[email protected]] global /Users/xperience/actions-runner/_work/opencv-python/opencv-python/opencv/modules/core/src/utils/samples.cpp (61) findFile cv::samples::findFile('starry_night.jpg') => ''
---------------------------------------------------------------------------
error Traceback (most recent call last)
Cell In [1], line 3
1 import cv2 as cv
2 import sys
----> 3 img = cv.imread(cv.samples.findFile("starry_night.jpg"))
4 if img is None:
5 sys.exit("Could not read the image.")
error: OpenCV(4.6.0) /Users/xperience/actions-runner/_work/opencv-python/opencv-python/opencv/modules/core/src/utils/samples.cpp:64: error: (-2:Unspecified error) OpenCV samples: Can't find required data file: starry_night.jpg in function 'findFile'
|
[
"It looks like the cv.imread() function is unable to find the image file \"starry_night.jpg\" in your current directory. This is likely because the findFile() function is returning an empty string, which indicates that the file could not be found.\nTo fix this issue, you will need to make sure that the \"starry_night.jpg\" file exists in your current working directory. You can verify this by running ls in your terminal to list all files in the current directory, or by using the os.path.exists() function in Python to check if the file exists.\nOnce you have confirmed that the file exists in your current directory, you can try modifying the code to specify the full path to the image file instead of relying on the findFile() function. For example:\nimport cv2 as cv\nimport os\n\n# Replace \"/path/to/image/file\" with the full path to your \"starry_night.jpg\" file\nimg_path = \"/path/to/image/file/starry_night.jpg\"\n\n# Check if the file exists\nif not os.path.exists(img_path):\n sys.exit(\"Error: File not found.\")\n\n# Read the image file\nimg = cv.imread(img_path)\n\n# Check if the image was successfully read\nif img is None:\n sys.exit(\"Error: Could not read the image.\")\n\n# Display the image\ncv.imshow(\"Display window\", img)\n\n# Wait for a key press and save the image if \"s\" is pressed\nk = cv.waitKey(0)\n...\n\n"
] |
[
0
] |
[] |
[] |
[
"apple_m1",
"opencv",
"python"
] |
stackoverflow_0074664356_apple_m1_opencv_python.txt
|
Q:
How to get rid of error messages in nushell?
In Bash I would do something like
...
...
if ! cd non_exist_dir > /dev/null 2>&1; then
echo "error in cd"
return 1
fi
...
...
How would I do that in idiomatic nushell ?
Especially, how can I get rid of the annoying error message displayed by nushell because the directory doesn't exist ?
Bonus points if I could get something like a "return" command, which seems to be missing in nushell.
A:
One solution is to create a custom command something like this.
def-env mycd [path] {
let p = (if ($path | path exists) { $path } else { $env.PWD })
cd $p
}
This solves part of the problem, getting rid of the error message by checking if the folder exists, and if it does, it uses that path. If it doesn't exist, it just uses your current directory.
This doesn't solve the second part, returning, but one could foresee setting $env.LAST_EXIT_CODE to some value. You'd have to play around a bit to see if that works and fits your needs. Good luck.
A:
Nushell 0.72 introduces try/catch blocks which can suppress or replace the error handling for Nushell builtins. For your example:
try {
cd non_exist_dir
} catch {
print -e "error in cd"
}
As for the other part of your question, a return code would only seem to be useful if are returning to a non-Nushell process. Any error handling from within Nushell can use Nushell errors and try/catch blocks.
But if you are returning to a non-Nushell process, then you can use the exit <status_code> builtin.
This would only work in either:
A script
An invocation of nu -c "<commands>"
However, a simple cd could never work in either case, since both cases start a new Nushell shell (try saying that 10 times real fast), and when that shell exits, the environment will be returned to its entry state (even with def-env).
But if you are doing something after the cd, then it would make sense to include this in a script. For example, a silly_cd.nu (silly, because it's pretty useless other than as a demonstration of exit):
#!/usr/bin/env nu
def main [d?: string] {
if ($d == null) {
# Prevent sourced function from exiting Nushell
return
}
try {
cd $d
} catch {
print -e "Error in cd"
exit 1
}
ls
}
|
How to get rid of error messages in nushell?
|
In Bash I would do something like
...
...
if ! cd non_exist_dir > /dev/null 2>&1; then
echo "error in cd"
return 1
fi
...
...
How would I do that in idiomatic nushell ?
Especially, how can I get rid of the annoying error message displayed by nushell because the directory doesn't exist ?
Bonus points if I could get something like a "return" command, which seems to be missing in nushell.
|
[
"One solution is to create a custom command something like this.\ndef-env mycd [path] {\n let p = (if ($path | path exists) { $path } else { $env.PWD })\n cd $p\n}\n\nThis solves part of the problem, getting rid of the error message by checking if the folder exists, and if it does, it uses that path. If it doesn't exist, it just uses your current directory.\nThis doesn't solve the second part, returning, but one could foresee setting $env.LAST_EXIT_CODE to some value. You'd have to play around a bit to see if that works and fits your needs. Good luck.\n",
"Nushell 0.72 introduces try/catch blocks which can suppress or replace the error handling for Nushell builtins. For your example:\ntry {\n cd non_exist_dir\n} catch {\n print -e \"error in cd\"\n}\n\nAs for the other part of your question, a return code would only seem to be useful if are returning to a non-Nushell process. Any error handling from within Nushell can use Nushell errors and try/catch blocks.\nBut if you are returning to a non-Nushell process, then you can use the exit <status_code> builtin.\nThis would only work in either:\n\nA script\nAn invocation of nu -c \"<commands>\"\n\nHowever, a simple cd could never work in either case, since both cases start a new Nushell shell (try saying that 10 times real fast), and when that shell exits, the environment will be returned to its entry state (even with def-env).\nBut if you are doing something after the cd, then it would make sense to include this in a script. For example, a silly_cd.nu (silly, because it's pretty useless other than as a demonstration of exit):\n#!/usr/bin/env nu\ndef main [d?: string] {\n if ($d == null) {\n # Prevent sourced function from exiting Nushell\n return\n }\n try {\n cd $d\n } catch {\n print -e \"Error in cd\"\n exit 1\n }\n ls\n}\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"nushell"
] |
stackoverflow_0074509786_nushell.txt
|
Q:
Is it possible to programmatically add an image file to an image or commandbutton control in a vba userform? - SOLVED
I am trying to get a image to load programmatically into image and commandbutton MSForms controls to no avail without the VB editor. I am using the macro structure below which works well with other controls. Microsoft indicates here that the editor must be used:
You must use the control's property page to assign a bitmap to the
Picture property. You cannot use the Visual Basic LoadPicture function
to assign a bitmap to Picture.
The macro below works when the .Picture command is commented out without image of course. When loading an image into a commandbutton the same problem occurs. I have tried various ways to provide the file location but it always errors out. Does someone know a clever work around?
Sub NewForm()
Dim TempForm As Object
Dim NewImage As MSForms.Image
Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(3)
With TempForm
.Properties("Height") = 300
.Properties("Width") = 300
End With
Set NewImage = TempForm.designer.Controls.Add("Forms.image.1")
With NewImage
.Picture = "C:\image.jpg" 'Nothing works here it seems
.Height = 100
.Left = 100
.Top = 100
.Width = 100
End With
End Sub
A:
Below is an example to add Images to Image and Command Button.
Three changes that I made
I changed Dim NewImage As MSForms.Image to Dim NewImage As Object. Using Dim NewImage As Image will also work.
I used an image from my pc.
I used LoadPicture().
Is this what you are trying?
Option Explicit
Sub NewForm()
Dim TempForm As Object
Dim NewImage As Object
Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(3)
With TempForm
.Properties("Height") = 300
.Properties("Width") = 300
End With
'~~> Image Control
Set NewImage = TempForm.designer.Controls.Add("Forms.image.1")
With NewImage
.Picture = LoadPicture("C:\Users\routs\Desktop\Start.Bmp")
.Height = 100
.Left = 100
.Top = 10
.Width = 100
End With
'~~> Command Button
Dim ctl_Command As Control
Set ctl_Command = TempForm.designer.Controls.Add("Forms.CommandButton.1", "CmdXYZ", False)
With ctl_Command
.Picture = LoadPicture("C:\Users\routs\Desktop\Start.Bmp")
.Left = 100
.Top = 140
.Height = 50
.Width = 50
.Visible = True
End With
End Sub
In Action
|
Is it possible to programmatically add an image file to an image or commandbutton control in a vba userform? - SOLVED
|
I am trying to get a image to load programmatically into image and commandbutton MSForms controls to no avail without the VB editor. I am using the macro structure below which works well with other controls. Microsoft indicates here that the editor must be used:
You must use the control's property page to assign a bitmap to the
Picture property. You cannot use the Visual Basic LoadPicture function
to assign a bitmap to Picture.
The macro below works when the .Picture command is commented out without image of course. When loading an image into a commandbutton the same problem occurs. I have tried various ways to provide the file location but it always errors out. Does someone know a clever work around?
Sub NewForm()
Dim TempForm As Object
Dim NewImage As MSForms.Image
Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(3)
With TempForm
.Properties("Height") = 300
.Properties("Width") = 300
End With
Set NewImage = TempForm.designer.Controls.Add("Forms.image.1")
With NewImage
.Picture = "C:\image.jpg" 'Nothing works here it seems
.Height = 100
.Left = 100
.Top = 100
.Width = 100
End With
End Sub
|
[
"Below is an example to add Images to Image and Command Button.\nThree changes that I made\n\nI changed Dim NewImage As MSForms.Image to Dim NewImage As Object. Using Dim NewImage As Image will also work.\nI used an image from my pc.\nI used LoadPicture().\n\nIs this what you are trying?\nOption Explicit\n\nSub NewForm()\n Dim TempForm As Object\n Dim NewImage As Object\n\n Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(3)\n With TempForm\n .Properties(\"Height\") = 300\n .Properties(\"Width\") = 300\n End With\n \n '~~> Image Control\n Set NewImage = TempForm.designer.Controls.Add(\"Forms.image.1\")\n With NewImage\n .Picture = LoadPicture(\"C:\\Users\\routs\\Desktop\\Start.Bmp\")\n .Height = 100\n .Left = 100\n .Top = 10\n .Width = 100\n End With\n \n '~~> Command Button\n Dim ctl_Command As Control\n Set ctl_Command = TempForm.designer.Controls.Add(\"Forms.CommandButton.1\", \"CmdXYZ\", False)\n \n With ctl_Command\n .Picture = LoadPicture(\"C:\\Users\\routs\\Desktop\\Start.Bmp\")\n .Left = 100\n .Top = 140\n .Height = 50\n .Width = 50\n .Visible = True\n End With\nEnd Sub\n\nIn Action\n\n"
] |
[
2
] |
[] |
[] |
[
"excel",
"image",
"programmatically",
"userform",
"vba"
] |
stackoverflow_0074664316_excel_image_programmatically_userform_vba.txt
|
Q:
How to write by column rather than rows - Python to CSV
I want to write my python list all_results to CSV. However when I use the following code, it saves each individual record in rows rather than columns.
import csv
fh = open('output.csv', 'w')
cvs_writer = csv.writer(fh)
# write one row with headers (using `writerow` without `s` at the end)
cvs_writer.writerow(["Column 1"])
# write many rows with results (using `writerows` with `s` at the end)
cvs_writer.writerows([all_results])
fh.close()
Output
|Column 1|
|row 1| |row 2| |row 3| |row 4| |row 5| |row 6| ---
Expected Output
|Column 1|
|row 1|
|row 2|
|row 3|
|row 4|
|row 5|
|row 6|
A:
To write all rows in a single column, you can use a list comprehension to create a list of lists, where each inner list contains a single item. You can then write the resulting list using the writerows method of the csv module.
Here is an example:
import csv
# Create a list of lists, where each inner list contains a single item
all_results = [[result] for result in all_results]
# Open the file in write mode
with open('output.csv', 'w') as fh:
# Create a CSV writer
cvs_writer = csv.writer(fh)
# Write the headers
cvs_writer.writerow(["Column 1"])
# Write the rows
cvs_writer.writerows(all_results)
This code will write the all_results list to a CSV file, with each item in the list appearing in a separate row in the first column.
|
How to write by column rather than rows - Python to CSV
|
I want to write my python list all_results to CSV. However when I use the following code, it saves each individual record in rows rather than columns.
import csv
fh = open('output.csv', 'w')
cvs_writer = csv.writer(fh)
# write one row with headers (using `writerow` without `s` at the end)
cvs_writer.writerow(["Column 1"])
# write many rows with results (using `writerows` with `s` at the end)
cvs_writer.writerows([all_results])
fh.close()
Output
|Column 1|
|row 1| |row 2| |row 3| |row 4| |row 5| |row 6| ---
Expected Output
|Column 1|
|row 1|
|row 2|
|row 3|
|row 4|
|row 5|
|row 6|
|
[
"To write all rows in a single column, you can use a list comprehension to create a list of lists, where each inner list contains a single item. You can then write the resulting list using the writerows method of the csv module.\nHere is an example:\nimport csv\n\n# Create a list of lists, where each inner list contains a single item\nall_results = [[result] for result in all_results]\n\n# Open the file in write mode\nwith open('output.csv', 'w') as fh:\n # Create a CSV writer\n cvs_writer = csv.writer(fh)\n\n # Write the headers\n cvs_writer.writerow([\"Column 1\"])\n\n # Write the rows\n cvs_writer.writerows(all_results)\n\nThis code will write the all_results list to a CSV file, with each item in the list appearing in a separate row in the first column.\n"
] |
[
1
] |
[] |
[] |
[
"export_to_csv",
"python"
] |
stackoverflow_0074664313_export_to_csv_python.txt
|
Q:
How to disable using cache results in Redshift Query?
I am interested in performance testing my query in Redshift.
I would like to disable the query from using any cached results from prior queries. In other words, I would like the query to run from scratch. Is it possible to disable cached results only for the execution of my query?
I would not like to disable cached results for the entire database/all queries.
A:
SET enable_result_cache_for_session TO OFF;
From enable_result_cache_for_session - Amazon Redshift:
Specifies whether to use query results caching. If enable_result_cache_for_session is on, Amazon Redshift checks for a valid, cached copy of the query results when a query is submitted. If a match is found in the result cache, Amazon Redshift uses the cached results and doesn’t execute the query. If enable_result_cache_for_session is off, Amazon Redshift ignores the results cache and executes all queries when they are submitted.
A:
Ran across this during a benchmark today and wanted to add an alternative to this. The benchmark tool I was using has a setup and teardown, but they don't run in the same session/transaction, so the enable_result_cache_for_session setting was having no effect. So I had to get a little clever.
From the Redshift documentation:
Amazon Redshift uses cached results for a new query when all of the following are true:
The user submitting the query has access permission to the objects used in the query.
The table or views in the query haven't been modified.
The query doesn't use a function that must be evaluated each time it's run, such as GETDATE.
The query doesn't reference Amazon Redshift Spectrum external tables.
Configuration parameters that might affect query results are unchanged.
The query syntactically matches the cached query.
In my case, I just added a GETDATE() column to the query to force it to not use the result cache on each run.
|
How to disable using cache results in Redshift Query?
|
I am interested in performance testing my query in Redshift.
I would like to disable the query from using any cached results from prior queries. In other words, I would like the query to run from scratch. Is it possible to disable cached results only for the execution of my query?
I would not like to disable cached results for the entire database/all queries.
|
[
"SET enable_result_cache_for_session TO OFF;\n\nFrom enable_result_cache_for_session - Amazon Redshift:\n\nSpecifies whether to use query results caching. If enable_result_cache_for_session is on, Amazon Redshift checks for a valid, cached copy of the query results when a query is submitted. If a match is found in the result cache, Amazon Redshift uses the cached results and doesn’t execute the query. If enable_result_cache_for_session is off, Amazon Redshift ignores the results cache and executes all queries when they are submitted.\n\n",
"Ran across this during a benchmark today and wanted to add an alternative to this. The benchmark tool I was using has a setup and teardown, but they don't run in the same session/transaction, so the enable_result_cache_for_session setting was having no effect. So I had to get a little clever.\nFrom the Redshift documentation:\n\nAmazon Redshift uses cached results for a new query when all of the following are true:\n\nThe user submitting the query has access permission to the objects used in the query.\n\nThe table or views in the query haven't been modified.\n\nThe query doesn't use a function that must be evaluated each time it's run, such as GETDATE.\n\nThe query doesn't reference Amazon Redshift Spectrum external tables.\n\nConfiguration parameters that might affect query results are unchanged.\n\nThe query syntactically matches the cached query.\n\n\n\nIn my case, I just added a GETDATE() column to the query to force it to not use the result cache on each run.\n"
] |
[
19,
0
] |
[] |
[] |
[
"amazon_redshift",
"amazon_web_services",
"sql"
] |
stackoverflow_0054805231_amazon_redshift_amazon_web_services_sql.txt
|
Q:
I want to split string without using split function?
I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
A:
Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.
You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.
A:
I'm going to assume that this is homework, so I will only give snippets as hints:
Finding indices of all occurrences of a given substring
Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:
String text = "012ab567ab0123ab";
// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
String API links
int indexOf(String, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.
Related questions
Searching for one string in another string
Extracting substrings at given indices out of a string
This snippet extracts substring at given indices out of a string and puts them into a List<String>:
String text = "0123456789abcdefghij";
List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));
System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"
String[] partsArray = parts.toArray(new String[0]);
Some key ideas:
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Works especially nicely if you don't know how many parts there'll be in advance
String API links
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Related questions
Fill array with List data
A:
You do now that most of the java standard libraries are open source
In this case you can start here
A:
This is the right answer
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
A:
Use String tokenizer to split strings in Java without split:
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
A:
/**
* My method split without javas split.
* Return array with words after mySplit from two texts;
* Uses trim.
*/
public class NoJavaSplit {
public static void main(String[] args) {
String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}
private static String [] mySplit(String text1, String text2) {
text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
A:
you can try, the way i did `{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(int i = 0; i <str.length();i++) {
if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string
System.out.println();
continue;
}
System.out.print(str.charAt(i));
}
sc.close();
}`
A:
The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?
A:
The way to go is to define the function you need first. In this case, it would probably be:
String[] split(String s, String separator)
The return type doesn't have to be an array. It can also be a list:
List<String> split(String s, String separator)
The code would then be roughly as follows:
start at the beginning
find the next occurence of the delimiter
the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
continue with step 2 until you have reached the end of the string
There are many fine points that you need to consider:
What happens if the string starts or ends with the delimiter?
What if multiple delimiters appear next to each other?
What should be the result of splitting the empty string? (1 empty field or 0 fields)
A:
You can do it using Java standard libraries.
Say the delimiter is : and
String s = "Harry:Potter"
int a = s.find(delimiter);
and then add
s.substring(start, a)
to a new String array.
Keep doing this till your start < string length
Should be enough I guess.
A:
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
A:
public class WithoutSpit_method {
public static void main(String arg[])
{
char[]str;
String s="Computer_software_developer_gautam";
String s1[];
for(int i=0;i<s.length()-1;)
{
int lengh=s.indexOf("_",i);
if(lengh==-1)
{
lengh=s.length();
}
System.out.print(" "+s.substring(i,lengh));
i=lengh+1;
}
}
}
Result: Computer software developer gautam
A:
Here is my way of doing with Scanner;
import java.util.Scanner;
public class spilt {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String to be Spilted : ");
String st = input.nextLine();
Scanner str = new Scanner(st);
while (str.hasNext())
{
System.out.println(str.next());
}
}
}
Hope it Helps!!!!!
A:
public class StringWitoutPre {
public static void main(String[] args) {
String str = "md taufique reja";
int len = str.length();
char ch[] = str.toCharArray();
String tmp = " ";
boolean flag = false;
for (int i = 0; i < str.length(); i++) {
if (ch[i] != ' ') {
tmp = tmp + ch[i];
flag = false;
} else {
flag = true;
}
if (flag || i == len - 1) {
System.out.println(tmp);
tmp = " ";
}
}
}
}
A:
In Java8 we can use Pattern and get the things done in more easy way. Here is the code.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
A:
static void splitString(String s, int index) {
char[] firstPart = new char[index];
char[] secondPart = new char[s.length() - index];
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (i < index) {
firstPart[i] = s.charAt(i);
} else {
secondPart[j] = s.charAt(i);
if (j < s.length()-index) {
j++;
}
}
}
System.out.println(firstPart);
System.out.println(secondPart);
}
A:
import java.util.Scanner;
public class Split {
static Scanner in = new Scanner(System.in);
static void printArray(String[] array){
for (int i = 0; i < array.length; i++) {
if(i!=array.length-1)
System.out.print(array[i]+",");
else
System.out.println(array[i]);
}
}
static String delimeterTrim(String str){
char ch = str.charAt(str.length()-1);
if(ch=='.'||ch=='!'||ch==';'){
str = str.substring(0,str.length()-1);
}
return str;
}
private static String [] mySplit(String text, char reg, boolean delimiterTrim) {
if(delimiterTrim){
text = delimeterTrim(text);
}
text = text.trim() + " ";
int massValue = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reg) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text.length(); j++) {
if (text.charAt(j) == reg) {
splitArray[i] = text.substring(0, j);
text = text.substring(j + 1, text.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the sentence :");
String text = in.nextLine();
//System.out.println("Enter the regex character :");
//char regex = in.next().charAt(0);
System.out.println("Do you want to trim the delimeter ?");
String delch = in.next();
boolean ch = false;
if(delch.equalsIgnoreCase("yes")){
ch = true;
}
System.out.println("Output String array is : ");
printArray(mySplit(text,' ',ch));
}
}
|
I want to split string without using split function?
|
I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
|
[
"Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.\nYou will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.\n",
"I'm going to assume that this is homework, so I will only give snippets as hints:\nFinding indices of all occurrences of a given substring\nHere's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:\nString text = \"012ab567ab0123ab\";\n\n// finding all occurrences forward: Method #1\nfor (int i = text.indexOf(\"ab\"); i != -1; i = text.indexOf(\"ab\", i+1)) {\n System.out.println(i);\n} // prints \"3\", \"8\", \"14\"\n\n// finding all occurrences forward: Method #2\nfor (int i = -1; (i = text.indexOf(\"ab\", i+1)) != -1; ) {\n System.out.println(i);\n} // prints \"3\", \"8\", \"14\"\n\nString API links\n\nint indexOf(String, int fromIndex)\n\nReturns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.\n\n\nRelated questions\n\nSearching for one string in another string\n\n\nExtracting substrings at given indices out of a string\nThis snippet extracts substring at given indices out of a string and puts them into a List<String>:\nString text = \"0123456789abcdefghij\";\n\nList<String> parts = new ArrayList<String>();\nparts.add(text.substring(0, 5));\nparts.add(text.substring(3, 7));\nparts.add(text.substring(9, 13));\nparts.add(text.substring(18, 20));\n\nSystem.out.println(parts); // prints \"[01234, 3456, 9abc, ij]\"\n\nString[] partsArray = parts.toArray(new String[0]);\n\nSome key ideas:\n\nEffective Java 2nd Edition, Item 25: Prefer lists to arrays\n\nWorks especially nicely if you don't know how many parts there'll be in advance\n\n\nString API links\n\nString substring(int beginIndex, int endIndex)\n\nReturns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.\n\n\nRelated questions\n\nFill array with List data\n\n",
"You do now that most of the java standard libraries are open source \nIn this case you can start here\n",
"This is the right answer\nimport java.util.StringTokenizer;\n\npublic class tt {\n public static void main(String a[]){\n String s = \"012ab567ab0123ab\";\n\n String delims = \"ab \";\n\n StringTokenizer st = new StringTokenizer(s, delims);\n System.out.println(\"No of Token = \" + st.countTokens());\n\n while (st.hasMoreTokens())\n {\n System.out.println(st.nextToken());\n }\n\n }\n\n}\n\n",
"Use String tokenizer to split strings in Java without split:\nimport java.util.StringTokenizer;\n\npublic class tt {\n public static void main(String a[]){\n String s = \"012ab567ab0123ab\";\n String delims = \"ab \";\n StringTokenizer st = new StringTokenizer(s, delims);\n System.out.println(\"No of Token = \" + st.countTokens());\n while (st.hasMoreTokens()) {\n System.out.println(st.nextToken());\n }\n }\n}\n\n",
"/**\n * My method split without javas split.\n * Return array with words after mySplit from two texts;\n * Uses trim.\n */\n\npublic class NoJavaSplit {\n\n public static void main(String[] args) {\n String text1 = \"Some text for example \";\n String text2 = \" Second sentences \";\n System.out.println(Arrays.toString(mySplit(text1, text2)));\n }\n\n private static String [] mySplit(String text1, String text2) {\n text1 = text1.trim() + \" \" + text2.trim() + \" \";\n char n = ' ';\n int massValue = 0;\n for (int i = 0; i < text1.length(); i++) {\n if (text1.charAt(i) == n) {\n massValue++;\n }\n }\n String[] splitArray = new String[massValue];\n for (int i = 0; i < splitArray.length; ) {\n for (int j = 0; j < text1.length(); j++) {\n if (text1.charAt(j) == n) {\n splitArray[i] = text1.substring(0, j);\n text1 = text1.substring(j + 1, text1.length());\n j = 0;\n i++;\n }\n }\n return splitArray;\n }\n return null;\n }\n}\n\n",
"you can try, the way i did `{\npublic static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n String str = sc.nextLine();\n\n for(int i = 0; i <str.length();i++) {\n if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string\n System.out.println();\n continue;\n }\n System.out.print(str.charAt(i));\n }\n sc.close();\n}` \n\n",
"The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?\n",
"The way to go is to define the function you need first. In this case, it would probably be:\nString[] split(String s, String separator)\n\nThe return type doesn't have to be an array. It can also be a list:\nList<String> split(String s, String separator)\n\nThe code would then be roughly as follows:\n\nstart at the beginning\nfind the next occurence of the delimiter\nthe substring between the end of the previous delimiter and the start of the current delimiter is added to the result\ncontinue with step 2 until you have reached the end of the string\n\nThere are many fine points that you need to consider:\n\nWhat happens if the string starts or ends with the delimiter?\nWhat if multiple delimiters appear next to each other?\nWhat should be the result of splitting the empty string? (1 empty field or 0 fields)\n\n",
"You can do it using Java standard libraries. \nSay the delimiter is : and\nString s = \"Harry:Potter\"\nint a = s.find(delimiter);\n\nand then add \ns.substring(start, a)\n\nto a new String array.\nKeep doing this till your start < string length\nShould be enough I guess.\n",
"public class MySplit {\n\npublic static String[] mySplit(String text,String delemeter){\n java.util.List<String> parts = new java.util.ArrayList<String>();\n text+=delemeter; \n\n for (int i = text.indexOf(delemeter), j=0; i != -1;) {\n parts.add(text.substring(j,i));\n j=i+delemeter.length();\n i = text.indexOf(delemeter,j);\n }\n\n\n return parts.toArray(new String[0]);\n}\n\npublic static void main(String[] args) {\n String str=\"012ab567ab0123ab\";\n String delemeter=\"ab\";\n String result[]=mySplit(str,delemeter);\n for(String s:result)\n System.out.println(s);\n}\n\n}\n\n",
"public class WithoutSpit_method {\n public static void main(String arg[])\n {\n\n char[]str;\n String s=\"Computer_software_developer_gautam\";\n String s1[];\n for(int i=0;i<s.length()-1;)\n {\n int lengh=s.indexOf(\"_\",i); \n if(lengh==-1)\n {\n lengh=s.length();\n }\n System.out.print(\" \"+s.substring(i,lengh));\n i=lengh+1;\n }\n\n }\n}\n\nResult: Computer software developer gautam\n",
"Here is my way of doing with Scanner;\nimport java.util.Scanner;\n\npublic class spilt {\n\n public static void main(String[] args)\n {\n Scanner input = new Scanner(System.in);\n System.out.print(\"Enter the String to be Spilted : \");\n String st = input.nextLine();\n Scanner str = new Scanner(st);\n while (str.hasNext())\n {\n System.out.println(str.next());\n }\n\n\n }\n\n}\n\nHope it Helps!!!!!\n",
"public class StringWitoutPre {\n\n public static void main(String[] args) {\n\n String str = \"md taufique reja\";\n int len = str.length();\n char ch[] = str.toCharArray();\n String tmp = \" \";\n boolean flag = false;\n\n for (int i = 0; i < str.length(); i++) {\n if (ch[i] != ' ') {\n tmp = tmp + ch[i];\n flag = false;\n } else {\n flag = true;\n }\n if (flag || i == len - 1) {\n System.out.println(tmp);\n tmp = \" \";\n }\n }\n }\n}\n\n",
"In Java8 we can use Pattern and get the things done in more easy way. Here is the code.\npackage com.company;\n\nimport java.util.regex.Pattern;\n\npublic class umeshtest {\n\n public static void main(String a[]) {\n String ss = \"I'm Testing and testing the new feature\";\n Pattern.compile(\" \").splitAsStream(ss).forEach(s -> System.out.println(s));\n }\n}\n\n",
" static void splitString(String s, int index) {\n char[] firstPart = new char[index];\n char[] secondPart = new char[s.length() - index];\n\n int j = 0;\n for (int i = 0; i < s.length(); i++) {\n if (i < index) {\n firstPart[i] = s.charAt(i);\n } else {\n secondPart[j] = s.charAt(i);\n if (j < s.length()-index) {\n j++;\n }\n }\n }\n System.out.println(firstPart);\n System.out.println(secondPart);\n }\n\n",
"import java.util.Scanner;\npublic class Split {\n static Scanner in = new Scanner(System.in);\n static void printArray(String[] array){\n for (int i = 0; i < array.length; i++) {\n if(i!=array.length-1)\n System.out.print(array[i]+\",\");\n else\n System.out.println(array[i]);\n }\n }\n static String delimeterTrim(String str){\n char ch = str.charAt(str.length()-1);\n if(ch=='.'||ch=='!'||ch==';'){\n str = str.substring(0,str.length()-1);\n }\n return str;\n }\n private static String [] mySplit(String text, char reg, boolean delimiterTrim) {\n if(delimiterTrim){\n text = delimeterTrim(text);\n }\n text = text.trim() + \" \";\n int massValue = 0;\n for (int i = 0; i < text.length(); i++) {\n if (text.charAt(i) == reg) {\n massValue++;\n }\n }\n String[] splitArray = new String[massValue];\n for (int i = 0; i < splitArray.length; ) {\n for (int j = 0; j < text.length(); j++) {\n if (text.charAt(j) == reg) {\n splitArray[i] = text.substring(0, j);\n text = text.substring(j + 1, text.length());\n j = 0;\n i++;\n }\n }\n return splitArray;\n }\n return null;\n }\n public static void main(String[] args) {\n System.out.println(\"Enter the sentence :\");\n String text = in.nextLine();\n //System.out.println(\"Enter the regex character :\");\n //char regex = in.next().charAt(0);\n System.out.println(\"Do you want to trim the delimeter ?\");\n String delch = in.next();\n boolean ch = false;\n if(delch.equalsIgnoreCase(\"yes\")){\n ch = true;\n }\n System.out.println(\"Output String array is : \");\n printArray(mySplit(text,' ',ch));\n }\n}\n\n"
] |
[
11,
5,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
"Split a string without using split()\nstatic String[] splitAString(String abc, char splitWith){\n char[] ch=abc.toCharArray();\n String temp=\"\";\n int j=0,length=0,size=0;\n for(int i=0;i<abc.length();i++){\n if(splitWith==abc.charAt(i)){\n size++;\n }\n }\n String[] arr=new String[size+1];\n for(int i=0;i<ch.length;i++){\n if(length>j){\n j++;\n temp=\"\";\n }\n if(splitWith==ch[i]){\n length++;\n }else{\n temp +=Character.toString(ch[i]); \n }\n arr[j]=temp;\n }\n return arr;\n}\npublic static void main(String[] args) {\n\n String[] arr=splitAString(\"abc-efg-ijk\", '-');\n\n for(int i=0;i<arr.length;i++){\n System.out.println(arr[i]);\n }\n}\n\n}\n",
"You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.\n"
] |
[
-1,
-2
] |
[
"java"
] |
stackoverflow_0002939691_java.txt
|
Q:
How can I propagate mousemove events from inside a bootstrap tooltip to an svg element at the same position
I have an svg element containing a circle element. I've attached a bootstrap tooltip to my circle element using body as its container so that the tooltip displays properly. The SVG has a mousemove event which captures all mouse movements in its bounding rect.
I would like the SVG to still receive these mousemove events when the mouse pointer s inside a tooltip displayed over the SVG. However my tooltip is not propogating these events to the SVG, and when the mouse is inside the tooltip, a 'mouseleave' event is being sent to the SVG which is not what I want.
I tried alternatively attaching the mousemove event to $(document) like
$(document).on('mousemove', $('#hover-circle'), function() {...} );
but this still doesn't receive mousemove events when pointer is inside tooltip.
At this point, I'm thinking of capturing mousemove events inside the tooltip and manually
passing them on to the SVG, however I'd rather not do this.
var svg = d3.select(panel[0]).append("svg")
.attr("width", "100%")
.attr("height", "100%")
.on("mousemove", function() {
console.log('test');
});
const hoverCircle = svg.append("g")
.append("circle")
.attr("id", "hover-circle")
.attr("r", 3)
.attr("cx", xScale(closestIndex))
.attr("cy", yScale(dataset[closestIndex].y))
.attr("title", dataset[closestIndex].evalStr)
.tooltip({
container: 'body',
trigger: 'manual'
})
.tooltip('show');
A:
I've come up with a possible solution to this now using
$('.tooltip').css('pointer-events', 'none');
This causes mouse events to pass through the absolute positioned tooltip to an underlying element. Seems to be compatible with most browsers these days.
|
How can I propagate mousemove events from inside a bootstrap tooltip to an svg element at the same position
|
I have an svg element containing a circle element. I've attached a bootstrap tooltip to my circle element using body as its container so that the tooltip displays properly. The SVG has a mousemove event which captures all mouse movements in its bounding rect.
I would like the SVG to still receive these mousemove events when the mouse pointer s inside a tooltip displayed over the SVG. However my tooltip is not propogating these events to the SVG, and when the mouse is inside the tooltip, a 'mouseleave' event is being sent to the SVG which is not what I want.
I tried alternatively attaching the mousemove event to $(document) like
$(document).on('mousemove', $('#hover-circle'), function() {...} );
but this still doesn't receive mousemove events when pointer is inside tooltip.
At this point, I'm thinking of capturing mousemove events inside the tooltip and manually
passing them on to the SVG, however I'd rather not do this.
var svg = d3.select(panel[0]).append("svg")
.attr("width", "100%")
.attr("height", "100%")
.on("mousemove", function() {
console.log('test');
});
const hoverCircle = svg.append("g")
.append("circle")
.attr("id", "hover-circle")
.attr("r", 3)
.attr("cx", xScale(closestIndex))
.attr("cy", yScale(dataset[closestIndex].y))
.attr("title", dataset[closestIndex].evalStr)
.tooltip({
container: 'body',
trigger: 'manual'
})
.tooltip('show');
|
[
"I've come up with a possible solution to this now using\n$('.tooltip').css('pointer-events', 'none');\nThis causes mouse events to pass through the absolute positioned tooltip to an underlying element. Seems to be compatible with most browsers these days.\n"
] |
[
2
] |
[] |
[] |
[
"bootstrap_5",
"d3.js",
"jquery",
"svg"
] |
stackoverflow_0074664266_bootstrap_5_d3.js_jquery_svg.txt
|
Q:
Im having Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
await (async)
(anonymous) @ Notes.js:11
commitHookEffectListMount @ react-dom.development.js:23150
commitPassiveMountOnFiber @ react-dom.development.js:24926
commitPassiveMountEffects_complete @ react-dom.development.js:24891
commitPassiveMountEffects_begin @ react-dom.development.js:24878
commitPassiveMountEffects @ react-dom.development.js:24866
flushPassiveEffectsImpl @ react-dom.development.js:27039
flushPassiveEffects @ react-dom.development.js:26984
(anonymous) @ react-dom.development.js:26769
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
notes.js
import React, { useContext,useEffect } from 'react'
import NoteContext from '../context/NoteContext'
import AddNote from './AddNote'
import NoteItem from './NoteItem'
// import cors from 'cors'
const Notes = () => {
const context = useContext(NoteContext);
const { notes, getNotes } = context;
useEffect(() => {
// getNotes(cors())
getNotes()
})
return (
<>
<AddNote />
<div className="row">
<h3>Your Notes</h3>
{notes.map((note) => {
return <NoteItem key={note._id} note={note} />
})}
</div>
</>
)
}
export default Notes;
notestate.js
import NoteContext from "./NoteContext";
import { useState } from "react";
const NoteState = (props) => {
const host = "http://localhost:8000/api/notes"
const notesInitial = []
const [notes, setNotes] = useState(notesInitial)
// Get all Notes
const getNotes = async () => {
// API Call
const response = await fetch(`${host}/fetchallnotes`,
{
method: 'GET',
headers: {
'auth-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjM3YzRiY2I1MGNhZDA5YTI0ZTY5MWQ1In0sImlhdCI6MTY2OTg1MzA1NH0.LjVz0RmQA5cFsiIbK3VZyELH8--YtpBlL_ccmwCMxfQ',
'Content-Type': 'application/json'
}
})
// convert json to text
// const json = await
// console.log(json)
console.log(await response.json());
}
// Add a Note
const addNote = async (title, description, tag) => {
// TODO: API Call
// API Call
const response = await fetch(`${host}/addnote`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
"auth-token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjM3YzRiY2I1MGNhZDA5YTI0ZTY5MWQ1In0sImlhdCI6MTY2OTg1MzA1NH0.LjVz0RmQA5cFsiIbK3VZyELH8--YtpBlL_ccmwCMxfQ"
},
body: JSON.stringify({ title, description, tag })
});
console.log("Adding a new note")
const note = {
"_id": "61322f119553781a8ca8d0e08",
"user": "6131dc5e3e4037cd4734a0664",
"title": title,
"description": description,
"tag": tag,
"date": "2021-09-03T14:20:09.668Z",
"__v": 0
};
setNotes(notes.concat(note))
}
// Delete a Note
const deleteNote = (id) => {
// TODO: API Call
console.log("Deleting the note with id" + id);
const newNotes = notes.filter((note) => { return note._id !== id })
setNotes(newNotes)
}
// Edit a Note
const editNote = async (id, title, description, tag) => {
// API Call
const response = await fetch(`${host}/updatenote/${id}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
"auth-token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjM3YzRiY2I1MGNhZDA5YTI0ZTY5MWQ1In0sImlhdCI6MTY2OTg1MzA1NH0.LjVz0RmQA5cFsiIbK3VZyELH8--YtpBlL_ccmwCMxfQ"
},
body: JSON.stringify({ title, description, tag })
});
const json = response.json();
// Logic to edit in client
for (let index = 0; index < notes.length; index++) {
const element = notes[index];
if (element._id === id) {
element.title = title;
element.description = description;
element.tag = tag;
}
}
}
return (
<NoteContext.Provider value={{ notes, addNote, deleteNote, editNote, getNotes }}>
{props.children}
</NoteContext.Provider>
)
}
export default NoteState;
port of react router is 3000
and
port of backend is 8000
help me solve this error
A:
This isn't really an answer but is too large for a comment. It appears from the error message that the problem is the response.json() fails becase the response is not JSON.
Is the request rejecting or is the handling of the response failing? The latter appears to be the case.
Can you try to test the response using something like below? (But you won't use then just test the response from your await.
You're not checking the response now. If you don't like this code example, the MDN page may be helpful and also the last block under the section title "Headers". (It has no anchor so couldn't link directly to that part of the page).
.then( response => {
if ( !response.ok ) {
throw new Error( 'Network response was not ok.' );
} else {
const contentType = response.headers.get('content-type');
if (!contentType ) {
throw new TypeError("No content-type in header.");
} else if ( contentType.includes('application/json') ) {
return response.json();
} else if ( contentType.includes('text/html') ) {
return response.text();
} else {
throw new TypeError("Invalid content-type.");
}
}
...
})
|
Im having Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
|
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
await (async)
(anonymous) @ Notes.js:11
commitHookEffectListMount @ react-dom.development.js:23150
commitPassiveMountOnFiber @ react-dom.development.js:24926
commitPassiveMountEffects_complete @ react-dom.development.js:24891
commitPassiveMountEffects_begin @ react-dom.development.js:24878
commitPassiveMountEffects @ react-dom.development.js:24866
flushPassiveEffectsImpl @ react-dom.development.js:27039
flushPassiveEffects @ react-dom.development.js:26984
(anonymous) @ react-dom.development.js:26769
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
notes.js
import React, { useContext,useEffect } from 'react'
import NoteContext from '../context/NoteContext'
import AddNote from './AddNote'
import NoteItem from './NoteItem'
// import cors from 'cors'
const Notes = () => {
const context = useContext(NoteContext);
const { notes, getNotes } = context;
useEffect(() => {
// getNotes(cors())
getNotes()
})
return (
<>
<AddNote />
<div className="row">
<h3>Your Notes</h3>
{notes.map((note) => {
return <NoteItem key={note._id} note={note} />
})}
</div>
</>
)
}
export default Notes;
notestate.js
import NoteContext from "./NoteContext";
import { useState } from "react";
const NoteState = (props) => {
const host = "http://localhost:8000/api/notes"
const notesInitial = []
const [notes, setNotes] = useState(notesInitial)
// Get all Notes
const getNotes = async () => {
// API Call
const response = await fetch(`${host}/fetchallnotes`,
{
method: 'GET',
headers: {
'auth-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjM3YzRiY2I1MGNhZDA5YTI0ZTY5MWQ1In0sImlhdCI6MTY2OTg1MzA1NH0.LjVz0RmQA5cFsiIbK3VZyELH8--YtpBlL_ccmwCMxfQ',
'Content-Type': 'application/json'
}
})
// convert json to text
// const json = await
// console.log(json)
console.log(await response.json());
}
// Add a Note
const addNote = async (title, description, tag) => {
// TODO: API Call
// API Call
const response = await fetch(`${host}/addnote`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
"auth-token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjM3YzRiY2I1MGNhZDA5YTI0ZTY5MWQ1In0sImlhdCI6MTY2OTg1MzA1NH0.LjVz0RmQA5cFsiIbK3VZyELH8--YtpBlL_ccmwCMxfQ"
},
body: JSON.stringify({ title, description, tag })
});
console.log("Adding a new note")
const note = {
"_id": "61322f119553781a8ca8d0e08",
"user": "6131dc5e3e4037cd4734a0664",
"title": title,
"description": description,
"tag": tag,
"date": "2021-09-03T14:20:09.668Z",
"__v": 0
};
setNotes(notes.concat(note))
}
// Delete a Note
const deleteNote = (id) => {
// TODO: API Call
console.log("Deleting the note with id" + id);
const newNotes = notes.filter((note) => { return note._id !== id })
setNotes(newNotes)
}
// Edit a Note
const editNote = async (id, title, description, tag) => {
// API Call
const response = await fetch(`${host}/updatenote/${id}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
"auth-token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjM3YzRiY2I1MGNhZDA5YTI0ZTY5MWQ1In0sImlhdCI6MTY2OTg1MzA1NH0.LjVz0RmQA5cFsiIbK3VZyELH8--YtpBlL_ccmwCMxfQ"
},
body: JSON.stringify({ title, description, tag })
});
const json = response.json();
// Logic to edit in client
for (let index = 0; index < notes.length; index++) {
const element = notes[index];
if (element._id === id) {
element.title = title;
element.description = description;
element.tag = tag;
}
}
}
return (
<NoteContext.Provider value={{ notes, addNote, deleteNote, editNote, getNotes }}>
{props.children}
</NoteContext.Provider>
)
}
export default NoteState;
port of react router is 3000
and
port of backend is 8000
help me solve this error
|
[
"This isn't really an answer but is too large for a comment. It appears from the error message that the problem is the response.json() fails becase the response is not JSON.\nIs the request rejecting or is the handling of the response failing? The latter appears to be the case.\nCan you try to test the response using something like below? (But you won't use then just test the response from your await.\nYou're not checking the response now. If you don't like this code example, the MDN page may be helpful and also the last block under the section title \"Headers\". (It has no anchor so couldn't link directly to that part of the page).\n .then( response => {\n if ( !response.ok ) {\n throw new Error( 'Network response was not ok.' );\n } else {\n const contentType = response.headers.get('content-type');\n if (!contentType ) {\n throw new TypeError(\"No content-type in header.\");\n } else if ( contentType.includes('application/json') ) {\n return response.json();\n } else if ( contentType.includes('text/html') ) {\n return response.text();\n } else {\n throw new TypeError(\"Invalid content-type.\");\n }\n }\n ...\n })\n\n"
] |
[
0
] |
[] |
[] |
[
"cors",
"javascript",
"mern",
"reactjs"
] |
stackoverflow_0074664218_cors_javascript_mern_reactjs.txt
|
Q:
How to write value != '' in Python Pandas
I dont know how to write a blank value, no data; not null; (!= '') in pandas. Below is an example that I am using.
df['Column4'] = np.where(df['Column1'].notnull(), 'Yes',
np.where(df['Column2']== 0, 'NO',
np.where(df['Column2'].notnull(), (df['Column2']),
np.where(df['Column3']!='', '','Not_Data'))))
I tried .fillna('', inplace=True), .dropna().empty
A:
You can use the notnull method of a pandas dataframe to check if a column contains any non-null values, and then use the np.where function to write the appropriate value based on that check. Here is an example:
# create a sample dataframe with some null values
df = pd.DataFrame({'Column1': [1, 2, None, 3],
'Column2': [None, 5, 6, None],
'Column3': [7, 8, 9, None]})
# use the `notnull` method to check if a column contains any non-null values
# and use the `np.where` function to write the appropriate value based on that check
df['Column4'] = np.where(df['Column1'].notnull(), 'Yes',
np.where(df['Column2'].notnull(), 'Yes',
np.where(df['Column3'].notnull(), 'Yes', 'No')))
# the resulting dataframe should look like this:
Column1 Column2 Column3 Column4
0 1.0 NaN 7.0 Yes
1 2.0 5.0 8.0 Yes
2 NaN 6.0 9.0 Yes
3 3.0 NaN NaN No
You can also use the notna method instead of notnull, which has the same effect. Note that the notna method was introduced in pandas version 0.24.0, so if you are using an older version you will need to use notnull instead.
If you want to check if a column contains any non-empty string values, you can use the str.len method along with the notnull method to check for the length of the strings in the column, and then use the np.where function to write the appropriate value based on that check. Here is an example:
# create a sample dataframe with some null and empty string values
df = pd.DataFrame({'Column1': [1, 2, None, 3],
'Column2': [None, 5, 6, None],
'Column3': ['', '8', '9', None]})
# use the `str.len` method along with the `notnull` method to check
# if a column contains any non-empty string values
# and use the `np.where` function to write the appropriate value based on that check
df['Column4'] = np.where(df['Column1'].notnull(), 'Yes',
np.where(df['Column2'].notnull(), 'Yes',
np.where((df['Column3'].str.len() > 0) & df['Column3'].notnull(), 'Yes', 'No')))
|
How to write value != '' in Python Pandas
|
I dont know how to write a blank value, no data; not null; (!= '') in pandas. Below is an example that I am using.
df['Column4'] = np.where(df['Column1'].notnull(), 'Yes',
np.where(df['Column2']== 0, 'NO',
np.where(df['Column2'].notnull(), (df['Column2']),
np.where(df['Column3']!='', '','Not_Data'))))
I tried .fillna('', inplace=True), .dropna().empty
|
[
"You can use the notnull method of a pandas dataframe to check if a column contains any non-null values, and then use the np.where function to write the appropriate value based on that check. Here is an example:\n# create a sample dataframe with some null values\ndf = pd.DataFrame({'Column1': [1, 2, None, 3],\n 'Column2': [None, 5, 6, None],\n 'Column3': [7, 8, 9, None]})\n\n# use the `notnull` method to check if a column contains any non-null values\n# and use the `np.where` function to write the appropriate value based on that check\ndf['Column4'] = np.where(df['Column1'].notnull(), 'Yes',\n np.where(df['Column2'].notnull(), 'Yes',\n np.where(df['Column3'].notnull(), 'Yes', 'No')))\n\n# the resulting dataframe should look like this:\n Column1 Column2 Column3 Column4\n0 1.0 NaN 7.0 Yes\n1 2.0 5.0 8.0 Yes\n2 NaN 6.0 9.0 Yes\n3 3.0 NaN NaN No\n\nYou can also use the notna method instead of notnull, which has the same effect. Note that the notna method was introduced in pandas version 0.24.0, so if you are using an older version you will need to use notnull instead.\nIf you want to check if a column contains any non-empty string values, you can use the str.len method along with the notnull method to check for the length of the strings in the column, and then use the np.where function to write the appropriate value based on that check. Here is an example:\n# create a sample dataframe with some null and empty string values\ndf = pd.DataFrame({'Column1': [1, 2, None, 3],\n 'Column2': [None, 5, 6, None],\n 'Column3': ['', '8', '9', None]})\n\n# use the `str.len` method along with the `notnull` method to check\n# if a column contains any non-empty string values\n# and use the `np.where` function to write the appropriate value based on that check\ndf['Column4'] = np.where(df['Column1'].notnull(), 'Yes',\n np.where(df['Column2'].notnull(), 'Yes',\n np.where((df['Column3'].str.len() > 0) & df['Column3'].notnull(), 'Yes', 'No')))\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074664374_pandas_python.txt
|
Q:
How to force reload page when next.js router push the same route with different query?
I'm developing a product detail page with /proudct?id=xxx route, when user in /proudct?id=1 jump to /proudct?id=2, only state dependency router.query.id change, I want to force reload the whole page instead of update some state.
A:
There is an upcoming but still unstable feature unstable_skipClientCache: true where you can skip the client's cache, see snippet below.
const router = useRouter()
const { pathname, asPath, query, locale } = router
router.push(
{
pathname,
query
},
asPath,
{
locale: newLocale,
unstable_skipClientCache: true
}
)
I use it for locale changes on my page as the session depends on it.
A:
I achieve this using replace and then reload.
router.replace("/product?id=2").then(() => router.reload());
|
How to force reload page when next.js router push the same route with different query?
|
I'm developing a product detail page with /proudct?id=xxx route, when user in /proudct?id=1 jump to /proudct?id=2, only state dependency router.query.id change, I want to force reload the whole page instead of update some state.
|
[
"There is an upcoming but still unstable feature unstable_skipClientCache: true where you can skip the client's cache, see snippet below.\n\nconst router = useRouter()\nconst { pathname, asPath, query, locale } = router\n\nrouter.push(\n {\n pathname,\n query\n },\n asPath,\n {\n locale: newLocale,\n unstable_skipClientCache: true\n }\n)\n\nI use it for locale changes on my page as the session depends on it.\n",
"I achieve this using replace and then reload.\nrouter.replace(\"/product?id=2\").then(() => router.reload());\n\n"
] |
[
0,
0
] |
[
"what worked for me was something like this but it doesn't feel like a good fix.\nrouter.replace({\n pathname: '/[whatever]',\n query: { param_key: param_value },\n}).then(() => router.reload()) \n\n"
] |
[
-2
] |
[
"next.js",
"next_router"
] |
stackoverflow_0072654241_next.js_next_router.txt
|
Q:
Tictactoe crashes of value is greater or equal to 9
Editing my sister's tic-tac-toe code and she (also I) hit a snag. If Player one was to type a number greater than 9 or type a number that at was already used it will crash. Is there and recommended solution to problem.
printGameBoard(gameBoard);
//User input requests
while(true) {
System.out.println("Enter your placement (1-9):");
int playerPos = scan.nextInt();
while(playerPositions.contains(playerPos) || cpuPositions.contains(playerPositions) || cpuPositions.contains(playerPos)){
System.out.println("Position taken! Enter another position:");
playerPos = scan.nextInt();
//Prevent user from printing on top of CPU
while(playerPositions.contains(playerPos) || cpuPositions.contains(playerPos)){
System.out.println("Position taken! Enter another position:");
playerPos= scan.nextInt();
}
}
placePiece(gameBoard, playerPos, "player");
String result = checkWinner();
if(result.length() > 0) {
System.out.println(result);
break;
}
//CPU random positions (this what you are looking for)
Random rand = new Random();
int cpuPos = rand.nextInt(9) + 1;
while(playerPositions.contains(cpuPos) || cpuPositions.contains(cpuPos)){
cpuPos = rand.nextInt(9) + 1;
}
placePiece(gameBoard, cpuPos, "cpu");
printGameBoard(gameBoard);
result = checkWinner();
if(result.length() > 0){
System.out.println(result);
break;
}
}
}
public static void placePiece(char[][] gameBoard, int pos, String user){
char symbol = ' ';
if(user.equals("player")){
symbol = 'X';
playerPositions.add(pos);
} else if(user.equals("cpu")){
symbol = 'O';
cpuPositions.add(pos);
}
switch(pos){
case 1:
gameBoard[0][0] = symbol;
break;
case 2:
gameBoard[0][2] = symbol;
break;
case 3:
gameBoard[0][4] = symbol;
break;
case 4:
gameBoard[2][0] = symbol;
break;
case 5:
gameBoard[2][2] = symbol;
break;
case 6:
gameBoard[2][4] = symbol;
break;
case 7:
gameBoard[4][0] = symbol;
break;
case 8:
gameBoard[4][2] = symbol;
break;
case 9:
gameBoard[4][4] = symbol;
break;
default:
break;
}
}
public static String checkWinner(){
// (This define what a winng move looks like)
List topRow = Arrays.asList(1, 2, 3);
List midRow = Arrays.asList(4, 5, 6);
List botRow = Arrays.asList(7, 8, 9);
List leftCol = Arrays.asList(1, 4, 7);
List midCol = Arrays.asList(2, 5, 8);
List rightCol = Arrays.asList(3, 6, 9);
List cross1 = Arrays.asList(1, 5, 9);
List cross2 = Arrays.asList(7, 5, 3);
List<List> winning = new ArrayList<List>();
winning.add(topRow);
winning.add(midRow);
winning.add(botRow);
winning.add(leftCol);
winning.add(midCol);
winning.add(rightCol);
winning.add(cross1);
winning.add(cross2);
for(List l : winning){
if(playerPositions.containsAll(l)){
return "Congraduations you won!";
} else if(cpuPositions.containsAll(l)){
return "CPU wins! Sorry!";
} else if(playerPositions.size() + cpuPositions.size() == 9){
return "We are tied!";
}
}
return "";
}
public static void printGameBoard (char [][] gameBoard){
for(char[] row : gameBoard) {
for(char c : row) {
System.out.print(c);
}
System.out.println();
}
}
}
PLAYGAME CODE
import java.util.*;
public class PlayGame
{
private int incrementer;
private char location[]=new char[10];
private char gamer;
public static void main(String args[])
{
String ch;
PlayGame Toe=new PlayGame();
do{
Toe.beginBoard();
Toe.startplay();
System.out.println ("Would you like to play again (Enter 'Y')? ");
Scanner in =new Scanner(System.in);
ch=in.nextLine();
System.out.println("ch value is "+ch);
}while (ch.equals("Y"));
}
public void beginBoard()
{
char locationdef[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9'};
int i;
incrementer = 0;
gamer = 'X';
for (i=1; i<10; i++) location[i]=locationdef[i];
presentBoard();
}
public String presentBoard()
{
System.out.println( "\n\n" );
System.out.println( "\n\n" );
System.out.println( "\n\n\t\t" + location [1] + " | " +location [2]+ " | " +location [3]);
System.out.println( " \t\t | | " );
System.out.println( " \t\t ___|____|___ " );
System.out.println( "\n\n\t\t" +location [4]+ " | " +location [5]+ " | " +location [6]);
System.out.println( " \t\t | | " );
System.out.println( " \t\t ___|____|___ " );
System.out.println( "\n\n\t\t" +location [7]+ " | " +location [8]+ " | " +location [9]);
System.out.println( " \t\t | | " );
System.out.println( " \t\t | | " );
System.out.println( "\n\n" );
return "presentBoard";
}
public void startplay()
{
int center;
char blank = ' ';
System.out.println( "gamer " + locategamer() +" will go first and be the letter 'X'" );
do {
presentBoard();
System.out.println( "\n\n gamer " + locategamer() +" choose a location." );
boolean currentlocation = true;
while (currentlocation) {
Scanner in =new Scanner (System.in);
center=in.nextInt();
currentlocation = checklocation(center);
if(currentlocation==false)
location[center]=locategamer();
}
System.out.println( "Excellent move" );
presentBoard();
latergamer();
}while ( getWinner() == blank );
}
public char getWinner()
{
char Winner = ' ';
if (location[1] == 'X' && location[2] == 'X' && location[3] == 'X') Winner = 'X';
if (location[4] == 'X' && location[5] == 'X' && location[6] == 'X') Winner = 'X';
if (location[7] == 'X' && location[8] == 'X' && location[9] == 'X') Winner = 'X';
if (location[1] == 'X' && location[4] == 'X' && location[7] == 'X') Winner = 'X';
if (location[2] == 'X' && location[5] == 'X' && location[8] == 'X') Winner = 'X';
if (location[3] == 'X' && location[6] == 'X' && location[9] == 'X') Winner = 'X';
if (location[1] == 'X' && location[5] == 'X' && location[9] == 'X') Winner = 'X';
if (location[3] == 'X' && location[5] == 'X' && location[7] == 'X') Winner = 'X';
if (Winner == 'X' )
{System.out.println("gamer1 wins the game." );
return Winner;
}
if (location[1] == 'O' && location[2] == 'O' && location[3] == 'O') Winner = 'O';
if (location[4] == 'O' && location[5] == 'O' && location[6] == 'O') Winner = 'O';
if (location[7] == 'O' && location[8] == 'O' && location[9] == 'O') Winner = 'O';
if (location[1] == 'O' && location[4] == 'O' && location[7] == 'O') Winner = 'O';
if (location[2] == 'O' && location[5] == 'O' && location[8] == 'O') Winner = 'O';
if (location[3] == 'O' && location[6] == 'O' && location[9] == 'O') Winner = 'O';
if (location[1] == 'O' && location[5] == 'O' && location[9] == 'O') Winner = 'O';
if (location[3] == 'O' && location[5] == 'O' && location[7] == 'O') Winner = 'O';
if (Winner == 'O' )
{
System.out.println( "gamer2 wins the game." );
return Winner; }
for(int i=1;i<10;i++)
{
if(location[i]=='X' || location[i]=='O')
{
if(i==9)
{
char Draw='D';
System.out.println(" Game is draw ");
return Draw;
}
continue;
}
else
break;
}
return Winner;
}
public boolean checklocation(int center)
{
if (location[center] == 'X' || location[center] == 'O')
{
System.out.println("That location is already occupied please choose another location");
return true;
}
else {
return false;
}
}
public void latergamer()
{
if (gamer == 'X')
gamer = 'O';
else gamer = 'X';
}
public String locatename()
{
return " Game Tic Tac Toe" ;
}
public char locategamer()
{
return gamer;
}
}
i found code to fix redundant input, but not the crash when input is higher than 9
A:
The recommended way is to check the input first and reject it if it is an invalid location (less than 1 or greater than 9).
In the class PlayGame that would mean to change the checklocation() method:
public boolean checklocation(int center)
{
if (center < 1 || 9 < center)
{
System.out.println("That location is not valid please choose another location");
return true;
}
else if (location[center] == 'X' || location[center] == 'O')
{
System.out.println("That location is already occupied please choose another location");
return true;
}
else {
return false;
}
}
A:
A possible solution to this issue would be to add additional checks to the input to make sure that the number entered is between 1 and 9 and has not already been used. For example, you could add an if statement that checks if the entered number is valid, and if not, prompts the user to enter a new number until a valid one is provided. You could also add a list of used numbers (similar to the playerPositions and cpuPositions lists) and check if the entered number is in that list before allowing the user to place their piece on the game board.
|
Tictactoe crashes of value is greater or equal to 9
|
Editing my sister's tic-tac-toe code and she (also I) hit a snag. If Player one was to type a number greater than 9 or type a number that at was already used it will crash. Is there and recommended solution to problem.
printGameBoard(gameBoard);
//User input requests
while(true) {
System.out.println("Enter your placement (1-9):");
int playerPos = scan.nextInt();
while(playerPositions.contains(playerPos) || cpuPositions.contains(playerPositions) || cpuPositions.contains(playerPos)){
System.out.println("Position taken! Enter another position:");
playerPos = scan.nextInt();
//Prevent user from printing on top of CPU
while(playerPositions.contains(playerPos) || cpuPositions.contains(playerPos)){
System.out.println("Position taken! Enter another position:");
playerPos= scan.nextInt();
}
}
placePiece(gameBoard, playerPos, "player");
String result = checkWinner();
if(result.length() > 0) {
System.out.println(result);
break;
}
//CPU random positions (this what you are looking for)
Random rand = new Random();
int cpuPos = rand.nextInt(9) + 1;
while(playerPositions.contains(cpuPos) || cpuPositions.contains(cpuPos)){
cpuPos = rand.nextInt(9) + 1;
}
placePiece(gameBoard, cpuPos, "cpu");
printGameBoard(gameBoard);
result = checkWinner();
if(result.length() > 0){
System.out.println(result);
break;
}
}
}
public static void placePiece(char[][] gameBoard, int pos, String user){
char symbol = ' ';
if(user.equals("player")){
symbol = 'X';
playerPositions.add(pos);
} else if(user.equals("cpu")){
symbol = 'O';
cpuPositions.add(pos);
}
switch(pos){
case 1:
gameBoard[0][0] = symbol;
break;
case 2:
gameBoard[0][2] = symbol;
break;
case 3:
gameBoard[0][4] = symbol;
break;
case 4:
gameBoard[2][0] = symbol;
break;
case 5:
gameBoard[2][2] = symbol;
break;
case 6:
gameBoard[2][4] = symbol;
break;
case 7:
gameBoard[4][0] = symbol;
break;
case 8:
gameBoard[4][2] = symbol;
break;
case 9:
gameBoard[4][4] = symbol;
break;
default:
break;
}
}
public static String checkWinner(){
// (This define what a winng move looks like)
List topRow = Arrays.asList(1, 2, 3);
List midRow = Arrays.asList(4, 5, 6);
List botRow = Arrays.asList(7, 8, 9);
List leftCol = Arrays.asList(1, 4, 7);
List midCol = Arrays.asList(2, 5, 8);
List rightCol = Arrays.asList(3, 6, 9);
List cross1 = Arrays.asList(1, 5, 9);
List cross2 = Arrays.asList(7, 5, 3);
List<List> winning = new ArrayList<List>();
winning.add(topRow);
winning.add(midRow);
winning.add(botRow);
winning.add(leftCol);
winning.add(midCol);
winning.add(rightCol);
winning.add(cross1);
winning.add(cross2);
for(List l : winning){
if(playerPositions.containsAll(l)){
return "Congraduations you won!";
} else if(cpuPositions.containsAll(l)){
return "CPU wins! Sorry!";
} else if(playerPositions.size() + cpuPositions.size() == 9){
return "We are tied!";
}
}
return "";
}
public static void printGameBoard (char [][] gameBoard){
for(char[] row : gameBoard) {
for(char c : row) {
System.out.print(c);
}
System.out.println();
}
}
}
PLAYGAME CODE
import java.util.*;
public class PlayGame
{
private int incrementer;
private char location[]=new char[10];
private char gamer;
public static void main(String args[])
{
String ch;
PlayGame Toe=new PlayGame();
do{
Toe.beginBoard();
Toe.startplay();
System.out.println ("Would you like to play again (Enter 'Y')? ");
Scanner in =new Scanner(System.in);
ch=in.nextLine();
System.out.println("ch value is "+ch);
}while (ch.equals("Y"));
}
public void beginBoard()
{
char locationdef[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9'};
int i;
incrementer = 0;
gamer = 'X';
for (i=1; i<10; i++) location[i]=locationdef[i];
presentBoard();
}
public String presentBoard()
{
System.out.println( "\n\n" );
System.out.println( "\n\n" );
System.out.println( "\n\n\t\t" + location [1] + " | " +location [2]+ " | " +location [3]);
System.out.println( " \t\t | | " );
System.out.println( " \t\t ___|____|___ " );
System.out.println( "\n\n\t\t" +location [4]+ " | " +location [5]+ " | " +location [6]);
System.out.println( " \t\t | | " );
System.out.println( " \t\t ___|____|___ " );
System.out.println( "\n\n\t\t" +location [7]+ " | " +location [8]+ " | " +location [9]);
System.out.println( " \t\t | | " );
System.out.println( " \t\t | | " );
System.out.println( "\n\n" );
return "presentBoard";
}
public void startplay()
{
int center;
char blank = ' ';
System.out.println( "gamer " + locategamer() +" will go first and be the letter 'X'" );
do {
presentBoard();
System.out.println( "\n\n gamer " + locategamer() +" choose a location." );
boolean currentlocation = true;
while (currentlocation) {
Scanner in =new Scanner (System.in);
center=in.nextInt();
currentlocation = checklocation(center);
if(currentlocation==false)
location[center]=locategamer();
}
System.out.println( "Excellent move" );
presentBoard();
latergamer();
}while ( getWinner() == blank );
}
public char getWinner()
{
char Winner = ' ';
if (location[1] == 'X' && location[2] == 'X' && location[3] == 'X') Winner = 'X';
if (location[4] == 'X' && location[5] == 'X' && location[6] == 'X') Winner = 'X';
if (location[7] == 'X' && location[8] == 'X' && location[9] == 'X') Winner = 'X';
if (location[1] == 'X' && location[4] == 'X' && location[7] == 'X') Winner = 'X';
if (location[2] == 'X' && location[5] == 'X' && location[8] == 'X') Winner = 'X';
if (location[3] == 'X' && location[6] == 'X' && location[9] == 'X') Winner = 'X';
if (location[1] == 'X' && location[5] == 'X' && location[9] == 'X') Winner = 'X';
if (location[3] == 'X' && location[5] == 'X' && location[7] == 'X') Winner = 'X';
if (Winner == 'X' )
{System.out.println("gamer1 wins the game." );
return Winner;
}
if (location[1] == 'O' && location[2] == 'O' && location[3] == 'O') Winner = 'O';
if (location[4] == 'O' && location[5] == 'O' && location[6] == 'O') Winner = 'O';
if (location[7] == 'O' && location[8] == 'O' && location[9] == 'O') Winner = 'O';
if (location[1] == 'O' && location[4] == 'O' && location[7] == 'O') Winner = 'O';
if (location[2] == 'O' && location[5] == 'O' && location[8] == 'O') Winner = 'O';
if (location[3] == 'O' && location[6] == 'O' && location[9] == 'O') Winner = 'O';
if (location[1] == 'O' && location[5] == 'O' && location[9] == 'O') Winner = 'O';
if (location[3] == 'O' && location[5] == 'O' && location[7] == 'O') Winner = 'O';
if (Winner == 'O' )
{
System.out.println( "gamer2 wins the game." );
return Winner; }
for(int i=1;i<10;i++)
{
if(location[i]=='X' || location[i]=='O')
{
if(i==9)
{
char Draw='D';
System.out.println(" Game is draw ");
return Draw;
}
continue;
}
else
break;
}
return Winner;
}
public boolean checklocation(int center)
{
if (location[center] == 'X' || location[center] == 'O')
{
System.out.println("That location is already occupied please choose another location");
return true;
}
else {
return false;
}
}
public void latergamer()
{
if (gamer == 'X')
gamer = 'O';
else gamer = 'X';
}
public String locatename()
{
return " Game Tic Tac Toe" ;
}
public char locategamer()
{
return gamer;
}
}
i found code to fix redundant input, but not the crash when input is higher than 9
|
[
"The recommended way is to check the input first and reject it if it is an invalid location (less than 1 or greater than 9).\nIn the class PlayGame that would mean to change the checklocation() method:\n public boolean checklocation(int center)\n {\n if (center < 1 || 9 < center)\n {\n System.out.println(\"That location is not valid please choose another location\");\n return true;\n }\n else if (location[center] == 'X' || location[center] == 'O')\n {\n System.out.println(\"That location is already occupied please choose another location\");\n return true;\n }\n else {\n return false;\n }\n }\n\n",
"A possible solution to this issue would be to add additional checks to the input to make sure that the number entered is between 1 and 9 and has not already been used. For example, you could add an if statement that checks if the entered number is valid, and if not, prompts the user to enter a new number until a valid one is provided. You could also add a list of used numbers (similar to the playerPositions and cpuPositions lists) and check if the entered number is in that list before allowing the user to place their piece on the game board.\n"
] |
[
0,
0
] |
[] |
[] |
[
"java"
] |
stackoverflow_0074664244_java.txt
|
Q:
Calculate difference between endTime from ID 1 and startTime from ID 2
id startTime endTime
1 2022-12-3 13:00:00 2022-12-3 14:00:00
2 2022-12-3 14:00:00 2022-12-3 14:30:00
3 2022-12-3 15:00:00 2022-12-3 15:15:00
4 2022-12-3 15:30:00 2222-12-3 16:30:00
5 2022-12-3 18:30:00 2022-12-3 19:00:00
SELECT startTime, endTime,
(TIMESTAMPDIFF(MINUTE, startTime , endTime) = '60') AS MinuteDiff
FROM booking
OUTPUT:
id startTime endTime MinuteDiff
1 2022-12-3 13:00:00 2022-12-3 14:00:00 1
2 2022-12-3 14:00:00 2022-12-3 14:30:00 0
3 2022-12-3 15:00:00 2022-12-3 15:15:00 0
4 2022-12-3 15:30:00 2022-12-3 16:30:00 1
5 2022-12-3 18:30:00 2022-12-3 19:00:00 0
I am calculating the difference between the startTime and endTime of ID 1, how to calculate the difference between the endTime of ID 1 and the startTime of ID 2, and so on?
A:
Do try this one:
If you want your last row to be included in your result, use LEFT JOIN, if you don't want to include the last row use 'JOIN'.
SELECT d.`id`,
d.`endTime`,
IFNULL(d1.`startTime`,d.`endTime`),
IFNULL(TIMESTAMPDIFF(MINUTE, d.endTime, d1.startTime),0) FROM date_table d LEFT
JOIN date_table d1 ON d1.`id`=d.`id`+1
Or you can use following with Windows Functions:
SELECT
id,
endTime,
lead(startTime) over (order by id) nextStartDate,
TIMESTAMPDIFF(MINUTE,endTime,lead(startTime) over (order by id)) as timeDiff
FROM
date_table d;
|
Calculate difference between endTime from ID 1 and startTime from ID 2
|
id startTime endTime
1 2022-12-3 13:00:00 2022-12-3 14:00:00
2 2022-12-3 14:00:00 2022-12-3 14:30:00
3 2022-12-3 15:00:00 2022-12-3 15:15:00
4 2022-12-3 15:30:00 2222-12-3 16:30:00
5 2022-12-3 18:30:00 2022-12-3 19:00:00
SELECT startTime, endTime,
(TIMESTAMPDIFF(MINUTE, startTime , endTime) = '60') AS MinuteDiff
FROM booking
OUTPUT:
id startTime endTime MinuteDiff
1 2022-12-3 13:00:00 2022-12-3 14:00:00 1
2 2022-12-3 14:00:00 2022-12-3 14:30:00 0
3 2022-12-3 15:00:00 2022-12-3 15:15:00 0
4 2022-12-3 15:30:00 2022-12-3 16:30:00 1
5 2022-12-3 18:30:00 2022-12-3 19:00:00 0
I am calculating the difference between the startTime and endTime of ID 1, how to calculate the difference between the endTime of ID 1 and the startTime of ID 2, and so on?
|
[
"Do try this one:\nIf you want your last row to be included in your result, use LEFT JOIN, if you don't want to include the last row use 'JOIN'.\nSELECT d.`id`, \nd.`endTime`, \nIFNULL(d1.`startTime`,d.`endTime`),\nIFNULL(TIMESTAMPDIFF(MINUTE, d.endTime, d1.startTime),0) FROM date_table d LEFT \nJOIN date_table d1 ON d1.`id`=d.`id`+1\n\nOr you can use following with Windows Functions:\nSELECT \n id,\n endTime,\n lead(startTime) over (order by id) nextStartDate,\n TIMESTAMPDIFF(MINUTE,endTime,lead(startTime) over (order by id)) as timeDiff\n FROM \n date_table d;\n\n"
] |
[
2
] |
[] |
[] |
[
"mariadb_10.4",
"sql"
] |
stackoverflow_0074664336_mariadb_10.4_sql.txt
|
Q:
android ViewModelFactory with hilt
I am first trying android ViewModel and Hilt DI
As i understand from below link, to initialize ViewModel with a value on run-time i should use ViewModelFactory
Use a ViewModelFactory
//ViewModel
class ScoreViewModel(finalScore: Int) : ViewModel() {
// The final score
var score = finalScore
init {
Log.i("ScoreViewModel", "Final score is $finalScore")
}
}
//ViewModelFactory
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ScoreViewModel::class.java)) {
return ScoreViewModel(finalScore) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
//Fragment
viewModelFactory = ScoreViewModelFactory(ScoreFragmentArgs.fromBundle(arguments!!).score)
And to use ViewModel with hilt i should use @ViewModelInject as explained in below link
Hilt and Jetpack integrations
//ViewModel
class ExampleViewModel @ViewModelInject constructor(
private val repository: ExampleRepository,
@Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
...
}
//Activity / Fragment
@AndroidEntryPoint
class ExampleActivity : AppCompatActivity() {
private val exampleViewModel: ExampleViewModel by viewModels()
...
}
But how to use Hilt with ViewModelFactory?
It seems the answer is in the @Assisted but i can't figure out how
How to tell hilt i like it to inject repository interfaces to ViewModel while still allowing ViewModelFactory to initialize the ViewModel with parameters on run-time?
A:
courtesy of @Elye, next articles helped a lot. I recommend a read.
Passing Activity Intent Data to ViewModel through Injection
Injecting ViewModel with Dagger Hilt
It seems that mostly Factory is not needed since mostly viewmodel initial parameters are taken from previous fragment and can be accessed via SavedStateHandle which is automatically injected if marked as @Assisted
To set-up hilt i used the following code-labs tutorial
Using Hilt in your Android app
Then, viewModel injection is done automatically using only the next code
Note that as noted by fabioCollini here, it seems savedStateHandle can also get values from safe args by simply placing argument name as the key. In fact, that is what i did in the following example. ps: In an attempt to make the safe args be more "safe", i did try to replace the SavedStateHandle with ItemsFragmentArgs hoping it will work but the app did not compile. I do hope it will be implemented in the future (and if already, please let me know)
//ItemFragment file
@AndroidEntryPoint
class ItemsFragment : Fragment() {
private val viewModel: ItemsViewModel by viewModels()
//use viewModel as you would. No need to initialize.
}
//Module file - if you have any repository, remember to bind it
//or provide the exact implementation as noted in code-labs
@InstallIn(ApplicationComponent::class)
@Module
abstract class DatabaseModuleBinder {
@Binds
abstract fun bindGlistRepository(impl: FirestoreGlistRepository): GlistRepository
}
//ItemsViewModel file - lastly, anotate as follows and take your arguments
//from savedStateHandle (for safe args, use variable name as key)
class ItemsViewModel @ViewModelInject constructor(private val glistRepo: GlistRepository,
@Assisted private val savedStateHandle: SavedStateHandle) : ViewModel() {
private val glistLiveDate = glistRepo.getGlistLiveData(
savedStateHandle.get<String>("listId")!!
)
..
}
Hope it helps anyone and if any mistake, please let me know
A:
Pass your ScoreViewModelFactory into built in ktx-extension of viewModel. Also you can consume Activity/Fragment arguments by using SavedStateHandle itself with defaultViewModelProviderFactory.
/*
Gradle Dependencies
def lifecycle_version = "2.2.0"
def hiltLifeVersion = "1.0.0-alpha01"
def hiltVersion = "2.28.1-alpha"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "com.google.dagger:hilt-android:$hiltVersion"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01"
implementation "androidx.hilt:hilt-work:$hiltLifeVersion"
implementation "androidx.hilt:hilt-common:1.0.0-alpha01"
kapt "com.google.dagger:hilt-android-compiler:$hiltVersion"
kapt "androidx.hilt:hilt-compiler:$hiltLifeVersion"
*/
import androidx.fragment.app.viewModels
@AndroidEntryPoint
class ExampleFragment : Fragment(R.layout.example_fragment) {
//internally using defaultViewModelProviderFactory
private val viewModel : ExampleViewModel by viewModels()
//or you own viewmodal factory instance --> scoreViewModelFactory
private val viewModel : ExampleViewModel by viewModels { scoreViewModelFactory }
}
class ExampleViewModel @ViewModelInject constructor(
private val repository: ExampleRepository,
@Assisted override val savedStateHandle: SavedStateHandle
) : ViewModel() {
//bundle args -> String, Int, Parcelable etc..
private val arg1LiveData: MutableLiveData<String> =
savedStateHandle.getLiveData("arg1", "")
}
In built ktx-extension of Fragment viewmodel
@MainThread
inline fun <reified VM : ViewModel> Fragment.viewModels(
noinline ownerProducer: () -> ViewModelStoreOwner = { this },
noinline factoryProducer: (() -> Factory)? = null
) = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)
A:
In Jilt 2.44, at least, there is no @ViewModelInject. To inject into the constructor of a ViewModel the ViewMolde needs to be annotated with @HiltViewModel and for the constructor you can just use @Inject.
@HiltViewModel
class MyViewModel @Inject constructor(
private val navigationHelper: NavHelper
) : ViewModel()
|
android ViewModelFactory with hilt
|
I am first trying android ViewModel and Hilt DI
As i understand from below link, to initialize ViewModel with a value on run-time i should use ViewModelFactory
Use a ViewModelFactory
//ViewModel
class ScoreViewModel(finalScore: Int) : ViewModel() {
// The final score
var score = finalScore
init {
Log.i("ScoreViewModel", "Final score is $finalScore")
}
}
//ViewModelFactory
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ScoreViewModel::class.java)) {
return ScoreViewModel(finalScore) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
//Fragment
viewModelFactory = ScoreViewModelFactory(ScoreFragmentArgs.fromBundle(arguments!!).score)
And to use ViewModel with hilt i should use @ViewModelInject as explained in below link
Hilt and Jetpack integrations
//ViewModel
class ExampleViewModel @ViewModelInject constructor(
private val repository: ExampleRepository,
@Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
...
}
//Activity / Fragment
@AndroidEntryPoint
class ExampleActivity : AppCompatActivity() {
private val exampleViewModel: ExampleViewModel by viewModels()
...
}
But how to use Hilt with ViewModelFactory?
It seems the answer is in the @Assisted but i can't figure out how
How to tell hilt i like it to inject repository interfaces to ViewModel while still allowing ViewModelFactory to initialize the ViewModel with parameters on run-time?
|
[
"courtesy of @Elye, next articles helped a lot. I recommend a read.\nPassing Activity Intent Data to ViewModel through Injection\nInjecting ViewModel with Dagger Hilt\nIt seems that mostly Factory is not needed since mostly viewmodel initial parameters are taken from previous fragment and can be accessed via SavedStateHandle which is automatically injected if marked as @Assisted\nTo set-up hilt i used the following code-labs tutorial\nUsing Hilt in your Android app\nThen, viewModel injection is done automatically using only the next code\nNote that as noted by fabioCollini here, it seems savedStateHandle can also get values from safe args by simply placing argument name as the key. In fact, that is what i did in the following example. ps: In an attempt to make the safe args be more \"safe\", i did try to replace the SavedStateHandle with ItemsFragmentArgs hoping it will work but the app did not compile. I do hope it will be implemented in the future (and if already, please let me know)\n//ItemFragment file\n@AndroidEntryPoint\nclass ItemsFragment : Fragment() {\n\n private val viewModel: ItemsViewModel by viewModels()\n\n //use viewModel as you would. No need to initialize.\n}\n\n//Module file - if you have any repository, remember to bind it \n//or provide the exact implementation as noted in code-labs\n@InstallIn(ApplicationComponent::class)\n@Module\nabstract class DatabaseModuleBinder {\n\n @Binds\n abstract fun bindGlistRepository(impl: FirestoreGlistRepository): GlistRepository\n\n}\n\n\n//ItemsViewModel file - lastly, anotate as follows and take your arguments \n//from savedStateHandle (for safe args, use variable name as key)\nclass ItemsViewModel @ViewModelInject constructor(private val glistRepo: GlistRepository,\n @Assisted private val savedStateHandle: SavedStateHandle) : ViewModel() {\n\n private val glistLiveDate = glistRepo.getGlistLiveData(\n savedStateHandle.get<String>(\"listId\")!!\n )\n\n..\n}\n\nHope it helps anyone and if any mistake, please let me know\n",
"Pass your ScoreViewModelFactory into built in ktx-extension of viewModel. Also you can consume Activity/Fragment arguments by using SavedStateHandle itself with defaultViewModelProviderFactory.\n/*\nGradle Dependencies\ndef lifecycle_version = \"2.2.0\"\ndef hiltLifeVersion = \"1.0.0-alpha01\"\ndef hiltVersion = \"2.28.1-alpha\"\nimplementation \"androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version\"\nimplementation \"androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version\"\nimplementation \"androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version\"\nimplementation \"com.google.dagger:hilt-android:$hiltVersion\"\nimplementation \"androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01\"\nimplementation \"androidx.hilt:hilt-work:$hiltLifeVersion\"\nimplementation \"androidx.hilt:hilt-common:1.0.0-alpha01\"\nkapt \"com.google.dagger:hilt-android-compiler:$hiltVersion\"\nkapt \"androidx.hilt:hilt-compiler:$hiltLifeVersion\"\n*/\n\nimport androidx.fragment.app.viewModels\n\n@AndroidEntryPoint\nclass ExampleFragment : Fragment(R.layout.example_fragment) {\n\n //internally using defaultViewModelProviderFactory \n private val viewModel : ExampleViewModel by viewModels()\n\n //or you own viewmodal factory instance --> scoreViewModelFactory\n private val viewModel : ExampleViewModel by viewModels { scoreViewModelFactory }\n\n}\n\nclass ExampleViewModel @ViewModelInject constructor(\n private val repository: ExampleRepository,\n @Assisted override val savedStateHandle: SavedStateHandle\n) : ViewModel() {\n\n //bundle args -> String, Int, Parcelable etc.. \n private val arg1LiveData: MutableLiveData<String> = \n savedStateHandle.getLiveData(\"arg1\", \"\")\n\n}\n\nIn built ktx-extension of Fragment viewmodel\n@MainThread\ninline fun <reified VM : ViewModel> Fragment.viewModels(\n noinline ownerProducer: () -> ViewModelStoreOwner = { this },\n noinline factoryProducer: (() -> Factory)? = null\n) = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)\n\n",
"In Jilt 2.44, at least, there is no @ViewModelInject. To inject into the constructor of a ViewModel the ViewMolde needs to be annotated with @HiltViewModel and for the constructor you can just use @Inject.\n@HiltViewModel\nclass MyViewModel @Inject constructor(\n private val navigationHelper: NavHelper\n) : ViewModel() \n\n\n"
] |
[
27,
6,
0
] |
[] |
[] |
[
"android",
"dagger_hilt"
] |
stackoverflow_0062650736_android_dagger_hilt.txt
|
Q:
java.lang.Object cannot be resolved in Eclipse
When I installed the latest installment in Mac OSX - the Mountain Lion - I experienced some problems getting Eclipse to work I also lost most of my Android developer files (but I still have my projects). I suspect this is due to the choice of removing the /Developer and move the XCode and other Apple developer tools (I placed my Android tools here).
I have now installed the latest version of Eclipse and the problem still seems to be around. There are errors in all my projects and I get an error message prompting:
The type java.lang.Object cannot be resolved. It is indirectly referenced
from required .class files
I tried to check the Java class-path both in Eclipse and in my terminal and these seems to be OK. java and javac both run in my terminal and there is a valid path to the java source files in Eclipse (Under Preferences, Java, Installed JREs). That being said I'm not an expert in Eclipse so there may be that I have misunderstood how this problem ought to be solved. Anyone here with similar problems or who know the cure?
A:
Make sure that you have a valid JRE or JDK defined in the Java Build Path of your project. Right-click on your project, select Properties... and then Java Build Path.
A:
I had this problem moving a Maven project from Eclipse to RAD. I had a JSP file that worked in Tomcat and JBoss, but threw a NullPointerException in WebSphere on the form definition during the compile.
Anyway, after transforming the Maven project into an Ant project (mvn ant:ant), I imported the Ant project into RAD and got this error. The fix:
Open the Java Build Path, selecting the Libraries tab.
Find the JRE System Library and remove it.
Add the JRE System Library.
Goofy, but it works. It must reset some property in a file. I don't know if the problem is the older version of Eclipse or RAD.
A:
After updating my Android SDK to make Appcelerator Titanium happy, I started getting "java.lang.Object cannot be resolved" for my Android projects in (non-Titanium) Eclipse.
I updated all dependencies in Eclipse, and the error healed after a restart of Eclipse.
A:
I had that error almost every time I launched Eclipse for the first time; if I close and then re-open Eclipse, the error is gone.
I found this solution useful, though (I've copied here to protect the link, credit goes to the original author):
In Eclipse go to Windows -> Preferences -> Java -> Installed JREs.
Select the currently active JRE/JDK and press the Edit button.
Select the rt.jar and change its position in the list of JRE system libraries (e.g. press the Up button once).
Confirm all changes, clean and rebuild the workspace.
The next time you face the problem reposition the rt.jar again (or reset the order by pressing the Restore Default button).
A:
please select your installed system jre version from java build path.
A:
Try the following and problem will go away
Close the project and reopen it.
Clean the project (It will rebuild the buildpath hence reconfiguring with the JDK libraries)
OR
Delete and Re-import the project and if necessary do the above steps again.
A:
This is an annoying Eclipse Bug which seems to bite now and then. See http://dev-answers.blogspot.de/2009/06/eclipse-build-errors-javalangobject.html for a possible solution, otherwise try the following;
Close the project and reopen it.
Clean the project (It will rebuild the buildpath hence reconfiguring with the JDK libraries)
OR
Delete and Re-import the project and if necessary do the above steps again.
The better cure is to try NetBeans instead of Eclipse
A:
I got this error and what I had to do was remove the JRE from the Window/Preferences/Java/Installed JREs and re-add it. This somehow cleared up eclipse's cache and rebuilt the project successfully. To get rid of the error in the file-editor I also had to close it and open the file once again.
A:
My problem was that I had in Eclipse: Window / Preferences... and then in the tree on the left Java / Installed JREs: C:\Program Files\Java\jre7
I changed to: c:\Program Files (x86)\Java\jre7
It solved my problem.
A:
I had the same issue and none of the above solutions worked for me.
Then I realized than the library (libs) folder was missing in the project. Once i added the libs folder and the corresponding Jar file, the issue was resolved..
A:
If your project specific (or if not applicable, workspace default) JDK/JRE is being referenced correctly and you've just begun to get this issue out of the blue: restart Eclipse.
Unfortunately, "restart Eclipse" is one of the standard troubleshooting steps when a project won't build. Eclipse even has a dedicated entry under the File menu.
A:
I had to add the JDK under the build path. After adding the correct build path it worked.
A:
I just had to restart eclipse, and the error went away. Strange.
A:
I solved this by pointing my eclipse to the jre available in jdk.
A:
This error caused by invalid sdk is pointing in your project.properties file of your project.
project.properties -> target=android-19 . change to version which is installed in your eclipse.The error will be gone.
A:
I had the same issue after moving from JRE7 to JDK7. Finally I had to remove the JRE7 configuration from the Eclipse preferences and then add the following two lines to the eclipse.ini file.
-vm
C:\Program Files\Java\jdk1.7.0_55\bin\javaw.exe
A:
I had this problem, and I understood that Eclipse has automatically imported a core reference, instead of the reference for the project I needed.
Deleted the import, and rearranged it, and everything worked fine.
A:
Same problem facing Me
Project->properties->Android
And select the api level and also go in java build path and check some external jar file path if we already add in it.update the jar file path
A:
On "The type java.lang.Object cannot be resolved. It is indirectly referenced
from required .class files":
I found my project had 2 meta-inf.java files in 2 different directories with the same 'module ' on line one (a copy/paste error).
Once this was corrected, I cleared the meta-inf.java file with the issue, rebuilding it line by line, guided by Eclipse, until I had a working module configuration.
|
java.lang.Object cannot be resolved in Eclipse
|
When I installed the latest installment in Mac OSX - the Mountain Lion - I experienced some problems getting Eclipse to work I also lost most of my Android developer files (but I still have my projects). I suspect this is due to the choice of removing the /Developer and move the XCode and other Apple developer tools (I placed my Android tools here).
I have now installed the latest version of Eclipse and the problem still seems to be around. There are errors in all my projects and I get an error message prompting:
The type java.lang.Object cannot be resolved. It is indirectly referenced
from required .class files
I tried to check the Java class-path both in Eclipse and in my terminal and these seems to be OK. java and javac both run in my terminal and there is a valid path to the java source files in Eclipse (Under Preferences, Java, Installed JREs). That being said I'm not an expert in Eclipse so there may be that I have misunderstood how this problem ought to be solved. Anyone here with similar problems or who know the cure?
|
[
"Make sure that you have a valid JRE or JDK defined in the Java Build Path of your project. Right-click on your project, select Properties... and then Java Build Path.\n",
"I had this problem moving a Maven project from Eclipse to RAD. I had a JSP file that worked in Tomcat and JBoss, but threw a NullPointerException in WebSphere on the form definition during the compile.\nAnyway, after transforming the Maven project into an Ant project (mvn ant:ant), I imported the Ant project into RAD and got this error. The fix:\n\nOpen the Java Build Path, selecting the Libraries tab.\nFind the JRE System Library and remove it.\nAdd the JRE System Library.\n\nGoofy, but it works. It must reset some property in a file. I don't know if the problem is the older version of Eclipse or RAD.\n",
"After updating my Android SDK to make Appcelerator Titanium happy, I started getting \"java.lang.Object cannot be resolved\" for my Android projects in (non-Titanium) Eclipse.\nI updated all dependencies in Eclipse, and the error healed after a restart of Eclipse. \n",
"I had that error almost every time I launched Eclipse for the first time; if I close and then re-open Eclipse, the error is gone.\nI found this solution useful, though (I've copied here to protect the link, credit goes to the original author):\n\n\nIn Eclipse go to Windows -> Preferences -> Java -> Installed JREs.\nSelect the currently active JRE/JDK and press the Edit button.\nSelect the rt.jar and change its position in the list of JRE system libraries (e.g. press the Up button once).\nConfirm all changes, clean and rebuild the workspace.\nThe next time you face the problem reposition the rt.jar again (or reset the order by pressing the Restore Default button).\n\n\n",
"please select your installed system jre version from java build path.\n",
"Try the following and problem will go away\n\nClose the project and reopen it.\nClean the project (It will rebuild the buildpath hence reconfiguring with the JDK libraries)\nOR\nDelete and Re-import the project and if necessary do the above steps again.\n\n",
"This is an annoying Eclipse Bug which seems to bite now and then. See http://dev-answers.blogspot.de/2009/06/eclipse-build-errors-javalangobject.html for a possible solution, otherwise try the following;\nClose the project and reopen it.\nClean the project (It will rebuild the buildpath hence reconfiguring with the JDK libraries)\nOR\nDelete and Re-import the project and if necessary do the above steps again.\nThe better cure is to try NetBeans instead of Eclipse\n",
"I got this error and what I had to do was remove the JRE from the Window/Preferences/Java/Installed JREs and re-add it. This somehow cleared up eclipse's cache and rebuilt the project successfully. To get rid of the error in the file-editor I also had to close it and open the file once again.\n",
"My problem was that I had in Eclipse: Window / Preferences... and then in the tree on the left Java / Installed JREs: C:\\Program Files\\Java\\jre7\nI changed to: c:\\Program Files (x86)\\Java\\jre7\nIt solved my problem.\n",
"I had the same issue and none of the above solutions worked for me.\nThen I realized than the library (libs) folder was missing in the project. Once i added the libs folder and the corresponding Jar file, the issue was resolved..\n",
"If your project specific (or if not applicable, workspace default) JDK/JRE is being referenced correctly and you've just begun to get this issue out of the blue: restart Eclipse.\nUnfortunately, \"restart Eclipse\" is one of the standard troubleshooting steps when a project won't build. Eclipse even has a dedicated entry under the File menu.\n",
"I had to add the JDK under the build path. After adding the correct build path it worked.\n",
"I just had to restart eclipse, and the error went away. Strange.\n",
"I solved this by pointing my eclipse to the jre available in jdk.\n",
"This error caused by invalid sdk is pointing in your project.properties file of your project.\nproject.properties -> target=android-19 . change to version which is installed in your eclipse.The error will be gone.\n",
"I had the same issue after moving from JRE7 to JDK7. Finally I had to remove the JRE7 configuration from the Eclipse preferences and then add the following two lines to the eclipse.ini file.\n-vm\nC:\\Program Files\\Java\\jdk1.7.0_55\\bin\\javaw.exe\n",
"I had this problem, and I understood that Eclipse has automatically imported a core reference, instead of the reference for the project I needed.\nDeleted the import, and rearranged it, and everything worked fine.\n",
"Same problem facing Me\nProject->properties->Android\nAnd select the api level and also go in java build path and check some external jar file path if we already add in it.update the jar file path \n",
"On \"The type java.lang.Object cannot be resolved. It is indirectly referenced\nfrom required .class files\":\nI found my project had 2 meta-inf.java files in 2 different directories with the same 'module ' on line one (a copy/paste error).\nOnce this was corrected, I cleared the meta-inf.java file with the issue, rebuilding it line by line, guided by Eclipse, until I had a working module configuration.\n"
] |
[
42,
11,
5,
2,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"android",
"eclipse",
"java"
] |
stackoverflow_0012073222_android_eclipse_java.txt
|
Q:
Accesing the parent __init__ variable to Child Python
Hello im trying to make a oop function but im currently stuck on how can i inherit the __init__ arguments of my parent class to the child class, is there a method that can i use to adapt the variable from my main to use in child?
class a:
def __init__(self, name):
self.name = name
class b(a):
def __init__(self, age):
super().__init__()
self.age = age
When i trying to use the name from the parent it errors.
b('joe', 40)
> Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: __init__() takes 2 positional arguments but 3 were given>
A:
In the b class, you need to include the name argument in the __init__ method and pass it to the super() method as shown below:
class a:
def __init__(self, name):
self.name = name
class b(a):
def __init__(self, name, age):
super().__init__(name)
self.age = age
Now you can create an instance of the b class and pass the name and age arguments as follows:
b('joe', 40)
This will correctly initialize the name attribute inherited from the a class and the age attribute in the b class.
A:
The arguments from the child constructor need to be passed to the parent. This is because the child constructor overrides the method (i.e. replaces the constructor method) from the parent. Calling super allows you to access the original parent constructor, which will need to be provided the appropriate arguments.
class a:
def __init__(self, name):
self.name = name
class b(a):
def __init__(self, name, age):
super().__init__(name)
self.age = age
As you might notice, this means you need to write a lot of boilerplate code to plumb down the arguments (especially if there are many arguments). If this class is purely for data, then dataclasses provide a much easier and less error prone alternative.
from dataclasses import dataclass
@dataclass
class a:
name: str
@dataclass
class b(a):
age: int
print(b('joe', 12))
b(name='joe', age=12)
|
Accesing the parent __init__ variable to Child Python
|
Hello im trying to make a oop function but im currently stuck on how can i inherit the __init__ arguments of my parent class to the child class, is there a method that can i use to adapt the variable from my main to use in child?
class a:
def __init__(self, name):
self.name = name
class b(a):
def __init__(self, age):
super().__init__()
self.age = age
When i trying to use the name from the parent it errors.
b('joe', 40)
> Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: __init__() takes 2 positional arguments but 3 were given>
|
[
"In the b class, you need to include the name argument in the __init__ method and pass it to the super() method as shown below:\nclass a:\n def __init__(self, name):\n self.name = name\n \nclass b(a):\n def __init__(self, name, age):\n super().__init__(name)\n self.age = age\n\nNow you can create an instance of the b class and pass the name and age arguments as follows:\nb('joe', 40)\n\n\nThis will correctly initialize the name attribute inherited from the a class and the age attribute in the b class.\n",
"The arguments from the child constructor need to be passed to the parent. This is because the child constructor overrides the method (i.e. replaces the constructor method) from the parent. Calling super allows you to access the original parent constructor, which will need to be provided the appropriate arguments.\nclass a:\n def __init__(self, name):\n self.name = name\n \nclass b(a):\n def __init__(self, name, age):\n super().__init__(name)\n self.age = age\n\nAs you might notice, this means you need to write a lot of boilerplate code to plumb down the arguments (especially if there are many arguments). If this class is purely for data, then dataclasses provide a much easier and less error prone alternative.\nfrom dataclasses import dataclass\n\n@dataclass\nclass a:\n name: str\n\n@dataclass\nclass b(a):\n age: int\n\nprint(b('joe', 12))\n\nb(name='joe', age=12)\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"oop",
"python",
"python_3.x"
] |
stackoverflow_0074664396_oop_python_python_3.x.txt
|
Q:
Error: request entity too large
I'm receiving the following error with express:
Error: request entity too large
at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15)
at json (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/json.js:60:5)
at Object.bodyParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:53:5)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.cookieParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js:60:5)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.logger (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/logger.js:158:5)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.staticMiddleware [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/static.js:55:61)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
TypeError: /Users/michaeljames/Documents/Projects/Proj/mean/app/views/includes/foot.jade:31
29| script(type="text/javascript", src="/js/socketio/connect.js")
30|
> 31| if (req.host='localhost')
32| //Livereload script rendered
33| script(type='text/javascript', src='http://localhost:35729/livereload.js')
34|
Cannot set property 'host' of undefined
at eval (eval at <anonymous> (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:152:8), <anonymous>:273:15)
at /Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:153:35
at Object.exports.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:197:10)
at Object.exports.renderFile (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:233:18)
at View.exports.renderFile [as engine] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:218:21)
at View.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/view.js:76:8)
at Function.app.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/application.js:504:10)
at ServerResponse.res.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/response.js:801:7)
at Object.handle (/Users/michaeljames/Documents/Projects/Proj/mean/config/express.js:82:29)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:188:17)
POST /api/0.1/people 500 618ms
I am using meanstack. I have the following use statements in my express.js
//Set Request Size Limit
app.use(express.limit(100000000));
Within fiddler I can see the content-length header with a value of: 1078702
I believe this is in octets, this is 1.0787 megabytes.
I have no idea why express is not letting me post the json array I was posting previously in another express project that was not using the mean stack project structure.
A:
I had the same error recently, and all the solutions I've found did not work.
After some digging, I found that setting app.use(express.bodyParser({limit: '50mb'})); did set the limit correctly.
When adding a console.log('Limit file size: '+limit); in node_modules/express/node_modules/connect/lib/middleware/json.js:46 and restarting node, I get this output in the console:
Limit file size: 1048576
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0
Limit file size: 52428800
Express server listening on port 3002
We can see that at first, when loading the connect module, the limit is set to 1mb (1048576 bytes). Then when I set the limit, the console.log is called again and this time the limit is 52428800 (50mb). However, I still get a 413 Request entity too large.
Then I added console.log('Limit file size: '+limit); in node_modules/express/node_modules/connect/node_modules/raw-body/index.js:10 and saw another line in the console when calling the route with a big request (before the error output) :
Limit file size: 1048576
This means that somehow, somewhere, connect resets the limit parameter and ignores what we specified. I tried specifying the bodyParser parameters in the route definition individually, but no luck either.
While I did not find any proper way to set it permanently, you can "patch" it in the module directly. If you are using Express 3.4.4, add this at line 46 of node_modules/express/node_modules/connect/lib/middleware/json.js :
limit = 52428800; // for 50mb, this corresponds to the size in bytes
The line number might differ if you don't run the same version of Express.
Please note that this is bad practice and it will be overwritten if you update your module.
So this temporary solution works for now, but as soon as a solution is found (or the module fixed, in case it's a module problem) you should update your code accordingly.
I have opened an issue on their GitHub about this problem.
[edit - found the solution]
After some research and testing, I found that when debugging, I added app.use(express.bodyParser({limit: '50mb'}));, but after app.use(express.json());. Express would then set the global limit to 1mb because the first parser he encountered when running the script was express.json(). Moving bodyParser above it did the trick.
That said, the bodyParser() method will be deprecated in Connect 3.0 and should not be used. Instead, you should declare your parsers explicitly, like so :
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
In case you need multipart (for file uploads) see this post.
[second edit]
Note that in Express 4, instead of express.json() and express.urlencoded(), you must require the body-parser module and use its json() and urlencoded() methods, like so:
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
If the extended option is not explicitly defined for bodyParser.urlencoded(), it will throw a warning (body-parser deprecated undefined extended: provide extended option). This is because this option will be required in the next version and will not be optional anymore. For more info on the extended option, you can refer to the readme of body-parser.
[third edit]
It seems that in Express v4.16.0 onwards, we can go back to the initial way of doing this (thanks to @GBMan for the tip):
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
A:
In my case it was not enough to add these lines :
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
I tried adding the parameterLimit option on urlencoded function as the documentation says and error no longer appears.
The parameterLimit option controls the maximum number of parameters
that are allowed in the URL-encoded data. If a request contains more
parameters than this value, a 413 will be returned to the client.
Defaults to 1000.
Try with this code:
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
A:
If someone tried all the answers, but hadn't had any success yet and uses NGINX to host the site add this line to /etc/nginx/sites-available
client_max_body_size 100M; #100mb
A:
I don't think this is the express global size limit, but specifically the connect.json middleware limit. This is 1MB by default when you use express.bodyParser() and don't provide a limit option.
Try:
app.post('/api/0.1/people', express.bodyParser({limit: '5mb'}), yourHandler);
A:
For express ~4.16.0, express.json with limit works directly
app.use(express.json({limit: '50mb'}));
A:
in my case .. setting parameterLimit:50000 fixed the problem
app.use( bodyParser.json({limit: '50mb'}) );
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit:50000
}));
A:
2016, none of the above worked for me until i explicity set the 'type' in addition to the 'limit' for bodyparser, example:
var app = express();
var jsonParser = bodyParser.json({limit:1024*1024*20, type:'application/json'});
var urlencodedParser = bodyParser.urlencoded({ extended:true,limit:1024*1024*20,type:'application/x-www-form-urlencoded' })
app.use(jsonParser);
app.use(urlencodedParser);
A:
The following worked for me... Just use
app.use(bodyParser({limit: '50mb'}));
that's it.
Tried all above and none worked. Found that even though we use like the following,
app.use(bodyParser());
app.use(bodyParser({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb'}));
only the 1st app.use(bodyParser()); one gets defined and the latter two lines were ignored.
Refer: https://github.com/expressjs/body-parser/issues/176 >> see 'dougwilson commented on Jun 17, 2016'
A:
In my case the problem was on Nginx configuration. To solve it I have to edit the file: /etc/nginx/nginx.conf and add this line inside server block:
client_max_body_size 5M;
Restart Nginx and the problems its gone
sudo systemctl restart nginx
A:
The setting below has worked for me
Express 4.16.1
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: false,
}))
Nginx
client_max_body_size 50m;
client_body_temp_path /data/temp;
A:
After דo many tries I got my solution
I have commented this line
app.use(bodyParser.json());
and I put
app.use(bodyParser.json({limit: '50mb'}))
Then it works
A:
A slightly different approach - the payload is too BIG
All the helpful answers so far deal with increasing the payload limit. But it might also be the case that the payload is indeed too big but for no good reason. If there's no valid reason for it to be, consider looking into why it's so bloated in the first place.
Our own experience
For example, in our case, an Angular app was greedily sending an entire object in the payload. When one bloated and redundant property was removed, the payload size was reduced by a factor of a 100. This significantly improved performance and resolved the 413 error.
A:
Little old post but I had the same problem
Using express 4.+
my code looks like this and it works great after two days of extensive testing.
var url = require('url'),
homePath = __dirname + '/../',
apiV1 = require(homePath + 'api/v1/start'),
bodyParser = require('body-parser').json({limit:'100mb'});
module.exports = function(app){
app.get('/', function (req, res) {
res.render( homePath + 'public/template/index');
});
app.get('/api/v1/', function (req, res) {
var query = url.parse(req.url).query;
if ( !query ) {
res.redirect('/');
}
apiV1( 'GET', query, function (response) {
res.json(response);
});
});
app.get('*', function (req,res) {
res.redirect('/');
});
app.post('/api/v1/', bodyParser, function (req, res) {
if ( !req.body ) {
res.json({
status: 'error',
response: 'No data to parse'
});
}
apiV1( 'POST', req.body, function (response) {
res.json(response);
});
});
};
A:
Pass the below configs to your server to increase your request size.
app.use(express.json({ extended: false, limit: '50mb' }))
app.use(express.urlencoded({ limit: '50mb', extended: false, parameterLimit: 50000 }))
A:
I've used another practice for this problem with multer dependancie.
Example:
multer = require('multer');
var uploading = multer({
limits: {fileSize: 1000000, files:1},
});
exports.uploadpictureone = function(req, res) {
cloudinary.uploader.upload(req.body.url, function(result) {
res.send(result);
});
};
module.exports = function(app) {
app.route('/api/upload', uploading).all(uploadPolicy.isAllowed)
.post(upload.uploadpictureone);
};
A:
Just adding this one line must solve it actually
app.use(express.json({limit: '50mb'}));
Also recommend you guys to send the whole image to the backend then convert it rather then sending the data from the frontend
A:
for me following snippet solved the problem.
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
A:
In my case removing Content-type from the request headers worked.
A:
If you are using express.json() and bodyParser together it will give error as express sets its own limit.
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
remove above code and just add below code
app.use(bodyParser.json({ limit: "200mb" }));
app.use(bodyParser.urlencoded({ limit: "200mb", extended: true, parameterLimit: 1000000 }));
A:
After trying everything in this post, i was unsuccessful. But I found a solution that worked for me.
I was able to solve it without using the body-parser and only with the express.
It looked like this:
const express = require('express');
const app = express();
app.use(express.json({limit: '25mb'}));
app.use(express.urlencoded({limit: '25mb', extended: true}));
Don't forget to use extended: true to remove the deprecated message from the console.
A:
I too faced that issue, I was making a silly mistake by repeating the app.use(bodyParser.json()) like below:
app.use(bodyParser.json())
app.use(bodyParser.json({ limit: '50mb' }))
by removing app.use(bodyParser.json()), solved the problem.
A:
I faced the same issue recently and bellow solution workes for me.
Dependency :
express >> version : 4.17.1
body-parser >> version": 1.19.0
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
For understanding :
HTTP 431
The HTTP 413 Payload Too Large response status code indicates that the
request entity is larger than limits defined by server; the server
might close the connection or return a Retry-After header field.
A:
The better use you can specify the limit of your file size as it is shown in the given lines:
app.use(bodyParser.json({limit: '10mb', extended: true}))
app.use(bodyParser.urlencoded({limit: '10mb', extended: true}))
You can also change the default setting in node-modules body-parser then in the lib folder, there are JSON and text file. Then change limit here. Actually, this condition pass if you don't pass the limit parameter in the given line
app.use(bodyParser.json({limit: '10mb', extended: true})).
A:
To add to Alexander's answer.
By default, NGINX has an upload limit of 1 MB per file. By limiting the file size of uploads, you can prevent some types of Denial-of-service (DOS) attacks and many other issues.
So when you try to upload a file above the 1MB limit you will run into a 413 error.
By editing client_max_body_size, you can adjust the file upload size. Use the http, server, or location block to edit client_max_body_size.
server {
server_name example.com;
location / {
proxy_set_header HOST $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
client_max_body_size 20M;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/infohob.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/infohob.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
Reference: Limit File Upload Size in NGINX
A:
Express 4.17.1
app.use( express.urlencoded( {
extended: true,
limit: '50mb'
} ) )
Demo csb
A:
Following code resolved my issue:
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false, limit: '5mb' });
A:
For me the main trick is
app.use(bodyParser.json({
limit: '20mb'
}));
app.use(bodyParser.urlencoded({
limit: '20mb',
parameterLimit: 100000,
extended: true
}));
bodyParse.json first
bodyParse.urlencoded second
A:
For those who start the NodeJS app in Azure under IIS, do not forget to modify web.config as explained here Azure App Service IIS "maxRequestLength" setting
A:
I am using multer to upload files to AWS s3.
For me, after adding client_max_body_size 100M; into nginx file,
I get 400 error. (but the 413 error is gone, this means that it successfully went through nginx and reach your server)
Solution is below:
https://stackoverflow.com/a/71240419/15477963
My app.js file did not need to change, and remain like this, which works:
const express = require('express');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
A:
Work for me:
Config nginx max file zise
[https://patriciahillebrandt.com/nginx-413-request-entity-too-large/][1]
and
app.use(bodyParser.json({ limit: "200mb" }));
app.use(bodyParser.urlencoded({ limit: "200mb", extended: true, parameterLimit: 1000000 }));
A:
This issue happens in two cases:
1- request body is too large and server cannot process this large data. this will serve it
app.use(express.json({limit: '50mb'}));
2- req.cookies is too large. When testing different next.js applications on the same browser, each time each app was starting on a different port if there were running some apps. Same app might end up starting at port 3000-3005 range. That means if your app saves cookie, that cookie will be saved for each port. Let's say you started 5 different apps at localhost:3000, and each one saved a cookie. If you make a request, all the cookies will be attached to the request object, in this case you will not able to process even small size of post.body. Solution is you have to delete all the cookies
|
Error: request entity too large
|
I'm receiving the following error with express:
Error: request entity too large
at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15)
at json (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/json.js:60:5)
at Object.bodyParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:53:5)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.cookieParser [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js:60:5)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.logger (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/logger.js:158:5)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at Object.staticMiddleware [as handle] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/middleware/static.js:55:61)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:193:15)
TypeError: /Users/michaeljames/Documents/Projects/Proj/mean/app/views/includes/foot.jade:31
29| script(type="text/javascript", src="/js/socketio/connect.js")
30|
> 31| if (req.host='localhost')
32| //Livereload script rendered
33| script(type='text/javascript', src='http://localhost:35729/livereload.js')
34|
Cannot set property 'host' of undefined
at eval (eval at <anonymous> (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:152:8), <anonymous>:273:15)
at /Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:153:35
at Object.exports.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:197:10)
at Object.exports.renderFile (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:233:18)
at View.exports.renderFile [as engine] (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/jade/lib/jade.js:218:21)
at View.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/view.js:76:8)
at Function.app.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/application.js:504:10)
at ServerResponse.res.render (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/lib/response.js:801:7)
at Object.handle (/Users/michaeljames/Documents/Projects/Proj/mean/config/express.js:82:29)
at next (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/lib/proto.js:188:17)
POST /api/0.1/people 500 618ms
I am using meanstack. I have the following use statements in my express.js
//Set Request Size Limit
app.use(express.limit(100000000));
Within fiddler I can see the content-length header with a value of: 1078702
I believe this is in octets, this is 1.0787 megabytes.
I have no idea why express is not letting me post the json array I was posting previously in another express project that was not using the mean stack project structure.
|
[
"I had the same error recently, and all the solutions I've found did not work.\nAfter some digging, I found that setting app.use(express.bodyParser({limit: '50mb'})); did set the limit correctly. \nWhen adding a console.log('Limit file size: '+limit); in node_modules/express/node_modules/connect/lib/middleware/json.js:46 and restarting node, I get this output in the console: \nLimit file size: 1048576\nconnect.multipart() will be removed in connect 3.0\nvisit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives\nconnect.limit() will be removed in connect 3.0\nLimit file size: 52428800\nExpress server listening on port 3002\n\nWe can see that at first, when loading the connect module, the limit is set to 1mb (1048576 bytes). Then when I set the limit, the console.log is called again and this time the limit is 52428800 (50mb). However, I still get a 413 Request entity too large.\nThen I added console.log('Limit file size: '+limit); in node_modules/express/node_modules/connect/node_modules/raw-body/index.js:10 and saw another line in the console when calling the route with a big request (before the error output) : \nLimit file size: 1048576\n\nThis means that somehow, somewhere, connect resets the limit parameter and ignores what we specified. I tried specifying the bodyParser parameters in the route definition individually, but no luck either.\nWhile I did not find any proper way to set it permanently, you can \"patch\" it in the module directly. If you are using Express 3.4.4, add this at line 46 of node_modules/express/node_modules/connect/lib/middleware/json.js :\nlimit = 52428800; // for 50mb, this corresponds to the size in bytes\n\nThe line number might differ if you don't run the same version of Express.\nPlease note that this is bad practice and it will be overwritten if you update your module.\nSo this temporary solution works for now, but as soon as a solution is found (or the module fixed, in case it's a module problem) you should update your code accordingly.\nI have opened an issue on their GitHub about this problem.\n[edit - found the solution]\nAfter some research and testing, I found that when debugging, I added app.use(express.bodyParser({limit: '50mb'}));, but after app.use(express.json());. Express would then set the global limit to 1mb because the first parser he encountered when running the script was express.json(). Moving bodyParser above it did the trick.\nThat said, the bodyParser() method will be deprecated in Connect 3.0 and should not be used. Instead, you should declare your parsers explicitly, like so :\napp.use(express.json({limit: '50mb'}));\napp.use(express.urlencoded({limit: '50mb'}));\n\nIn case you need multipart (for file uploads) see this post.\n[second edit]\nNote that in Express 4, instead of express.json() and express.urlencoded(), you must require the body-parser module and use its json() and urlencoded() methods, like so:\nvar bodyParser = require('body-parser');\napp.use(bodyParser.json({limit: '50mb'}));\napp.use(bodyParser.urlencoded({limit: '50mb', extended: true}));\n\nIf the extended option is not explicitly defined for bodyParser.urlencoded(), it will throw a warning (body-parser deprecated undefined extended: provide extended option). This is because this option will be required in the next version and will not be optional anymore. For more info on the extended option, you can refer to the readme of body-parser.\n[third edit]\nIt seems that in Express v4.16.0 onwards, we can go back to the initial way of doing this (thanks to @GBMan for the tip):\napp.use(express.json({limit: '50mb'}));\napp.use(express.urlencoded({limit: '50mb'}));\n\n",
"In my case it was not enough to add these lines :\nvar bodyParser = require('body-parser');\napp.use(bodyParser.json({limit: '50mb'}));\napp.use(bodyParser.urlencoded({limit: '50mb', extended: true}));\n\nI tried adding the parameterLimit option on urlencoded function as the documentation says and error no longer appears.\n\nThe parameterLimit option controls the maximum number of parameters\nthat are allowed in the URL-encoded data. If a request contains more\nparameters than this value, a 413 will be returned to the client.\nDefaults to 1000.\n\nTry with this code:\nvar bodyParser = require('body-parser');\napp.use(bodyParser.json({limit: \"50mb\"}));\napp.use(bodyParser.urlencoded({limit: \"50mb\", extended: true, parameterLimit:50000}));\n\n",
"If someone tried all the answers, but hadn't had any success yet and uses NGINX to host the site add this line to /etc/nginx/sites-available\nclient_max_body_size 100M; #100mb\n\n",
"I don't think this is the express global size limit, but specifically the connect.json middleware limit. This is 1MB by default when you use express.bodyParser() and don't provide a limit option.\nTry:\napp.post('/api/0.1/people', express.bodyParser({limit: '5mb'}), yourHandler);\n\n",
"For express ~4.16.0, express.json with limit works directly\napp.use(express.json({limit: '50mb'}));\n\n",
"in my case .. setting parameterLimit:50000 fixed the problem\napp.use( bodyParser.json({limit: '50mb'}) );\napp.use(bodyParser.urlencoded({\n limit: '50mb',\n extended: true,\n parameterLimit:50000\n}));\n\n",
"2016, none of the above worked for me until i explicity set the 'type' in addition to the 'limit' for bodyparser, example:\n var app = express();\n var jsonParser = bodyParser.json({limit:1024*1024*20, type:'application/json'});\n var urlencodedParser = bodyParser.urlencoded({ extended:true,limit:1024*1024*20,type:'application/x-www-form-urlencoded' })\n\n app.use(jsonParser);\n app.use(urlencodedParser);\n\n",
"The following worked for me... Just use \napp.use(bodyParser({limit: '50mb'}));\n\nthat's it.\nTried all above and none worked. Found that even though we use like the following,\napp.use(bodyParser());\napp.use(bodyParser({limit: '50mb'}));\napp.use(bodyParser.urlencoded({limit: '50mb'}));\n\nonly the 1st app.use(bodyParser()); one gets defined and the latter two lines were ignored.\nRefer: https://github.com/expressjs/body-parser/issues/176 >> see 'dougwilson commented on Jun 17, 2016'\n",
"In my case the problem was on Nginx configuration. To solve it I have to edit the file: /etc/nginx/nginx.conf and add this line inside server block:\nclient_max_body_size 5M;\n\nRestart Nginx and the problems its gone\nsudo systemctl restart nginx\n\n",
"The setting below has worked for me\nExpress 4.16.1\napp.use(bodyParser.json({ limit: '50mb' }))\napp.use(bodyParser.urlencoded({\n limit: '50mb',\n extended: false,\n}))\n\nNginx\nclient_max_body_size 50m;\nclient_body_temp_path /data/temp;\n\n",
"After דo many tries I got my solution\nI have commented this line\napp.use(bodyParser.json());\n\nand I put\napp.use(bodyParser.json({limit: '50mb'}))\n\nThen it works\n",
"A slightly different approach - the payload is too BIG\nAll the helpful answers so far deal with increasing the payload limit. But it might also be the case that the payload is indeed too big but for no good reason. If there's no valid reason for it to be, consider looking into why it's so bloated in the first place.\nOur own experience\nFor example, in our case, an Angular app was greedily sending an entire object in the payload. When one bloated and redundant property was removed, the payload size was reduced by a factor of a 100. This significantly improved performance and resolved the 413 error.\n",
"Little old post but I had the same problem\nUsing express 4.+\nmy code looks like this and it works great after two days of extensive testing.\nvar url = require('url'),\n homePath = __dirname + '/../',\n apiV1 = require(homePath + 'api/v1/start'),\n bodyParser = require('body-parser').json({limit:'100mb'});\n\nmodule.exports = function(app){\n app.get('/', function (req, res) {\n res.render( homePath + 'public/template/index');\n });\n\n app.get('/api/v1/', function (req, res) {\n var query = url.parse(req.url).query;\n if ( !query ) {\n res.redirect('/');\n }\n apiV1( 'GET', query, function (response) {\n res.json(response);\n });\n });\n\n app.get('*', function (req,res) {\n res.redirect('/');\n });\n\n app.post('/api/v1/', bodyParser, function (req, res) {\n if ( !req.body ) {\n res.json({\n status: 'error',\n response: 'No data to parse'\n });\n }\n apiV1( 'POST', req.body, function (response) {\n res.json(response);\n });\n });\n};\n\n",
"Pass the below configs to your server to increase your request size.\napp.use(express.json({ extended: false, limit: '50mb' }))\napp.use(express.urlencoded({ limit: '50mb', extended: false, parameterLimit: 50000 }))\n\n",
"I've used another practice for this problem with multer dependancie.\nExample: \nmulter = require('multer');\n\nvar uploading = multer({\n limits: {fileSize: 1000000, files:1},\n});\n\nexports.uploadpictureone = function(req, res) {\n cloudinary.uploader.upload(req.body.url, function(result) {\n res.send(result);\n });\n};\n\nmodule.exports = function(app) {\n app.route('/api/upload', uploading).all(uploadPolicy.isAllowed)\n .post(upload.uploadpictureone);\n};\n\n",
"Just adding this one line must solve it actually\napp.use(express.json({limit: '50mb'}));\n\nAlso recommend you guys to send the whole image to the backend then convert it rather then sending the data from the frontend\n",
"for me following snippet solved the problem.\nvar bodyParser = require('body-parser');\napp.use(bodyParser.json({limit: '50mb'})); \n\n",
"In my case removing Content-type from the request headers worked.\n",
"If you are using express.json() and bodyParser together it will give error as express sets its own limit.\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\n\nremove above code and just add below code\napp.use(bodyParser.json({ limit: \"200mb\" }));\napp.use(bodyParser.urlencoded({ limit: \"200mb\", extended: true, parameterLimit: 1000000 }));\n\n",
"After trying everything in this post, i was unsuccessful. But I found a solution that worked for me.\nI was able to solve it without using the body-parser and only with the express.\nIt looked like this:\nconst express = require('express'); \n\nconst app = express();\napp.use(express.json({limit: '25mb'}));\napp.use(express.urlencoded({limit: '25mb', extended: true}));\n\nDon't forget to use extended: true to remove the deprecated message from the console.\n",
"I too faced that issue, I was making a silly mistake by repeating the app.use(bodyParser.json()) like below:\napp.use(bodyParser.json())\napp.use(bodyParser.json({ limit: '50mb' }))\n\nby removing app.use(bodyParser.json()), solved the problem.\n",
"I faced the same issue recently and bellow solution workes for me.\n\nDependency : \nexpress >> version : 4.17.1\nbody-parser >> version\": 1.19.0\n\n\nconst express = require('express');\nconst bodyParser = require('body-parser');\n\nconst app = express(); \napp.use(bodyParser.json({limit: '50mb'}));\napp.use(bodyParser.urlencoded({limit: '50mb', extended: true}));\n\nFor understanding :\nHTTP 431 \n\nThe HTTP 413 Payload Too Large response status code indicates that the\nrequest entity is larger than limits defined by server; the server\nmight close the connection or return a Retry-After header field.\n\n",
"The better use you can specify the limit of your file size as it is shown in the given lines:\napp.use(bodyParser.json({limit: '10mb', extended: true}))\napp.use(bodyParser.urlencoded({limit: '10mb', extended: true}))\n\nYou can also change the default setting in node-modules body-parser then in the lib folder, there are JSON and text file. Then change limit here. Actually, this condition pass if you don't pass the limit parameter in the given line\napp.use(bodyParser.json({limit: '10mb', extended: true})).\n",
"To add to Alexander's answer.\nBy default, NGINX has an upload limit of 1 MB per file. By limiting the file size of uploads, you can prevent some types of Denial-of-service (DOS) attacks and many other issues.\nSo when you try to upload a file above the 1MB limit you will run into a 413 error.\nBy editing client_max_body_size, you can adjust the file upload size. Use the http, server, or location block to edit client_max_body_size.\nserver {\n server_name example.com;\n\n location / {\n proxy_set_header HOST $host;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n\n proxy_pass http://127.0.0.1:8080;\n client_max_body_size 20M;\n }\n\n listen [::]:443 ssl ipv6only=on; # managed by Certbot\n listen 443 ssl; # managed by Certbot\n ssl_certificate /etc/letsencrypt/live/infohob.com/fullchain.pem; # managed by Certbot\n ssl_certificate_key /etc/letsencrypt/live/infohob.com/privkey.pem; # managed by Certbot\n include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot\n ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot\n\n}\n\nReference: Limit File Upload Size in NGINX\n",
"Express 4.17.1\napp.use( express.urlencoded( {\n extended: true,\n limit: '50mb'\n} ) )\n\nDemo csb\n",
"Following code resolved my issue:\nvar bodyParser = require('body-parser');\nvar urlencodedParser = bodyParser.urlencoded({ extended: false, limit: '5mb' });\n\n",
"For me the main trick is \napp.use(bodyParser.json({\n limit: '20mb'\n}));\n\napp.use(bodyParser.urlencoded({\n limit: '20mb',\n parameterLimit: 100000,\n extended: true \n}));\n\nbodyParse.json first\nbodyParse.urlencoded second\n",
"For those who start the NodeJS app in Azure under IIS, do not forget to modify web.config as explained here Azure App Service IIS \"maxRequestLength\" setting\n",
"I am using multer to upload files to AWS s3.\nFor me, after adding client_max_body_size 100M; into nginx file,\nI get 400 error. (but the 413 error is gone, this means that it successfully went through nginx and reach your server)\nSolution is below:\nhttps://stackoverflow.com/a/71240419/15477963\nMy app.js file did not need to change, and remain like this, which works:\nconst express = require('express');\nconst bodyParser = require('body-parser');\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\n\n",
"Work for me:\nConfig nginx max file zise\n[https://patriciahillebrandt.com/nginx-413-request-entity-too-large/][1]\nand\napp.use(bodyParser.json({ limit: \"200mb\" }));\napp.use(bodyParser.urlencoded({ limit: \"200mb\", extended: true, parameterLimit: 1000000 }));\n\n",
"This issue happens in two cases:\n1- request body is too large and server cannot process this large data. this will serve it\napp.use(express.json({limit: '50mb'}));\n\n2- req.cookies is too large. When testing different next.js applications on the same browser, each time each app was starting on a different port if there were running some apps. Same app might end up starting at port 3000-3005 range. That means if your app saves cookie, that cookie will be saved for each port. Let's say you started 5 different apps at localhost:3000, and each one saved a cookie. If you make a request, all the cookies will be attached to the request object, in this case you will not able to process even small size of post.body. Solution is you have to delete all the cookies\n\n"
] |
[
1438,
174,
71,
40,
31,
21,
16,
16,
14,
13,
9,
8,
6,
6,
5,
5,
4,
4,
4,
4,
3,
3,
2,
2,
1,
1,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"express",
"http",
"javascript",
"node.js"
] |
stackoverflow_0019917401_express_http_javascript_node.js.txt
|
Q:
How to replace NAN values based on the values in another column in pandas
I am using the breast-cancer-wisconsin dataset that looks as follows:
The Bare Nuclei column has 16 missing entries denoted by "?" which I replace with NAN as follows:
df.replace('?', np.NAN, regex=False, inplace = True)
resulting in this (a few of the 16 missing entries):
I want to replace the NANs with the most frequently occurring value with respect to each class. To elaborate, the most frequently occurring value in column 'Bare Nuclei' which has class=2 (benign cancer) should be used to replace all the rows that have 'Bare Nuclei' == NAN and Class == 2. Similarly for class = 4 (malignant).
I tried the following:
df[df['Class']== 2]['Bare Nuclei'].fillna(df_vals[df_vals['Class']==2]['Bare Nuclei'].mode(), inplace=True)
df[df['Class']== 4]['Bare Nuclei'].fillna(df_vals[df_vals['Class']==4]['Bare Nuclei'].mode(), inplace=True)
It did not result in any error but when I tried this:
df.isnull().any()
Bare Nuclei shows True which means the NAN values are still there.
(column "Bare Nuclei" is of type object)
I don't understand what I am doing wrong. Please help!
Thank you.
A:
You can try via groupby()+agg()+fillna():
s=df_vals.groupby('class')['Bare Nuclei'].agg(lambda x:x.mode(dropna=False).iat[0])
df['Bare Nuclei']=df['Bare Nuclei'].fillna(df['class'].map(s))
OR
by your approach use loc:
df.loc[df['Class']== 2,'Bare Nuclei'].fillna(df_vals.loc[df_vals['Class']==2,'Bare Nuclei'].mode(), inplace=True)
A:
As a late answer, if you want to replace every NaN you have in the "Bare Nuclei" column by the values in the column "Class":
selection_condition = pd.isna(df["Bare Nuclei"])
df["Bare Nuclei"].iloc[selection_condition] = df[selection_condition]["Class"]
If you you want to be class specific regarding your replacement:
selection_condition = pd.isna(df["Bare Nuclei"]) & (df["Class"] == 2)
df["Bare Nuclei"].iloc[selection_condition] = df[selection_condition]["Class"]
A:
file.info()
file['Bare Nuclei'].loc[file['Bare Nuclei'] == '?'] = panda.nan
file.dropna(inplace = True)
file.drop(['Sample code number'],axis = 1,inplace = True)
file['Bare Nuclei'] = file.astype({"Bare Nuclei": int})
from sklearn.metrics import accuracy_score
for i in range(num_split):
first = filename.drop(['Class','Bare Nuclei'],axis=1)
second = filename['Class'].values
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.8, random_state = 0)
classifier = LogisticRegression(max_iter = 200, solver = 'newton-cg')
classifier.fit(x_train, y_train)
Sk_overall = Sk_overall + classifier.score(x_test,y_test)
Sk_Accuracy = Sk_overall/i
|
How to replace NAN values based on the values in another column in pandas
|
I am using the breast-cancer-wisconsin dataset that looks as follows:
The Bare Nuclei column has 16 missing entries denoted by "?" which I replace with NAN as follows:
df.replace('?', np.NAN, regex=False, inplace = True)
resulting in this (a few of the 16 missing entries):
I want to replace the NANs with the most frequently occurring value with respect to each class. To elaborate, the most frequently occurring value in column 'Bare Nuclei' which has class=2 (benign cancer) should be used to replace all the rows that have 'Bare Nuclei' == NAN and Class == 2. Similarly for class = 4 (malignant).
I tried the following:
df[df['Class']== 2]['Bare Nuclei'].fillna(df_vals[df_vals['Class']==2]['Bare Nuclei'].mode(), inplace=True)
df[df['Class']== 4]['Bare Nuclei'].fillna(df_vals[df_vals['Class']==4]['Bare Nuclei'].mode(), inplace=True)
It did not result in any error but when I tried this:
df.isnull().any()
Bare Nuclei shows True which means the NAN values are still there.
(column "Bare Nuclei" is of type object)
I don't understand what I am doing wrong. Please help!
Thank you.
|
[
"You can try via groupby()+agg()+fillna():\ns=df_vals.groupby('class')['Bare Nuclei'].agg(lambda x:x.mode(dropna=False).iat[0])\ndf['Bare Nuclei']=df['Bare Nuclei'].fillna(df['class'].map(s))\n\nOR\nby your approach use loc:\ndf.loc[df['Class']== 2,'Bare Nuclei'].fillna(df_vals.loc[df_vals['Class']==2,'Bare Nuclei'].mode(), inplace=True)\n\n",
"As a late answer, if you want to replace every NaN you have in the \"Bare Nuclei\" column by the values in the column \"Class\":\nselection_condition = pd.isna(df[\"Bare Nuclei\"])\ndf[\"Bare Nuclei\"].iloc[selection_condition] = df[selection_condition][\"Class\"]\n\nIf you you want to be class specific regarding your replacement:\nselection_condition = pd.isna(df[\"Bare Nuclei\"]) & (df[\"Class\"] == 2)\ndf[\"Bare Nuclei\"].iloc[selection_condition] = df[selection_condition][\"Class\"]\n\n",
"file.info()\nfile['Bare Nuclei'].loc[file['Bare Nuclei'] == '?'] = panda.nan\n\nfile.dropna(inplace = True)\nfile.drop(['Sample code number'],axis = 1,inplace = True)\nfile['Bare Nuclei'] = file.astype({\"Bare Nuclei\": int})\n\nfrom sklearn.metrics import accuracy_score\nfor i in range(num_split):\n first = filename.drop(['Class','Bare Nuclei'],axis=1)\n second = filename['Class'].values\n x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.8, random_state = 0)\n classifier = LogisticRegression(max_iter = 200, solver = 'newton-cg')\n classifier.fit(x_train, y_train)\n Sk_overall = Sk_overall + classifier.score(x_test,y_test)\n Sk_Accuracy = Sk_overall/i\n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"dataframe",
"pandas"
] |
stackoverflow_0068811809_dataframe_pandas.txt
|
Q:
tensorflow.python.framework.errors_impl.ResourceExhaustedError: failed to allocate memory [Op:AddV2]
Hi I am a beginner in DL and tensorflow,
I created a CNN (you can see the model below)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=7, activation="relu", input_shape=[512, 640, 3]))
model.add(tf.keras.layers.MaxPooling2D(2))
model.add(tf.keras.layers.Conv2D(filters=128, kernel_size=3, activation="relu"))
model.add(tf.keras.layers.Conv2D(filters=128, kernel_size=3, activation="relu"))
model.add(tf.keras.layers.MaxPooling2D(2))
model.add(tf.keras.layers.Conv2D(filters=256, kernel_size=3, activation="relu"))
model.add(tf.keras.layers.Conv2D(filters=256, kernel_size=3, activation="relu"))
model.add(tf.keras.layers.MaxPooling2D(2))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(2, activation='softmax'))
optimizer = tf.keras.optimizers.SGD(learning_rate=0.2) #, momentum=0.9, decay=0.1)
model.compile(optimizer=optimizer, loss='mse', metrics=['accuracy'])
I tried building and training it with the cpu and it was completed successfully (but very slowly) so I decided to install tensorflow-gpu.
Installed everything as instructed in https://www.tensorflow.org/install/gpu).
But now when I am trying to build the model this error comes up:
> Traceback (most recent call last): File
> "C:/Users/thano/Documents/Py_workspace/AI_tensorflow/fire_detection/main.py",
> line 63, in <module>
> model = create_models.model1() File "C:\Users\thano\Documents\Py_workspace\AI_tensorflow\fire_detection\create_models.py",
> line 20, in model1
> model.add(tf.keras.layers.Dense(128, activation='relu')) File "C:\Python37\lib\site-packages\tensorflow\python\training\tracking\base.py",
> line 530, in _method_wrapper
> result = method(self, *args, **kwargs) File "C:\Python37\lib\site-packages\keras\engine\sequential.py", line 217,
> in add
> output_tensor = layer(self.outputs[0]) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 977,
> in __call__
> input_list) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 1115,
> in _functional_construction_call
> inputs, input_masks, args, kwargs) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 848,
> in _keras_tensor_symbolic_call
> return self._infer_output_signature(inputs, args, kwargs, input_masks) File
> "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 886,
> in _infer_output_signature
> self._maybe_build(inputs) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 2659,
> in _maybe_build
> self.build(input_shapes) # pylint:disable=not-callable File "C:\Python37\lib\site-packages\keras\layers\core.py", line 1185, in
> build
> trainable=True) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 663,
> in add_weight
> caching_device=caching_device) File "C:\Python37\lib\site-packages\tensorflow\python\training\tracking\base.py",
> line 818, in _add_variable_with_custom_getter
> **kwargs_for_getter) File "C:\Python37\lib\site-packages\keras\engine\base_layer_utils.py", line
> 129, in make_variable
> shape=variable_shape if variable_shape else None) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variables.py",
> line 266, in __call__
> return cls._variable_v1_call(*args, **kwargs) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variables.py",
> line 227, in _variable_v1_call
> shape=shape) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variables.py",
> line 205, in <lambda>
> previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variable_scope.py",
> line 2626, in default_variable_creator
> shape=shape) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variables.py",
> line 270, in __call__
> return super(VariableMetaclass, cls).__call__(*args, **kwargs) File
> "C:\Python37\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py",
> line 1613, in __init__
> distribute_strategy=distribute_strategy) File "C:\Python37\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py",
> line 1740, in _init_from_args
> initial_value = initial_value() File "C:\Python37\lib\site-packages\keras\initializers\initializers_v2.py",
> line 517, in __call__
> return self._random_generator.random_uniform(shape, -limit, limit, dtype) File
> "C:\Python37\lib\site-packages\keras\initializers\initializers_v2.py",
> line 973, in random_uniform
> shape=shape, minval=minval, maxval=maxval, dtype=dtype, seed=self.seed) File
> "C:\Python37\lib\site-packages\tensorflow\python\util\dispatch.py",
> line 206, in wrapper
> return target(*args, **kwargs) File "C:\Python37\lib\site-packages\tensorflow\python\ops\random_ops.py",
> line 315, in random_uniform
> result = math_ops.add(result * (maxval - minval), minval, name=name) File
> "C:\Python37\lib\site-packages\tensorflow\python\util\dispatch.py",
> line 206, in wrapper
> return target(*args, **kwargs) File "C:\Python37\lib\site-packages\tensorflow\python\ops\math_ops.py",
> line 3943, in add
> return gen_math_ops.add_v2(x, y, name=name) File "C:\Python37\lib\site-packages\tensorflow\python\ops\gen_math_ops.py",
> line 454, in add_v2
> _ops.raise_from_not_ok_status(e, name) File "C:\Python37\lib\site-packages\tensorflow\python\framework\ops.py",
> line 6941, in raise_from_not_ok_status
> six.raise_from(core._status_to_exception(e.code, message), None) File "<string>", line 3, in raise_from
> tensorflow.python.framework.errors_impl.ResourceExhaustedError: failed
> to allocate memory [Op:AddV2]
Any ideas what might be the problem?
A:
The error is telling you that it couldn't allocate as much VRAM as you are using. The easiest way to overcome this kind of problem is to reduce to batch-size to a number that fits on your GPU's VRAM.
A:
The error message you received tensorflow.python.framework.errors_impl.ResourceExhaustedError: failed to allocate memory [Op:AddV2] could indicate that your GPU does not have enough memory for the training job you want to run. What GPU are you using and how much vRAM does it have?
When it comes to "Out Of Memory" (OOM) errors when training, the most straightforward thing to do is to reduce the batch_size hyperparameter.
There's no straightforward way to determine what the largest batch_size you can use while training that will fit your GPU's available vRAM other than trial and error. A general rule however, is to use a power of 2 (e.g. 8, 16, 32).
A:
As this implies an out-of-memory scenario, the first thing you should try is to reduce the batch size. This could also happen if you have a very large training dataset size. You can try training the model on a subset of training data and see if that helps.
A:
If you have lot of training samples you might get ResourceExhaustedError
ResourceExhaustedError from tensorflow
For example, this error might be raised if a per-user quota is
exhausted, or perhaps the entire file system is out of space.
How to fix this error:
Setting smaller batch_size when training model using fit method:
batch_size: Integer or None. Number of samples per gradient update.
Which means is higher the batch_size more memory is required while
training.
If you are on Jupyter notebook try restarting kernel
Restarting kernel will reset your notebook and remove all the memory allocated to variables or methods
you've defined!
|
tensorflow.python.framework.errors_impl.ResourceExhaustedError: failed to allocate memory [Op:AddV2]
|
Hi I am a beginner in DL and tensorflow,
I created a CNN (you can see the model below)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=7, activation="relu", input_shape=[512, 640, 3]))
model.add(tf.keras.layers.MaxPooling2D(2))
model.add(tf.keras.layers.Conv2D(filters=128, kernel_size=3, activation="relu"))
model.add(tf.keras.layers.Conv2D(filters=128, kernel_size=3, activation="relu"))
model.add(tf.keras.layers.MaxPooling2D(2))
model.add(tf.keras.layers.Conv2D(filters=256, kernel_size=3, activation="relu"))
model.add(tf.keras.layers.Conv2D(filters=256, kernel_size=3, activation="relu"))
model.add(tf.keras.layers.MaxPooling2D(2))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(2, activation='softmax'))
optimizer = tf.keras.optimizers.SGD(learning_rate=0.2) #, momentum=0.9, decay=0.1)
model.compile(optimizer=optimizer, loss='mse', metrics=['accuracy'])
I tried building and training it with the cpu and it was completed successfully (but very slowly) so I decided to install tensorflow-gpu.
Installed everything as instructed in https://www.tensorflow.org/install/gpu).
But now when I am trying to build the model this error comes up:
> Traceback (most recent call last): File
> "C:/Users/thano/Documents/Py_workspace/AI_tensorflow/fire_detection/main.py",
> line 63, in <module>
> model = create_models.model1() File "C:\Users\thano\Documents\Py_workspace\AI_tensorflow\fire_detection\create_models.py",
> line 20, in model1
> model.add(tf.keras.layers.Dense(128, activation='relu')) File "C:\Python37\lib\site-packages\tensorflow\python\training\tracking\base.py",
> line 530, in _method_wrapper
> result = method(self, *args, **kwargs) File "C:\Python37\lib\site-packages\keras\engine\sequential.py", line 217,
> in add
> output_tensor = layer(self.outputs[0]) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 977,
> in __call__
> input_list) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 1115,
> in _functional_construction_call
> inputs, input_masks, args, kwargs) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 848,
> in _keras_tensor_symbolic_call
> return self._infer_output_signature(inputs, args, kwargs, input_masks) File
> "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 886,
> in _infer_output_signature
> self._maybe_build(inputs) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 2659,
> in _maybe_build
> self.build(input_shapes) # pylint:disable=not-callable File "C:\Python37\lib\site-packages\keras\layers\core.py", line 1185, in
> build
> trainable=True) File "C:\Python37\lib\site-packages\keras\engine\base_layer.py", line 663,
> in add_weight
> caching_device=caching_device) File "C:\Python37\lib\site-packages\tensorflow\python\training\tracking\base.py",
> line 818, in _add_variable_with_custom_getter
> **kwargs_for_getter) File "C:\Python37\lib\site-packages\keras\engine\base_layer_utils.py", line
> 129, in make_variable
> shape=variable_shape if variable_shape else None) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variables.py",
> line 266, in __call__
> return cls._variable_v1_call(*args, **kwargs) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variables.py",
> line 227, in _variable_v1_call
> shape=shape) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variables.py",
> line 205, in <lambda>
> previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variable_scope.py",
> line 2626, in default_variable_creator
> shape=shape) File "C:\Python37\lib\site-packages\tensorflow\python\ops\variables.py",
> line 270, in __call__
> return super(VariableMetaclass, cls).__call__(*args, **kwargs) File
> "C:\Python37\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py",
> line 1613, in __init__
> distribute_strategy=distribute_strategy) File "C:\Python37\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py",
> line 1740, in _init_from_args
> initial_value = initial_value() File "C:\Python37\lib\site-packages\keras\initializers\initializers_v2.py",
> line 517, in __call__
> return self._random_generator.random_uniform(shape, -limit, limit, dtype) File
> "C:\Python37\lib\site-packages\keras\initializers\initializers_v2.py",
> line 973, in random_uniform
> shape=shape, minval=minval, maxval=maxval, dtype=dtype, seed=self.seed) File
> "C:\Python37\lib\site-packages\tensorflow\python\util\dispatch.py",
> line 206, in wrapper
> return target(*args, **kwargs) File "C:\Python37\lib\site-packages\tensorflow\python\ops\random_ops.py",
> line 315, in random_uniform
> result = math_ops.add(result * (maxval - minval), minval, name=name) File
> "C:\Python37\lib\site-packages\tensorflow\python\util\dispatch.py",
> line 206, in wrapper
> return target(*args, **kwargs) File "C:\Python37\lib\site-packages\tensorflow\python\ops\math_ops.py",
> line 3943, in add
> return gen_math_ops.add_v2(x, y, name=name) File "C:\Python37\lib\site-packages\tensorflow\python\ops\gen_math_ops.py",
> line 454, in add_v2
> _ops.raise_from_not_ok_status(e, name) File "C:\Python37\lib\site-packages\tensorflow\python\framework\ops.py",
> line 6941, in raise_from_not_ok_status
> six.raise_from(core._status_to_exception(e.code, message), None) File "<string>", line 3, in raise_from
> tensorflow.python.framework.errors_impl.ResourceExhaustedError: failed
> to allocate memory [Op:AddV2]
Any ideas what might be the problem?
|
[
"The error is telling you that it couldn't allocate as much VRAM as you are using. The easiest way to overcome this kind of problem is to reduce to batch-size to a number that fits on your GPU's VRAM.\n",
"The error message you received tensorflow.python.framework.errors_impl.ResourceExhaustedError: failed to allocate memory [Op:AddV2] could indicate that your GPU does not have enough memory for the training job you want to run. What GPU are you using and how much vRAM does it have?\nWhen it comes to \"Out Of Memory\" (OOM) errors when training, the most straightforward thing to do is to reduce the batch_size hyperparameter.\nThere's no straightforward way to determine what the largest batch_size you can use while training that will fit your GPU's available vRAM other than trial and error. A general rule however, is to use a power of 2 (e.g. 8, 16, 32).\n",
"As this implies an out-of-memory scenario, the first thing you should try is to reduce the batch size. This could also happen if you have a very large training dataset size. You can try training the model on a subset of training data and see if that helps.\n",
"If you have lot of training samples you might get ResourceExhaustedError\nResourceExhaustedError from tensorflow\n\nFor example, this error might be raised if a per-user quota is\nexhausted, or perhaps the entire file system is out of space.\n\nHow to fix this error:\n\nSetting smaller batch_size when training model using fit method:\n\n\nbatch_size: Integer or None. Number of samples per gradient update.\n\n\nWhich means is higher the batch_size more memory is required while\ntraining.\n\n\nIf you are on Jupyter notebook try restarting kernel\n\n\nRestarting kernel will reset your notebook and remove all the memory allocated to variables or methods\nyou've defined!\n\n"
] |
[
7,
4,
0,
0
] |
[] |
[] |
[
"conv_neural_network",
"deep_learning",
"gpu",
"python",
"tensorflow"
] |
stackoverflow_0069641708_conv_neural_network_deep_learning_gpu_python_tensorflow.txt
|
Q:
dpdk-testpmd command executed and then hangs
I made ready dpdk compatible environment and then I tried to send packets using dpdk-testpmd and wanted to see it being received in another server.
I am using vfio-pci driver in no-IOMMU (unsafe) mode.
I ran
$./dpdk-testpmd -l 11-15 -- -i
which had output like
EAL: Detected NUMA nodes: 2
EAL: Detected static linkage of DPDK
EAL: Multi-process socket /var/run/dpdk/rte/mp_socket
EAL: Selected IOVA mode 'PA'
EAL: VFIO support initialized
EAL: Using IOMMU type 8 (No-IOMMU)
EAL: Probe PCI driver: net_i40e (8086:1572) device: 0000:01:00.1 (socket 0)
TELEMETRY: No legacy callbacks, legacy socket not created
Interactive-mode selected
testpmd: create a new mbuf pool <mb_pool_1>: n=179456, size=2176, socket=1
testpmd: preferred mempool ops selected: ring_mp_mc
testpmd: create a new mbuf pool <mb_pool_0>: n=179456, size=2176, socket=0
testpmd: preferred mempool ops selected: ring_mp_mc
Warning! port-topology=paired and odd forward ports number, the last port will pair with itself.
Configuring Port 0 (socket 0)
Port 0: E4:43:4B:4E:82:00
Checking link statuses...
Done
then
$set nbcore 4
Number of forwarding cores set to 4
testpmd> show config fwd
txonly packet forwarding - ports=1 - cores=1 - streams=1 - NUMA support enabled, MP allocation mode: native
Logical Core 12 (socket 0) forwards packets on 1 streams:
RX P=0/Q=0 (socket 0) -> TX P=0/Q=0 (socket 0) peer=BE:A6:27:C7:09:B4
my nbcore is not being set correctly, even 'txonly' mode was not being set before I set the eth-peer addr. but some parameters are working. Moreover if I don't change the burst delay my server gets crashed as soon as I start transmitting through it has 10G ethernet port (80MBps available bandwidth by calculation). Hence, I am not seeing packets at receiving server by tailing tcpdump at corresponding receiving interface. What is happening here and what am I doing wrong?
A:
based on the question & answers in the comments, the real intention is to send packets from DPDK testpmd using Intel Fortville (net_i40e) to the remote server.
The real issue for traffic not being generated is neither the application command line nor the interactive option is set to create packets via dpdk-testpmd.
In order to generate packets there are 2 options in testpmd
start tx_first: this will send out a default burst of 32 packets as soon the port is started.
forward mode tx-only: this puts the port under dpdk-testpmd in transmission-only mode. once the port is start it will transmit packets with the default packet size.
Neither of these options is utilized, hence my suggestion is
please have a walk through DPDK documentation on testpmd and its configuratio
make use of either --tx-first or use --forward-mode=txonly as per DPDK Testpmd Command-line Options
make use of either start txfirst or set fwd txonly or set fwd flwogen under interactive mode refer Testpmd Runtime Functions
with this traffic will be generated from testpmd and sent to the device (remote server). A quick example of the same is "dpdk-testpmd --file-prefix=test1 -a81:00.0 -l 7,8 --socket-mem=1024 -- --burst=128 --txd=8192 --rxd=8192 --mbcache=512 --rxq=1 --txq=1 --nb-cores=2 -a --forward-mode=io --rss-udp --enable-rx-cksum --no-mlockall --no-lsc-interrupt --enable-drop-en --no-rmv-interrupt -i"
From the above example config parameters
numbers of packets for rx-tx burst is set by --burst=128
number of rx-tx queues is configured by --rxq=1 --txq=1
number of cores to use for rx-tx is set by --nb-cores=2
to set flowgen, txonly, rxonly or io mode we use --forward-mode=io
hence in comments, it is mentioned neither set nbcore 4 or there are any configurations in testpmd args or interactive which shows the application is set for TX only.
The second part of the query is really confusing, because as it states
Moreover if I don't change the burst delay my server gets crashed as
soon as I start transmitting through it has 10G ethernet port (80MBps
available bandwidth by calculation). Hence, I am not seeing packets at
receiving server by tailing tcpdump at corresponding receiving
interface. What is happening here and what am I doing wrong?
assuming my server is the remote server to which packets are being sent by dpdk testpmd. because there is mention of I see packets with tcpdump (since Intel fortville X710 when bound with UIO driver will remove kernel netlink interface).
it is mentioned 80MBps which is around 0.08Gbps, is really strange. If the remote interface is set to promiscuous mode and there is AF_XDP application or raw socket application configured to receive traffic at line rate (10Gbps) it works. Since there is no logs or crash dump of the remote server, and it is highly unlikely actual traffic is generated from testpmd, this looks more of config or setup issue in remote server.
[EDIT-1] based on the live debug, it is confirmed
The DPDK is not installed - fixed by using ninja isntall
the DPDK nic port eno2 - is not connected to remote server directly.
the dpdk nic port eno2 is connected through switch
DPDk application testpmd is not crashing - confirmed with pgrep testpmd
instead when used with set fwd txonly, packets flood the switch and SSH packets from other port is dropped.
Solution: please use another switch for data path testing, or use direct connection to remote server.
|
dpdk-testpmd command executed and then hangs
|
I made ready dpdk compatible environment and then I tried to send packets using dpdk-testpmd and wanted to see it being received in another server.
I am using vfio-pci driver in no-IOMMU (unsafe) mode.
I ran
$./dpdk-testpmd -l 11-15 -- -i
which had output like
EAL: Detected NUMA nodes: 2
EAL: Detected static linkage of DPDK
EAL: Multi-process socket /var/run/dpdk/rte/mp_socket
EAL: Selected IOVA mode 'PA'
EAL: VFIO support initialized
EAL: Using IOMMU type 8 (No-IOMMU)
EAL: Probe PCI driver: net_i40e (8086:1572) device: 0000:01:00.1 (socket 0)
TELEMETRY: No legacy callbacks, legacy socket not created
Interactive-mode selected
testpmd: create a new mbuf pool <mb_pool_1>: n=179456, size=2176, socket=1
testpmd: preferred mempool ops selected: ring_mp_mc
testpmd: create a new mbuf pool <mb_pool_0>: n=179456, size=2176, socket=0
testpmd: preferred mempool ops selected: ring_mp_mc
Warning! port-topology=paired and odd forward ports number, the last port will pair with itself.
Configuring Port 0 (socket 0)
Port 0: E4:43:4B:4E:82:00
Checking link statuses...
Done
then
$set nbcore 4
Number of forwarding cores set to 4
testpmd> show config fwd
txonly packet forwarding - ports=1 - cores=1 - streams=1 - NUMA support enabled, MP allocation mode: native
Logical Core 12 (socket 0) forwards packets on 1 streams:
RX P=0/Q=0 (socket 0) -> TX P=0/Q=0 (socket 0) peer=BE:A6:27:C7:09:B4
my nbcore is not being set correctly, even 'txonly' mode was not being set before I set the eth-peer addr. but some parameters are working. Moreover if I don't change the burst delay my server gets crashed as soon as I start transmitting through it has 10G ethernet port (80MBps available bandwidth by calculation). Hence, I am not seeing packets at receiving server by tailing tcpdump at corresponding receiving interface. What is happening here and what am I doing wrong?
|
[
"based on the question & answers in the comments, the real intention is to send packets from DPDK testpmd using Intel Fortville (net_i40e) to the remote server.\nThe real issue for traffic not being generated is neither the application command line nor the interactive option is set to create packets via dpdk-testpmd.\nIn order to generate packets there are 2 options in testpmd\n\nstart tx_first: this will send out a default burst of 32 packets as soon the port is started.\nforward mode tx-only: this puts the port under dpdk-testpmd in transmission-only mode. once the port is start it will transmit packets with the default packet size.\n\nNeither of these options is utilized, hence my suggestion is\n\nplease have a walk through DPDK documentation on testpmd and its configuratio\nmake use of either --tx-first or use --forward-mode=txonly as per DPDK Testpmd Command-line Options\nmake use of either start txfirst or set fwd txonly or set fwd flwogen under interactive mode refer Testpmd Runtime Functions\n\nwith this traffic will be generated from testpmd and sent to the device (remote server). A quick example of the same is \"dpdk-testpmd --file-prefix=test1 -a81:00.0 -l 7,8 --socket-mem=1024 -- --burst=128 --txd=8192 --rxd=8192 --mbcache=512 --rxq=1 --txq=1 --nb-cores=2 -a --forward-mode=io --rss-udp --enable-rx-cksum --no-mlockall --no-lsc-interrupt --enable-drop-en --no-rmv-interrupt -i\"\nFrom the above example config parameters\n\nnumbers of packets for rx-tx burst is set by --burst=128 \nnumber of rx-tx queues is configured by --rxq=1 --txq=1 \nnumber of cores to use for rx-tx is set by --nb-cores=2\nto set flowgen, txonly, rxonly or io mode we use --forward-mode=io\n\nhence in comments, it is mentioned neither set nbcore 4 or there are any configurations in testpmd args or interactive which shows the application is set for TX only.\nThe second part of the query is really confusing, because as it states\n\nMoreover if I don't change the burst delay my server gets crashed as\nsoon as I start transmitting through it has 10G ethernet port (80MBps\navailable bandwidth by calculation). Hence, I am not seeing packets at\nreceiving server by tailing tcpdump at corresponding receiving\ninterface. What is happening here and what am I doing wrong?\n\nassuming my server is the remote server to which packets are being sent by dpdk testpmd. because there is mention of I see packets with tcpdump (since Intel fortville X710 when bound with UIO driver will remove kernel netlink interface).\nit is mentioned 80MBps which is around 0.08Gbps, is really strange. If the remote interface is set to promiscuous mode and there is AF_XDP application or raw socket application configured to receive traffic at line rate (10Gbps) it works. Since there is no logs or crash dump of the remote server, and it is highly unlikely actual traffic is generated from testpmd, this looks more of config or setup issue in remote server.\n[EDIT-1] based on the live debug, it is confirmed\n\nThe DPDK is not installed - fixed by using ninja isntall\nthe DPDK nic port eno2 - is not connected to remote server directly.\nthe dpdk nic port eno2 is connected through switch\nDPDk application testpmd is not crashing - confirmed with pgrep testpmd\ninstead when used with set fwd txonly, packets flood the switch and SSH packets from other port is dropped.\n\nSolution: please use another switch for data path testing, or use direct connection to remote server.\n"
] |
[
1
] |
[] |
[] |
[
"dpdk",
"dpdk_pmd"
] |
stackoverflow_0074640903_dpdk_dpdk_pmd.txt
|
Q:
Unable to connect to MySQL database in NestJS using docker
I am trying to connect my NestJS project with MySQL database using TypeORM using docker but it isn't working. However, when I run my NestJS app without docker container it connects to my local MySQL database correctly. Here is my project structure
Here is my docker-compose.yml file
version: '3.8'
services:
mysqldb:
image: mysql:latest
restart: always
cap_add:
- SYS_NICE
env_file: ./.env
environment:
- MYSQL_ROOT_PASSWORD=$MYSQLDB_ROOT_PASSWORD
- MYSQL_DATABASE=$MYSQLDB_DATABASE
ports:
- $MYSQLDB_LOCAL_PORT:$MYSQLDB_DOCKER_PORT
volumes:
- db:/var/lib/mysql
- ./db/init_database.sql:/docker-entrypoint-initdb.d/init_database.sql
networks:
- backend
demo-api:
depends_on:
- mysqldb
build: ./demo-api
restart: unless-stopped
env_file: ./.env
ports:
- $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
environment:
- DB_HOST=mysqldb
- DB_USER=$MYSQLDB_USER
- DB_PASSWORD=$MYSQLDB_ROOT_PASSWORD
- DB_NAME=$MYSQLDB_DATABASE
- DB_PORT=$MYSQLDB_DOCKER_PORT
- CLIENT_ORIGIN=$CLIENT_ORIGIN
networks:
- backend
- frontend
demo-ui:
depends_on:
- demo-api
build:
context: ./demo-ui
args:
- REACT_APP_API_BASE_URL=$CLIENT_API_BASE_URL
ports:
- $REACT_LOCAL_PORT:$REACT_DOCKER_PORT
networks:
- frontend
volumes:
db:
driver: local
networks:
backend:
frontend:
This is how my .env file looks in the project root folder
MYSQLDB_USER=root
MYSQLDB_ROOT_PASSWORD=123456
MYSQLDB_DATABASE=demo_db
MYSQLDB_LOCAL_PORT=3307
MYSQLDB_DOCKER_PORT=3306
NODE_LOCAL_PORT=6868
NODE_DOCKER_PORT=8080
CLIENT_ORIGIN=http://127.0.0.1:8888
CLIENT_API_BASE_URL=http://127.0.0.1:8080/api
REACT_LOCAL_PORT=8888
REACT_DOCKER_PORT=80
And this is how my .env file looks inside the demo-api folder
DB_TYPE=mysql
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=123456
DB_NAME=demo_db
DB_PORT=3306
# JWT
JWT_SECRET=<YOUR JWT SECRET>
NODE_DOCKER_PORT=8080
CLIENT_ORIGIN=http://127.0.0.1:8081
And this is how I am setting up the database connection in app.module.ts file
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { User } from './users/entities/user.entity';
import { UsersModule } from './users/users.module';
const entities = [User];
const DBModule = TypeOrmModule.forRootAsync({
useFactory: async () => ({
type: process.env.DB_TYPE as any,
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT),
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
entities: entities,
synchronize: true,
}),
});
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
DBModule,
UsersModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Am I missing or doing something wrong in my docker-compose.yml file?
A:
Running docker-compose down -v and then running docker-compose up again resolved the issue for me
|
Unable to connect to MySQL database in NestJS using docker
|
I am trying to connect my NestJS project with MySQL database using TypeORM using docker but it isn't working. However, when I run my NestJS app without docker container it connects to my local MySQL database correctly. Here is my project structure
Here is my docker-compose.yml file
version: '3.8'
services:
mysqldb:
image: mysql:latest
restart: always
cap_add:
- SYS_NICE
env_file: ./.env
environment:
- MYSQL_ROOT_PASSWORD=$MYSQLDB_ROOT_PASSWORD
- MYSQL_DATABASE=$MYSQLDB_DATABASE
ports:
- $MYSQLDB_LOCAL_PORT:$MYSQLDB_DOCKER_PORT
volumes:
- db:/var/lib/mysql
- ./db/init_database.sql:/docker-entrypoint-initdb.d/init_database.sql
networks:
- backend
demo-api:
depends_on:
- mysqldb
build: ./demo-api
restart: unless-stopped
env_file: ./.env
ports:
- $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
environment:
- DB_HOST=mysqldb
- DB_USER=$MYSQLDB_USER
- DB_PASSWORD=$MYSQLDB_ROOT_PASSWORD
- DB_NAME=$MYSQLDB_DATABASE
- DB_PORT=$MYSQLDB_DOCKER_PORT
- CLIENT_ORIGIN=$CLIENT_ORIGIN
networks:
- backend
- frontend
demo-ui:
depends_on:
- demo-api
build:
context: ./demo-ui
args:
- REACT_APP_API_BASE_URL=$CLIENT_API_BASE_URL
ports:
- $REACT_LOCAL_PORT:$REACT_DOCKER_PORT
networks:
- frontend
volumes:
db:
driver: local
networks:
backend:
frontend:
This is how my .env file looks in the project root folder
MYSQLDB_USER=root
MYSQLDB_ROOT_PASSWORD=123456
MYSQLDB_DATABASE=demo_db
MYSQLDB_LOCAL_PORT=3307
MYSQLDB_DOCKER_PORT=3306
NODE_LOCAL_PORT=6868
NODE_DOCKER_PORT=8080
CLIENT_ORIGIN=http://127.0.0.1:8888
CLIENT_API_BASE_URL=http://127.0.0.1:8080/api
REACT_LOCAL_PORT=8888
REACT_DOCKER_PORT=80
And this is how my .env file looks inside the demo-api folder
DB_TYPE=mysql
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=123456
DB_NAME=demo_db
DB_PORT=3306
# JWT
JWT_SECRET=<YOUR JWT SECRET>
NODE_DOCKER_PORT=8080
CLIENT_ORIGIN=http://127.0.0.1:8081
And this is how I am setting up the database connection in app.module.ts file
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { User } from './users/entities/user.entity';
import { UsersModule } from './users/users.module';
const entities = [User];
const DBModule = TypeOrmModule.forRootAsync({
useFactory: async () => ({
type: process.env.DB_TYPE as any,
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT),
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
entities: entities,
synchronize: true,
}),
});
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
DBModule,
UsersModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Am I missing or doing something wrong in my docker-compose.yml file?
|
[
"Running docker-compose down -v and then running docker-compose up again resolved the issue for me\n"
] |
[
0
] |
[] |
[] |
[
"docker",
"mysql",
"nestjs",
"typeorm"
] |
stackoverflow_0074663212_docker_mysql_nestjs_typeorm.txt
|
Q:
Auditing with ASP.NET and SQL Server
What is the best approach to audit the database for:
Make a copy of the deleted and updated records.
Save the date and user ID of the ones who did the DML which is (the ID) was saved on a session in ASP.NET
My manager told me to add 3 extra columns to each table one for the ID of whom updated the record, one for whom deleted the record and the third has a boolean value 0 for deleted and 1 for active (not deleted yet), but I think this is a work around and I'm pretty sure there is a better way to do it .
I was thinking of creating history tables and write an AFTER DELETE trigger that saves all the DML.
Is this it or is there a more plain forward way?
A:
Creating history tables and using triggers to save the DML is a common and effective approach for auditing a database. This approach allows you to track and record the changes made to the database, including who made the changes and when they were made. It also allows you to maintain a copy of deleted and updated records, which can be useful for auditing and debugging purposes.
One potential downside of this approach is that it can increase the complexity and size of the database, as you need to create additional tables and triggers to track the changes. Additionally, it can potentially impact the performance of the database, as the triggers need to be executed every time a change is made to the database.
In general, auditing the database is an important task that can help ensure the integrity and reliability of the data. The approach you choose will depend on the specific requirements and constraints of your application and database. It's always a good idea to consider the trade-offs and potential drawbacks of different approaches before implementing a solution.
A:
SQL Server 2016 onwards you can do this using Temporal tables:
A system-versioned temporal table is a type of user table designed to
keep a full history of data changes, allowing easy point-in-time
analysis. This type of temporal table is referred to as a
system-versioned temporal table because the period of validity for
each row is managed by the system (that is, the database engine).
If what you are really trying to do is to record who changed what, a better approach is to use roles and groups to prevent users altering anything they shouldn't.
|
Auditing with ASP.NET and SQL Server
|
What is the best approach to audit the database for:
Make a copy of the deleted and updated records.
Save the date and user ID of the ones who did the DML which is (the ID) was saved on a session in ASP.NET
My manager told me to add 3 extra columns to each table one for the ID of whom updated the record, one for whom deleted the record and the third has a boolean value 0 for deleted and 1 for active (not deleted yet), but I think this is a work around and I'm pretty sure there is a better way to do it .
I was thinking of creating history tables and write an AFTER DELETE trigger that saves all the DML.
Is this it or is there a more plain forward way?
|
[
"Creating history tables and using triggers to save the DML is a common and effective approach for auditing a database. This approach allows you to track and record the changes made to the database, including who made the changes and when they were made. It also allows you to maintain a copy of deleted and updated records, which can be useful for auditing and debugging purposes.\nOne potential downside of this approach is that it can increase the complexity and size of the database, as you need to create additional tables and triggers to track the changes. Additionally, it can potentially impact the performance of the database, as the triggers need to be executed every time a change is made to the database.\nIn general, auditing the database is an important task that can help ensure the integrity and reliability of the data. The approach you choose will depend on the specific requirements and constraints of your application and database. It's always a good idea to consider the trade-offs and potential drawbacks of different approaches before implementing a solution.\n",
"SQL Server 2016 onwards you can do this using Temporal tables:\n\nA system-versioned temporal table is a type of user table designed to\nkeep a full history of data changes, allowing easy point-in-time\nanalysis. This type of temporal table is referred to as a\nsystem-versioned temporal table because the period of validity for\neach row is managed by the system (that is, the database engine).\n\nIf what you are really trying to do is to record who changed what, a better approach is to use roles and groups to prevent users altering anything they shouldn't.\n"
] |
[
1,
1
] |
[] |
[] |
[
"asp.net",
"audit",
"c#",
"database",
"sql_server"
] |
stackoverflow_0074664379_asp.net_audit_c#_database_sql_server.txt
|
Q:
Reactjs child component goes into infinite loop on setting state array provided by parent in props
Parent element fetches array from server and provides child element in props to show array (tickets).
Parent Element
render() {
return (
<div style={outerBoundary}>
<ShowArray tickets={this.state.tickets}/>
</div>
)
}
Child Element
render() {
const { classes } = this.props;
var tablePadding = {
'padding':'1em',
}
this.setState({
tickets:this.props.tickets,
});
return (
<div>
<Paper className={classes.root} style={tablePadding}>
<Typography variant="title" id="tableTitle">
Array Elements
</Typography>
{this.state.tickets && this.state.tickets.length > 0 && this.state.tickets.map((n, index) => {
console.log(n, index)
return (
<TableRow> n.id </TableRow>
);
})}
)
}
Problem that i am facing is ticket state that i am setting in child element using value of props goes into infinite loop.
this.setState({
tickets:this.props.tickets,
});
A:
You can't call setState inside your render function
this.setState({
tickets:this.props.tickets,
});
as the setState function is causing a re-render so on the next render you will call setState again and you will need to re-render again so that's why you have the loop
A:
Don't setState in render. You can map props instead:
render() {
const { classes } = this.props;
var tablePadding = {
'padding':'1em',
}
return (
<div>
<Paper className={classes.root} style={tablePadding}>
<Typography variant="title" id="tableTitle">
Array Elements
</Typography>
{this.props.tickets.map((n, index) => {
console.log(n, index)
return (
<TableRow> n.id </TableRow>
);
})}
)
}
A:
Please remove this.setState from the child's render method and try the below in your child component,
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.tickets){
return {
tickets: tickets
}
}
}
Inside the render of child component,
render() {
const { classes } = this.props;
const { tickets } = this.state;
var tablePadding = {
'padding':'1em',
.
.
.
.
}
Try this...
A:
To expand on what everyone else has said, you are using setState in the render method.
It appears you are changing the state using the props
this.setState({
tickets:this.props.tickets,
});
In your code, you do not need to do this, you can use this.props. directly instead of this.state.tickets in jsx.
However, should you need to update your state based on the props, you should use getDerivedStateFromProps
With that, you can write a static method like this
static getDerivedStateFromProps(props) {
return {
tickets: props.tickets
}
}
The return value of getDerivedStateFromProps is used to update the state. In this case, the tickets key in state will be updated with the value of props.tickets.
A:
To avoid the infinite loop, call useEffect and pass in [this.props.tickets] as the second argument.
The lambda in the first argument will then only be called when this.props.tickets changes value, limiting the number of times the state will be updated.
|
Reactjs child component goes into infinite loop on setting state array provided by parent in props
|
Parent element fetches array from server and provides child element in props to show array (tickets).
Parent Element
render() {
return (
<div style={outerBoundary}>
<ShowArray tickets={this.state.tickets}/>
</div>
)
}
Child Element
render() {
const { classes } = this.props;
var tablePadding = {
'padding':'1em',
}
this.setState({
tickets:this.props.tickets,
});
return (
<div>
<Paper className={classes.root} style={tablePadding}>
<Typography variant="title" id="tableTitle">
Array Elements
</Typography>
{this.state.tickets && this.state.tickets.length > 0 && this.state.tickets.map((n, index) => {
console.log(n, index)
return (
<TableRow> n.id </TableRow>
);
})}
)
}
Problem that i am facing is ticket state that i am setting in child element using value of props goes into infinite loop.
this.setState({
tickets:this.props.tickets,
});
|
[
"You can't call setState inside your render function\nthis.setState({\n tickets:this.props.tickets,\n});\n\nas the setState function is causing a re-render so on the next render you will call setState again and you will need to re-render again so that's why you have the loop\n",
"Don't setState in render. You can map props instead:\nrender() {\n const { classes } = this.props;\n var tablePadding = {\n 'padding':'1em',\n }\n\n return (\n <div>\n <Paper className={classes.root} style={tablePadding}>\n <Typography variant=\"title\" id=\"tableTitle\">\n Array Elements\n </Typography>\n {this.props.tickets.map((n, index) => {\n console.log(n, index)\n return (\n <TableRow> n.id </TableRow>\n );\n })}\n )\n }\n\n",
"Please remove this.setState from the child's render method and try the below in your child component,\nstatic getDerivedStateFromProps(nextProps, prevState) {\n if(nextProps.tickets){\n return {\n tickets: tickets\n }\n }\n}\n\nInside the render of child component,\nrender() {\n const { classes } = this.props;\n const { tickets } = this.state;\n var tablePadding = {\n 'padding':'1em',\n .\n .\n .\n .\n}\n\nTry this...\n",
"To expand on what everyone else has said, you are using setState in the render method.\nIt appears you are changing the state using the props\nthis.setState({\n tickets:this.props.tickets,\n});\n\nIn your code, you do not need to do this, you can use this.props. directly instead of this.state.tickets in jsx.\nHowever, should you need to update your state based on the props, you should use getDerivedStateFromProps\nWith that, you can write a static method like this\nstatic getDerivedStateFromProps(props) {\n return {\n tickets: props.tickets\n }\n}\n\nThe return value of getDerivedStateFromProps is used to update the state. In this case, the tickets key in state will be updated with the value of props.tickets.\n",
"To avoid the infinite loop, call useEffect and pass in [this.props.tickets] as the second argument.\nThe lambda in the first argument will then only be called when this.props.tickets changes value, limiting the number of times the state will be updated.\n"
] |
[
2,
1,
0,
0,
0
] |
[] |
[] |
[
"javascript",
"reactjs"
] |
stackoverflow_0051818755_javascript_reactjs.txt
|
Q:
How to use a private NPM Package in Cloud Firestore?
I'm using NPM to create a package which contains typescript classes and methods that are used both in my front-end UI (angular) as well as in my backend (mostly google cloud functions).
While I can install the test package in VSCode where I am writing and testing my functions, when I try to deploy to Google Firebase Cloud functions (using firebase deploy --only functions, the deploy fails, saying in can't find my NPM package. If I make the package public, it works as expected, but I would really prefer not to make the NPM package public.
Is there some workaround?
A:
If you want to use an NPM package that is not public in your Google Cloud Functions, you will need to host the package yourself. This can be done by publishing the package to a private npm registry such as Verdaccio or Sinopia, or by hosting the package files on a web server and installing them from there.
Here are the steps for publishing your package to a private npm registry:
Install and configure the private npm registry on your server. You can follow the instructions for your chosen registry to set this up.
Publish your NPM package to the private registry. You can do this by running the npm publish command and specifying the registry URL as the --registry option. For example:
npm publish --registry=http://my-private-registry.com
Install your package in your Google Cloud Functions project by running the npm install command and specifying the registry URL as the --registry option. For example:
npm install my-private-package --registry=http://my-private-registry.com
Alternatively, you can host the package files on a web server and install them using the npm install command with the --save-exact and --fetch-retries options, as shown below:
npm install http://my-server.com/my-private-package.tgz --save-exact --fetch-retries=5
Using a private npm registry or a web server allows you to keep your NPM package private while still being able to use it in your Google Cloud Functions project. Keep in mind that hosting your own registry or web server will require additional setup and maintenance efforts on your part. It may be easier to simply make your NPM package public, but the decision ultimately depends on your specific requirements and preferences.
|
How to use a private NPM Package in Cloud Firestore?
|
I'm using NPM to create a package which contains typescript classes and methods that are used both in my front-end UI (angular) as well as in my backend (mostly google cloud functions).
While I can install the test package in VSCode where I am writing and testing my functions, when I try to deploy to Google Firebase Cloud functions (using firebase deploy --only functions, the deploy fails, saying in can't find my NPM package. If I make the package public, it works as expected, but I would really prefer not to make the NPM package public.
Is there some workaround?
|
[
"If you want to use an NPM package that is not public in your Google Cloud Functions, you will need to host the package yourself. This can be done by publishing the package to a private npm registry such as Verdaccio or Sinopia, or by hosting the package files on a web server and installing them from there.\nHere are the steps for publishing your package to a private npm registry:\nInstall and configure the private npm registry on your server. You can follow the instructions for your chosen registry to set this up.\nPublish your NPM package to the private registry. You can do this by running the npm publish command and specifying the registry URL as the --registry option. For example:\nnpm publish --registry=http://my-private-registry.com\n\nInstall your package in your Google Cloud Functions project by running the npm install command and specifying the registry URL as the --registry option. For example:\nnpm install my-private-package --registry=http://my-private-registry.com\n\nAlternatively, you can host the package files on a web server and install them using the npm install command with the --save-exact and --fetch-retries options, as shown below:\nnpm install http://my-server.com/my-private-package.tgz --save-exact --fetch-retries=5\n\nUsing a private npm registry or a web server allows you to keep your NPM package private while still being able to use it in your Google Cloud Functions project. Keep in mind that hosting your own registry or web server will require additional setup and maintenance efforts on your part. It may be easier to simply make your NPM package public, but the decision ultimately depends on your specific requirements and preferences.\n"
] |
[
0
] |
[] |
[] |
[
"firebase",
"npm"
] |
stackoverflow_0074664375_firebase_npm.txt
|
Q:
How to add new video files to HLS?
I'm having trouble live streaming a video file that is constantly updated using HLS.
Video files recorded by POST from the client are sent to the server.
The server converts the received video to HLS (.m3u8 .ts).
You can convert to .m3u8 and .ts with the following code.
def to_m3u8(movie_path: Path):
"""
Convert mp4 to m3u8.
:param movie_path:
:return: m3u8 file path
"""
m3u8_path = movie_path.parent/f"{movie_path.stem}.m3u8"
command = f"ffmpeg -i {movie_path} " \
f"-c copy " \
f"-f segment -segment_time_delta 0 " \
f"-segment_list_type hls " \
f"-movflags +faststart " \
f"-preset ultrafast " \
f"-hls_playlist_type event " \
f"-hls_flags append_list " \
f"-hls_list_size 10 " \
f"-segment_list_size 0 " \
f"-segment_list {m3u8_path} " \
f"-segment_format mpegts " \
f"{movie_path.parent}/segment_%03d.ts"
logger.info(f"command: {command}")
subprocess.run(command, shell=True)
return m3u8_path
I can see the .m3u8 .ts file being overwritten every time I receive POST data.
But when I open the .m3u8 in VLC it plays a few seconds of video and then stops.
.m3u8 file is like this.
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-ALLOW-CACHE:YES
#EXT-X-TARGETDURATION:5
#EXTINF:4.660000,
segment_000.ts
#EXTINF:4.120000,
segment_001.ts
#EXTINF:0.160000,
segment_002.ts
#EXT-X-ENDLIST
I thought #EXT-X-ENDLIST is don't need. So I remove the line. Below code.
with open(m3u8_path, "r") as f:
lines = f.readlines()
with open(m3u8_path, "w") as f:
for line in lines:
if line.startswith("#EXT-X-ENDLIST") is False:
f.write(line)
How ever it can't streaming. It's behave like a movie file.
How can I read the newly added files at any time?
Can it be handled by changing FFmpege options?
A:
To make sure that the HLS stream is constantly updated, you can use the -hls_flags append_list option in the ffmpeg command that you are using to create the HLS stream. This option will make sure that the HLS playlist is constantly updated with new segments as they are added, so that the stream is always up-to-date.
Here is an example of how you can use this option in your ffmpeg command:
command = f"ffmpeg -i {movie_path}" \
f"-c copy -map 0" \
f"-f segment -segment_time_delta 0 " \
f"-segment_list_type hls" \
f"-mov flags +faststart" \
f"-preset veryfast" \
f"-hls_playlist_type event" \
f"-hls_flags append_list" \
f"-segment_list_size 0" \
f"-segment_list {m3u8_path}" \
f"-segment_format mpegts" \
f"{movie_path.parent}/segment_%03d.ts"
You can also use the -hls_list_size option to control how many segments are included in the HLS playlist at any given time. This can be useful if you want to limit the size of the playlist to prevent it from growing too large. For example, you can use the -hls_list_size 10 option to make sure that only the 10 most recent segments are included in the playlist.
|
How to add new video files to HLS?
|
I'm having trouble live streaming a video file that is constantly updated using HLS.
Video files recorded by POST from the client are sent to the server.
The server converts the received video to HLS (.m3u8 .ts).
You can convert to .m3u8 and .ts with the following code.
def to_m3u8(movie_path: Path):
"""
Convert mp4 to m3u8.
:param movie_path:
:return: m3u8 file path
"""
m3u8_path = movie_path.parent/f"{movie_path.stem}.m3u8"
command = f"ffmpeg -i {movie_path} " \
f"-c copy " \
f"-f segment -segment_time_delta 0 " \
f"-segment_list_type hls " \
f"-movflags +faststart " \
f"-preset ultrafast " \
f"-hls_playlist_type event " \
f"-hls_flags append_list " \
f"-hls_list_size 10 " \
f"-segment_list_size 0 " \
f"-segment_list {m3u8_path} " \
f"-segment_format mpegts " \
f"{movie_path.parent}/segment_%03d.ts"
logger.info(f"command: {command}")
subprocess.run(command, shell=True)
return m3u8_path
I can see the .m3u8 .ts file being overwritten every time I receive POST data.
But when I open the .m3u8 in VLC it plays a few seconds of video and then stops.
.m3u8 file is like this.
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-ALLOW-CACHE:YES
#EXT-X-TARGETDURATION:5
#EXTINF:4.660000,
segment_000.ts
#EXTINF:4.120000,
segment_001.ts
#EXTINF:0.160000,
segment_002.ts
#EXT-X-ENDLIST
I thought #EXT-X-ENDLIST is don't need. So I remove the line. Below code.
with open(m3u8_path, "r") as f:
lines = f.readlines()
with open(m3u8_path, "w") as f:
for line in lines:
if line.startswith("#EXT-X-ENDLIST") is False:
f.write(line)
How ever it can't streaming. It's behave like a movie file.
How can I read the newly added files at any time?
Can it be handled by changing FFmpege options?
|
[
"To make sure that the HLS stream is constantly updated, you can use the -hls_flags append_list option in the ffmpeg command that you are using to create the HLS stream. This option will make sure that the HLS playlist is constantly updated with new segments as they are added, so that the stream is always up-to-date.\nHere is an example of how you can use this option in your ffmpeg command:\ncommand = f\"ffmpeg -i {movie_path}\" \\\n f\"-c copy -map 0\" \\\n f\"-f segment -segment_time_delta 0 \" \\\n f\"-segment_list_type hls\" \\\n f\"-mov flags +faststart\" \\\n f\"-preset veryfast\" \\\n f\"-hls_playlist_type event\" \\\n f\"-hls_flags append_list\" \\\n f\"-segment_list_size 0\" \\\n f\"-segment_list {m3u8_path}\" \\\n f\"-segment_format mpegts\" \\\n f\"{movie_path.parent}/segment_%03d.ts\"\n\nYou can also use the -hls_list_size option to control how many segments are included in the HLS playlist at any given time. This can be useful if you want to limit the size of the playlist to prevent it from growing too large. For example, you can use the -hls_list_size 10 option to make sure that only the 10 most recent segments are included in the playlist.\n"
] |
[
0
] |
[] |
[] |
[
"ffmpeg",
"http_live_streaming",
"python"
] |
stackoverflow_0074664406_ffmpeg_http_live_streaming_python.txt
|
Q:
How to change a File's last Access/Modify/Change Date?
I have some files on a scratch drive of a HPC server. The server automatically deletes files which are 2 weeks old.
Using stat filename.txt I can see the follow information. Is there a way to somehow open/touch/manipulate files to update the Access date to prevent deletion without actually changing the file?
File: ‘name’
Size: 2583438768 Blocks: 4819945 IO Block: 524288 regular file
Device: xxh/xxxd Inode: 10354xxxx Links: 1
Access: (/-rw-r--r--) Uid: (/) Gid: (/)
Context: system_u:object_r:tmp_t:s0
Access: 2022-11-22 09:47:33.000000000 -0800
Modify: 2019-12-06 06:50:33.000000000 -0800
Change: 2022-11-22 16:54:55.000000000 -0800
Birth: -
A:
Use the Linux touch command, eg:
$ touch filename.txt
|
How to change a File's last Access/Modify/Change Date?
|
I have some files on a scratch drive of a HPC server. The server automatically deletes files which are 2 weeks old.
Using stat filename.txt I can see the follow information. Is there a way to somehow open/touch/manipulate files to update the Access date to prevent deletion without actually changing the file?
File: ‘name’
Size: 2583438768 Blocks: 4819945 IO Block: 524288 regular file
Device: xxh/xxxd Inode: 10354xxxx Links: 1
Access: (/-rw-r--r--) Uid: (/) Gid: (/)
Context: system_u:object_r:tmp_t:s0
Access: 2022-11-22 09:47:33.000000000 -0800
Modify: 2019-12-06 06:50:33.000000000 -0800
Change: 2022-11-22 16:54:55.000000000 -0800
Birth: -
|
[
"Use the Linux touch command, eg:\n$ touch filename.txt\n\n"
] |
[
1
] |
[] |
[] |
[
"file",
"hpc",
"linux"
] |
stackoverflow_0074664397_file_hpc_linux.txt
|
Q:
Multi-Tenant Database Design - Staff and Customers Can Belong To Multiple Tenants
I'm designing a multi-tenant application and have read this post Is this multi-tenant database design is good concerning multi-tenant database design. The post emphasises the fact that a customer or staff can belong to multiple different tenants. I really enjoyed the answer given by user: Benny Hill and like the table design but am struggling with the importance of the customers table.
The foreign-key in the customers table links to the users table which contains for instance the first and last names of the user and other user specific information.
It appears to me that any specific information (eg: date_joined, date_left, etc...) about a customer and a particular tenant will be stored in the join table (customers_tenants)
It also appears to me that no additional information can be stored in the customers table because the customers table is about the customer alone and have no connection to a tenant. I can't think from the top of my head any relevant information/data that can be stored in the customers table which will be relevant to all the multiple tenants a customer is member of. Maybe someone can prove me wrong.
My conclusion is that the customers table is not needed. The customer in the join table customers_tenants can be replaced directly with the user from the users table. I don't see the need of the customers table at all.
I hope someone can clarify to me why the customers table is important.
A:
The customers details table is still needed.
What is unneeded though is the details of the costumers ( date_joined, date_left, etc...) being repeated on the join table customers_tenants
as long as it is a one to many table the details shouldn't be repeated in each row for better performance.
|
Multi-Tenant Database Design - Staff and Customers Can Belong To Multiple Tenants
|
I'm designing a multi-tenant application and have read this post Is this multi-tenant database design is good concerning multi-tenant database design. The post emphasises the fact that a customer or staff can belong to multiple different tenants. I really enjoyed the answer given by user: Benny Hill and like the table design but am struggling with the importance of the customers table.
The foreign-key in the customers table links to the users table which contains for instance the first and last names of the user and other user specific information.
It appears to me that any specific information (eg: date_joined, date_left, etc...) about a customer and a particular tenant will be stored in the join table (customers_tenants)
It also appears to me that no additional information can be stored in the customers table because the customers table is about the customer alone and have no connection to a tenant. I can't think from the top of my head any relevant information/data that can be stored in the customers table which will be relevant to all the multiple tenants a customer is member of. Maybe someone can prove me wrong.
My conclusion is that the customers table is not needed. The customer in the join table customers_tenants can be replaced directly with the user from the users table. I don't see the need of the customers table at all.
I hope someone can clarify to me why the customers table is important.
|
[
"The customers details table is still needed.\nWhat is unneeded though is the details of the costumers ( date_joined, date_left, etc...) being repeated on the join table customers_tenants\nas long as it is a one to many table the details shouldn't be repeated in each row for better performance.\n"
] |
[
0
] |
[] |
[] |
[
"database",
"database_design",
"multi_tenant",
"sql"
] |
stackoverflow_0074664207_database_database_design_multi_tenant_sql.txt
|
Q:
In pytorch torchscript, how to define mutiple entry point
Have a torch model as follow :
MyModel
update(self) : Update some params.
predict(self,X) : Predict with some input tensor.
When exporting to torchscript, is there a way to have 2 entry points:
One for update()
One for predict()
A:
Yes, you can define multiple entry points in a TorchScript model by using the @torch.jit.export decorator to specify which methods should be exported as entry points.
For example, given a PyTorch model defined as follows:
class MyModel(nn.Module):
def update(self):
# Update some params.
def predict(self, X):
# Predict with some input tensor.
You can use the @torch.jit.export decorator to specify that the update and predict methods should be exported as entry points in the resulting TorchScript module, like this:
class MyModel(nn.Module):
@torch.jit.export
def update(self):
# Update some params.
@torch.jit.export
def predict(self, X):
# Predict with some input tensor.
You can then export the MyModel class to TorchScript using the following code:
model = MyModel()
traced_model = torch.jit.script(model)
The resulting TorchScript module will have two entry points, update and predict, which you can use to call the corresponding methods of your model.
traced_model.update()
traced_model.predict(X)
Alternatively, you can also use the torch.jit.export decorator at the class level to specify that all of the methods in the class should be exported as entry points in the resulting TorchScript module. For example:
@torch.jit.export
class MyModel(nn.Module):
def update(self):
# Update some params.
def predict(self, X):
# Predict with some input tensor.
In this code, the @torch.jit.export decorator is applied to the MyModel class itself, which tells the torch.jit.script function to export all of the methods in the MyModel class as entry points in the resulting TorchScript module.
You can then export the MyModel class to TorchScript using the following code:
model = MyModel()
traced_model = torch.jit.script(model)
The resulting TorchScript module will have two entry points, update and predict, which you can use to call the corresponding methods of your model.
traced_model.update()
traced_model.predict(X)
|
In pytorch torchscript, how to define mutiple entry point
|
Have a torch model as follow :
MyModel
update(self) : Update some params.
predict(self,X) : Predict with some input tensor.
When exporting to torchscript, is there a way to have 2 entry points:
One for update()
One for predict()
|
[
"Yes, you can define multiple entry points in a TorchScript model by using the @torch.jit.export decorator to specify which methods should be exported as entry points.\nFor example, given a PyTorch model defined as follows:\nclass MyModel(nn.Module):\ndef update(self):\n # Update some params.\n\ndef predict(self, X):\n # Predict with some input tensor.\n\nYou can use the @torch.jit.export decorator to specify that the update and predict methods should be exported as entry points in the resulting TorchScript module, like this:\nclass MyModel(nn.Module):\[email protected]\ndef update(self):\n # Update some params.\n\[email protected]\ndef predict(self, X):\n # Predict with some input tensor.\n\nYou can then export the MyModel class to TorchScript using the following code:\nmodel = MyModel()\ntraced_model = torch.jit.script(model)\n\nThe resulting TorchScript module will have two entry points, update and predict, which you can use to call the corresponding methods of your model.\ntraced_model.update()\ntraced_model.predict(X)\n\nAlternatively, you can also use the torch.jit.export decorator at the class level to specify that all of the methods in the class should be exported as entry points in the resulting TorchScript module. For example:\[email protected]\nclass MyModel(nn.Module):\n def update(self):\n # Update some params.\n\n def predict(self, X):\n # Predict with some input tensor.\n\nIn this code, the @torch.jit.export decorator is applied to the MyModel class itself, which tells the torch.jit.script function to export all of the methods in the MyModel class as entry points in the resulting TorchScript module.\nYou can then export the MyModel class to TorchScript using the following code:\nmodel = MyModel()\ntraced_model = torch.jit.script(model)\n\nThe resulting TorchScript module will have two entry points, update and predict, which you can use to call the corresponding methods of your model.\ntraced_model.update()\ntraced_model.predict(X)\n\n"
] |
[
1
] |
[] |
[] |
[
"onnx",
"onnxruntime",
"pytorch",
"torchscript"
] |
stackoverflow_0074664418_onnx_onnxruntime_pytorch_torchscript.txt
|
Q:
How to update child with new fields in firebase realtime database?
During authentication the user is created with email and user name. Now I am trying to update that user with new fields like first name, last name, address, etc on registration time. But when I try to insert a new field it updates with the new fields and the old fields are removed.
public class User {
String uid,userName,firstName,lastName,email;
public User() {
}
//called on the time of auth
public User(String email, String userName) {
this.email = email;
this.userName = userName;
}
//called on registration process
public User( String firstName, String lastName,String mobileNo) {
this.firstName = firstName;
this.lastName = lastName;
this.mobileNo = mobileNo;
}
@Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("email", email);
result.put("userName", userName);
result.put("firstName", firstName);
result.put("lastName", lastName);
return result;
}
The following methods are used to add and update the firebase database. The addUser method is functional properly but during the update method it replace the old data.
String userId = getUid(); // its retrun firebase current user id as I use
// auth authentication
//first time entry in database
private void writeNewUser(String name, String email) {
User user = new User(name, email);
Map<String, Object> postValues = user.toMap();
mDatabase.child("users").child(userId).setValue(postValues);
}
//Its called during the registration porecess
private void updateUser() {
User user = new User(firstName, lastName, email);
Map<String, Object> postValues = user.toMap();
mDatabase.child("users").child(userId).updateChildren(postValues);
}
A:
I think the solution is quite simple, just get the old value first, before update, and modify with new fields or new value, then do the update.
To get the oldValues I don't know if using getValue(User.class) will return error or not, so for safety, let's just loop from the children.
private void updateUser() {
mDatabase.child("users").child(userId)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> postValues = new HashMap<String,Object>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
postValues.put(snapshot.getKey(),snapshot.getValue());
}
postValues.put("email", email);
postValues.put("firstName", firstName);
postValues.put("lastName", lastName);
mDatabase.child("users").child(userId).updateChildren(postValues);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
}
);
}
And also, the constructor that you wrote for new User(String,String,String) is for firstName, lastName, and mobileNo Is the field that gone is perhaps the email?
A:
I don't know for java
in javascript to update the token on the profile, i use this way for edit value "Token" :
const db = getDatabase();
const postData = "123456789";
const updates = {};
updates["users/" + userID + "/" + "Token"] = postData;
return update(ref(db), updates)
with a data structure in firebase like this :
{
"users": {
"UuhktDC8QmaWZZtEYbFHFS7cOsK3" : {
"Name" : "Roma",
"Email" : "[email protected]",
"Token" : "faaQ7aRkTNCGOTG"
}
}
}
|
How to update child with new fields in firebase realtime database?
|
During authentication the user is created with email and user name. Now I am trying to update that user with new fields like first name, last name, address, etc on registration time. But when I try to insert a new field it updates with the new fields and the old fields are removed.
public class User {
String uid,userName,firstName,lastName,email;
public User() {
}
//called on the time of auth
public User(String email, String userName) {
this.email = email;
this.userName = userName;
}
//called on registration process
public User( String firstName, String lastName,String mobileNo) {
this.firstName = firstName;
this.lastName = lastName;
this.mobileNo = mobileNo;
}
@Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("email", email);
result.put("userName", userName);
result.put("firstName", firstName);
result.put("lastName", lastName);
return result;
}
The following methods are used to add and update the firebase database. The addUser method is functional properly but during the update method it replace the old data.
String userId = getUid(); // its retrun firebase current user id as I use
// auth authentication
//first time entry in database
private void writeNewUser(String name, String email) {
User user = new User(name, email);
Map<String, Object> postValues = user.toMap();
mDatabase.child("users").child(userId).setValue(postValues);
}
//Its called during the registration porecess
private void updateUser() {
User user = new User(firstName, lastName, email);
Map<String, Object> postValues = user.toMap();
mDatabase.child("users").child(userId).updateChildren(postValues);
}
|
[
"I think the solution is quite simple, just get the old value first, before update, and modify with new fields or new value, then do the update. \nTo get the oldValues I don't know if using getValue(User.class) will return error or not, so for safety, let's just loop from the children.\nprivate void updateUser() { \n mDatabase.child(\"users\").child(userId)\n .addListenerForSingleValueEvent(new ValueEventListener() {\n @Override\n public void onDataChange(DataSnapshot dataSnapshot) {\n Map<String, Object> postValues = new HashMap<String,Object>();\n for (DataSnapshot snapshot : dataSnapshot.getChildren()) {\n postValues.put(snapshot.getKey(),snapshot.getValue());\n }\n postValues.put(\"email\", email);\n postValues.put(\"firstName\", firstName);\n postValues.put(\"lastName\", lastName);\n mDatabase.child(\"users\").child(userId).updateChildren(postValues);\n }\n\n @Override\n public void onCancelled(DatabaseError databaseError) {}\n }\n );\n}\n\nAnd also, the constructor that you wrote for new User(String,String,String) is for firstName, lastName, and mobileNo Is the field that gone is perhaps the email?\n",
"I don't know for java \nin javascript to update the token on the profile, i use this way for edit value \"Token\" :\nconst db = getDatabase();\nconst postData = \"123456789\";\nconst updates = {};\n\nupdates[\"users/\" + userID + \"/\" + \"Token\"] = postData;\n\nreturn update(ref(db), updates)\n\nwith a data structure in firebase like this :\n{\n\"users\": {\n \"UuhktDC8QmaWZZtEYbFHFS7cOsK3\" : {\n \"Name\" : \"Roma\",\n \"Email\" : \"[email protected]\",\n \"Token\" : \"faaQ7aRkTNCGOTG\"\n }\n }\n}\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"android",
"firebase",
"firebase_realtime_database"
] |
stackoverflow_0044224083_android_firebase_firebase_realtime_database.txt
|
Q:
PHP Loop does not contain any errors but its not working either. Here's my code:
My while loop not working, I also have a while loop on the same PHP page, but this one doesn't working, I dont understand why. Heres my code:
$posts_query = "SELECT * FROM posts ORDER BY id";
$posts_result = mysqli_query($connection, $posts_query);
<ul class="accordion__wrapper">
<?php while ($post_side = mysqli_fetch_assoc($posts_result)) : ?>
<?php
$category_id = $post_side['category_id'];
$category_query = "SELECT category_name FROM categories WHERE id=$category_id";
$category_result = mysqli_query($connection, $category_query);
$category = mysqli_fetch_assoc($category_result);
?>
<li class="accordion__menu accordion__products-bg">
<button class="accordion__effect accordion__products-btn">
<?= $category['category_name'] ?>
</button>
<div class="accordion__panel accordion__products-list">
<p>
<a href="#articleOne" data-localscroll="true">Artikel 1</a>
</p>
<p>
<a href="#articleTwo" data-localscroll="true">Artikel 2</a>
</p>
<p>
<a href="#articleThree" data-localscroll="true">Artikel 3</a>
</p>
</div>
</li>
<?php endwhile ?>
</ul>
Its not showing any error, and the doesn't show either...
A:
Already solved, the problem was happen because I try to the same variable with only one call.. But I think there should be another way that can siplify it
$categories_query = "SELECT * FROM categories ORDER BY id";
$categories_result = mysqli_query($connection, $categories_query);
$side_categories_query = "SELECT * FROM categories ORDER BY id";
$side_categories_result = mysqli_query($connection, $side_categories_query);
<?php
$no = 1;
while ($category = mysqli_fetch_assoc($categories_result)) : ?>
<button class="product__top-btn products-btn-<?= $no; ?>">
<?= $category['category_name'] ?>
</button>
<?php $no++;
endwhile ?>
<?php $no = 1;
while ($side_category = mysqli_fetch_assoc($side_categories_result))
: ?>
<div class="accordion__menu accordion__products-bg">
<button class="accordion__effect accordion__products-btn">
<?= $side_category['category_name'] ?>
</button>
</div>
<?php $no++;
endwhile ?>
|
PHP Loop does not contain any errors but its not working either. Here's my code:
|
My while loop not working, I also have a while loop on the same PHP page, but this one doesn't working, I dont understand why. Heres my code:
$posts_query = "SELECT * FROM posts ORDER BY id";
$posts_result = mysqli_query($connection, $posts_query);
<ul class="accordion__wrapper">
<?php while ($post_side = mysqli_fetch_assoc($posts_result)) : ?>
<?php
$category_id = $post_side['category_id'];
$category_query = "SELECT category_name FROM categories WHERE id=$category_id";
$category_result = mysqli_query($connection, $category_query);
$category = mysqli_fetch_assoc($category_result);
?>
<li class="accordion__menu accordion__products-bg">
<button class="accordion__effect accordion__products-btn">
<?= $category['category_name'] ?>
</button>
<div class="accordion__panel accordion__products-list">
<p>
<a href="#articleOne" data-localscroll="true">Artikel 1</a>
</p>
<p>
<a href="#articleTwo" data-localscroll="true">Artikel 2</a>
</p>
<p>
<a href="#articleThree" data-localscroll="true">Artikel 3</a>
</p>
</div>
</li>
<?php endwhile ?>
</ul>
Its not showing any error, and the doesn't show either...
|
[
"Already solved, the problem was happen because I try to the same variable with only one call.. But I think there should be another way that can siplify it\n$categories_query = \"SELECT * FROM categories ORDER BY id\";\n$categories_result = mysqli_query($connection, $categories_query);\n$side_categories_query = \"SELECT * FROM categories ORDER BY id\";\n$side_categories_result = mysqli_query($connection, $side_categories_query);\n <?php\n $no = 1;\n while ($category = mysqli_fetch_assoc($categories_result)) : ?>\n <button class=\"product__top-btn products-btn-<?= $no; ?>\">\n <?= $category['category_name'] ?>\n </button>\n <?php $no++;\n endwhile ?>\n <?php $no = 1;\n while ($side_category = mysqli_fetch_assoc($side_categories_result)) \n : ?>\n <div class=\"accordion__menu accordion__products-bg\">\n <button class=\"accordion__effect accordion__products-btn\">\n <?= $side_category['category_name'] ?>\n </button>\n </div>\n <?php $no++;\n endwhile ?>\n\n"
] |
[
0
] |
[] |
[] |
[
"html",
"php"
] |
stackoverflow_0074663718_html_php.txt
|
Q:
Firebase Project ID must be in lowercase
I'm trying to host a portal on Firebase.
I have currently installed Firebase CLI and when I load up terminal and type the following commande in the location directory that contains the project root folder I get the following error message.
$ init firebase
Error: Invalid project id: XXXXXXXXXXX.
Note: Project id must be all lowercase.
My Project ID on Firebase is grabcab-cd93e so it is in lower case.
How can I fix this?
A:
I got similar issue, and following page helps me.
https://github.com/firebase/firebase-tools/issues/2203
I open my ~/.config/configstore/firebase-tools.json, and delete the line that project's name includes uppercase.
There should be the project XXXXXXXXXXX as you say.
A:
I am not sure but in my case I have created branch in uppercase and while setting up firebase project for prod and staging, ProjectId accidentally happens to be in uppercase(firebase took the branchName for projectId), and since then I was getting this exact same error and then all commands fails,
even firebase use --clear.
This happens even if there is no .firebaserc file.
I am able to solve this using following these two commands.
firebase use --clear --project "ProjectName" (Cleared active project.)
firebase use --add (to define a new project alias).
|
Firebase Project ID must be in lowercase
|
I'm trying to host a portal on Firebase.
I have currently installed Firebase CLI and when I load up terminal and type the following commande in the location directory that contains the project root folder I get the following error message.
$ init firebase
Error: Invalid project id: XXXXXXXXXXX.
Note: Project id must be all lowercase.
My Project ID on Firebase is grabcab-cd93e so it is in lower case.
How can I fix this?
|
[
"I got similar issue, and following page helps me.\nhttps://github.com/firebase/firebase-tools/issues/2203\nI open my ~/.config/configstore/firebase-tools.json, and delete the line that project's name includes uppercase.\nThere should be the project XXXXXXXXXXX as you say.\n",
"I am not sure but in my case I have created branch in uppercase and while setting up firebase project for prod and staging, ProjectId accidentally happens to be in uppercase(firebase took the branchName for projectId), and since then I was getting this exact same error and then all commands fails,\neven firebase use --clear.\nThis happens even if there is no .firebaserc file.\nI am able to solve this using following these two commands.\nfirebase use --clear --project \"ProjectName\" (Cleared active project.)\n\nfirebase use --add (to define a new project alias).\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"firebase",
"firebase_cli"
] |
stackoverflow_0063678267_firebase_firebase_cli.txt
|
Q:
Can I use #ifdef in a .def?
Can I use #ifdef sections in a .def file for a dll? E.g.:
LIBRARY "mydll"
EXPORTS
checkRequirements
createDevice
installDriver
isPastVersionInstalled
removeDevice
#ifdef myVar
doSomethingElse
#endif
A:
No, not possible, it is not a file that's pre-processed. Although I supposed you could by running the preprocessor to generate another .def file and link that one.
The more effective approach is to eliminate the need for a .def file completely. Use __declspec(dllexport) in your code on the functions that should be exported. Then any #ifdef in that code will automatically ensure that a function is neither compiled nor exported.
A:
I don't know if .def files can have that exactly, but you can certainly create a file named (for example) mydll.def.in and then use the compiler preprocessor to generate the .def file at build time.
On Linux that would be done like this:
cpp -DmyVar=1 mydll.def.in > mydll.def
I imagine you're doing this on Windows, and I can't help you with that, but it'll be similar.
The only gotcha is that, depending on your compiler, you might need the rest of the file to consist of valid C tokens, and you mustn't have any symbols in the file that can be confused with macros. Gcc has an option --traditional-cpp to get around this sort of trouble, and your compiler might have the same sort of thing.
A:
I recently needed to solve exactly the same issue. I needed only small differences in otherwise large .def file; differences that change per architecture and between release/debug build. I found the regular C preprocessor unsuitable (and unusable without modifications) for this purpose.
So I ended up writing my own, much simpler, preprocessor for the .def files: github.com/tringi/defprep
Usage example is in the middle of the page.
The syntax is simple: Rows annotated with #ABC or #ABC=def at the end of the line will make it into output only if there's ABC, or ABC=def respectively, on the command line. I usually pass just a couple of Visual Studio macros like $(ProcessorArchitecture) and $(Configuration).
|
Can I use #ifdef in a .def?
|
Can I use #ifdef sections in a .def file for a dll? E.g.:
LIBRARY "mydll"
EXPORTS
checkRequirements
createDevice
installDriver
isPastVersionInstalled
removeDevice
#ifdef myVar
doSomethingElse
#endif
|
[
"No, not possible, it is not a file that's pre-processed. Although I supposed you could by running the preprocessor to generate another .def file and link that one.\nThe more effective approach is to eliminate the need for a .def file completely. Use __declspec(dllexport) in your code on the functions that should be exported. Then any #ifdef in that code will automatically ensure that a function is neither compiled nor exported.\n",
"I don't know if .def files can have that exactly, but you can certainly create a file named (for example) mydll.def.in and then use the compiler preprocessor to generate the .def file at build time.\nOn Linux that would be done like this:\ncpp -DmyVar=1 mydll.def.in > mydll.def\n\nI imagine you're doing this on Windows, and I can't help you with that, but it'll be similar.\nThe only gotcha is that, depending on your compiler, you might need the rest of the file to consist of valid C tokens, and you mustn't have any symbols in the file that can be confused with macros. Gcc has an option --traditional-cpp to get around this sort of trouble, and your compiler might have the same sort of thing.\n",
"I recently needed to solve exactly the same issue. I needed only small differences in otherwise large .def file; differences that change per architecture and between release/debug build. I found the regular C preprocessor unsuitable (and unusable without modifications) for this purpose.\nSo I ended up writing my own, much simpler, preprocessor for the .def files: github.com/tringi/defprep\nUsage example is in the middle of the page.\nThe syntax is simple: Rows annotated with #ABC or #ABC=def at the end of the line will make it into output only if there's ABC, or ABC=def respectively, on the command line. I usually pass just a couple of Visual Studio macros like $(ProcessorArchitecture) and $(Configuration).\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"conditional_compilation",
"dll",
"function"
] |
stackoverflow_0010616284_conditional_compilation_dll_function.txt
|
Q:
python continue download from where I left off
I'm trying to download a very large file in collab to my gDrive. Sometimes the connection cuts out, and It requires I restart. Is there a way I can download from where I left off?
My code looks like so:
from requests import get
import sys
def download(url, file_name):
# open in binary mode
with open(file_name, "wb") as f:
print("Downloading %s" % file_name)
response = get(url, stream=True)
total_length = response.headers.get('content-length')
if total_length is None: # no content length header
f.write(response.content)
else:
dl = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
done = int(50 * dl / total_length)
sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)) )
sys.stdout.flush()
A:
To download a file from a specific point, you can use the Range request header to specify the byte range that you want to download. For example, to download the last 100 bytes of a file, you can use the following code:
from requests import get
import sys
def download(url, file_name, start_byte, end_byte):
# open in binary mode
with open(file_name, "wb") as f:
print("Downloading %s" % file_name)
response = get(url, headers={'Range': f'bytes={start_byte}-{end_byte}'}, stream=True)
total_length = response.headers.get('content-length')
if total_length is None: # no content length header
f.write(response.content)
else:
dl = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
done = int(50 * dl / total_length)
sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)) )
sys.stdout.flush()
# download the last 100 bytes of the file
download(url, file_name, -100, None)
Note that not all servers support the Range header.
|
python continue download from where I left off
|
I'm trying to download a very large file in collab to my gDrive. Sometimes the connection cuts out, and It requires I restart. Is there a way I can download from where I left off?
My code looks like so:
from requests import get
import sys
def download(url, file_name):
# open in binary mode
with open(file_name, "wb") as f:
print("Downloading %s" % file_name)
response = get(url, stream=True)
total_length = response.headers.get('content-length')
if total_length is None: # no content length header
f.write(response.content)
else:
dl = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
done = int(50 * dl / total_length)
sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)) )
sys.stdout.flush()
|
[
"To download a file from a specific point, you can use the Range request header to specify the byte range that you want to download. For example, to download the last 100 bytes of a file, you can use the following code:\nfrom requests import get\nimport sys\n\ndef download(url, file_name, start_byte, end_byte):\n # open in binary mode\n with open(file_name, \"wb\") as f:\n print(\"Downloading %s\" % file_name)\n response = get(url, headers={'Range': f'bytes={start_byte}-{end_byte}'}, stream=True)\n total_length = response.headers.get('content-length')\n\n if total_length is None: # no content length header\n f.write(response.content)\n else:\n dl = 0\n total_length = int(total_length)\n for data in response.iter_content(chunk_size=4096):\n dl += len(data)\n f.write(data)\n done = int(50 * dl / total_length)\n sys.stdout.write(\"\\r[%s%s]\" % ('=' * done, ' ' * (50-done)) ) \n sys.stdout.flush()\n\n# download the last 100 bytes of the file\ndownload(url, file_name, -100, None)\n\nNote that not all servers support the Range header.\n"
] |
[
1
] |
[] |
[] |
[
"download",
"python"
] |
stackoverflow_0074664425_download_python.txt
|
Q:
Converting currency to numeric value
Since they are in object format, I am trying to create a new variable by converting prices in my df to a numeric value.
I tried to remove the ',' and '$' from the numbers in the column and then convert them to a different type with pd.to_numeric
df_l['price_MXN2'] = df_l['price_MXN'].str.replace(',','')
df_l['price_MXN2'] = df_l['price_MXN'].str.replace('$','')
df_l['price_MXN2'] = pd.to_numeric(df_l['price_MXN2'])
I get "ValueError: Unable to parse string at position 0"
A:
It looks like you're trying to convert a currency string to a numeric value in a Pandas DataFrame. The error message "ValueError: Unable to parse string at position 0" indicates that the to_numeric() method is unable to parse the string at the first position (index 0) in the price_MXN2 column.
One possible reason for this error is that the price_MXN2 column contains invalid characters or non-numeric values. You can check the values in the price_MXN2 column using the df_l['price_MXN2'].unique() method, which will return an array of all unique values in the column.
If the price_MXN2 column contains invalid characters or non-numeric values, you can use the pd.to_numeric() method with the errors parameter set to 'coerce' to convert the values to numeric while ignoring or replacing any invalid characters. Here's an example:
# Convert the price_MXN2 column to numeric, ignoring any invalid values
df_l['price_MXN2'] = pd.to_numeric(df_l['price_MXN2'], errors='coerce')
This will convert the price_MXN2 column to numeric, and any invalid values will be replaced with NaN. You can then use the df_l.dropna() method to remove any rows with missing values from the DataFrame.
|
Converting currency to numeric value
|
Since they are in object format, I am trying to create a new variable by converting prices in my df to a numeric value.
I tried to remove the ',' and '$' from the numbers in the column and then convert them to a different type with pd.to_numeric
df_l['price_MXN2'] = df_l['price_MXN'].str.replace(',','')
df_l['price_MXN2'] = df_l['price_MXN'].str.replace('$','')
df_l['price_MXN2'] = pd.to_numeric(df_l['price_MXN2'])
I get "ValueError: Unable to parse string at position 0"
|
[
"It looks like you're trying to convert a currency string to a numeric value in a Pandas DataFrame. The error message \"ValueError: Unable to parse string at position 0\" indicates that the to_numeric() method is unable to parse the string at the first position (index 0) in the price_MXN2 column.\nOne possible reason for this error is that the price_MXN2 column contains invalid characters or non-numeric values. You can check the values in the price_MXN2 column using the df_l['price_MXN2'].unique() method, which will return an array of all unique values in the column.\nIf the price_MXN2 column contains invalid characters or non-numeric values, you can use the pd.to_numeric() method with the errors parameter set to 'coerce' to convert the values to numeric while ignoring or replacing any invalid characters. Here's an example:\n # Convert the price_MXN2 column to numeric, ignoring any invalid values\ndf_l['price_MXN2'] = pd.to_numeric(df_l['price_MXN2'], errors='coerce')\n\nThis will convert the price_MXN2 column to numeric, and any invalid values will be replaced with NaN. You can then use the df_l.dropna() method to remove any rows with missing values from the DataFrame.\n"
] |
[
0
] |
[] |
[] |
[
"converters",
"currency",
"dtype",
"pandas"
] |
stackoverflow_0074664454_converters_currency_dtype_pandas.txt
|
Q:
How HashMap stores Character keys? [Java]
public static void main(String[] args) {
Map<Character, Integer> map = new HashMap();
map.put('A',1);
map.put('a',1);
map.put('f',5);
map.put('t',5);
map.put('m',4);
map.put('r',3);
System.out.println(map.keySet());
}
Not able to understand why here the output is not in order, like:
[A,a,f,t,m,r]
instead, it is printing:
[A, a, r, t, f, m]
can anyone please explain?
Thank you :)
A:
A HashMap makes no guarantees about the internal ordering, other than it being consistent - i.e., if you run the same program twice with the same JDK, you'll get the same order.
If you want a HashMap that preserves the order of insertion, you could use a LinkedHashMap.
|
How HashMap stores Character keys? [Java]
|
public static void main(String[] args) {
Map<Character, Integer> map = new HashMap();
map.put('A',1);
map.put('a',1);
map.put('f',5);
map.put('t',5);
map.put('m',4);
map.put('r',3);
System.out.println(map.keySet());
}
Not able to understand why here the output is not in order, like:
[A,a,f,t,m,r]
instead, it is printing:
[A, a, r, t, f, m]
can anyone please explain?
Thank you :)
|
[
"A HashMap makes no guarantees about the internal ordering, other than it being consistent - i.e., if you run the same program twice with the same JDK, you'll get the same order.\nIf you want a HashMap that preserves the order of insertion, you could use a LinkedHashMap.\n"
] |
[
1
] |
[] |
[] |
[
"hashmap",
"java"
] |
stackoverflow_0074664460_hashmap_java.txt
|
Q:
GIT Client on Windows Complaining about Ownership
With great difficulty due to my limited knowledge of Linux, I set up a GIT server on my Raspberry Pi. It works great except for one thing that's been driving me nuts. I've used every Google fu move I can think of and I've gotten nowhere.
I'm using Git Extensions as the client on 3 Windows machines. One at work (no problems) and 2 at home. The local repository at home is on a shared NAS drive on my LAN. It works fine on my main computer, but when I try to access it on my secondary computer, I get the following error:
warning: '//NAS/REPOSITORY' is owned by:
'S-1-5-...'
but the current user is:
'S-1-5-...'
where 'S-1-5-...' is two different really long alphanumeric strings that mean nothing to me. It says warning, but then whenever I try to do anything I immediately I get errors I can't decipher after that like:
fatal: this operation must be run in a work tree
or
fatal: No names found, cannot describe anything.
I'm the only user, using the same windows account, username, email address, etc. configured in Git Extensions. As I understand it on the server end, the only user is git which I use for all machines.
As a workaround, I'm able to clone the repository to a different folder on my secondary computer and I have no problems with GIT, but I have problems with my code because it expects things to be in a certain directory. I can change that based on the user, but as far as my code knows, I am the same user on both machines (because I am!). So that is not a good solution. I want to be able to work in the same folder on my NAS no matter what computer I'm using.
-Is there a way to configure GIT or GIT Extensions (I'm not totally sure who is doing the complaining) to not care about ownership? I've tried cloning as a Public Repository, but I guess that doesn't mean what it seems to mean because I get the same errors.
-How do I know and/or configure what user GIT or GIT Extensions thinks I am?
A:
It sounds like the issue is related to file permissions on the shared NAS drive. Since you are using the same Windows user account on both computers, it's likely that the issue is caused by the different SIDs (security identifier) assigned to that user account on the two different computers.
To fix this issue, you can try one of the following options:
Change the owner of the shared NAS drive to the user account you are using on both computers. This will allow both computers to access the repository with the same permissions. You can use the chown command in Linux to change the owner of the shared NAS drive, like this:
chown -R <username> <path-to-shared-drive>
Configure the shared NAS drive to allow access to the repository for all users. This will allow both computers to access the repository without checking for ownership. You can use the chmod command in Linux to change the permissions on the shared NAS drive, like this:
chmod -R 777 <path-to-shared-drive>
Configure Git Extensions to use the correct user account on each computer. By default, Git Extensions uses the current Windows user account to access the repository. However, you can specify a different user account to use by setting the user.name and user.email configuration values in Git Extensions. To do this, go to the "Settings" tab in Git Extensions and enter the correct user name and email address for the user account you want to use.
[user]
name = <username>
email = <email-address>
After changing the configuration values, you will need to close and re-open Git Extensions for the changes to take effect.
Keep in mind that this option will only work if the user account you are using on both computers has the same user name and email address.
I hope one of these options helps to fix the issue you are experiencing. Let me know if you have any questions or if you need further assistance.
|
GIT Client on Windows Complaining about Ownership
|
With great difficulty due to my limited knowledge of Linux, I set up a GIT server on my Raspberry Pi. It works great except for one thing that's been driving me nuts. I've used every Google fu move I can think of and I've gotten nowhere.
I'm using Git Extensions as the client on 3 Windows machines. One at work (no problems) and 2 at home. The local repository at home is on a shared NAS drive on my LAN. It works fine on my main computer, but when I try to access it on my secondary computer, I get the following error:
warning: '//NAS/REPOSITORY' is owned by:
'S-1-5-...'
but the current user is:
'S-1-5-...'
where 'S-1-5-...' is two different really long alphanumeric strings that mean nothing to me. It says warning, but then whenever I try to do anything I immediately I get errors I can't decipher after that like:
fatal: this operation must be run in a work tree
or
fatal: No names found, cannot describe anything.
I'm the only user, using the same windows account, username, email address, etc. configured in Git Extensions. As I understand it on the server end, the only user is git which I use for all machines.
As a workaround, I'm able to clone the repository to a different folder on my secondary computer and I have no problems with GIT, but I have problems with my code because it expects things to be in a certain directory. I can change that based on the user, but as far as my code knows, I am the same user on both machines (because I am!). So that is not a good solution. I want to be able to work in the same folder on my NAS no matter what computer I'm using.
-Is there a way to configure GIT or GIT Extensions (I'm not totally sure who is doing the complaining) to not care about ownership? I've tried cloning as a Public Repository, but I guess that doesn't mean what it seems to mean because I get the same errors.
-How do I know and/or configure what user GIT or GIT Extensions thinks I am?
|
[
"It sounds like the issue is related to file permissions on the shared NAS drive. Since you are using the same Windows user account on both computers, it's likely that the issue is caused by the different SIDs (security identifier) assigned to that user account on the two different computers.\nTo fix this issue, you can try one of the following options:\nChange the owner of the shared NAS drive to the user account you are using on both computers. This will allow both computers to access the repository with the same permissions. You can use the chown command in Linux to change the owner of the shared NAS drive, like this:\nchown -R <username> <path-to-shared-drive>\n\nConfigure the shared NAS drive to allow access to the repository for all users. This will allow both computers to access the repository without checking for ownership. You can use the chmod command in Linux to change the permissions on the shared NAS drive, like this:\nchmod -R 777 <path-to-shared-drive>\n\nConfigure Git Extensions to use the correct user account on each computer. By default, Git Extensions uses the current Windows user account to access the repository. However, you can specify a different user account to use by setting the user.name and user.email configuration values in Git Extensions. To do this, go to the \"Settings\" tab in Git Extensions and enter the correct user name and email address for the user account you want to use.\n[user]\n name = <username>\n email = <email-address>\n\nAfter changing the configuration values, you will need to close and re-open Git Extensions for the changes to take effect.\nKeep in mind that this option will only work if the user account you are using on both computers has the same user name and email address.\nI hope one of these options helps to fix the issue you are experiencing. Let me know if you have any questions or if you need further assistance.\n"
] |
[
1
] |
[] |
[] |
[
"git",
"git_extensions",
"ownership",
"raspberry_pi",
"windows"
] |
stackoverflow_0074664462_git_git_extensions_ownership_raspberry_pi_windows.txt
|
Q:
Rails - How to use Devise in both API and non-API mode in the same application
rails 7.0.3.1
devise 4.8.1
I'm aware that its possible to use Devise in API mode. But is it possible to use Devise both in API and non-API mode, "at the same time"? One use case of this is having one Rails app both serving its own static pages and being a back-end to a front-end client (e.g. developed using React).
A:
Not an expert, but i'm sure you will get other answers that will give more detailed answers. I think you can acheive what you want, with defining extra routes and extra set up.
I would ask myself is there any benefit of having rails views AND a seperate react app? Cant the same result be achieved by using only react frontend and a rails api?
There are some good tutorials by Deanin on YouTube describing a lot of react integration with rails. I have a rails app that has rails views which expose an Api to a React app, and this works well but the authentications are handled seperately for each app as I dont need it to be the same app doing this.
|
Rails - How to use Devise in both API and non-API mode in the same application
|
rails 7.0.3.1
devise 4.8.1
I'm aware that its possible to use Devise in API mode. But is it possible to use Devise both in API and non-API mode, "at the same time"? One use case of this is having one Rails app both serving its own static pages and being a back-end to a front-end client (e.g. developed using React).
|
[
"Not an expert, but i'm sure you will get other answers that will give more detailed answers. I think you can acheive what you want, with defining extra routes and extra set up.\nI would ask myself is there any benefit of having rails views AND a seperate react app? Cant the same result be achieved by using only react frontend and a rails api?\nThere are some good tutorials by Deanin on YouTube describing a lot of react integration with rails. I have a rails app that has rails views which expose an Api to a React app, and this works well but the authentications are handled seperately for each app as I dont need it to be the same app doing this.\n"
] |
[
0
] |
[] |
[] |
[
"devise",
"ruby_on_rails"
] |
stackoverflow_0074289443_devise_ruby_on_rails.txt
|
Q:
EF Core Fluent API For Base Class Setting FK
I am trying to set up audit properties for each of my Entities with an abstract Base class
public abstract class Base
{
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
public int CreatedByUserId { get; set; }
[ForeignKey("CreatedByUserId")]
public virtual User CreatedBy { get; set; }
public int ModifiedByUserId { get; set; }
[ForeignKey("ModifiedByUserId")]
public virtual User ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
Somehow the Data Annotations doesn't work in EF Core but was working in my EF 6 Project
I am now receiving this error:
Unable to determine the relationship represented by navigation 'Address.CreatedBy' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
These are my models:
public class Address : Base
{
public int Id { get; set; }
public string StringAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
public class User : Base
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Email { get; set; }
public string ContactNumber { get; set; }
public string SecondaryContactNumber { get; set; }
public int RoleId { get; set; }
public Role Role { get; set; }
public HashSet<Address> Addresses { get; set; }
}
What's weird is when I remove the Base inheritance from my other entities apart from User, EF Core is able to set the FK without any errors.
How do I configure it manually with Fluent API?
I already have a BaseConfig class as starting point to be inherited by my other entity config classes:
public class BaseConfig<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : Base
{
public virtual void Configure(EntityTypeBuilder<TEntity> builder)
{
builder.Property(x => x.DateCreated).HasDefaultValueSql("GETDATE()");
builder.Property(x => x.DateModified).HasDefaultValueSql("GETDATE()");
// Am I setting this correctly?
builder
.HasOne(b => b.CreatedBy)
.WithMany()
.HasForeignKey(p => p.CreatedByUserId);
}
}
A:
This error occurs when Entity Framework is unable to determine the relationship between two entities based on their navigation properties. In your case, the Address entity has a CreatedBy navigation property that refers to a User entity, but Entity Framework doesn't know how these entities are related.
You can use the HasOne and WithOne methods on the EntityTypeBuilder class to define the relationship between your User entity and the Base abstract class. This will allow Entity Framework to correctly determine the relationship between these entities and avoid the error you are seeing.
For example, you can define the relationship between the User entity and the CreatedBy navigation property like this:
modelBuilder.Entity<User>()
.HasOne(u => u.CreatedBy)
.WithMany()
.HasForeignKey(u => u.CreatedByUserId);
This creates a one-to-many relationship between the User entity and the CreatedBy property, where the CreatedBy property represents the parent User entity and the CreatedByUserId property is the foreign key.
You can use similar Fluent API code to define the relationship between the User entity and the ModifiedBy property.
Finally, you can use the Ignore method on the EntityTypeBuilder class to tell Entity Framework to ignore certain properties that you don't want it to manage. This can be useful for properties that are derived from other properties or that are not relevant to your application. For example, you can use the Ignore method to tell Entity Framework to ignore the DateCreated and DateModified properties on the Base class like this:
modelBuilder.Entity<Base>()
.Ignore(b => b.DateCreated)
.Ignore(b => b.DateModified);
It's not uncommon for Entity Framework to have trouble determining the relationships between entities when using inheritance. This is because inheritance can make it difficult for Entity Framework to determine the correct navigation properties and foreign keys to use.
In your case, when you remove the inheritance from the Address entity, Entity Framework is able to set the foreign key without any errors because it no longer has to determine the relationship between the Address and User entities. Instead, the Address entity has a direct reference to the User entity, which makes it easier for Entity Framework to determine the correct foreign key.
curious why it should be HasMany?
In the code you provided, the Base class has two navigation properties named CreatedBy and ModifiedBy, which are both of type User. The User class, on the other hand, has a navigation property named Addresses that is a collection of Address objects.
In the Fluent API configuration, the HasMany method is used to specify that a navigation property is a collection of objects, whereas the HasOne method is used to specify that a navigation property is a single object.
In the BaseConfig class, the HasOne method is used to specify that the CreatedBy and ModifiedBy navigation properties are of type User, and the WithMany method is used to specify that the User class has a collection of Base objects.
In the AddressConfig class, the HasOne method is used to specify that the User navigation property is of type User, and the WithMany method is used to specify that the User class has a collection of Address objects.
In this case, the use of the HasMany and WithMany methods in the configuration is correct because it accurately reflects the relationships between the entities.
lastly, the modelbuilder targets the User entity, shouldn't it be set in the Base configuration? i see it sort of defeats the purpose of having a base class and then setting the FK for each entity
The BaseConfig class is defined as a generic base class that can be used to configure any entity that derives from the Base class. This means that the BaseConfig class is not specific to any particular entity, and it does not need to be configured for any particular entity type.
The BaseConfig class defines the navigation and foreign key properties for the CreatedBy and ModifiedBy navigation properties in the Base class. This means that any entity that derives from the Base class will automatically have these properties configured.
In the AddressConfig class, the BaseConfig class is inherited and the Configure method is overridden to configure the relationship between the Address and User entities. This is necessary because the Address class has a User navigation property, and this property must be specifically configured in order for Entity Framework to understand the relationship between the two entities.
Therefore, it is correct to set the relationship between the Address and User entities in the AddressConfig class, and it does not defeat the purpose of having a base class. The BaseConfig class is still used to define the common navigation and foreign key properties for all entities that derive from the Base class, and the derived entity-specific configuration classes are used to define any additional configuration that is specific to a particular entity type.
A:
You can simplify your model by using naming conventions for your properties to let Entity Framework automatically determine the relationships between your entities.
Here is how you can update your model to use naming conventions:
public abstract class Base
{
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
public int CreatedById { get; set; }
public User CreatedBy { get; set; }
public int ModifiedById { get; set; }
public User ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
public class Address : Base
{
public int Id { get; set; }
public string StringAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
public class User : Base
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Email { get; set; }
public string ContactNumber { get; set; }
public string SecondaryContactNumber { get; set; }
public int RoleId { get; set; }
public Role Role { get; set; }
public HashSet<Address> Addresses { get; set; }
}
With the updated model, Entity Framework will be able to automatically determine the relationships between your entities based on the naming conventions for your properties. For example, the CreatedById property in the Base class represents a foreign key for the CreatedBy property, which is a navigation property for the User entity. Similarly, the UserId property in the Address class represents a foreign key for the User property, which is a navigation property for the User entity.
You can remove the BaseConfig class from your code, as it is no longer needed to define the relationships between your entities.
public class BaseConfig<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : Base
{
public virtual void Configure(EntityTypeBuilder<TEntity> builder)
{
builder.Property(x => x.DateCreated).HasDefaultValueSql("GETDATE()");
builder.Property(x => x.DateModified).HasDefaultValueSql("GETDATE()");
// Relationships are defined automatically based on naming conventions
// so this code is no longer needed
}
}
|
EF Core Fluent API For Base Class Setting FK
|
I am trying to set up audit properties for each of my Entities with an abstract Base class
public abstract class Base
{
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
public int CreatedByUserId { get; set; }
[ForeignKey("CreatedByUserId")]
public virtual User CreatedBy { get; set; }
public int ModifiedByUserId { get; set; }
[ForeignKey("ModifiedByUserId")]
public virtual User ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
Somehow the Data Annotations doesn't work in EF Core but was working in my EF 6 Project
I am now receiving this error:
Unable to determine the relationship represented by navigation 'Address.CreatedBy' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
These are my models:
public class Address : Base
{
public int Id { get; set; }
public string StringAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
public class User : Base
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Email { get; set; }
public string ContactNumber { get; set; }
public string SecondaryContactNumber { get; set; }
public int RoleId { get; set; }
public Role Role { get; set; }
public HashSet<Address> Addresses { get; set; }
}
What's weird is when I remove the Base inheritance from my other entities apart from User, EF Core is able to set the FK without any errors.
How do I configure it manually with Fluent API?
I already have a BaseConfig class as starting point to be inherited by my other entity config classes:
public class BaseConfig<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : Base
{
public virtual void Configure(EntityTypeBuilder<TEntity> builder)
{
builder.Property(x => x.DateCreated).HasDefaultValueSql("GETDATE()");
builder.Property(x => x.DateModified).HasDefaultValueSql("GETDATE()");
// Am I setting this correctly?
builder
.HasOne(b => b.CreatedBy)
.WithMany()
.HasForeignKey(p => p.CreatedByUserId);
}
}
|
[
"This error occurs when Entity Framework is unable to determine the relationship between two entities based on their navigation properties. In your case, the Address entity has a CreatedBy navigation property that refers to a User entity, but Entity Framework doesn't know how these entities are related.\nYou can use the HasOne and WithOne methods on the EntityTypeBuilder class to define the relationship between your User entity and the Base abstract class. This will allow Entity Framework to correctly determine the relationship between these entities and avoid the error you are seeing.\nFor example, you can define the relationship between the User entity and the CreatedBy navigation property like this:\nmodelBuilder.Entity<User>()\n .HasOne(u => u.CreatedBy)\n .WithMany()\n .HasForeignKey(u => u.CreatedByUserId);\n\nThis creates a one-to-many relationship between the User entity and the CreatedBy property, where the CreatedBy property represents the parent User entity and the CreatedByUserId property is the foreign key.\nYou can use similar Fluent API code to define the relationship between the User entity and the ModifiedBy property.\nFinally, you can use the Ignore method on the EntityTypeBuilder class to tell Entity Framework to ignore certain properties that you don't want it to manage. This can be useful for properties that are derived from other properties or that are not relevant to your application. For example, you can use the Ignore method to tell Entity Framework to ignore the DateCreated and DateModified properties on the Base class like this:\nmodelBuilder.Entity<Base>()\n .Ignore(b => b.DateCreated)\n .Ignore(b => b.DateModified);\n\nIt's not uncommon for Entity Framework to have trouble determining the relationships between entities when using inheritance. This is because inheritance can make it difficult for Entity Framework to determine the correct navigation properties and foreign keys to use.\nIn your case, when you remove the inheritance from the Address entity, Entity Framework is able to set the foreign key without any errors because it no longer has to determine the relationship between the Address and User entities. Instead, the Address entity has a direct reference to the User entity, which makes it easier for Entity Framework to determine the correct foreign key.\n\ncurious why it should be HasMany?\n\nIn the code you provided, the Base class has two navigation properties named CreatedBy and ModifiedBy, which are both of type User. The User class, on the other hand, has a navigation property named Addresses that is a collection of Address objects.\nIn the Fluent API configuration, the HasMany method is used to specify that a navigation property is a collection of objects, whereas the HasOne method is used to specify that a navigation property is a single object.\nIn the BaseConfig class, the HasOne method is used to specify that the CreatedBy and ModifiedBy navigation properties are of type User, and the WithMany method is used to specify that the User class has a collection of Base objects.\nIn the AddressConfig class, the HasOne method is used to specify that the User navigation property is of type User, and the WithMany method is used to specify that the User class has a collection of Address objects.\nIn this case, the use of the HasMany and WithMany methods in the configuration is correct because it accurately reflects the relationships between the entities.\n\nlastly, the modelbuilder targets the User entity, shouldn't it be set in the Base configuration? i see it sort of defeats the purpose of having a base class and then setting the FK for each entity\n\nThe BaseConfig class is defined as a generic base class that can be used to configure any entity that derives from the Base class. This means that the BaseConfig class is not specific to any particular entity, and it does not need to be configured for any particular entity type.\nThe BaseConfig class defines the navigation and foreign key properties for the CreatedBy and ModifiedBy navigation properties in the Base class. This means that any entity that derives from the Base class will automatically have these properties configured.\nIn the AddressConfig class, the BaseConfig class is inherited and the Configure method is overridden to configure the relationship between the Address and User entities. This is necessary because the Address class has a User navigation property, and this property must be specifically configured in order for Entity Framework to understand the relationship between the two entities.\nTherefore, it is correct to set the relationship between the Address and User entities in the AddressConfig class, and it does not defeat the purpose of having a base class. The BaseConfig class is still used to define the common navigation and foreign key properties for all entities that derive from the Base class, and the derived entity-specific configuration classes are used to define any additional configuration that is specific to a particular entity type.\n",
"You can simplify your model by using naming conventions for your properties to let Entity Framework automatically determine the relationships between your entities.\nHere is how you can update your model to use naming conventions:\npublic abstract class Base\n{\n public bool IsActive { get; set; }\n public bool IsDeleted { get; set; }\n\n public int CreatedById { get; set; }\n public User CreatedBy { get; set; }\n\n public int ModifiedById { get; set; }\n public User ModifiedBy { get; set; }\n\n public DateTime DateCreated { get; set; }\n public DateTime DateModified { get; set; }\n}\n\npublic class Address : Base\n{\n public int Id { get; set; }\n public string StringAddress { get; set; }\n public string City { get; set; }\n public string State { get; set; }\n public string ZipCode { get; set; }\n\n public int UserId { get; set; }\n public User User { get; set; }\n}\n\npublic class User : Base\n{\n public int Id { get; set; }\n public string FirstName { get; set; }\n public string MiddleName { get; set; }\n public string LastName { get; set; }\n public DateTime BirthDate { get; set; }\n public string Email { get; set; }\n public string ContactNumber { get; set; }\n public string SecondaryContactNumber { get; set; }\n\n public int RoleId { get; set; }\n public Role Role { get; set; }\n\n public HashSet<Address> Addresses { get; set; }\n}\n\nWith the updated model, Entity Framework will be able to automatically determine the relationships between your entities based on the naming conventions for your properties. For example, the CreatedById property in the Base class represents a foreign key for the CreatedBy property, which is a navigation property for the User entity. Similarly, the UserId property in the Address class represents a foreign key for the User property, which is a navigation property for the User entity.\nYou can remove the BaseConfig class from your code, as it is no longer needed to define the relationships between your entities.\npublic class BaseConfig<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : Base\n{\n public virtual void Configure(EntityTypeBuilder<TEntity> builder)\n {\n builder.Property(x => x.DateCreated).HasDefaultValueSql(\"GETDATE()\");\n builder.Property(x => x.DateModified).HasDefaultValueSql(\"GETDATE()\");\n\n // Relationships are defined automatically based on naming conventions\n // so this code is no longer needed\n }\n}\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"c#",
"ef_fluent_api",
"entity_framework_core"
] |
stackoverflow_0074664000_c#_ef_fluent_api_entity_framework_core.txt
|
Q:
How to open a terminal via intellij in the selected folder
I want to right click on a file in intellij and open the terminal there in mac. I tried 'External Tools' but doesn't open the terminal in the selected directory even though I set $FileDir$ as the working directory of that tool
A:
1. Out-of-the-box (no plugins)
Drag and drop a selected folder into the IntelliJ built-in Teminal opens a new terminal session in the built-in Terminal. (As @MariuszWróbel has written.)
2. With plugins:
There are 2 plugins (as far as I know):
Open Terminal Here
Open In Terminal
Both the plugins open an external terminal (outside of IntelliJ). Each of them adds some item(s) to the context menu of files and folders:
2a. Open Terminal Here plugin
It opens terminal in the current folder. The plugin works out of the box, no additional settings are required.
2b. Open In Terminal plugin
It does the same as the previous plus offers opening the terminal in the root folder of the module. The plugin does not work out of the box, you need to configure it as described here.
Linux:
Terminal command: gnome-terminal
Options: --working-directory
Windows:
Terminal command: cmd /C start cmd.exe /K
Options: cd /D
Windows (with babun or cygwin):
Terminal command: C:<USER-DIRECTORY>.babun\cygwin\bin\mintty.exe
Options: -i /Cygwin-Terminal.ico C:<USER-DIRECTORY>.babun\cygwin\bin\bash.exe -l -c "cd \"$0\" ; exec bash"
Mac OS:
Terminal command: open -a Terminal
A:
You can just easily drag a selected folder and drop into terminal window.
A:
just right click on the project folder that is being open in intelij, and select the option open in terminal
A:
In newer versions of Intellij, this seems to be integrated in the Terminal plugin, which is available by default.
You can either open a directory with your mouse by:
right click -> Open In -> Terminal
or assign a shortcut to the keymap command Plugins/Terminal/Open in Terminal.
Since creating a new terminal tab works with command + T, I've assigned command + option + T
|
How to open a terminal via intellij in the selected folder
|
I want to right click on a file in intellij and open the terminal there in mac. I tried 'External Tools' but doesn't open the terminal in the selected directory even though I set $FileDir$ as the working directory of that tool
|
[
"1. Out-of-the-box (no plugins)\nDrag and drop a selected folder into the IntelliJ built-in Teminal opens a new terminal session in the built-in Terminal. (As @MariuszWróbel has written.)\n2. With plugins:\nThere are 2 plugins (as far as I know):\n\nOpen Terminal Here\nOpen In Terminal\n\n\nBoth the plugins open an external terminal (outside of IntelliJ). Each of them adds some item(s) to the context menu of files and folders:\n\n2a. Open Terminal Here plugin\nIt opens terminal in the current folder. The plugin works out of the box, no additional settings are required.\n2b. Open In Terminal plugin\nIt does the same as the previous plus offers opening the terminal in the root folder of the module. The plugin does not work out of the box, you need to configure it as described here.\n\n\nLinux:\nTerminal command: gnome-terminal\nOptions: --working-directory\n\nWindows:\nTerminal command: cmd /C start cmd.exe /K\nOptions: cd /D\n\nWindows (with babun or cygwin):\nTerminal command: C:<USER-DIRECTORY>.babun\\cygwin\\bin\\mintty.exe\nOptions: -i /Cygwin-Terminal.ico C:<USER-DIRECTORY>.babun\\cygwin\\bin\\bash.exe -l -c \"cd \\\"$0\\\" ; exec bash\"\n\nMac OS:\nTerminal command: open -a Terminal\n\n\n",
"You can just easily drag a selected folder and drop into terminal window. \n",
"just right click on the project folder that is being open in intelij, and select the option open in terminal\n",
"In newer versions of Intellij, this seems to be integrated in the Terminal plugin, which is available by default.\nYou can either open a directory with your mouse by:\nright click -> Open In -> Terminal\n\nor assign a shortcut to the keymap command Plugins/Terminal/Open in Terminal.\nSince creating a new terminal tab works with command + T, I've assigned command + option + T\n"
] |
[
24,
22,
1,
0
] |
[] |
[] |
[
"intellij_idea"
] |
stackoverflow_0031285898_intellij_idea.txt
|
Q:
How can I trigger breakpoints when attaching to app using `flutter attach` command?
What am I doing?
I have a native iOS app, I wrote a Flutter module for a new feature and integrated it into the current native app. In order to use cool Flutter features like Hot Reload, I launched the native app in an iOS Simulator, then I open my Flutter project folder in my VSCode and ran flutter attach to attach the Flutter debugger to the native app, as I opened the Flutter made screen, then it was connected, and whenever I make a change in Flutter code, I can hit r to trigger a hot reload to see the update on the screen.
What is the problem?
I wanted to debug some code so I put some breakpoints, then I triggered a hot reload to run the code which refreshes the UI, the UI was refreshed but...none of my breakpoints was triggered.
Question:
Why hadn't these breakpoints been triggered?
If I can not use breakpoints, how can I debug something like this under this situation?
Thanks!
A:
You need to run flutter attach by VSCode command Palette VSCode -> View -> Command Palette(Shift + cmd + P), search Debug: Attach to Flutter on Device, and run this command. If succeeds, then you can trigger breakpoints.
|
How can I trigger breakpoints when attaching to app using `flutter attach` command?
|
What am I doing?
I have a native iOS app, I wrote a Flutter module for a new feature and integrated it into the current native app. In order to use cool Flutter features like Hot Reload, I launched the native app in an iOS Simulator, then I open my Flutter project folder in my VSCode and ran flutter attach to attach the Flutter debugger to the native app, as I opened the Flutter made screen, then it was connected, and whenever I make a change in Flutter code, I can hit r to trigger a hot reload to see the update on the screen.
What is the problem?
I wanted to debug some code so I put some breakpoints, then I triggered a hot reload to run the code which refreshes the UI, the UI was refreshed but...none of my breakpoints was triggered.
Question:
Why hadn't these breakpoints been triggered?
If I can not use breakpoints, how can I debug something like this under this situation?
Thanks!
|
[
"You need to run flutter attach by VSCode command Palette VSCode -> View -> Command Palette(Shift + cmd + P), search Debug: Attach to Flutter on Device, and run this command. If succeeds, then you can trigger breakpoints.\n"
] |
[
0
] |
[] |
[] |
[
"flutter",
"ios"
] |
stackoverflow_0060505892_flutter_ios.txt
|
Q:
Docker NPM Maximum call stack size exceeded
I'm trying to implement HMR in Nest in Docker.
Every time on start I get this error:
/node_modules/enhanced-resolve/lib/Resolver.js:433
if (err) return callback(err);
^
RangeError: Maximum call stack size exceeded
at /node_modules/enhanced-resolve/lib/Resolver.js:433:5
at eval (eval at create (/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:27:1)
npm version
{
api: '0.0.1',
npm: '7.24.2',
node: '14.18.1',
}
My Dockerfile:
RUN npm install -g npm@7
RUN npm cache clean --force
RUN npm install
RUN npm run build
package.json:
"dependencies": {
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.2.0",
"@nestjs/core": "^9.0.0",
"@nestjs/jwt": "^9.0.0",
"@nestjs/mapped-types": "*",
"@nestjs/passport": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/serve-static": "^3.0.0",
"@nestjs/typeorm": "^9.0.1",
"bcrypt": "^5.0.0",
"nestjs-typeorm-paginate": "^4.0.2",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"pg": "^8.6.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"slugify": "^1.4.5",
"typeorm": "^0.3.10",
"uuid": "^9.0.0"
},
"devDependencies": {
"@nestjs/cli": "^9.1.5",
"@nestjs/schematics": "^9.0.3",
"@nestjs/testing": "^9.2.0",
"@types/express": "^4.17.13",
"@types/jest": "^28.1.8",
"@types/node": "^16.0.0",
"@types/passport-jwt": "^3.0.7",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "^28.0.1",
"prettier": "^2.3.2",
"run-script-webpack-plugin": "^0.1.0",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "^28.0.8",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "^4.1.0",
"typescript": "^4.9.3",
"webpack": "^5.75.0",
"webpack-node-externals": "^3.0.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"main": "index.js"
I've already tried removing node_modules and reinstalling, and a different version of Node and npm. Any ideas?
A:
The "Maximum call stack size exceeded" error that you're encountering is typically caused by a JavaScript or TypeScript program that has an infinite recursive function call. In this case, it looks like the error is occurring in the Resolver module from the enhanced-resolve package.
One potential cause of this error is that the enhanced-resolve package is not installed correctly in your Docker image. This could happen if you're using a base image that does not include the necessary tools and dependencies for running a Node.js application, or if you're not installing the enhanced-resolve package correctly in your Dockerfile.
To fix this issue, you will need to make sure that your Docker image includes the node and npm packages, and that the enhanced-resolve package is installed correctly in your Dockerfile. Here's an example of how you can do this:
# Install Node.js and npm
RUN apt-get update && apt-get install -y nodejs npm
# Install the enhanced-resolve package
RUN npm install enhanced-resolve
This will ensure that the necessary tools and dependencies are included in your Docker image, and that the enhanced-resolve package is installed correctly. Once you've updated your Dockerfile, you can rebuild your Docker image and try running your application again to see if the error persists.
|
Docker NPM Maximum call stack size exceeded
|
I'm trying to implement HMR in Nest in Docker.
Every time on start I get this error:
/node_modules/enhanced-resolve/lib/Resolver.js:433
if (err) return callback(err);
^
RangeError: Maximum call stack size exceeded
at /node_modules/enhanced-resolve/lib/Resolver.js:433:5
at eval (eval at create (/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:27:1)
npm version
{
api: '0.0.1',
npm: '7.24.2',
node: '14.18.1',
}
My Dockerfile:
RUN npm install -g npm@7
RUN npm cache clean --force
RUN npm install
RUN npm run build
package.json:
"dependencies": {
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.2.0",
"@nestjs/core": "^9.0.0",
"@nestjs/jwt": "^9.0.0",
"@nestjs/mapped-types": "*",
"@nestjs/passport": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/serve-static": "^3.0.0",
"@nestjs/typeorm": "^9.0.1",
"bcrypt": "^5.0.0",
"nestjs-typeorm-paginate": "^4.0.2",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"pg": "^8.6.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"slugify": "^1.4.5",
"typeorm": "^0.3.10",
"uuid": "^9.0.0"
},
"devDependencies": {
"@nestjs/cli": "^9.1.5",
"@nestjs/schematics": "^9.0.3",
"@nestjs/testing": "^9.2.0",
"@types/express": "^4.17.13",
"@types/jest": "^28.1.8",
"@types/node": "^16.0.0",
"@types/passport-jwt": "^3.0.7",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "^28.0.1",
"prettier": "^2.3.2",
"run-script-webpack-plugin": "^0.1.0",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "^28.0.8",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "^4.1.0",
"typescript": "^4.9.3",
"webpack": "^5.75.0",
"webpack-node-externals": "^3.0.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"main": "index.js"
I've already tried removing node_modules and reinstalling, and a different version of Node and npm. Any ideas?
|
[
"The \"Maximum call stack size exceeded\" error that you're encountering is typically caused by a JavaScript or TypeScript program that has an infinite recursive function call. In this case, it looks like the error is occurring in the Resolver module from the enhanced-resolve package.\nOne potential cause of this error is that the enhanced-resolve package is not installed correctly in your Docker image. This could happen if you're using a base image that does not include the necessary tools and dependencies for running a Node.js application, or if you're not installing the enhanced-resolve package correctly in your Dockerfile.\nTo fix this issue, you will need to make sure that your Docker image includes the node and npm packages, and that the enhanced-resolve package is installed correctly in your Dockerfile. Here's an example of how you can do this:\n# Install Node.js and npm\nRUN apt-get update && apt-get install -y nodejs npm\n\n# Install the enhanced-resolve package\nRUN npm install enhanced-resolve\n\nThis will ensure that the necessary tools and dependencies are included in your Docker image, and that the enhanced-resolve package is installed correctly. Once you've updated your Dockerfile, you can rebuild your Docker image and try running your application again to see if the error persists.\n"
] |
[
0
] |
[] |
[] |
[
"docker",
"nestjs",
"npm"
] |
stackoverflow_0074664110_docker_nestjs_npm.txt
|
Q:
How to dynamically allocate vector and struct in a code?
I'm trying to allocate a struct and an array in the code below, but I have no idea how to proceed.
I'm trying to do this without adding other libraries.
It's in portuguese so I'm sorry if you don't understant the meaning.
struct RegistroAluno{
int Matricula;
char Nome[20];
int AnoNascimento;
};
int main()
{
int QuantidadeAlunos;
printf("Quantos alunos serão armazenados?\n");
scanf("%i", &QuantidadeAlunos);
struct RegistroAluno P1[QuantidadeAlunos];
struct *P1=(int *)malloc(QuantidadeAlunos*sizeof(struct));
for(int i=0; i<QuantidadeAlunos; i++){
printf("Qual a matrícula do aluno?\n");
scanf("%i", &P1[i].Matricula);
}/* I gotta do the same to all the other elements of the struct*/
return 0;
}
I'm trying to allocate a struct and an array
A:
You allocate a variable length array (VLA) of struct RegistroAluno here:
struct RegistroAluno P1[QuantidadeAlunos];
Alternatively, you can allocate the array dynamically like this:
struct RegistroAluno *P1 = malloc(QuantidadeAlunos*sizeof(*P1));
Here the complete program with includes and error handling:
#include <stdlib.h>
#include <stdio.h>
struct RegistroAluno{
int Matricula;
char Nome[20];
int AnoNascimento;
};
int main(void) {
printf("Quantos alunos serão armazenados?\n");
int QuantidadeAlunos;
if(scanf("%i", &QuantidadeAlunos) != 1) {
printf("scanf failed\n");
return 1;
}
if(QuantidadeAlunos < 1) {
printf("QuantidadeAlunos must be > 0\n");
return 1;
}
struct RegistroAluno *P1 = malloc(QuantidadeAlunos*sizeof(*P1));
if(!P1) {
printf("malloc failed\n");
return 1;
}
for(int i=0; i<QuantidadeAlunos; i++){
printf("Qual a matrícula do aluno?\n");
if(scanf("%i", &P1[i].Matricula) != 1) {
printf("scanf failed\n");
return 1;
}
}
}
and example session:
Quantos alunos serão armazenados?
2
Qual a matrícula do aluno?
3
Qual a matrícula do aluno?
4
|
How to dynamically allocate vector and struct in a code?
|
I'm trying to allocate a struct and an array in the code below, but I have no idea how to proceed.
I'm trying to do this without adding other libraries.
It's in portuguese so I'm sorry if you don't understant the meaning.
struct RegistroAluno{
int Matricula;
char Nome[20];
int AnoNascimento;
};
int main()
{
int QuantidadeAlunos;
printf("Quantos alunos serão armazenados?\n");
scanf("%i", &QuantidadeAlunos);
struct RegistroAluno P1[QuantidadeAlunos];
struct *P1=(int *)malloc(QuantidadeAlunos*sizeof(struct));
for(int i=0; i<QuantidadeAlunos; i++){
printf("Qual a matrícula do aluno?\n");
scanf("%i", &P1[i].Matricula);
}/* I gotta do the same to all the other elements of the struct*/
return 0;
}
I'm trying to allocate a struct and an array
|
[
"You allocate a variable length array (VLA) of struct RegistroAluno here:\n struct RegistroAluno P1[QuantidadeAlunos];\n\nAlternatively, you can allocate the array dynamically like this:\n struct RegistroAluno *P1 = malloc(QuantidadeAlunos*sizeof(*P1));\n\nHere the complete program with includes and error handling:\n#include <stdlib.h>\n#include <stdio.h>\n\nstruct RegistroAluno{\n int Matricula;\n char Nome[20];\n int AnoNascimento;\n};\n\nint main(void) {\n printf(\"Quantos alunos serão armazenados?\\n\");\n int QuantidadeAlunos;\n if(scanf(\"%i\", &QuantidadeAlunos) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n if(QuantidadeAlunos < 1) {\n printf(\"QuantidadeAlunos must be > 0\\n\");\n return 1;\n }\n struct RegistroAluno *P1 = malloc(QuantidadeAlunos*sizeof(*P1));\n if(!P1) {\n printf(\"malloc failed\\n\");\n return 1;\n }\n for(int i=0; i<QuantidadeAlunos; i++){\n printf(\"Qual a matrícula do aluno?\\n\");\n if(scanf(\"%i\", &P1[i].Matricula) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n }\n}\n\nand example session:\nQuantos alunos serão armazenados?\n2\nQual a matrícula do aluno?\n3\nQual a matrícula do aluno?\n4\n\n"
] |
[
0
] |
[] |
[] |
[
"c",
"malloc",
"struct",
"vector"
] |
stackoverflow_0074664468_c_malloc_struct_vector.txt
|
Q:
Is there any difference between manualluy login and selenium-python?
There are two method.
First, launch chrome debugging mode by using os.system() module and manually login, then connect selenium to get page source.
Second, launch and login are also controlled by selenium, Then get page source.
Because too difficult to login webpage(2 session needed), i didn't try second method.
So, i just want to know, Is there any difference between manualluy login and selenium-python?
A:
There may be a difference between manually logging in to a website and using Selenium to login to the same website. This difference may be due to a number of factors, such as the way in which the website authenticates users, the specific actions that are performed during the login process, and the way in which the website responds to different types of input.
One potential difference between manual and automated login is that manual login may allow a user to enter their credentials in a more flexible way, such as using a keyboard, mouse, or other input device, whereas automated login may be more limited in terms of the input methods that are supported. Additionally, manual login may allow a user to view and interact with the website in a way that is not possible with automated login, such as clicking on buttons or links, or interacting with other elements on the page.
Another potential difference is that manual login may be subject to human error, such as mistyping a password or entering the wrong username, whereas automated login using Selenium can be more consistent and reliable. However, automated login may also be subject to errors, such as incorrect configuration of the Selenium script or errors in the website's authentication system.
Overall, the differences between manual and automated login will depend on the specific website and the way in which it is designed and implemented. It is therefore important to carefully evaluate the specific requirements and constraints of the login process in order to determine the best approach for logging in to the website.
|
Is there any difference between manualluy login and selenium-python?
|
There are two method.
First, launch chrome debugging mode by using os.system() module and manually login, then connect selenium to get page source.
Second, launch and login are also controlled by selenium, Then get page source.
Because too difficult to login webpage(2 session needed), i didn't try second method.
So, i just want to know, Is there any difference between manualluy login and selenium-python?
|
[
"There may be a difference between manually logging in to a website and using Selenium to login to the same website. This difference may be due to a number of factors, such as the way in which the website authenticates users, the specific actions that are performed during the login process, and the way in which the website responds to different types of input.\nOne potential difference between manual and automated login is that manual login may allow a user to enter their credentials in a more flexible way, such as using a keyboard, mouse, or other input device, whereas automated login may be more limited in terms of the input methods that are supported. Additionally, manual login may allow a user to view and interact with the website in a way that is not possible with automated login, such as clicking on buttons or links, or interacting with other elements on the page.\nAnother potential difference is that manual login may be subject to human error, such as mistyping a password or entering the wrong username, whereas automated login using Selenium can be more consistent and reliable. However, automated login may also be subject to errors, such as incorrect configuration of the Selenium script or errors in the website's authentication system.\nOverall, the differences between manual and automated login will depend on the specific website and the way in which it is designed and implemented. It is therefore important to carefully evaluate the specific requirements and constraints of the login process in order to determine the best approach for logging in to the website.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"selenium"
] |
stackoverflow_0074664211_python_selenium.txt
|
Q:
Can we use the "SInce" and "Until" option in TWEEPY to fetch tweets from a specific date?
Actually, I am working on a project which collects tweets if we pass a certain keyword. For ex. If I pass the keyword as "Messi", it will collect every tweets regarding Messi. We are passing the parameters as "query" and "no of tweets". No of tweets will restrict the count of tweets that we need. So, tweepy collects the recent tweets from the field. What I want, is that I want to retrieve tweets from a certain timeline. Suppose, I want the tweets regarding "Messi" from 20th Jan 2022 to 02nd Feb 2022, it should fetch from that certain timeline.I've used POSTMAN with the twitter API and I am getting the results in that, but it is not being applied in the Python Tweepy code. So, do we have any option regarding that?
I tried POSTMAN, and in that we have the endpoint of "Full Archived Search". So, we can pass the since and until option in that, but it is not being applied to the Python Tweepy Code, which I'm doing. So, can we apply since and until option in the tweepy code? If not, do we have any ther alternative for it?
A:
Yes, you can use the since and until parameters in the tweepy code to collect tweets within a certain timeline. These parameters can be passed as part of the query parameter in the Cursor object when calling the Cursor.items() method.
Here is an example of how you can use these parameters:
import tweepy
# authentication details and other code to initialize the tweepy API client
# ...
# define the start and end dates for the timeline
start_date = "2022-01-20"
end_date = "2022-02-02"
# define the keyword to search for in the tweets
keyword = "Messi"
# create the query string to search for tweets containing the keyword
# within the defined timeline
query = f"{keyword} since:{start_date} until:{end_date}"
# create a tweepy Cursor object to iterate over the tweets matching the query
cursor = tweepy.Cursor(api.search, q=query)
# iterate over the tweets and print the text of each tweet
for tweet in cursor.items():
print(tweet.text)
You can find more information about the since and until parameters in the Twitter API documentation.
|
Can we use the "SInce" and "Until" option in TWEEPY to fetch tweets from a specific date?
|
Actually, I am working on a project which collects tweets if we pass a certain keyword. For ex. If I pass the keyword as "Messi", it will collect every tweets regarding Messi. We are passing the parameters as "query" and "no of tweets". No of tweets will restrict the count of tweets that we need. So, tweepy collects the recent tweets from the field. What I want, is that I want to retrieve tweets from a certain timeline. Suppose, I want the tweets regarding "Messi" from 20th Jan 2022 to 02nd Feb 2022, it should fetch from that certain timeline.I've used POSTMAN with the twitter API and I am getting the results in that, but it is not being applied in the Python Tweepy code. So, do we have any option regarding that?
I tried POSTMAN, and in that we have the endpoint of "Full Archived Search". So, we can pass the since and until option in that, but it is not being applied to the Python Tweepy Code, which I'm doing. So, can we apply since and until option in the tweepy code? If not, do we have any ther alternative for it?
|
[
"Yes, you can use the since and until parameters in the tweepy code to collect tweets within a certain timeline. These parameters can be passed as part of the query parameter in the Cursor object when calling the Cursor.items() method.\nHere is an example of how you can use these parameters:\nimport tweepy\n\n# authentication details and other code to initialize the tweepy API client\n# ...\n\n# define the start and end dates for the timeline\nstart_date = \"2022-01-20\"\nend_date = \"2022-02-02\"\n\n# define the keyword to search for in the tweets\nkeyword = \"Messi\"\n\n# create the query string to search for tweets containing the keyword\n# within the defined timeline\nquery = f\"{keyword} since:{start_date} until:{end_date}\"\n\n# create a tweepy Cursor object to iterate over the tweets matching the query\ncursor = tweepy.Cursor(api.search, q=query)\n\n# iterate over the tweets and print the text of each tweet\nfor tweet in cursor.items():\n print(tweet.text)\n\n\nYou can find more information about the since and until parameters in the Twitter API documentation.\n"
] |
[
0
] |
[] |
[] |
[
"postman",
"python",
"tweepy",
"twitter_api_v2"
] |
stackoverflow_0074664447_postman_python_tweepy_twitter_api_v2.txt
|
Q:
CORS, withCredentials and third party cookies
I'm trying to do a CORS GET that sends the cookie along with it. I've set all the headers (access-control-allow-origin, access-control-allow-credentials, access-control-allow-headers) in the server and am using withCredentials: true and crossDomain: true in the jquery ajax request. Everything works when I tell my browser to allow third-party cookies. Is there any way to do this without forcing visitors to allow third party cookies? I've even tried redirecting the user and redirecting back, but CORS will refuse to send the cookie along. :/
I've tried doing the CORS request via ajax, as well as via an iframe.
A:
I don't think it is possible. See my (old but relevant) blog post on this.
The only bullet-proof way is to use 1st-party cookies (that is, open window in a top-level window like a separate tab, or redirect current window).
In some cases it is not necessary though. Browsers have slightly different notions of what third-party cookie is, and default behavior is also different. This post has a nice overview on these details. So in some cases you could do tricks to enable (or at least detect) use of cookies on the page.
Other workarounds include putting one server under a subdomain of the other (subdomains are usually not considered 3rd-party), or changing the flow so that the user is authenticated by other means than cookies.
A:
if you set cookie (origin 2 set cookie) you should know third party cookie will be used, but if you only get cookie (only send cookie for origin 2 without setting in response) there is no reason third party cookie play a role.
so i think you set a cookie in origin 2 and because of that force you enable third party cookie.
Note that cookies set in CORS responses are subject to normal
third-party cookie policies. In the example above, the page is loaded
from foo.example but the cookie on line 19 is sent by bar.other, and
would thus not be saved if the user's browser is configured to reject
all third-party cookies.
Cross-Origin Resource Sharing mozilla.org
|
CORS, withCredentials and third party cookies
|
I'm trying to do a CORS GET that sends the cookie along with it. I've set all the headers (access-control-allow-origin, access-control-allow-credentials, access-control-allow-headers) in the server and am using withCredentials: true and crossDomain: true in the jquery ajax request. Everything works when I tell my browser to allow third-party cookies. Is there any way to do this without forcing visitors to allow third party cookies? I've even tried redirecting the user and redirecting back, but CORS will refuse to send the cookie along. :/
I've tried doing the CORS request via ajax, as well as via an iframe.
|
[
"I don't think it is possible. See my (old but relevant) blog post on this.\nThe only bullet-proof way is to use 1st-party cookies (that is, open window in a top-level window like a separate tab, or redirect current window).\nIn some cases it is not necessary though. Browsers have slightly different notions of what third-party cookie is, and default behavior is also different. This post has a nice overview on these details. So in some cases you could do tricks to enable (or at least detect) use of cookies on the page.\nOther workarounds include putting one server under a subdomain of the other (subdomains are usually not considered 3rd-party), or changing the flow so that the user is authenticated by other means than cookies.\n",
"if you set cookie (origin 2 set cookie) you should know third party cookie will be used, but if you only get cookie (only send cookie for origin 2 without setting in response) there is no reason third party cookie play a role.\nso i think you set a cookie in origin 2 and because of that force you enable third party cookie.\n\nNote that cookies set in CORS responses are subject to normal\nthird-party cookie policies. In the example above, the page is loaded\nfrom foo.example but the cookie on line 19 is sent by bar.other, and\nwould thus not be saved if the user's browser is configured to reject\nall third-party cookies.\nCross-Origin Resource Sharing mozilla.org\n\n"
] |
[
7,
0
] |
[] |
[] |
[
"cookies",
"cors",
"cross_domain",
"same_origin_policy"
] |
stackoverflow_0025858737_cookies_cors_cross_domain_same_origin_policy.txt
|
Q:
How to give custom divider in container?
I need to give this divider but I don't know how to coding it .
I tried but I don't know how to give thin to thick .
A:
You can use flutter widget
Container(
child: Column(children: [
Text('Title'),
Divider(thickness: 5,color: Colors.black,),
Text('Description'),
],),
A:
Use container with gradient instead of Divider.
Container(
height: 2,
width: 100,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: <Color>[
Color.green.withOpacity(0.1),
Color.green,
Color.green.withOpacity(0.1),
],
),
),
),
This is only for divider with that effect.
for content above and below you can use Column widget
Column (
children: [
widget1,
divider,
widget2,
]
)
change height, width, color and opacity as needed
A:
this is what you should use to solve your problem
Divider(thickness: 2,color:Colors.grey)
A:
You Can Use The Container With Gradient instead of Divider.
Like This:
SizedBox(
width: 200,
height: 4,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Colors.blue,
Colors.red,
],
)
),
),
),
|
How to give custom divider in container?
|
I need to give this divider but I don't know how to coding it .
I tried but I don't know how to give thin to thick .
|
[
"You can use flutter widget\nContainer(\n child: Column(children: [\n Text('Title'),\n Divider(thickness: 5,color: Colors.black,),\n Text('Description'),\n ],),\n\n",
"Use container with gradient instead of Divider.\nContainer(\n height: 2,\n width: 100,\n decoration: BoxDecoration(\n gradient: LinearGradient(\n begin: Alignment.centerLeft,\n end: Alignment.centerRight,\n colors: <Color>[\n Color.green.withOpacity(0.1),\n Color.green,\n Color.green.withOpacity(0.1),\n ], \n ),\n ),\n ),\n\nThis is only for divider with that effect.\nfor content above and below you can use Column widget\nColumn (\n children: [\n widget1,\n divider,\n widget2,\n ]\n)\n\nchange height, width, color and opacity as needed\n",
"this is what you should use to solve your problem\nDivider(thickness: 2,color:Colors.grey)\n\n",
"You Can Use The Container With Gradient instead of Divider.\nLike This:\nSizedBox(\n width: 200,\n height: 4,\n child: Container(\n decoration: BoxDecoration(\n gradient: LinearGradient(\n begin: Alignment.topRight,\n end: Alignment.bottomLeft,\n colors: [\n Colors.blue,\n Colors.red,\n ],\n )\n ),\n ),\n),\n\n"
] |
[
0,
0,
0,
0
] |
[] |
[] |
[
"flutter"
] |
stackoverflow_0074659736_flutter.txt
|
Q:
How can i remove the laravel-logo in the reset password mail from Laravel 8?
i am just developing a laravel shop, including a password reset functionality. So far so good, everything works pretty fine and in meantime i have also implemented an "email-blade-file" to customize the the content of the mail-text.
@component('mail::message')
{{-- Greeting --}}
@if (! empty($greeting))
# {{ $greeting }}
@else
@if ($level === 'error')
# @lang('Es tut uns leid!')
@else
# @lang('Guten Tag!')
@endif
@endif
{{-- Intro Lines --}}
@foreach ($introLines as $line)
{{ $line }}
@endforeach
{{-- Action Button --}}
@isset($actionText)
<?php
switch ($level) {
case 'success':
case 'error':
$color = $level;
break;
default:
$color = 'primary';
}
?>
@component('mail::button', ['url' => $actionUrl, 'color' => $color])
{{ $actionText }}
@endcomponent
@endisset
{{-- Outro Lines --}}
@foreach ($outroLines as $line)
{{ $line }}
@endforeach
<!--
{{-- Salutation --}}
@if (! empty($salutation))
{{ $salutation }}
@else
@lang('Regards'),<br>
{{ config('app.name') }}
@endif
{{-- Subcopy --}}
@isset($actionText)
@slot('subcopy')
@lang(
"If you’re having trouble clicking the \":actionText\" button, copy and paste the URL below\n".
'into your web browser:',
[
'actionText' => $actionText,
]
) <span class="break-all">[{{ $displayableActionUrl }}]({{ $actionUrl }})</span>
@endslot
@endisset
-->
@endcomponent
As you can see, something is commented out, because i do not use all this stuff. Here i can handle something like Greetings, Salutions and so on. In addition to this, i have also implemented a new notofication: ResetPassword:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class ResetPassword extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Shucube - Passwort vergessen?')
->line('Sie haben Ihr Passwort vergessen? Kein Problem...')
->action('Passwort Link', url('/'))
->line('Beste Grüße...');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
This also works pretty fine. The main part you can se in the function toMail(). All in all you can say that I handle the main content in ResetPassword.php and the general part in the blade file. Cool stuff.
But until now i am not able to remove the laravel logo which is located on the top of the mail. In best case I want to replace it with my own logo. Does anybody have an idea?
email
A:
From shell run php artisan vendor:publish and then select Laravel-mail. This will create blade views for mail in resources/views/vendor/mail
A:
If you change your APP_NAME from .env file from "Laravel" to anything else, it will disappear
|
How can i remove the laravel-logo in the reset password mail from Laravel 8?
|
i am just developing a laravel shop, including a password reset functionality. So far so good, everything works pretty fine and in meantime i have also implemented an "email-blade-file" to customize the the content of the mail-text.
@component('mail::message')
{{-- Greeting --}}
@if (! empty($greeting))
# {{ $greeting }}
@else
@if ($level === 'error')
# @lang('Es tut uns leid!')
@else
# @lang('Guten Tag!')
@endif
@endif
{{-- Intro Lines --}}
@foreach ($introLines as $line)
{{ $line }}
@endforeach
{{-- Action Button --}}
@isset($actionText)
<?php
switch ($level) {
case 'success':
case 'error':
$color = $level;
break;
default:
$color = 'primary';
}
?>
@component('mail::button', ['url' => $actionUrl, 'color' => $color])
{{ $actionText }}
@endcomponent
@endisset
{{-- Outro Lines --}}
@foreach ($outroLines as $line)
{{ $line }}
@endforeach
<!--
{{-- Salutation --}}
@if (! empty($salutation))
{{ $salutation }}
@else
@lang('Regards'),<br>
{{ config('app.name') }}
@endif
{{-- Subcopy --}}
@isset($actionText)
@slot('subcopy')
@lang(
"If you’re having trouble clicking the \":actionText\" button, copy and paste the URL below\n".
'into your web browser:',
[
'actionText' => $actionText,
]
) <span class="break-all">[{{ $displayableActionUrl }}]({{ $actionUrl }})</span>
@endslot
@endisset
-->
@endcomponent
As you can see, something is commented out, because i do not use all this stuff. Here i can handle something like Greetings, Salutions and so on. In addition to this, i have also implemented a new notofication: ResetPassword:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class ResetPassword extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Shucube - Passwort vergessen?')
->line('Sie haben Ihr Passwort vergessen? Kein Problem...')
->action('Passwort Link', url('/'))
->line('Beste Grüße...');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
This also works pretty fine. The main part you can se in the function toMail(). All in all you can say that I handle the main content in ResetPassword.php and the general part in the blade file. Cool stuff.
But until now i am not able to remove the laravel logo which is located on the top of the mail. In best case I want to replace it with my own logo. Does anybody have an idea?
email
|
[
"From shell run php artisan vendor:publish and then select Laravel-mail. This will create blade views for mail in resources/views/vendor/mail\n",
"If you change your APP_NAME from .env file from \"Laravel\" to anything else, it will disappear\n"
] |
[
0,
0
] |
[] |
[] |
[
"laravel",
"php"
] |
stackoverflow_0066490634_laravel_php.txt
|
Q:
Session destroy randomly after redirection from PayU payment gateway redirection in Codeigniter 4
This question is posting after trying many solutions for about past 2 days and nothing is worked. Session in my Codeingiter 4 project behaving in a strange manner. There is a payment module in my application and PayU is my payment gateway provider. After the payment gateway redirection PayU will post some response data in my URL. At this time session destroys automatically. I don't know why and for your understanding it's happening becasue it's not happening everytime, say out of 10 session will destroy 7 time after the successfull payment. I get all the response from the PayU inside my controller. If the payment is cancelled by the use the frequency is about 5 out of 10 tries. This issue is only happends after redirection from PayU payment gateway irrespective of the payment status. I tried this,this,this,this and many other sites other than in StackOverflow.
I'm using Open LiteSpeed server in AlmaLinux 8. I added this in my virtual server config file
context / {
location $DOC_ROOT/
allowBrowse 1
extraHeaders header edit set-cookie $1;httponly;secure;samesite=none
}
My htaccess file doesn't contain anything other than a rewrite rule for hiding public from URL.
This is my .env
app.sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler' // Initially it was FileHandler
app.sessionCookieName = 'ci_session'
app.sessionExpiration = 7200
app.sessionSavePath = ci_sessions
# app.sessionMatchIP = false
app.sessionTimeToUpdate = 300
# app.sessionRegenerateDestroy = false
# app.CSPEnabled = false
// Initially all the cookie preferences are commented out experimented with different values.
cookie.prefix = ''
cookie.expires = 7200
cookie.path = '/'
cookie.domain = '<domain_name>'
cookie.secure = true
# cookie.httponly = false
cookie.samesite = 'none' // I tried Lax also
# cookie.raw = false
security.csrfProtection = 'cookie'
security.tokenName = 'csrf_token_name'
security.headerName = 'X-CSRF-TOKEN'
security.cookieName = 'csrf_cookie_name'
security.expires = 7200
security.regenerate = true
security.redirect = true
security.samesite = 'Lax'
curlrequest.shareOptions = true
I tried this in my BaseController
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
$this->session = \Config\Services::session();
session();
}
I added this line in my php.ini
session.auto_start = 1
After the payment PayU will post response to this function
I'm using PHP 7.4, Codeigniter 4.1.5 and Litespeed 1.7.14.
Update
I updated Codeingiter version to 4.2.3 latest version but there is no heal for this issue.
A:
The reply given from PayU is,
TL;DR - In Chrome v.84 SameSite cookie attribute is released which if not handled by the server may lead to an issue causing loss of session data or session ID gets NULL.The issue where cookies are getting NULL in return journey is occurring with chrome browser 84+ version.There is no restriction from PayU's end as such for cookies .
Solution Suggested:The chrome 84 security update says that SameSite attribute of cookie will be Lax(allowed for GET requests) by default and if we want cookie to travel then it should be marked SameSite : None and "Secure" explicitly. (Ref. https://web.dev/samesite-cookies-explained/
Session getting null or getting destroyed during the transaction is
not happening due to PayU but Chrome has updated some cache and
cookies policy in their last update v84, same has to be implemented
in your session.
PayU is not playing any role with the session,If you will try same on
Mozilla it will work there and you will not face any null session
issue.
Please find the below points available on Chrome forum to replicate
this issue.
A cookie associated with a cross-site resource at was set
without the SameSite attribute. It has been blocked, as Chrome now
only delivers cookies with cross-site requests if they are set with
SameSite=None and Secure. You can review cookies in developer
tools under Application>Storage>Cookies and see more details at
and .
Please find below solution for this issue:
The issue where cookies are getting NULL in return journey is
occurring with chrome browser 84+ version. There is no restriction
from PayU's end as such for cookies . Solution Suggested:The chrome 84
security update says that SameSite attribute of cookie will be
Lax(allowed for GET requests) by default and if we want cookie to
travel then it should be marked SameSite : None and "Secure"
explicitly. (Ref. https://web.dev/samesite-cookies-explained/
• SameSite cookies explained Learn how to mark your cookies for
first-party and third-party usage with the SameSite attribute. You can
enhance your site's security by using SameSite's Lax and Strict values
to improve protection against CSRF attacks. Specifying the new None
attribute allows you to explicitly mark your cookies for cross-site
usage. web.dev
Please check with your tech team if after making changes at your end ,
session id is NULL in return journey to merchant website. If session
id is Null , Please find below RCA on issue with chrome browser 84
version.
This is to inform you about the changes released by Chrome in the
latest update v.84 and its impact on transaction processing. Below are
the details on the same.
Incident Reference across pan India Session ID missing in header
response post-payment resulting in session data loss. A few merchants
across PayU have raised concerns of loss of the session, when the
transaction is processed on Chrome browser having version greater than
v84. This issue is arising due to the change in Cookie policy from
Chrome. The changes block the cookies from retaining when user moves
across the multiple domains, and thus, resulting in loss of session
for the user.
Transaction Impact High
Affected Area Production and UAT
Short Description of Incident treating Q.1 How does the Chrome
SameSite Cookie policy affect my browser redirection integration? In
Chrome v.84 SameSite cookie attribute is released which if not handled
by the server may lead to an issue causing loss of session data or
session ID gets NULL. Merchants might experience sudden surge of
incomplete orders at their end Q.2 About Chrome's SameSite Cookie
Policy For users running Chrome v.84 and higher, Chrome is enforcing a
secure-by-default cookie classification system treating cookies that
have not declared SameSite value as SameSite=Lax cookies. Only
cookies set as SameSite=None will be available, provided they are
being accessed from secure connections. Chrome 84 release note link
for reference:https://support.google.com/chrome/a/answer/7679408?hl=en
Q.3 How to fix (or prepare) for it? Session data is not a part of
PayU integration, it is managed by merchants. You can refer to the
link below and make required changes.Below link can be used for
reference. ( Ref. https://web.dev/samesite-cookies-explained/ )
SameSite cookies explainedLearn how to mark your cookies for
first-party and third-party usage with the SameSite attribute. You can
enhance your site's security by using SameSite's Lax and Strict values
to improve protection...web.dev
A:
Make following changes.
in config/cookie.php page set
$secure = true ;
$samesite = 'None';
in config/security.php set
$samesite = 'None';
Then give absolute path as redirect url:
eg: domain.com/customer/Pay/checkTransaction
|
Session destroy randomly after redirection from PayU payment gateway redirection in Codeigniter 4
|
This question is posting after trying many solutions for about past 2 days and nothing is worked. Session in my Codeingiter 4 project behaving in a strange manner. There is a payment module in my application and PayU is my payment gateway provider. After the payment gateway redirection PayU will post some response data in my URL. At this time session destroys automatically. I don't know why and for your understanding it's happening becasue it's not happening everytime, say out of 10 session will destroy 7 time after the successfull payment. I get all the response from the PayU inside my controller. If the payment is cancelled by the use the frequency is about 5 out of 10 tries. This issue is only happends after redirection from PayU payment gateway irrespective of the payment status. I tried this,this,this,this and many other sites other than in StackOverflow.
I'm using Open LiteSpeed server in AlmaLinux 8. I added this in my virtual server config file
context / {
location $DOC_ROOT/
allowBrowse 1
extraHeaders header edit set-cookie $1;httponly;secure;samesite=none
}
My htaccess file doesn't contain anything other than a rewrite rule for hiding public from URL.
This is my .env
app.sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler' // Initially it was FileHandler
app.sessionCookieName = 'ci_session'
app.sessionExpiration = 7200
app.sessionSavePath = ci_sessions
# app.sessionMatchIP = false
app.sessionTimeToUpdate = 300
# app.sessionRegenerateDestroy = false
# app.CSPEnabled = false
// Initially all the cookie preferences are commented out experimented with different values.
cookie.prefix = ''
cookie.expires = 7200
cookie.path = '/'
cookie.domain = '<domain_name>'
cookie.secure = true
# cookie.httponly = false
cookie.samesite = 'none' // I tried Lax also
# cookie.raw = false
security.csrfProtection = 'cookie'
security.tokenName = 'csrf_token_name'
security.headerName = 'X-CSRF-TOKEN'
security.cookieName = 'csrf_cookie_name'
security.expires = 7200
security.regenerate = true
security.redirect = true
security.samesite = 'Lax'
curlrequest.shareOptions = true
I tried this in my BaseController
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
$this->session = \Config\Services::session();
session();
}
I added this line in my php.ini
session.auto_start = 1
After the payment PayU will post response to this function
I'm using PHP 7.4, Codeigniter 4.1.5 and Litespeed 1.7.14.
Update
I updated Codeingiter version to 4.2.3 latest version but there is no heal for this issue.
|
[
"The reply given from PayU is,\nTL;DR - In Chrome v.84 SameSite cookie attribute is released which if not handled by the server may lead to an issue causing loss of session data or session ID gets NULL.The issue where cookies are getting NULL in return journey is occurring with chrome browser 84+ version.There is no restriction from PayU's end as such for cookies .\nSolution Suggested:The chrome 84 security update says that SameSite attribute of cookie will be Lax(allowed for GET requests) by default and if we want cookie to travel then it should be marked SameSite : None and \"Secure\" explicitly. (Ref. https://web.dev/samesite-cookies-explained/\n\nSession getting null or getting destroyed during the transaction is\nnot happening due to PayU but Chrome has updated some cache and\ncookies policy in their last update v84, same has to be implemented\nin your session.\nPayU is not playing any role with the session,If you will try same on\nMozilla it will work there and you will not face any null session\nissue.\nPlease find the below points available on Chrome forum to replicate\nthis issue.\nA cookie associated with a cross-site resource at was set\nwithout the SameSite attribute. It has been blocked, as Chrome now\nonly delivers cookies with cross-site requests if they are set with\nSameSite=None and Secure. You can review cookies in developer\ntools under Application>Storage>Cookies and see more details at \nand .\nPlease find below solution for this issue:\nThe issue where cookies are getting NULL in return journey is\noccurring with chrome browser 84+ version. There is no restriction\nfrom PayU's end as such for cookies . Solution Suggested:The chrome 84\nsecurity update says that SameSite attribute of cookie will be\nLax(allowed for GET requests) by default and if we want cookie to\ntravel then it should be marked SameSite : None and \"Secure\"\nexplicitly. (Ref. https://web.dev/samesite-cookies-explained/\n• SameSite cookies explained Learn how to mark your cookies for\nfirst-party and third-party usage with the SameSite attribute. You can\nenhance your site's security by using SameSite's Lax and Strict values\nto improve protection against CSRF attacks. Specifying the new None\nattribute allows you to explicitly mark your cookies for cross-site\nusage. web.dev\nPlease check with your tech team if after making changes at your end ,\nsession id is NULL in return journey to merchant website. If session\nid is Null , Please find below RCA on issue with chrome browser 84\nversion.\nThis is to inform you about the changes released by Chrome in the\nlatest update v.84 and its impact on transaction processing. Below are\nthe details on the same.\nIncident Reference across pan India Session ID missing in header\nresponse post-payment resulting in session data loss. A few merchants\nacross PayU have raised concerns of loss of the session, when the\ntransaction is processed on Chrome browser having version greater than\nv84. This issue is arising due to the change in Cookie policy from\nChrome. The changes block the cookies from retaining when user moves\nacross the multiple domains, and thus, resulting in loss of session\nfor the user.\nTransaction Impact High\nAffected Area Production and UAT\nShort Description of Incident treating Q.1 How does the Chrome\nSameSite Cookie policy affect my browser redirection integration? In\nChrome v.84 SameSite cookie attribute is released which if not handled\nby the server may lead to an issue causing loss of session data or\nsession ID gets NULL. Merchants might experience sudden surge of\nincomplete orders at their end Q.2 About Chrome's SameSite Cookie\nPolicy For users running Chrome v.84 and higher, Chrome is enforcing a\nsecure-by-default cookie classification system treating cookies that\nhave not declared SameSite value as SameSite=Lax cookies. Only\ncookies set as SameSite=None will be available, provided they are\nbeing accessed from secure connections. Chrome 84 release note link\nfor reference:https://support.google.com/chrome/a/answer/7679408?hl=en\nQ.3 How to fix (or prepare) for it? Session data is not a part of\nPayU integration, it is managed by merchants. You can refer to the\nlink below and make required changes.Below link can be used for\nreference. ( Ref. https://web.dev/samesite-cookies-explained/ )\nSameSite cookies explainedLearn how to mark your cookies for\nfirst-party and third-party usage with the SameSite attribute. You can\nenhance your site's security by using SameSite's Lax and Strict values\nto improve protection...web.dev\n\n",
"Make following changes.\nin config/cookie.php page set\n$secure = true ;\n$samesite = 'None';\nin config/security.php set\n$samesite = 'None';\nThen give absolute path as redirect url:\neg: domain.com/customer/Pay/checkTransaction\n"
] |
[
0,
0
] |
[] |
[] |
[
"codeigniter",
"codeigniter_4",
"php",
"session"
] |
stackoverflow_0073266571_codeigniter_codeigniter_4_php_session.txt
|
Q:
Unable to resolve module 'module://@babel/runtime/helpers/interopRequireDefault.js' - EXPO SNACK
I am getting the error 'Unable to resolve module 'module://@babel/runtime/helpers/interopRequireDefault.js' when I try to run the following code in Expo Snack
Below is my code for HomeScreen.js
import { StyleSheet, Text, View, FlatList } from "react-native";
import axios from "axios";
import { useState, useEffect } from "react";
export default function HomeScreen() {
const [cycles, setCycles] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const { data: response } = await axios.get(
"URL"
);
setCycles(response);
} catch (error) {
console.error(error.message);
}
};
fetchData();
}, []);
return (
<View style={styles.container}>
{/* <Text> {JSON.stringify(cycles[0])} </Text> */}
<FlatList
data={cycles}
renderItem={(
{ item } //this part will iterate over every item in the array and return a listItem
) => (
<Text>
{new Date(item.startDate).toLocaleDateString("us-EN")} -{" "}
{new Date(item.endDate).toLocaleDateString("us-EN")}{" "}
</Text>
)}
/>
<Text>Hello</Text>
</View>
);
}
And below is App.js
import { StyleSheet, Text, View, FlatList } from "react-native";
import axios from "axios";
import { useState, useEffect } from "react";
import HomeScreen from "./screens/HomeScreen";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/stack";
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: "Welcome" }}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
Package.json file
{
"dependencies": {
"react-native-paper": "4.9.2",
"@expo/vector-icons": "^13.0.0",
"expo-constants": "~13.2.4",
"axios": "*",
"@react-navigation/stack": "*",
"@react-navigation/native": "6.0.0",
"react-native-gesture-handler": "~2.5.0",
"react-native-safe-area-context": "4.3.1",
"react-native-screens": "~3.15.0"
}
}
From one of the questions I found Unable to resolve module `@babel/runtime/helpers/interopRequireDefault`, I tried adding babel and it has not worked.(ie it throws another error as below)
Thanks for any help!
A:
The error "Unable to resolve module 'module://@babel/runtime/helpers/interopRequireDefault.js'" typically occurs when a module that is required by your code cannot be found by the JavaScript runtime. In this case, it looks like the @babel/runtime package is not installed correctly, or it is not being included correctly in your code.
To fix this error, you will need to make sure that the @babel/runtime package is installed in your project, and that it is being imported correctly in your code. You can install the @babel/runtime package using the following command:
npm install @babel/runtime
Once the package is installed, you will need to import it in your code using the following syntax:
import interopRequireDefault from '@babel/runtime/helpers/interopRequireDefault';
This will import the interopRequireDefault function from the @babel/runtime package, allowing you to use it in your code without encountering the "Unable to resolve module" error.
If you're still encountering the error after installing the @babel/runtime package and importing it correctly in your code, it's possible that there is a problem with the way the package is being bundled or transpiled by Expo. In this case, you may need to contact the Expo support team for further assistance.
|
Unable to resolve module 'module://@babel/runtime/helpers/interopRequireDefault.js' - EXPO SNACK
|
I am getting the error 'Unable to resolve module 'module://@babel/runtime/helpers/interopRequireDefault.js' when I try to run the following code in Expo Snack
Below is my code for HomeScreen.js
import { StyleSheet, Text, View, FlatList } from "react-native";
import axios from "axios";
import { useState, useEffect } from "react";
export default function HomeScreen() {
const [cycles, setCycles] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const { data: response } = await axios.get(
"URL"
);
setCycles(response);
} catch (error) {
console.error(error.message);
}
};
fetchData();
}, []);
return (
<View style={styles.container}>
{/* <Text> {JSON.stringify(cycles[0])} </Text> */}
<FlatList
data={cycles}
renderItem={(
{ item } //this part will iterate over every item in the array and return a listItem
) => (
<Text>
{new Date(item.startDate).toLocaleDateString("us-EN")} -{" "}
{new Date(item.endDate).toLocaleDateString("us-EN")}{" "}
</Text>
)}
/>
<Text>Hello</Text>
</View>
);
}
And below is App.js
import { StyleSheet, Text, View, FlatList } from "react-native";
import axios from "axios";
import { useState, useEffect } from "react";
import HomeScreen from "./screens/HomeScreen";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/stack";
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: "Welcome" }}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
Package.json file
{
"dependencies": {
"react-native-paper": "4.9.2",
"@expo/vector-icons": "^13.0.0",
"expo-constants": "~13.2.4",
"axios": "*",
"@react-navigation/stack": "*",
"@react-navigation/native": "6.0.0",
"react-native-gesture-handler": "~2.5.0",
"react-native-safe-area-context": "4.3.1",
"react-native-screens": "~3.15.0"
}
}
From one of the questions I found Unable to resolve module `@babel/runtime/helpers/interopRequireDefault`, I tried adding babel and it has not worked.(ie it throws another error as below)
Thanks for any help!
|
[
"The error \"Unable to resolve module 'module://@babel/runtime/helpers/interopRequireDefault.js'\" typically occurs when a module that is required by your code cannot be found by the JavaScript runtime. In this case, it looks like the @babel/runtime package is not installed correctly, or it is not being included correctly in your code.\nTo fix this error, you will need to make sure that the @babel/runtime package is installed in your project, and that it is being imported correctly in your code. You can install the @babel/runtime package using the following command:\nnpm install @babel/runtime\n\nOnce the package is installed, you will need to import it in your code using the following syntax:\nimport interopRequireDefault from '@babel/runtime/helpers/interopRequireDefault';\n\nThis will import the interopRequireDefault function from the @babel/runtime package, allowing you to use it in your code without encountering the \"Unable to resolve module\" error.\nIf you're still encountering the error after installing the @babel/runtime package and importing it correctly in your code, it's possible that there is a problem with the way the package is being bundled or transpiled by Expo. In this case, you may need to contact the Expo support team for further assistance.\n"
] |
[
0
] |
[] |
[] |
[
"babeljs",
"expo",
"npm",
"react_native"
] |
stackoverflow_0074663541_babeljs_expo_npm_react_native.txt
|
Q:
Getting custom components to work within react-hook-form using onChange
I have a checkout cart where you have different cart items, and for each one you can change the quantity prior to purchase.
Here's how the code looks:
import React, { useEffect, useState } from "react";
import PureInput from "./PureInput";
import { useForm, Controller } from "react-hook-form";
const CartInner = React.forwardRef(
(
{
control,
element,
value,
handleOnChange,
images,
name,
monthlyAmount,
price,
projectedGrowth,
id,
...inputProps
}: any,
ref: any
) => {
return (
<div className="grid gap-8 grid-cols-2 mb-12 py-6 px-8 border-2 border-slate-200">
<div>
<PureInput
min={200}
max={price}
onChange={handleOnChange}
type="number"
step={200}
defaultValue={element.price}
id={id}
ref={ref}
{...inputProps}
/>
</div>
</div>
);
}
);
export default function Checkout() {
const { control, handleSubmit } = useForm();
const handleOnChange = (index: any, e: any) => {
console.log(e, "e");
};
const onSubmit = async (data: any) => {
console.log(data, "data from Form.tsx");
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-8 grid-cols-3">
<div className="col-span-2">
{[0, 2].map((element, index) => {
return (
<fieldset key={index}>
<Controller
render={({ field }) => (
<CartInner
element={element}
handleOnChange={(e) => handleOnChange(index, e)}
{...field}
/>
)}
name={`test.${index}.lastName`}
control={control}
/>
</fieldset>
);
})}
<button>Progess to payment</button>
</div>
</form>
);
}
And the PureInput:
import * as React from "react";
type IProps = any;
const PureInput = React.forwardRef(
({ className, id, onChange, ...inputProps }: IProps, ref: any) => {
return (
<input
id={id}
ref={ref}
onChange={onChange}
type="input"
className={`${className} block w-full bg-white text-black rounded-md border-2 font-bold border-grey-200 text-xl px-4 py-4 focus:border-orange-500 focus:ring-orange-500`}
{...inputProps}
/>
);
}
);
export default PureInput;
Everything works fine in terms of submitting the form. When I do, I get an array of whatever values I have entered into the input:
[{lastName: "1600"}
{lastName: "800"}]
My package versions:
"react-dom": "18.2.0",
"react-hook-form": "^7.29.0",
But my onChange no longer fires. How can I get the onChange to fire so I can log the value of the input inside <Checkout /> component?
Here's a codesandbox if it helps
A:
The onChange event handler is only called when the input value is changed. It's not called when the form is submitted.
To access the values of the inputs when the form is submitted, you can use the handleSubmit hook provided by react-hook-form in your Checkout component. This hook takes a callback function as an argument, and this function will be called when the form is submitted. The values of the form inputs will be passed to this callback as an object:
import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
const CartInner = React.forwardRef(
(
{
control,
element,
value,
handleOnChange,
images,
name,
monthlyAmount,
price,
projectedGrowth,
id,
...inputProps
}: any,
ref: any
) => {
return (
<div className="grid gap-8 grid-cols-2 mb-12 py-6 px-8 border-2 border-slate-200">
<div>
<PureInput
min={200}
max={price}
onChange={handleOnChange}
type="number"
step={200}
defaultValue={element.price}
id={id}
ref={ref}
{...inputProps}
/>
</div>
</div>
);
}
);
export default function Checkout() {
const { control, handleSubmit } = useForm();
const handleOnChange = (index: any, e: any) => {
console.log(e, "e");
};
const onSubmit = async (data: any) => {
console.log(data, "data from Form.tsx");
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-8 grid-cols-3">
<div className="col-span-2">
{[0, 2].map((element, index) => {
return (
<fieldset key={index}>
<Controller
render={({ field }) => (
<CartInner
element={element}
handleOnChange={(e) => handleOnChange(index, e)}
{...field}
/>
)}
name={`test.${index}.lastName`}
control={control}
/>
</fieldset>
);
})}
<button>Progess to payment</button>
</div>
</form>
);
}
A:
You can make the following changes to plug into onChange event
// pass an event handler name with different name
<PureInput
min={200}
max={price}
// pass a handler with different name as inputOptions overrides that prop
handleOnChange={handleOnChange}
type="number"
step={200}
defaultValue={element.price}
id={id}
ref={ref}
{...inputProps}
/>
//plug into the default onchange to call you handler also
<input
id={id}
ref={ref}
onChange={(e) => {
console.log("on change");
// call react-hook-form onChange
onChange(e);
// call your handler
handleOnChange(e);
}}
type="input"
className={`${className} block w-full bg-white text-black rounded-md border-2 font-bold border-grey-200 text-xl px-4 py-4 focus:border-orange-500 focus:ring-orange-500`}
{...inputProps}
/>
Hope it helps you in solving your problem,
Cheers
A:
This part of the documentation led me to the answer:
import React, { useEffect, useState } from "react";
import PureInput from "./PureInput";
import { useForm, Controller } from "react-hook-form";
const CartInner = React.forwardRef(
({ onChange, onBlur, name, label, ...inputProps }: any, ref: any) => {
return (
<input
name={name}
ref={ref}
onChange={onChange}
onBlur={onBlur}
type="number"
/>
);
}
);
export default function Checkout() {
const { control, handleSubmit } = useForm();
const handleOnChange = (index: any, e: any) => {
console.log(e.target.value, "e");
};
const onSubmit = async (data: any) => {
console.log(data, "data from Form.tsx");
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-8 grid-cols-3">
<div className="col-span-2">
{[0, 2].map((element, index) => {
return (
<fieldset key={index}>
<Controller
render={({ field: { onBlur, value, name, ref } }) => (
<CartInner
key={index}
name={name}
ref={ref}
onChange={(e) => handleOnChange(index, e)}
onBlur={onBlur}
/>
)}
name={`test.${index}.lastName`}
control={control}
/>
</fieldset>
);
})}
<button>Progess to payment</button>
</div>
</form>
);
}
// add delete
// total money
// add the cart documents to a history with a timestamp and show it was a BUY ORDER
// delete the documents from the cart
|
Getting custom components to work within react-hook-form using onChange
|
I have a checkout cart where you have different cart items, and for each one you can change the quantity prior to purchase.
Here's how the code looks:
import React, { useEffect, useState } from "react";
import PureInput from "./PureInput";
import { useForm, Controller } from "react-hook-form";
const CartInner = React.forwardRef(
(
{
control,
element,
value,
handleOnChange,
images,
name,
monthlyAmount,
price,
projectedGrowth,
id,
...inputProps
}: any,
ref: any
) => {
return (
<div className="grid gap-8 grid-cols-2 mb-12 py-6 px-8 border-2 border-slate-200">
<div>
<PureInput
min={200}
max={price}
onChange={handleOnChange}
type="number"
step={200}
defaultValue={element.price}
id={id}
ref={ref}
{...inputProps}
/>
</div>
</div>
);
}
);
export default function Checkout() {
const { control, handleSubmit } = useForm();
const handleOnChange = (index: any, e: any) => {
console.log(e, "e");
};
const onSubmit = async (data: any) => {
console.log(data, "data from Form.tsx");
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="grid gap-8 grid-cols-3">
<div className="col-span-2">
{[0, 2].map((element, index) => {
return (
<fieldset key={index}>
<Controller
render={({ field }) => (
<CartInner
element={element}
handleOnChange={(e) => handleOnChange(index, e)}
{...field}
/>
)}
name={`test.${index}.lastName`}
control={control}
/>
</fieldset>
);
})}
<button>Progess to payment</button>
</div>
</form>
);
}
And the PureInput:
import * as React from "react";
type IProps = any;
const PureInput = React.forwardRef(
({ className, id, onChange, ...inputProps }: IProps, ref: any) => {
return (
<input
id={id}
ref={ref}
onChange={onChange}
type="input"
className={`${className} block w-full bg-white text-black rounded-md border-2 font-bold border-grey-200 text-xl px-4 py-4 focus:border-orange-500 focus:ring-orange-500`}
{...inputProps}
/>
);
}
);
export default PureInput;
Everything works fine in terms of submitting the form. When I do, I get an array of whatever values I have entered into the input:
[{lastName: "1600"}
{lastName: "800"}]
My package versions:
"react-dom": "18.2.0",
"react-hook-form": "^7.29.0",
But my onChange no longer fires. How can I get the onChange to fire so I can log the value of the input inside <Checkout /> component?
Here's a codesandbox if it helps
|
[
"The onChange event handler is only called when the input value is changed. It's not called when the form is submitted.\nTo access the values of the inputs when the form is submitted, you can use the handleSubmit hook provided by react-hook-form in your Checkout component. This hook takes a callback function as an argument, and this function will be called when the form is submitted. The values of the form inputs will be passed to this callback as an object:\nimport React, { useEffect, useState } from \"react\";\nimport { useForm } from \"react-hook-form\";\n\nconst CartInner = React.forwardRef(\n (\n {\n control,\n element,\n value,\n handleOnChange,\n images,\n name,\n monthlyAmount,\n price,\n projectedGrowth,\n id,\n ...inputProps\n }: any,\n ref: any\n ) => {\n return (\n <div className=\"grid gap-8 grid-cols-2 mb-12 py-6 px-8 border-2 border-slate-200\">\n <div>\n <PureInput\n min={200}\n max={price}\n onChange={handleOnChange}\n type=\"number\"\n step={200}\n defaultValue={element.price}\n id={id}\n ref={ref}\n {...inputProps}\n />\n </div>\n </div>\n );\n }\n);\n\nexport default function Checkout() {\n const { control, handleSubmit } = useForm();\n\n const handleOnChange = (index: any, e: any) => {\n console.log(e, \"e\");\n };\n\n const onSubmit = async (data: any) => {\n console.log(data, \"data from Form.tsx\");\n };\n\n return (\n <form onSubmit={handleSubmit(onSubmit)} className=\"grid gap-8 grid-cols-3\">\n <div className=\"col-span-2\">\n {[0, 2].map((element, index) => {\n return (\n <fieldset key={index}>\n <Controller\n render={({ field }) => (\n <CartInner\n element={element}\n handleOnChange={(e) => handleOnChange(index, e)}\n {...field}\n />\n )}\n name={`test.${index}.lastName`}\n control={control}\n />\n </fieldset>\n );\n })}\n <button>Progess to payment</button>\n </div>\n </form>\n );\n}\n\n",
"You can make the following changes to plug into onChange event\n // pass an event handler name with different name \n <PureInput\n min={200}\n max={price}\n // pass a handler with different name as inputOptions overrides that prop\n handleOnChange={handleOnChange}\n type=\"number\"\n step={200}\n defaultValue={element.price}\n id={id}\n ref={ref}\n {...inputProps}\n />\n\n//plug into the default onchange to call you handler also\n <input\n id={id}\n ref={ref}\n onChange={(e) => {\n console.log(\"on change\");\n // call react-hook-form onChange\n onChange(e);\n // call your handler\n handleOnChange(e);\n }}\n type=\"input\"\n className={`${className} block w-full bg-white text-black rounded-md border-2 font-bold border-grey-200 text-xl px-4 py-4 focus:border-orange-500 focus:ring-orange-500`}\n {...inputProps}\n />\n\nHope it helps you in solving your problem,\nCheers\n",
"This part of the documentation led me to the answer:\nimport React, { useEffect, useState } from \"react\";\n\nimport PureInput from \"./PureInput\";\nimport { useForm, Controller } from \"react-hook-form\";\n\nconst CartInner = React.forwardRef(\n ({ onChange, onBlur, name, label, ...inputProps }: any, ref: any) => {\n return (\n <input\n name={name}\n ref={ref}\n onChange={onChange}\n onBlur={onBlur}\n type=\"number\"\n />\n );\n }\n);\n\nexport default function Checkout() {\n const { control, handleSubmit } = useForm();\n\n const handleOnChange = (index: any, e: any) => {\n console.log(e.target.value, \"e\");\n };\n\n const onSubmit = async (data: any) => {\n console.log(data, \"data from Form.tsx\");\n };\n\n return (\n <form onSubmit={handleSubmit(onSubmit)} className=\"grid gap-8 grid-cols-3\">\n <div className=\"col-span-2\">\n {[0, 2].map((element, index) => {\n return (\n <fieldset key={index}>\n <Controller\n render={({ field: { onBlur, value, name, ref } }) => (\n <CartInner\n key={index}\n name={name}\n ref={ref}\n onChange={(e) => handleOnChange(index, e)}\n onBlur={onBlur}\n />\n )}\n name={`test.${index}.lastName`}\n control={control}\n />\n </fieldset>\n );\n })}\n <button>Progess to payment</button>\n </div>\n </form>\n );\n}\n\n// add delete\n// total money\n// add the cart documents to a history with a timestamp and show it was a BUY ORDER\n// delete the documents from the cart\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"javascript",
"react_hook_form",
"reactjs"
] |
stackoverflow_0074663485_javascript_react_hook_form_reactjs.txt
|
Q:
Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any)
I have a component that looks like this. This version works perfectly:
export default function StatusMessage(isAdded: boolean, errorMessage: string) {
if (isAdded) {
return <ResultAlert severity="success" text="User Added" />;
} else {
if (errorMessage !== '') {
if (
errorMessage.includes('email')
) {
return <ResultAlert severity="error" />;
}
if (
errorMessage.includes('phone number')
) {
return (
<ResultAlert severity="error" text="" />
);
}
}
}
}
Now, I am trying to change the way I export it. I am trying this:
type StatusMessageProps = {
isAdded: boolean;
errorMessage: string;
}
export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
isAdded,
errorMessage
}) => {
but i keep getting an error that:
Type '({ isAdded, errorMessage }: PropsWithChildren<StatusMessageProps>) => Element | undefined' is not assignable to type 'FunctionComponent<StatusMessageProps>'.
Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
Type 'undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
I am using the same method on different pages but the error is only here
Edit:
I am using this component like this:
const [isAdded, setIsAdded] = useState(false);
{isSubmitted && StatusMessage(isAdded, errorMessage)}
it gives me an error on isAdded that
Argument of type 'boolean' is not assignable to parameter of type 'PropsWithChildren<StatusMessageProps>'.ts(2345)
A:
You must have forgotten return a value in your component. Are you forgetting return null since void 0 is unacceptable result of a React component?
export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
isAdded,
errorMessage
}) => {
if (isAdded) {
return <ResultAlert severity="success" text="User Added" />;
} else {
if (errorMessage !== '') {
if (
errorMessage.includes('email')
) {
return <ResultAlert severity="error" />;
}
if (
errorMessage.includes('phone number')
) {
return (
<ResultAlert severity="error" text="" />
);
}
}
// Here where you missed
return null;
}
}
A:
in my case return null; didn't work so I return <></>;
|
Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any)
|
I have a component that looks like this. This version works perfectly:
export default function StatusMessage(isAdded: boolean, errorMessage: string) {
if (isAdded) {
return <ResultAlert severity="success" text="User Added" />;
} else {
if (errorMessage !== '') {
if (
errorMessage.includes('email')
) {
return <ResultAlert severity="error" />;
}
if (
errorMessage.includes('phone number')
) {
return (
<ResultAlert severity="error" text="" />
);
}
}
}
}
Now, I am trying to change the way I export it. I am trying this:
type StatusMessageProps = {
isAdded: boolean;
errorMessage: string;
}
export const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({
isAdded,
errorMessage
}) => {
but i keep getting an error that:
Type '({ isAdded, errorMessage }: PropsWithChildren<StatusMessageProps>) => Element | undefined' is not assignable to type 'FunctionComponent<StatusMessageProps>'.
Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
Type 'undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
I am using the same method on different pages but the error is only here
Edit:
I am using this component like this:
const [isAdded, setIsAdded] = useState(false);
{isSubmitted && StatusMessage(isAdded, errorMessage)}
it gives me an error on isAdded that
Argument of type 'boolean' is not assignable to parameter of type 'PropsWithChildren<StatusMessageProps>'.ts(2345)
|
[
"You must have forgotten return a value in your component. Are you forgetting return null since void 0 is unacceptable result of a React component?\nexport const StatusMessage: React.FunctionComponent<StatusMessageProps> = ({\n isAdded,\n errorMessage\n}) => {\n if (isAdded) {\n return <ResultAlert severity=\"success\" text=\"User Added\" />;\n } else {\n if (errorMessage !== '') {\n if (\n errorMessage.includes('email')\n ) {\n return <ResultAlert severity=\"error\" />;\n }\n if (\n errorMessage.includes('phone number')\n ) {\n return (\n <ResultAlert severity=\"error\" text=\"\" />\n );\n } \n }\n\n // Here where you missed\n return null;\n }\n}\n\n",
"in my case return null; didn't work so I return <></>;\n"
] |
[
22,
0
] |
[] |
[] |
[
"javascript",
"react_native",
"react_props",
"reactjs",
"typescript"
] |
stackoverflow_0063132565_javascript_react_native_react_props_reactjs_typescript.txt
|
Q:
user.status always returns "offline"
I know that user.status should be used to return the user status. But it always returns the status of offline, regardless of the fact that I or other participants change the status.
Code:
@app_commands.command(name='user', description=f'Детальна інформація про користувача')
async def user_(self, interaction: discord.Interaction, user: discord.Member = None):
ctx = await self.bot.get_context(interaction)# Don't pay attention to it
if user is None:
user = ctx.author
print(user.status)
global user_status
user_status = None
if user.status == discord.Status.online:
user_status = "<:online:1038376483758030898>В мережі"
elif user.status == discord.Status.offline or user.status == discord.Status.invisible:
user_status = "<:ofline:1038376481774120970>Не в мережі"
elif user.status == discord.Status.idle:
user_status = "<:idle:1038376474958381056>Відійшов"
elif user.status == discord.Status.dnd or user.status == discord.Status.do_not_disturb:
user_status = "<:dnds:1048347246556626954>Не турбувати"
await interaction.response.send_message(embed=embed, ephemeral=True)
In another command (not a slash command), this status check is working properly. Intentions I have set up that
bot = commands.Bot(commands.when_mentioned_or('.'), intents = discord.Intents.all()).
And in the portal of the developers, too, seems to be right
A:
It seems to be a bug that it shows up as offline everytime, but here's something you can do:
userstatus = await interaction.guild.get_member(user.id).status
if userstatus == discord.Status.online:
user_status = "<:online:1038376483758030898>В мережі"
#rest of your checks here
ps: You don't need or user.status == discord.Status.do_not_disturb and or user.status == discord.Status.invisible because they mean the same thing as discord.Status.offline and discord.Status.dnd respectively.
|
user.status always returns "offline"
|
I know that user.status should be used to return the user status. But it always returns the status of offline, regardless of the fact that I or other participants change the status.
Code:
@app_commands.command(name='user', description=f'Детальна інформація про користувача')
async def user_(self, interaction: discord.Interaction, user: discord.Member = None):
ctx = await self.bot.get_context(interaction)# Don't pay attention to it
if user is None:
user = ctx.author
print(user.status)
global user_status
user_status = None
if user.status == discord.Status.online:
user_status = "<:online:1038376483758030898>В мережі"
elif user.status == discord.Status.offline or user.status == discord.Status.invisible:
user_status = "<:ofline:1038376481774120970>Не в мережі"
elif user.status == discord.Status.idle:
user_status = "<:idle:1038376474958381056>Відійшов"
elif user.status == discord.Status.dnd or user.status == discord.Status.do_not_disturb:
user_status = "<:dnds:1048347246556626954>Не турбувати"
await interaction.response.send_message(embed=embed, ephemeral=True)
In another command (not a slash command), this status check is working properly. Intentions I have set up that
bot = commands.Bot(commands.when_mentioned_or('.'), intents = discord.Intents.all()).
And in the portal of the developers, too, seems to be right
|
[
"It seems to be a bug that it shows up as offline everytime, but here's something you can do:\nuserstatus = await interaction.guild.get_member(user.id).status\nif userstatus == discord.Status.online:\n user_status = \"<:online:1038376483758030898>В мережі\"\n#rest of your checks here\n\nps: You don't need or user.status == discord.Status.do_not_disturb and or user.status == discord.Status.invisible because they mean the same thing as discord.Status.offline and discord.Status.dnd respectively.\n"
] |
[
1
] |
[] |
[] |
[
"discord.py"
] |
stackoverflow_0074663046_discord.py.txt
|
Q:
jQuery AJAX POST not passing value to controller in ASP.Net Core MVC
I have been digging around for a few hours now and just not finding anything. A lot of questions similar to this are about posting to controllers but I am just trying to post a single integer. I have confirmed the code is calling into the controller as I can hit a break-point in the controller and see that the value I have hard-coded is not being passed to the controller. I am sure there is something stupid I am missing but I can't figure it out after trying a lot of different things the controller always get the value of "0" for the selectedNavigationItemID. What am I missing to pass the integer into my controller?
Striped out AJAX call:
$(document).ready(function()
{
$('#SelectedExistingNavigationItemID').change(function()
{
$.ajax('../Sections/GetSectionNavigationItemInfo/'),
{
type: 'POST',
dataType: 'json',
data: { 'selectedNavigationItemID': '3'},
success: function(data, status, jqXHR)
{
if ("success" == status)
{
alert('good');
}
}
};
});
});
Code on my controller side:
[Route("GetSectionNavigationItemInfo")]
public async Task<JsonResult> GetSectionNavigationItemInfo(int selectedNavigationItemID)
{
var navigationItem = await _navigationHelper.GetSectionNavigationMenuItem(selectedNavigationItemID);
return Json(navigationItem);
}
I have tried removing the questions around the information in data, specifiying application/json for a contentType, changing dataType to multipart/form-data but it all results in the value of 0 being passed into the controller.
What stupid little thing am I missing to make this work?
A:
If you look at the browser's network tab, it's probably being sent with the GET method, because your ajax syntax is incorrect and Ajax Configuration aren't applied, and by default it's being sent with the GET method, try changing your code to :
$(document).ready(function()
{
$('#SelectedExistingNavigationItemID').change(function() {
$.ajax({
url: '../Sections/GetSectionNavigationItemInfo/',
type: 'POST',
dataType: 'json',
data: { 'selectedNavigationItemID': '3' },
success: function(data, status, jqXHR) {
if ("success" == status) {
alert('good');
}
}
});
});
});
A tip to improve your code:
It is better to add [HttpPost] attribute to your action so that your action is only available via POST method. This way, your action method would no longer be called with the GET method, and you could debug your code more easily and find the problem.
[HttpPost]
[Route("GetSectionNavigationItemInfo")]
public async Task<JsonResult> GetSectionNavigationItemInfo(int selectedNavigationItemID)
{
var navigationItem = await _navigationHelper.GetSectionNavigationMenuItem(selectedNavigationItemID);
return Json(navigationItem);
}
|
jQuery AJAX POST not passing value to controller in ASP.Net Core MVC
|
I have been digging around for a few hours now and just not finding anything. A lot of questions similar to this are about posting to controllers but I am just trying to post a single integer. I have confirmed the code is calling into the controller as I can hit a break-point in the controller and see that the value I have hard-coded is not being passed to the controller. I am sure there is something stupid I am missing but I can't figure it out after trying a lot of different things the controller always get the value of "0" for the selectedNavigationItemID. What am I missing to pass the integer into my controller?
Striped out AJAX call:
$(document).ready(function()
{
$('#SelectedExistingNavigationItemID').change(function()
{
$.ajax('../Sections/GetSectionNavigationItemInfo/'),
{
type: 'POST',
dataType: 'json',
data: { 'selectedNavigationItemID': '3'},
success: function(data, status, jqXHR)
{
if ("success" == status)
{
alert('good');
}
}
};
});
});
Code on my controller side:
[Route("GetSectionNavigationItemInfo")]
public async Task<JsonResult> GetSectionNavigationItemInfo(int selectedNavigationItemID)
{
var navigationItem = await _navigationHelper.GetSectionNavigationMenuItem(selectedNavigationItemID);
return Json(navigationItem);
}
I have tried removing the questions around the information in data, specifiying application/json for a contentType, changing dataType to multipart/form-data but it all results in the value of 0 being passed into the controller.
What stupid little thing am I missing to make this work?
|
[
"If you look at the browser's network tab, it's probably being sent with the GET method, because your ajax syntax is incorrect and Ajax Configuration aren't applied, and by default it's being sent with the GET method, try changing your code to :\n$(document).ready(function()\n{\n $('#SelectedExistingNavigationItemID').change(function() {\n $.ajax({\n url: '../Sections/GetSectionNavigationItemInfo/',\n type: 'POST',\n dataType: 'json',\n data: { 'selectedNavigationItemID': '3' },\n success: function(data, status, jqXHR) {\n if (\"success\" == status) {\n alert('good');\n }\n }\n });\n });\n});\n\nA tip to improve your code:\nIt is better to add [HttpPost] attribute to your action so that your action is only available via POST method. This way, your action method would no longer be called with the GET method, and you could debug your code more easily and find the problem.\n[HttpPost]\n[Route(\"GetSectionNavigationItemInfo\")]\npublic async Task<JsonResult> GetSectionNavigationItemInfo(int selectedNavigationItemID)\n{\n var navigationItem = await _navigationHelper.GetSectionNavigationMenuItem(selectedNavigationItemID);\n return Json(navigationItem);\n}\n\n"
] |
[
1
] |
[] |
[] |
[
"ajax",
"asp.net_core_mvc",
"jquery"
] |
stackoverflow_0074664342_ajax_asp.net_core_mvc_jquery.txt
|
Q:
TRIGGER for validating data
I have 2 tables:
Chestionar
{
id_c pk
punctaj_max
}
Test{
id_t pk
punctaj
id_c fk
}
I want to define a trigger to validate that, before an update, the modified punctaj is between 0 and the punctaj_max from the chestionar table with that id_c.
I tried this but it doesn't work
CREATE OR REPLACE TRIGGER check_val_salary
BEFORE UPDATE of punctaj ON test
FOR EACH ROW
BEGIN
IF :new.punctaj<0 OR :new.punctaj > (Select punctaj_max from chestionar c where c.id_c=:old.id_c)
THEN
RAISE_APPLICATION_ERROR (-20508, 'Punctaj out of bounds');
END;
Any tips please?
A:
Tables and some sample data for chestionar:
SQL> create table chestionar
2 (id_c number primary key,
3 punctaj_max number);
Table created.
SQL> insert into chestionar
2 select 1 id_c, 100 punctaj_max from dual union all
3 select 2 , 200 from dual;
2 rows created.
SQL> create table test
2 (id_t number primary key,
3 punctaj number,
4 id_c number references chestionar(id_c));
Table created.
Trigger:
SQL> create or replace trigger trg_biu_test
2 before insert or update on test
3 for each row
4 declare
5 l_punctaj_max chestionar.punctaj_max%type;
6 begin
7 select c.punctaj_max
8 into l_punctaj_max
9 from chestionar c
10 where c.id_c = :new.id_c;
11
12 if :new.punctaj not between 0 and l_punctaj_max then
13 raise_application_error(-20000, 'Punctaj should be between 0 and ' || l_punctaj_max);
14 end if;
15 exception
16 when no_data_found then
17 raise_application_error(-20001, 'Can not find boundary for that ID');
18 end;
19 /
Trigger created.
Testing:
SQL> insert into test (id_t, punctaj, id_c) values (1001, 555, 3);
insert into test (id_t, punctaj, id_c) values (1001, 555, 3)
*
ERROR at line 1:
ORA-20001: Can not find boundary for that ID
ORA-06512: at "SCOTT.TRG_BIU_TEST", line 14
ORA-04088: error during execution of trigger 'SCOTT.TRG_BIU_TEST'
SQL> insert into test (id_t, punctaj, id_c) values (1001, 555, 1);
insert into test (id_t, punctaj, id_c) values (1001, 555, 1)
*
ERROR at line 1:
ORA-20000: Punctaj should be between 0 and 100
ORA-06512: at "SCOTT.TRG_BIU_TEST", line 10
ORA-04088: error during execution of trigger 'SCOTT.TRG_BIU_TEST'
SQL> insert into test (id_t, punctaj, id_c) values (1001, 55, 1);
1 row created.
SQL>
|
TRIGGER for validating data
|
I have 2 tables:
Chestionar
{
id_c pk
punctaj_max
}
Test{
id_t pk
punctaj
id_c fk
}
I want to define a trigger to validate that, before an update, the modified punctaj is between 0 and the punctaj_max from the chestionar table with that id_c.
I tried this but it doesn't work
CREATE OR REPLACE TRIGGER check_val_salary
BEFORE UPDATE of punctaj ON test
FOR EACH ROW
BEGIN
IF :new.punctaj<0 OR :new.punctaj > (Select punctaj_max from chestionar c where c.id_c=:old.id_c)
THEN
RAISE_APPLICATION_ERROR (-20508, 'Punctaj out of bounds');
END;
Any tips please?
|
[
"Tables and some sample data for chestionar:\nSQL> create table chestionar\n 2 (id_c number primary key,\n 3 punctaj_max number);\n\nTable created.\n\nSQL> insert into chestionar\n 2 select 1 id_c, 100 punctaj_max from dual union all\n 3 select 2 , 200 from dual;\n\n2 rows created.\n\nSQL> create table test\n 2 (id_t number primary key,\n 3 punctaj number,\n 4 id_c number references chestionar(id_c));\n\nTable created.\n\nTrigger:\nSQL> create or replace trigger trg_biu_test\n 2 before insert or update on test\n 3 for each row\n 4 declare\n 5 l_punctaj_max chestionar.punctaj_max%type;\n 6 begin\n 7 select c.punctaj_max\n 8 into l_punctaj_max\n 9 from chestionar c\n 10 where c.id_c = :new.id_c;\n 11\n 12 if :new.punctaj not between 0 and l_punctaj_max then\n 13 raise_application_error(-20000, 'Punctaj should be between 0 and ' || l_punctaj_max);\n 14 end if;\n 15 exception\n 16 when no_data_found then\n 17 raise_application_error(-20001, 'Can not find boundary for that ID');\n 18 end;\n 19 /\n\nTrigger created.\n\nTesting:\nSQL> insert into test (id_t, punctaj, id_c) values (1001, 555, 3);\ninsert into test (id_t, punctaj, id_c) values (1001, 555, 3)\n *\nERROR at line 1:\nORA-20001: Can not find boundary for that ID\nORA-06512: at \"SCOTT.TRG_BIU_TEST\", line 14\nORA-04088: error during execution of trigger 'SCOTT.TRG_BIU_TEST'\n\n\nSQL> insert into test (id_t, punctaj, id_c) values (1001, 555, 1);\ninsert into test (id_t, punctaj, id_c) values (1001, 555, 1)\n *\nERROR at line 1:\nORA-20000: Punctaj should be between 0 and 100\nORA-06512: at \"SCOTT.TRG_BIU_TEST\", line 10\nORA-04088: error during execution of trigger 'SCOTT.TRG_BIU_TEST'\n\n\nSQL> insert into test (id_t, punctaj, id_c) values (1001, 55, 1);\n\n1 row created.\n\nSQL>\n\n"
] |
[
0
] |
[] |
[] |
[
"oracle",
"plsql",
"sql",
"triggers"
] |
stackoverflow_0074663266_oracle_plsql_sql_triggers.txt
|
Q:
count the number of values in data frame's column that exist in another data frame's column
I have two data frames:
df1:
Index
Date
0
2016-03-21 20:10:00
1
2016-03-22 21:09:00
2
2016-05-03 17:05:00
df2:
Index
Date
0
2016-03-21 20:10:00
1
2016-03-21 21:00:00
2
2016-03-22 21:09:00
3
2016-05-03 17:05:00
4
2017-06-01 16:10:00
There's probably a really simple way to do this but how would I count the number of values in the df1 Date column that are also in the df2 Date column? (These are not unique value counts)
A:
The simplest approach to solve your problem will be use set intersection(find common element from set).
Eg:
df1=pd.DataFrame({"date":['2016-03-21 20:10:00','2016-03-22 21:09:00','2016-05-03 17:05:00']})
df2=pd.DataFrame({"date":['2016-03-21 20:10:00','2016-03-21 21:00:00',
'2016-03-22 21:09:00','2016-05-03 17:05:00','2017-06-01 16:10:00']})
print(len(set(df1.date) & set(df2.date))) # 3
This will just convert that specified column to python-set and find common between them.
If you want to use Pandas then you can use pandas.merge() to get the common rows based on the columns.
df3 = pd.merge(df1, df2)
print(len(df3)) # 3
and count common rows using len function.
A:
You could use the isin function:
len(df1[df1.Date.isin(df2.Date)])
Output:
3
|
count the number of values in data frame's column that exist in another data frame's column
|
I have two data frames:
df1:
Index
Date
0
2016-03-21 20:10:00
1
2016-03-22 21:09:00
2
2016-05-03 17:05:00
df2:
Index
Date
0
2016-03-21 20:10:00
1
2016-03-21 21:00:00
2
2016-03-22 21:09:00
3
2016-05-03 17:05:00
4
2017-06-01 16:10:00
There's probably a really simple way to do this but how would I count the number of values in the df1 Date column that are also in the df2 Date column? (These are not unique value counts)
|
[
"The simplest approach to solve your problem will be use set intersection(find common element from set).\nEg:\ndf1=pd.DataFrame({\"date\":['2016-03-21 20:10:00','2016-03-22 21:09:00','2016-05-03 17:05:00']})\n\ndf2=pd.DataFrame({\"date\":['2016-03-21 20:10:00','2016-03-21 21:00:00',\n '2016-03-22 21:09:00','2016-05-03 17:05:00','2017-06-01 16:10:00']})\n\nprint(len(set(df1.date) & set(df2.date))) # 3\n\nThis will just convert that specified column to python-set and find common between them.\n\nIf you want to use Pandas then you can use pandas.merge() to get the common rows based on the columns.\ndf3 = pd.merge(df1, df2)\nprint(len(df3)) # 3\n\nand count common rows using len function.\n",
"You could use the isin function:\nlen(df1[df1.Date.isin(df2.Date)])\n\nOutput:\n3\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"count",
"date",
"pandas",
"python"
] |
stackoverflow_0074664246_count_date_pandas_python.txt
|
Q:
jQuery - Illegal invocation
jQuery v1.7.2
I have this funcion that is giving me the following error while executing :
Uncaught TypeError: Illegal invocation
Here's the function :
$('form[name="twp-tool-distance-form"]').on('submit', function(e) {
e.preventDefault();
var from = $('form[name="twp-tool-distance-form"] input[name="from"]');
var to = $('form[name="twp-tool-distance-form"] input[name="to"]');
var unit = $('form[name="twp-tool-distance-form"] input[name="unit"]');
var speed = game.unit.speed($(unit).val());
if (!/^\d{3}\|\d{3}$/.test($(from).val()))
{
$(from).css('border-color', 'red');
return false;
}
if (!/^\d{3}\|\d{3}$/.test($(to).val()))
{
$(to).css('border-color', 'red');
return false;
}
var data = {
from : from,
to : to,
speed : speed
};
$.ajax({
url : base_url+'index.php',
type: 'POST',
dataType: 'json',
data: data,
cache : false
}).done(function(response) {
alert(response);
});
return false;
});
If I remove data from ajax call, it works .. any suggestions?
Thanks!
A:
Try to set processData: false in ajax settings like this
$.ajax({
url : base_url+'index.php',
type: 'POST',
dataType: 'json',
data: data,
cache : false,
processData: false
}).done(function(response) {
alert(response);
});
A:
I think you need to have strings as the data values. It's likely something internally within jQuery that isn't encoding/serializing correctly the To & From Objects.
Try:
var data = {
from : from.val(),
to : to.val(),
speed : speed
};
Notice also on the lines:
$(from).css(...
$(to).css(
You don't need the jQuery wrapper as To & From are already jQuery objects.
A:
Just for the record it can also happen if you try to use undeclared variable in data like
var layout = {};
$.ajax({
...
data: {
layout: laoyut // notice misspelled variable name
},
...
});
A:
If you want to submit a form using Javascript FormData API with uploading files you need to set below two options:
processData: false,
contentType: false
You can try as follows:
//Ajax Form Submission
$(document).on("click", ".afs", function (e) {
e.preventDefault();
e.stopPropagation();
var thisBtn = $(this);
var thisForm = thisBtn.closest("form");
var formData = new FormData(thisForm[0]);
//var formData = thisForm.serializeArray();
$.ajax({
type: "POST",
url: "<?=base_url();?>assignment/createAssignment",
data: formData,
processData: false,
contentType: false,
success:function(data){
if(data=='yes')
{
alert('Success! Record inserted successfully');
}
else if(data=='no')
{
alert('Error! Record not inserted successfully')
}
else
{
alert('Error! Try again');
}
}
});
});
A:
In my case, I just changed
Note: This is in case of Django, so I added csrftoken. In your case, you may not need it.
Added contentType: false, processData: false
Commented out "Content-Type": "application/json"
$.ajax({
url: location.pathname,
type: "POST",
crossDomain: true,
dataType: "json",
headers: {
"X-CSRFToken": csrftoken,
"Content-Type": "application/json"
},
data:formData,
success: (response, textStatus, jQxhr) => {
},
error: (jQxhr, textStatus, errorThrown) => {
}
})
to
$.ajax({
url: location.pathname,
type: "POST",
crossDomain: true,
dataType: "json",
contentType: false,
processData: false,
headers: {
"X-CSRFToken": csrftoken
// "Content-Type": "application/json",
},
data:formData,
success: (response, textStatus, jQxhr) => {
},
error: (jQxhr, textStatus, errorThrown) => {
}
})
and it worked.
A:
In My case I have't define all variables which I am passing to data in ajax.
var page = 1;
$.ajax({
url: 'your_url',
type: "post",
data: { 'page' : page, 'search_candidate' : search_candidate }
success: function(result){
alert('function called');
}
)}
I have just defined variable var search_candidate = "candidate name"; and its working.
var page = 1;
var search_candidate = "candidate name"; // defined
$.ajax({
url: 'your_url',
type: "post",
data: { 'page' : page, 'search_candidate' : search_candidate }
success: function(result){
alert('function called');
}
)}
A:
Working for me.
processData: false,
contentType: false, is required for working.
var formData = new FormData($('#author_post')[0]);
formData.append('t','author-add');
$.ajax({
type: 'POST',
url: 'url-here',
cache: false,
processData: false,
contentType: false,
data:formData,
success: function(response) {
//success code
}
});
A:
My problem was unrelated to processData. It was because I sent a function that cannot be called later with apply because it did not have enough arguments. Specifically I shouldn't have used alert as the error callback.
$.ajax({
url: csvApi,
success: parseCsvs,
dataType: "json",
timeout: 5000,
processData: false,
error: alert
});
See this answer for more information on why that can be a problem: Why are certain function calls termed "illegal invocations" in JavaScript?
The way I was able to discover this was by adding a console.log(list[ firingIndex ]) to jQuery so I could track what it was firing.
This was the fix:
function myError(jqx, textStatus, errStr) {
alert(errStr);
}
$.ajax({
url: csvApi,
success: parseCsvs,
dataType: "json",
timeout: 5000,
error: myError // Note that passing `alert` instead can cause a "jquery.js:3189 Uncaught TypeError: Illegal invocation" sometimes
});
A:
Also this is a cause too:
If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().
A:
Working sample code is here -
var formData = new FormData($("#formId")[0]);
$.ajax({
url : "/api/v1/save-data",
type : "POST",
enctype: "multipart/form-data",
dataType: "json",
data: formData,
success : function(data) {
console.log(data);
},
cache: false,
contentType: false,
processData: false,
error: function() {
console.log("Error");
}
});
|
jQuery - Illegal invocation
|
jQuery v1.7.2
I have this funcion that is giving me the following error while executing :
Uncaught TypeError: Illegal invocation
Here's the function :
$('form[name="twp-tool-distance-form"]').on('submit', function(e) {
e.preventDefault();
var from = $('form[name="twp-tool-distance-form"] input[name="from"]');
var to = $('form[name="twp-tool-distance-form"] input[name="to"]');
var unit = $('form[name="twp-tool-distance-form"] input[name="unit"]');
var speed = game.unit.speed($(unit).val());
if (!/^\d{3}\|\d{3}$/.test($(from).val()))
{
$(from).css('border-color', 'red');
return false;
}
if (!/^\d{3}\|\d{3}$/.test($(to).val()))
{
$(to).css('border-color', 'red');
return false;
}
var data = {
from : from,
to : to,
speed : speed
};
$.ajax({
url : base_url+'index.php',
type: 'POST',
dataType: 'json',
data: data,
cache : false
}).done(function(response) {
alert(response);
});
return false;
});
If I remove data from ajax call, it works .. any suggestions?
Thanks!
|
[
"Try to set processData: false in ajax settings like this\n$.ajax({\n url : base_url+'index.php',\n type: 'POST',\n dataType: 'json',\n data: data,\n cache : false,\n processData: false\n}).done(function(response) {\n alert(response);\n});\n\n",
"I think you need to have strings as the data values. It's likely something internally within jQuery that isn't encoding/serializing correctly the To & From Objects.\nTry:\nvar data = {\n from : from.val(),\n to : to.val(),\n speed : speed\n};\n\nNotice also on the lines:\n$(from).css(...\n$(to).css(\n\nYou don't need the jQuery wrapper as To & From are already jQuery objects.\n",
"Just for the record it can also happen if you try to use undeclared variable in data like\nvar layout = {};\n$.ajax({\n ...\n data: {\n layout: laoyut // notice misspelled variable name\n },\n ...\n});\n\n",
"If you want to submit a form using Javascript FormData API with uploading files you need to set below two options:\nprocessData: false,\ncontentType: false\n\nYou can try as follows:\n//Ajax Form Submission\n$(document).on(\"click\", \".afs\", function (e) {\n e.preventDefault();\n e.stopPropagation();\n var thisBtn = $(this);\n var thisForm = thisBtn.closest(\"form\");\n var formData = new FormData(thisForm[0]);\n //var formData = thisForm.serializeArray();\n\n $.ajax({\n type: \"POST\",\n url: \"<?=base_url();?>assignment/createAssignment\",\n data: formData,\n processData: false,\n contentType: false,\n success:function(data){\n if(data=='yes')\n {\n alert('Success! Record inserted successfully');\n }\n else if(data=='no')\n {\n alert('Error! Record not inserted successfully')\n }\n else\n {\n alert('Error! Try again');\n }\n }\n });\n});\n\n",
"In my case, I just changed \nNote: This is in case of Django, so I added csrftoken. In your case, you may not need it. \n\nAdded contentType: false, processData: false\nCommented out \"Content-Type\": \"application/json\"\n\n$.ajax({\n url: location.pathname, \n type: \"POST\",\n crossDomain: true,\n dataType: \"json\",\n headers: {\n \"X-CSRFToken\": csrftoken,\n \"Content-Type\": \"application/json\"\n },\n data:formData,\n success: (response, textStatus, jQxhr) => {\n\n },\n error: (jQxhr, textStatus, errorThrown) => {\n\n }\n})\n\nto\n$.ajax({\n url: location.pathname, \n type: \"POST\",\n crossDomain: true,\n dataType: \"json\",\n contentType: false,\n processData: false,\n headers: {\n \"X-CSRFToken\": csrftoken\n // \"Content-Type\": \"application/json\",\n },\n data:formData,\n success: (response, textStatus, jQxhr) => {\n\n },\n error: (jQxhr, textStatus, errorThrown) => {\n\n }\n})\n\nand it worked.\n",
"In My case I have't define all variables which I am passing to data in ajax.\nvar page = 1;\n\n$.ajax({\n url: 'your_url',\n type: \"post\",\n data: { 'page' : page, 'search_candidate' : search_candidate }\n success: function(result){\n alert('function called');\n }\n)}\n\nI have just defined variable var search_candidate = \"candidate name\"; and its working.\nvar page = 1;\nvar search_candidate = \"candidate name\"; // defined\n$.ajax({\n url: 'your_url',\n type: \"post\",\n data: { 'page' : page, 'search_candidate' : search_candidate }\n success: function(result){\n alert('function called');\n }\n)}\n\n",
"Working for me.\nprocessData: false,\ncontentType: false, is required for working.\n var formData = new FormData($('#author_post')[0]);\n formData.append('t','author-add');\n $.ajax({\n type: 'POST',\n url: 'url-here',\n cache: false,\n processData: false,\n contentType: false,\n data:formData,\n success: function(response) {\n //success code\n }\n });\n\n",
"My problem was unrelated to processData. It was because I sent a function that cannot be called later with apply because it did not have enough arguments. Specifically I shouldn't have used alert as the error callback.\n$.ajax({\n url: csvApi,\n success: parseCsvs,\n dataType: \"json\",\n timeout: 5000,\n processData: false,\n error: alert\n});\n\nSee this answer for more information on why that can be a problem: Why are certain function calls termed \"illegal invocations\" in JavaScript?\nThe way I was able to discover this was by adding a console.log(list[ firingIndex ]) to jQuery so I could track what it was firing.\nThis was the fix:\nfunction myError(jqx, textStatus, errStr) {\n alert(errStr);\n}\n\n$.ajax({\n url: csvApi,\n success: parseCsvs,\n dataType: \"json\",\n timeout: 5000,\n error: myError // Note that passing `alert` instead can cause a \"jquery.js:3189 Uncaught TypeError: Illegal invocation\" sometimes\n});\n\n",
"Also this is a cause too:\nIf you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().\n",
"Working sample code is here -\nvar formData = new FormData($(\"#formId\")[0]);\n \n$.ajax({\n url : \"/api/v1/save-data\",\n type : \"POST\",\n enctype: \"multipart/form-data\",\n dataType: \"json\",\n data: formData,\n success : function(data) {\n console.log(data);\n },\n cache: false,\n contentType: false,\n processData: false,\n error: function() {\n console.log(\"Error\");\n }\n});\n\n"
] |
[
149,
126,
22,
21,
6,
4,
2,
0,
0,
0
] |
[] |
[] |
[
"ajax",
"jquery",
"post"
] |
stackoverflow_0010324594_ajax_jquery_post.txt
|
Q:
Illegalargumentexception : java.net.URISyntaxException : Relative path in absolute path URI getting while reading json files recursively from ADLSS
Folder structure:
A -> B1->C1->.json
-> B2->C2->.json
There can be many folders under A and B which doesn't follow any pattern.
The above is the folder structure in ADLS while reading Json files recursively using spark we are getting below error.
java.net.URISyntaxException : Relative path in absolute path URI
def json_parquet(sourceFilePath):
df=(spark.read.format("json")
.option("multiline",True)
.option("recursiveFileLookup", "true")
.option("pathGlobFilter","*.json")
.load(sourceFilePath))
sourceFilepath='dbfs:/mnt/pp-working-1/A'
json_parquet(sourceFilepath)
It is working fine with S3 mnt but failing with ADLS mnt.
A:
You might need to modify the sourceFilePath variable to include the full URI of the file you want to load, including the scheme (e.g. adl:// or wasbs://) and the hostname or storage account name. For example:
sourceFilePath = 'adl://<storage_account_name>.dfs.core.windows.net/mnt/pp-working-1/A'
You can also try using the spark.read.json method to load the JSON files, which automatically detects the schema of the JSON files and loads them as a DataFrame. This method also takes an option called recursiveFileLookup, which allows you to specify whether to recursively search for files in subdirectories. For example:
def json_parquet(sourceFilePath):
df = spark.read.json(sourceFilePath, recursiveFileLookup=True)
return df
sourceFilePath = 'adl://<storage_account_name>.dfs.core.windows.net/mnt/pp-working-1/A'
df = json_parquet(sourceFilePath)
Alternatively, you can use the spark.read.format method and specify the json format, along with the recursiveFileLookup and pathGlobFilter options to recursively search for JSON files in the specified directory and load them as a DataFrame. For example:
def json_parquet(sourceFilePath):
df = (spark.read.format("json")
.option("recursiveFileLookup", "true")
.option("pathGlobFilter","*.json")
.load(sourceFilePath))
return df
sourceFilePath = 'adl://<storage_account_name>.dfs.core.windows.net/mnt/pp-working-1/A'
df = json_parquet(sourceFilePath)
I hope this helps.
|
Illegalargumentexception : java.net.URISyntaxException : Relative path in absolute path URI getting while reading json files recursively from ADLSS
|
Folder structure:
A -> B1->C1->.json
-> B2->C2->.json
There can be many folders under A and B which doesn't follow any pattern.
The above is the folder structure in ADLS while reading Json files recursively using spark we are getting below error.
java.net.URISyntaxException : Relative path in absolute path URI
def json_parquet(sourceFilePath):
df=(spark.read.format("json")
.option("multiline",True)
.option("recursiveFileLookup", "true")
.option("pathGlobFilter","*.json")
.load(sourceFilePath))
sourceFilepath='dbfs:/mnt/pp-working-1/A'
json_parquet(sourceFilepath)
It is working fine with S3 mnt but failing with ADLS mnt.
|
[
"You might need to modify the sourceFilePath variable to include the full URI of the file you want to load, including the scheme (e.g. adl:// or wasbs://) and the hostname or storage account name. For example:\nsourceFilePath = 'adl://<storage_account_name>.dfs.core.windows.net/mnt/pp-working-1/A'\n\nYou can also try using the spark.read.json method to load the JSON files, which automatically detects the schema of the JSON files and loads them as a DataFrame. This method also takes an option called recursiveFileLookup, which allows you to specify whether to recursively search for files in subdirectories. For example:\ndef json_parquet(sourceFilePath):\n df = spark.read.json(sourceFilePath, recursiveFileLookup=True)\n return df\n\nsourceFilePath = 'adl://<storage_account_name>.dfs.core.windows.net/mnt/pp-working-1/A'\ndf = json_parquet(sourceFilePath)\n\n\nAlternatively, you can use the spark.read.format method and specify the json format, along with the recursiveFileLookup and pathGlobFilter options to recursively search for JSON files in the specified directory and load them as a DataFrame. For example:\ndef json_parquet(sourceFilePath):\n df = (spark.read.format(\"json\")\n .option(\"recursiveFileLookup\", \"true\")\n .option(\"pathGlobFilter\",\"*.json\")\n .load(sourceFilePath))\n return df\n\nsourceFilePath = 'adl://<storage_account_name>.dfs.core.windows.net/mnt/pp-working-1/A'\ndf = json_parquet(sourceFilePath)\n\nI hope this helps.\n"
] |
[
0
] |
[] |
[] |
[
"azure_data_lake",
"databricks",
"pyspark",
"python"
] |
stackoverflow_0074664413_azure_data_lake_databricks_pyspark_python.txt
|
Q:
How can I efficiently randomly select items from a dictionary that meet my requirements?
So at the moment, I have a large dictionary of items. Might be a little confusing, but each of these keys have different values, and the values themselves correspond to another dictionary.
I need to make sure that my random selection from the first dict covers all possible values in the second dict. I'll provide a rudimentary example:
Dict_1 = {key1: (A, C), key2: (B, O, P), key3: (R, T, A)} # and so on
Dict_2 = {A: (1, 4, 7), B: (9, 2, 3), C: (1, 3)} # etc
I need a random selection of Dict_1 to give me a coverage of all numbers from 1 - 10 in Dict_2 values.
At the moment, I am selecting 6 random keys from Dict_1, taking all the numbers that those letters would correspond with, and comparing that set to a set of the numbers from 1 - 10. If the selection isn't a subset of 1 - 10, select 6 more random ones and try again, until I have 1 - 10.
Now, this works, but I know it's far from efficient. How can I improve this method?
I am using Python.
A:
One way to improve the efficiency of your method is to first create a set of all the numbers in Dict 2 and then iterate through Dict 1, adding the corresponding numbers from Dict 2 to a temporary set. Then, you can check if the temporary set is a subset of the set of all numbers from 1 to 10. If it is, you can return the selection of keys from Dict 1 that you used to create the temporary set. If it is not, you can continue iterating through Dict 1 and adding the corresponding numbers to the temporary set until it is a subset of the set of all numbers from 1 to 10.
Here is an example of how this might look in code:
import random
# Dict 1
dict1 = {
"key1": ("A", "C"),
"key2": ("B", "O", "P"),
"key3": ("R", "T", "A"),
...
}
# Dict 2
dict2 = {
"A": (1, 4, 7),
"B": (9, 2, 3),
"C": (1, 3),
...
}
# Set of all numbers from 1 to 10
numbers = set(range(1, 11))
# Function to get a selection of keys from Dict 1 that covers all numbers from 1 to 10 in Dict 2
def get_selection(dict1, dict2, numbers):
|
How can I efficiently randomly select items from a dictionary that meet my requirements?
|
So at the moment, I have a large dictionary of items. Might be a little confusing, but each of these keys have different values, and the values themselves correspond to another dictionary.
I need to make sure that my random selection from the first dict covers all possible values in the second dict. I'll provide a rudimentary example:
Dict_1 = {key1: (A, C), key2: (B, O, P), key3: (R, T, A)} # and so on
Dict_2 = {A: (1, 4, 7), B: (9, 2, 3), C: (1, 3)} # etc
I need a random selection of Dict_1 to give me a coverage of all numbers from 1 - 10 in Dict_2 values.
At the moment, I am selecting 6 random keys from Dict_1, taking all the numbers that those letters would correspond with, and comparing that set to a set of the numbers from 1 - 10. If the selection isn't a subset of 1 - 10, select 6 more random ones and try again, until I have 1 - 10.
Now, this works, but I know it's far from efficient. How can I improve this method?
I am using Python.
|
[
"One way to improve the efficiency of your method is to first create a set of all the numbers in Dict 2 and then iterate through Dict 1, adding the corresponding numbers from Dict 2 to a temporary set. Then, you can check if the temporary set is a subset of the set of all numbers from 1 to 10. If it is, you can return the selection of keys from Dict 1 that you used to create the temporary set. If it is not, you can continue iterating through Dict 1 and adding the corresponding numbers to the temporary set until it is a subset of the set of all numbers from 1 to 10.\nHere is an example of how this might look in code:\nimport random\n\n# Dict 1\ndict1 = {\n \"key1\": (\"A\", \"C\"),\n \"key2\": (\"B\", \"O\", \"P\"),\n \"key3\": (\"R\", \"T\", \"A\"),\n ...\n}\n\n# Dict 2\ndict2 = {\n \"A\": (1, 4, 7),\n \"B\": (9, 2, 3),\n \"C\": (1, 3),\n ...\n}\n\n# Set of all numbers from 1 to 10\nnumbers = set(range(1, 11))\n\n# Function to get a selection of keys from Dict 1 that covers all numbers from 1 to 10 in Dict 2\ndef get_selection(dict1, dict2, numbers):\n\n"
] |
[
0
] |
[] |
[] |
[
"dictionary",
"python",
"random",
"set",
"subset"
] |
stackoverflow_0074664141_dictionary_python_random_set_subset.txt
|
Q:
Android emulator not receiving push notifications
I'm using push notifications on google cloud, however for some reason i cant receive push notifications on the emulator.
The same application does receive notifications when i test it on a real device however.
Has anyone else encountered this or found solutions to it? the emulated device has net access and is the same android version as the real one so i cant think of any reason it shouldn't work.
A:
Which target have your emulator? For Google Services like GCM, use a "Google APIs" (any version) target to receive push notifications
A:
Edit your Android Virtual Machine (AVD) Target to use 'Google APIs' to enable GCM Push Notifications to be received by the emulator.
A:
Was your emulator receiving Firebase push notifications before? If yes, force reboot your emulator.
A:
Ensure you connected a google account on the emulator
A:
If you reach her, then you can try this answer.
Noting that no need to login in emulator with any google account.
A:
My solution: Allow notifications in settings. Some emulators are denied by default.
|
Android emulator not receiving push notifications
|
I'm using push notifications on google cloud, however for some reason i cant receive push notifications on the emulator.
The same application does receive notifications when i test it on a real device however.
Has anyone else encountered this or found solutions to it? the emulated device has net access and is the same android version as the real one so i cant think of any reason it shouldn't work.
|
[
"Which target have your emulator? For Google Services like GCM, use a \"Google APIs\" (any version) target to receive push notifications\n",
"Edit your Android Virtual Machine (AVD) Target to use 'Google APIs' to enable GCM Push Notifications to be received by the emulator.\n\n",
"Was your emulator receiving Firebase push notifications before? If yes, force reboot your emulator.\n",
"Ensure you connected a google account on the emulator\n",
"If you reach her, then you can try this answer.\nNoting that no need to login in emulator with any google account.\n",
"My solution: Allow notifications in settings. Some emulators are denied by default.\n\n"
] |
[
32,
23,
14,
13,
0,
0
] |
[] |
[] |
[
"android",
"google_cloud_messaging",
"push_notification"
] |
stackoverflow_0020521600_android_google_cloud_messaging_push_notification.txt
|
Q:
What is a subresource?
I am trying to understand what a subresource is. My understanding is that a SR is a part of a CRD, extending it for a scale field and a status field. Is that correct?
Why do we need an extra "thing" for this? Why do we not just put this in the CRD?
When do you want to use this?
A:
By convention, the Kubernetes API makes a distinction between the specification of the desired state of an object (a nested object field called "spec") and the status of the object at the current time (a nested object field called "status"). The specification is a complete description of the desired state, including configuration settings provided by the user, default values expanded by the system, and properties initialized or otherwise changed after creation by other ecosystem components (e.g., schedulers, auto-scalers), and is persisted in Etcd with the API object. The status summarizes the current state of the object in the system, and is usually persisted with the object by an automated processes but may be generated on the fly. At some cost and perhaps some temporary degradation in behavior, the status could be reconstructed by observation if it were lost.
The PUT and POST verbs on objects MUST ignore the "status" values, to avoid accidentally overwriting the status in read-modify-write scenarios. A /status subresource MUST be provided to enable system components to update statuses of resources they manage.
You can read more about the API convention in Kubernetes API Convention doc.
|
What is a subresource?
|
I am trying to understand what a subresource is. My understanding is that a SR is a part of a CRD, extending it for a scale field and a status field. Is that correct?
Why do we need an extra "thing" for this? Why do we not just put this in the CRD?
When do you want to use this?
|
[
"By convention, the Kubernetes API makes a distinction between the specification of the desired state of an object (a nested object field called \"spec\") and the status of the object at the current time (a nested object field called \"status\"). The specification is a complete description of the desired state, including configuration settings provided by the user, default values expanded by the system, and properties initialized or otherwise changed after creation by other ecosystem components (e.g., schedulers, auto-scalers), and is persisted in Etcd with the API object. The status summarizes the current state of the object in the system, and is usually persisted with the object by an automated processes but may be generated on the fly. At some cost and perhaps some temporary degradation in behavior, the status could be reconstructed by observation if it were lost.\nThe PUT and POST verbs on objects MUST ignore the \"status\" values, to avoid accidentally overwriting the status in read-modify-write scenarios. A /status subresource MUST be provided to enable system components to update statuses of resources they manage.\nYou can read more about the API convention in Kubernetes API Convention doc.\n"
] |
[
0
] |
[] |
[] |
[
"kubernetes"
] |
stackoverflow_0074357766_kubernetes.txt
|
Q:
Error Cannot Set Headers After They Are Set to Client
Im Creating and Employee Leave Managment System
Everything Thing Works Fine Until When I try To update The Leave Status By Admin and Th Logged in Acc or user is not roled as Admin
Ive a Middleware that checks the authentication of user and role of user
When An employeee tries to access this route it crashes the server logging Cannot Set Headers Already Set To client and then ive to restart the server and access the route again
her is my Auth code:
const employeeModels = require("../models/employeeModels");
exports.isAuthenticated = async (req, res, next) => {
try {
const { token } = req.cookies;
if (!token)
return res
.status(400)
.json({ success: false, error: "Please Login First" });
const decodedData = jwt.verify(token, "njuebuipoqdjbcibwjcnowdopq");
req.employee = await employeeModels.findById(decodedData.id);
next();
} catch (e) {
res.status(500).json({
success: false,
error: e.message,
});
next();
}
};
exports.AuthorizeRoles = (...role) => {
return (req, res, next) => {
if (!role.includes(req.employee.role)) {
res.status(400).json({
success: false,
error: "Only Admin is Allowed to Access this route",
});
}
next();
};
};
here is my leave controller
exports.createLeave = async (req, res, next) => {
try {
const { reason, noOfDays } = req.body;
const leave = await (
await LeaveModel.create({
reason,
noOfDays,
employee: req.employee._id,
})
).populate({
path: "employee",
});
res.status(200).json({
success: true,
message: "leave Has Been Submitted Successfully",
leave,
});
} catch (e) {
res.status(400).json({
success: false,
error: e.message,
});
next();
}
};
//get All Leaves For Admin
exports.getAllLeaves = async (req, res, next) => {
try {
const leaves = await LeaveModel.find().populate("employee");
if (leaves)
return res.status(200).json({
success: true,
leaves,
});
} catch (e) {
res.status(401).json({
success: false,
error: e.message,
});
next();
}
};
exports.updateLeaveStatus = async (req, res, next) => {
try {
const leave = await LeaveModel.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true,
});
if (leave)
return res.status(200).json({
success: true,
message: "Leave Status Updated Successfully",
leave,
});
} catch (e) {
return res.status(401).json({
success: false,
error: e.message,
});
next();
}
};
exports.deleteLeave = async (req, res) => {
try {
const leave = await LeaveModel.findByIdAndDelete(req.params.id);
if (leave)
return res.status(200).json({
success: true,
message: "Leave Deleted Successfully",
});
} catch (e) {
res.status(401).json({
success: false,
error: e.message,
});
next();
}
};
//controller for getting single leave detail
exports.getSingleLeave = async (req, res) => {
try {
//getting Leave From The Leave Model By Passing Id Fetched From The Req Url Param
const leave = await LeaveModel.findById(req.params.id).populate("employee");
if (leave)
return res.status(200).json({
success: true,
leave,
});
} catch (e) {
res.status(401).json({
success: false,
error: e.message,
});
next();
}
};
here are my leave routes
const {
createLeave,
getAllLeaves,
updateLeaveStatus,
deleteLeave,
getSingleLeave,
} = require("../controllers/leaveController");
const {
isAuthenticated,
AuthorizeRoles,
} = require("../middleware/Authentication");
const Leaverouter = express.Router();
Leaverouter.post("/createleave", isAuthenticated, createLeave)
.get(
"/admin/getallleaves",
isAuthenticated,
AuthorizeRoles("admin"),
getAllLeaves
)
.patch(
"/admin/updateleave/:id",
isAuthenticated,
AuthorizeRoles("admin"),
updateLeaveStatus
)
.delete(
"/admin/deleteleave/:id",
isAuthenticated,
AuthorizeRoles("admin"),
deleteLeave
)
.get(
"/admin/leavedetails/:id",
isAuthenticated,
AuthorizeRoles("admin"),
getSingleLeave
);
module.exports = Leaverouter;
A:
Do not call next() after sending a response (you have multiple places where you are doing this). You ONLY call next() when you want routing to continue so some other route handler can send a response. If you've already sent a response and then you call next() and some other route handler (or the default 404 route handler) gets called and tries to then send a second response, you will get this error.
The particular error you are getting is caused when your code is attempting to send more than one response to the same request.
|
Error Cannot Set Headers After They Are Set to Client
|
Im Creating and Employee Leave Managment System
Everything Thing Works Fine Until When I try To update The Leave Status By Admin and Th Logged in Acc or user is not roled as Admin
Ive a Middleware that checks the authentication of user and role of user
When An employeee tries to access this route it crashes the server logging Cannot Set Headers Already Set To client and then ive to restart the server and access the route again
her is my Auth code:
const employeeModels = require("../models/employeeModels");
exports.isAuthenticated = async (req, res, next) => {
try {
const { token } = req.cookies;
if (!token)
return res
.status(400)
.json({ success: false, error: "Please Login First" });
const decodedData = jwt.verify(token, "njuebuipoqdjbcibwjcnowdopq");
req.employee = await employeeModels.findById(decodedData.id);
next();
} catch (e) {
res.status(500).json({
success: false,
error: e.message,
});
next();
}
};
exports.AuthorizeRoles = (...role) => {
return (req, res, next) => {
if (!role.includes(req.employee.role)) {
res.status(400).json({
success: false,
error: "Only Admin is Allowed to Access this route",
});
}
next();
};
};
here is my leave controller
exports.createLeave = async (req, res, next) => {
try {
const { reason, noOfDays } = req.body;
const leave = await (
await LeaveModel.create({
reason,
noOfDays,
employee: req.employee._id,
})
).populate({
path: "employee",
});
res.status(200).json({
success: true,
message: "leave Has Been Submitted Successfully",
leave,
});
} catch (e) {
res.status(400).json({
success: false,
error: e.message,
});
next();
}
};
//get All Leaves For Admin
exports.getAllLeaves = async (req, res, next) => {
try {
const leaves = await LeaveModel.find().populate("employee");
if (leaves)
return res.status(200).json({
success: true,
leaves,
});
} catch (e) {
res.status(401).json({
success: false,
error: e.message,
});
next();
}
};
exports.updateLeaveStatus = async (req, res, next) => {
try {
const leave = await LeaveModel.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true,
});
if (leave)
return res.status(200).json({
success: true,
message: "Leave Status Updated Successfully",
leave,
});
} catch (e) {
return res.status(401).json({
success: false,
error: e.message,
});
next();
}
};
exports.deleteLeave = async (req, res) => {
try {
const leave = await LeaveModel.findByIdAndDelete(req.params.id);
if (leave)
return res.status(200).json({
success: true,
message: "Leave Deleted Successfully",
});
} catch (e) {
res.status(401).json({
success: false,
error: e.message,
});
next();
}
};
//controller for getting single leave detail
exports.getSingleLeave = async (req, res) => {
try {
//getting Leave From The Leave Model By Passing Id Fetched From The Req Url Param
const leave = await LeaveModel.findById(req.params.id).populate("employee");
if (leave)
return res.status(200).json({
success: true,
leave,
});
} catch (e) {
res.status(401).json({
success: false,
error: e.message,
});
next();
}
};
here are my leave routes
const {
createLeave,
getAllLeaves,
updateLeaveStatus,
deleteLeave,
getSingleLeave,
} = require("../controllers/leaveController");
const {
isAuthenticated,
AuthorizeRoles,
} = require("../middleware/Authentication");
const Leaverouter = express.Router();
Leaverouter.post("/createleave", isAuthenticated, createLeave)
.get(
"/admin/getallleaves",
isAuthenticated,
AuthorizeRoles("admin"),
getAllLeaves
)
.patch(
"/admin/updateleave/:id",
isAuthenticated,
AuthorizeRoles("admin"),
updateLeaveStatus
)
.delete(
"/admin/deleteleave/:id",
isAuthenticated,
AuthorizeRoles("admin"),
deleteLeave
)
.get(
"/admin/leavedetails/:id",
isAuthenticated,
AuthorizeRoles("admin"),
getSingleLeave
);
module.exports = Leaverouter;
|
[
"Do not call next() after sending a response (you have multiple places where you are doing this). You ONLY call next() when you want routing to continue so some other route handler can send a response. If you've already sent a response and then you call next() and some other route handler (or the default 404 route handler) gets called and tries to then send a second response, you will get this error.\nThe particular error you are getting is caused when your code is attempting to send more than one response to the same request.\n"
] |
[
0
] |
[] |
[] |
[
"custom_error_handling",
"express",
"javascript",
"node.js"
] |
stackoverflow_0074664393_custom_error_handling_express_javascript_node.js.txt
|
Q:
How can you use images in a list of objects and use them in react?
I imported pictures into my portfolio component and used each of them as a property in a list of objects. But when I try to send them over as a prop, the image disappears, and instead shows up as a missing picture. If I made an image tag with the pictures within the component I import them in, they appear just fine. But when I pass them as a prop, that's when they disappear. I import them in a Portfolio component, and try to send them as a prop in a Project component. Someone said earlier to not try to pass an object to a src attribute, and instead try to send the image url as a prop, but if I'm using a the map function to go through each element, I'm not sure how I can send each image URL.
Here is a few of the imports in the Portfolio component:
import video_player from "../../images/portfolioImages/video_player.png";
import weather_app from "../../images/portfolioImages/weather_app.png";
Here is a bit of the array of objects:
const projects = [
{
name: "Real-Time-Chatroom",
type: "Web Page",
description:
"Discord-like webpage that allows for several different users to send messages to a variety of different servers/chatrooms.",
picture: { chatroom },
},
{
name: "Weather App",
type: "Web Page",
description:
"Weather application that uses user's location to find the correct weather, and display that information on screen, with CSS styling that changes depending on the weather conditions of the user's area.",
picture: { weather_app },
},
];
And here is my Projects component code:
import React from "react";
import "./Project.css";
const Project = ({ name, type, description, image }) => {
return (
<div className="project">
<h1>{name}</h1>
<img src={image} alt={name}/>
</div>
);
};
export default Project;
A:
Here's an example of how you can update your code to correctly use the images in the projects array:
import React from "react";
import "./Project.css";
// Import the image files
import chatroom from "./chatroom.jpg";
import weather_app from "./weather_app.jpg";
const projects = [
{
name: "Real-Time-Chatroom",
type: "Web Page",
description:
"Discord-like webpage that allows for several different users to send messages to a variety of different servers/chatrooms.",
image: chatroom, // Use the imported image value as the image URL
},
{
name: "Weather App",
type: "Web Page",
description:
"Weather application that uses user's location to find the correct weather, and display that information on screen, with CSS styling that changes depending on the weather conditions of the user's area.",
image: weather_app, // Use the imported image value as the image URL
},
];
const Project = ({ name, type, description, image }) => {
return (
<div className="project">
<h1>{name}</h1>
<img src={image} alt={name} />
</div>
);
};
export default Project;
In this updated code, we import the image files using the import statement, and then we use the imported value as the src attribute for the img element in the Projectcomponent. This will ensure that the correct image is displayed for each project in theprojects` array.
Once you've updated your code to import and use the image files correctly, you can use the projects array to render a list of Project components in your application. Here's an example of how you can do this using the map() method:
import React from "react";
import Project from "./Project";
function App() {
return (
<div className="app">
{projects.map((project) => (
<Project
name={project.name}
type={project.type}
description={project.description}
image={project.image}
/>
))}
</div>
);
}
export default App;
In this example, we use the map() method to iterate over the projects array and render a Project component for each item in the array. We pass the name, type, description, and image properties from each object in the projects array to the Project as component
|
How can you use images in a list of objects and use them in react?
|
I imported pictures into my portfolio component and used each of them as a property in a list of objects. But when I try to send them over as a prop, the image disappears, and instead shows up as a missing picture. If I made an image tag with the pictures within the component I import them in, they appear just fine. But when I pass them as a prop, that's when they disappear. I import them in a Portfolio component, and try to send them as a prop in a Project component. Someone said earlier to not try to pass an object to a src attribute, and instead try to send the image url as a prop, but if I'm using a the map function to go through each element, I'm not sure how I can send each image URL.
Here is a few of the imports in the Portfolio component:
import video_player from "../../images/portfolioImages/video_player.png";
import weather_app from "../../images/portfolioImages/weather_app.png";
Here is a bit of the array of objects:
const projects = [
{
name: "Real-Time-Chatroom",
type: "Web Page",
description:
"Discord-like webpage that allows for several different users to send messages to a variety of different servers/chatrooms.",
picture: { chatroom },
},
{
name: "Weather App",
type: "Web Page",
description:
"Weather application that uses user's location to find the correct weather, and display that information on screen, with CSS styling that changes depending on the weather conditions of the user's area.",
picture: { weather_app },
},
];
And here is my Projects component code:
import React from "react";
import "./Project.css";
const Project = ({ name, type, description, image }) => {
return (
<div className="project">
<h1>{name}</h1>
<img src={image} alt={name}/>
</div>
);
};
export default Project;
|
[
"Here's an example of how you can update your code to correctly use the images in the projects array:\nimport React from \"react\";\nimport \"./Project.css\";\n\n// Import the image files\nimport chatroom from \"./chatroom.jpg\";\nimport weather_app from \"./weather_app.jpg\";\n\nconst projects = [\n {\n name: \"Real-Time-Chatroom\",\n type: \"Web Page\",\n description:\n \"Discord-like webpage that allows for several different users to send messages to a variety of different servers/chatrooms.\",\n image: chatroom, // Use the imported image value as the image URL\n },\n {\n name: \"Weather App\",\n type: \"Web Page\",\n description:\n \"Weather application that uses user's location to find the correct weather, and display that information on screen, with CSS styling that changes depending on the weather conditions of the user's area.\",\n image: weather_app, // Use the imported image value as the image URL\n },\n];\n\nconst Project = ({ name, type, description, image }) => {\n return (\n <div className=\"project\">\n <h1>{name}</h1>\n <img src={image} alt={name} />\n </div>\n );\n};\n\nexport default Project;\n\nIn this updated code, we import the image files using the import statement, and then we use the imported value as the src attribute for the img element in the Projectcomponent. This will ensure that the correct image is displayed for each project in theprojects` array.\nOnce you've updated your code to import and use the image files correctly, you can use the projects array to render a list of Project components in your application. Here's an example of how you can do this using the map() method:\nimport React from \"react\";\nimport Project from \"./Project\";\n\nfunction App() {\n return (\n <div className=\"app\">\n {projects.map((project) => (\n <Project\n name={project.name}\n type={project.type}\n description={project.description}\n image={project.image}\n />\n ))}\n </div>\n );\n}\n\nexport default App;\n\nIn this example, we use the map() method to iterate over the projects array and render a Project component for each item in the array. We pass the name, type, description, and image properties from each object in the projects array to the Project as component\n"
] |
[
1
] |
[] |
[] |
[
"reactjs"
] |
stackoverflow_0074664505_reactjs.txt
|
Q:
How to solve "ModuleNotFoundError: No module named 'tensorflow.tsl'"?
I installed python but didn't work. Then all of the following but when, I was supposed to import the following it didn't work.
!pip install -U pip
!pip install tensorflow
from tensorflow import keras
from tensorflow.keras import layers
A:
I think you can try to run pip install tensorflow in command
A:
If you're having trouble importing a package in Python, it's possible that you haven't installed it properly or that it's not installed at all. To check if tensorflow is installed, you can try running pip freeze in your terminal. This will print out a list of all the packages that are currently installed in your environment. If tensorflow is not in that list, then you need to install it.
If you're not sure how to install a package in Python, you can use the pip command. For example, to install tensorflow, you would run pip install tensorflow in your terminal. Once the installation is complete, you should be able to import tensorflow in your Python code without any issues
|
How to solve "ModuleNotFoundError: No module named 'tensorflow.tsl'"?
|
I installed python but didn't work. Then all of the following but when, I was supposed to import the following it didn't work.
!pip install -U pip
!pip install tensorflow
from tensorflow import keras
from tensorflow.keras import layers
|
[
"I think you can try to run pip install tensorflow in command\n",
"If you're having trouble importing a package in Python, it's possible that you haven't installed it properly or that it's not installed at all. To check if tensorflow is installed, you can try running pip freeze in your terminal. This will print out a list of all the packages that are currently installed in your environment. If tensorflow is not in that list, then you need to install it.\nIf you're not sure how to install a package in Python, you can use the pip command. For example, to install tensorflow, you would run pip install tensorflow in your terminal. Once the installation is complete, you should be able to import tensorflow in your Python code without any issues\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"python_3.x",
"tensorflow"
] |
stackoverflow_0074664203_python_python_3.x_tensorflow.txt
|
Q:
Whatever I try cors just doesn't seem to work in production
Hi im using the cors npm library to connect a backend with a front-end ive built backends before with fastApi middleware and that worked perfectly fine but with expressjs it doesn't seem to work in production at all only in development. I keep getting this error
Access to XMLHttpRequest at 'https://invoiceappnodejs.herokuapp.com/send_mail' from origin
'https://www.omillerwieldinginvoice.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
here is the code
const cors = require('cors');
require('dotenv').config()
const express = require('express');
const nodemailer = require('nodemailer');
const app = express();
app.use(express.json());
app.options('/send_mail', cors())
app.use(cors({
allowedHeaders:["*"],
exposedHeaders: ['*']
origins:'https://www.omillerwieldinginvoice.com/',
headers:'*',
preflightContinue: false,
methods:"GET, POST, PUT, PATCH, POST, DELETE"
}))
|
Whatever I try cors just doesn't seem to work in production
|
Hi im using the cors npm library to connect a backend with a front-end ive built backends before with fastApi middleware and that worked perfectly fine but with expressjs it doesn't seem to work in production at all only in development. I keep getting this error
Access to XMLHttpRequest at 'https://invoiceappnodejs.herokuapp.com/send_mail' from origin
'https://www.omillerwieldinginvoice.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
here is the code
const cors = require('cors');
require('dotenv').config()
const express = require('express');
const nodemailer = require('nodemailer');
const app = express();
app.use(express.json());
app.options('/send_mail', cors())
app.use(cors({
allowedHeaders:["*"],
exposedHeaders: ['*']
origins:'https://www.omillerwieldinginvoice.com/',
headers:'*',
preflightContinue: false,
methods:"GET, POST, PUT, PATCH, POST, DELETE"
}))
|
[] |
[] |
[
"Since you explicitly put https://www.omillerwieldinginvoice.com/ as origin, the request for https://invoiceappnodejs.herokuapp.com/send_mail wouldn't work. So you need to add the correct origin to your origins.\nAlso don't forget to initalize CORS before your routes. So order should be:\napp.use(cors({});\napp.use(express.json());\napp.options('/send_mail', cors());\n\n",
"Different browser request differently likes: Mozilla: http://www.example.com and chrome: http://example.com. you can use like this:\ncors({\n origin: [\"http://example.com\",\"http://www.example.com\"],\n optionsSuccessStatus: 200\n})\n\n"
] |
[
-1,
-1
] |
[
"cors",
"node.js"
] |
stackoverflow_0071929395_cors_node.js.txt
|
Q:
how do I add array in object property in another array as parameter in function?
i tried to make a function for averaging all the array in an object of another array, but however i tried i can't call the parameter for the function i make
let students = [randy, riziq, rama];
let randy = {
name: 'Randy',
score: [75, 80, 90]
};
let riziq = {
name: 'Riziq',
score: [50, 90, 90]
};
let rama = {
name: 'Rama',
score: [80, 75, 90]
};
function average(/*students*/) {
let avgScore = /*students's score avg*/
return /*students's name + "" + student's average*/
};
console.log(average(/*students*/));
is there any way to call that?
i tried to make a for loop to each of the props inside the students array but still i can't call that.
i tried to sum all the student's score with array.reduce() of the students array and divide them with array.length
A:
Put let students = [randy, riziq, rama]; after the declaration of variables.
let randy = {
name: 'Randy',
score: [75, 80, 90]
};
let riziq = {
name: 'Riziq',
score: [50, 90, 90]
};
let rama = {
name: 'Rama',
score: [80, 75, 90]
};
let students = [randy, riziq, rama];
function average(students) {
return students.map(({name, score}) => {
const total = score.reduce((a, b) => a + b,0);
return `${name} ${total/score.length}`;
});
}
console.log(average(students));
Learn more about .map() and .reduce()
A:
let randy = {
name: 'Randy',
score: [75, 80, 90]
};
let riziq = {
name: 'Riziq',
score: [50, 90, 90]
};
let rama = {
name: 'Rama',
score: [80, 75, 90]
};
let students = [randy, riziq, rama];
function average(students) {
var data = { "averages" : {}};
var i;
for (i = 0; i < students.length; ++i) {
var total = 0;
for (var ti = 0; ti < students[i].score.length; ti++) {
total += students[i].score[ti] << 0;
}
var avg = total/students[i].score.length;
data.averages[i] = {
"name":students[i].name,
"average":avg.toFixed(2),
};
}
return data;
};
console.log(average(students));
|
how do I add array in object property in another array as parameter in function?
|
i tried to make a function for averaging all the array in an object of another array, but however i tried i can't call the parameter for the function i make
let students = [randy, riziq, rama];
let randy = {
name: 'Randy',
score: [75, 80, 90]
};
let riziq = {
name: 'Riziq',
score: [50, 90, 90]
};
let rama = {
name: 'Rama',
score: [80, 75, 90]
};
function average(/*students*/) {
let avgScore = /*students's score avg*/
return /*students's name + "" + student's average*/
};
console.log(average(/*students*/));
is there any way to call that?
i tried to make a for loop to each of the props inside the students array but still i can't call that.
i tried to sum all the student's score with array.reduce() of the students array and divide them with array.length
|
[
"Put let students = [randy, riziq, rama]; after the declaration of variables.\n\n\nlet randy = {\n name: 'Randy',\n score: [75, 80, 90]\n};\nlet riziq = {\n name: 'Riziq',\n score: [50, 90, 90]\n};\nlet rama = {\n name: 'Rama',\n score: [80, 75, 90]\n};\n\nlet students = [randy, riziq, rama];\n\nfunction average(students) {\n return students.map(({name, score}) => {\n const total = score.reduce((a, b) => a + b,0);\n return `${name} ${total/score.length}`;\n});\n}\n\nconsole.log(average(students));\n\n\n\nLearn more about .map() and .reduce()\n",
"\n\nlet randy = {\n name: 'Randy',\n score: [75, 80, 90]\n };\nlet riziq = {\n name: 'Riziq',\n score: [50, 90, 90]\n };\nlet rama = {\n name: 'Rama',\n score: [80, 75, 90]\n };\n let students = [randy, riziq, rama];\n \nfunction average(students) {\n var data = { \"averages\" : {}};\n var i;\n for (i = 0; i < students.length; ++i) {\n var total = 0;\n for (var ti = 0; ti < students[i].score.length; ti++) {\n total += students[i].score[ti] << 0;\n }\n var avg = total/students[i].score.length;\n \n data.averages[i] = { \n \"name\":students[i].name, \n \"average\":avg.toFixed(2), \n }; \n }\n \n return data;\n};\n \nconsole.log(average(students));\n\n\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"arrays",
"function",
"javascript",
"object"
] |
stackoverflow_0074664399_arrays_function_javascript_object.txt
|
Q:
GNU Prolog (glpc): error trying to execute as: No such file or directory
I'm trying to use the GNU Prolog Compiler to build an executable from my Prolog program like so:
$ gplc solution.prolog -o prog
and it's failing with a really cryptic error:
error trying to execute as: No such file or directory
I can't figure out what it's trying to tell me is missing. Does anyone know?
I'm using Fedora Silverblue 37, and glpc is running inside of a 'toolbox' that is also Fedora 37.
A:
The issue appears to have been that I didn't have a C compiler installed. I installed the gcc package, and got a different error:
gcc: fatal error: cannot read spec file ‘/usr/lib/rpm/redhat/redhat-hardened-ld’: No such file or directory
Apparently to get that file, I needed to install the redhat-rpm-config package. I found that package name from this relevant comment on the RedHat bugzilla.
Compilation succeeds now!
|
GNU Prolog (glpc): error trying to execute as: No such file or directory
|
I'm trying to use the GNU Prolog Compiler to build an executable from my Prolog program like so:
$ gplc solution.prolog -o prog
and it's failing with a really cryptic error:
error trying to execute as: No such file or directory
I can't figure out what it's trying to tell me is missing. Does anyone know?
I'm using Fedora Silverblue 37, and glpc is running inside of a 'toolbox' that is also Fedora 37.
|
[
"The issue appears to have been that I didn't have a C compiler installed. I installed the gcc package, and got a different error:\ngcc: fatal error: cannot read spec file ‘/usr/lib/rpm/redhat/redhat-hardened-ld’: No such file or directory\n\nApparently to get that file, I needed to install the redhat-rpm-config package. I found that package name from this relevant comment on the RedHat bugzilla.\nCompilation succeeds now!\n"
] |
[
1
] |
[] |
[] |
[
"fedora",
"gnu_prolog",
"linux"
] |
stackoverflow_0074664555_fedora_gnu_prolog_linux.txt
|
Q:
I can't upload my Unity game to Google Play
I can't upload my Unity game to Google Play.
Android App Bundle is not signed error.
I was trying to upload my game to google play console but i am getting application package not signed error. I searched on the internet but couldn't find a solution
A:
Watch this video at 2:30 to create the keystore files. Do not delete the files or you won't be able to updated the app on play store.
|
I can't upload my Unity game to Google Play
|
I can't upload my Unity game to Google Play.
Android App Bundle is not signed error.
I was trying to upload my game to google play console but i am getting application package not signed error. I searched on the internet but couldn't find a solution
|
[
"Watch this video at 2:30 to create the keystore files. Do not delete the files or you won't be able to updated the app on play store.\n"
] |
[
0
] |
[] |
[] |
[
"google_play_console",
"unity3d"
] |
stackoverflow_0074655733_google_play_console_unity3d.txt
|
Q:
how to assume roles twice (or multiple times) in the script
I am trying to assume a role twice in the script, I assume the role first like this
import boto3 session = boto3.Session(profile_name="learnaws-test")
sts = session.client("sts")
response = sts.assume_role(
RoleArn="arn:aws:iam::xxx:role/s3-readonly-access",
RoleSessionName="learnaws-test-session"
)
new_session = Session(aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'])
but after I have done this, I understand I can use this new_session to access s3 buckets or whatever resourse and stuff but I need to assume another role from this role, how do I assume another role?
logically, I think from this "new_session" we have to do something to assume another role, but what is it?
A:
Call AssumeRole
When calling AssumeRole(), a new set of credentials is returned. You can then use these credentials to create new clients, including another Security Token Service (STS) client that can be used to call AssumeRole() again.
Here is an example:
import boto3
# Create STS client using default credentials
sts_client = boto3.client('sts')
# Assume Role 1
response1 = sts_client.assume_role(RoleArn='arn:aws:iam::111111111111:role/assume1', RoleSessionName='One')
credentials1 = response1['Credentials']
role1_session = boto3.Session(
aws_access_key_id=credentials1['AccessKeyId'],
aws_secret_access_key=credentials1['SecretAccessKey'],
aws_session_token=credentials1['SessionToken'])
sts_client1 = role1_session.client('sts')
# Assume Role 2
response2 = sts_client1.assume_role(RoleArn='arn:aws:iam::111111111111:role/assume2', RoleSessionName='Two')
credentials2 = response2['Credentials']
role2_session = boto3.Session(
aws_access_key_id=credentials2['AccessKeyId'],
aws_secret_access_key=credentials2['SecretAccessKey'],
aws_session_token=credentials2['SessionToken'])
# Use Role 2
s3_client2 = role2_session.client('s3')
response = s3_client2.list_buckets()
print(response)
Use profiles
However, there is an easier way to do this using profiles. You can configure the ~/.aws/config file to assume roles automatically:
[default]
region = ap-southeast-2
[profile role1]
role_arn=arn:aws:iam::111111111111:role/assume1
source_profile=default
[profile role2]
role_arn=arn:aws:iam::111111111111:role/assume2
source_profile=role1
This is telling boto3:
When assuming role1, use the default credentials
When assuming role2, use credentials from role1
Assuming both roles is then as simple as:
import boto3
session = boto3.Session(profile_name='role2')
s3_client = session.client('s3')
response = s3_client.list_buckets()
print(response)
This also works with the AWS CLI:
aws s3 ls --profile role2
For more information, see: Credentials — Boto3 documentation
|
how to assume roles twice (or multiple times) in the script
|
I am trying to assume a role twice in the script, I assume the role first like this
import boto3 session = boto3.Session(profile_name="learnaws-test")
sts = session.client("sts")
response = sts.assume_role(
RoleArn="arn:aws:iam::xxx:role/s3-readonly-access",
RoleSessionName="learnaws-test-session"
)
new_session = Session(aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'])
but after I have done this, I understand I can use this new_session to access s3 buckets or whatever resourse and stuff but I need to assume another role from this role, how do I assume another role?
logically, I think from this "new_session" we have to do something to assume another role, but what is it?
|
[
"Call AssumeRole\nWhen calling AssumeRole(), a new set of credentials is returned. You can then use these credentials to create new clients, including another Security Token Service (STS) client that can be used to call AssumeRole() again.\nHere is an example:\nimport boto3\n\n# Create STS client using default credentials\n\nsts_client = boto3.client('sts')\n\n# Assume Role 1\n\nresponse1 = sts_client.assume_role(RoleArn='arn:aws:iam::111111111111:role/assume1', RoleSessionName='One')\n\ncredentials1 = response1['Credentials']\n\nrole1_session = boto3.Session(\n aws_access_key_id=credentials1['AccessKeyId'],\n aws_secret_access_key=credentials1['SecretAccessKey'],\n aws_session_token=credentials1['SessionToken'])\n\nsts_client1 = role1_session.client('sts')\n\n# Assume Role 2\n\nresponse2 = sts_client1.assume_role(RoleArn='arn:aws:iam::111111111111:role/assume2', RoleSessionName='Two')\n\ncredentials2 = response2['Credentials']\n\nrole2_session = boto3.Session(\n aws_access_key_id=credentials2['AccessKeyId'],\n aws_secret_access_key=credentials2['SecretAccessKey'],\n aws_session_token=credentials2['SessionToken'])\n\n# Use Role 2\n\ns3_client2 = role2_session.client('s3')\n\nresponse = s3_client2.list_buckets()\n\nprint(response)\n\nUse profiles\nHowever, there is an easier way to do this using profiles. You can configure the ~/.aws/config file to assume roles automatically:\n[default]\nregion = ap-southeast-2\n\n[profile role1]\nrole_arn=arn:aws:iam::111111111111:role/assume1\nsource_profile=default\n\n[profile role2]\nrole_arn=arn:aws:iam::111111111111:role/assume2\nsource_profile=role1\n\nThis is telling boto3:\n\nWhen assuming role1, use the default credentials\nWhen assuming role2, use credentials from role1\n\nAssuming both roles is then as simple as:\nimport boto3\n\nsession = boto3.Session(profile_name='role2')\ns3_client = session.client('s3')\n\nresponse = s3_client.list_buckets()\n\nprint(response)\n\nThis also works with the AWS CLI:\naws s3 ls --profile role2\n\nFor more information, see: Credentials — Boto3 documentation\n"
] |
[
0
] |
[] |
[] |
[
"amazon_web_services",
"assume_role",
"boto3",
"python"
] |
stackoverflow_0074657438_amazon_web_services_assume_role_boto3_python.txt
|
Q:
If only one element in a hashset, how can I get it out?
I have a set like below:
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
How can I get the 1 out? I can do it by for(integer i : set). My specified problem is "Given an array of integers, every element appears twice except for one. Find that single one."
I want to use add elements into the set if the set doesn't contain it and remove existing elements during the loop. And the last remaining element is the answer. I don't know how to return it.
public static int singleNumber(int[] A) {
HashSet<Integer> set = new HashSet<>();
for (int a : A) {
if (!set.contains(a)) {
set.add(a);
} else {
set.remove(a);
}
}
/**
* for(Integer i : set) { return i; }
*return A[0]; //need one useless return
/**
* while(set.iterator().hasNext()) { return set.iterator().next(); }
* return A[0]; //need one useless return
*/
return set.toArray(new Integer[1])[0];
}
A:
set.iterator().next()
Do so only if you are sure there is an element in the set. Otherwise next() will throw an exception.
A:
Simply try using HashSet#toArray() method
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
if (set.size() == 1) { // make sure that there is only one element in set
Integer value = set.toArray(new Integer[1])[0];
System.out.println(value);//output 1
}
A:
The typical solution includes a check if the current iterator position has any left element through setIterator.hasNext() which returns true only if there is an extra element unchecked. For example
HashSet set = new HashSet();
Iterator setIterator = set.iterator();
while(setIterator.hasNext()){
String item = setIterator().next();
...
}
A:
If you know what the element is and you just want to empty the set, you can use remove(Object o) (or clear() for that matter). If you don't know what it is and want to see it without removing it, use an iterator. If you don't know what it is and want to remove it, you should use an iterator using the iterator's remove() method. This is the safe (and recommended) way to remove elements from a collection. Since Set is unordered, it's difficult to specify what you want to remove. And for any collection, you would usually only know what you are removing if you iterate through the collection.
A:
Solution Using Java Stream
If you want to use Java Stream any of the following options will give you the desired result:
Option 1
Just return the only element from the stream:
set.stream().findFirst().get()
Option 2
Or use Stream.reduce; since adding the only element to zero has no effect
(a little too much IMHO :))
set.stream().reduce(0, Integer::sum)
You can test it here.
|
If only one element in a hashset, how can I get it out?
|
I have a set like below:
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
How can I get the 1 out? I can do it by for(integer i : set). My specified problem is "Given an array of integers, every element appears twice except for one. Find that single one."
I want to use add elements into the set if the set doesn't contain it and remove existing elements during the loop. And the last remaining element is the answer. I don't know how to return it.
public static int singleNumber(int[] A) {
HashSet<Integer> set = new HashSet<>();
for (int a : A) {
if (!set.contains(a)) {
set.add(a);
} else {
set.remove(a);
}
}
/**
* for(Integer i : set) { return i; }
*return A[0]; //need one useless return
/**
* while(set.iterator().hasNext()) { return set.iterator().next(); }
* return A[0]; //need one useless return
*/
return set.toArray(new Integer[1])[0];
}
|
[
"set.iterator().next()\nDo so only if you are sure there is an element in the set. Otherwise next() will throw an exception.\n",
"Simply try using HashSet#toArray() method\nHashSet<Integer> set = new HashSet<Integer>();\nset.add(1);\n\nif (set.size() == 1) { // make sure that there is only one element in set\n Integer value = set.toArray(new Integer[1])[0];\n System.out.println(value);//output 1\n}\n\n",
"The typical solution includes a check if the current iterator position has any left element through setIterator.hasNext() which returns true only if there is an extra element unchecked. For example\nHashSet set = new HashSet(); \nIterator setIterator = set.iterator();\nwhile(setIterator.hasNext()){\n String item = setIterator().next();\n ...\n}\n\n",
"If you know what the element is and you just want to empty the set, you can use remove(Object o) (or clear() for that matter). If you don't know what it is and want to see it without removing it, use an iterator. If you don't know what it is and want to remove it, you should use an iterator using the iterator's remove() method. This is the safe (and recommended) way to remove elements from a collection. Since Set is unordered, it's difficult to specify what you want to remove. And for any collection, you would usually only know what you are removing if you iterate through the collection.\n",
"Solution Using Java Stream\nIf you want to use Java Stream any of the following options will give you the desired result:\nOption 1\nJust return the only element from the stream:\nset.stream().findFirst().get()\nOption 2\nOr use Stream.reduce; since adding the only element to zero has no effect\n(a little too much IMHO :))\nset.stream().reduce(0, Integer::sum)\nYou can test it here.\n"
] |
[
13,
3,
0,
0,
0
] |
[] |
[] |
[
"hashset",
"java",
"set"
] |
stackoverflow_0023595749_hashset_java_set.txt
|
Q:
Append dictionary in json using Python
I am doing my first Python program and its Hangman game. I managed to make it work but as a part of the task I need to write "best results -hall of fame" table as json file. Each entry in the table should consist of name of the person and the result they achieved (number of tries before guessing a word). My idea is to use dictionary for that purpose and to append the result of each game to that same dictionary.
My code goes like this:
with open("hall.json","a") as django:
json.dump(hall_of_fame, django)
hall_of_fame is a dictionary where after playing a game the result is saved in the form of {john:5}
The problem I have is that after playing several games my .json file looks like this:
{john:5}{ana:7}{mary:3}{jim:1}{willie:6}
instead I want to get .json file to look like this:
{john:5,ana:7,mary:3,jim:1,willie:6}
What am I doing wrong? Can someone please take a look?
A:
you should read your old json content. then append new item to it. an finally write it to your json file again. use code below:
with open ("hall.json") as f:
dct=json.load(f)
#add new item to dct
dct.update(hall_of_fame)
#write new dct to json file
with open("hall.json","w") as f:
json.dump(dct,f)
have fun :)
A:
You're overwriting the file every time you write to it. Instead, you should read the existing data from the file, append the new data to the dictionary, and then write the whole dictionary back to the file.
Here's an example of how you can do that:
import json
# Read the existing data from the file
with open("hall.json", "r") as django:
hall_of_fame = json.load(django)
# Append the new data to the dictionary
hall_of_fame["john"] = 5
hall_of_fame["ana"] = 7
hall_of_fame["mary"] = 3
hall_of_fame["jim"] = 1
hall_of_fame["willie"] = 6
# Write the updated dictionary back to the file
with open("hall.json", "w") as django:
json.dump(hall_of_fame, django)
Alternatively, you can use the json.dump() method's ensure_ascii and indent parameters to make the resulting JSON file more readable. Here's an example:
import json
# Read the existing data from the file
with open("hall.json", "r") as django:
hall_of_fame = json.load(django)
# Append the new data to the dictionary
hall_of_fame["john"] = 5
hall_of_fame["ana"] = 7
hall_of_fame["mary"] = 3
hall_of_fame["jim"] = 1
hall_of_fame["willie"] = 6
# Write the updated dictionary back to the file
with open("hall.json", "w") as django:
json.dump(hall_of_fame, django, ensure_ascii=False, indent=4)
|
Append dictionary in json using Python
|
I am doing my first Python program and its Hangman game. I managed to make it work but as a part of the task I need to write "best results -hall of fame" table as json file. Each entry in the table should consist of name of the person and the result they achieved (number of tries before guessing a word). My idea is to use dictionary for that purpose and to append the result of each game to that same dictionary.
My code goes like this:
with open("hall.json","a") as django:
json.dump(hall_of_fame, django)
hall_of_fame is a dictionary where after playing a game the result is saved in the form of {john:5}
The problem I have is that after playing several games my .json file looks like this:
{john:5}{ana:7}{mary:3}{jim:1}{willie:6}
instead I want to get .json file to look like this:
{john:5,ana:7,mary:3,jim:1,willie:6}
What am I doing wrong? Can someone please take a look?
|
[
"you should read your old json content. then append new item to it. an finally write it to your json file again. use code below:\nwith open (\"hall.json\") as f:\n dct=json.load(f)\n\n#add new item to dct\ndct.update(hall_of_fame)\n\n#write new dct to json file\nwith open(\"hall.json\",\"w\") as f:\n json.dump(dct,f)\n\nhave fun :)\n",
"You're overwriting the file every time you write to it. Instead, you should read the existing data from the file, append the new data to the dictionary, and then write the whole dictionary back to the file.\nHere's an example of how you can do that:\nimport json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django)\n\nAlternatively, you can use the json.dump() method's ensure_ascii and indent parameters to make the resulting JSON file more readable. Here's an example:\nimport json\n\n# Read the existing data from the file\nwith open(\"hall.json\", \"r\") as django:\n hall_of_fame = json.load(django)\n\n# Append the new data to the dictionary\nhall_of_fame[\"john\"] = 5\nhall_of_fame[\"ana\"] = 7\nhall_of_fame[\"mary\"] = 3\nhall_of_fame[\"jim\"] = 1\nhall_of_fame[\"willie\"] = 6\n\n# Write the updated dictionary back to the file\nwith open(\"hall.json\", \"w\") as django:\n json.dump(hall_of_fame, django, ensure_ascii=False, indent=4)\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"append",
"dictionary",
"json",
"python"
] |
stackoverflow_0074663995_append_dictionary_json_python.txt
|
Q:
How do I run my main function in parallel with a multiprocessing.Process without it freezing? (sorry for the sloppy code, I'm new and self taught)
My main function is an app that I want to use for macros, the macros themselves all work as intended, and the function is technically able to work. The issue arises when you start the function, as you can't interact with the GUI because it is frozen, it unfreezes when the function ends and then the GUI becomes usable again. Again, I'm sorry about the sloppy and changing code, like I said, I'm self taught and a lot is borrowed and mangled together.
I tried using different start methods like spawn and fork, I tried setting up different ways for the function to end so it wouldn't wait, and at one point the GUI worked but the second I fixed the other bug this one came. I don't have an old save sadly as it was overwritten. There are no errors and I understand that there probably is a solution already out there but I have yet to find it. The code is long 400-ish lines so be warned.
from ast import Call
from cgitb import text
from concurrent.futures import process, thread
from itertools import starmap
from logging import PlaceHolder, error
from re import L
import tkinter
import tkinter.messagebox
from turtle import width
import customtkinter
import threading
import multiprocessing
import time
import pyautogui
import sys
import keyboard
label_text="Select counter as well as type below:"
macro_select=0
rand_offset_min=0 #needed to set the variables in case of no entry
rand_offset_max=3
radio_select=0
label_="Please select a macro type:"
dead=False
base_start=";"
customtkinter.set_appearance_mode("System") # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("blue") # Themes: "blue" (standard), "green", "dark-blue"
n_process = []
s_process = []
c_process = []
multiprocessing.set_start_method("spawn")
def netherwart(metric_raw):
y=0
time.sleep(5)
print(metric_raw)
PlaceHolder_0=int(metric_raw)
while y <= PlaceHolder_0:
print (PlaceHolder_0)
print("running")
print(y)
pyautogui.keyDown(' ')
pyautogui.keyDown('a')
time.sleep(28)
pyautogui.keyUp('a')
pyautogui.keyDown('d')
time.sleep(28)
pyautogui.keyUp('d')
y=y+1
print("flag0")
def sugarcane(metric_raw):
y=0
time.sleep(5)
PlaceHolder_0=int(metric_raw)
while y <= PlaceHolder_0:
print (PlaceHolder_0)
print("running.")
pyautogui.keyDown(' ')
pyautogui.keyDown('d')
time.sleep(.25)
pyautogui.keyDown('w')
time.sleep(14.5)
pyautogui.keyUp('d')
time.sleep(1)
pyautogui.keyUp('w')
pyautogui.keyDown('s')
time.sleep(17.5)
pyautogui.keyUp('s')
pyautogui.keyDown('a')
pyautogui.keyDown('w')
time.sleep(.25)
pyautogui.keyUp('w')
time.sleep(.25)
pyautogui.keyUp('a')
y=y+1
def cobblestone(metric_raw):
y=0
time.sleep(5)
PlaceHolder_0=int(metric_raw)
while y <= PlaceHolder_0:
print (PlaceHolder_0)
print("running..")
pyautogui.keyDown(' ')
pyautogui.keyDown('w')
time.sleep(30)
y=y+1
class App(customtkinter.CTk):
WIDTH = 780 #set the width of the main gui
HEIGHT = 520 #set the height of the main gui
def __init__(self):
multiprocessing.freeze_support()
super().__init__()
self.title("EzFarmerGui") #Naming the program
self.geometry(f"{App.WIDTH} x {App.HEIGHT}")#Setting the background size
self.protocol("WM_DELETE_WINDOW", self.on_closing)
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)
self.frame_left = customtkinter.CTkFrame(master=self, width=180, corner_radius=0)
self.frame_left.grid(row=0, column=0,rowspan=4, sticky="nswe")
self.frame_right = customtkinter.CTkFrame(master=self)
self.frame_right.grid(row=0, column=1,rowspan=1, sticky="nswe", padx=20, pady=10)
#left frame
self.frame_left.grid_rowconfigure(0, minsize=10) # empty row with minsize as spacing
self.frame_left.grid_rowconfigure(5, weight=1) # empty row as spacing
self.frame_left.grid_rowconfigure(8, minsize=20) # empty row with minsize as spacing
self.frame_left.grid_rowconfigure(11, minsize=10) # empty row with minsize as spacing | the first number is the actual row or column, row is the y and column is the x
self.label_1 = customtkinter.CTkLabel(master=self.frame_left,text="Farming Options:",text_font=("Roboto Medium", -16)) # font name and size in px
self.label_1.grid(row=1, column=0, pady=10, padx=10)
self.button_1 = customtkinter.CTkButton(master=self.frame_left,text="Netherwart",text_font=("Roboto Medium", -12),command=self.netherwart_event)
self.button_1.grid(row=2, column=0, pady=10, padx=20)
self.button_2 = customtkinter.CTkButton(master=self.frame_left,text="Sugarcane",text_font=("Roboto Medium", -12),command=self.sugarcane_event)
self.button_2.grid(row=3, column=0, pady=10,padx=20)
self.button_3 = customtkinter.CTkButton(master=self.frame_left,text="Cobblestone",text_font=("Roboto Medium", -12),command=self.cobblestone_event)
self.button_3.grid(row=4, column=0, pady=10,padx=20)
self.button_4 = customtkinter.CTkButton(master=self.frame_left,text="Settings",text_font=("Roboto Medium", -12),command=self.settings_event)
self.button_4.grid(row=6, column=0, pady=10,padx=20)
#Right frame
self.frame_right.rowconfigure((0, 1, 2), minsize=0,weight=2)
self.frame_right.rowconfigure(7, weight=10)
self.frame_right.rowconfigure(3,weight=1)
self.frame_right.columnconfigure((0, 1), weight=1)
self.frame_right.columnconfigure(2, weight=0)
self.frame_info = customtkinter.CTkFrame(master=self.frame_right)
self.frame_info.grid(row=0, column=0, columnspan=2, rowspan=2, pady=10, padx=20, sticky="nsew")
self.frame_options = customtkinter.CTkFrame(master=self.frame_right)
self.frame_options.grid(row=2, column=0, columnspan=2,rowspan=1,pady=10,padx=20,sticky="nsew")
self.frame_options.rowconfigure(0,weight=1)
self.frame_options.columnconfigure(0,weight=1)
#Configure info
self.frame_info.rowconfigure(0, weight=1)
self.frame_info.columnconfigure(0, weight=1)
self.frame_info.rowconfigure(0, weight=1)
self.frame_info.columnconfigure(0, weight=1)
self.label_info_1 = customtkinter.CTkLabel(master=self.frame_info,text=label_ ,height=100,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_1.grid(column=0, row=0, sticky="nwe", padx=15, pady=10)
#Configure options
self.frame_options.rowconfigure(0,minsize=10, weight=1)
self.frame_options.columnconfigure(0,minsize=10, weight=1)
self.frame_options.rowconfigure(0,minsize=10, weight=1)
self.frame_options.columnconfigure(0,minsize=10, weight=1)
self.frame_options.rowconfigure(0,minsize=10, weight=1)
self.frame_options.columnconfigure(1,minsize=10, weight=1)
self.frame_options.rowconfigure(0,minsize=10, weight=1)
self.frame_options.columnconfigure(2,minsize=10, weight=1)
self.radio_var = tkinter.IntVar(value=0)
self.label_info_2 = customtkinter.CTkLabel(master=self.frame_options,text=label_text ,height=40,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_2.grid(column=0, row=0, sticky="nwe", padx=15, pady=10,columnspan=4)
self.label_radio_0=customtkinter.CTkRadioButton(master=self.frame_options,variable=self.radio_var,text="Repititions",text_font=("Roboto Medium", -12),value=0,command=self.repititions_event)
self.label_radio_0.grid(column=0,columnspan=1, row=3,padx=10,pady=10,sticky="nswe")
self.label_radio_1=customtkinter.CTkRadioButton(master=self.frame_options,variable=self.radio_var,text="Time",text_font=("Roboto Medium", -12),value=1,command=self.time_event)
self.label_radio_1.grid(column=1,columnspan=1, row=3,padx=10,pady=10,sticky="nswe")
self.label_radio_2=customtkinter.CTkRadioButton(master=self.frame_options,variable=self.radio_var,text="Experience",text_font=("Roboto Medium", -12),value=2,command=self.exp_event)
self.label_radio_2.grid(column=2,columnspan=1, row=3,padx=10,pady=10,sticky="nswe")
self.label_radio_3=customtkinter.CTkRadioButton(master=self.frame_options,variable=self.radio_var,text="Gold",text_font=("Roboto Medium", -12),value=3,command=self.gold_event)
self.label_radio_3.grid(column=3,columnspan=1, row=3,padx=10,pady=10,sticky="nswe")
self.slider=customtkinter.CTkSlider(master=self.frame_options,number_of_steps=250,from_=1, to=250,command=self.update_metrics_)
self.slider.grid(column=0,row=4,columnspan=4,padx=10,pady=20,sticky="nsew")
#start/stop frame
self.start_stop = customtkinter.CTkFrame(master=self.frame_right)
self.start_stop.grid(row=4, column=0, columnspan=2,rowspan=1,pady=10,padx=20,sticky="nsew")
self.start_stop.rowconfigure((0),minsize=10,weight=1)
self.start_stop.columnconfigure((0,1,2),minsize=10,weight=1)
self.start=customtkinter.CTkButton(master=self.start_stop,text="Start",command=self.start_event)
self.start.grid(row=0,column=0,padx=20,pady=20)
self.stop=customtkinter.CTkButton(master=self.start_stop,text="Stop",command=self.stop_event)
self.stop.grid(row=0,column=2,padx=20,pady=20)
def start_event(self):
metric_raw=str(round(self.slider.get()))
global n_process,s_process,c_process
if macro_select == 0:
print("\nStarted")
n = multiprocessing.Process(target=netherwart(metric_raw))
n.start()
print("flag")
ac=multiprocessing.active_children
print(f'Active Children: {len(ac)}')
n_process.append(n)
elif macro_select == 1:
print("\nStarted")
s = multiprocessing.Process(target=sugarcane(metric_raw))
s.start()
print("flag")
ac=multiprocessing.active_children
print(f'Active Children: {len(ac)}')
s_process.append(s)
elif macro_select == 2:
print("\nStarted")
c = multiprocessing.Process(target=cobblestone(metric_raw))
c.start()
print("flag")
ac=multiprocessing.active_children
print(f'Active Children: {len(ac)}')
c_process.append(c)
def stop_event(self):
if macro_select == 0:
print("\nEnded")
for process in n_process:
for process in multiprocessing.active_children():
process.terminate()
print(multiprocessing.active_children)
elif macro_select == 1:
print("\nEnded")
for process in s_process:
for process in multiprocessing.active_children():
process.terminate()
print(multiprocessing.active_children)
elif macro_select == 2:
print("\nEnded")
for process in c_process:
for process in multiprocessing.active_children():
process.terminate()
print(multiprocessing.active_children)
def netherwart_event(self):
global macro_select
macro_select=0
label_="The netherwart macro has been selected."
self.label_info_1 = customtkinter.CTkLabel(master=self.frame_info,text=label_ ,height=100,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_1.grid(column=0, row=0, sticky="nwe", padx=15, pady=10)
def sugarcane_event(self):
global macro_select
macro_select=1
label_="The sugarcane macro has been selected."
self.label_info_1 = customtkinter.CTkLabel(master=self.frame_info,text=label_ ,height=100,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_1.grid(column=0, row=0, sticky="nwe", padx=15, pady=10)
def cobblestone_event(self):
global macro_select
macro_select=2
label_="The cobblestone macro has been selected."
self.label_info_1 = customtkinter.CTkLabel(master=self.frame_info,text=label_ ,height=100,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_1.grid(column=0, row=0, sticky="nwe", padx=15, pady=10)
def repititions_event(self):
global radio_select
radio_select=0
def time_event(self):
global radio_select
radio_select=1
def exp_event(self):
global radio_select
radio_select=2
def gold_event(self):
global radio_select
radio_select=3
def update_metrics_(self, slider):
global radio_select
global macro_select
global xp
metric_raw=str(round(self.slider.get()))
if radio_select == 0:
label_text="Number of repititions: "+ metric_raw
elif radio_select == 1:
if macro_select==0:
place_holder=int(metric_raw)
time_0=int(rand_offset_max+58)
time_1=int(place_holder*time_0)
time_1=str(time_1)
label_text="Approximate time to complete: "+ time_1 +" seconds."
elif macro_select==1:
place_holder=int(metric_raw)
time_0_0=int(rand_offset_max+34)
time_1_0=int(place_holder*time_0_0)
time_1_0=str(time_1_0)
label_text="Approximate time to complete: "+ time_1_0 +" seconds"
elif macro_select==2:
place_holder=int(metric_raw)
time_1_0_0=int(30*place_holder)
time_1_0_0=str(time_1_0_0)
label_text="Approximate time to complete: "+ time_1_0_0 +" seconds"
elif radio_select == 2:
if macro_select==0:
place_holder=int(metric_raw)
xp=int(1334*place_holder)
xp=str(xp)
label_text="Approximate experience gained: " + xp +"xp"
elif macro_select==1:
place_holder=int(metric_raw)
xp=int(3341*place_holder)
xp=str(xp)
label_text="Approximate experience gained: " + xp +"xp"
elif macro_select==2:
place_holder=int(metric_raw)
xp=int(600*place_holder)
xp=str(xp)
label_text="Approximate experience gained: " + xp +"xp"
elif radio_select == 3:
if macro_select==0:
place_holder=int(metric_raw)
gold=int(30000*place_holder)
gold=str(gold)
label_text="Approximate gold gained: " + gold +"gold"
elif macro_select==1:
place_holder=int(metric_raw)
gold=int(9000*place_holder)
gold=str(gold)
label_text="Approximate gold gained: " + gold +"gold"
elif macro_select==2:
place_holder=int(metric_raw)
gold=int(3000*place_holder)
gold=str(gold)
label_text="Approximate gold gained: " + gold +"gold"
self.label_info_2 = customtkinter.CTkLabel(master=self.frame_options,text=label_text ,height=40,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_2.grid(column=0, row=0, sticky="nwe", padx=15, pady=10,columnspan=4)
def settings_event(self):
self.settings_window=customtkinter.CTkToplevel(master=self)
self.settings_window.geometry("600x400")
self.settings_window.title("Settings")
self.settings_window_options=customtkinter.CTkFrame(master=self.settings_window)
self.settings_window_options.grid(padx=20,pady=20,column=0,row=0,rowspan=4,columnspan=4,sticky="nsew")
self.settings_window.rowconfigure(0,minsize=10,weight=1)
self.settings_window.rowconfigure(1,minsize=10,weight=1)
self.settings_window.rowconfigure(2,minsize=10,weight=1)
self.settings_window.rowconfigure(3,minsize=10,weight=1)
self.settings_window.columnconfigure(0,minsize=10,weight=1)
self.settings_window.columnconfigure(1,minsize=10,weight=1)
self.settings_window.columnconfigure(2,minsize=10,weight=1)
self.settings_window.columnconfigure(3,minsize=10,weight=1)
self.settings_window_options.rowconfigure(0,minsize=10,weight=1)
self.settings_window_options.rowconfigure(1,minsize=10,weight=1)
self.settings_window_options.rowconfigure(2,minsize=10,weight=1)
self.settings_window_options.rowconfigure(3,minsize=10,weight=1)
self.settings_window_options.columnconfigure(0,minsize=10,weight=1)
self.settings_window_options.columnconfigure(1,minsize=10,weight=1)
self.settings_window_options.columnconfigure(2,minsize=10,weight=1)
self.settings_window_options.columnconfigure(3,minsize=10,weight=1)
self.random_offset_lable_frame=customtkinter.CTkFrame(master=self.settings_window_options)
self.random_offset_lable_frame.grid(column=0,row=0,columnspan=4,padx=20,pady=20,rowspan=1,sticky="nsew")
self.random_offset_lable_frame.columnconfigure(0,minsize=10,weight=1)
self.random_offset_lable_frame.columnconfigure(1,minsize=10,weight=1)
self.random_offset_lable_frame.columnconfigure(2,minsize=10,weight=1)
self.random_offset_lable_frame.rowconfigure(0,minsize=10,weight=1)
self.random_offset_lable_frame.rowconfigure(1,minsize=10,weight=1)
self.random_offset_lable_frame.rowconfigure(2,minsize=10,weight=1)
self.random_offset_lable=customtkinter.CTkLabel(master=self.random_offset_lable_frame,text="EzFarm settings:")
self.random_offset_lable.grid(column=1,row=1,columnspan=1,rowspan=1,sticky="nsew")
self.random_offset_lable_frame_1=customtkinter.CTkFrame(master=self.settings_window_options)
self.random_offset_lable_frame_1.grid(column=0,row=1,columnspan=2,padx=20,pady=20,rowspan=1,sticky="nsew")
self.random_offset_lable_frame_2=customtkinter.CTkFrame(master=self.settings_window_options)
self.random_offset_lable_frame_2.grid(column=2,row=1,columnspan=2,padx=20,pady=20,rowspan=1,sticky="nsew")
self.random_offset_lable_1=customtkinter.CTkLabel(master=self.random_offset_lable_frame_1,text="Personalization::")
self.random_offset_lable_1.grid(column=1,row=0,columnspan=1,rowspan=1,padx=20,pady=20,sticky="n")
self.random_offset_lable_2=customtkinter.CTkLabel(master=self.random_offset_lable_frame_2,text="Randomized offset:")
self.random_offset_lable_2.grid(column=1,row=1,columnspan=1,rowspan=1,padx=20,pady=20,sticky="n")
self.optionmenu_1 = customtkinter.CTkOptionMenu(master=self.random_offset_lable_frame_1,values=["Light", "Dark", "System"],command=self.change_appearance_mode)
self.optionmenu_1.grid(row=2,column=1,padx=20,pady=10,sticky="nsew")
self.random_offset_lable_2.columnconfigure(0,minsize=10,weight=1)
self.random_offset_lable_2.columnconfigure(1,minsize=10,weight=1)
self.random_offset_lable_2.columnconfigure(2,minsize=10,weight=1)
self.random_offset_lable_2.rowconfigure(0,minsize=10,weight=1)
self.random_offset_lable_2.rowconfigure(1,minsize=10,weight=1)
self.random_offset_lable_2.rowconfigure(2,minsize=10,weight=1)
self.offset_ui_0=customtkinter.CTkEntry(master=self.random_offset_lable_2,width=30,placeholder_text="Insert the min value:")
self.offset_ui_0.grid(row=1,column=0,columnspan=2,padx=10,pady=10,sticky="nsew")
self.offset_ui_1=customtkinter.CTkEntry(master=self.random_offset_lable_2,width=30,placeholder_text="Insert the max value:")
self.offset_ui_1.grid(row=2,column=0,columnspan=2,padx=10,pady=10,sticky="nsew")
self.submit_button=customtkinter.CTkButton(master=self.random_offset_lable_frame_2,text="Submit",command=self.submit)
self.submit_button.grid(row=3,column=1,padx=20,pady=20,sticky="nsew")
def submit(self):
global rand_offset_min
global rand_offset_max
rand_offset_min=int(self.offset_ui_0.get())
rand_offset_max=int(self.offset_ui_1.get())
if rand_offset_min<0 or rand_offset_max<0:
error_=customtkinter.CTkToplevel(master=self)
error_.title("Error")
error_message=customtkinter.CTkLabel(master=error_,text="Error, please enter a whole number over 0")
error_message.grid(padx=10,pady=10)
def change_appearance_mode(self, new_appearance_mode):
customtkinter.set_appearance_mode(new_appearance_mode)
def button_event(self):
print("Button pressed")
def change_appearance_mode(self, new_appearance_mode):
customtkinter.set_appearance_mode(new_appearance_mode)
def on_closing(self, event=0):
self.destroy()
if __name__ == "__main__":
app = App()
app.mainloop()
A:
It looks like you're trying to use multiple threads to run your macros simultaneously. However, the GUI freezes because you're blocking the main thread, which is responsible for updating the GUI.
To fix this, you need to make sure that your macro functions are non-blocking, i.e. they don't freeze the main thread. One way to do this is to use the threading module to run each macro in a separate thread.
Here's an example of how you could modify your code to do this:
import threading
def netherwart(metric_raw):
# ...
def sugarcane(metric_raw):
# ...
def cobblestone(metric_raw):
# ...
def run_macro(func, metric_raw):
thread = threading.Thread(target=func, args=(metric_raw,))
thread.start()
# To run a macro, call the run_macro() function with the name of the macro function
# and the metric_raw argument that you want to pass to it.
run_macro(sugarcane, 100)
This way, each macro function will be run in a separate thread, and the main thread will be free to update the GUI. You'll need to make similar changes to the rest of your code to ensure that all blocking operations are moved to separate threads.
I hope this helps!
|
How do I run my main function in parallel with a multiprocessing.Process without it freezing? (sorry for the sloppy code, I'm new and self taught)
|
My main function is an app that I want to use for macros, the macros themselves all work as intended, and the function is technically able to work. The issue arises when you start the function, as you can't interact with the GUI because it is frozen, it unfreezes when the function ends and then the GUI becomes usable again. Again, I'm sorry about the sloppy and changing code, like I said, I'm self taught and a lot is borrowed and mangled together.
I tried using different start methods like spawn and fork, I tried setting up different ways for the function to end so it wouldn't wait, and at one point the GUI worked but the second I fixed the other bug this one came. I don't have an old save sadly as it was overwritten. There are no errors and I understand that there probably is a solution already out there but I have yet to find it. The code is long 400-ish lines so be warned.
from ast import Call
from cgitb import text
from concurrent.futures import process, thread
from itertools import starmap
from logging import PlaceHolder, error
from re import L
import tkinter
import tkinter.messagebox
from turtle import width
import customtkinter
import threading
import multiprocessing
import time
import pyautogui
import sys
import keyboard
label_text="Select counter as well as type below:"
macro_select=0
rand_offset_min=0 #needed to set the variables in case of no entry
rand_offset_max=3
radio_select=0
label_="Please select a macro type:"
dead=False
base_start=";"
customtkinter.set_appearance_mode("System") # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("blue") # Themes: "blue" (standard), "green", "dark-blue"
n_process = []
s_process = []
c_process = []
multiprocessing.set_start_method("spawn")
def netherwart(metric_raw):
y=0
time.sleep(5)
print(metric_raw)
PlaceHolder_0=int(metric_raw)
while y <= PlaceHolder_0:
print (PlaceHolder_0)
print("running")
print(y)
pyautogui.keyDown(' ')
pyautogui.keyDown('a')
time.sleep(28)
pyautogui.keyUp('a')
pyautogui.keyDown('d')
time.sleep(28)
pyautogui.keyUp('d')
y=y+1
print("flag0")
def sugarcane(metric_raw):
y=0
time.sleep(5)
PlaceHolder_0=int(metric_raw)
while y <= PlaceHolder_0:
print (PlaceHolder_0)
print("running.")
pyautogui.keyDown(' ')
pyautogui.keyDown('d')
time.sleep(.25)
pyautogui.keyDown('w')
time.sleep(14.5)
pyautogui.keyUp('d')
time.sleep(1)
pyautogui.keyUp('w')
pyautogui.keyDown('s')
time.sleep(17.5)
pyautogui.keyUp('s')
pyautogui.keyDown('a')
pyautogui.keyDown('w')
time.sleep(.25)
pyautogui.keyUp('w')
time.sleep(.25)
pyautogui.keyUp('a')
y=y+1
def cobblestone(metric_raw):
y=0
time.sleep(5)
PlaceHolder_0=int(metric_raw)
while y <= PlaceHolder_0:
print (PlaceHolder_0)
print("running..")
pyautogui.keyDown(' ')
pyautogui.keyDown('w')
time.sleep(30)
y=y+1
class App(customtkinter.CTk):
WIDTH = 780 #set the width of the main gui
HEIGHT = 520 #set the height of the main gui
def __init__(self):
multiprocessing.freeze_support()
super().__init__()
self.title("EzFarmerGui") #Naming the program
self.geometry(f"{App.WIDTH} x {App.HEIGHT}")#Setting the background size
self.protocol("WM_DELETE_WINDOW", self.on_closing)
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)
self.frame_left = customtkinter.CTkFrame(master=self, width=180, corner_radius=0)
self.frame_left.grid(row=0, column=0,rowspan=4, sticky="nswe")
self.frame_right = customtkinter.CTkFrame(master=self)
self.frame_right.grid(row=0, column=1,rowspan=1, sticky="nswe", padx=20, pady=10)
#left frame
self.frame_left.grid_rowconfigure(0, minsize=10) # empty row with minsize as spacing
self.frame_left.grid_rowconfigure(5, weight=1) # empty row as spacing
self.frame_left.grid_rowconfigure(8, minsize=20) # empty row with minsize as spacing
self.frame_left.grid_rowconfigure(11, minsize=10) # empty row with minsize as spacing | the first number is the actual row or column, row is the y and column is the x
self.label_1 = customtkinter.CTkLabel(master=self.frame_left,text="Farming Options:",text_font=("Roboto Medium", -16)) # font name and size in px
self.label_1.grid(row=1, column=0, pady=10, padx=10)
self.button_1 = customtkinter.CTkButton(master=self.frame_left,text="Netherwart",text_font=("Roboto Medium", -12),command=self.netherwart_event)
self.button_1.grid(row=2, column=0, pady=10, padx=20)
self.button_2 = customtkinter.CTkButton(master=self.frame_left,text="Sugarcane",text_font=("Roboto Medium", -12),command=self.sugarcane_event)
self.button_2.grid(row=3, column=0, pady=10,padx=20)
self.button_3 = customtkinter.CTkButton(master=self.frame_left,text="Cobblestone",text_font=("Roboto Medium", -12),command=self.cobblestone_event)
self.button_3.grid(row=4, column=0, pady=10,padx=20)
self.button_4 = customtkinter.CTkButton(master=self.frame_left,text="Settings",text_font=("Roboto Medium", -12),command=self.settings_event)
self.button_4.grid(row=6, column=0, pady=10,padx=20)
#Right frame
self.frame_right.rowconfigure((0, 1, 2), minsize=0,weight=2)
self.frame_right.rowconfigure(7, weight=10)
self.frame_right.rowconfigure(3,weight=1)
self.frame_right.columnconfigure((0, 1), weight=1)
self.frame_right.columnconfigure(2, weight=0)
self.frame_info = customtkinter.CTkFrame(master=self.frame_right)
self.frame_info.grid(row=0, column=0, columnspan=2, rowspan=2, pady=10, padx=20, sticky="nsew")
self.frame_options = customtkinter.CTkFrame(master=self.frame_right)
self.frame_options.grid(row=2, column=0, columnspan=2,rowspan=1,pady=10,padx=20,sticky="nsew")
self.frame_options.rowconfigure(0,weight=1)
self.frame_options.columnconfigure(0,weight=1)
#Configure info
self.frame_info.rowconfigure(0, weight=1)
self.frame_info.columnconfigure(0, weight=1)
self.frame_info.rowconfigure(0, weight=1)
self.frame_info.columnconfigure(0, weight=1)
self.label_info_1 = customtkinter.CTkLabel(master=self.frame_info,text=label_ ,height=100,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_1.grid(column=0, row=0, sticky="nwe", padx=15, pady=10)
#Configure options
self.frame_options.rowconfigure(0,minsize=10, weight=1)
self.frame_options.columnconfigure(0,minsize=10, weight=1)
self.frame_options.rowconfigure(0,minsize=10, weight=1)
self.frame_options.columnconfigure(0,minsize=10, weight=1)
self.frame_options.rowconfigure(0,minsize=10, weight=1)
self.frame_options.columnconfigure(1,minsize=10, weight=1)
self.frame_options.rowconfigure(0,minsize=10, weight=1)
self.frame_options.columnconfigure(2,minsize=10, weight=1)
self.radio_var = tkinter.IntVar(value=0)
self.label_info_2 = customtkinter.CTkLabel(master=self.frame_options,text=label_text ,height=40,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_2.grid(column=0, row=0, sticky="nwe", padx=15, pady=10,columnspan=4)
self.label_radio_0=customtkinter.CTkRadioButton(master=self.frame_options,variable=self.radio_var,text="Repititions",text_font=("Roboto Medium", -12),value=0,command=self.repititions_event)
self.label_radio_0.grid(column=0,columnspan=1, row=3,padx=10,pady=10,sticky="nswe")
self.label_radio_1=customtkinter.CTkRadioButton(master=self.frame_options,variable=self.radio_var,text="Time",text_font=("Roboto Medium", -12),value=1,command=self.time_event)
self.label_radio_1.grid(column=1,columnspan=1, row=3,padx=10,pady=10,sticky="nswe")
self.label_radio_2=customtkinter.CTkRadioButton(master=self.frame_options,variable=self.radio_var,text="Experience",text_font=("Roboto Medium", -12),value=2,command=self.exp_event)
self.label_radio_2.grid(column=2,columnspan=1, row=3,padx=10,pady=10,sticky="nswe")
self.label_radio_3=customtkinter.CTkRadioButton(master=self.frame_options,variable=self.radio_var,text="Gold",text_font=("Roboto Medium", -12),value=3,command=self.gold_event)
self.label_radio_3.grid(column=3,columnspan=1, row=3,padx=10,pady=10,sticky="nswe")
self.slider=customtkinter.CTkSlider(master=self.frame_options,number_of_steps=250,from_=1, to=250,command=self.update_metrics_)
self.slider.grid(column=0,row=4,columnspan=4,padx=10,pady=20,sticky="nsew")
#start/stop frame
self.start_stop = customtkinter.CTkFrame(master=self.frame_right)
self.start_stop.grid(row=4, column=0, columnspan=2,rowspan=1,pady=10,padx=20,sticky="nsew")
self.start_stop.rowconfigure((0),minsize=10,weight=1)
self.start_stop.columnconfigure((0,1,2),minsize=10,weight=1)
self.start=customtkinter.CTkButton(master=self.start_stop,text="Start",command=self.start_event)
self.start.grid(row=0,column=0,padx=20,pady=20)
self.stop=customtkinter.CTkButton(master=self.start_stop,text="Stop",command=self.stop_event)
self.stop.grid(row=0,column=2,padx=20,pady=20)
def start_event(self):
metric_raw=str(round(self.slider.get()))
global n_process,s_process,c_process
if macro_select == 0:
print("\nStarted")
n = multiprocessing.Process(target=netherwart(metric_raw))
n.start()
print("flag")
ac=multiprocessing.active_children
print(f'Active Children: {len(ac)}')
n_process.append(n)
elif macro_select == 1:
print("\nStarted")
s = multiprocessing.Process(target=sugarcane(metric_raw))
s.start()
print("flag")
ac=multiprocessing.active_children
print(f'Active Children: {len(ac)}')
s_process.append(s)
elif macro_select == 2:
print("\nStarted")
c = multiprocessing.Process(target=cobblestone(metric_raw))
c.start()
print("flag")
ac=multiprocessing.active_children
print(f'Active Children: {len(ac)}')
c_process.append(c)
def stop_event(self):
if macro_select == 0:
print("\nEnded")
for process in n_process:
for process in multiprocessing.active_children():
process.terminate()
print(multiprocessing.active_children)
elif macro_select == 1:
print("\nEnded")
for process in s_process:
for process in multiprocessing.active_children():
process.terminate()
print(multiprocessing.active_children)
elif macro_select == 2:
print("\nEnded")
for process in c_process:
for process in multiprocessing.active_children():
process.terminate()
print(multiprocessing.active_children)
def netherwart_event(self):
global macro_select
macro_select=0
label_="The netherwart macro has been selected."
self.label_info_1 = customtkinter.CTkLabel(master=self.frame_info,text=label_ ,height=100,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_1.grid(column=0, row=0, sticky="nwe", padx=15, pady=10)
def sugarcane_event(self):
global macro_select
macro_select=1
label_="The sugarcane macro has been selected."
self.label_info_1 = customtkinter.CTkLabel(master=self.frame_info,text=label_ ,height=100,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_1.grid(column=0, row=0, sticky="nwe", padx=15, pady=10)
def cobblestone_event(self):
global macro_select
macro_select=2
label_="The cobblestone macro has been selected."
self.label_info_1 = customtkinter.CTkLabel(master=self.frame_info,text=label_ ,height=100,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_1.grid(column=0, row=0, sticky="nwe", padx=15, pady=10)
def repititions_event(self):
global radio_select
radio_select=0
def time_event(self):
global radio_select
radio_select=1
def exp_event(self):
global radio_select
radio_select=2
def gold_event(self):
global radio_select
radio_select=3
def update_metrics_(self, slider):
global radio_select
global macro_select
global xp
metric_raw=str(round(self.slider.get()))
if radio_select == 0:
label_text="Number of repititions: "+ metric_raw
elif radio_select == 1:
if macro_select==0:
place_holder=int(metric_raw)
time_0=int(rand_offset_max+58)
time_1=int(place_holder*time_0)
time_1=str(time_1)
label_text="Approximate time to complete: "+ time_1 +" seconds."
elif macro_select==1:
place_holder=int(metric_raw)
time_0_0=int(rand_offset_max+34)
time_1_0=int(place_holder*time_0_0)
time_1_0=str(time_1_0)
label_text="Approximate time to complete: "+ time_1_0 +" seconds"
elif macro_select==2:
place_holder=int(metric_raw)
time_1_0_0=int(30*place_holder)
time_1_0_0=str(time_1_0_0)
label_text="Approximate time to complete: "+ time_1_0_0 +" seconds"
elif radio_select == 2:
if macro_select==0:
place_holder=int(metric_raw)
xp=int(1334*place_holder)
xp=str(xp)
label_text="Approximate experience gained: " + xp +"xp"
elif macro_select==1:
place_holder=int(metric_raw)
xp=int(3341*place_holder)
xp=str(xp)
label_text="Approximate experience gained: " + xp +"xp"
elif macro_select==2:
place_holder=int(metric_raw)
xp=int(600*place_holder)
xp=str(xp)
label_text="Approximate experience gained: " + xp +"xp"
elif radio_select == 3:
if macro_select==0:
place_holder=int(metric_raw)
gold=int(30000*place_holder)
gold=str(gold)
label_text="Approximate gold gained: " + gold +"gold"
elif macro_select==1:
place_holder=int(metric_raw)
gold=int(9000*place_holder)
gold=str(gold)
label_text="Approximate gold gained: " + gold +"gold"
elif macro_select==2:
place_holder=int(metric_raw)
gold=int(3000*place_holder)
gold=str(gold)
label_text="Approximate gold gained: " + gold +"gold"
self.label_info_2 = customtkinter.CTkLabel(master=self.frame_options,text=label_text ,height=40,corner_radius=6,fg_color=("white", "gray38"),justify=tkinter.LEFT)
self.label_info_2.grid(column=0, row=0, sticky="nwe", padx=15, pady=10,columnspan=4)
def settings_event(self):
self.settings_window=customtkinter.CTkToplevel(master=self)
self.settings_window.geometry("600x400")
self.settings_window.title("Settings")
self.settings_window_options=customtkinter.CTkFrame(master=self.settings_window)
self.settings_window_options.grid(padx=20,pady=20,column=0,row=0,rowspan=4,columnspan=4,sticky="nsew")
self.settings_window.rowconfigure(0,minsize=10,weight=1)
self.settings_window.rowconfigure(1,minsize=10,weight=1)
self.settings_window.rowconfigure(2,minsize=10,weight=1)
self.settings_window.rowconfigure(3,minsize=10,weight=1)
self.settings_window.columnconfigure(0,minsize=10,weight=1)
self.settings_window.columnconfigure(1,minsize=10,weight=1)
self.settings_window.columnconfigure(2,minsize=10,weight=1)
self.settings_window.columnconfigure(3,minsize=10,weight=1)
self.settings_window_options.rowconfigure(0,minsize=10,weight=1)
self.settings_window_options.rowconfigure(1,minsize=10,weight=1)
self.settings_window_options.rowconfigure(2,minsize=10,weight=1)
self.settings_window_options.rowconfigure(3,minsize=10,weight=1)
self.settings_window_options.columnconfigure(0,minsize=10,weight=1)
self.settings_window_options.columnconfigure(1,minsize=10,weight=1)
self.settings_window_options.columnconfigure(2,minsize=10,weight=1)
self.settings_window_options.columnconfigure(3,minsize=10,weight=1)
self.random_offset_lable_frame=customtkinter.CTkFrame(master=self.settings_window_options)
self.random_offset_lable_frame.grid(column=0,row=0,columnspan=4,padx=20,pady=20,rowspan=1,sticky="nsew")
self.random_offset_lable_frame.columnconfigure(0,minsize=10,weight=1)
self.random_offset_lable_frame.columnconfigure(1,minsize=10,weight=1)
self.random_offset_lable_frame.columnconfigure(2,minsize=10,weight=1)
self.random_offset_lable_frame.rowconfigure(0,minsize=10,weight=1)
self.random_offset_lable_frame.rowconfigure(1,minsize=10,weight=1)
self.random_offset_lable_frame.rowconfigure(2,minsize=10,weight=1)
self.random_offset_lable=customtkinter.CTkLabel(master=self.random_offset_lable_frame,text="EzFarm settings:")
self.random_offset_lable.grid(column=1,row=1,columnspan=1,rowspan=1,sticky="nsew")
self.random_offset_lable_frame_1=customtkinter.CTkFrame(master=self.settings_window_options)
self.random_offset_lable_frame_1.grid(column=0,row=1,columnspan=2,padx=20,pady=20,rowspan=1,sticky="nsew")
self.random_offset_lable_frame_2=customtkinter.CTkFrame(master=self.settings_window_options)
self.random_offset_lable_frame_2.grid(column=2,row=1,columnspan=2,padx=20,pady=20,rowspan=1,sticky="nsew")
self.random_offset_lable_1=customtkinter.CTkLabel(master=self.random_offset_lable_frame_1,text="Personalization::")
self.random_offset_lable_1.grid(column=1,row=0,columnspan=1,rowspan=1,padx=20,pady=20,sticky="n")
self.random_offset_lable_2=customtkinter.CTkLabel(master=self.random_offset_lable_frame_2,text="Randomized offset:")
self.random_offset_lable_2.grid(column=1,row=1,columnspan=1,rowspan=1,padx=20,pady=20,sticky="n")
self.optionmenu_1 = customtkinter.CTkOptionMenu(master=self.random_offset_lable_frame_1,values=["Light", "Dark", "System"],command=self.change_appearance_mode)
self.optionmenu_1.grid(row=2,column=1,padx=20,pady=10,sticky="nsew")
self.random_offset_lable_2.columnconfigure(0,minsize=10,weight=1)
self.random_offset_lable_2.columnconfigure(1,minsize=10,weight=1)
self.random_offset_lable_2.columnconfigure(2,minsize=10,weight=1)
self.random_offset_lable_2.rowconfigure(0,minsize=10,weight=1)
self.random_offset_lable_2.rowconfigure(1,minsize=10,weight=1)
self.random_offset_lable_2.rowconfigure(2,minsize=10,weight=1)
self.offset_ui_0=customtkinter.CTkEntry(master=self.random_offset_lable_2,width=30,placeholder_text="Insert the min value:")
self.offset_ui_0.grid(row=1,column=0,columnspan=2,padx=10,pady=10,sticky="nsew")
self.offset_ui_1=customtkinter.CTkEntry(master=self.random_offset_lable_2,width=30,placeholder_text="Insert the max value:")
self.offset_ui_1.grid(row=2,column=0,columnspan=2,padx=10,pady=10,sticky="nsew")
self.submit_button=customtkinter.CTkButton(master=self.random_offset_lable_frame_2,text="Submit",command=self.submit)
self.submit_button.grid(row=3,column=1,padx=20,pady=20,sticky="nsew")
def submit(self):
global rand_offset_min
global rand_offset_max
rand_offset_min=int(self.offset_ui_0.get())
rand_offset_max=int(self.offset_ui_1.get())
if rand_offset_min<0 or rand_offset_max<0:
error_=customtkinter.CTkToplevel(master=self)
error_.title("Error")
error_message=customtkinter.CTkLabel(master=error_,text="Error, please enter a whole number over 0")
error_message.grid(padx=10,pady=10)
def change_appearance_mode(self, new_appearance_mode):
customtkinter.set_appearance_mode(new_appearance_mode)
def button_event(self):
print("Button pressed")
def change_appearance_mode(self, new_appearance_mode):
customtkinter.set_appearance_mode(new_appearance_mode)
def on_closing(self, event=0):
self.destroy()
if __name__ == "__main__":
app = App()
app.mainloop()
|
[
"It looks like you're trying to use multiple threads to run your macros simultaneously. However, the GUI freezes because you're blocking the main thread, which is responsible for updating the GUI.\nTo fix this, you need to make sure that your macro functions are non-blocking, i.e. they don't freeze the main thread. One way to do this is to use the threading module to run each macro in a separate thread.\nHere's an example of how you could modify your code to do this:\nimport threading\n\ndef netherwart(metric_raw):\n # ...\n\ndef sugarcane(metric_raw):\n # ...\n\ndef cobblestone(metric_raw):\n # ...\n\ndef run_macro(func, metric_raw):\n thread = threading.Thread(target=func, args=(metric_raw,))\n thread.start()\n\n# To run a macro, call the run_macro() function with the name of the macro function\n# and the metric_raw argument that you want to pass to it.\nrun_macro(sugarcane, 100)\n\nThis way, each macro function will be run in a separate thread, and the main thread will be free to update the GUI. You'll need to make similar changes to the rest of your code to ensure that all blocking operations are moved to separate threads.\nI hope this helps!\n"
] |
[
0
] |
[] |
[] |
[
"multiprocessing",
"python",
"tkinter"
] |
stackoverflow_0074664305_multiprocessing_python_tkinter.txt
|
Q:
a value of color can't be assigned to a type color
I am getting an error how can I solve this.
A:
You need to replace Colors.indigo[900] with Colors.indigo[900]!:
Color bgColor = data['isDayTime'] ? Colors.blue : Colors.indigo[900]!;
Color.indigo is a MaterialColor and the returned type of the operator [] on a MaterialColor is Color?. It means it can return a Color, but also null.
If you know that Colors.indigo[900] is not null. Then you can use the null check operator (!) to tell dart that you know the variable Colors? Colors.indigo[900] is not null and it is in fact a Color.
|
a value of color can't be assigned to a type color
|
I am getting an error how can I solve this.
|
[
"You need to replace Colors.indigo[900] with Colors.indigo[900]!:\nColor bgColor = data['isDayTime'] ? Colors.blue : Colors.indigo[900]!;\n\nColor.indigo is a MaterialColor and the returned type of the operator [] on a MaterialColor is Color?. It means it can return a Color, but also null.\nIf you know that Colors.indigo[900] is not null. Then you can use the null check operator (!) to tell dart that you know the variable Colors? Colors.indigo[900] is not null and it is in fact a Color.\n"
] |
[
0
] |
[] |
[] |
[
"flutter"
] |
stackoverflow_0074664545_flutter.txt
|
Q:
How can I slow down the refresh rate in pygame?
I'm new to python and I'm trying to make a simple platformer game using pygame. My issue is that when I use a while loop to make a block fall until it hits the bottom of the screen, it travels there all at once and I can't see it happening. However when I move the block side to side using if statements, I can see that happening. How can I slow down the falling block down so it's visible?
I was following a tutorial for the most part, but wanted to add my own thing.
clock = pygame.time.Clock()
fps = 60
run = True
while run:
clock.tick(fps)
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > 0:
x = x - 5
if keys[pygame.K_d] and x < (500 - width):
x = x + 5
if keys[pygame.K_s]: #this is the portion that is too fast.
while y < (500 - height):
y = y + 5
player = pygame.draw.rect(screen, (player_color), (x,y,width,height))
pygame.display.update()
I tried putting the entire while ... y = y + 5 code into an if as well; that slowed it down, but it only moved when I held down the s key.
A:
If you want it to fully 'animate' down, you should add the code that keeps the pygame screen/player updating in your while loop, otherwise you're just changing the y without changing the screen. So your code would look somewhat like this:
clock = pygame.time.Clock()
fps = 60
run = True
while run:
clock.tick(fps)
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > 0:
x = x - 5
if keys[pygame.K_d] and x < (500 - width):
x = x + 5
if keys[pygame.K_s]: #this is the portion that is too fast.
while y < (500 - height):
y = y + 5
player = pygame.draw.rect(screen, (player_color), (x,y,width,height)) # Make sure to update the player
pygame.display.update() # Make sure to update the display
player = pygame.draw.rect(screen, (player_color), (x,y,width,height))
pygame.display.update()
Changing the FPS:
But, if you do want to change the speed of the game loop/essentially the frames per second, you can simply change the fps variable/the clock.tick() argument. So for example:
clock = pygame.time.Clock()
fps = 30 # This value is the amount of frames per second
run = True
while run:
clock.tick(fps) # The argument (currently fps) passed into this method will change the frames per second
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > 0:
x = x - 5
if keys[pygame.K_d] and x < (500 - width):
x = x + 5
if keys[pygame.K_s]: #this is the portion that is too fast.
while y < (500 - height):
y = y + 5
player = pygame.draw.rect(screen, (player_color), (x,y,width,height))
pygame.display.update()
You can read more about the clock.tick() method here
Please mark my answer as accepted if it solved your issue
|
How can I slow down the refresh rate in pygame?
|
I'm new to python and I'm trying to make a simple platformer game using pygame. My issue is that when I use a while loop to make a block fall until it hits the bottom of the screen, it travels there all at once and I can't see it happening. However when I move the block side to side using if statements, I can see that happening. How can I slow down the falling block down so it's visible?
I was following a tutorial for the most part, but wanted to add my own thing.
clock = pygame.time.Clock()
fps = 60
run = True
while run:
clock.tick(fps)
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > 0:
x = x - 5
if keys[pygame.K_d] and x < (500 - width):
x = x + 5
if keys[pygame.K_s]: #this is the portion that is too fast.
while y < (500 - height):
y = y + 5
player = pygame.draw.rect(screen, (player_color), (x,y,width,height))
pygame.display.update()
I tried putting the entire while ... y = y + 5 code into an if as well; that slowed it down, but it only moved when I held down the s key.
|
[
"If you want it to fully 'animate' down, you should add the code that keeps the pygame screen/player updating in your while loop, otherwise you're just changing the y without changing the screen. So your code would look somewhat like this:\nclock = pygame.time.Clock()\nfps = 60\nrun = True\nwhile run:\n clock.tick(fps)\n keys = pygame.key.get_pressed()\n if keys[pygame.K_a] and x > 0:\n x = x - 5\n if keys[pygame.K_d] and x < (500 - width):\n x = x + 5\n if keys[pygame.K_s]: #this is the portion that is too fast. \n while y < (500 - height):\n y = y + 5 \n player = pygame.draw.rect(screen, (player_color), (x,y,width,height)) # Make sure to update the player\n pygame.display.update() # Make sure to update the display\n player = pygame.draw.rect(screen, (player_color), (x,y,width,height))\n pygame.display.update()\n\nChanging the FPS:\nBut, if you do want to change the speed of the game loop/essentially the frames per second, you can simply change the fps variable/the clock.tick() argument. So for example:\nclock = pygame.time.Clock()\nfps = 30 # This value is the amount of frames per second\nrun = True\nwhile run:\n clock.tick(fps) # The argument (currently fps) passed into this method will change the frames per second\n keys = pygame.key.get_pressed()\n if keys[pygame.K_a] and x > 0:\n x = x - 5\n if keys[pygame.K_d] and x < (500 - width):\n x = x + 5\n if keys[pygame.K_s]: #this is the portion that is too fast. \n while y < (500 - height):\n y = y + 5 \n player = pygame.draw.rect(screen, (player_color), (x,y,width,height))\n pygame.display.update()\n\nYou can read more about the clock.tick() method here\nPlease mark my answer as accepted if it solved your issue\n"
] |
[
1
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0074664312_pygame_python.txt
|
Q:
Postman doesn't have the required permissions to install Node.js and other dependencies
When I try to install interceptor to use cookies in postman I get the error that is mentioned in header. OS is linux.
I googled the error description but it is not mentioned anywhere. Any idea would be really helpful.
A:
Well, there is not any answer here yet. But I found a workaround that is installing PostmanCanary. I couldn't install interceptor to Postman in Linux but I installed it to PostmanCanary successfully and it works perfect.
A:
I had a similar problem, though I got the error code CHROME_NOT_INSTALLED as well. The solution was too simple: I had Chromium installed, not Chrome.
A:
As per the troubleshooting tips it could happen if NativeMessagingHosts directory is missing,
this can be solved by creating NativeMessagingHosts directory in ~/.config/google-chrome/ in case of linux.
Reference: https://learning.postman.com/docs/sending-requests/capturing-request-data/interceptor/#troubleshooting-tips
A:
And if desired to use interceptor on any other chrome based browser like brave, do the following
find the utils.js file. in my system the path looked like
/opt/postman/app/resources/app/utils/interceptor/utils.js
change the path of the key named LINUX to the path containing NativeMessagingHosts directory.
const nativeMessagingHosts = {
MACOS: '/Library/Application Support/Google/Chrome/NativeMessagingHosts/',
LINUX: '/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts/',
WINDOWS: 'HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\'
}
Here I changed the path from /.config/google-chrome/NativeMessagingHosts to /.config/BraveSoftware/Brave-Browser/NativeMessagingHosts/
Now try to install the interceptor again.
|
Postman doesn't have the required permissions to install Node.js and other dependencies
|
When I try to install interceptor to use cookies in postman I get the error that is mentioned in header. OS is linux.
I googled the error description but it is not mentioned anywhere. Any idea would be really helpful.
|
[
"Well, there is not any answer here yet. But I found a workaround that is installing PostmanCanary. I couldn't install interceptor to Postman in Linux but I installed it to PostmanCanary successfully and it works perfect.\n",
"I had a similar problem, though I got the error code CHROME_NOT_INSTALLED as well. The solution was too simple: I had Chromium installed, not Chrome.\n",
"As per the troubleshooting tips it could happen if NativeMessagingHosts directory is missing,\nthis can be solved by creating NativeMessagingHosts directory in ~/.config/google-chrome/ in case of linux.\nReference: https://learning.postman.com/docs/sending-requests/capturing-request-data/interceptor/#troubleshooting-tips\n",
"And if desired to use interceptor on any other chrome based browser like brave, do the following\n\nfind the utils.js file. in my system the path looked like\n/opt/postman/app/resources/app/utils/interceptor/utils.js\nchange the path of the key named LINUX to the path containing NativeMessagingHosts directory.\n\nconst nativeMessagingHosts = {\n MACOS: '/Library/Application Support/Google/Chrome/NativeMessagingHosts/',\n LINUX: '/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts/',\n WINDOWS: 'HKCU\\\\Software\\\\Google\\\\Chrome\\\\NativeMessagingHosts\\\\'\n }\n\nHere I changed the path from /.config/google-chrome/NativeMessagingHosts to /.config/BraveSoftware/Brave-Browser/NativeMessagingHosts/\nNow try to install the interceptor again.\n"
] |
[
2,
2,
1,
0
] |
[
"Make sure you have the following in the environment variable PATH:\nC:\\Program Files\\Nodejs\\\nI have face same issue before, and later it got fixed.\n"
] |
[
-1
] |
[
"linux",
"postman",
"ubuntu"
] |
stackoverflow_0060973689_linux_postman_ubuntu.txt
|
Q:
do you have to pass SSO profile credentials in order to assume the IAM role using boto3
I have my config file set up with multiple profiles and I am trying to assume an IAM role, but all the articles I see about assuming roles are starting with making an sts client using
import boto3 client = boto3.client('sts')
which makes sense but the only problem is, It gives me an error when I try to do it like this. but when I do it like this, while passing a profile that exists in my config file, it works. here is the code below:
import boto3 session = boto3.Session(profile_name="test_profile")
sts = session.client("sts")
response = sts.assume_role(
RoleArn="arn:aws:iam::xxx:role/role-name",
RoleSessionName="test-session"
)
new_session = Session(aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'])
when other people are assuming roles in their codes without passing a profile in, how does that even work? does boto3 automatically grabs the default profile from the config file or something like that in their case?
A:
Yes. This line:
sts = session.client("sts")
tells boto3 to create a session using the default credentials.
The credentials can be provided in the ~/.aws/credentials file. If the code is running on an Amazon EC2 instance, boto3 will automatically use credentials associated with the IAM Role associated with the instance.
Credentials can also be passed via Environment Variables.
See: Credentials — Boto3 documentation
|
do you have to pass SSO profile credentials in order to assume the IAM role using boto3
|
I have my config file set up with multiple profiles and I am trying to assume an IAM role, but all the articles I see about assuming roles are starting with making an sts client using
import boto3 client = boto3.client('sts')
which makes sense but the only problem is, It gives me an error when I try to do it like this. but when I do it like this, while passing a profile that exists in my config file, it works. here is the code below:
import boto3 session = boto3.Session(profile_name="test_profile")
sts = session.client("sts")
response = sts.assume_role(
RoleArn="arn:aws:iam::xxx:role/role-name",
RoleSessionName="test-session"
)
new_session = Session(aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'])
when other people are assuming roles in their codes without passing a profile in, how does that even work? does boto3 automatically grabs the default profile from the config file or something like that in their case?
|
[
"Yes. This line:\nsts = session.client(\"sts\")\n\ntells boto3 to create a session using the default credentials.\nThe credentials can be provided in the ~/.aws/credentials file. If the code is running on an Amazon EC2 instance, boto3 will automatically use credentials associated with the IAM Role associated with the instance.\nCredentials can also be passed via Environment Variables.\nSee: Credentials — Boto3 documentation\n"
] |
[
0
] |
[] |
[] |
[
"amazon_iam",
"amazon_web_services",
"assume_role",
"boto3",
"python"
] |
stackoverflow_0074656007_amazon_iam_amazon_web_services_assume_role_boto3_python.txt
|
Q:
How can I edit an embed field with a button in Discord.py?
Basically, I'm making a poll command. I want it to put the user's vote in the embed field, and obviously make it so they can't vote again, again, and again. No idea how to do this.
Command Preview Here
Here's the code:
class Buttons(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Yes", style=discord.ButtonStyle.success, emoji='')
async def upvote_button(self, button : discord.ui.Button, interaction : discord.Interaction):
pass
@discord.ui.button(label="No", style=discord.ButtonStyle.danger, emoji='')
async def downvote_button(self, button : discord.ui.Button, interaction : discord.Interaction):
pass
class Poll(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="poll", description="Ask a question and receive upvotes or downvotes (Yes/No)")
async def poll(self, interaction : discord.Interaction, *, question : str):
embed = discord.Embed(
description=question,
color = 0xb037e1
)
embed.set_author(name="Poll", icon_url=self.bot.user.avatar)
embed.set_footer(text="Asked by: " + str(interaction.user), icon_url=interaction.user.avatar)
embed.add_field(name="Upvotes", value="X", inline=True)
embed.add_field(name="Downvotes", value="X", inline=True)
await interaction.response.send_message(embed=embed, view=Buttons())
Probably very simple, although I still haven't thought about a way
A:
The easiest way to do this is by using dictionaries, lists, or even sets to store the users that have clicked.
For this example, I will use one list to store the users who have clicked the upvote and downvote buttons. Like here:
class Buttons(discord.ui.View):
def __init__(self, *, timeout=None):
super().__init__(timeout=timeout or 180)
self.voted_users = []
self.upvote_count = 0
self.downvote_count = 0
@discord.ui.button(
label="Yes", style=discord.ButtonStyle.success, emoji=""
)
async def upvote_button(
self, interaction: discord.Interaction, button: discord.ui.Button
):
if (
interaction.user in self.voted_users
): # check if the user has already voted or not and return if true
return await interaction.response.send_message(
content="You've already voted!", ephemeral=True
)
self.upvote_count += 1
self.voted_users.append(interaction.user) # add the user to voted list
await interaction.response.send_message("Upvoted!", ephemeral=True)
@discord.ui.button(label="No", style=discord.ButtonStyle.danger, emoji="")
async def downvote_button(
self, interaction: discord.Interaction, button: discord.ui.Button
):
if (
interaction.user in self.voted_users
): # check if the user has already voted or not and return if true
return await interaction.response.send_message(
content="You've already voted!", ephemeral=True
)
self.downvote_count += 1
self.voted_users.append(interaction.user) # add the user to voted list
await interaction.response.send_message("Downvoted!", ephemeral=True)
By the way, interaction always comes before the button in the button callback argument if you're using discord.py.
|
How can I edit an embed field with a button in Discord.py?
|
Basically, I'm making a poll command. I want it to put the user's vote in the embed field, and obviously make it so they can't vote again, again, and again. No idea how to do this.
Command Preview Here
Here's the code:
class Buttons(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Yes", style=discord.ButtonStyle.success, emoji='')
async def upvote_button(self, button : discord.ui.Button, interaction : discord.Interaction):
pass
@discord.ui.button(label="No", style=discord.ButtonStyle.danger, emoji='')
async def downvote_button(self, button : discord.ui.Button, interaction : discord.Interaction):
pass
class Poll(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="poll", description="Ask a question and receive upvotes or downvotes (Yes/No)")
async def poll(self, interaction : discord.Interaction, *, question : str):
embed = discord.Embed(
description=question,
color = 0xb037e1
)
embed.set_author(name="Poll", icon_url=self.bot.user.avatar)
embed.set_footer(text="Asked by: " + str(interaction.user), icon_url=interaction.user.avatar)
embed.add_field(name="Upvotes", value="X", inline=True)
embed.add_field(name="Downvotes", value="X", inline=True)
await interaction.response.send_message(embed=embed, view=Buttons())
Probably very simple, although I still haven't thought about a way
|
[
"The easiest way to do this is by using dictionaries, lists, or even sets to store the users that have clicked.\nFor this example, I will use one list to store the users who have clicked the upvote and downvote buttons. Like here:\nclass Buttons(discord.ui.View):\n def __init__(self, *, timeout=None):\n super().__init__(timeout=timeout or 180)\n\n self.voted_users = []\n\n self.upvote_count = 0\n self.downvote_count = 0\n\n @discord.ui.button(\n label=\"Yes\", style=discord.ButtonStyle.success, emoji=\"\"\n )\n async def upvote_button(\n self, interaction: discord.Interaction, button: discord.ui.Button\n ):\n if (\n interaction.user in self.voted_users\n ): # check if the user has already voted or not and return if true\n return await interaction.response.send_message(\n content=\"You've already voted!\", ephemeral=True\n )\n\n self.upvote_count += 1\n self.voted_users.append(interaction.user) # add the user to voted list\n\n await interaction.response.send_message(\"Upvoted!\", ephemeral=True)\n\n @discord.ui.button(label=\"No\", style=discord.ButtonStyle.danger, emoji=\"\")\n async def downvote_button(\n self, interaction: discord.Interaction, button: discord.ui.Button\n ):\n if (\n interaction.user in self.voted_users\n ): # check if the user has already voted or not and return if true\n return await interaction.response.send_message(\n content=\"You've already voted!\", ephemeral=True\n )\n\n self.downvote_count += 1\n self.voted_users.append(interaction.user) # add the user to voted list\n\n await interaction.response.send_message(\"Downvoted!\", ephemeral=True)\n\nBy the way, interaction always comes before the button in the button callback argument if you're using discord.py.\n"
] |
[
0
] |
[] |
[] |
[
"discord.py",
"discord_buttons"
] |
stackoverflow_0074664053_discord.py_discord_buttons.txt
|
Q:
POST http://localhost:3000/undefined/post 404 (Not Found)
I'm tried to fatch my api data from backend by using axios. I'm getting an error, like this:
POST http://localhost:3000/undefined/post 404 (Not Found)
API routes like this:
// route middleware
app.use("/api", portRoutes);
// passing on controllers
router.post("/post", create);
// rest of code will have in controller folder
Now I have tried to work in frontend
I have tried by this way:
.env file
REACT_APP_API = http://localhost:8000/api
I dont know why does not access my server side links
handleSubmit function
const handleSubmit = (e) => {
e.preventDefault();
// access data from backend
axios
.post(`${process.env.REACT_APP_API}/post`, { title, content, user })
.then((response) => {
console.log(response);
setState({ ...state, title: "", content: "", user: "" });
alert(`Post Title ${response.data.title} is created`);
})
.catch((error) => {
console.log(error.response);
alert(error.response.data.error);
});
};
I'm sure my api is ok, I have checked my api with postman software.
A:
You cant access .env file from server side in your frontend app.
My suggestion is create in your frontend a config axios file
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:8000/api',
});
export default api;
Then in your handleSubmit function:
const handleSubmit = (e) => {
e.preventDefault();
// access data from backend
api
.post(`/post`, { title, content, user })
.then((response) => {
console.log(response);
setState({ ...state, title: "", content: "", user: "" });
alert(`Post Title ${response.data.title} is created`);
})
.catch((error) => {
console.log(error.response);
alert(error.response.data.error);
});
};
A:
I have solved my error from this link
Please feel free read this article if you faced same problem, that I have faced.
Thank you.
A:
this is also due to .env file in src folder... move it outside of src folder to the main client folder
|
POST http://localhost:3000/undefined/post 404 (Not Found)
|
I'm tried to fatch my api data from backend by using axios. I'm getting an error, like this:
POST http://localhost:3000/undefined/post 404 (Not Found)
API routes like this:
// route middleware
app.use("/api", portRoutes);
// passing on controllers
router.post("/post", create);
// rest of code will have in controller folder
Now I have tried to work in frontend
I have tried by this way:
.env file
REACT_APP_API = http://localhost:8000/api
I dont know why does not access my server side links
handleSubmit function
const handleSubmit = (e) => {
e.preventDefault();
// access data from backend
axios
.post(`${process.env.REACT_APP_API}/post`, { title, content, user })
.then((response) => {
console.log(response);
setState({ ...state, title: "", content: "", user: "" });
alert(`Post Title ${response.data.title} is created`);
})
.catch((error) => {
console.log(error.response);
alert(error.response.data.error);
});
};
I'm sure my api is ok, I have checked my api with postman software.
|
[
"You cant access .env file from server side in your frontend app.\nMy suggestion is create in your frontend a config axios file\nimport axios from 'axios';\n\nconst api = axios.create({\n baseURL: 'http://localhost:8000/api',\n});\n\nexport default api;\n\nThen in your handleSubmit function:\nconst handleSubmit = (e) => {\n e.preventDefault();\n\n // access data from backend\n api\n .post(`/post`, { title, content, user })\n .then((response) => {\n console.log(response);\n setState({ ...state, title: \"\", content: \"\", user: \"\" });\n alert(`Post Title ${response.data.title} is created`);\n })\n .catch((error) => {\n console.log(error.response);\n alert(error.response.data.error);\n });\n };\n\n",
"I have solved my error from this link\nPlease feel free read this article if you faced same problem, that I have faced.\nThank you.\n",
"this is also due to .env file in src folder... move it outside of src folder to the main client folder\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"axios",
"javascript",
"node.js",
"reactjs"
] |
stackoverflow_0066444086_axios_javascript_node.js_reactjs.txt
|
Q:
C# gives me different result of ModPow from Java & Python. Is this a bug?
all
I am Joshua.
Currently I am developing some kind of calculation logic in C#, .NET 4.7.
And I am stuck for a couple of days when using ModPow from BigInteger class.
Finally I compared with some other languages like Javascript and Python.
Here are the codes;
C#
var _a = BigInteger.Parse("-112504099738967919768410869814860903982619354592334385300478909977139427923361560492994684609769555842111970113942123739668771370088164545697837713491001933076595596664223176568695966455489156970812960564312137880189440762210023504737301351876623478203051273064143361985681097609967600291953777514093844982210010914333130253653115287655327635099624170100570446664200407152843331467876643789736619196583683418866514683967222986915221982722110686116114379750004515841618651243098835937383564483775550060041152863597757016771967904349656600797877149977649728258675384541203748747540152406727068415700988829908215424137984927266987257127615691501812286981137284264501640480312282004988469360705007547931588660449754580929985074021203105802730617855236140743357649842847802339153126105816742502906195190402079944900015779354117203169724787481860002766072928442884322075317745510521170465176626766316916518300959480576101945671060969719420147093892605449154540004740863401759952424765321581716947920578041839", NumberStyles.Number);
var _b = BigInteger.Parse("42710288472123706107732045980552936061105504205720832439400517546130482902053491661703847614802545363376415610740434485703528101945149576942291183712758802525948559100109353863348012045024391482754729786318228709846887076811626987986636873030977565323002665497040002349699696324754471341241246091133248712513", NumberStyles.Number);
var _c = BigInteger.Parse("5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807", NumberStyles.Number);
var _modPowRes = BigInteger.ModPow(_a, _b, _c);
NumberFormatInfo _formatter = new NumberFormatInfo();
_formatter.NegativeSign = "-";
string _stringRes = _modPowRes.ToString("D", _formatter);
// -4025962189194561064516553363283375014525921961557175720338529077112971710311848366234203913802556580292548393361209331638020083844074732374616343653135077799402946400533385408838985464487221381056062706959966844828188406680815976045839849337092509291814967568127589935214307295687077940893465121894442245470126915769901660325457529592729859443914551917517655171549159468233372814554103351084536838316208603471169266662039167296594675085295938849603548128017384775032304908588861826301095512209694112961080272106412321025934327013828425487280677537982063915874200399589997896633613461631025068511458444974149152947749747984549594822000420708352393424384641432718686749229405669436317664008070112083271636922781745940251494349374415266883563753139424535520085753958356376469108498554786941521255255003415937460671624180845917463097501347690828778209895285876290213489273200505952380626734459377765095025966725691306820725825499
Javascript, I used jsbn library
var _a = new BigInteger("-112504099738967919768410869814860903982619354592334385300478909977139427923361560492994684609769555842111970113942123739668771370088164545697837713491001933076595596664223176568695966455489156970812960564312137880189440762210023504737301351876623478203051273064143361985681097609967600291953777514093844982210010914333130253653115287655327635099624170100570446664200407152843331467876643789736619196583683418866514683967222986915221982722110686116114379750004515841618651243098835937383564483775550060041152863597757016771967904349656600797877149977649728258675384541203748747540152406727068415700988829908215424137984927266987257127615691501812286981137284264501640480312282004988469360705007547931588660449754580929985074021203105802730617855236140743357649842847802339153126105816742502906195190402079944900015779354117203169724787481860002766072928442884322075317745510521170465176626766316916518300959480576101945671060969719420147093892605449154540004740863401759952424765321581716947920578041839", 10);
var _b = new BigInteger("42710288472123706107732045980552936061105504205720832439400517546130482902053491661703847614802545363376415610740434485703528101945149576942291183712758802525948559100109353863348012045024391482754729786318228709846887076811626987986636873030977565323002665497040002349699696324754471341241246091133248712513", 10);
var _c = new BigInteger("5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807", 10);
var _modPowRes = _a.modPow(_b, _c);
var _stringRes = _modPowRes.toString(10);
// 1783643806175396998275362602355826387650690265345724813364371805666764467579142495237890860674783000854825016824437046690023645956675737723594580834731857259761425187634662132104996180029411374011438919474589553364998222309255272614979511868027284402170465728908528297700102876189729595563926155962569604427283291749203673030343591516627038015511719927953742781126799972560120257074290771695973286302279629131295383214811291564651109155633319576684151577295199734593114604874743329126921653504771250132941337184148762999959335547394147714802188259839801355116944682610659081543579365393513921728510730572041617697936145453462119608425988630323921319186513104423344823774870759265115372373731593225388193828408607005773987710556891304121163609340263880054616842988101393815039937434342691332663137114581535172021453932283969024301846449291944006405969946744999443455011016318658938083030075774742259090377978078691693422518308
Python
_a = -112504099738967919768410869814860903982619354592334385300478909977139427923361560492994684609769555842111970113942123739668771370088164545697837713491001933076595596664223176568695966455489156970812960564312137880189440762210023504737301351876623478203051273064143361985681097609967600291953777514093844982210010914333130253653115287655327635099624170100570446664200407152843331467876643789736619196583683418866514683967222986915221982722110686116114379750004515841618651243098835937383564483775550060041152863597757016771967904349656600797877149977649728258675384541203748747540152406727068415700988829908215424137984927266987257127615691501812286981137284264501640480312282004988469360705007547931588660449754580929985074021203105802730617855236140743357649842847802339153126105816742502906195190402079944900015779354117203169724787481860002766072928442884322075317745510521170465176626766316916518300959480576101945671060969719420147093892605449154540004740863401759952424765321581716947920578041839
_b = 42710288472123706107732045980552936061105504205720832439400517546130482902053491661703847614802545363376415610740434485703528101945149576942291183712758802525948559100109353863348012045024391482754729786318228709846887076811626987986636873030977565323002665497040002349699696324754471341241246091133248712513
_c = 5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807
_modPowRes = pow(_a, _b, _c)
print(_modPowRes)
#1783643806175396998275362602355826387650690265345724813364371805666764467579142495237890860674783000854825016824437046690023645956675737723594580834731857259761425187634662132104996180029411374011438919474589553364998222309255272614979511868027284402170465728908528297700102876189729595563926155962569604427283291749203673030343591516627038015511719927953742781126799972560120257074290771695973286302279629131295383214811291564651109155633319576684151577295199734593114604874743329126921653504771250132941337184148762999959335547394147714802188259839801355116944682610659081543579365393513921728510730572041617697936145453462119608425988630323921319186513104423344823774870759265115372373731593225388193828408607005773987710556891304121163609340263880054616842988101393815039937434342691332663137114581535172021453932283969024301846449291944006405969946744999443455011016318658938083030075774742259090377978078691693422518308
As you can see, all the consant valus _a, _b and _c are the same.
But only C# gives me the different result of ModPow.
I have tried smaller numbers, then C# gives me the same result as other languages.
I have tried to run my unit test project as x64, x86 and AnyCpu on platform target.
But the result is the same.
Can somebody explain why this is happening?
A:
Python and C# have different definitions of Mod. Python uses the mathematical definition of mod (the result is always a non-negative number) while C# returns a value with the same sign as you started with.
You'll notice that the difference between C#'s answer and Python's answer is precisely the modulus. In effect, both are returning the same value, but a different representation of it.
>>> x # result returned by C#
-4025962189194561064516553363283375014525921961557175720338529077112971710311848366234203913802556580292548393361209331638020083844074732374616343653135077799402946400533385408838985464487221381056062706959966844828188406680815976045839849337092509291814967568127589935214307295687077940893465121894442245470126915769901660325457529592729859443914551917517655171549159468233372814554103351084536838316208603471169266662039167296594675085295938849603548128017384775032304908588861826301095512209694112961080272106412321025934327013828425487280677537982063915874200399589997896633613461631025068511458444974149152947749747984549594822000420708352393424384641432718686749229405669436317664008070112083271636922781745940251494349374415266883563753139424535520085753958356376469108498554786941521255255003415937460671624180845917463097501347690828778209895285876290213489273200505952380626734459377765095025966725691306820725825499
>>> y # result returned by Python
1783643806175396998275362602355826387650690265345724813364371805666764467579142495237890860674783000854825016824437046690023645956675737723594580834731857259761425187634662132104996180029411374011438919474589553364998222309255272614979511868027284402170465728908528297700102876189729595563926155962569604427283291749203673030343591516627038015511719927953742781126799972560120257074290771695973286302279629131295383214811291564651109155633319576684151577295199734593114604874743329126921653504771250132941337184148762999959335547394147714802188259839801355116944682610659081543579365393513921728510730572041617697936145453462119608425988630323921319186513104423344823774870759265115372373731593225388193828408607005773987710556891304121163609340263880054616842988101393815039937434342691332663137114581535172021453932283969024301846449291944006405969946744999443455011016318658938083030075774742259090377978078691693422518308
>>> y - x # your modulus
5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807
|
C# gives me different result of ModPow from Java & Python. Is this a bug?
|
all
I am Joshua.
Currently I am developing some kind of calculation logic in C#, .NET 4.7.
And I am stuck for a couple of days when using ModPow from BigInteger class.
Finally I compared with some other languages like Javascript and Python.
Here are the codes;
C#
var _a = BigInteger.Parse("-112504099738967919768410869814860903982619354592334385300478909977139427923361560492994684609769555842111970113942123739668771370088164545697837713491001933076595596664223176568695966455489156970812960564312137880189440762210023504737301351876623478203051273064143361985681097609967600291953777514093844982210010914333130253653115287655327635099624170100570446664200407152843331467876643789736619196583683418866514683967222986915221982722110686116114379750004515841618651243098835937383564483775550060041152863597757016771967904349656600797877149977649728258675384541203748747540152406727068415700988829908215424137984927266987257127615691501812286981137284264501640480312282004988469360705007547931588660449754580929985074021203105802730617855236140743357649842847802339153126105816742502906195190402079944900015779354117203169724787481860002766072928442884322075317745510521170465176626766316916518300959480576101945671060969719420147093892605449154540004740863401759952424765321581716947920578041839", NumberStyles.Number);
var _b = BigInteger.Parse("42710288472123706107732045980552936061105504205720832439400517546130482902053491661703847614802545363376415610740434485703528101945149576942291183712758802525948559100109353863348012045024391482754729786318228709846887076811626987986636873030977565323002665497040002349699696324754471341241246091133248712513", NumberStyles.Number);
var _c = BigInteger.Parse("5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807", NumberStyles.Number);
var _modPowRes = BigInteger.ModPow(_a, _b, _c);
NumberFormatInfo _formatter = new NumberFormatInfo();
_formatter.NegativeSign = "-";
string _stringRes = _modPowRes.ToString("D", _formatter);
// -4025962189194561064516553363283375014525921961557175720338529077112971710311848366234203913802556580292548393361209331638020083844074732374616343653135077799402946400533385408838985464487221381056062706959966844828188406680815976045839849337092509291814967568127589935214307295687077940893465121894442245470126915769901660325457529592729859443914551917517655171549159468233372814554103351084536838316208603471169266662039167296594675085295938849603548128017384775032304908588861826301095512209694112961080272106412321025934327013828425487280677537982063915874200399589997896633613461631025068511458444974149152947749747984549594822000420708352393424384641432718686749229405669436317664008070112083271636922781745940251494349374415266883563753139424535520085753958356376469108498554786941521255255003415937460671624180845917463097501347690828778209895285876290213489273200505952380626734459377765095025966725691306820725825499
Javascript, I used jsbn library
var _a = new BigInteger("-112504099738967919768410869814860903982619354592334385300478909977139427923361560492994684609769555842111970113942123739668771370088164545697837713491001933076595596664223176568695966455489156970812960564312137880189440762210023504737301351876623478203051273064143361985681097609967600291953777514093844982210010914333130253653115287655327635099624170100570446664200407152843331467876643789736619196583683418866514683967222986915221982722110686116114379750004515841618651243098835937383564483775550060041152863597757016771967904349656600797877149977649728258675384541203748747540152406727068415700988829908215424137984927266987257127615691501812286981137284264501640480312282004988469360705007547931588660449754580929985074021203105802730617855236140743357649842847802339153126105816742502906195190402079944900015779354117203169724787481860002766072928442884322075317745510521170465176626766316916518300959480576101945671060969719420147093892605449154540004740863401759952424765321581716947920578041839", 10);
var _b = new BigInteger("42710288472123706107732045980552936061105504205720832439400517546130482902053491661703847614802545363376415610740434485703528101945149576942291183712758802525948559100109353863348012045024391482754729786318228709846887076811626987986636873030977565323002665497040002349699696324754471341241246091133248712513", 10);
var _c = new BigInteger("5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807", 10);
var _modPowRes = _a.modPow(_b, _c);
var _stringRes = _modPowRes.toString(10);
// 1783643806175396998275362602355826387650690265345724813364371805666764467579142495237890860674783000854825016824437046690023645956675737723594580834731857259761425187634662132104996180029411374011438919474589553364998222309255272614979511868027284402170465728908528297700102876189729595563926155962569604427283291749203673030343591516627038015511719927953742781126799972560120257074290771695973286302279629131295383214811291564651109155633319576684151577295199734593114604874743329126921653504771250132941337184148762999959335547394147714802188259839801355116944682610659081543579365393513921728510730572041617697936145453462119608425988630323921319186513104423344823774870759265115372373731593225388193828408607005773987710556891304121163609340263880054616842988101393815039937434342691332663137114581535172021453932283969024301846449291944006405969946744999443455011016318658938083030075774742259090377978078691693422518308
Python
_a = -112504099738967919768410869814860903982619354592334385300478909977139427923361560492994684609769555842111970113942123739668771370088164545697837713491001933076595596664223176568695966455489156970812960564312137880189440762210023504737301351876623478203051273064143361985681097609967600291953777514093844982210010914333130253653115287655327635099624170100570446664200407152843331467876643789736619196583683418866514683967222986915221982722110686116114379750004515841618651243098835937383564483775550060041152863597757016771967904349656600797877149977649728258675384541203748747540152406727068415700988829908215424137984927266987257127615691501812286981137284264501640480312282004988469360705007547931588660449754580929985074021203105802730617855236140743357649842847802339153126105816742502906195190402079944900015779354117203169724787481860002766072928442884322075317745510521170465176626766316916518300959480576101945671060969719420147093892605449154540004740863401759952424765321581716947920578041839
_b = 42710288472123706107732045980552936061105504205720832439400517546130482902053491661703847614802545363376415610740434485703528101945149576942291183712758802525948559100109353863348012045024391482754729786318228709846887076811626987986636873030977565323002665497040002349699696324754471341241246091133248712513
_c = 5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807
_modPowRes = pow(_a, _b, _c)
print(_modPowRes)
#1783643806175396998275362602355826387650690265345724813364371805666764467579142495237890860674783000854825016824437046690023645956675737723594580834731857259761425187634662132104996180029411374011438919474589553364998222309255272614979511868027284402170465728908528297700102876189729595563926155962569604427283291749203673030343591516627038015511719927953742781126799972560120257074290771695973286302279629131295383214811291564651109155633319576684151577295199734593114604874743329126921653504771250132941337184148762999959335547394147714802188259839801355116944682610659081543579365393513921728510730572041617697936145453462119608425988630323921319186513104423344823774870759265115372373731593225388193828408607005773987710556891304121163609340263880054616842988101393815039937434342691332663137114581535172021453932283969024301846449291944006405969946744999443455011016318658938083030075774742259090377978078691693422518308
As you can see, all the consant valus _a, _b and _c are the same.
But only C# gives me the different result of ModPow.
I have tried smaller numbers, then C# gives me the same result as other languages.
I have tried to run my unit test project as x64, x86 and AnyCpu on platform target.
But the result is the same.
Can somebody explain why this is happening?
|
[
"Python and C# have different definitions of Mod. Python uses the mathematical definition of mod (the result is always a non-negative number) while C# returns a value with the same sign as you started with.\nYou'll notice that the difference between C#'s answer and Python's answer is precisely the modulus. In effect, both are returning the same value, but a different representation of it.\n>>> x # result returned by C#\n-4025962189194561064516553363283375014525921961557175720338529077112971710311848366234203913802556580292548393361209331638020083844074732374616343653135077799402946400533385408838985464487221381056062706959966844828188406680815976045839849337092509291814967568127589935214307295687077940893465121894442245470126915769901660325457529592729859443914551917517655171549159468233372814554103351084536838316208603471169266662039167296594675085295938849603548128017384775032304908588861826301095512209694112961080272106412321025934327013828425487280677537982063915874200399589997896633613461631025068511458444974149152947749747984549594822000420708352393424384641432718686749229405669436317664008070112083271636922781745940251494349374415266883563753139424535520085753958356376469108498554786941521255255003415937460671624180845917463097501347690828778209895285876290213489273200505952380626734459377765095025966725691306820725825499\n>>> y # result returned by Python\n1783643806175396998275362602355826387650690265345724813364371805666764467579142495237890860674783000854825016824437046690023645956675737723594580834731857259761425187634662132104996180029411374011438919474589553364998222309255272614979511868027284402170465728908528297700102876189729595563926155962569604427283291749203673030343591516627038015511719927953742781126799972560120257074290771695973286302279629131295383214811291564651109155633319576684151577295199734593114604874743329126921653504771250132941337184148762999959335547394147714802188259839801355116944682610659081543579365393513921728510730572041617697936145453462119608425988630323921319186513104423344823774870759265115372373731593225388193828408607005773987710556891304121163609340263880054616842988101393815039937434342691332663137114581535172021453932283969024301846449291944006405969946744999443455011016318658938083030075774742259090377978078691693422518308\n>>> y - x # your modulus\n5809605995369958062791915965639201402176612226902900533702900882779736177890990861472094774477339581147373410185646378328043729800750470098210924487866935059164371588168047540943981644516632755067501626434556398193186628990071248660819361205119793693985433297036118232914410171876807536457391277857011849897410207519105333355801121109356897459426271845471397952675959440793493071628394122780510124618488232602464649876850458861245784240929258426287699705312584509625419513463605155428017165714465363094021609290561084025893662561222573202082865797821865270991145082200656978177192827024538990239969175546190770645685893438011714430426409338676314743571154537142031573004276428701433036381801705308659830751190352946025482059931306571004727362479688415574702596946457770284148435989129632853918392117997472632693078113129886487399347796982772784615865232621289656944284216824611318709764535152507354116344703769998514148343807\n\n"
] |
[
1
] |
[] |
[] |
[
"biginteger",
"c#",
"javascript",
"mod",
"python"
] |
stackoverflow_0074664517_biginteger_c#_javascript_mod_python.txt
|
Q:
Remerge MR in GitLab
I did a Merge Request and already merged it, but want to edit commit messages squash/unsquash commits, etc. I know that I can do something that via git commit --fixup/git rebase into merged branch, but what will be with the MR itself? Will it be automatically fixed or not?
Let's say I have a source branch:
$ git log --oneline -n2
b6ddddddd commit message 1
b7ddddddd commit message 2
And I have a branch where source branch is merged to:
$ git log --oneline -n2
c6cccccac Merge branch `source` into `destination`
c7cccccbc MR Commit message
Here I have MR that actually has two squashed commits (b6ddddddd, b7ddddddd), but I want to "unsquash" commits and redo MR (that one is merged), is there a way to do so or I need to open a new MR?
A:
I did a Merge Request and already merged it
That would mean "reopening the MR", and that is not currently (2022) possible, as explained here.
It is best to make a new separate MR, with the source branch rebased on top the target remote branch, and where you can push again, for said new MR.
|
Remerge MR in GitLab
|
I did a Merge Request and already merged it, but want to edit commit messages squash/unsquash commits, etc. I know that I can do something that via git commit --fixup/git rebase into merged branch, but what will be with the MR itself? Will it be automatically fixed or not?
Let's say I have a source branch:
$ git log --oneline -n2
b6ddddddd commit message 1
b7ddddddd commit message 2
And I have a branch where source branch is merged to:
$ git log --oneline -n2
c6cccccac Merge branch `source` into `destination`
c7cccccbc MR Commit message
Here I have MR that actually has two squashed commits (b6ddddddd, b7ddddddd), but I want to "unsquash" commits and redo MR (that one is merged), is there a way to do so or I need to open a new MR?
|
[
"\nI did a Merge Request and already merged it\n\nThat would mean \"reopening the MR\", and that is not currently (2022) possible, as explained here.\nIt is best to make a new separate MR, with the source branch rebased on top the target remote branch, and where you can push again, for said new MR.\n"
] |
[
1
] |
[] |
[] |
[
"git",
"git_merge",
"gitlab"
] |
stackoverflow_0074657275_git_git_merge_gitlab.txt
|
Q:
Creating a nested list using insert() in Python
I'm trying to find a way to create a nested list out of an already-existing non-empty list using built-in list fuctions.
Here is a small example:
a=['Groceries', 'School Fees', 'Medicines', 'Furniture']
When I try a[0].insert(0, 1000) for example, I'm met with an error. Is there any way to do this?
|
Creating a nested list using insert() in Python
|
I'm trying to find a way to create a nested list out of an already-existing non-empty list using built-in list fuctions.
Here is a small example:
a=['Groceries', 'School Fees', 'Medicines', 'Furniture']
When I try a[0].insert(0, 1000) for example, I'm met with an error. Is there any way to do this?
|
[] |
[] |
[
"Make a function for inner inserting.\nTry this\na=['Groceries', 'School Fees', 'Medicines', 'Furniture']\ndef innerInsert(index, value):\n try:\n a[index].insert(index, value)\n except AttributeError:\n a[index] = []\n a[index].insert(index, value)\n\ninnerInsert(0, 10000)\ninnerInsert(0, 100)\nprint(a)\n\n\n[[100, 10000], 'School Fees', 'Medicines', 'Furniture']\n\nFor more options, I made some changes to the function\na=['Groceries', 'School Fees', 'Medicines', 'Furniture']\ndef innerInsert(l, iLstIndex, iLstValueIndex, value):\n try:\n l[iLstIndex].insert(iLstValueIndex, value)\n except AttributeError:\n l[iLstIndex] = []\n l[iLstIndex].insert(iLstValueIndex, value)\n\ninnerInsert(a, 0, 0, 10000)\ninnerInsert(a, 0, 1, 2)\ninnerInsert(a, 0, 2, 3)\ninnerInsert(a, 0, 3, 4)\ninnerInsert(a, 0, 4, 1)\ninnerInsert(a, 0, 5, 2)\ninnerInsert(a[0], 4, 2, 100)\nprint(a)\n\nOUTPUT\n[[10000, 2, 3, 4, [100], 2], 'School Fees', 'Medicines', 'Furniture']\n\n",
"You can use indexing to access the first sublist and then use the list.insert() method to insert the new value at the specified index. For example:\na = ['Groceries', 'School Fees', 'Medicines', 'Furniture']\nb = [[element] for element in a]\n\n# Add the value 1000 to the first element of the first sublist\nb[0].insert(0, 1000)\n\n# The resulting nested list should be: [[1000, 'Groceries'], ['School Fees'], ['Medicines'], ['Furniture']]\nprint(b)\n\n\n"
] |
[
-1,
-1
] |
[
"list",
"nested_lists",
"python"
] |
stackoverflow_0074664508_list_nested_lists_python.txt
|
Q:
Pivot SQL data without aggregation
So I need to straight pivot my data with no aggregation. I have tried PIVOT, UNPIVOT, CROSS APPLY, and CASE statements all driving me crazy.
Here is my current data set
Header
Contract Value
Total Cost
Profit
Original Budget
1000
900
100
Change Orders
100
90
90
And this is what I would like to do. I want the values in the rows to be the column names.
Header
Original Budget
Change Orders
Contract Value
1000
100
Total Cost
900
100
Profit
100
10
Can someone please point me in the right direction.
A:
To pivot your data without aggregation, you can use the PIVOT operator in SQL. The PIVOT operator allows you to transform rows into columns, and specify the values that should be used as column names.
Here is an example of how you could use the PIVOT operator to transform your data:
SELECT *
FROM yourTable
PIVOT
(
MAX(ContractValue)
FOR Header IN ([Original Budget], [Change Orders])
) AS PivotTable
In this query, the PIVOT operator is used to transform the rows in the yourTable table into columns. The MAX function is used to specify the values that should be used as column names, and the FOR clause specifies the values that should be used as the column names in the output. In this case, the column names are the values in the Header column.
This query will produce the following output:
Original Budget
Change Orders
1000
100
900
90
100
10
You can adjust the column names and values in the PIVOT operator to produce the output that you need. For more information on using the PIVOT operator, you can refer to the documentation for your database management system (DBMS).
A:
What are you looking is called Fully Trasnpose a table in SQL. it can be done with Unpivot and Pivot or Cross apply and Pivot
your data
CREATE TABLE mytable(
Header VARCHAR(100) NOT NULL
,Contract_Value INTEGER NOT NULL
,Total_Cost INTEGER NOT NULL
,Profit INTEGER NOT NULL
);
INSERT INTO mytable
(Header,Contract_Value,Total_Cost,Profit) VALUES
('Original Budget',1000,900,100),
('Change Orders',100,90,90);
using Unpivot and Pivot
SELECT
name AS Header,
[Original Budget],
[Change Orders]
FROM
(
select
Header,
name,
value
from
mytable unpivot (
value for name in (
[Contract_Value], [Profit], [Total_Cost]
)
) unpiv
) Src PIVOT (
MAX(value) FOR Header IN (
[Original Budget], [Change Orders]
)
) Pvt
ORDER BY
[Original Budget] desc
using Cross apply and Pivot
select name as header,
[Original Budget],
[Change Orders]
from
(
select Header,name,value1
From mytable
Cross Apply ( values ('Contract_Value',Contract_Value)
,('Total_Cost',Total_Cost)
,('Profit',Profit)
) B (name,value1)
) src
pivot
(
max(value1)
for Header in ([Original Budget], [Change Orders])
) piv
order by [Original Budget] desc
dbfiddle
|
Pivot SQL data without aggregation
|
So I need to straight pivot my data with no aggregation. I have tried PIVOT, UNPIVOT, CROSS APPLY, and CASE statements all driving me crazy.
Here is my current data set
Header
Contract Value
Total Cost
Profit
Original Budget
1000
900
100
Change Orders
100
90
90
And this is what I would like to do. I want the values in the rows to be the column names.
Header
Original Budget
Change Orders
Contract Value
1000
100
Total Cost
900
100
Profit
100
10
Can someone please point me in the right direction.
|
[
"To pivot your data without aggregation, you can use the PIVOT operator in SQL. The PIVOT operator allows you to transform rows into columns, and specify the values that should be used as column names.\nHere is an example of how you could use the PIVOT operator to transform your data:\nSELECT *\nFROM yourTable\nPIVOT\n(\n MAX(ContractValue)\n FOR Header IN ([Original Budget], [Change Orders])\n) AS PivotTable\n\nIn this query, the PIVOT operator is used to transform the rows in the yourTable table into columns. The MAX function is used to specify the values that should be used as column names, and the FOR clause specifies the values that should be used as the column names in the output. In this case, the column names are the values in the Header column.\nThis query will produce the following output:\n\n\n\n\nOriginal Budget\nChange Orders\n\n\n\n\n1000\n100\n\n\n900\n90\n\n\n100\n10\n\n\n\n\nYou can adjust the column names and values in the PIVOT operator to produce the output that you need. For more information on using the PIVOT operator, you can refer to the documentation for your database management system (DBMS).\n",
"What are you looking is called Fully Trasnpose a table in SQL. it can be done with Unpivot and Pivot or Cross apply and Pivot\nyour data\nCREATE TABLE mytable(\n Header VARCHAR(100) NOT NULL \n ,Contract_Value INTEGER NOT NULL\n ,Total_Cost INTEGER NOT NULL\n ,Profit INTEGER NOT NULL\n);\nINSERT INTO mytable\n(Header,Contract_Value,Total_Cost,Profit) VALUES \n('Original Budget',1000,900,100),\n('Change Orders',100,90,90);\n\nusing Unpivot and Pivot\nSELECT \n name AS Header, \n [Original Budget], \n [Change Orders] \nFROM \n (\n select \n Header, \n name, \n value \n from \n mytable unpivot (\n value for name in (\n [Contract_Value], [Profit], [Total_Cost]\n )\n ) unpiv\n ) Src PIVOT (\n MAX(value) FOR Header IN (\n [Original Budget], [Change Orders]\n )\n ) Pvt \nORDER BY \n [Original Budget] desc\n\nusing Cross apply and Pivot\nselect name as header,\n [Original Budget],\n [Change Orders]\nfrom \n(\nselect Header,name,value1\n From mytable\n Cross Apply ( values ('Contract_Value',Contract_Value)\n ,('Total_Cost',Total_Cost)\n ,('Profit',Profit)\n ) B (name,value1)\n) src\npivot\n(\n max(value1)\n for Header in ([Original Budget], [Change Orders])\n) piv\norder by [Original Budget] desc\n\ndbfiddle\n"
] |
[
1,
0
] |
[] |
[] |
[
"pivot",
"sql",
"sql_server"
] |
stackoverflow_0074662805_pivot_sql_sql_server.txt
|
Q:
Spatie\Backup\BackupDestination\BackupDestination::connectionError(): Return value must be of type Exception, null returned
I'm trying to backup Laravel to google drive, I'm using Spatie and masbug/flysystem-google-drive-ext
and facing this problem.(it's working fine when taking backup in local.)
main-error:
Here is my backup.php/database.php/filesystems.php/GoogleDriveServiceProvider.php:
backup.php, database.php, filesystems.ph, GoogleDriveServiceProvider.php
A:
This problem is solved by making name=''(backup.php)
|
Spatie\Backup\BackupDestination\BackupDestination::connectionError(): Return value must be of type Exception, null returned
|
I'm trying to backup Laravel to google drive, I'm using Spatie and masbug/flysystem-google-drive-ext
and facing this problem.(it's working fine when taking backup in local.)
main-error:
Here is my backup.php/database.php/filesystems.php/GoogleDriveServiceProvider.php:
backup.php, database.php, filesystems.ph, GoogleDriveServiceProvider.php
|
[
"This problem is solved by making name=''(backup.php)\n"
] |
[
0
] |
[] |
[] |
[
"flysystem_google_drive",
"google_drive_api",
"laravel",
"laravel_backup",
"spatie_ssh"
] |
stackoverflow_0074651650_flysystem_google_drive_google_drive_api_laravel_laravel_backup_spatie_ssh.txt
|
Q:
Alternative for if-break in c?
Hello I am still a beginner when it comes to programming and I have been working on a checkers game. However, we cannot use 'break' to our program unless if its switch-case. How can I revise my work? I already tried to loop it using while.
int validateMove(int x1 , int y1)
{
int a , b;
printf( "Available coordinates to send the piece are: \n" ) ;
a=1, b=1;
while(board[x1-a][y1+b] == ' ')
{
if((x1-a)==-1 || (y1+b)==8)
break;
printf("%d%d , ", x1-a , y1+b);
a++;
b++;
}
a=1 , b=1;
while(board[x1+a][y1-b] == ' ')
{
if((x1+a)==8 || (y1-b)==-1)
break;
printf("%d%d , ", x1+a, y1-b);
a++;
b++;
}
a=1 , b=1;
while(board[x1+a][y1+b] == ' ')
{
if((x1+a)==8 || (y1+b)==8)
break;
printf("%d%d , ",x1+a, y1+b);
a++;
b++;
}
a=1;
b=1;
while(board[x1-a][y1-b] == ' ')
{
if((x1-a)==-1 || (y1-b)==-1)
break;
printf("%d%d , ", x1-a, y1-b);
a++;
b++;
}
}
A:
You only provided us a snippet so this has not been tested. validateMove() doesn't return anything so I changed the return type from int to void. Consider introducing a constant for your magic value ' ', perhaps:
#define EMPTY ' '
I would extract a function instead of repeating yourself 4 times. return is then a suitable alternative to break:
void validateMoveHelper(int x1, int y1, int af, int bf, int v, int v2) {
for(int a = 1, b = 1; board[x1 + af * a][y1 + bf * b] == ' '; a++, b++) {
if((x1 + af * a) == v || (y1 + bf * b) == v2)
return;
printf("%d%d , ", x1 + af * a , y1 + bf * b);
}
}
void validateMove(int x1, int y1) {
printf( "Available coordinates to send the piece are: \n" ) ;
validateMoveHelper(x1, y1, -1, -1, 1, 8);
validateMoveHelper(x1, y1, 8, 1, -1, -1);
validateMoveHelper(x1, y1, 8, 1, 1, 8);
validateMoveHelper(x1, y1, -1, -1, -1, -1);
}
Then I would extract those 4 rows of 4 values into a table t and run it in a loop. You want to document what the table contains, though, or maybe use an array of structs instead.
void validateMoveHelper(int x1, int y1, int t[4]) {
for(int a = 1, b = 1; board[x1 + t[0] * a][y1 + t[1] * b] == ' '; a++, b++) {
if((x1 + t[0] * a) == t[2] || (y1 + t[1] * b) == t[3])
return;
printf("%d%d , ", x1 + t[0] * a , y1 + t[1] * b);
}
}
void validateMove(int x1, int y1) {
printf( "Available coordinates to send the piece are: \n" ) ;
int t[][4] = {
{-1, -1, 1, 8},
{ 8, 1, -1, -1},
{ 8, 1, 1, 8},
{-1, -1, -1, -1}
};
for(int i = 0; i < sizeof t / sizeof *t; i++)
validateMoveHelper(x1, y1, t[i]);
}
|
Alternative for if-break in c?
|
Hello I am still a beginner when it comes to programming and I have been working on a checkers game. However, we cannot use 'break' to our program unless if its switch-case. How can I revise my work? I already tried to loop it using while.
int validateMove(int x1 , int y1)
{
int a , b;
printf( "Available coordinates to send the piece are: \n" ) ;
a=1, b=1;
while(board[x1-a][y1+b] == ' ')
{
if((x1-a)==-1 || (y1+b)==8)
break;
printf("%d%d , ", x1-a , y1+b);
a++;
b++;
}
a=1 , b=1;
while(board[x1+a][y1-b] == ' ')
{
if((x1+a)==8 || (y1-b)==-1)
break;
printf("%d%d , ", x1+a, y1-b);
a++;
b++;
}
a=1 , b=1;
while(board[x1+a][y1+b] == ' ')
{
if((x1+a)==8 || (y1+b)==8)
break;
printf("%d%d , ",x1+a, y1+b);
a++;
b++;
}
a=1;
b=1;
while(board[x1-a][y1-b] == ' ')
{
if((x1-a)==-1 || (y1-b)==-1)
break;
printf("%d%d , ", x1-a, y1-b);
a++;
b++;
}
}
|
[
"You only provided us a snippet so this has not been tested. validateMove() doesn't return anything so I changed the return type from int to void. Consider introducing a constant for your magic value ' ', perhaps:\n#define EMPTY ' '\n\nI would extract a function instead of repeating yourself 4 times. return is then a suitable alternative to break:\nvoid validateMoveHelper(int x1, int y1, int af, int bf, int v, int v2) {\n for(int a = 1, b = 1; board[x1 + af * a][y1 + bf * b] == ' '; a++, b++) {\n if((x1 + af * a) == v || (y1 + bf * b) == v2)\n return;\n printf(\"%d%d , \", x1 + af * a , y1 + bf * b);\n }\n}\n\nvoid validateMove(int x1, int y1) {\n printf( \"Available coordinates to send the piece are: \\n\" ) ;\n validateMoveHelper(x1, y1, -1, -1, 1, 8);\n validateMoveHelper(x1, y1, 8, 1, -1, -1);\n validateMoveHelper(x1, y1, 8, 1, 1, 8);\n validateMoveHelper(x1, y1, -1, -1, -1, -1);\n}\n\nThen I would extract those 4 rows of 4 values into a table t and run it in a loop. You want to document what the table contains, though, or maybe use an array of structs instead.\nvoid validateMoveHelper(int x1, int y1, int t[4]) {\n for(int a = 1, b = 1; board[x1 + t[0] * a][y1 + t[1] * b] == ' '; a++, b++) {\n if((x1 + t[0] * a) == t[2] || (y1 + t[1] * b) == t[3])\n return;\n printf(\"%d%d , \", x1 + t[0] * a , y1 + t[1] * b);\n }\n}\n\nvoid validateMove(int x1, int y1) {\n printf( \"Available coordinates to send the piece are: \\n\" ) ;\n int t[][4] = {\n {-1, -1, 1, 8},\n { 8, 1, -1, -1},\n { 8, 1, 1, 8},\n {-1, -1, -1, -1}\n };\n for(int i = 0; i < sizeof t / sizeof *t; i++)\n validateMoveHelper(x1, y1, t[i]);\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"c"
] |
stackoverflow_0074664348_c.txt
|
Q:
diff showing only the diff color without change code
I have changed line of a sql file file. But the diff only shows the diff colour without any change code.
the line is: @enabled=0, before the change we had 1 instead of 0.
without the gitattribute
*.sql text diff
I get the error message that file suppressed by a .gitattributes entry or the file's encoding is unsupported.
[this is the link of the image of my git diff] (https://i.stack.imgur.com/bgMvv.png)
A:
You need to check your git status (assuming the @enabled=0 was done on your workstation)
Check if:
the file is indeed Test/Scripts/ScriptsIgnoredOnImport.sql
there is any local commit which would not have been pushed yet.
The file on GitHub can also tell you more, by typing b (which triggers the file "blame" view on GitHub).
As shown here, you can then "View blame prior to this change" and see if your @enabled= was visible then.
|
diff showing only the diff color without change code
|
I have changed line of a sql file file. But the diff only shows the diff colour without any change code.
the line is: @enabled=0, before the change we had 1 instead of 0.
without the gitattribute
*.sql text diff
I get the error message that file suppressed by a .gitattributes entry or the file's encoding is unsupported.
[this is the link of the image of my git diff] (https://i.stack.imgur.com/bgMvv.png)
|
[
"You need to check your git status (assuming the @enabled=0 was done on your workstation)\nCheck if:\n\nthe file is indeed Test/Scripts/ScriptsIgnoredOnImport.sql\nthere is any local commit which would not have been pushed yet.\n\nThe file on GitHub can also tell you more, by typing b (which triggers the file \"blame\" view on GitHub).\nAs shown here, you can then \"View blame prior to this change\" and see if your @enabled= was visible then.\n"
] |
[
0
] |
[] |
[] |
[
"gitlab"
] |
stackoverflow_0074655016_gitlab.txt
|
Q:
Using % with variables inside function call
Simply put, it's
set /a mm=%r:~2,3%
BUT, the 2 is codified as set /a d=2 and the 3 is codified as set /a l=3.
So, now how do I write the first expression using the codified variables?
i.e. set /a mm=%r:~%d%,%l%% doesn't work. What's the gimmick?
I've tried...
set /a mm="%r:~(%%d),%%l%" and all kinds of other codifications but the % usage throws me.
A:
@echo off
::: Experimental Module
set /a s=0
title %date% @ %time% playtime.bat by -JpE-
:start
if %s% geq 2 cls & set /a s=0
echo .
echo .
echo %date% @ %time%
set /a a=11 & set /a b=4 & set /a c=115
echo .
set /a s+=1
echo a==%a%, b==%b%, c==%c%
call :funct1 a,b,c
goto start
::::::::::::::::::::::::::::::::::::::::::::
:funct1
set g=%~2
set h=%~3
call :funct2 z,x,%g%,%h%
call :funct4 %z%,%x%,%g%,%h%
exit /b %errorlevel%
:funct2 <ReturnVar1, ReturnVar2, Arg_g, Arg_h>
set /a g=%~3 & set /a h=%~4
set /a r=1
set /a d=1000
if %g% neq 0 if %g% gtr 0 set /a r=(%d%*%~4/%~3)
::: Return z & x as %~1 & %~2
call :funct3 z,x,r
::::::::::::::::::::::::::::
set "%~1=%z%"
set "%~2=%x%"
exit /b %errorlevel%
::: Calc :::
:funct3 <rr,mm,r>
set /a r=%~3
set bats=C:\Users\JpE\Documents\AAA Sync2Laptop\Batch Files\BCS-Suite
set strlen="%bats%\string_length.bat"
call %strlen% len,r
REM echo length of %r% is %len%
::: 1000 so 3 digits accuracy right of decimal point.
set /a lngt=3
set /a digi=(%len%-%lngt%)
echo * & echo . & echo len==%len% digi==%digi%
:::::::::::::::::::::::::
REM set /a mm=%r:~2,3%
call set /a mm=(%%r:~%digi%,%lngt%%%)
:::::::::::::::::::::::::
set /a rr=(%r%/1000)
::: Okay to here :::
echo sending back from funct3: rr==%rr%, mm==%mm%
set "%~1=%rr%"
set "%~2=%mm%"
exit /b %errorlevel%
::: Display :::
:funct4 <rr,mm,a,b,c>
echo .
echo A == %a%
echo B == %b%
echo C == %c%
echo .
echo C / B == %rr%.%mm%
echo .
pause
echo .
echo .
exit /b %errorlevel%
:return
echo Program Terminating
pause
|
Using % with variables inside function call
|
Simply put, it's
set /a mm=%r:~2,3%
BUT, the 2 is codified as set /a d=2 and the 3 is codified as set /a l=3.
So, now how do I write the first expression using the codified variables?
i.e. set /a mm=%r:~%d%,%l%% doesn't work. What's the gimmick?
I've tried...
set /a mm="%r:~(%%d),%%l%" and all kinds of other codifications but the % usage throws me.
|
[
"@echo off\n::: Experimental Module\nset /a s=0\ntitle %date% @ %time% playtime.bat by -JpE-\n\n:start\nif %s% geq 2 cls & set /a s=0\necho .\necho .\necho %date% @ %time%\nset /a a=11 & set /a b=4 & set /a c=115\necho .\nset /a s+=1\necho a==%a%, b==%b%, c==%c%\ncall :funct1 a,b,c\ngoto start\n\n::::::::::::::::::::::::::::::::::::::::::::\n\n\n:funct1\nset g=%~2\nset h=%~3\ncall :funct2 z,x,%g%,%h%\ncall :funct4 %z%,%x%,%g%,%h%\nexit /b %errorlevel%\n\n\n:funct2 <ReturnVar1, ReturnVar2, Arg_g, Arg_h>\nset /a g=%~3 & set /a h=%~4\nset /a r=1\nset /a d=1000\n\nif %g% neq 0 if %g% gtr 0 set /a r=(%d%*%~4/%~3)\n\n::: Return z & x as %~1 & %~2\ncall :funct3 z,x,r\n::::::::::::::::::::::::::::\n\nset \"%~1=%z%\"\nset \"%~2=%x%\"\nexit /b %errorlevel%\n\n\n::: Calc :::\n:funct3 <rr,mm,r>\nset /a r=%~3\n\nset bats=C:\\Users\\JpE\\Documents\\AAA Sync2Laptop\\Batch Files\\BCS-Suite\nset strlen=\"%bats%\\string_length.bat\"\ncall %strlen% len,r \nREM echo length of %r% is %len%\n::: 1000 so 3 digits accuracy right of decimal point.\nset /a lngt=3\nset /a digi=(%len%-%lngt%)\necho * & echo . & echo len==%len% digi==%digi%\n:::::::::::::::::::::::::\nREM set /a mm=%r:~2,3%\ncall set /a mm=(%%r:~%digi%,%lngt%%%)\n:::::::::::::::::::::::::\nset /a rr=(%r%/1000)\n\n::: Okay to here :::\necho sending back from funct3: rr==%rr%, mm==%mm%\nset \"%~1=%rr%\"\nset \"%~2=%mm%\"\nexit /b %errorlevel%\n\n\n\n::: Display :::\n:funct4 <rr,mm,a,b,c>\necho .\necho A == %a%\necho B == %b%\necho C == %c%\n\necho .\necho C / B == %rr%.%mm%\necho .\npause\necho .\necho .\nexit /b %errorlevel%\n\n\n:return\n\necho Program Terminating\npause\n\n"
] |
[
0
] |
[] |
[] |
[
"batch_file",
"cmd",
"variables",
"windows"
] |
stackoverflow_0074663581_batch_file_cmd_variables_windows.txt
|
Q:
Why is the fixed font size on canvas elements ignored and gets bigger in a larger canvas?
My code aims to creates different width <canvas> elements and sets font to 20px for all, but the result shows the font getting bigger in larger windows!
Why? I’ve not instructed it to use different size fonts.
var n = 0,
wind = 30,
canv = [],
ct = []
for (n = 0; n < wind; n++) {
canv[n] = document.createElement('canvas');
canv[n].id = "C" + n;
canv[n].style.width = 30 * n + "px";
canv[n].style.height = 30 * n + "px";
canv[n].style.top = 5 * n + "px";
canv[n].style.left = 5 * n + "px";
canv[n].style.zIndex = n;
canv[n].style.position = "absolute";
canv[n].style.border = "2px solid";
document.body.appendChild(canv[n]);
ct[n] = canv[n].getContext("2d");
ct[n].font = "20px Arial"
ct[n].fillText(n, 20, 20)
}
|
Why is the fixed font size on canvas elements ignored and gets bigger in a larger canvas?
|
My code aims to creates different width <canvas> elements and sets font to 20px for all, but the result shows the font getting bigger in larger windows!
Why? I’ve not instructed it to use different size fonts.
var n = 0,
wind = 30,
canv = [],
ct = []
for (n = 0; n < wind; n++) {
canv[n] = document.createElement('canvas');
canv[n].id = "C" + n;
canv[n].style.width = 30 * n + "px";
canv[n].style.height = 30 * n + "px";
canv[n].style.top = 5 * n + "px";
canv[n].style.left = 5 * n + "px";
canv[n].style.zIndex = n;
canv[n].style.position = "absolute";
canv[n].style.border = "2px solid";
document.body.appendChild(canv[n]);
ct[n] = canv[n].getContext("2d");
ct[n].font = "20px Arial"
ct[n].fillText(n, 20, 20)
}
|
[] |
[] |
[
"The reason that the font size appears to be increasing in larger windows is that the font size is specified in pixels (px), which is a fixed unit of measurement. This means that the size of the font will not change relative to the size of the window.\nOne possible solution to this issue is to specify the font size using a relative unit of measurement, such as percentage (%), em, or rem. These units of measurement will scale the font size relative to the parent element, which in this case would be the canvas element.\nHere is an example of how you could modify your code to use a relative unit of measurement for the font size:\nvar n=0, wind=30, canv=[], ct=[]\nfor (n=0; n<wind; n++){\n canv[n] = document.createElement('canvas');\n canv[n].id = \"C\"+n;\n canv[n].style.width = 30*n+\"px\";\n canv[n].style.height = 30*n+\"px\";\n canv[n].style.top = 5*n + \"px\";\n canv[n].style.left = 5*n + \"px\";\n canv[n].style.zIndex = n;\n canv[n].style.position = \"absolute\";\n canv[n].style.border = \"2px solid\";\n \n document.body.appendChild(canv[n]);\n ct[n] = canv[n].getContext(\"2d\");\n ct[n].font=\"2em Arial\" // Use a relative unit of measurement for the font size\n ct[n].fillText(n,20,20)\n}\n\nIn the example above, the font size is set to 2em, which means that it will be twice the size of the default font size of the parent element (i.e. the canvas element). This means that the font size will scale proportionally with the size of the canvas element.\nHope this helps!\n"
] |
[
-1
] |
[
"css",
"font_size",
"html",
"html5_canvas",
"javascript"
] |
stackoverflow_0074664581_css_font_size_html_html5_canvas_javascript.txt
|
Q:
CSS filter making element dissapear
I haven't found any good answers for this so I'm asking here; I have buttons on my website that i'm trying to mimic an OS X Lion style with, and I'm using keyframes to make an active button have a sort-of glow effect. However, using filter: brightness(x) for some reason is making my element disappear. Could it be because I'm using pseudo elements for the border? Or something else.
I tried using CSS filters to brighten a background gradient (I tried an image as well with the same results) and it ended up making the element disappear and show me my pseudo element (also I can't find the code snippet button anymore, is it gone?)
button {
padding: 5px 16px;
border-radius: 4px;
outline: none;
background: linear-gradient(to bottom, #fff 0 30%, #e2e2e2 70% 100%);
color: black;
border: none;
position: relative;
transform-style: preserve-3d;
letter-spacing: -0.3px;
text-shadow: -0.5px -0.5px 1px rgba(0, 0, 0, 0.1);
transition: 0s;
font-family: "Lucida Grande", sans-serif;
transform: scale(4);
margin: 200px;
}
button::after {
content: '';
position: absolute;
background: rgb(120, 120, 120);
width: calc(100% + 2px);
height: calc(100% + 2px);
left: -1px;
top: -1px;
transform: translateZ(-1px);
border-radius: 5px;
opacity: 1;
z-index: -1;
}
button:active {
background: linear-gradient(to bottom, rgb(188, 206, 233) 0, rgb(115, 158, 227) 50%, rgb(92, 145, 226) 51%, rgb(174, 215, 231) 100%);
animation: glow 1s infinite;
}
button:active::after {
content: '';
position: absolute;
background: linear-gradient(to bottom, rgb(89, 92, 169) 0 40%, rgb(80, 89, 142) 60% 100%);
width: calc(100% + 2px);
height: calc(100% + 2px);
left: -1px;
top: -1px;
transform: translateZ(-1px);
border-radius: 5px;
opacity: 1;
}
@keyframes glow {
0% {
filter: brightness(1.1);
}
50% {
filter: brightness(1.2);
}
100% {
filter: brightness(1.1);
}
}
<button>Button</button>
JSFiddle if there isn't a run snippet button
A:
According to this answer, it seems that this is because filter overrides transform-style: preserve-3d, which then causes translateZ(-1px) to have unexpected result in this use case.
This could be avoided by refactor the styles without 3D transforms such as translateZ(-1px). While it might not be perfect, here is a possible example with the workaround.
This example moved styles on the original ::after to a ::before, and moved the button background style to a new ::after, as an alternative approach to the use of translateZ(-1px) to display the button background.
Hope this will help.
Example:
button {
padding: 5px 16px;
border-radius: 4px;
outline: none;
color: black;
border: none;
position: relative;
letter-spacing: -0.3px;
text-shadow: -0.5px -0.5px 1px rgba(0, 0, 0, 0.1);
transition: 0s;
font-family: "Lucida Grande", sans-serif;
transform: scale(2);
margin: 50px 100px;
}
button:active {
animation: glow 1s infinite;
}
button::before {
content: '';
position: absolute;
background: rgb(120, 120, 120);
width: calc(100% + 2px);
height: calc(100% + 2px);
left: -0.625px;
top: -0.625px;
border-radius: 5px;
opacity: 1;
z-index: -1;
}
button:active::before {
content: '';
position: absolute;
background: linear-gradient(to bottom, rgb(89, 92, 169) 0 40%, rgb(80, 89, 142) 60% 100%);
width: calc(100% + 2px);
height: calc(100% + 2px);
left: -0.625px;
top: -0.625px;
border-radius: 5px;
opacity: 1;
}
button::after {
content: '';
position: absolute;
inset: 0;
border-radius: 4px;
outline: none;
background: linear-gradient(to bottom, #fff 0 30%, #e2e2e2 70% 100%);
border: none;
transition: 0s;
z-index: -1;
}
button:active::after {
background: linear-gradient(to bottom, rgb(188, 206, 233) 0, rgb(115, 158, 227) 50%, rgb(92, 145, 226) 51%, rgb(174, 215, 231) 100%);
}
@keyframes glow {
0% {
filter: brightness(1.1);
}
50% {
filter: brightness(1.2);
}
100% {
filter: brightness(1.1);
}
}
<button>Button</button>
|
CSS filter making element dissapear
|
I haven't found any good answers for this so I'm asking here; I have buttons on my website that i'm trying to mimic an OS X Lion style with, and I'm using keyframes to make an active button have a sort-of glow effect. However, using filter: brightness(x) for some reason is making my element disappear. Could it be because I'm using pseudo elements for the border? Or something else.
I tried using CSS filters to brighten a background gradient (I tried an image as well with the same results) and it ended up making the element disappear and show me my pseudo element (also I can't find the code snippet button anymore, is it gone?)
button {
padding: 5px 16px;
border-radius: 4px;
outline: none;
background: linear-gradient(to bottom, #fff 0 30%, #e2e2e2 70% 100%);
color: black;
border: none;
position: relative;
transform-style: preserve-3d;
letter-spacing: -0.3px;
text-shadow: -0.5px -0.5px 1px rgba(0, 0, 0, 0.1);
transition: 0s;
font-family: "Lucida Grande", sans-serif;
transform: scale(4);
margin: 200px;
}
button::after {
content: '';
position: absolute;
background: rgb(120, 120, 120);
width: calc(100% + 2px);
height: calc(100% + 2px);
left: -1px;
top: -1px;
transform: translateZ(-1px);
border-radius: 5px;
opacity: 1;
z-index: -1;
}
button:active {
background: linear-gradient(to bottom, rgb(188, 206, 233) 0, rgb(115, 158, 227) 50%, rgb(92, 145, 226) 51%, rgb(174, 215, 231) 100%);
animation: glow 1s infinite;
}
button:active::after {
content: '';
position: absolute;
background: linear-gradient(to bottom, rgb(89, 92, 169) 0 40%, rgb(80, 89, 142) 60% 100%);
width: calc(100% + 2px);
height: calc(100% + 2px);
left: -1px;
top: -1px;
transform: translateZ(-1px);
border-radius: 5px;
opacity: 1;
}
@keyframes glow {
0% {
filter: brightness(1.1);
}
50% {
filter: brightness(1.2);
}
100% {
filter: brightness(1.1);
}
}
<button>Button</button>
JSFiddle if there isn't a run snippet button
|
[
"According to this answer, it seems that this is because filter overrides transform-style: preserve-3d, which then causes translateZ(-1px) to have unexpected result in this use case.\nThis could be avoided by refactor the styles without 3D transforms such as translateZ(-1px). While it might not be perfect, here is a possible example with the workaround.\nThis example moved styles on the original ::after to a ::before, and moved the button background style to a new ::after, as an alternative approach to the use of translateZ(-1px) to display the button background.\nHope this will help.\nExample:\n\n\nbutton {\n padding: 5px 16px;\n border-radius: 4px;\n outline: none;\n color: black;\n border: none;\n position: relative;\n letter-spacing: -0.3px;\n text-shadow: -0.5px -0.5px 1px rgba(0, 0, 0, 0.1);\n transition: 0s;\n font-family: \"Lucida Grande\", sans-serif;\n transform: scale(2);\n margin: 50px 100px;\n}\n\nbutton:active {\n animation: glow 1s infinite;\n}\n\nbutton::before {\n content: '';\n position: absolute;\n background: rgb(120, 120, 120);\n width: calc(100% + 2px);\n height: calc(100% + 2px);\n left: -0.625px;\n top: -0.625px;\n border-radius: 5px;\n opacity: 1;\n z-index: -1;\n}\n\nbutton:active::before {\n content: '';\n position: absolute;\n background: linear-gradient(to bottom, rgb(89, 92, 169) 0 40%, rgb(80, 89, 142) 60% 100%);\n width: calc(100% + 2px);\n height: calc(100% + 2px);\n left: -0.625px;\n top: -0.625px;\n border-radius: 5px;\n opacity: 1;\n}\n\nbutton::after {\n content: '';\n position: absolute;\n inset: 0;\n border-radius: 4px;\n outline: none;\n background: linear-gradient(to bottom, #fff 0 30%, #e2e2e2 70% 100%);\n border: none;\n transition: 0s;\n z-index: -1;\n}\n\nbutton:active::after {\n background: linear-gradient(to bottom, rgb(188, 206, 233) 0, rgb(115, 158, 227) 50%, rgb(92, 145, 226) 51%, rgb(174, 215, 231) 100%);\n}\n\n@keyframes glow {\n 0% {\n filter: brightness(1.1);\n }\n 50% {\n filter: brightness(1.2);\n }\n 100% {\n filter: brightness(1.1);\n }\n}\n<button>Button</button>\n\n\n\n"
] |
[
0
] |
[] |
[] |
[
"animation",
"button",
"css",
"filter",
"html"
] |
stackoverflow_0074663883_animation_button_css_filter_html.txt
|
Q:
Laravel project auto refresh after changes
Does anyone know if there is a way to run the code changes in a Laravel project without refreshing the page every time.
I know that to see the changes I need to
php artisan serve
but I do it every time and it is kind of frustrating.
Thank you anyways.
A:
You can achieve this with Laravel Mix.
According to this part of the documentation, you need to edit your webpack.mix.js file, and add this to the end:
mix.browserSync('127.0.0.1:8000');
It needs to match to the output of the php artisan serve command, where you found a line something like this:
Laravel development server started: <http://127.0.0.1:8000>
After this, you have to run the php artisan serve, and the npm run watch command simultaneously. You must leave to run both commands while you edit your files.
Note: The first time you run the npm run watch, it installs additional components. But the command output is quite clear on that. If everything is in order, Laravel Mix automatically opens your browser with http://localhost:3000, or something like this.
A:
add in webpack.max.js file in laravel
mix.browserSync('127.0.0.1:8000');
then run this command
> npm install browser-sync [email protected] --save-dev --production=false
after this run npm run watch
> Browsersync automatic run your port 3000
A:
To achieve this you can use Laravel Mix
Ensure that Node.js and NPM are installed:
run node -v and npm -v.
Install Laravel Mix
npm install.
Install browser-sync and browser-sync-webpack-plugin
npm install browser-sync browser-sync-webpack-plugin --save-dev --production=false
Open webpack.mix.js and add this line
mix.browserSync('127.0.0.1:8000');.
Run Project with these two commands: The npm run watch command will continue running in your terminal and watch all relevant CSS and JavaScript files for changes. Webpack will automatically recompile your assets when it detects a change
php artisan serve. and then npm run watch.
A:
First make sure you install nodejs, After that install laravel-mix
npm install --save-dev laravel-mix
create webpack.mix.js file in root folder for your project and add to it
const mix =require('laravel-mix')
mix.browserSync('127.0.0.1:8000');
Open package.json file and add to script section:
"scripts": {
"watch": "mix watch"
}
Run laravel project
php artisan serve
To update laravel project auto when you make changes run in another terminal:
npm run watch
Updated from Laravel 9.x
you can use vite instead of laravel-mix, you should run this command to install vite:
npm install
Without any configuration, The next line of code will include auto in master page, If you want to include in another master page like admin, you can write it to auto refresh when make changes:
@vite(['resources/sass/app.scss', 'resources/js/app.js'])
After installing vite, run this command
npm run dev
And run
php artisan serve
For more information, view docs
|
Laravel project auto refresh after changes
|
Does anyone know if there is a way to run the code changes in a Laravel project without refreshing the page every time.
I know that to see the changes I need to
php artisan serve
but I do it every time and it is kind of frustrating.
Thank you anyways.
|
[
"You can achieve this with Laravel Mix.\nAccording to this part of the documentation, you need to edit your webpack.mix.js file, and add this to the end:\nmix.browserSync('127.0.0.1:8000');\n\nIt needs to match to the output of the php artisan serve command, where you found a line something like this:\nLaravel development server started: <http://127.0.0.1:8000>\n\nAfter this, you have to run the php artisan serve, and the npm run watch command simultaneously. You must leave to run both commands while you edit your files.\nNote: The first time you run the npm run watch, it installs additional components. But the command output is quite clear on that. If everything is in order, Laravel Mix automatically opens your browser with http://localhost:3000, or something like this.\n",
"add in webpack.max.js file in laravel \nmix.browserSync('127.0.0.1:8000');\n\nthen run this command \n> npm install browser-sync [email protected] --save-dev --production=false\n\nafter this run npm run watch \n> Browsersync automatic run your port 3000\n\n",
"To achieve this you can use Laravel Mix\n\nEnsure that Node.js and NPM are installed:\n\n\nrun node -v and npm -v.\n\n\nInstall Laravel Mix\n\n\nnpm install.\n\n\nInstall browser-sync and browser-sync-webpack-plugin\n\n\nnpm install browser-sync browser-sync-webpack-plugin --save-dev --production=false\n\n\nOpen webpack.mix.js and add this line\n\n\nmix.browserSync('127.0.0.1:8000');.\n\n\nRun Project with these two commands: The npm run watch command will continue running in your terminal and watch all relevant CSS and JavaScript files for changes. Webpack will automatically recompile your assets when it detects a change\n\n\nphp artisan serve. and then npm run watch.\n\n",
"First make sure you install nodejs, After that install laravel-mix\nnpm install --save-dev laravel-mix\n\ncreate webpack.mix.js file in root folder for your project and add to it\nconst mix =require('laravel-mix')\nmix.browserSync('127.0.0.1:8000');\n\nOpen package.json file and add to script section:\n \"scripts\": {\n \"watch\": \"mix watch\"\n }\n\nRun laravel project\nphp artisan serve\n\nTo update laravel project auto when you make changes run in another terminal:\nnpm run watch \n\nUpdated from Laravel 9.x\nyou can use vite instead of laravel-mix, you should run this command to install vite:\nnpm install\n\nWithout any configuration, The next line of code will include auto in master page, If you want to include in another master page like admin, you can write it to auto refresh when make changes:\n@vite(['resources/sass/app.scss', 'resources/js/app.js'])\n\nAfter installing vite, run this command\nnpm run dev\n\nAnd run\nphp artisan serve\n\nFor more information, view docs\n"
] |
[
42,
5,
0,
0
] |
[] |
[] |
[
"browser",
"laravel"
] |
stackoverflow_0049392001_browser_laravel.txt
|
Q:
while adding event in React it not working properly
I add onclick event in button tag but when we see it in html element it did not render even only render button tag element and because of that click event is not fired on clicking the button
I add onclick event in button tag but when we see it in html element it did not render even only render button tag element and because of that click event is not fired on clicking the button
below is my code
class Admin extends React.Component{
constructor(){
super();
this.state={
buttonText:"Sign In"
}
}
render(){
return(
<>
<button onClick={this.signOut}>{this.state.buttonText}</button>
</>
)
}
// signOut(){
// this.setState({
// buttonText:"Sign out"
// })
// console.log("click");
// }
signout=()=>{
// alert("click");
// this.setState({
// buttonText:"Sign out"
// })
console.log("hii");
}
}
export default Admin;
and this is html that rendered
Sign in
A:
Here are a few pointer
the code does not work because the case if different
onClick={this.signOut} not equal onClick={this.signout}
bind this to the function to set state
class Admin extends React.Component {
constructor() {
super();
this.state = {
buttonText: "Sign In"
};
// bind to this
this.signOut = this.signOut.bind(this);
}
render() {
return (
<>
<button onClick={this.signOut}>{this.state.buttonText}</button>
</>
);
}
signOut() {
this.setState({
buttonText: "Sign out"
});
console.log("click");
}
}
Read more about class components or even better start with function component
Hope it helps, Happy coding
|
while adding event in React it not working properly
|
I add onclick event in button tag but when we see it in html element it did not render even only render button tag element and because of that click event is not fired on clicking the button
I add onclick event in button tag but when we see it in html element it did not render even only render button tag element and because of that click event is not fired on clicking the button
below is my code
class Admin extends React.Component{
constructor(){
super();
this.state={
buttonText:"Sign In"
}
}
render(){
return(
<>
<button onClick={this.signOut}>{this.state.buttonText}</button>
</>
)
}
// signOut(){
// this.setState({
// buttonText:"Sign out"
// })
// console.log("click");
// }
signout=()=>{
// alert("click");
// this.setState({
// buttonText:"Sign out"
// })
console.log("hii");
}
}
export default Admin;
and this is html that rendered
Sign in
|
[
"Here are a few pointer\nthe code does not work because the case if different\nonClick={this.signOut} not equal onClick={this.signout}\nbind this to the function to set state\nclass Admin extends React.Component {\n constructor() {\n super();\n this.state = {\n buttonText: \"Sign In\"\n };\n // bind to this \n this.signOut = this.signOut.bind(this);\n }\n\n render() {\n return (\n <>\n <button onClick={this.signOut}>{this.state.buttonText}</button>\n </>\n );\n }\n signOut() {\n this.setState({\n buttonText: \"Sign out\"\n });\n console.log(\"click\");\n }\n}\n\nRead more about class components or even better start with function component\nHope it helps, Happy coding\n"
] |
[
0
] |
[] |
[] |
[
"events",
"reactjs"
] |
stackoverflow_0074663427_events_reactjs.txt
|
Q:
Reset app password which was saved initially
In my project by default bitbucket app password is setup i want to remove it so that if i push the code it should ask me app password every time.
Any solution to fix this issue.
A:
Check if your app password is stored by a git credential helper:
(assuming your git remote -v shows an HTTPS URL)
git config --global credential.helper
xxx
# replace xxx by the actual value from the previous command
print "host=bitbucket.org\nprotocol=https" | git credential-xxx get
# if you see the app password, remove it with:
print "host=bitbucket.org\nprotocol=https\nusername=you" | git credential-xxx erase
# (replace you by your BitBucket account)
|
Reset app password which was saved initially
|
In my project by default bitbucket app password is setup i want to remove it so that if i push the code it should ask me app password every time.
Any solution to fix this issue.
|
[
"Check if your app password is stored by a git credential helper:\n(assuming your git remote -v shows an HTTPS URL)\ngit config --global credential.helper\nxxx\n\n# replace xxx by the actual value from the previous command\nprint \"host=bitbucket.org\\nprotocol=https\" | git credential-xxx get\n\n# if you see the app password, remove it with:\nprint \"host=bitbucket.org\\nprotocol=https\\nusername=you\" | git credential-xxx erase\n# (replace you by your BitBucket account)\n\n"
] |
[
0
] |
[] |
[] |
[
"bitbucket",
"git"
] |
stackoverflow_0074664327_bitbucket_git.txt
|
Q:
The way for slice to expend itself in go
I am new to go and now evaluate a demo function about slice with Fibonacci sequence
package main
import "fmt"
func fbn(n int) []uint64 {
fbnSlice := make([]uint64, n)
fbnSlice[0] = 1
fbnSlice[1] = 1
for i := 2; i < n; i++ {
fbnSlice[i] = fbnSlice[i-1] + fbnSlice[i-2]
}
return fbnSlice
}
func main() {
fnbSlice := fbn(5)
fmt.Println(fnbSlice)
}
It will print "[1 1 2 3 5]"
My doubt is how the slice add it's len to 5, thanks!
A:
make([]uint64, n)
Will make a slice of length n, filled with zeros. Hence, fbn(5) will produce a slice of length 5.
A:
In the code, the function fbn is defined with an input parameter n which determines the length of the slice. The slice is created with a length of n using the make function and the first two elements of the slice are initialized to 1. Then, in the for loop, the subsequent elements are calculated by summing the previous two elements in the slice. Finally, the completed slice is returned.
In the main function, the fbn function is called with an input of 5, so the resulting slice will have a length of 5. This is why the output is [1 1 2 3 5] - it is the first 5 elements of the Fibonacci sequence.
|
The way for slice to expend itself in go
|
I am new to go and now evaluate a demo function about slice with Fibonacci sequence
package main
import "fmt"
func fbn(n int) []uint64 {
fbnSlice := make([]uint64, n)
fbnSlice[0] = 1
fbnSlice[1] = 1
for i := 2; i < n; i++ {
fbnSlice[i] = fbnSlice[i-1] + fbnSlice[i-2]
}
return fbnSlice
}
func main() {
fnbSlice := fbn(5)
fmt.Println(fnbSlice)
}
It will print "[1 1 2 3 5]"
My doubt is how the slice add it's len to 5, thanks!
|
[
"make([]uint64, n)\n\nWill make a slice of length n, filled with zeros. Hence, fbn(5) will produce a slice of length 5.\n",
"In the code, the function fbn is defined with an input parameter n which determines the length of the slice. The slice is created with a length of n using the make function and the first two elements of the slice are initialized to 1. Then, in the for loop, the subsequent elements are calculated by summing the previous two elements in the slice. Finally, the completed slice is returned.\nIn the main function, the fbn function is called with an input of 5, so the resulting slice will have a length of 5. This is why the output is [1 1 2 3 5] - it is the first 5 elements of the Fibonacci sequence.\n"
] |
[
0,
0
] |
[] |
[] |
[
"go",
"slice"
] |
stackoverflow_0074664498_go_slice.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.