content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Kivy showing a black screen when trying to use kv file?
So I want to do the styling of my Kivy app in a external .kv file, but when I run the main code, nothing appears to the black Kivy window.
Here's my main file called main.py
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
class MyGrid... | Kivy showing a black screen when trying to use kv file? | So I want to do the styling of my Kivy app in a external .kv file, but when I run the main code, nothing appears to the black Kivy window.
Here's my main file called main.py
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
class MyGrid(Widget):
pass
class MyApp(App):
def build(self)... | [
"In order to load widgets from a separate kivy file, you need to import Builder:\nfrom kivy.lang.builder import Builder\nBuilder.load_file('my.kv')\n\nor in .py file\nBuilder.load_string(\"\"\"\n<MyGrid>:\n Label:\n text: \"example example\"\n\"\"\")\n\n",
"The kivy file name should always be the App cl... | [
2,
0
] | [] | [] | [
"kivy",
"kivy_language",
"python",
"user_interface"
] | stackoverflow_0068575800_kivy_kivy_language_python_user_interface.txt |
Q:
Pandas - Remove first occurrence of value if it matches certain condition
I am looking to remove END from 'Task' column if there is no START before it. The data can be grouped by 'Session' and if the first occurance of the 'Task' is END, then I want to replace that specific occurrence with nAn value.
Session
Task... | Pandas - Remove first occurrence of value if it matches certain condition | I am looking to remove END from 'Task' column if there is no START before it. The data can be grouped by 'Session' and if the first occurance of the 'Task' is END, then I want to replace that specific occurrence with nAn value.
Session
Task
0
1
1
1
END
2
1
3
1
START
4
1
5
1
END
6
2
7
2
START
... | [
"Using Dataframe apply with a custom function to remove unmatched \"END\"\nCode\ndef remove_unmatched(x):\n ' removes \"END\" value when not preceeded by \"START\" '\n preceeded = False\n result = []\n for z in x:\n if z == \"START\":\n preceeded = True # Set prec... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074320765_dataframe_pandas_python.txt |
Q:
How to get another column in a dataframe filled with values from another columns based on multiple conditions?
I have a dataframe with 6 columns:
Id count1 Value1 count2 Value2 Value3
1 1200 3 2000 4 6
2 100 2 400 5 8
3 800 4 1100 ... | How to get another column in a dataframe filled with values from another columns based on multiple conditions? | I have a dataframe with 6 columns:
Id count1 Value1 count2 Value2 Value3
1 1200 3 2000 4 6
2 100 2 400 5 8
3 800 4 1100 7 9
I need to get a new column with following conditions:
if count 1 > 1000, new column should take value... | [
"you can use np.select()\nimport numpy as np\n\ncondlist=[(df['count1'] > 1000),(df['count2'] > 1000) & (df['count1'] <= 1000)]\nchoicelist=[df['Value1'], df['Value2']]\ndefault=df['Value3']\n\ndf['new_column']=np.select(condlist,choicelist,default)\n\n"
] | [
1
] | [] | [] | [
"data_science",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074320529_data_science_dataframe_numpy_pandas_python.txt |
Q:
How to randomly choose something from a list then remove it while in a function
from random import choice
from random import choices
from random import shuffle
wkd = ["Razvan", "Vali", "Stefan", "Dontu","Abel", "David P.", "Beni N."]
cls = ["Angelo", "Dragos", "Beni D.", "Andy", "Vlad T.", "Dani", "Ruben", "Geor... | How to randomly choose something from a list then remove it while in a function | from random import choice
from random import choices
from random import shuffle
wkd = ["Razvan", "Vali", "Stefan", "Dontu","Abel", "David P.", "Beni N."]
cls = ["Angelo", "Dragos", "Beni D.", "Andy", "Vlad T.", "Dani", "Ruben", "George", "Sebi Br."]
restul = ["Claudiu", "Cipri", "David", "Rares N.", "Vlad P.", "Mari... | [
"When you do your random choice, you pick from the sum of lists (which is ok). When you come to remove the chosen item, you catch errors, which then may mask the actual removal. You probably need a function which tried each container in turn:\ndef remove_element(containers, element):\n for c in containers:\n ... | [
1
] | [] | [] | [
"list",
"python",
"random"
] | stackoverflow_0074321482_list_python_random.txt |
Q:
How to implement setData on PyQt5 QAbstractTableModel with QSqlRelationalTableModel
I am newbie with Pyqt and need help with setting setData on QAbstractTableModel with QSqlRelationalTableModel table model
I have this simple code and I dont now how to implement setData function.
I can't set value to field.
I'm get... | How to implement setData on PyQt5 QAbstractTableModel with QSqlRelationalTableModel | I am newbie with Pyqt and need help with setting setData on QAbstractTableModel with QSqlRelationalTableModel table model
I have this simple code and I dont now how to implement setData function.
I can't set value to field.
I'm getting TypeError: 'QSqlRelationalTableModel' object is not subscriptable error.
Also, how t... | [
"The \"object is not subscriptable\" error means that you're trying to access an item or index for an object that doesn't provide such interface.\n>>> obj = 100\n>>> print(obj[2])\n\nTypeError: 'int' object is not subscriptable\n\nself._model[index.row()][index.column()] cannot work because Qt models are not lists ... | [
0,
0
] | [] | [] | [
"pyqt5",
"python",
"qabstracttablemodel"
] | stackoverflow_0074318100_pyqt5_python_qabstracttablemodel.txt |
Q:
Simplest way to retrieve a Job results?
I have a python program launching a batch job. The job outputs a json file, I'd like to know what is the easiest way to get this result back to the python program that launched it.
So far I thought of these solutions:
Upload the json file to S3 (pretty heavy)
Display it in... | Simplest way to retrieve a Job results? | I have a python program launching a batch job. The job outputs a json file, I'd like to know what is the easiest way to get this result back to the python program that launched it.
So far I thought of these solutions:
Upload the json file to S3 (pretty heavy)
Display it in the pod logs then read the logs from the pyt... | [
"An easy way not involving any other databases/pods is to run the first pod as an init container, mount a volume that is shared in both containers and use the JSON file in the next python program. (Also, this approach does not need a persistent volume, just a shared one), see this example:\nhttps://kubernetes.io/do... | [
1
] | [] | [] | [
"amazon_eks",
"kubernetes",
"kubernetes_jobs",
"kubernetes_pod",
"python"
] | stackoverflow_0074313839_amazon_eks_kubernetes_kubernetes_jobs_kubernetes_pod_python.txt |
Q:
Why does this error show up in this case but not the other?
def biggestWithPos(A):
answer = 0
for i in A:
if i > answer:
answer = i
return (answer)
Why is it that when I change answer = i to answer = A[i] I get the error: list index out of range?
A:
In this:
for i in A:
i is not... | Why does this error show up in this case but not the other? | def biggestWithPos(A):
answer = 0
for i in A:
if i > answer:
answer = i
return (answer)
Why is it that when I change answer = i to answer = A[i] I get the error: list index out of range?
| [
"In this:\nfor i in A:\n\ni is not the index but rather the element in A, which is presumably a list.\nIf A were [4, 5, 6], then doing this you'd be trying to access A[4] on the first iteration, which is an out of range index.\n",
"In Python, when you are inside a for loop like for i in A, i is not the index of t... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074321572_python.txt |
Q:
Python: how to dynamically add a number to the end of the name of a list
In python I am appending elements to a list. The element name I am getting from an input file, so the element_name is an unknown. I would like to create a new list by adding a number to the end of the original list (dyn_list1) or even by usin... | Python: how to dynamically add a number to the end of the name of a list | In python I am appending elements to a list. The element name I am getting from an input file, so the element_name is an unknown. I would like to create a new list by adding a number to the end of the original list (dyn_list1) or even by using one of the elements in the list (element_name). How can this be achieved?
dy... | [
"my_list = [\"something\"]\n\ng = globals()\nfor i in range(1, 5):\n g['dynamiclist_{0}'.format(i)] = my_list\n\nprint(dynamiclist_1)\nprint(dynamiclist_2)\nprint(dynamiclist_3)\nprint(dynamiclist_4)\n\n\nsomething like that ?\n\n",
"I'm not sure I understand correctly, but I think you want to add the dat... | [
2,
0,
0
] | [] | [] | [
"append",
"dynamic",
"element",
"list",
"python"
] | stackoverflow_0074310621_append_dynamic_element_list_python.txt |
Q:
Pygame segmentation fault with import depending on position in code?
I know these segmentation fault questions are common, but I couldn't find answer and I am pulling my hair out as the code works without issue in some parts of the code, but not others or in some cases it works the first time then, the next day, i... | Pygame segmentation fault with import depending on position in code? | I know these segmentation fault questions are common, but I couldn't find answer and I am pulling my hair out as the code works without issue in some parts of the code, but not others or in some cases it works the first time then, the next day, it falls over.
Basically, I am importing spritesheets for a simply pygame g... | [
"The likely problem is that you are doing your import before you have called pygame.init(), so pygame has not been initialized.\nConsider doing this in your second file:\nfrom spritesheets import Spritesheet\n\ndef get_sprites():\n return [\n Spritesheet('../graphics/player/players.png'),\n Sprites... | [
0
] | [] | [] | [
"import",
"pygame",
"python",
"segmentation_fault"
] | stackoverflow_0074319757_import_pygame_python_segmentation_fault.txt |
Q:
Select Python interpreter does not work in VScode
I have installed the first Python interpreter in my Windows PC and the path of python.exe is
C:\Users\myname\AppData\Local\Programs\Python\Python38-32\python.exe
It worked well originally (running, debugging, etc...).
Recently, I tried to install miniconda in my c... | Select Python interpreter does not work in VScode | I have installed the first Python interpreter in my Windows PC and the path of python.exe is
C:\Users\myname\AppData\Local\Programs\Python\Python38-32\python.exe
It worked well originally (running, debugging, etc...).
Recently, I tried to install miniconda in my computer to build different Python environment and the p... | [
"I just reloaded the python extension which you will see when you go to the vscode and the \"python extension\" and in that the below \"reload required\" option will be there just click and then check the \"python interpreter\" in the \"view\" again it will resolve the current issue which you are facing.\n",
"Whe... | [
10,
3,
2,
1,
1,
0,
0
] | [
"The value of python in the terminal is entirely disconnected from what you select in VS Code as the terminal controls what is on PATH. You have two options:\n\nUse a virtual environment so the Python extension can activate your terminal to make python point at what you want\nUse the green Play button to run your c... | [
-1
] | [
"python",
"visual_studio_code"
] | stackoverflow_0061097183_python_visual_studio_code.txt |
Q:
How to combine h5 data numpy arrays based on date in filename?
I have hundreds of .h5 files with dates in their filename (e.g ...20221017...). For each file, I have extracted some parameters into a numpy array of the format
[[param_1a, param_2a...param_5a],
...
[param_1x, param_2x,...param_5x]]
which represe... | How to combine h5 data numpy arrays based on date in filename? | I have hundreds of .h5 files with dates in their filename (e.g ...20221017...). For each file, I have extracted some parameters into a numpy array of the format
[[param_1a, param_2a...param_5a],
...
[param_1x, param_2x,...param_5x]]
which represents data of interest. I want to group the data by month, so instead ... | [
"Ok, here is the beginning of an answer. (I suspect you may have more questions as you work thru the details.)\nThere are several ways to get the filenames. You could put them in a file, but it's easier (and better IMHO) to use the glob.iglob() function. There are 2 examples below that show how to: 1) open each fil... | [
0,
0
] | [] | [] | [
"glob",
"h5py",
"hdf",
"numpy",
"python"
] | stackoverflow_0074111422_glob_h5py_hdf_numpy_python.txt |
Q:
What is the most efficient way to find pattern in inner axis of np array and modify it?
I have a 3d array [[[]]]. I want to look at all the arrays on the last axis or the inner most axis. If they match this pattern [x,x,x,x] I want to change them to [0,0,0,0]. I know what I want to do. I just don't know the most e... | What is the most efficient way to find pattern in inner axis of np array and modify it? | I have a 3d array [[[]]]. I want to look at all the arrays on the last axis or the inner most axis. If they match this pattern [x,x,x,x] I want to change them to [0,0,0,0]. I know what I want to do. I just don't know the most efficient method to do this.
Current Code:
most_common = np.array(stats.mode(img_arr)[0][0][0]... | [
"One way is to subtract your pattern from the last axis and check norm=0:\nimport numpy as np\na = np.arange(3*3*3).reshape(3,3,3)\nb = np.array([0,1,2])\nc = np.array([99,98,97])\nindices = np.sum(np.abs(a-b), axis=2) == 0\na[indices] = c\nprint(a)\n\n"
] | [
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074321713_arrays_numpy_python.txt |
Q:
Why use range(len(n)-1)?
In a lot of the code I've done, in many instances range(len(n)-1) was used such as in the examples below:
To find a number that doubles in a list from another number:
def double(n)
for i in range(len(n)-1):
if n[i]*2 == n[i+1]:
print(n[i+1])
Takes a string and coun... | Why use range(len(n)-1)? | In a lot of the code I've done, in many instances range(len(n)-1) was used such as in the examples below:
To find a number that doubles in a list from another number:
def double(n)
for i in range(len(n)-1):
if n[i]*2 == n[i+1]:
print(n[i+1])
Takes a string and counts the number of times that tw... | [
"Take an example list:\nn = [0,1,2,3,4,5,6,7,8,9]\n\nThe length of this list, len(n) is 10.\nAn example of a case that would require len(n)-1 would be if you are running a process that looks at the adjacent (preceding or the next) element.\nSo for example, lets create a new list, m, that is the sum of the n and n+1... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074321363_python.txt |
Q:
Pandas create a new column based on string-matching values from another column
Is there any way to create a new column based on string-matching values from another column without duplicating the column and replacing the values?
So far this is one solution that I am using:
df = pd.DataFrame({
"Task": ["T1"... | Pandas create a new column based on string-matching values from another column | Is there any way to create a new column based on string-matching values from another column without duplicating the column and replacing the values?
So far this is one solution that I am using:
df = pd.DataFrame({
"Task": ["T1", "T1", "T2", "T3","T3"],
"Complexity": [1, 2, 3, 2, 1],
"Status": [... | [
"like that?\nimport pandas as pd\n\ndf = pd.DataFrame({\n \"Task\": [\"T1\", \"T1\", \"T2\", \"T3\",\"T3\"],\n \"Complexity\": [1, 2, 3, 2, 1],\n \"Status\": [\"OpenA\", \"ClosedB\", \"ClosedC\", \"OpenC\", \"OpenA\"]})\n\ndf['Statno']=df['Status'].replace({'(?i).*Open.*': '1', '(?i).*Close.*' ... | [
0
] | [] | [] | [
"pandas",
"python",
"replace",
"string"
] | stackoverflow_0074321803_pandas_python_replace_string.txt |
Q:
Plotly - change the background color of the html page when doing fig.show()
Is there any way to change the background color of the page that pops up when I do fig.show()?
Currently it's just white. I can change the background color of the plot itself, but not the HTML body.
A:
You can achieve that with paper_bgc... | Plotly - change the background color of the html page when doing fig.show() | Is there any way to change the background color of the page that pops up when I do fig.show()?
Currently it's just white. I can change the background color of the plot itself, but not the HTML body.
| [
"You can achieve that with paper_bgcolor as follows:\nimport plotly.express as px\nfig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])\n\nfig.update_layout(\n paper_bgcolor='rgba(192,192,192,255)',\n plot_bgcolor='rgba(0,204,204,255)'\n)\nfig.show()\n\n\n"
] | [
0
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0073138913_plotly_python.txt |
Q:
Why is the list not altering after operations performed in a function?
def test(nums):
nums = list(set(nums))
nums = [1,2,3,4,1,2,3,4]
test(nums)
print(nums)
[1,2,3,4,1,2,3,4]
I am not able to understand the process. If I do something like
def test(nums):
nums.append(7)
nums = [1,2,3,4,1,2,3,4]
test(num... | Why is the list not altering after operations performed in a function? | def test(nums):
nums = list(set(nums))
nums = [1,2,3,4,1,2,3,4]
test(nums)
print(nums)
[1,2,3,4,1,2,3,4]
I am not able to understand the process. If I do something like
def test(nums):
nums.append(7)
nums = [1,2,3,4,1,2,3,4]
test(nums)
print(nums)
[1,2,3,4,1,2,3,4,7]
the list alters.
| [
"everything is object in python\nwhen you are using object method inside any function then python changes that object depending upon that method. append is inplace in your case\nIn this case,\ndef test(nums):\n nums.append(7)\n\nnums = [1,2,3,4,1,2,3,4]\ntest(nums)\nprint(nums)\n\nnums is list object, and you ar... | [
1
] | [] | [] | [
"function",
"list",
"python"
] | stackoverflow_0074321744_function_list_python.txt |
Q:
Pandas unable to read my file despite correct path
Before anyone says "there are already solutions for this" or "check the path, relative or absolute", I have already done all of that. I am working on my final uni project and this is driving me nuts.
I'm trying to import some molecules using pandas:
df_chloropheno... | Pandas unable to read my file despite correct path | Before anyone says "there are already solutions for this" or "check the path, relative or absolute", I have already done all of that. I am working on my final uni project and this is driving me nuts.
I'm trying to import some molecules using pandas:
df_chlorophenol = pd.read_csv(r'Neural_Network_V1/Simulation_Dataset/C... | [
"If the script is in Neural_Network_V1, and you use the path Neural_Network_V1/Simulation_Dataset/Chlorophenol.csv, then it is a relative path, and the script will look for that path relative to where it is run from, so effectively it’ll try Neural_Network_V1/ Neural_Network_V1/Simulation_Dataset/Chlorophenol.csv.\... | [
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074321752_csv_pandas_python.txt |
Q:
Open Unity or C# project using python on a MacOS?
How do you open a Unity/C# project using python code (pycharm)?
I have a unity app and I am writing a script to open the app in the background and sign it. I've completed this task for Windows but the same code doesn't work for Mac, as expected.
Even if I change th... | Open Unity or C# project using python on a MacOS? | How do you open a Unity/C# project using python code (pycharm)?
I have a unity app and I am writing a script to open the app in the background and sign it. I've completed this task for Windows but the same code doesn't work for Mac, as expected.
Even if I change the paths, I keep facing 2 errors, (1) file/folder not fo... | [
"On MacOS, the actual executable file is inside the Unity.app directory (an .app file is really a folder).\nThe right path may be something like /Applications/Unity/Hub/Editor/2021.1.28f1/Unity.app/Contents/MacOS/Unity, depending on which version you installed and where you let the Hub install it, or where you inst... | [
0
] | [] | [] | [
"c#",
"macos",
"python",
"unity3d"
] | stackoverflow_0074321413_c#_macos_python_unity3d.txt |
Q:
How to delete keys from dictionary by their values
students = {'palii':('male','170'),
'Minckach':('male','176'),
'ddl':('male','180'),
'Red1ska':('male','188'),
'Sargeras':('male','185'),
'Gerus':('female','160'),
'Liah':('male','183'),
... | How to delete keys from dictionary by their values | students = {'palii':('male','170'),
'Minckach':('male','176'),
'ddl':('male','180'),
'Red1ska':('male','188'),
'Sargeras':('male','185'),
'Gerus':('female','160'),
'Liah':('male','183'),
'Chhekan':('female','182'),
'Leshega'... | [
"Are you wanting this?\n\nIterate over dict.\nKeep height if gender =='male'.\nCompute the average.\n\nheight_lst = [int(height) for name, (gender, height) in students.items() if gender == 'male']\nprint(f'Average: {sum(height_lst)/len(height_lst)}') \n\nOutput:Average: 181.875\nYou can correct newDict like the bel... | [
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074321858_dictionary_python.txt |
Q:
Best way to create a temporary directory on AWS Lambda Function with Python?
Possibly being a bit knit-picky, but does anyone know of a more "elegant" method for doing this?
Right now I create tmp directories like this:
tmp_file_path_obj = Path(mktemp(dir=f"/tmp/path/to/nested/dir/with/non/existent/parents"))
tmp_... | Best way to create a temporary directory on AWS Lambda Function with Python? | Possibly being a bit knit-picky, but does anyone know of a more "elegant" method for doing this?
Right now I create tmp directories like this:
tmp_file_path_obj = Path(mktemp(dir=f"/tmp/path/to/nested/dir/with/non/existent/parents"))
tmp_file_path_obj.parent.mkdir(exist_ok=True, parents=True)
I would like a method tha... | [
"import tempfile\ntemp_dir = tempfile.TemporaryDirectory()\n"
] | [
3
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"python",
"temp"
] | stackoverflow_0074321952_amazon_web_services_aws_lambda_python_temp.txt |
Q:
`conda info` points to a different base path while called from within Python
I have observed a strange behaviour:
In my shell I activate a conda environment abc with conda activate abc.
I run conda info --base and obtain a proper path where I installed conda, I get: $HOME/miniconda3.
I start a python interpreter ... | `conda info` points to a different base path while called from within Python | I have observed a strange behaviour:
In my shell I activate a conda environment abc with conda activate abc.
I run conda info --base and obtain a proper path where I installed conda, I get: $HOME/miniconda3.
I start a python interpreter with python
In the interpreter I run: import os and os.system("conda info --base")... | [
"I can only reproduce this behavior in the case that the abc environment has the conda package installed.\n$ mamba create -yn foo python\n$ mamba run -n foo python -c 'import os; os.system(\"conda info --base\")'\n/Users/mfansler/miniconda3\n\n$ mamba create -yn bar conda\n$ mamba run -n bar python -c 'import os; o... | [
1
] | [] | [] | [
"conda",
"python",
"shell"
] | stackoverflow_0074321787_conda_python_shell.txt |
Q:
Monitor CPU temperature in python on windows11
I have wrote a code to monitor ram memory usage, CPU memory usage, and CPU temperature I have used both psutil and WMI and I'm some kind of problem the code ran perfectly when I had windows 10 I updated to window 11 it is not working. I have checked python interpreter... | Monitor CPU temperature in python on windows11 | I have wrote a code to monitor ram memory usage, CPU memory usage, and CPU temperature I have used both psutil and WMI and I'm some kind of problem the code ran perfectly when I had windows 10 I updated to window 11 it is not working. I have checked python interpreter it is on 3.10
I get this my output/error message:
C... | [
"OpenHardwareMonitor can generate logs (options/log Sensors)\nThe log is called OpenHardwareMonitorLog-YYYY-MM-DD.csv\nThe idea is therefore to launch OpenHardwareMonitor beforehand (possible to execute via scheduled task + subprocess, or in automatic execution at startup), and to retrieve the correct column in the... | [
0
] | [] | [] | [
"operating_system",
"psutil",
"python",
"python_3.x",
"wmi"
] | stackoverflow_0071579624_operating_system_psutil_python_python_3.x_wmi.txt |
Q:
Turtle() only listening to onkeypress one time, not repeating keys
so I am making snake and whenever I call my key press it works fine just one time. I can go up once, down once, right and left all exactly one time. But if I want to use this key to change direction again I cannot, anyone know why? Here is my code ... | Turtle() only listening to onkeypress one time, not repeating keys | so I am making snake and whenever I call my key press it works fine just one time. I can go up once, down once, right and left all exactly one time. But if I want to use this key to change direction again I cannot, anyone know why? Here is my code (also mainloop causes my turtle not to show):
from turtle import *
from ... | [
"\nscreen.onkeypress(snake.up, \"Up\")\nscreen.onkeypress(snake.down, \"Down\")\nscreen.onkeypress(snake.left, \"Left\")\nscreen.onkeypress(snake.right, \"Right\")\nscreen.listen()\nscreen.listen()\n\n\nThe block above needs to be moved into a while loop.\nRight now, it will check if the user ever presses a key. If... | [
0,
0
] | [] | [] | [
"listen",
"python",
"screen",
"turtle_graphics",
"user_interface"
] | stackoverflow_0067249284_listen_python_screen_turtle_graphics_user_interface.txt |
Q:
I can't convert the json date
I have a small code in python that what I try to do is show me the date but I can't get it to show me, the date is generated by a url in json:
this is the url:.
https://images.habbo.com/habbo-web-news/es/production/front.json
and what I try is to be published with this code:
`import t... | I can't convert the json date | I have a small code in python that what I try to do is show me the date but I can't get it to show me, the date is generated by a url in json:
this is the url:.
https://images.habbo.com/habbo-web-news/es/production/front.json
and what I try is to be published with this code:
`import time
time.ctime(int("1667300455000")... | [
"This is caused by the fact that 1667300455000 is simply too far in the future.\nI suspect that your JSON gives the time in milliseconds and therefore, we need to divide it by 1000.\ntime.ctime(int(\"1667300455\"))\n'Tue Nov 1 12:00:55 2022'\n\nNow this date looks correct ^^\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074321869_python.txt |
Q:
How to change the body background around plotly figure when rendered in browser?
I was wondering if anyone knows how to remove this white border in firefox (or also chrome, doesn't matter) when I render a Scatter3d plot with plotly (python) for the browser. I already tried changing the margin to 0 but that did no ... | How to change the body background around plotly figure when rendered in browser? | I was wondering if anyone knows how to remove this white border in firefox (or also chrome, doesn't matter) when I render a Scatter3d plot with plotly (python) for the browser. I already tried changing the margin to 0 but that did no change to the border. It seems like this white border is created around the actual fig... | [
"Thanks @Hamzah and @EricLavault for your help!\nI managed to find a solution here: https://community.plotly.com/t/show-tell-plotly-graph-background-color-in-html-file-with-css-style/43223\nFor using it in Ubuntu I just had to replace the\nos.startfile(output_file)\nwith\nwebbrowser.open('file://' + os.path.realpat... | [
1,
0
] | [] | [] | [
"browser",
"plotly",
"plotly_python",
"python",
"rendering"
] | stackoverflow_0073996407_browser_plotly_plotly_python_python_rendering.txt |
Q:
How to save the results of a function as a new CSV?
The code is required to take addresses from a csv file and then use a function to compute the corresponding Latitudes and Longitudes. While I get the correct Latitudes and Longitudes but I am unable to save them to a new csv file.
import requests
import urllib.pa... | How to save the results of a function as a new CSV? | The code is required to take addresses from a csv file and then use a function to compute the corresponding Latitudes and Longitudes. While I get the correct Latitudes and Longitudes but I am unable to save them to a new csv file.
import requests
import urllib.parse
import pandas as pd
#function to get the Coordinates:... | [
"Just a small modification might help\ndef lat_long(add):\n url = 'https://nominatim.openstreetmap.org/search/'+urllib.parse.quote(add)+'?format=json'\n response = requests.get(url).json()\n print(response[0][\"lat\"], response[0][\"lon\"])\n Lat = response[0][\"lat\"]\n Long = response[0][\"lon\"]\n... | [
0,
0
] | [] | [] | [
"csv",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074321764_csv_dictionary_pandas_python.txt |
Q:
Pandas convert date
Hey guys I need some help, my date is not in the correct format.
I made a function to convert all columns of dates it works but, it gives a return of SettingWithCopyWarning.
(https://i.stack.imgur.com/5xlT4.png)
(https://i.stack.imgur.com/hZe9f.png)
(https://i.stack.imgur.com/iglZB.png)
can you... | Pandas convert date | Hey guys I need some help, my date is not in the correct format.
I made a function to convert all columns of dates it works but, it gives a return of SettingWithCopyWarning.
(https://i.stack.imgur.com/5xlT4.png)
(https://i.stack.imgur.com/hZe9f.png)
(https://i.stack.imgur.com/iglZB.png)
can you tell me how to solve thi... | [
"If your code is working and is doing its job you can always ignore the error by adding this at the top. I would not recommend it in a very large scale project.\nfrom pandas.core.common import SettingWithCopyWarning\n\nwarnings.simplefilter(action=\"ignore\", category=SettingWithCopyWarning)\n\n"
] | [
-1
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074321669_dataframe_datetime_pandas_python.txt |
Q:
How to do text pre-processing using spaCy?
How to do preprocessing steps like Stopword removal , punctuation removal , stemming and lemmatization in spaCy using python.
I have text data in csv file like paragraphs and sentences. I want to do text cleaning.
Kindly give example by loading csv in pandas dataframe
... | How to do text pre-processing using spaCy? | How to do preprocessing steps like Stopword removal , punctuation removal , stemming and lemmatization in spaCy using python.
I have text data in csv file like paragraphs and sentences. I want to do text cleaning.
Kindly give example by loading csv in pandas dataframe
| [
"This may help:\nimport spacy #load spacy\nnlp = spacy.load(\"en\", disable=['parser', 'tagger', 'ner'])\nstops = stopwords.words(\"english\")\n\ndef normalize(comment, lowercase, remove_stopwords):\n if lowercase:\n comment = comment.lower()\n comment = nlp(comment)\n lemmatized = list()\n for w... | [
14,
11,
6,
0
] | [
"Please read their docs, here is one example:\nhttps://nicschrading.com/project/Intro-to-NLP-with-spaCy/\n"
] | [
-2
] | [
"nlp",
"python",
"spacy"
] | stackoverflow_0045605946_nlp_python_spacy.txt |
Q:
Make loop run only when holding right click
I'm trying to make a program that randomly moves the mouse only when the right mouse button is held to prank a friend.
I found some code online to detect right-clicks with Win32 API. When I added my own while loop, it didn't stop after it started. I tried adding an if st... | Make loop run only when holding right click | I'm trying to make a program that randomly moves the mouse only when the right mouse button is held to prank a friend.
I found some code online to detect right-clicks with Win32 API. When I added my own while loop, it didn't stop after it started. I tried adding an if statement with break but nothing changed.
import wi... | [
"You can try replacing your main while loop with this one that uses the assignment (walrus) operator := to continuously check the button state\nhas_right_clicked = False # flag if the button has been pressed yet\n\nwhile state := win32api.GetKeyState(0x02) # Right button down = 1. Button up = -128:\n if state ... | [
0,
0
] | [] | [] | [
"mouse",
"pyautogui",
"python",
"pywin32",
"windows"
] | stackoverflow_0074321781_mouse_pyautogui_python_pywin32_windows.txt |
Q:
How can I make my code more efficient for Roman to Integer conversion?
I'm new to programming. In Python, I wrote a program to convert Roman numerals to integers. The constraints are:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman nu... | How can I make my code more efficient for Roman to Integer conversion? | I'm new to programming. In Python, I wrote a program to convert Roman numerals to integers. The constraints are:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
How can I make this run faster?
Here is my co... | [
"Will approach this by using dictionary like this;\nJust compare and do the right ops. Except the last one, if one letter is less than its latter one, this letter is subtracted.\n\n def romanToInt(self, s: str) -> int:\n ans = 0\n prev = 0\n dc = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1... | [
3,
0,
0
] | [] | [] | [
"performance",
"python",
"runtime"
] | stackoverflow_0073308036_performance_python_runtime.txt |
Q:
I would like to understand e notation and how to round it in python
print("%10.3e"%(356.08977)).
output: 3.561e+02
Can anyone explain me output of this. I really don't understand the logic in it.
A:
For starters e means that you choose scientific notation. For example:
>>> 8e-2
0.08 # 8 * 10**-2
Now abo... | I would like to understand e notation and how to round it in python | print("%10.3e"%(356.08977)).
output: 3.561e+02
Can anyone explain me output of this. I really don't understand the logic in it.
| [
"For starters e means that you choose scientific notation. For example:\n>>> 8e-2\n0.08 # 8 * 10**-2\n\nNow about the 10.3 you are practically saying that you want 3 decimals. As a result:\n>>>print(\"%10.4e\"%(356.08977))\n3.5609e+02\n\nSo the output means 3.561 * 10^2\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074322094_python.txt |
Q:
How to have one item in the legend selected by default in plotly/dash?
How to have one item in the legend selected by default and the others should be deselected?
I want the initial plot looking like this:
#prepare thr chart
fig = px.line(df, x='date', y='diesel_price', color='region',
title='Die... | How to have one item in the legend selected by default in plotly/dash? | How to have one item in the legend selected by default and the others should be deselected?
I want the initial plot looking like this:
#prepare thr chart
fig = px.line(df, x='date', y='diesel_price', color='region',
title='Diesel price in the US',
labels={'date':'Date',
... | [
"You can achive that through visible attribute as follows:\nimport plotly.express as px\n\ndf = px.data.gapminder().query(\"continent=='Oceania'\")\n\nfig = px.line(df, x=\"year\", y=\"lifeExp\", color='country')\n\nfig.update_traces(visible=\"legendonly\") #<----- deselect all lines \n\nfig.data[0].visible=True ... | [
2
] | [] | [] | [
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074322004_plotly_plotly_dash_python.txt |
Q:
How do I make my Nextcord bot record messages after a command?
I made a bot, and now I want to add a "guess" command where the user tries to guess a number between 1 - 100. The bot will generate a random number and then I want it to record messages after the command has been sent, and only the messages of that use... | How do I make my Nextcord bot record messages after a command? | I made a bot, and now I want to add a "guess" command where the user tries to guess a number between 1 - 100. The bot will generate a random number and then I want it to record messages after the command has been sent, and only the messages of that user.
Here is the code that I've made so far:
##GUESS COMMAND
@client.c... | [] | [] | [
"@client.command(name=\"guess\")\nasync def guess(ctx):\n await ctx.reply(\"I thought of a number between **1 and 100, You got 5 guesses good luck!**\")\n guesses = 0\n num = random.randint(1, 100)\n while True: \n if guesses>5: # Just in case so it always makes sure there are 5 attempts\n ... | [
-1
] | [
"bots",
"discord.py",
"nextcord",
"python"
] | stackoverflow_0074322133_bots_discord.py_nextcord_python.txt |
Q:
Python - Get newest dict value where string = string
I have this code and it works. But I want to get two different files.
file_type returns either NP or KL. So I want to get the NP file with the max value and I want to get the KL file with the max value.
The dict looks like
{"Blah_Blah_NP_2022-11-01_003006.xlsx":... | Python - Get newest dict value where string = string | I have this code and it works. But I want to get two different files.
file_type returns either NP or KL. So I want to get the NP file with the max value and I want to get the KL file with the max value.
The dict looks like
{"Blah_Blah_NP_2022-11-01_003006.xlsx": "2022-03-11",
"Blah_Blah_KL_2022-11-01_003006.xlsx": "202... | [
"You could filter the dictionary into two dictionaries (or however many you need if there's more types) and then get the max date for any of those.\nBut the whole operation can be done efficiently in only few lines:\nfrom pathlib import Path\nfrom datetime import datetime\n\n\ndef get_newest():\n maxs = {}\n ... | [
1,
0
] | [] | [] | [
"dictionary",
"max",
"python"
] | stackoverflow_0074322141_dictionary_max_python.txt |
Q:
convert email .msg into .eml with Python
I have a folder with several emails.msg and I want to convert them to emails.eml with Python3. Is there a way?
Thanks
A:
have a look at msg-parser, their pip wiki shows a simple example of how one can achieve that.
| convert email .msg into .eml with Python | I have a folder with several emails.msg and I want to convert them to emails.eml with Python3. Is there a way?
Thanks
| [
"have a look at msg-parser, their pip wiki shows a simple example of how one can achieve that.\n"
] | [
0
] | [] | [] | [
"eml",
"msg",
"python"
] | stackoverflow_0074322272_eml_msg_python.txt |
Q:
I'm using WSL how I upgrade Python to the last version through the console?
I'm using WSL how I upgrade Python to the last version through the console?
Right now I have 3.8.10
A:
I tried these steps and it worked.
Note: in step 3 you just need to change the version that you want to install
Installation steps
Run... | I'm using WSL how I upgrade Python to the last version through the console? | I'm using WSL how I upgrade Python to the last version through the console?
Right now I have 3.8.10
| [
"I tried these steps and it worked.\nNote: in step 3 you just need to change the version that you want to install\nInstallation steps\nRun the following commands in your WSL terminal:\n# Update package lists{\nsudo apt update\n\n# Install dependent libraries:\nsudo apt install build-essential zlib1g-dev libncurses5... | [
1,
0,
0
] | [] | [] | [
"console",
"python",
"upgrade",
"windows_subsystem_for_linux"
] | stackoverflow_0069774921_console_python_upgrade_windows_subsystem_for_linux.txt |
Q:
Are there considerations that need made when using Mocking for python unittests when the object being mocked is in another function?
I'm not super familiar with mocking, but I have to write unit tests for an endpoint for a flask app. So I'm using flask's unittest tools. We use blueprints, so the endpoints are loca... | Are there considerations that need made when using Mocking for python unittests when the object being mocked is in another function? | I'm not super familiar with mocking, but I have to write unit tests for an endpoint for a flask app. So I'm using flask's unittest tools. We use blueprints, so the endpoints are located in a different file than the flask app. I have a function (call it function A). That function uses a helper function (call it function... | [
"I'll try to answer to your question. I have create 2 files in the paths you have indicated in your question:\n\nproduction file is: src/routes/CRUD/myscript.py\ntest code file is : test_scripts/test_script.py\n\nThe content of 2 files are showed below.\ntest_script.py\nimport json\nimport unittest\nfrom unittest i... | [
1,
0
] | [] | [] | [
"flask",
"mocking",
"python",
"unit_testing"
] | stackoverflow_0074308795_flask_mocking_python_unit_testing.txt |
Q:
Package requirements 'tensorflow~=2.10.0', 'transformers~=4.22.1', 'TorchCRF~=1.1.0' are not satisfied
I am using PyCharm 2022.2.3 (Professional Edition), Python 3.11.0 (have any problem in compatible between this version of Python with PyTorch?) , Windows 11 x64.
Microsoft Windows [Version 10.0.22621.674]
(c) Mic... | Package requirements 'tensorflow~=2.10.0', 'transformers~=4.22.1', 'TorchCRF~=1.1.0' are not satisfied | I am using PyCharm 2022.2.3 (Professional Edition), Python 3.11.0 (have any problem in compatible between this version of Python with PyTorch?) , Windows 11 x64.
Microsoft Windows [Version 10.0.22621.674]
(c) Microsoft Corporation. All rights reserved.
C:\Users\donhu>python
Python 3.11.0 (main, Oct 24 2022, 18:26:48) ... | [
"For PyCharm, take a look at https://www.jetbrains.com/help/pycharm/managing-dependencies.html#populate_dependency_files\nAfter you've set it up, you can click Install requirement.\n\nOpen a project with the requirements file specified, a notification bar is displayed on top of any Python or requirements file opene... | [
2
] | [] | [] | [
"huggingface_transformers",
"pycharm",
"python",
"pytorch",
"tensorflow"
] | stackoverflow_0074322227_huggingface_transformers_pycharm_python_pytorch_tensorflow.txt |
Q:
How to use itertools to remove lines starting with one of a list of strings
I assume this is a good task for Python's itertools. But I don't get it which one of it's magic methods I should use here.
The input data
kill = ['err A', 'err B', 'err C']
lines = ['keep A', 'err B foo', 'err A bar', 'keep B', 'err C foo... | How to use itertools to remove lines starting with one of a list of strings | I assume this is a good task for Python's itertools. But I don't get it which one of it's magic methods I should use here.
The input data
kill = ['err A', 'err B', 'err C']
lines = ['keep A', 'err B foo', 'err A bar', 'keep B', 'err C foobar']
The expected output
['keep A', 'keep B']
Very conservatively I would solv... | [
"There's no need for itertools, just use a list comprehension. You can convert kill to a tuple, and then it can be used as the argument to startswith().\nkillt = tuple(kill)\nresult = [line for line in lines if not line.startswith(killt)]\n\n",
"Barmar already took the obvious one, so here are two itertools ones ... | [
1,
1
] | [] | [] | [
"python",
"python_itertools"
] | stackoverflow_0074322183_python_python_itertools.txt |
Q:
Serial port permission error, and 'unexpected keyword argument' related to 'Systole' package when plotting raw PPG time series
I'm trying to assess if an Oximeter plugged in via USB is correctly collecting heart rate data. I am using the Systole package, and some pre-writtend code sourced here (Scroll down to Reco... | Serial port permission error, and 'unexpected keyword argument' related to 'Systole' package when plotting raw PPG time series | I'm trying to assess if an Oximeter plugged in via USB is correctly collecting heart rate data. I am using the Systole package, and some pre-writtend code sourced here (Scroll down to Recording PPG Signal :Recording PPG Signal code
I am having 2 errors, the first is:SerialException: could not open port 'COM4': Permissi... | [
"I'm sorry but are you sure you are pointing to the right file? this generation of errors occurs when the file is not reached because it does not exist.\nalso in the service documentation to write or read a file you should do:\nimport serial\n\ns = serial.Serial('COM7')\nres = s.read() # or s.write()\nprint(res)\... | [
1,
1
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0074318519_jupyter_notebook_python.txt |
Q:
how can I sort dictionary by value and if values are same then how can I sort keys by alphabet
my_dictionary = {'a': 1, 'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2, 'g': 1}
How can I sort my_dictionary by value and if values are same then how can I sort keys by alphabet
i_want = {'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2... | how can I sort dictionary by value and if values are same then how can I sort keys by alphabet | my_dictionary = {'a': 1, 'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2, 'g': 1}
How can I sort my_dictionary by value and if values are same then how can I sort keys by alphabet
i_want = {'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2, 'a': 1, 'g': 1}
| [
"Try this:\n# First sort base negative number ascending\n# Second sort base alphabet ascending\n>>> dict(sorted(dct.items(), key = lambda x: (-x[1], x[0])))\n# --------------------------------------------^^^ here we can pass numbers as negative.\n{'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2, 'a': 1, 'g': 1}\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074322375_dictionary_python.txt |
Q:
django displaying posts and comments
this is models.py
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
date = models.DateTimeField(default=timezone.now)
def write(self):
se... | django displaying posts and comments | this is models.py
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
date = models.DateTimeField(default=timezone.now)
def write(self):
self.date = timezone.now()
self.save... | [
"You don't need to query list of comments in you views, you need just posts:\ndef post(request):\n datas = Post.objects.order_by('-date')\n return render(request, 'post.html', {'datas': datas})\n\nAnd in template you can then do something like this:\n{% block main %}\n<div class=\"container\">\n {% for data ... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0054604584_django_python.txt |
Q:
How to Use Scipy Optimize Vectorized Parameter
I found in the release notes from scipy to version 1.9.0 the following about the optimisation module, in the section "scipy.optimize improvements", 4th point:
Add a vectorized parameter to call a vectorized objective function only once per iteration.
However, I alre... | How to Use Scipy Optimize Vectorized Parameter | I found in the release notes from scipy to version 1.9.0 the following about the optimisation module, in the section "scipy.optimize improvements", 4th point:
Add a vectorized parameter to call a vectorized objective function only once per iteration.
However, I already checked out the documentation for such parameter... | [
"Those notes have a more specific note for scipy.optimize.differential_evolution. That parameter is explained there. I've also come across it in other SO questions, but I don't recall which functions use it.\nBasically for functions that allow it, you can write an objective function, or other callable (jacobian, ... | [
2
] | [] | [] | [
"python",
"scipy",
"vectorization"
] | stackoverflow_0074322298_python_scipy_vectorization.txt |
Q:
convert a list into a single string consisting with double quotes and separated by comma
I have met a problem to convert a list: list=['1','2','3'] into ' "1","2","3" '.
My code is:
str(",".join('"{}"'.format(i) for i in list))
but my output is:
"1","2","3" instead of ' "1","2","3" '
May I have your sugge... | convert a list into a single string consisting with double quotes and separated by comma | I have met a problem to convert a list: list=['1','2','3'] into ' "1","2","3" '.
My code is:
str(",".join('"{}"'.format(i) for i in list))
but my output is:
"1","2","3" instead of ' "1","2","3" '
May I have your suggestion? Thanks.
| [
"I see you don't want to just prepend/append the needed substrings(the single quote and white space) to the crucial string. Here's a trick with str.replace() function:\nlst = ['1','2','3']\nresult = \"' - '\".replace('-', \",\".join('\"{}\"'.format(i) for i in lst))\n\nprint(result)\n\nThe output:\n' \"1\",\"2\",\"... | [
2,
0,
0
] | [] | [] | [
"formatting",
"list",
"python",
"string"
] | stackoverflow_0047003246_formatting_list_python_string.txt |
Q:
Docker container throws an error urllib.error.URLError: urlopen error [Errno -3] Temporary failure in name resolution with aws vpn connected
I am running my python Flask project inside of the docker container and all the requests work fine, when I turn on the aws vpn client in order to connect to an external servi... | Docker container throws an error urllib.error.URLError: urlopen error [Errno -3] Temporary failure in name resolution with aws vpn connected | I am running my python Flask project inside of the docker container and all the requests work fine, when I turn on the aws vpn client in order to connect to an external service I get an error:
urllib.error.URLError: <urlopen error [Errno -3] Temporary failure in name resolution>
I get this error while making the /logi... | [
"Based on urllib.error.URLError [python-docs]\n\nThe reason for this error. It can be a message string or another exception instance.\n\nAnd the Temporary failure in name resolution error occurs when the system(or in your case your docker container) cannot translate a website name into an IP address. While the erro... | [
0
] | [] | [] | [
"aws_vpn",
"docker",
"docker_compose",
"python"
] | stackoverflow_0074321796_aws_vpn_docker_docker_compose_python.txt |
Q:
Difference between Eigen Svd and np.linag svd
I'm currently trying to implement some prototype Python code into C++ and am running into an issue where I am getting different results for svd calculate between the 2 when using the same exact array
Code:
python:
(U, S, V) = np.linalg.svd(H)
... | Difference between Eigen Svd and np.linag svd | I'm currently trying to implement some prototype Python code into C++ and am running into an issue where I am getting different results for svd calculate between the 2 when using the same exact array
Code:
python:
(U, S, V) = np.linalg.svd(H)
print("h\n",H)
... | [
"I didn't notice that the V's were just transposes of each other. user chrslg has a good explanation for why this is so Ill just copy it here:\n\"I'd say, \"because\" :-). I don't think there is a good reason. Just 2 implementations. In maths lessons, you've probably learned SVD decomposition with formula M=U.S.Vᵀ.... | [
1
] | [] | [] | [
"c++",
"eigen",
"linear_algebra",
"python"
] | stackoverflow_0074322089_c++_eigen_linear_algebra_python.txt |
Q:
Split URL at - With Python
Does anyone know how I can extract the end 6 characters in a absoloute URL e.g
/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104
This is not a typical URL sometimetimes it ends -221104
Also, is there a way to turn 221104 into the dat... | Split URL at - With Python | Does anyone know how I can extract the end 6 characters in a absoloute URL e.g
/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104
This is not a typical URL sometimetimes it ends -221104
Also, is there a way to turn 221104 into the date 04 11 2022 easily?
Thanks in a... | [
"You should use the datetime module for parsing strings into datetimes, like so.\nfrom datetime import datetime\n\nurl = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'\n\ndatetime_string = url.split('--')[1]\n\ndate = datetime.strptime(dat... | [
3,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074322378_python.txt |
Q:
LCS: Why is my count variable not performing erroneously
LeetCode: longest consecutive sequence
Question:Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4... | LCS: Why is my count variable not performing erroneously | LeetCode: longest consecutive sequence
Question:Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1,... | [
"This one should work efficiently enough (for each element,the set is accessed about 3 times so, including the creation of the set, that would make the complexity O(4n), which is still O(n)):\ndef longest_seq(a: list) -> int :\n a = set(a)\n max_seq = 0\n for i in a:\n if i-1 in a:\n cont... | [
1,
1
] | [] | [] | [
"algorithm",
"arrays",
"python"
] | stackoverflow_0074321496_algorithm_arrays_python.txt |
Q:
Python error in telegram bot when editing a message
I see error:
(async_telebot.py:529 MainThread) ERROR - TeleBot: "59754269930"
In my code, I handle the callback:
select_item = {}
async def show_items(message, is_update):
with con.cursor() as cursor:
cursor.execute('SELECT * FROM items ORDER BY id A... | Python error in telegram bot when editing a message | I see error:
(async_telebot.py:529 MainThread) ERROR - TeleBot: "59754269930"
In my code, I handle the callback:
select_item = {}
async def show_items(message, is_update):
with con.cursor() as cursor:
cursor.execute('SELECT * FROM items ORDER BY id ASC')
items = cursor.fetchall()
con.commit... | [
"I found a solution:\n if call.data == 'item1':\n await show_items(call, True)\n\nand\nawait bot.edit_message_media(chat_id=message.message.chat.id, message_id=message.message.id, media=types.InputMedia(type='photo', media=open('start.jpg', 'rb')))\n await bot.edit_message_caption(chat_id=message... | [
0
] | [] | [] | [
"py_telegram_bot_api",
"python",
"telebot"
] | stackoverflow_0074321998_py_telegram_bot_api_python_telebot.txt |
Q:
PIP Cannot Install psutil
below are my specs
My PC is running Windows 11 V. 21H2. I am using Python 3.10. I use Pycharm 2021.2.3. I am using PIP 21.3.1 to install python libraries. To the best of my knowledge, everything is up to date.
I'm using the pip install psutil funtion in the terminal. I was able to initial... | PIP Cannot Install psutil | below are my specs
My PC is running Windows 11 V. 21H2. I am using Python 3.10. I use Pycharm 2021.2.3. I am using PIP 21.3.1 to install python libraries. To the best of my knowledge, everything is up to date.
I'm using the pip install psutil funtion in the terminal. I was able to initialize the install and begin the d... | [
"This worked for me:\nhttps://blog.hqcodeshop.fi/archives/499-Python-Windows-Pip-requiring-Build-Tools-for-Visual-Studio.html\nGet the 2017 version of the build tools then explicitly ask to install that specific version \"MSVC v140 - VS 2015 C++ build tools (v14.00)\" of the build tools under \"Individual Component... | [
1
] | [] | [] | [
"pip",
"psutil",
"pycharm",
"python",
"visual_c++"
] | stackoverflow_0070146282_pip_psutil_pycharm_python_visual_c++.txt |
Q:
Stable Diffusion (Couldn't Install Torch & Pip Version)
I am trying to install and configure Stable Diffusion AI locally on my PC (Windows 11 Pro x64), following the How-To-Geek article, How to Run Stable Diffusion Locally With a GUI on Windows
Naturally enough, I've run into problems, primarily (as the code below... | Stable Diffusion (Couldn't Install Torch & Pip Version) | I am trying to install and configure Stable Diffusion AI locally on my PC (Windows 11 Pro x64), following the How-To-Geek article, How to Run Stable Diffusion Locally With a GUI on Windows
Naturally enough, I've run into problems, primarily (as the code below shows, Torch install and Pip version :)
This is what I get w... | [
"You need to install Python 3.10.6 (https://www.python.org/ftp/python/3.10.6/python-3.10.6-amd64.exe)\nMake sure to choose \"add to PATH\" when installing or add it manually.\nRemove the venv folder from your Stable Diffusion folder that was created with the wrong version of python.\nLaunch webui-user.bat again and... | [
9,
0,
0
] | [
"I literally tried everything. Manual install of torch, updating pip, checking PATH, reinstalling python. The only thing that worked was restarting my computer.\n"
] | [
-1
] | [
"pip",
"python",
"torch",
"windows"
] | stackoverflow_0073817772_pip_python_torch_windows.txt |
Q:
How to make this type of horizontal barplot in python/seaborn?
I was wondering if its possible to make a bar plot that looks like this in Python:
Specifically, the details I'm interested in are:
Have the grey bars for each category take up the entire width of plot
Have the percent value take up that percentage o... | How to make this type of horizontal barplot in python/seaborn? | I was wondering if its possible to make a bar plot that looks like this in Python:
Specifically, the details I'm interested in are:
Have the grey bars for each category take up the entire width of plot
Have the percent value take up that percentage of the grey bar in a different color
Have the category name be inside... | [
"You could first create a bar plot with all values 100 and plot the intended bars on top.\nMatplotlib's new bar_label() function lets you label the bars with their values. ax.text() can add the y tick labels as text into the plot.\nThe following code gets some test data from wikipedia (to make things reproducible,... | [
2
] | [] | [] | [
"bar_chart",
"plot",
"python",
"seaborn"
] | stackoverflow_0074321174_bar_chart_plot_python_seaborn.txt |
Q:
Python: wait for apps to open and load before proceeding
I'm trying to build a script that opens all of the web dev programs I use. I want the print("Opened all apps") to only run once all 3 programs have opened and fully loaded (rather than currently printing after just opening the programs and not waiting for th... | Python: wait for apps to open and load before proceeding | I'm trying to build a script that opens all of the web dev programs I use. I want the print("Opened all apps") to only run once all 3 programs have opened and fully loaded (rather than currently printing after just opening the programs and not waiting for them to load) because I want to do something after they've loade... | [
"The wait method waits for the process to exit. There's no standard way to tell when a program has \"finished\" starting up.\n",
"That depends on your definition of \"load\".\nsubprocess spawns simple processes in a subshell, once the process completes it returns an exitcode. wait does just that, it waits for the... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0074322324_python.txt |
Q:
Python-pptx - How to delete all shapes in pptx slide in python?
I use this library : https://python-pptx.readthedocs.io/, and I'm looking for a method to delete all shapes of a slide (and to replace by shapes taken from another slide).
Thanks.
A:
It's possible, though it is a little tricky. I adapted the code fr... | Python-pptx - How to delete all shapes in pptx slide in python? | I use this library : https://python-pptx.readthedocs.io/, and I'm looking for a method to delete all shapes of a slide (and to replace by shapes taken from another slide).
Thanks.
| [
"It's possible, though it is a little tricky. I adapted the code from this answer and this answer.\nfrom pptx import Presentation\nimport copy\n\nprs = Presentation(\"test169_presentation.pptx\")\ndef delete_shapes(prs, slide_index):\n for shape in prs.slides[slide_index].shapes:\n shape_element = shape.e... | [
0
] | [] | [] | [
"powerpoint",
"python",
"python_pptx",
"shapes"
] | stackoverflow_0074322152_powerpoint_python_python_pptx_shapes.txt |
Q:
PIL image rotation and background issue
I am trying to rotate my transparent gif using the PIL rotate() but I am getting a diamond after rotating it.
Similar problems on SO were solved by using
transparency = img.info['transparency']
img.save('result.gif',transparency=transparency)
or by using
img.save('result.gi... | PIL image rotation and background issue | I am trying to rotate my transparent gif using the PIL rotate() but I am getting a diamond after rotating it.
Similar problems on SO were solved by using
transparency = img.info['transparency']
img.save('result.gif',transparency=transparency)
or by using
img.save('result.gif', **img.info)
But I am getting the followi... | [
"Post edited: Try to use this to make black backgroud transparent\nfrom PIL import Image\n\nimg = Image.open('img.png')\nimg = img.convert(\"RGBA\")\ndatas = img.getdata()\n\nwith Image.open(file) as im:\ntransparency = im.info['transparency']\nimg = im.rotate(90, expand=True)\nimg.save('result.gif', transparency=t... | [
0,
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0057833276_python_python_imaging_library.txt |
Q:
JSON to CSV iterate through nested objects and map value to key
I do have a json in the format of (but with even more/deeper nested objects)
{
"Group": {
"Group1": {
"GroupA": {
"value": "#fffff",
"type": "color"
},
"GroupB": {
... | JSON to CSV iterate through nested objects and map value to key | I do have a json in the format of (but with even more/deeper nested objects)
{
"Group": {
"Group1": {
"GroupA": {
"value": "#fffff",
"type": "color"
},
"GroupB": {
"value": "#c2c2c2",
"type": "color"
... | [
"\ni don't care about the tool stack\n\nSo, why not use jq, then?\nIt can transform JSON with ease, and even generate your desired output format using the @csv builtin and the --raw-output (or -r) option.\n.Group | to_entries | reduce (\n .[] | (.value | paths(objects) as $p | [$p, getpath($p).value]) + [.key]\n) ... | [
0
] | [] | [] | [
"converters",
"csv",
"json",
"pandas",
"python"
] | stackoverflow_0074318671_converters_csv_json_pandas_python.txt |
Q:
Parsing subfields in XML and merging with matching columns
This is a follow-up question from here. it got lost due to high amount of other topic on this forum. Maybe i presented the question too complicated. Since then I improved and simplified the approach.
To sum up: i'd like to extract data from subfields in mu... | Parsing subfields in XML and merging with matching columns | This is a follow-up question from here. it got lost due to high amount of other topic on this forum. Maybe i presented the question too complicated. Since then I improved and simplified the approach.
To sum up: i'd like to extract data from subfields in multiple XML files and attach those to a new df on a matching posi... | [
"If I understand the situation correctly, this can be done - but because of the complexity, I would use here lxml, instead of ElementTree.\nI'll try to annotate the code a bit, but you'll have to really do read up on this.\nBy the way, the two xml files you posted are not well formed (closing tags for <energenti> a... | [
1,
1
] | [] | [] | [
"pandas",
"python",
"xml",
"xml_parsing"
] | stackoverflow_0074314696_pandas_python_xml_xml_parsing.txt |
Q:
CodeWars kata Vowel One
The code doesn't seem to replace non-vowel characters in a string.
def vowel_one(s):
not_vowel = '0'
vowels = {'a':'1',
'e':'1',
'i':'1',
'o':'1',
'u':'1'}
#dictionary with keys as vowels, and their values as 1
... | CodeWars kata Vowel One | The code doesn't seem to replace non-vowel characters in a string.
def vowel_one(s):
not_vowel = '0'
vowels = {'a':'1',
'e':'1',
'i':'1',
'o':'1',
'u':'1'}
#dictionary with keys as vowels, and their values as 1
s = s.lower() #changing list... | [
"\nYou don't require a dictionary if all your values are 1.\nYou don't require two for loops that would just increase the time complexity.\nYou don't require to convert the string into a list.\n\nHere's my code:\ndef vowel_one(s):\n vowels = ['a', 'e','i', 'o', 'u'] # simple list\n #dictionary with keys as vo... | [
1
] | [] | [] | [
"dictionary",
"python",
"string"
] | stackoverflow_0074322549_dictionary_python_string.txt |
Q:
How to reverse vowels in string and return it
I am Trying to make a program in Python to reverse the vowels in a string and return the string like this:
vow = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
vowin = []
place = []
def string(string):
for ch in string:
if ch in vow:
vowin.... | How to reverse vowels in string and return it | I am Trying to make a program in Python to reverse the vowels in a string and return the string like this:
vow = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
vowin = []
place = []
def string(string):
for ch in string:
if ch in vow:
vowin.append(ch)
else:
continue
f... | [
"No indexing required if vowin is used as a LIFO (last in, first out) stack. First pass, fill with vowels in order. Second pass, each vowel is replaced from vowin via .pop() which removes the last value.\nvow = 'aeiouAEIOU'\n\ndef string(s):\n vowin = [] # make sure to reset each call to string()\n place =... | [
0,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074321040_list_python_string.txt |
Q:
Python3 multiprocessing.pool in PyQt5 QThread raises TypeError cannot pickle 'TaskThread'[QThread] object
I've this piece of code to try to understand use of Python3 multiprocessing.pool in a PyQt5 QThread :
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton, QVBoxLayout
from Py... | Python3 multiprocessing.pool in PyQt5 QThread raises TypeError cannot pickle 'TaskThread'[QThread] object | I've this piece of code to try to understand use of Python3 multiprocessing.pool in a PyQt5 QThread :
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton, QVBoxLayout
from PyQt5.QtCore import QThread, pyqtSignal , pyqtSlot
import time
import os
import multiprocessing as mp
def wo... | [
"The problem is that self.worker is an instance method, which means that the instance must be pickled and sent to the worker process for execution. Not all classes can be pickled, and certainly not a TaskThread (which would somehow have to execute a thread??). And more generally, you need to be careful about how mu... | [
1
] | [] | [] | [
"pyqt",
"pyqt5",
"python",
"python_3.x",
"python_multiprocessing"
] | stackoverflow_0074322469_pyqt_pyqt5_python_python_3.x_python_multiprocessing.txt |
Q:
Python - TypeError: Object of type 'int64' is not JSON serializable
I have a data frame that stores store name and daily sales count. I am trying to insert this to Salesforce using the Python script below.
However, I get the following error:
TypeError: Object of type 'int64' is not JSON serializable
Below, there ... | Python - TypeError: Object of type 'int64' is not JSON serializable | I have a data frame that stores store name and daily sales count. I am trying to insert this to Salesforce using the Python script below.
However, I get the following error:
TypeError: Object of type 'int64' is not JSON serializable
Below, there is the view of the data frame.
Storename,Count
Store A,10
Store B,12
Stor... | [
"You can define your own encoder to solve this problem.\nimport json\nimport numpy as np\n\nclass NpEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n if isinstance(obj, np.floating):\n return float(obj)\n if isins... | [
176,
172,
38,
30,
12,
8,
6,
2,
0,
0
] | [
"If you have control over the creation of DataFrame, you can force it to use standard Python types for values (e.g. int instead of numpy.int64) by setting dtype to object:\ndf = pd.DataFrame(data=some_your_data, dtype=object)\n\nThe obvious downside is that you get less performance than with primitive datatypes. Bu... | [
-1,
-1,
-1
] | [
"numpy",
"python"
] | stackoverflow_0050916422_numpy_python.txt |
Q:
How to get SHAP values for each class on a multiclass classification problem in python
I have the following dataframe:
import pandas as pd
import random
import xgboost
import shap
foo = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9,10],
'var1':random.sample(range(1, 100), 10),
'var2... | How to get SHAP values for each class on a multiclass classification problem in python | I have the following dataframe:
import pandas as pd
import random
import xgboost
import shap
foo = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9,10],
'var1':random.sample(range(1, 100), 10),
'var2':random.sample(range(1, 100), 10),
'var3':random.sample(range(1, 100), 1... | [
"By doing some research and with the help of this post and @Alessandro Nesti 's answer, here is my solution:\nfoo = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9,10],\n 'var1':random.sample(range(1, 100), 10),\n 'var2':random.sample(range(1, 100), 10),\n 'var3':random.s... | [
2,
1,
1,
0
] | [] | [] | [
"machine_learning",
"python",
"python_3.x",
"shap",
"xgboost"
] | stackoverflow_0071753428_machine_learning_python_python_3.x_shap_xgboost.txt |
Q:
Where am I supposed to store the matching engine data?
I'm working a specific algorithm related to matching engine using python and I was wondering where to store the data (orderbook)?
Is there a fast way (read and write) data to a storage rather than the database? taking in the consideration the matching engine h... | Where am I supposed to store the matching engine data? | I'm working a specific algorithm related to matching engine using python and I was wondering where to store the data (orderbook)?
Is there a fast way (read and write) data to a storage rather than the database? taking in the consideration the matching engine has to be fast in reading and writing the data in the stored ... | [
"I was involved with a financial matching engine once. The only way we could manage the volume of data was to forego the dbms. Live data was kept in memory, and an append-only log of order book changes was kept in flat files in the local file system. Actual trades were stored in a proper (beefy) db, but they were o... | [
1
] | [] | [] | [
"cryptocurrency",
"database",
"matching",
"postgresql",
"python"
] | stackoverflow_0074322067_cryptocurrency_database_matching_postgresql_python.txt |
Q:
How to get the first digits from a column name?
my column names are 22abcd123, 33sdfjsdh77, 45hgvjh77, 44vhsfgdhd88
i need my column name as 22,33,45,44.
I tried:
res = int(re.findall('(\d+)',df.columns[5])[0])
i got the answer for 1 column name . but I need it for every column name in a Dataframe
A:
You can use... | How to get the first digits from a column name? | my column names are 22abcd123, 33sdfjsdh77, 45hgvjh77, 44vhsfgdhd88
i need my column name as 22,33,45,44.
I tried:
res = int(re.findall('(\d+)',df.columns[5])[0])
i got the answer for 1 column name . but I need it for every column name in a Dataframe
| [
"You can use:\ndf.columns = df.columns.str.extract('(\\d+)', expand=False)\n\n",
"First you can get all of your column names as an array using:\nmyArray = pandas.columns(df)\n\nNow you have an array of column names in myArray\nNow write a loop to get your new column names and add the new column names to an array:... | [
1,
0
] | [] | [] | [
"list",
"pandas",
"python"
] | stackoverflow_0074322511_list_pandas_python.txt |
Q:
Continous output with asyncio subprocess
I'm using asyncio subprocess to execute a subcommand. I want to see the long-running process and save the content at the same time to a buffer for later use. Furthermore, I found this related question (Getting live output from asyncio subprocess), but it mainly centers arou... | Continous output with asyncio subprocess | I'm using asyncio subprocess to execute a subcommand. I want to see the long-running process and save the content at the same time to a buffer for later use. Furthermore, I found this related question (Getting live output from asyncio subprocess), but it mainly centers around the use case for ssh.
The asyncio subproces... | [
"Your code is working fine as-is for me. What command are you trying to run that is causing your issue?\nTwo things I can think of to help, are\n\nInstead of calling .wait() afterwards, set the returncode as the loop condition to keep running.\nDon't wait for full line returns in case the program is like ffmpeg whe... | [
3
] | [] | [] | [
"logging",
"python",
"python_asyncio",
"subprocess"
] | stackoverflow_0070759661_logging_python_python_asyncio_subprocess.txt |
Q:
Combine duplicate rows in Pandas
I got a dataframe where some rows contains almost duplicate values. I'd like to combine these rows as much as possible to reduce the row numbers. Let's say I got following dataframe:
One
Two
Three
A
B
C
B
B
B
C
A
B
In this example I'd like the output to be:
One
Two
Three
ABC... | Combine duplicate rows in Pandas | I got a dataframe where some rows contains almost duplicate values. I'd like to combine these rows as much as possible to reduce the row numbers. Let's say I got following dataframe:
One
Two
Three
A
B
C
B
B
B
C
A
B
In this example I'd like the output to be:
One
Two
Three
ABC
AB
CB
The real d... | [
"You can use something like this:\ndf = df.groupby(['Two'])['One','Three'].apply(''.join).reset_index()\n\nIf you can provide a small bit of code that creates the first df it'd be easier to try out solutions.\nAlso this other post may help: pandas - Merge nearly duplicate rows based on column value\nEDIT:\nDoes thi... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074322309_pandas_python.txt |
Q:
Selenium Python code to Loop through items select box
I'm trying to loop through some pages and get the data from each page, but I keep getting the same error after the second page.
Here is a snippet of the code:
driver = webdriver.Chrome('C:\ProgramData\Anaconda3\chromedriver.exe')
driver.get('https://cvmweb.cvm.... | Selenium Python code to Loop through items select box | I'm trying to loop through some pages and get the data from each page, but I keep getting the same error after the second page.
Here is a snippet of the code:
driver = webdriver.Chrome('C:\ProgramData\Anaconda3\chromedriver.exe')
driver.get('https://cvmweb.cvm.gov.br/SWB/Sistemas/SCW/CPublica/InfDiario/CPublicaInfDiari... | [
"I suppose the page is reloaded after selecting an element from the select box. And every time the page is reloaded, Selenium looses connection to the elements that were found. So you need to find elements again after selecting an option.\nIf select box doesn't change its position on the page, it should work:\ndri... | [
0
] | [] | [] | [
"automation",
"html",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074321771_automation_html_python_selenium_web_scraping.txt |
Q:
Hover the Mouse to the tab and scrape the products
Hello I am trying to use selenium to automatically scrape the products titles and prices, i am using ActionChains and move_to_element, but somehow it gave me timeout exception, Is there a better way to do it?
titles in the tab
https://denago.com/collections/ebikes... | Hover the Mouse to the tab and scrape the products | Hello I am trying to use selenium to automatically scrape the products titles and prices, i am using ActionChains and move_to_element, but somehow it gave me timeout exception, Is there a better way to do it?
titles in the tab
https://denago.com/collections/ebikes
#For Dynamic webpage, import selenium
!apt-get update
!... | [
"There are a couple of problems:\n\nBrowser opens at the default size which is small and the element you are searching for to hover is absent on the page. So you need to set options.add_argument('window-size=1200,1980').\nThere is a message about cookies that overlaps elements on the page. It's better to close it: ... | [
1,
0,
0
] | [] | [] | [
"google_colaboratory",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074321957_google_colaboratory_python_selenium_web_scraping.txt |
Q:
Extract and take average of csv column based on condition
I'm taking a class on Python, so I'm definitely not using it on a day to day basis but am trying my best to learn. One of my assignments is to read data from a csv file and get the average beginning weight of males and females in the file. I'm not allowed t... | Extract and take average of csv column based on condition | I'm taking a class on Python, so I'm definitely not using it on a day to day basis but am trying my best to learn. One of my assignments is to read data from a csv file and get the average beginning weight of males and females in the file. I'm not allowed to use Pandas or any other external packages so am just importin... | [
"I see a couple of thing wrong with your code.\nthe line csv_reader = csv.reader(csv_file, delimiter='|') produces an iterable which you need to process to get at specific lines of data, also when you utilize the with open construct, it isn't necessary to close the file, since that is automatically handled for you.... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074322371_python.txt |
Q:
How to extract domain address from a links in python data frame and write them into new one
I have an excel file that contains links and other information in different columns, I created a date frame where I left only a column with the links from the original Excel file. I need to get the domain addresses from the... | How to extract domain address from a links in python data frame and write them into new one | I have an excel file that contains links and other information in different columns, I created a date frame where I left only a column with the links from the original Excel file. I need to get the domain addresses from the links.
I have tried the following:
import re
from tldextract import extract # pip install tld... | [
"This doesn't fix your problem, but may guide you to where the TypeError is raised.\nTry adding a try/except in your function to catch which url is raising the TypeError.\nimport re\nfrom tldextract import extract # pip install tldextract\n\ndf25=df[['Источник 1']]\n\ndef get_domain(url):\n try:\n subd... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"url"
] | stackoverflow_0074322636_dataframe_pandas_python_url.txt |
Q:
Assemble separate sentences connected by dictionary attributes
I have the following list of dictionaries and I'm trying to come up with a single connected sentence based on whether the fact that the dictionary of the child sentences have the "ref" attribute connecting it to the father sentence.
clause_list = [
... | Assemble separate sentences connected by dictionary attributes | I have the following list of dictionaries and I'm trying to come up with a single connected sentence based on whether the fact that the dictionary of the child sentences have the "ref" attribute connecting it to the father sentence.
clause_list = [
{"id": "T1", "text": "hi"},
{"id": "T2", "text": "I'm", "ref": ... | [
"probablly is best use a class and not a dict, but you could convert to list of dict to list of classes easy.\nThis work. Convert the list of dict to list of Clauses. and the clauses has the method search_ref that print the partial text if there are no referenced object, or add the referenced object and continue if... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"nlp",
"python"
] | stackoverflow_0074322683_dictionary_nlp_python.txt |
Q:
Replace substring by substring in column of data frame
I have a pandas data frame data with several columns. One of these columns is GEN. This column contains german cities as strings. Some of these cities are in a bad format, meaning that they have values like "Frankfurt a.Main". For every element in data['GEN'] ... | Replace substring by substring in column of data frame | I have a pandas data frame data with several columns. One of these columns is GEN. This column contains german cities as strings. Some of these cities are in a bad format, meaning that they have values like "Frankfurt a.Main". For every element in data['GEN'] I would like to replace every expression of the form "\.[A-Z... | [
"You can use pandas.Series.str.replace to capture the two groups that compose a german city name in your original data and then add a whitespace between them.\nTry this :\ndata['GEN'] = data['GEN'].str.replace(r'(\\w+\\s.*\\.)(\\w*)', r'\\1 \\2', regex=True)\n\n# Output :\n0 Frankfurt a. Main\n1 Frankfurt a... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"replace"
] | stackoverflow_0074322614_dataframe_pandas_python_replace.txt |
Q:
Combine data from lines in a pandas df where client_id is duplicated
I have combined 2 dataframes and I want to make sure that the user id is not repeated and all values are written in 1 line, and not duplicated.
This is a ready-made dataframe, but I need to edit it and remove repetitions.
I attach the input data:... | Combine data from lines in a pandas df where client_id is duplicated | I have combined 2 dataframes and I want to make sure that the user id is not repeated and all values are written in 1 line, and not duplicated.
This is a ready-made dataframe, but I need to edit it and remove repetitions.
I attach the input data:
rzd = pd.DataFrame({
'client_id': [111, 112, 113, 114, 115],
'rzd... | [
"If possible, you should prefer joining so that there isn't a duplicate row issue at all. However, if you're just given full_result and not the initial tables, this can be accomplished using a groupby expression:\nfull_result.groupby(\"client_id\").first().reset_index()\n\nFor each client_id, it takes the first non... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074322204_pandas_python.txt |
Q:
Creating a custom image dataset for super-resolution
I'm working on developing a custom image dataset for a super-resolution deep learning network. I have the images saved to disk and can create the HDF5 dataset files. Here's the code I'm using:
import os, cv2, h5py, glob
import numpy as np
from glob import glob... | Creating a custom image dataset for super-resolution | I'm working on developing a custom image dataset for a super-resolution deep learning network. I have the images saved to disk and can create the HDF5 dataset files. Here's the code I'm using:
import os, cv2, h5py, glob
import numpy as np
from glob import glob
# define the paths to the dataset
BASE_DATA_PATH = '/usr... | [
"You are the victim of a small error in the referenced post. (My apologies; I was the author of that post. Apparently no one noticed the error creating the dataset with the wrong dtype. I corrected that answer to get the dtype from an image, then use it when creating the dataset.)\nIn addition, you need to add some... | [
0
] | [] | [] | [
"dataset",
"h5py",
"hdf5",
"opencv",
"python"
] | stackoverflow_0074319305_dataset_h5py_hdf5_opencv_python.txt |
Q:
How to run a python or .exe file in html page?
I tried running my game on a html website, but it didn't work.
can i use html or css or javascript to open and application or .exe
i tried using iframe but it just shows me the parent directory [This is the image i receive] (https://i.stack.imgur.com/kUChj.png) (https... | How to run a python or .exe file in html page? | I tried running my game on a html website, but it didn't work.
can i use html or css or javascript to open and application or .exe
i tried using iframe but it just shows me the parent directory [This is the image i receive] (https://i.stack.imgur.com/kUChj.png) (https://i.stack.imgur.com/kUChj.png)
i also tried the anc... | [
"Recently thanks yo PyScript is possible to run a python script within a HTML page in the new <py-script> tag, by example\n <py-script>\n from datetime import datetime\n now = datetime.now()\n now.strftime(\"%m/%d/%Y, %H:%M:%S\")\n </py-script>\n\nYou can see the Python source code within the <py-script> and ... | [
2,
0,
0
] | [] | [] | [
"css",
"html",
"javascript",
"python"
] | stackoverflow_0074322631_css_html_javascript_python.txt |
Q:
Adjacency matrix with string nodes in Pythom
I have a csv file of nodes and a csv file of edges - all the nodes are STRING.
I need help please for how can I build an adjacency matrix of this graph in python?
Example of the data:
Nodes csv:
a
b
c
d
Edges csv:
a,b
b,c
a,c
d,a
b,d
I want it to be presented as an ad... | Adjacency matrix with string nodes in Pythom | I have a csv file of nodes and a csv file of edges - all the nodes are STRING.
I need help please for how can I build an adjacency matrix of this graph in python?
Example of the data:
Nodes csv:
a
b
c
d
Edges csv:
a,b
b,c
a,c
d,a
b,d
I want it to be presented as an adjacency matrix:
a b c d
a 0 1 1 1
b 1 0 ... | [
"Ok: assuming your nodes and edges have been converted to lists as follows, this works (as you can see, the code is self-explanatory):\nnodes = ['a','b','c','d']\nedges = [('a','b'),('b','c'),('a','c'),('d','a'),('b','d')]\n\nimport numpy as np\nn = len(nodes)\nmatrix = np.zeros((n,n), dtype=int)\nfor i in range(n)... | [
0
] | [] | [] | [
"graph_theory",
"matrix",
"python"
] | stackoverflow_0074322574_graph_theory_matrix_python.txt |
Q:
How to remove rows that have 3 word or less in dataframe?
Because I want to remove ambiguity when I train the data. I want to clean it well. So how can I remove all rows that contain 3 words or less in python?
A:
Hello World! This will be my first contribution ever to SO :-)
Let's create some data:
data = { 'S... | How to remove rows that have 3 word or less in dataframe? | Because I want to remove ambiguity when I train the data. I want to clean it well. So how can I remove all rows that contain 3 words or less in python?
| [
"Hello World! This will be my first contribution ever to SO :-) \n\nLet's create some data:\ndata = { 'Source':['Hello all Im Happy','Its a lie, dont trust him','Oops','foo','bar']}\ndf = pd.DataFrame (data, columns = ['Source'])\n\nMy approach is very straight forward, simple and little \"brute\" and inefficient,... | [
2,
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0056235469_dataframe_python.txt |
Q:
progressive iteration approximation(PIA) method for bspline not working?
I am new to this, and tried to implement this algorithm by using uniform B-Spline. And I don't know where I did it wrong, the result just doesn't come out the way it supposed to be.
I don't know if the basis is wrong or the procedure of the P... | progressive iteration approximation(PIA) method for bspline not working? | I am new to this, and tried to implement this algorithm by using uniform B-Spline. And I don't know where I did it wrong, the result just doesn't come out the way it supposed to be.
I don't know if the basis is wrong or the procedure of the PIA is wrong. Is there someone that could help me out? Thank you so much!!
I us... | [
"There are a few things we need to take care of.\nFirst, I will put b_spline_basis into a separate file. It was almost correct but there are two changes. The intervals where the degree zero basis functions evaluate to 1 had to be adapted so that the basis functions sum up to one on the entire interval [a, b] (your ... | [
1
] | [] | [] | [
"approximation",
"interpolation",
"python",
"spline"
] | stackoverflow_0074304134_approximation_interpolation_python_spline.txt |
Q:
python change total time into minutes and subtract from the time 10 minutes without using any imports
The question includes that you need to have a main class consisting of fields, these fields are hours minutes, and seconds. I have to use this format and I can't import anything like datetime. the question is that... | python change total time into minutes and subtract from the time 10 minutes without using any imports | The question includes that you need to have a main class consisting of fields, these fields are hours minutes, and seconds. I have to use this format and I can't import anything like datetime. the question is that I need to add 2 methods first to count full minutes in our time for example let's say we have a time of 1 ... | [
"Here's my code:\nclass Time:\n def __init__(self, h, m, s):\n self.h = h; self.m = m; self.s = s # Compiled Code\n # if self.h > 24 or self. m > 60 or self.s > 60: raise ValueError\n \n def time_to_minute(self):\n return self.h*60 + self.m + round(self.s/60, 2) # Round decimals to 2 d... | [
0,
0
] | [] | [] | [
"python",
"time"
] | stackoverflow_0074322284_python_time.txt |
Q:
Extract value by using function with parameter in a dict
I have a nested dictionary containing both the title and the number of pages of a book. Here is the dict:
text = {
1: {
1: {"ch.name": "The Boy Who Lived", "pages": "146"},
2: {"ch.name": "The Vanishing Glass", "pages": "126"},
},
... | Extract value by using function with parameter in a dict | I have a nested dictionary containing both the title and the number of pages of a book. Here is the dict:
text = {
1: {
1: {"ch.name": "The Boy Who Lived", "pages": "146"},
2: {"ch.name": "The Vanishing Glass", "pages": "126"},
},
2: {
1: {"ch.name": "The Worst Birthday", "pages": "1... | [
"You could restructure slightly like this:\ndef stranger_binger(seasons, start, pages_left):\n num_pages_watched = 0\n started = False # added to determine if we've reached the start point yet\n for season, chapters in seasons.items():\n for chapter, info in chapters.items():\n if not sta... | [
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074322869_dictionary_python.txt |
Q:
OSError: There was a specific connection error when trying to load CompVis/stable-diffusion-v1-4:
System Info
Google Colab, Free version, GPU
Information
[ ] The official example scripts
[X] My own modified scripts
Tasks
[ ] An officially supported task in the examples folder (such as GLUE/SQuAD, ...)
[X] My o... | OSError: There was a specific connection error when trying to load CompVis/stable-diffusion-v1-4: | System Info
Google Colab, Free version, GPU
Information
[ ] The official example scripts
[X] My own modified scripts
Tasks
[ ] An officially supported task in the examples folder (such as GLUE/SQuAD, ...)
[X] My own task or dataset (give details below)
Reproduction
https://github.com/woctezuma/stable-diffusion-col... | [
"just go to the huggingface website and agree the terms.\nhttps://huggingface.co/CompVis/stable-diffusion-v1-4\nyou need to be logged into your hugging face account.\n"
] | [
2
] | [] | [] | [
"huggingface",
"huggingface_transformers",
"python",
"stable_diffusion"
] | stackoverflow_0074304875_huggingface_huggingface_transformers_python_stable_diffusion.txt |
Q:
Getting original value back after percentage increase?
I am a store owner.
The bank deducts 10%
How can I set my prices to be 10% extra.
e.g
Product costs $34
Add 10% and send $37.40 to the bank, then bank deducts 10% of $37.40, leaving the store with only $33.70, while 10% deduction should leave the store with $3... | Getting original value back after percentage increase? | I am a store owner.
The bank deducts 10%
How can I set my prices to be 10% extra.
e.g
Product costs $34
Add 10% and send $37.40 to the bank, then bank deducts 10% of $37.40, leaving the store with only $33.70, while 10% deduction should leave the store with $34
How much additional to add to the $34 so that the deductio... | [
"Use this:\nbank price = intial price * 1.12\nExample\n37.74 = 34 * 1.12\nI suggest adding 12% to the price\n",
"Take the current price and divide it by (100 - bank percent) then multiple all by 100.\nso you have $34.00 and you say this is reduced by 10%, but you want the final dollar value you get to be $34.00. ... | [
0,
0
] | [] | [] | [
"javascript",
"math",
"php",
"python"
] | stackoverflow_0071797977_javascript_math_php_python.txt |
Q:
How can I fail tests in a "teardown" fixture properly in pytest?
I have a test framework that is performing multiple asserts and catching them (inherited someone else's code). The proprietary results report is correct, but as you may have guessed, pytest will mark these as passed:
test_something.py::TestSomething:... | How can I fail tests in a "teardown" fixture properly in pytest? | I have a test framework that is performing multiple asserts and catching them (inherited someone else's code). The proprietary results report is correct, but as you may have guessed, pytest will mark these as passed:
test_something.py::TestSomething::test_that_should_fail PASSED
I've added an autouse fixture as such:
... | [
"As you've discovered, a fixture is a separate object from the test itself.\nYou'll need to modify the appropriate pytest hook. I haven't personally tested, but I believe placing the following code into your projects conftest.py will give you your desired result.\ndef check_for_failure(output) -> bool:\n # defin... | [
1
] | [] | [] | [
"pytest",
"python",
"testing"
] | stackoverflow_0074312272_pytest_python_testing.txt |
Q:
Can I change the amplitude of wav audio file in python from the numpy array?
I'm still starting with audio processing using python and still trying to understand the nature of data and how to process it. I've been stuck trying to increase/decrease the amplitude (volume/loudness if I can say so) of a wav file (with... | Can I change the amplitude of wav audio file in python from the numpy array? | I'm still starting with audio processing using python and still trying to understand the nature of data and how to process it. I've been stuck trying to increase/decrease the amplitude (volume/loudness if I can say so) of a wav file (without using Pydub Audiosegment) I haven't seen this answered somewhere from what I s... | [
"Well works fine with be.\nThe missing piece might be how to convert back to bytes without changing the size (since you did not use unpack, you might have done something wrong when pack. Good news is you can't pack the same way you unpacked)\nimport numpy as np\nimport wave\n\nfilename = 'violin.wav'\naudiofile = w... | [
0
] | [] | [] | [
"audio",
"numpy",
"python",
"wav",
"wave"
] | stackoverflow_0074322029_audio_numpy_python_wav_wave.txt |
Q:
Plotting multiple lineplots on single plot with for loop using matplotlib
I have a list of about 200 dataframes that look like this:
I'm running these dataframes through a for loop that runs a linear regression on each one and generates some error metrics. I'd like to generate a single plot that has all these lin... | Plotting multiple lineplots on single plot with for loop using matplotlib | I have a list of about 200 dataframes that look like this:
I'm running these dataframes through a for loop that runs a linear regression on each one and generates some error metrics. I'd like to generate a single plot that has all these lines but I'm not sure how to do that. Here is the code for the for loop:
clst_lst... | [
"Let's have a look at the docs for sns.lineplot\nIt says there's a parameter called ax which we can use to graph the plot.\nUsing your suggestion, we can define said ax and insert it into the sns.lineplot call like so\nfig, ax = plt.subplots()\n\n# really big for-loop\n...\n\n# add `ax` arg here\nsns.lineplot(data=... | [
2
] | [] | [] | [
"for_loop",
"line_plot",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074322895_for_loop_line_plot_matplotlib_pandas_python.txt |
Q:
How to merge a nested dictionary with a dataframe?
I have a dataframe like this:
df
name A B C D
0 name1 11 12 13 14
1 name2 21 22 23 24
And there is this dictionary:
d = {'name1': {'1': {'0': 9, '1': 0, '2': 0},
'2': {'0': 14, '1': 8, '2': 10},
... | How to merge a nested dictionary with a dataframe? | I have a dataframe like this:
df
name A B C D
0 name1 11 12 13 14
1 name2 21 22 23 24
And there is this dictionary:
d = {'name1': {'1': {'0': 9, '1': 0, '2': 0},
'2': {'0': 14, '1': 8, '2': 10},
'3': {'0': 0, '1': 5, '2': 0}},
'name2':... | [
"Maybe not cleanest, but with fewer commands:\ndf = df.merge(\n pd.DataFrame(d).T.reset_index().rename(columns={\"index\": \"name\"}), on=\"name\"\n).set_index([\"name\", \"A\", \"B\", \"C\", \"D\"])\ndf = df.apply(lambda x: [d.values() for d in x]).explode(df.columns.to_list())\n\nprint(df)\n\nPrints:\n ... | [
2,
2,
1
] | [] | [] | [
"dictionary",
"merge",
"pandas",
"python"
] | stackoverflow_0074322623_dictionary_merge_pandas_python.txt |
Q:
How can I throw a runtime error in TFLite?
I'm getting a bug that only seems to happen when running my TFLite model on android (I can't replicate it in python).
Internal error: Failed to run on the given Interpreter: tensorflow/lite/kernels/gather_nd.cc:135 indices_has_only_positive_elements was not true.
To trac... | How can I throw a runtime error in TFLite? | I'm getting a bug that only seems to happen when running my TFLite model on android (I can't replicate it in python).
Internal error: Failed to run on the given Interpreter: tensorflow/lite/kernels/gather_nd.cc:135 indices_has_only_positive_elements was not true.
To track it down, I'm trying to put in asserts into the... | [
"You're correct that asserts are stripped out in TensorFlow Lite, since they would add overhead in production scenarios.\nThe best way to handle errors like this is to use the TF Lite error reporting APIs. You can call interpreter->ReportError() with a message, and it will be reported to the user however is appropr... | [
0
] | [] | [] | [
"python",
"tensorflow",
"tensorflow_lite"
] | stackoverflow_0074323100_python_tensorflow_tensorflow_lite.txt |
Q:
PYTHON TkInter - setting and accessing entry widget text as variable
Ive tried reading as many articles about this as i can, but cannot find anything that helps me. In my code, i have created a class EntryWidget which has an entry widget amongst other things in it, and in my main class Controller for the app, i ha... | PYTHON TkInter - setting and accessing entry widget text as variable | Ive tried reading as many articles about this as i can, but cannot find anything that helps me. In my code, i have created a class EntryWidget which has an entry widget amongst other things in it, and in my main class Controller for the app, i have created an instance of the class EntryWidget called self.entry. I am tr... | [
"If your EntryWidget class doesn't subclass Tkinter.Entry, you will need to define get() method for your EntryWidget class. The error says that self.entry is a EntryWidget instance but does not contain get() method.\n",
"I wrote myself a small function that allows the user to enter a value into a tkinter.Entry, a... | [
2,
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0012755749_python_tkinter.txt |
Q:
ModuleNotFoundError: No module named 'cv2' in VS code
im trying to run this
import cv2
import numpy as np
import os
from matplotlib import plypot as plt
import time
import mediapipe as mp
and also
cap = cv2.VideoCapture(0)
while cap.isOpened():
#Reads feed
ret, frame = cap.read()
cv2.inshow('OpenCV ... | ModuleNotFoundError: No module named 'cv2' in VS code | im trying to run this
import cv2
import numpy as np
import os
from matplotlib import plypot as plt
import time
import mediapipe as mp
and also
cap = cv2.VideoCapture(0)
while cap.isOpened():
#Reads feed
ret, frame = cap.read()
cv2.inshow('OpenCV feed', frame)
#breaks for a while
if cv2.waitKe... | [
"Try using pip3 install opencv-python, as it installs opencv for python3, not python2 (if you have it installed). If you only have python3, pip and pip3 are basically the same thing (I think).\n"
] | [
0
] | [] | [] | [
"numpy",
"opencv",
"pip",
"python"
] | stackoverflow_0074320047_numpy_opencv_pip_python.txt |
Q:
OpenApi for Python
I'm trying to use OpenAPI for a Python project.
I've previously used OpenAPI with Java and it was really easy as you could configure it into pom.xml so that you would write a yaml file and then you would get an interface that you could implement into your controller.
I'm now working in Python an... | OpenApi for Python | I'm trying to use OpenAPI for a Python project.
I've previously used OpenAPI with Java and it was really easy as you could configure it into pom.xml so that you would write a yaml file and then you would get an interface that you could implement into your controller.
I'm now working in Python and I'm trying to do a sim... | [
"You may want to try import flask_restx.\nThen visit top-level URL of your flask app to see the swagger details.\nhttps://flask-restx.readthedocs.io/en/latest/swagger.html#swaggerui\nEDIT\nConsider using apispec.\n$ pip install -U 'apispec[yaml]'\n\n"
] | [
0
] | [] | [] | [
"openapi",
"python"
] | stackoverflow_0074323134_openapi_python.txt |
Q:
Tkinter recursion error when calling update several times
I want to create a frameless resizable window, the problem is, when there are many widgets, they glitch when the window is resized using a Sizegrip. The only solution that I found that removes this glitch effect is to update the window during the resize.
Un... | Tkinter recursion error when calling update several times | I want to create a frameless resizable window, the problem is, when there are many widgets, they glitch when the window is resized using a Sizegrip. The only solution that I found that removes this glitch effect is to update the window during the resize.
Unfortunately if you keep resizing for a few seconds a recursion ... | [
"Check if you're already resizing and don't call root.update() again.\nresizing = False\n\ndef on_resize(event):\n global resizing\n if not resizing:\n resizing = True\n root.update()\n resizing = False\n\n"
] | [
0
] | [] | [] | [
"frameless",
"python",
"recursion",
"resize",
"tkinter"
] | stackoverflow_0074323151_frameless_python_recursion_resize_tkinter.txt |
Q:
Python sql search inside a loop returning the same value
I am currently having a few issues checking a database in python inside a loop.
Each time i am presented with the same value.
My goal is to check a table called seeTicketsEvents for empty event ids.
Then for each check another table called seeTicketsTickets ... | Python sql search inside a loop returning the same value | I am currently having a few issues checking a database in python inside a loop.
Each time i am presented with the same value.
My goal is to check a table called seeTicketsEvents for empty event ids.
Then for each check another table called seeTicketsTickets for the name & data and then pass the id back to the first tab... | [
"I think the problem is in this line:\n mycursor.execute(\"SELECT * FROM `seeTicketsTickets` WHERE `showName` = showname AND `showDate` = showdate LIMIT 1\")\n\nWhat does the query\nSELECT * FROM `seeTicketsTickets` WHERE `showName` = showname AND `showDate` = showdate LIMIT 1\n\nreturn?\nIt returns the firs... | [
1
] | [] | [] | [
"mysql",
"python",
"sql"
] | stackoverflow_0074322594_mysql_python_sql.txt |
Q:
Convert row to column in pandas
I am using pandas to convert dict to html table, but not able to figure out, how to convert row to column in this case?
import pandas as pd
c = {'result': 'FAIL', "LinkA": "https:// example.com/dwdewdbeuwwuvdwudwufdqwdqqdqdqdqwedeuq.txt",
"NDT": "https://example.com/dgwuydweuf... | Convert row to column in pandas | I am using pandas to convert dict to html table, but not able to figure out, how to convert row to column in this case?
import pandas as pd
c = {'result': 'FAIL', "LinkA": "https:// example.com/dwdewdbeuwwuvdwudwufdqwdqqdqdqdqwedeuq.txt",
"NDT": "https://example.com/dgwuydweufdwuefgwfwfdwefef.txt",
"KKT": "h... | [
"Change how you create the df using pd.DataFrame.from_dict\n\nimport pandas as pd\n\nc = {'result': 'FAIL', \"LinkA\": \"https:// example.com/dwdewdbeuwwuvdwudwufdqwdqqdqdqdqwedeuq.txt\",\n \"NDT\": \"https://example.com/dgwuydweufdwuefgwfwfdwefef.txt\",\n \"KKT\": \"https:// example.com/fewnewvbbcuwecvwxvw... | [
1,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074322857_pandas_python.txt |
Q:
print Count of String type time entries group by hour
I have a dataframe df with column time as a string.
I want to get a count of these entries grouped hourly.
for example how many time entries are there between every hour from 00:00:00 to 23:59:59.
A:
You can group by the hour of this column using something l... | print Count of String type time entries group by hour | I have a dataframe df with column time as a string.
I want to get a count of these entries grouped hourly.
for example how many time entries are there between every hour from 00:00:00 to 23:59:59.
| [
"You can group by the hour of this column using something like this:\ndf.groupby(df.Time.dt.hour).count()\n\n",
"As you have a string, you can slice the hour part and value_counts:\nout = df['Time'].str[:2].value_counts(sort=False)\n\nOr:\nout = df.groupby(df['Time'].str[:2]).count()\n\n"
] | [
1,
1
] | [] | [] | [
"datetime",
"pandas",
"python",
"string"
] | stackoverflow_0074322635_datetime_pandas_python_string.txt |
Q:
Transform normal python function to lambda
i have this function:
def add_transaction(list_of_items):
for item in list_of_items:
if item not in item_dict.keys():
raise ValueError("You cannot make a transaction containing items that are not present in the items dictionary because it means th... | Transform normal python function to lambda | i have this function:
def add_transaction(list_of_items):
for item in list_of_items:
if item not in item_dict.keys():
raise ValueError("You cannot make a transaction containing items that are not present in the items dictionary because it means that the Store does not has those items available,... | [
"You can do this with set.isssubset() and this hack to raise an exception from a lambda. You'll also need to abuse the or operator to both call transaction_data.append(lst) and return the list.\nitem_dict = {'a': 1, 'b': 2, 'c': 3}\ntransaction_data = []\n\nfn = lambda lst: (transaction_data.append(lst) or lst) if ... | [
2
] | [] | [] | [
"function",
"lambda",
"python"
] | stackoverflow_0074323289_function_lambda_python.txt |
Q:
Remove a list in a list of lists based on condition
I have the following list of lists:
lst = [['a',102, True],['b',None, False], ['c',100, False]]
I'd like to remove any lists where the value in the second position is None. How can I do this (in a list comprehension)
I've tried a few different list comprehension... | Remove a list in a list of lists based on condition | I have the following list of lists:
lst = [['a',102, True],['b',None, False], ['c',100, False]]
I'd like to remove any lists where the value in the second position is None. How can I do this (in a list comprehension)
I've tried a few different list comprehension but can't seem to figure it out. Thanks!
| [
"Use this:\nlst = (('a',102, True),('b',None, False), ('c',100, False))\nlst = tuple([el for el in lst if el[1] is not None])\nprint(lst) # => (('a', 102, True), ('c', 100, False))\n\nYour data is a tuple of tuples, not a list of lists, so you need to convert it to a tuple at the end.\n",
"Try this:\nlst = [item... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074323236_python.txt |
Q:
Adding weighted directed edges to the networkx plot with an arrow from source to destination
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab
plt.rcParams['figure.figsize'] = [10, 10]
G = nx.DiGraph()
G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_fro... | Adding weighted directed edges to the networkx plot with an arrow from source to destination | import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab
plt.rcParams['figure.figsize'] = [10, 10]
G = nx.DiGraph()
G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)
G.add_edges_from([('B','C'),('E','F')], wei... | [
"I solved it by referring to the library manual:\nOn the draw_networkx_edges function, there is a parameter to specify your node size. when you plug the same value into both, it fixes it!\n nodeopt = {\n 'node_size' : 1400,\n 'node_color': 'white',\n 'node_shape': 'o',\n 'linewidths': 1,\n 'edgecolo... | [
2,
1
] | [] | [] | [
"directed_graph",
"graph",
"networkx",
"plot",
"python"
] | stackoverflow_0074323183_directed_graph_graph_networkx_plot_python.txt |
Q:
Iteration of 2D array for an advection-diffusion model takes too long
I'm trying to model 2D advection-diffusion in Python and got into a trouble.
I used indicies and nested for loops to manipulate the values inside my 2d array which contains concentration of certain particles, and it is now taking forever to iter... | Iteration of 2D array for an advection-diffusion model takes too long | I'm trying to model 2D advection-diffusion in Python and got into a trouble.
I used indicies and nested for loops to manipulate the values inside my 2d array which contains concentration of certain particles, and it is now taking forever to iterate.
Is there more efficient way for the iteration?
Many thanks in advance,... | [
"I'm assuming dt, mu[0], dx, dy, u, v are scalars. You can eliminate the inner two loops just by using the same formula with the u_UPW array shifted up or down, or left or right, by 1, based on the indexing you need.\nFor example, instead of u_UPW[l,j], just use u_UPW[1:Nx-1,1:Ny-1], and instead of u_UPW[l+1,j] us... | [
1
] | [] | [] | [
"for_loop",
"indices",
"python"
] | stackoverflow_0074323298_for_loop_indices_python.txt |
Q:
pandas: merge (join) two data frames on multiple columns
I am trying to join two pandas data frames using two columns:
new_df = pd.merge(A_df, B_df, how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')
but got the following error:
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4164)()
... | pandas: merge (join) two data frames on multiple columns | I am trying to join two pandas data frames using two columns:
new_df = pd.merge(A_df, B_df, how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')
but got the following error:
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4164)()
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/i... | [
"Try this\nnew_df = pd.merge(A_df, B_df, how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])\n\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html\n\nleft_on : label or list, or array-like Field names to join on in left\nDataFrame. Can be a vector or list of vectors of ... | [
551,
12,
10,
5,
0
] | [] | [] | [
"join",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0041815079_join_pandas_python_python_3.x.txt |
Q:
torch.cuda.is_available() returns false in colab
I am trying to use GPU in google colab. Below are the details of the versions of pytorch and cuda installed in my colab.
Torch 1.3.1 CUDA 10.1.243
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2018 NVIDIA Corporation
Built on Sat_Aug_25_21:08:01_CDT_201... | torch.cuda.is_available() returns false in colab | I am trying to use GPU in google colab. Below are the details of the versions of pytorch and cuda installed in my colab.
Torch 1.3.1 CUDA 10.1.243
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2018 NVIDIA Corporation
Built on Sat_Aug_25_21:08:01_CDT_2018
Cuda compilation tools, release 10.0, V10.0.130
I a... | [
"Make sure your Hardware accelerator is set to GPU. \nRuntime > Change runtime type > Hardware Accelerator\n",
"In case anyone else comes here and makes the same mistake I was making:\nIf you are trying to check if GPU is available and you do:\nif torch.cuda.is_available:\n print('GPU available')\nelse:\n print... | [
16,
1,
1,
0,
0,
0
] | [] | [] | [
"google_colaboratory",
"python",
"pytorch"
] | stackoverflow_0059154623_google_colaboratory_python_pytorch.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.