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:
Style Normal exists already - Python - OpenPyxl
I have looked into many stackoverflow questions but none of them seemed to solve my problem. I am using Python and Openpyxl to fill a whole row with red given a certain condition. I did all the importations necessary :
from openpyxl.styles import PatternFill, NamedSt... | Style Normal exists already - Python - OpenPyxl | I have looked into many stackoverflow questions but none of them seemed to solve my problem. I am using Python and Openpyxl to fill a whole row with red given a certain condition. I did all the importations necessary :
from openpyxl.styles import PatternFill, NamedStyle, Color
from openpyxl.styles.colors import RED
An... | [
"If using a NamedStyle, you're required to pass a name.\nred_foreground = NamedStyle(\n name=\"RedForeground\",\n fill=PatternFill(\n patternType='solid',\n fill_type='solid', \n fgColor=Color(RED)\n )\n)\n\nSince you're assigning this NamedStyle to more than one cell, it makes sense t... | [
3,
1,
0,
0
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0045055488_openpyxl_python.txt |
Q:
Bar Chart with Wide Format Data Fails With Data of Type datetime.time or datetime.timedelta
I am trying to create a stacked bar chart of values of type datetime.time (alternatively datetime.timedelta) using plotly, but with no success.
I follow the example "Bar charts with Wide Format Data
" given in the documenta... | Bar Chart with Wide Format Data Fails With Data of Type datetime.time or datetime.timedelta | I am trying to create a stacked bar chart of values of type datetime.time (alternatively datetime.timedelta) using plotly, but with no success.
I follow the example "Bar charts with Wide Format Data
" given in the documentation. I just convert the values to datetime.time:
import plotly.express as px
import datetime
wi... | [
"As noted in the comments, the current date format fails, so it can be converted to a stacked bar chart by converting it to seconds. Finally, correct the scale on the y-axis.\nimport plotly.express as px\nimport datetime\n\nwide_df = px.data.medals_wide()\n\nwide_df[\"gold\"] = wide_df[\"gold\"].apply(lambda x: dat... | [
0
] | [] | [] | [
"bar_chart",
"plotly",
"python",
"stacked_bar_chart",
"timedelta"
] | stackoverflow_0074411479_bar_chart_plotly_python_stacked_bar_chart_timedelta.txt |
Q:
trying to use boto copy to s3 unless file exists
in my code below,
fn2 is the local file and "my_bucket_object.key" is a list of files in my s3 bucket.
I am looking at my local files, taking the latest one by creation date and then looking at the bucket and I only want to copy the latest one there (this is working... | trying to use boto copy to s3 unless file exists | in my code below,
fn2 is the local file and "my_bucket_object.key" is a list of files in my s3 bucket.
I am looking at my local files, taking the latest one by creation date and then looking at the bucket and I only want to copy the latest one there (this is working) but not if it exists already. What is happening is t... | [
"You could make a List of the object keys and then check whether it exists:\nobject_keys = [object.key for object in my_bucket.objects.all()]\nif fn2 not in object_keys:\n s3.meta.client.upload_file(fn, f'eod-candles-{ex}', fn2)\n\n"
] | [
1
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"boto",
"python"
] | stackoverflow_0074405827_amazon_s3_amazon_web_services_boto_python.txt |
Q:
Atomic Code in gunicorn multiprocessing / only run code in worker 1?
I am new to gunicorn multiprocessing (by calling gunicorn --worker=X).
I am using it with Flask to provide the WSGI implementation for our productive frontend. To use multiprocessing, we pass the above mentioned parameter to unicorn.
Our Flask a... | Atomic Code in gunicorn multiprocessing / only run code in worker 1? | I am new to gunicorn multiprocessing (by calling gunicorn --worker=X).
I am using it with Flask to provide the WSGI implementation for our productive frontend. To use multiprocessing, we pass the above mentioned parameter to unicorn.
Our Flask application also uses APScheduler (via Flask-APScheduler) to run a cron tas... | [
"The --preload parameter for gunicorn gives an opportunity to run code just in the parent worker.\nAll the code that is run before app.run() (or whatever you called your Flask() object) is apparently run on the parent process.\nDidn't find any documentation on this unfortunately, but this post lead me to it.\nSo, r... | [
0
] | [] | [] | [
"apscheduler",
"flask",
"gunicorn",
"python",
"python_multiprocessing"
] | stackoverflow_0074404922_apscheduler_flask_gunicorn_python_python_multiprocessing.txt |
Q:
How to stop Thread via button?
I have a button that is supposed to stop a thread that is running a server function on another Python file. The solutions I've tried are as follows:
Solution #1: Threading.Event
mainmenu.py
import server as serv #as in server.py
import socket
from threading import Thread
import custo... | How to stop Thread via button? | I have a button that is supposed to stop a thread that is running a server function on another Python file. The solutions I've tried are as follows:
Solution #1: Threading.Event
mainmenu.py
import server as serv #as in server.py
import socket
from threading import Thread
import customtkinter as cust
class GUI2(cust.C... | [
"A (if not the) major cause of an unresponsive tkinter GUI is a callback that keeps running.\nThe only callback that we see is leavewindow().\nIn that function, basically only self.thread.join() can cause this.\nBy default, sockets are created in blocking mode.\nSo for example recv will wait until it receives data.... | [
1
] | [] | [] | [
"customtkinter",
"python",
"tkinter"
] | stackoverflow_0074405097_customtkinter_python_tkinter.txt |
Q:
pipenv. Create Virtual Env. Acces denied
I have Pipfile in my project folder.
I try to create VM for my project by using
pipenv --python 3.9.6
But it doesn't work for me.
Creating a virtualenv for this project...
Pipfile: Path_to_Pipfile
Using c:/users/.../.pyenv/pyenv-win/versions/3.9.6 (None) to create virtual... | pipenv. Create Virtual Env. Acces denied | I have Pipfile in my project folder.
I try to create VM for my project by using
pipenv --python 3.9.6
But it doesn't work for me.
Creating a virtualenv for this project...
Pipfile: Path_to_Pipfile
Using c:/users/.../.pyenv/pyenv-win/versions/3.9.6 (None) to create virtualenv...
[== ] Creating virtual environment...R... | [
"I worked to me to describe whole path to python instead version only.\n\npipenv --python C:\\Users\\...\\.pyenv\\pyenv-win\\versions\\3.9.6\\python.exe\n\nBut on another station it works only set a version.\n"
] | [
0
] | [] | [] | [
"pipenv",
"python",
"virtualenv"
] | stackoverflow_0074400120_pipenv_python_virtualenv.txt |
Q:
How to use try/except blocks for multiple variables that require user input?
while True:
try:
age = int(input("Enter your age: "))
if age <= 0:
raise TypeError("Enter a number greater than zero")
except ValueError:
print("Invalid age. Must be a number.")
except TypeE... | How to use try/except blocks for multiple variables that require user input? | while True:
try:
age = int(input("Enter your age: "))
if age <= 0:
raise TypeError("Enter a number greater than zero")
except ValueError:
print("Invalid age. Must be a number.")
except TypeError as err:
print(err)
except:
print('Invalid input')
bre... | [
"You can put your user input request into a function that is called for each unique variable see the following as an example:\n# Function to request input and verify input type is valid\ndef getInput(prompt, respType= None):\n while True:\n resp = input(prompt)\n if respType == str or respType == N... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"try_except"
] | stackoverflow_0074405899_python_python_3.x_try_except.txt |
Q:
How to multiply every two elements of a list in python
I have a list(string): []
I need to multiply every two elements and than sum up the results
So for the list:[0,1,2,3,4]
I need to get the result: 105.
(0+1)×(1+2)×(2+3)×(3+4)=105
How do I do that?
I tried to write this code:
Lst3= [0,1,2,3,4]
multiply=0
sum=... | How to multiply every two elements of a list in python | I have a list(string): []
I need to multiply every two elements and than sum up the results
So for the list:[0,1,2,3,4]
I need to get the result: 105.
(0+1)×(1+2)×(2+3)×(3+4)=105
How do I do that?
I tried to write this code:
Lst3= [0,1,2,3,4]
multiply=0
sum=0
count=1
for i in lst3:
multiply= i*lst3[i+1]
sum= ... | [
"You can use zip to achieve it. zip is a built-in class, which collects items from the same index of multiple iterators and returns an iterator. In your case, you want to add two adjacent items in a list, so you need to pass two lists to zip with one shifting an item out.\nlst = [0, 1, 2, 3, 4]\n\nresult = 1\nfor a... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074412363_python.txt |
Q:
Python Regular Expression Match All 5 Digit Numbers but None Larger
I'm attempting to string match 5-digit coupon codes spread throughout a HTML web page. For example, 53232, 21032, 40021 etc... I can handle the simpler case of any string of 5 digits with [0-9]{5}, though this also matches 6, 7, 8... n digit numbe... | Python Regular Expression Match All 5 Digit Numbers but None Larger | I'm attempting to string match 5-digit coupon codes spread throughout a HTML web page. For example, 53232, 21032, 40021 etc... I can handle the simpler case of any string of 5 digits with [0-9]{5}, though this also matches 6, 7, 8... n digit numbers. Can someone please suggest how I would modify this regular expressio... | [
">>> import re\n>>> s=\"four digits 1234 five digits 56789 six digits 012345\"\n>>> re.findall(r\"\\D(\\d{5})\\D\", s)\n['56789']\n\nif they can occur at the very beginning or the very end, it's easier to pad the string than mess with special cases\n>>> re.findall(r\"\\D(\\d{5})\\D\", \" \"+s+\" \")\n\n",
"Withou... | [
50,
22,
16,
5,
3,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003532947_python_regex.txt |
Q:
How do you pass a function as an argument to another function, but the initial function's arguments change?
How can you write a function f that takes another function g as an argument, but where function g has arguments that change dynamically depending on what happens in function f?
A pseudocode example would be:... | How do you pass a function as an argument to another function, but the initial function's arguments change? | How can you write a function f that takes another function g as an argument, but where function g has arguments that change dynamically depending on what happens in function f?
A pseudocode example would be:
def function(another_function(parameters)): # another function passed as an argument, with parameters
for i... | [
"Let's create a function that takes two parameters. The first parameter is a reference to a function and the other is a parameter to be used by that function\ndef func1(func, p):\n func(p)\n\nfunc1(print, 'Hello world!')\n\nSo we call func1 with a reference to the built-in print function (doesn't have to be buil... | [
2,
1
] | [] | [] | [
"function",
"python",
"syntax"
] | stackoverflow_0074412498_function_python_syntax.txt |
Q:
login menu is appearing twice
I am creating a simple program that checks a text file for usernames and passwords. if the username and password is found a message is printed and access to granted. it returns the success message if the details are correct however when i run my code i am prompted to enter my username... | login menu is appearing twice | I am creating a simple program that checks a text file for usernames and passwords. if the username and password is found a message is printed and access to granted. it returns the success message if the details are correct however when i run my code i am prompted to enter my username and password twice.
this is the co... | [
"login is called twice. On user_found = login() and\nelif options == \"2\":\n login()\n\nYou should probably only include it in the if-else statement.\nif options == \"1\":\n register()\nelif options == \"2\":\n user_found = login()\nelif options == \"3\":\n sys.exit()\nelse:\n print(\"Please make a ... | [
0,
0
] | [] | [] | [
"authentication",
"loops",
"menu",
"python"
] | stackoverflow_0074412199_authentication_loops_menu_python.txt |
Q:
YouTube Data API - How to authorise app from remote web server
I have a script on a VPS that uploads files to my youtube channel. This is a headless server which I use via a ssh session. I am having a problem with the authorisation part. When I run my script, I am asked to authorise myself using the link provided.... | YouTube Data API - How to authorise app from remote web server | I have a script on a VPS that uploads files to my youtube channel. This is a headless server which I use via a ssh session. I am having a problem with the authorisation part. When I run my script, I am asked to authorise myself using the link provided. As I cannot use a browser on my VPS, I can only paste this link on ... | [
"The issue you are having is that the YouTube api only supports a single form for authorization. with the exception of content owners that own and manage multiple YouTube channels (Note I am and have never gotten this to work. I suspect you may need to be white listed.)\nThe code you are using will connect to a st... | [
2
] | [] | [] | [
"google_api",
"google_api_python_client",
"google_oauth",
"python",
"youtube_api"
] | stackoverflow_0074353803_google_api_google_api_python_client_google_oauth_python_youtube_api.txt |
Q:
Combine two deep learning models: Could not compute output KerasTensor
I face a problem in merging two deep learning models. I'm trying to build two deep learning models for multi-class classification problems, but there is a problem with output layer.
Code:
import numpy as np
import tensorflow as tf
from tensorfl... | Combine two deep learning models: Could not compute output KerasTensor | I face a problem in merging two deep learning models. I'm trying to build two deep learning models for multi-class classification problems, but there is a problem with output layer.
Code:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras import layers
from tensorflow.keras.layers import... | [
"The reason is that you have two inputs and probably you would be passing one input to the model, therefore the model is not able to compute the output at softmax layers, otherwise, your model is fine...\n_input1 = tf.random.normal((1,51238,1,1500))\n_input2 = tf.random.normal((1,51238,1,1500))\n#Now, pass the both... | [
0
] | [] | [] | [
"deep_learning",
"keras",
"python",
"tensorflow"
] | stackoverflow_0074402494_deep_learning_keras_python_tensorflow.txt |
Q:
C programming recursion segmentation fault
I am trying to using with recursion function. But I got failed which is segmentation fault.
#include <stdio.h>
int factorial( int x );
int main(){
factorial(4);
return 0;
}
int factorial( int x ){
return x* factorial(x-1);
}
I have seen the same ... | C programming recursion segmentation fault | I am trying to using with recursion function. But I got failed which is segmentation fault.
#include <stdio.h>
int factorial( int x );
int main(){
factorial(4);
return 0;
}
int factorial( int x ){
return x* factorial(x-1);
}
I have seen the same code in Python and C programming does not giv... | [
"The problem is that you didn´t tell the factorial function when should it end.\nTry instead\nlong factorial(int x) { \n if (n == 0) \n return 1; \n else \n return(x * factorial(x-1)); \n} \n\nLike this when it reaches the number 0 is gonna Stop and return the factorial from x.\nThis work... | [
1,
1
] | [] | [] | [
"error_handling",
"factorial",
"python",
"recursion",
"segmentation_fault"
] | stackoverflow_0074412532_error_handling_factorial_python_recursion_segmentation_fault.txt |
Q:
"cannot access local variable 'a' where it is not associated with a value", but the value is defined
I don't know why when a is located in def test() it can not be found and gives the error
UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
import keyboard
import time
a ... | "cannot access local variable 'a' where it is not associated with a value", but the value is defined | I don't know why when a is located in def test() it can not be found and gives the error
UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
import keyboard
import time
a = 0
def test():
a+= 1
print("The number is now ", a)
time.sleep(1)
while keyboard.is_pressed... | [
"To access a global variable within a function you must specify it with global. Otherwise, the variable inside the function is a local variable that only has utility inside that function. That's why you get the error: \"UnboundLocalError: local variable 'a' referenced before assignment\". Inside the function you ha... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074412503_python.txt |
Q:
Not able to append values from a dataFrame to a google sheet at specific columns
import pandas as pd
import pygsheets
import gspread
from gspread_dataframe import set_with_dataframe
from google.oauth2.service_account import Credentials
def csv_to_sheets():
tokenPath ='path for service account file.json'
sco... | Not able to append values from a dataFrame to a google sheet at specific columns | import pandas as pd
import pygsheets
import gspread
from gspread_dataframe import set_with_dataframe
from google.oauth2.service_account import Credentials
def csv_to_sheets():
tokenPath ='path for service account file.json'
scopes = ['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis... | [
"Modification points:\n\nIt seems that the arguments of values_append is values_append(range, params, body). Ref I thought that this might be the reason of your issue.\n\nWhen this is refrected in your script, how about the following modification?\nFrom:\ngs.values_append('sheet1', {'valueInputOption': 'RAW'}, {'va... | [
2
] | [] | [] | [
"csv",
"google_sheets",
"google_sheets_api",
"gspread",
"python"
] | stackoverflow_0074411988_csv_google_sheets_google_sheets_api_gspread_python.txt |
Q:
Is there a way to insert values into a list of tuple in Python?
I have a empty list of tuple and I wish to enter values inside that tuple.
The desired output is :
lst = [()] --> lst = [(1,2,'string1','string2',3)]
A:
A tuple is, by definition, unchangable.
You may want to replace that tuple with a new one lik... | Is there a way to insert values into a list of tuple in Python? | I have a empty list of tuple and I wish to enter values inside that tuple.
The desired output is :
lst = [()] --> lst = [(1,2,'string1','string2',3)]
| [
"A tuple is, by definition, unchangable.\nYou may want to replace that tuple with a new one like this:\nlst = [()]\nlst[0] = (\"item1\", \"item2\")\n\nIn this way you are replacing the origina tuple with a new one with the desired items. If the tuple is not empty you can do:\nlst[0] = (*lst[0], \"new item\")\n\nHer... | [
1,
0
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0074412648_list_python_tuples.txt |
Q:
Python check if list in list of lists with numpy arrays
I want to check if my query which is of type list is in the database (a list of lists). In the example below it is.
query = [np.array([[4,3],[6,4]]),5,2,1,5]
database = [ [np.array([[8,5],[2,1]]),5,3,1,9],
[np.array([[4,3],[6,4]]),5,2,1,5],
... | Python check if list in list of lists with numpy arrays | I want to check if my query which is of type list is in the database (a list of lists). In the example below it is.
query = [np.array([[4,3],[6,4]]),5,2,1,5]
database = [ [np.array([[8,5],[2,1]]),5,3,1,9],
[np.array([[4,3],[6,4]]),5,2,1,5],
[np.array([[7,2],[6,4]]),0,0,8,5]]
I have tried thi... | [
"Try this:\nquery = [i.tolist() if isinstance(i, np.ndarray) else i for i in query]\nprint(np.any([[i.tolist() if isinstance(i, np.ndarray) else i for i in data] == query for data in database]))\n\nOutput:\nTrue\n\n",
"Since np.array_equal can accept arrays or scalars, you could use it this way:\nIn [107]: any(al... | [
1,
1,
0
] | [] | [] | [
"list",
"numpy",
"python"
] | stackoverflow_0057543856_list_numpy_python.txt |
Q:
GoogleNews- pygooglenews -Could not parse your date error
Using pygooglenews a month ago and it was working, however now there seems to be an error: Could not parse your date
Does anyone know how to bypass this or six this issue?
gn = GoogleNews(lang = 'en')
def get_news(search):
stories = []
start_date = d... | GoogleNews- pygooglenews -Could not parse your date error | Using pygooglenews a month ago and it was working, however now there seems to be an error: Could not parse your date
Does anyone know how to bypass this or six this issue?
gn = GoogleNews(lang = 'en')
def get_news(search):
stories = []
start_date = datetime.date(2020,1,1)
end_date = datetime.date(2021,12,31)
... | [
"THe main reason is because the format is mm/dd/yy so you need to change to\ngn.set_time_range('12/01/2019','12/31/2019')\ngn.set_encode('utf-8')\ngn.search('Christmas')\n\n",
"I also had the same problem but I fixed it by reinstall the regex package.\nHere is what I did.\n!pip install regex==2022.3.2\n\nAnd my p... | [
0,
0
] | [] | [] | [
"date",
"error_handling",
"parsing",
"pygooglenews",
"python"
] | stackoverflow_0073084068_date_error_handling_parsing_pygooglenews_python.txt |
Q:
Decrease time of a function (Python)
I'm trying to create a function in python that from a list of strings will return me a dict where the key(index) shows the most repetitive character for each index between all the strings. for example a list1 = ['one', 'two', 'twin', 'who'] should return index 0=t index 1=w ind... | Decrease time of a function (Python) | I'm trying to create a function in python that from a list of strings will return me a dict where the key(index) shows the most repetitive character for each index between all the strings. for example a list1 = ['one', 'two', 'twin', 'who'] should return index 0=t index 1=w index 2=o index 3=n in fact the most frequent... | [
"Whether something is quick enough is a matter of use case, but this solution uses a couple of seconds to go through the default wordlist available under OS X.\nPython's collections.Counter implements a counter object for you, so you don't have keep track of the counts of multiple possible values yourself.\nI've pa... | [
2,
0
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0074412345_performance_python.txt |
Q:
How to find elements between MergedCells
I have an .xlsx format table
Ive imported it into google docs:
https://docs.google.com/spreadsheets/d/1rlyuBgs_LtRRp5aBFUjyqVmP3Lg0snETeWnvXadZ35o
The table may change daily. The item's data and their amount in this table can change, but the headers (category name, for ex "... | How to find elements between MergedCells | I have an .xlsx format table
Ive imported it into google docs:
https://docs.google.com/spreadsheets/d/1rlyuBgs_LtRRp5aBFUjyqVmP3Lg0snETeWnvXadZ35o
The table may change daily. The item's data and their amount in this table can change, but the headers (category name, for ex "Processors"/"Motherboards", which r placed in ... | [
"I don't see pandas tag but in case you're interested, here is proposition using this library to make an Excel workbook with multiple sheets that refer to the items of each category. We'll use pandas.read_excel to read the original Excel file, then select the items and finally create a new Excel file by using panda... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"python",
"xlsx"
] | stackoverflow_0074412321_excel_openpyxl_python_xlsx.txt |
Q:
Building a simple calculator and having problems with string formatting when returning the remainder
I'm building a basic calculator, and keep getting "TypeError: not all arguments converted during string formatting" at a line with returning the remainder. How can I fix this?
a = (input())
b = (input())
c = str(in... | Building a simple calculator and having problems with string formatting when returning the remainder | I'm building a basic calculator, and keep getting "TypeError: not all arguments converted during string formatting" at a line with returning the remainder. How can I fix this?
a = (input())
b = (input())
c = str(input())
if (b==0.0) and ((c=='mod') or (c=='/') or (c=='div')):
print ('Zero division!')
if c == '+':
... | [
"The function input() returns a String typ you should change it to float(input()) so that you can perform arithmetic operations with it.\n",
"Your input for variable 'a' and 'b' doesn't have any typecasting for float or int, This should fix the problem:\na = float(input())\nb = float(input())\nc = str(input())\ni... | [
0,
0
] | [] | [] | [
"calculator",
"python"
] | stackoverflow_0074412469_calculator_python.txt |
Q:
Windows .bat file to run python script
Try to create a Windows .bat file to achieve the below function:
cd C:\repo\demo
venv\Scripts\activate
python test.py
In Visual Studio Code terminal window, I can run the above lines without issue.
Created a .bat file as below:
cd C:\repo\demo
"C:\Users\jw\AppData\Local\Prog... | Windows .bat file to run python script | Try to create a Windows .bat file to achieve the below function:
cd C:\repo\demo
venv\Scripts\activate
python test.py
In Visual Studio Code terminal window, I can run the above lines without issue.
Created a .bat file as below:
cd C:\repo\demo
"C:\Users\jw\AppData\Local\Programs\Python\Python310\python.exe" "venv\Scri... | [
"You should either remove \"C:\\...\\python.exe\" from the second line:\ncd C:\\repo\\demo\n\"C:\\Users\\jw\\AppData\\Local\\Programs\\Python\\Python310\\python.exe\" \"venv\\Scripts\\activate\"\npython heatmap.py <-- like this\npause\n\nor remove python\ncd C:\\repo\\demo\n\"C:\\Users\\jw\\AppData\\Local\\Program... | [
0,
0
] | [] | [] | [
"batch_file",
"python"
] | stackoverflow_0074386866_batch_file_python.txt |
Q:
how to print specific value in dictionary
data = [
{
'name': 'Instagram',
'follower_count': 346,
'description': 'Social media platform',
'country': 'United States'
},
{
'name': 'Cristiano Ronaldo',
'follower_count': 215,
'description': 'Footballer... | how to print specific value in dictionary | data = [
{
'name': 'Instagram',
'follower_count': 346,
'description': 'Social media platform',
'country': 'United States'
},
{
'name': 'Cristiano Ronaldo',
'follower_count': 215,
'description': 'Footballer',
'country': 'Portugal'
}]
how to... | [
"You have a list of dictionaries, so what you’ll need to do is first index the array before accessing the follower count.\nSomething like:\ndata[i][“follower_count”]\n\nWhere i is some index in the array.\n",
"Basically, just select the dict you want (0 if you want the first) and then select the 'follower_count' ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074411678_python.txt |
Q:
Semaphores on Python
I've started programming in Python a few weeks ago and was trying to use Semaphores to synchronize two simple threads, for learning purposes. Here is what I've got:
import threading
sem = threading.Semaphore()
def fun1():
while True:
sem.acquire()
print(1)
sem.rele... | Semaphores on Python | I've started programming in Python a few weeks ago and was trying to use Semaphores to synchronize two simple threads, for learning purposes. Here is what I've got:
import threading
sem = threading.Semaphore()
def fun1():
while True:
sem.acquire()
print(1)
sem.release()
def fun2():
whi... | [
"It is working fine, its just that its printing too fast for you to see . Try putting a time.sleep() in both functions (a small amount) to sleep the thread for that much amount of time, to actually be able to see both 1 as well as 2.\nExample -\nimport threading\nimport time\nsem = threading.Semaphore()\n\ndef fun1... | [
30,
16,
6,
2,
1,
0
] | [] | [] | [
"multithreading",
"python",
"python_multithreading",
"semaphore"
] | stackoverflow_0031508574_multithreading_python_python_multithreading_semaphore.txt |
Q:
Sending modals data in a channel with pycord
i'm trying to do a suggestion modal in a cog for a pycord discord bot, but I want to send the datas of the modal then I get an error (like always)...
class SuggestModal(Modal):
def __init__(self, bot) -> None:
self.title = "New suggestion:"
self.bot ... | Sending modals data in a channel with pycord | i'm trying to do a suggestion modal in a cog for a pycord discord bot, but I want to send the datas of the modal then I get an error (like always)...
class SuggestModal(Modal):
def __init__(self, bot) -> None:
self.title = "New suggestion:"
self.bot = bot
self.add_item(InputText(label="Usern... | [
"You didn't to pass the bot parameter to the init() method of SuggestModal.\n@slash_command(name=\"suggest\", description=\"Send a suggestion!\")\nasync def suggestion(self, ctx):\n suggest = SuggestModal(self.bot)\n await ctx.interaction.response.send_modal(suggest)\n\n",
"The AttributeError: 'SuggestModal... | [
1,
0,
0
] | [] | [] | [
"asynchronous",
"discord.py",
"pycord",
"python"
] | stackoverflow_0071469180_asynchronous_discord.py_pycord_python.txt |
Q:
How to fix local variable 'id' referenced before assignment
I want to get a variable from a JSON file to python but it says that the local variable 'id' is referenced before assignment
def getInfo(name):
with open("data.json") as file:
file_data = json.load(file)
for i in file_data["data"]:
... | How to fix local variable 'id' referenced before assignment | I want to get a variable from a JSON file to python but it says that the local variable 'id' is referenced before assignment
def getInfo(name):
with open("data.json") as file:
file_data = json.load(file)
for i in file_data["data"]:
if i["name"] == name:
id = i["id"]
return id
| [
"No need to specify a constructor if you don't do anything in it.\ngetInfo() stops iterating when it finds the id\nNo need to keep on looping once it has been found.\nclass Info:\n def getInfo(self,name):\n with open(\"data.json\") as file:\n file_data = json.load(file)\n for i in fi... | [
0,
-1
] | [] | [] | [
"python"
] | stackoverflow_0074412741_python.txt |
Q:
Kill python script, and restart
Currently, I have this script which if it errors, it completely restarts. Which is perfect for what I need.
But there is one problem, I want the script to automatically restart, even when it did not crash. every 30 seconds.
This is what I have:
while True:
try:
do_main_l... | Kill python script, and restart | Currently, I have this script which if it errors, it completely restarts. Which is perfect for what I need.
But there is one problem, I want the script to automatically restart, even when it did not crash. every 30 seconds.
This is what I have:
while True:
try:
do_main_logic()
except:
pass
I a... | [
"If you want to restart each 30 second, maybe you can do a sort of:\nimport time\n\nwhile True:\n try:\n do_main_logic()\n except:\n pass\n finally:\n time.sleep(30)\n\nIn this way at the end of the while, in both cases you hit the try or the except the script will sleep for 30 second.... | [
1,
0,
0
] | [] | [] | [
"automation",
"python"
] | stackoverflow_0074412665_automation_python.txt |
Q:
Switching keys of a dictionary without switching the values
Let's say I have a dictionary like below
myDict = {"a": 1, "b": 2, "c": 3, "d": 4}
and I'm trying to get this result
myDict = {"b": 1, "a": 2, "c": 3, "d": 4}
I tried running using
dictionary[new_key] = dictionary.pop(old_key)
But thats just deleting a... | Switching keys of a dictionary without switching the values | Let's say I have a dictionary like below
myDict = {"a": 1, "b": 2, "c": 3, "d": 4}
and I'm trying to get this result
myDict = {"b": 1, "a": 2, "c": 3, "d": 4}
I tried running using
dictionary[new_key] = dictionary.pop(old_key)
But thats just deleting and appending a new key and value to the dictionary. It would resu... | [
"So I understand you aim to preserve the sequence.\nMake first a new dictionary that maps the old keys to the new keys:\nmapping = {\"a\": \"b\", \"b\": \"a\"}\n\nNow you can generate the new structure\nmy_dict = {mapping.get(key, key): value for key, value in my_dict.items()}\n\nThe get method here tries to map th... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074412818_python.txt |
Q:
Insert data at end of worksheet with pandas in python
I'm working with a data analysis and I have a question that I can't solve, I have 2 .xlsx sheets, both are the same, only with data in different columns, I wanted to add the data from sheet 2, at the end of sheet 1
First I imported the two files
file_excel = p... | Insert data at end of worksheet with pandas in python | I'm working with a data analysis and I have a question that I can't solve, I have 2 .xlsx sheets, both are the same, only with data in different columns, I wanted to add the data from sheet 2, at the end of sheet 1
First I imported the two files
file_excel = pd.read_excel("feedback.xlsx", engine='openpyxl')
file_inser... | [
"It seems that your excelfiles/sheets have different headers, so make sure first that the two dataframes have the same columns (by using pandas.DataFrame.columns) then use pandas.concat.\nTry this :\nfile_insert.columns= file_excel.columns\n\nout_df= pd.concat([file_excel, file_insert], ignore_index=True)\n\n# Outp... | [
0
] | [] | [] | [
"analysis",
"insert",
"pandas",
"python"
] | stackoverflow_0074412771_analysis_insert_pandas_python.txt |
Q:
No module named "numpy" (and tensorflow) even though installed
I have been struggling on this for a while without prevail. I am trying to run a test script with
import numpy as np
array1 = np.array([1,2,3])
However, I get the error "No module named 'numpy'". The same goes for Tensorflow.
But trying "pip install n... | No module named "numpy" (and tensorflow) even though installed | I have been struggling on this for a while without prevail. I am trying to run a test script with
import numpy as np
array1 = np.array([1,2,3])
However, I get the error "No module named 'numpy'". The same goes for Tensorflow.
But trying "pip install numpy" on terminal gives "Requirement already satisfied: numpy in /us... | [
"Make sure you pip install and run scripts in the right python environment (can be python-venv or conda env), you can troubleshoot these with which python and which pip or pip --version\nYou can create venv with\npython3 -m venv env\n\nand make sure you are in the correct python environment by activate it:\nsource ... | [
2,
0
] | [] | [] | [
"module",
"numpy",
"pip",
"python"
] | stackoverflow_0074412804_module_numpy_pip_python.txt |
Q:
cannot access local variable 'nr' where it is not associated with a value
def NearByDoc(request):
if request.method == "POST":
nearby = request.POST.get("NearBy")
nr = nearby
return render(request,'nearbyDoc.html',{'nrb':NearBy_Doctor.objects.all(),'near':nr})
How can I pass "nr" variable ... | cannot access local variable 'nr' where it is not associated with a value | def NearByDoc(request):
if request.method == "POST":
nearby = request.POST.get("NearBy")
nr = nearby
return render(request,'nearbyDoc.html',{'nrb':NearBy_Doctor.objects.all(),'near':nr})
How can I pass "nr" variable to the dictionary?
Help me to solve this. I'm new at Django.
| [
"I think your error may occur when request.method != \"POST\", in which condition, nr is not initialized. I think the following changes may be helpful:\ndef NearByDoc(request):\n nr = None\n if request.method == \"POST\":\n nearby = request.POST.get(\"NearBy\")\n nr = nearby\n return render(r... | [
2
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0074412874_django_django_views_python.txt |
Q:
How to access 'missing' Environmental variables?
I am adding an environmental variable in bashrc, but am unable to see the variables using os.environ.get in a Python file.
I am using Raspbian on a Raspberry Pi 4.
I am setting an environmental variable in “bashrc” as follows:
export DB_USER='emailAddress@gmail.com'... | How to access 'missing' Environmental variables? | I am adding an environmental variable in bashrc, but am unable to see the variables using os.environ.get in a Python file.
I am using Raspbian on a Raspberry Pi 4.
I am setting an environmental variable in “bashrc” as follows:
export DB_USER='emailAddress@gmail.com'
When calling the following on Terminal:
$ env
…I fi... | [
"Since this is a service (so, not your user, as per Chepner's comment) calling something this looks like you want to make the environment variable available system-wide.\n/etc/environment may fit your needs. You would just add\nDB_USER=emailAddress@gmail.com\n\nto it. (no, don't use export)\nSee also https://supe... | [
1,
0,
0
] | [] | [] | [
"environment_variables",
"python",
"python_3.x",
"raspberry_pi"
] | stackoverflow_0074337655_environment_variables_python_python_3.x_raspberry_pi.txt |
Q:
How to replace hex value in bytes file using python
I have a file inside it with values like this:
55 02 00 00 04 29 00 00 69 00 00 00 14 00 00 00 46 31 35 39 42 37 38 44 41 36 34 35 35 34 36 44 5f 23 23 00 00 00 00 00 14 00 00 00 38 43 36 30 31 31 35 33 43 44 33 35 44 32 42 33 5f 23 23 00 07 00 00 00 33 30 31 3... | How to replace hex value in bytes file using python | I have a file inside it with values like this:
55 02 00 00 04 29 00 00 69 00 00 00 14 00 00 00 46 31 35 39 42 37 38 44 41 36 34 35 35 34 36 44 5f 23 23 00 00 00 00 00 14 00 00 00 38 43 36 30 31 31 35 33 43 44 33 35 44 32 42 33 5f 23 23 00 07 00 00 00 33 30 31 30 35 30
I want it to change to this:
55 02 00 00 05 29 00... | [
"I think you need is bytes.fromhex, not bytes.\nimport os\nori = input(\"Enter the hex value to be replaced: \")\nmod = input('Enter the hex value you want to replace:')\noriconvert = bytes.fromhex(ori)\nmodconvert = bytes.fromhex(mod)\nwith open('hero.bytes','rb') as test:\n test = test.read()\n test = test.... | [
0
] | [] | [] | [
"byte",
"hex",
"python"
] | stackoverflow_0074412918_byte_hex_python.txt |
Q:
Is it possible to replace elements of a list with a "for in" iteration in Python?
I'm trying to iterate over a list and change its values with a "for in" loop:
example_string = "This is a string."
for char in example_string :
char = 'r'
example_list = list(example_string)
for char in example_list:
char ... | Is it possible to replace elements of a list with a "for in" iteration in Python? | I'm trying to iterate over a list and change its values with a "for in" loop:
example_string = "This is a string."
for char in example_string :
char = 'r'
example_list = list(example_string)
for char in example_list:
char = 'r'
The string object is not modified by the iteration.
Does the "for in" iteration ... | [
"You can change in a list, but use the index instead:\nexample_string = [\"This is a string.\", \"This is another string\"]\n\nfor i in range(len(example_string)):\n example_string[i] = \"r\"\n\nprint(example_string)\n\n\nIn your example, only the variable would change:\nexample_string = \"This is a string.\"\n\... | [
1,
1,
0
] | [] | [] | [
"for_in_loop",
"list",
"python",
"string"
] | stackoverflow_0074412815_for_in_loop_list_python_string.txt |
Q:
How to find minimum digit in a number using recursion [Python]
I have a function that gets a number and should return the minimum digit.
This is what I was trying to do, but maybe I didn't fully understand how recursion works.
def min_dig(num):
minimum = 9
if num < 10:
return num
min_dig(num / ... | How to find minimum digit in a number using recursion [Python] | I have a function that gets a number and should return the minimum digit.
This is what I was trying to do, but maybe I didn't fully understand how recursion works.
def min_dig(num):
minimum = 9
if num < 10:
return num
min_dig(num / 10)
if num % 10 < minimum:
minimum = num % 10
return... | [
"I think what the recursion trying to do is like this:\ndef min_dig(num):\n if num < 10:\n return num\n return min(num % 10, min_dig(num // 10))\n\nprint(min_dig(98918))\n\nIf the number is smaller than 10, then its minimum digit is itself. If the number is larger than 10, we just compare its last digi... | [
7,
3,
0
] | [
"You have made minimum as your local variable so every time it will assign the value as 9. Try to make it global variable.\nminimum = 9\ndef min_dig(num):\n global minimum\n if num < 10:\n return num\n min_dig(num // 10)\n if num % 10 < minimum:\n minimum = num % 10\n return minimum\n\n... | [
-1
] | [
"python",
"recursion"
] | stackoverflow_0074412991_python_recursion.txt |
Q:
How to write a python function that adds all arguments?
I'd like to write a python function which adds all its arguments, using + operator. Number of arguments are not specified:
def my_func(*args):
return arg1 + arg2 + arg3 + ...
How do I do it?
Best Regards
A:
Just use the sum built-in function
>>> def my... | How to write a python function that adds all arguments? | I'd like to write a python function which adds all its arguments, using + operator. Number of arguments are not specified:
def my_func(*args):
return arg1 + arg2 + arg3 + ...
How do I do it?
Best Regards
| [
"Just use the sum built-in function\n>>> def my_func(*args):\n... return sum(args)\n...\n>>> my_func(1,2,3,4)\n10\n>>>\n\n\nEdit:\nI don't know why you want to avoid sum, but here we go:\n>>> def my_func(*args):\n... return reduce((lambda x, y: x + y), args)\n...\n>>> my_func(1,2,3,4)\n10\n>>>\n\nInstead of t... | [
18,
6,
1
] | [
"def sumall(*args):\n sum_ = 0\n for num in args:\n sum_ += num\n return sum_\n\nprint(sumall(1,5,7))\n\nThe output is 13.\n"
] | [
-1
] | [
"add",
"arguments",
"function",
"python"
] | stackoverflow_0011520236_add_arguments_function_python.txt |
Q:
I want to see who clicked the button on Discord.py, how do I do?
I'm making a bot for my Discord server, and I'd like to see who clicks the button for a little project. Can anyone help me?
async def bottoni(ctx):
await buttons.send(
content = "click!",
channel = ctx.channel.id,
componen... | I want to see who clicked the button on Discord.py, how do I do? | I'm making a bot for my Discord server, and I'd like to see who clicks the button for a little project. Can anyone help me?
async def bottoni(ctx):
await buttons.send(
content = "click!",
channel = ctx.channel.id,
components = [
ActionRow([
Button(
... | [
"Reading the docs\n\nSo here is your code\nsync def bottoni(ctx):\n await buttons.send(\n content = \"click!\",\n channel = ctx.channel.id,\n components = [\n ActionRow([\n Button(\n label=\"first\",\n style=ButtonType().Success... | [
2,
0
] | [] | [] | [
"bots",
"button",
"discord",
"python"
] | stackoverflow_0072676399_bots_button_discord_python.txt |
Q:
Why function colis(collision) doesn't work?
Function doesn't work
I tried to make a game, and at the some point all start going wrong.(my english isn't best, i know, sorry)
I use library pygame for my project. I made a function which detect the contact of objects, but when i start the game function doesn't work. I... | Why function colis(collision) doesn't work? | Function doesn't work
I tried to make a game, and at the some point all start going wrong.(my english isn't best, i know, sorry)
I use library pygame for my project. I made a function which detect the contact of objects, but when i start the game function doesn't work. I tried to start it without function and then all ... | [
"Your function colis doesn't do anything. There is no return value. All it does is change the values of a few local variables, variables which go out of scope when the function finishes. Thus the function call colis(x,y,50,50,100,100,200,200) has no effect. The values of x and y are not changed by the function call... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074412381_python.txt |
Q:
Kernel Problems on VSCode
I have been trying to work with a jupyter notebook inside vscode, but when I create it the right kernel appears for like 10 seconds and then it disappears.
When I try to check it in the kernels' list I cannot find it.
How to solve this problem?
Many thanks
I have tried multiple times to s... | Kernel Problems on VSCode | I have been trying to work with a jupyter notebook inside vscode, but when I create it the right kernel appears for like 10 seconds and then it disappears.
When I try to check it in the kernels' list I cannot find it.
How to solve this problem?
Many thanks
I have tried multiple times to select the kernel but it is not ... | [
"\nIn VSCode navigate to extensions, search for Jupyter and install it.\nLink is Jupyter\nRun command prompt as administrator and execute\npython -m pip install jupyter\nRestart VSCode and in the command palette search for Jupyter. You should see an option to select default interpreter, point to your python executa... | [
0
] | [] | [] | [
"jupyter_notebook",
"kernel",
"python",
"visual_studio_code"
] | stackoverflow_0074411842_jupyter_notebook_kernel_python_visual_studio_code.txt |
Q:
Is there an elegant way to check if index can be requested in a numpy array?
I am looking for an elegant way to check if a given index is inside a numpy array (for example for BFS algorithms on a grid).
The following code does what I want:
import numpy as np
def isValid(np_shape: tuple, index: tuple):
if min(... | Is there an elegant way to check if index can be requested in a numpy array? | I am looking for an elegant way to check if a given index is inside a numpy array (for example for BFS algorithms on a grid).
The following code does what I want:
import numpy as np
def isValid(np_shape: tuple, index: tuple):
if min(index) < 0:
return False
for ind,sh in zip(index,np_shape):
if... | [
"You can try:\ndef isValid(np_shape: tuple, index: tuple):\n index = np.array(index)\n return (index >= 0).all() and (index < arr.shape).all()\n\narr = np.zeros((3,5))\nprint(isValid(arr.shape,(0,0))) # True\nprint(isValid(arr.shape,(2,4))) # True\nprint(isValid(arr.shape,(4,4))) # False\n\n",
"I have bench... | [
3,
2
] | [] | [] | [
"built_in",
"numpy",
"python"
] | stackoverflow_0074412630_built_in_numpy_python.txt |
Q:
Django order by combination of direct and related fields
I have the following models:
class Product(models.Model):
name = models.CharField(max_length=50)
stock_quantity = models.IntegerField()
class Variation(models.Model):
parent_product = models.ForeignKey(Product, on_delete=models.CASCADE, related_... | Django order by combination of direct and related fields | I have the following models:
class Product(models.Model):
name = models.CharField(max_length=50)
stock_quantity = models.IntegerField()
class Variation(models.Model):
parent_product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='variations')
stock_quantity = models.IntegerField()... | [
"Product.objects.alias(true_quantity=Case(When(stock_quantity__isnull=True, then=Sum(\"variation__stock_quantity\")), default=F('stock_quantity')).order_by('true_quantity')\n\nalias() allows for additionnal culomn inside your resultset such as related or calculated ones (alias() won't expose the value when manipula... | [
0
] | [] | [] | [
"django",
"django_orm",
"postgresql",
"python"
] | stackoverflow_0074412946_django_django_orm_postgresql_python.txt |
Q:
Finding all distinct graphs with n nodes(networkx)
For example, I want to find all the graphlets with 4 nodes. It will give me 11 distinct graphs.. Is there a function or easy way to generate all these graphs in networkx. I am new to networkx so I do not know all of its features.
I am expecting to get all the uniq... | Finding all distinct graphs with n nodes(networkx) | For example, I want to find all the graphlets with 4 nodes. It will give me 11 distinct graphs.. Is there a function or easy way to generate all these graphs in networkx. I am new to networkx so I do not know all of its features.
I am expecting to get all the unique graphs of fixed size n.
| [
"All the graph variations can be generated with networkx using nx.graph_atlas(), see the docs and the official plot example.\nBy default, this function will generate all graphs that have up to (and including) 6 nodes, so to keep only the four-node graphs an additional condition is needed:\nfrom networkx import grap... | [
2
] | [] | [] | [
"graph",
"graph_neural_network",
"networkx",
"python"
] | stackoverflow_0074411773_graph_graph_neural_network_networkx_python.txt |
Q:
How to get a dictionary from a file to average a users input value and then print
I have a function in my program that is supposed to allow the user to input a name and then display the average times for the name entered. This program uses csv import and to read the file and display the data. The file contains a c... | How to get a dictionary from a file to average a users input value and then print | I have a function in my program that is supposed to allow the user to input a name and then display the average times for the name entered. This program uses csv import and to read the file and display the data. The file contains a column of names, then times for each name (marathon runner) in Boston, Chicago, and NY.
... | [
"A dummy times example.\nTimes should be in seconds but for the sake of the example let's use integers.\ntimes = [{\"name\": \"A\", \"boston\": 2, \"chicago\": 3, \"NY\": 4}, {\"name\": \"B\", \"boston\": 5, \"chicago\": 6, \"NY\": 7}]\n\nUpdated function :\ndef racerAvg(times):\n name = input(\"Please enter rac... | [
0
] | [] | [] | [
"average",
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0074413039_average_dictionary_python_python_3.x.txt |
Q:
How to de-nested a list of list of dictionary into a DataFrame?
I have a list of list of dictionary like this
['[{"date_update":"31-03-2022","diemquatrinh":"6.0"}]',
'[{"date_update":"28-04-2022","diemquatrinh":"6.5"}]',
'[{"date_update":"25-12-2021","diemquatrinh":"6.0"}, {"date_update":"28-04-2022","diemqua... | How to de-nested a list of list of dictionary into a DataFrame? | I have a list of list of dictionary like this
['[{"date_update":"31-03-2022","diemquatrinh":"6.0"}]',
'[{"date_update":"28-04-2022","diemquatrinh":"6.5"}]',
'[{"date_update":"25-12-2021","diemquatrinh":"6.0"}, {"date_update":"28-04-2022","diemquatrinh":"6.25"},{"date_update":"28-07-2022","diemquatrinh":"6.5"}]',
... | [
"First, convert strings to dictionary.\nimport pandas as pd\nimport json\n\nexample_data=['[{\"date_update\":\"31-03-2022\",\"diemquatrinh\":\"6.0\"}]', \n\n'[{\"date_update\":\"28-04-2022\",\"diemquatrinh\":\"6.5\"}]', \n\n'[{\"date_update\":\"25-12-2021\",\"diemquatrinh\":\"6.0\"}, {\"date_update\":\"28-04-2022\... | [
1
] | [] | [] | [
"dataframe",
"nested_lists",
"python"
] | stackoverflow_0074410522_dataframe_nested_lists_python.txt |
Q:
How do I make function decorators and chain them together?
How do I make two decorators in Python that would do the following?
@make_bold
@make_italic
def say():
return "Hello"
Calling say() should return:
"<b><i>Hello</i></b>"
A:
If you are not into long explanations, see Paolo Bergantino’s answer.
Decorato... | How do I make function decorators and chain them together? | How do I make two decorators in Python that would do the following?
@make_bold
@make_italic
def say():
return "Hello"
Calling say() should return:
"<b><i>Hello</i></b>"
| [
"If you are not into long explanations, see Paolo Bergantino’s answer.\nDecorator Basics\nPython’s functions are objects\nTo understand decorators, you must first understand that functions are objects in Python. This has important consequences. Let’s see why with a simple example :\ndef shout(word=\"yes\"):\n re... | [
4673,
3062,
154,
140,
74,
66,
44,
23,
22,
15,
11,
10,
8,
7,
7,
7,
0,
0,
0
] | [] | [] | [
"decorator",
"function",
"python",
"python_decorators"
] | stackoverflow_0000739654_decorator_function_python_python_decorators.txt |
Q:
Kali-Linux: Repeat series of commands in terminal after every few seconds using python script
I want to execute a few commands one after another every few minutes in the terminal, so how can it be done by making a python script
A:
import os
import time
cmds = ["ls /", "ls /etc", "ls /tmp"]
for cmd in cmds:
... | Kali-Linux: Repeat series of commands in terminal after every few seconds using python script | I want to execute a few commands one after another every few minutes in the terminal, so how can it be done by making a python script
| [
"import os\nimport time\n\ncmds = [\"ls /\", \"ls /etc\", \"ls /tmp\"]\nfor cmd in cmds:\n os.system(cmd)\n time.sleep(5*60) # sleep for 5 minutes\n\nTo be improved to get the command status, stdout and stderr, ...\n"
] | [
0
] | [] | [] | [
"kali_linux",
"linux",
"python",
"terminal"
] | stackoverflow_0074413217_kali_linux_linux_python_terminal.txt |
Q:
Ways of dealing with humongous amounts of data? (reading, plotting etc.)
I have to work with gigantic amounts of trading data. I'm talking about around 127,000,000 rows in a BigQuery environment. I am working in a Jupyterlab notebook with limited memory, which causes constant crashes after a certain point and a ce... | Ways of dealing with humongous amounts of data? (reading, plotting etc.) | I have to work with gigantic amounts of trading data. I'm talking about around 127,000,000 rows in a BigQuery environment. I am working in a Jupyterlab notebook with limited memory, which causes constant crashes after a certain point and a certain amount of data. My goal is too generate plots like the following ones:
.... | [
"You can preprocess this in BigQuery. The QUANTILES for the box plot can be calculated in a table. The outliners are the values above Q3 or below Q1. These can be filtered by joining both tables and returning a 3rd table.\ncreate temp table \n tbl as (Select d, rand() y from unnest(generate_array(1,1000)) as d, unn... | [
1
] | [] | [] | [
"bigdata",
"boxplot",
"google_bigquery",
"jupyter_lab",
"python"
] | stackoverflow_0074392013_bigdata_boxplot_google_bigquery_jupyter_lab_python.txt |
Q:
I am trying to extract data from class using selenium but it is not working
I need to scrape data from this website:
https://www.daraz.pk/products/hy-i189662857-s1379994759.html?spm=a2a0e.searchlistcategory.list.3.70426378Fs3yJh&search=1
and html code for this is:
<div class="mod-reviews">
<div class="item">...... | I am trying to extract data from class using selenium but it is not working | I need to scrape data from this website:
https://www.daraz.pk/products/hy-i189662857-s1379994759.html?spm=a2a0e.searchlistcategory.list.3.70426378Fs3yJh&search=1
and html code for this is:
<div class="mod-reviews">
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
<div clas... | [
"These elements only appear after you scroll down the page for a while.\nTry to GUI-Automate that with a javascript injection like this\nfor i in range(25):\n driver.execute_script(\"window.scrollBy(0,100)\")\n\nSadly, that scrolling does not work until you put your mouse cursor there, so there will other gui au... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074413260_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
Blackjack python game
I have to create a blackjack game in python in which the user inputs the number of decks that are being used and the amount of money the user wants to bet. The rules are: o The player places his bet (should be read from the keyboard).
o The dealer and player are dealt two cards (one card... | Blackjack python game | I have to create a blackjack game in python in which the user inputs the number of decks that are being used and the amount of money the user wants to bet. The rules are: o The player places his bet (should be read from the keyboard).
o The dealer and player are dealt two cards (one card of the dealer should be hi... | [
"You have not defined the function total that you call. Try adding this to your code\ndef total(array):\n total = 0\n for card in array:\n if card == \"J\" or card == \"Q\" or card == \"K\":\n total = total + 10\n elif card == \"A\":\n if total >=11:\n total ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074413209_python.txt |
Q:
How do I duplicate a dictionary element and re add it back with a key and value change
dict1 = {"top":{"left":[100],"right":[100],"down":[200]}}
dict2 = {"top1":{"left":[100],"right":[100],"down":[200]},"top2":{"left":[100],"right":[100],"down":[300]}}
Above are two dictionaries, the first being the starting and... | How do I duplicate a dictionary element and re add it back with a key and value change | dict1 = {"top":{"left":[100],"right":[100],"down":[200]}}
dict2 = {"top1":{"left":[100],"right":[100],"down":[200]},"top2":{"left":[100],"right":[100],"down":[300]}}
Above are two dictionaries, the first being the starting and the bottom being the final. I want to duplicate the first one's values and then re-add them... | [
"We use deepcopy so that each item has unique lists, rather than sharing them between all the items. We loop twice, to add two copies to dict2.\nimport copy\n\ndict1 = {\"top\":{\"left\":[100],\"right\":[100],\"down\":[200]}}\n\ndict2 = {}\n\nfor i in range(2):\n # make a copy of {\"left\":[100],\"right\":[100],... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074409099_python.txt |
Q:
Fizz buzz extended
I know how to make a basic fizzbuzz, but now that I am asked to extend it and make it so that the user inputs the number, I cant seem to make it work how the sample code does.
{Game Requirements:
Provide a welcome message,
Ask the user to enter a value,
Check it is correct against the stored val... | Fizz buzz extended | I know how to make a basic fizzbuzz, but now that I am asked to extend it and make it so that the user inputs the number, I cant seem to make it work how the sample code does.
{Game Requirements:
Provide a welcome message,
Ask the user to enter a value,
Check it is correct against the stored value in the sequence,
If t... | [
"This code here assigns the input it receives from the console to a variable called 'answer'. Since the input it got from the console is a string, the 'answer' variable's type becomes a string.\nanswer = input()\n\nAnd when you try to compare a string to and integer it will always return false. This is what is happ... | [
2
] | [] | [] | [
"fizzbuzz",
"python"
] | stackoverflow_0074409915_fizzbuzz_python.txt |
Q:
How to make list of lists from a flat list given specific elements in Python
There is a way to "unflatten" a list in Python (see, for example, HERE). However, how to do that efficiently given specific elements? Here is a slightly altered beginning of Jane Austen's "Pride and Prejudice":
Austen = """ONE: It is a tr... | How to make list of lists from a flat list given specific elements in Python | There is a way to "unflatten" a list in Python (see, for example, HERE). However, how to do that efficiently given specific elements? Here is a slightly altered beginning of Jane Austen's "Pride and Prejudice":
Austen = """ONE: It is a truth universally acknowledged, ONE: that a single man in possession
of a good fortu... | [
"I'd first build a list with all positions of breakpoints with their index in the list. Then use itertools.groupby to avoid adjacent duplicates and return only the indices of the start of each \"new\" list.\nBuild the new list by iteration through that index list with itertools.zip_longest.\nimport itertools\n\npoi... | [
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074412934_list_python.txt |
Q:
How i can fix mypy error: Incompatible types in assignment expression has type Optional
For example, i have a this code:
def func(
a: int | None = None,
b: str | None = None,
):
if not (a or b):
b = "string"
elif a:
b = str(a)
c: str = b
return type(c)
for which the error r... | How i can fix mypy error: Incompatible types in assignment expression has type Optional | For example, i have a this code:
def func(
a: int | None = None,
b: str | None = None,
):
if not (a or b):
b = "string"
elif a:
b = str(a)
c: str = b
return type(c)
for which the error raises:
error: Incompatible types in assignment (expression has type "Optional[str]", variable... | [
"Just use the same type for c in this case within func():\ndef func(a: Optional[int] = None, b: Optional[str] = None):\n if not (a or b):\n b = \"string\"\n elif a:\n b = str(a)\n c: Optional[str] = b\n return type(c)\n\nNote I used the type Optional from the module typing as it is clearer... | [
0
] | [] | [] | [
"mypy",
"python",
"python_3.10",
"python_typing"
] | stackoverflow_0074413332_mypy_python_python_3.10_python_typing.txt |
Q:
Convert all Text Documents from a folder to PDF
I have few text documents in a folder and would like to convert them to PDF Format. I am able to do it individually with the below code. Is there any way to select all the text files from a folder, convert and save them with the original name (as it was for text docu... | Convert all Text Documents from a folder to PDF | I have few text documents in a folder and would like to convert them to PDF Format. I am able to do it individually with the below code. Is there any way to select all the text files from a folder, convert and save them with the original name (as it was for text documents)? Below is the code I used to convert each file... | [
"Use os.listdir() to get the files in the directory you want, filter for text files, and then do your conversion.\nfrom fpdf import FPDF\n\ndef convert_one_file(path):\n pdf = FPDF()\n\n pdf.add_page()\n pdf.set_font(\"Arial\", size = 8)\n\n f = open(path, \"r\")\n\n for x in f:\n pdf.cell(10,... | [
0,
0
] | [] | [] | [
"fpdf",
"pyfpdf",
"python"
] | stackoverflow_0074410563_fpdf_pyfpdf_python.txt |
Q:
Expected shape=(None, 256, 256, 3), found shape=(None, 256, 256, 4)
I'm decoding a base64 image with the following code:
def string_to_image(base64_string):
decoded = base64.b64decode(base64_string)
np_data = np.frombuffer(decoded, np.uint8)
img = cv2.imdecode(np_data, cv2.IMREAD_UNCHANGED)
return ... | Expected shape=(None, 256, 256, 3), found shape=(None, 256, 256, 4) | I'm decoding a base64 image with the following code:
def string_to_image(base64_string):
decoded = base64.b64decode(base64_string)
np_data = np.frombuffer(decoded, np.uint8)
img = cv2.imdecode(np_data, cv2.IMREAD_UNCHANGED)
return img
The goal is to receive an image from the request body, decode it, re... | [
"You could reshape the array by using tf.squeeze after reshaping the tensor. According to documentation, tf.squeeze will remove axis with dimensions 1.\nimage_resized = tf.reshape(decoded_image, (-1, 256, 256, 3, 1))\nimage_resized = tf.squeeze(image_resized)\n\n\n",
"With vijayachandran mariappan comment and An... | [
2,
0
] | [] | [] | [
"base64",
"image_resizing",
"python",
"tensorflow"
] | stackoverflow_0074391030_base64_image_resizing_python_tensorflow.txt |
Q:
How can I use os.path.join on a Tensorflow Tensor?
I'm trying to create a custom Tensorflow dataset using the tensorflow.data.data API. However, my original data consists of many smaller images known as tiles which must be concatenated to form a larger image. These tiles are also undergoing image augmentation. For... | How can I use os.path.join on a Tensorflow Tensor? | I'm trying to create a custom Tensorflow dataset using the tensorflow.data.data API. However, my original data consists of many smaller images known as tiles which must be concatenated to form a larger image. These tiles are also undergoing image augmentation. For this reason, os.path.join is being used. However, os.pa... | [
"Instead of os.path.join you could use tf.strings.join and specify the operator with os.path.sep. Here's a small working example, where you get the folder path from your file path with tf.strings:\nfilepath = tf.convert_to_tensor('C:\\ProgramData\\Anaconda3\\envs\\3.9\\lib\\ntpath.py')\nfolderpath = tf.strings.spli... | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074160837_python_tensorflow.txt |
Q:
Create arbitrary sized in-memory file with python
I am in the process of writing integration tests for an S3 bucket. I therefore need to programmatically create files which I can use in my tests for up- and downloading.
I'm basically looking for a solution similar to how I would do it in bash, i.e.:
mkfile -n 1g ~... | Create arbitrary sized in-memory file with python | I am in the process of writing integration tests for an S3 bucket. I therefore need to programmatically create files which I can use in my tests for up- and downloading.
I'm basically looking for a solution similar to how I would do it in bash, i.e.:
mkfile -n 1g ~/Desktop/MyTestFile
Opposed to above, I would however ... | [
"So I ended up doing this:\nsize = 10000000\n\nwith BytesIO() as buffer: \n buffer.write(bytearray(os.urandom(size)))\n buffer.seek(0)\n ...\n #Use my buffer to do some logic\n\nIt does the trick - i.e. writing a random string to a bytes array and persists it in a BytesIO memorystream.\n"
] | [
0
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074412277_pytest_python.txt |
Q:
How to shuffle order of command in Python?
Like in the title, i want to shuffle order of command ,
a = [print("something"),print("another_thing")]
import random
random.shuffle(a)
for i in a:
print(i)
A:
The easiest way is to use Lambdas:
comms = [lambda: print("something"), lambda: print("another_thing")]
S... | How to shuffle order of command in Python? | Like in the title, i want to shuffle order of command ,
a = [print("something"),print("another_thing")]
import random
random.shuffle(a)
for i in a:
print(i)
| [
"The easiest way is to use Lambdas:\ncomms = [lambda: print(\"something\"), lambda: print(\"another_thing\")]\n\nShuffle the items as you did:\nrandom.shuffle(comms)\n\nThen call the items (and collect the results):\nresults = list(comm() for comm in comms)\n\n"
] | [
1
] | [] | [] | [
"command",
"command_line",
"python",
"shuffle"
] | stackoverflow_0074413326_command_command_line_python_shuffle.txt |
Q:
group by line break and execute regex
From one connector, I receive a very specific string format:
{#{123}#};{#{abc}#}\n{#{345}#};{#{def}#}\n{#{789}#};{#{ghi}#}
I can't change that format. Currently, I use the regex (?s){#{(.*?)}#}. This results in a list ["123", "abc", "345", "def", "789", "ghi"]
Is it possible ... | group by line break and execute regex | From one connector, I receive a very specific string format:
{#{123}#};{#{abc}#}\n{#{345}#};{#{def}#}\n{#{789}#};{#{ghi}#}
I can't change that format. Currently, I use the regex (?s){#{(.*?)}#}. This results in a list ["123", "abc", "345", "def", "789", "ghi"]
Is it possible to get the output grouped by line? Somethin... | [
"Since you have pairs of matches on each line, you can capture them:\nre.findall(r'{#{(.*?)}#};{#{(.*?)}#}', text)\n\nSee the Python demo.\nOutput:\n[('123', 'abc'), ('345', 'def'), ('789', 'ghi')]\n\nNote you should not use (?s) DOTALL inline flag since it makes . match across lines.\n"
] | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074413442_python_regex.txt |
Q:
"UnsupportedOperation: fileno" in Spacy Jupyter Notebook
Anyone might know what this error is about and what to do about it?
Spacy works in python command line interface though.
I have tried to google various parts of the error, but found nothing specific.
This has been on Conda, on Windows 11, with Python 3.9.
Er... | "UnsupportedOperation: fileno" in Spacy Jupyter Notebook | Anyone might know what this error is about and what to do about it?
Spacy works in python command line interface though.
I have tried to google various parts of the error, but found nothing specific.
This has been on Conda, on Windows 11, with Python 3.9.
Error message below for reference.
UnsupportedOperation ... | [
"The issue was temporarily addressed by uninstall the current version of Wasabi with an older one.\npip uninstall wasabi -y\n\npip install wasabi==0.9.1\n\n\nThe folks from Github mentioned that a newer version of Wasabi should avoid this problem.\n",
"I have the same issue. Maybe you can try that.\nconda update ... | [
12,
3,
0
] | [] | [] | [
"import",
"python",
"spacy"
] | stackoverflow_0073161364_import_python_spacy.txt |
Q:
Inconsistent tags between XBRL files from the SEC (EDGAR)
I'm parsing every XBRL files from the SEC through EDGAR in order to retrieve some data (in json format on python).
I have no problem parsing those files. My problem lies in the structure of the XBRL files provided by the SEC, i noticed that some companies u... | Inconsistent tags between XBRL files from the SEC (EDGAR) | I'm parsing every XBRL files from the SEC through EDGAR in order to retrieve some data (in json format on python).
I have no problem parsing those files. My problem lies in the structure of the XBRL files provided by the SEC, i noticed that some companies use some tags and others dont. Some will use "Revenues" while ot... | [
"Indeed, it is the case that filers use inconsistent tagging. This is one of the main challenges for processing XBRL data across filings.\nThere is a list of tags for use by all companies, in the US GAAP taxonomy namespace, however this alone is not enough to solve the problem, as (i) companies might still use diff... | [
0,
0,
0
] | [] | [] | [
"edgar",
"python",
"xbrl"
] | stackoverflow_0074122589_edgar_python_xbrl.txt |
Q:
While loop in a CUDA thread blocking other thread from running
While I have 5 CUDA threads, I hope the first thread to wait for the other four thread to finish running and adding increment to a counter, so the first thread will finish only when the other 4 threads are finished and the counter becomes 4.
The while ... | While loop in a CUDA thread blocking other thread from running | While I have 5 CUDA threads, I hope the first thread to wait for the other four thread to finish running and adding increment to a counter, so the first thread will finish only when the other 4 threads are finished and the counter becomes 4.
The while loop in the first thread that I use to make it wait turns out blocki... | [
"I have made it works by adding nanosleep\nimport os\n\n_path = r\"C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.33.31629\\bin\\Hostx64\\x64\"\n\nif os.system(\"cl.exe\"):\n os.environ['PATH'] += ';' + _path\nif os.system(\"cl.exe\"):\n raise RuntimeError(\"cl.exe still not ... | [
0
] | [] | [] | [
"cuda",
"python"
] | stackoverflow_0074409577_cuda_python.txt |
Q:
How can i speed up this python code with parallel processing?
I'm doing a lot of processing on a "big" (80,000 elements) numpy array "x_a"
order = np.arange(1, 101)
rho = [spctr.aryule(x_a, i, norm='biased')[1] for i in order]
(numpy imported as np, spectrum imported as spctr), I'm doing a bunch of independent ca... | How can i speed up this python code with parallel processing? | I'm doing a lot of processing on a "big" (80,000 elements) numpy array "x_a"
order = np.arange(1, 101)
rho = [spctr.aryule(x_a, i, norm='biased')[1] for i in order]
(numpy imported as np, spectrum imported as spctr), I'm doing a bunch of independent calls to a function that takes as input the array (and doesn't modify... | [
"Using multiprocessing here is not a good idea here. In fact, aryule is very inefficient. Parallelizing an inefficient implementation simply waste more resources. Moreover, the way aryule works internally will cause the parallelization not to be much faster. We can actually write a drastically faster implementation... | [
1
] | [] | [] | [
"numpy_ndarray",
"parallel_processing",
"performance",
"python"
] | stackoverflow_0074410243_numpy_ndarray_parallel_processing_performance_python.txt |
Q:
Equivalent of j in NumPy
What is the equivalent of Octave's j in NumPy? How can I use j in Python?
In Octave:
octave:1> j
ans = 0 + 1i
octave:1> j*pi/4
ans = 0.00000 + 0.78540i
But in Python:
>>> import numpy as np
>>> np.imag
<function imag at 0x2368140>
>>> np.imag(3)
array(0)
>>> np.imag(3,2)
Traceback (most... | Equivalent of j in NumPy | What is the equivalent of Octave's j in NumPy? How can I use j in Python?
In Octave:
octave:1> j
ans = 0 + 1i
octave:1> j*pi/4
ans = 0.00000 + 0.78540i
But in Python:
>>> import numpy as np
>>> np.imag
<function imag at 0x2368140>
>>> np.imag(3)
array(0)
>>> np.imag(3,2)
Traceback (most recent call last):
File "<s... | [
"In Python, 1j or 0+1j is a literal of complex type. You can broadcast that into an array using expressions, for example\nIn [17]: 1j * np.arange(5)\nOut[17]: array([ 0.+0.j, 0.+1.j, 0.+2.j, 0.+3.j, 0.+4.j])\n\nCreate an array from literals:\nIn [18]: np.array([1j])\nOut[18]: array([ 0.+1.j])\n\nNote that what ... | [
52,
10,
0
] | [] | [] | [
"complex_numbers",
"numpy",
"python"
] | stackoverflow_0028872862_complex_numbers_numpy_python.txt |
Q:
How do i display in plot sum values that match a given condition
I have like a DataFrame with tables of diff values.
Suppose like i have this data
Fruits Volume
Apple 120
Peach 340
Apple 400
Apple 21
Peach 45
etc... ...
How do i group fruits up, so my plot would not look like picrelated?
A:
... | How do i display in plot sum values that match a given condition | I have like a DataFrame with tables of diff values.
Suppose like i have this data
Fruits Volume
Apple 120
Peach 340
Apple 400
Apple 21
Peach 45
etc... ...
How do i group fruits up, so my plot would not look like picrelated?
| [
"You can try first sorting your dataframe by the column you want to group:\ndf = df.sort_values(\"Fruits\")\n\nand then when you plot (e.g with seaborn) specify the color based on the group:\nimport seaborn as sns\nsns.barplot(data=df, x=\"label\", y=\"Volume\", hue=\"Fruits\")\n\n"
] | [
0
] | [] | [] | [
"data_analysis",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074413578_data_analysis_dataframe_pandas_python.txt |
Q:
How to get user details in serializer in Django rest framework?
I am trying to get users details from django using rest framework. but there is error:
module 'core.model' has no attribute 'Users'
to do that I added this line in settings.py:
REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER':'users.serialize... | How to get user details in serializer in Django rest framework? | I am trying to get users details from django using rest framework. but there is error:
module 'core.model' has no attribute 'Users'
to do that I added this line in settings.py:
REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER':'users.serializers.userSerializer' }
Since it is a model of Django auth and in my mo... | [
"We must import User model like:\nfrom django.contrib.auth.models import User\n\n",
"It seems that you have a custom User model inside the core app.\nBe sure you have substituted your User model inside settings.py:\nAUTH_USER_MODEL = 'myapp.MyUser'\n\nWould be 'core.User' in your case, I believe.\nThen to referen... | [
0,
0
] | [] | [] | [
"django",
"django_admin",
"django_rest_framework",
"python"
] | stackoverflow_0070663255_django_django_admin_django_rest_framework_python.txt |
Q:
How to convert netmask to wildcard with netaddr python library?
I want to convert netmask to wildcard mask with netaddr library
so the input is netmask = 255.255.255.0 and the output is wildcard = 0.0.0.255
or the input is netmask = 255.255.255.252 and the output is wildcard = 0.0.0.3
A:
netaddr not support non-... | How to convert netmask to wildcard with netaddr python library? | I want to convert netmask to wildcard mask with netaddr library
so the input is netmask = 255.255.255.0 and the output is wildcard = 0.0.0.255
or the input is netmask = 255.255.255.252 and the output is wildcard = 0.0.0.3
| [
"netaddr not support non-contiguous wildcard but cisco-acl can help to play with wildcard\nfrom cisco_acl import AddressAg\n\naddress = AddressAg(\"0.0.0.0 255.255.255.0\")\nmask = address.subnet.split()[1]\nwildmask = address.wildcard.split()[1]\nprint(mask) # 255.255.255.0\nprint(wildmask) # 0.0.0.255\n\n",
"... | [
0,
0
] | [] | [] | [
"netmask",
"networking",
"python"
] | stackoverflow_0055673505_netmask_networking_python.txt |
Q:
my for loop doesn't work when i tried to make a user interface
I'm making a user interface but my for loop is not working. i wanted to say somthing when th username was alredy used butmy code yust skips the for loop and then append the username and password to the list. in the txt file stand in each line username;... | my for loop doesn't work when i tried to make a user interface | I'm making a user interface but my for loop is not working. i wanted to say somthing when th username was alredy used butmy code yust skips the for loop and then append the username and password to the list. in the txt file stand in each line username;password
import tkinter as tk
from tkinter import *
root = Tk()
r... | [
".readlines on a file in append mode starts reading from the end of that file\nSo, since from userfile you're only reading, just open it in read mode:\nwith open(\"users.txt\", 'r') as userfile:\n ... # your code\n\n"
] | [
0
] | [] | [] | [
"for_loop",
"python",
"tkinter"
] | stackoverflow_0074413462_for_loop_python_tkinter.txt |
Q:
sorting by lowest key in a dict (Python)
I have a dictionary:
where 0 and 1 are two index and the other numbers inside the two dictionaries are the frequency of each word in a previous list of strings
letter_positions={0: {'l': 1, 'y': 2, 'm': 1, 'r': 2}, 1: {'t': 2, 'e': 1, 'n': 1, 's': 3}}
I get that by a functi... | sorting by lowest key in a dict (Python) | I have a dictionary:
where 0 and 1 are two index and the other numbers inside the two dictionaries are the frequency of each word in a previous list of strings
letter_positions={0: {'l': 1, 'y': 2, 'm': 1, 'r': 2}, 1: {'t': 2, 'e': 1, 'n': 1, 's': 3}}
I get that by a function that return a dictionary with the most freq... | [
"I'd suggest to sort the dictionary by the keys:\nmost_popular = max(sorted(counts.items()), key=lambda v: v[1])\n\n",
"You can switch to min() and change the key= function:\nletter_positions = {\n 0: {\"l\": 1, \"y\": 2, \"m\": 1, \"r\": 2},\n 1: {\"t\": 2, \"e\": 1, \"n\": 1, \"s\": 3},\n}\n\n\nfinal_dict... | [
0,
0,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074413649_python_sorting.txt |
Q:
Is it possible to append different values to different keys of a dictionary?
I have a dictionary:
groups = {'group1': array([450, 449.]), 'group2': array([490, 489.]), 'group3': array([568, 567.])}
I have to iterate over a txt file that I have loaded using numpy.loadtxt() with many values:
subjects =
[1.0, -1.0... | Is it possible to append different values to different keys of a dictionary? | I have a dictionary:
groups = {'group1': array([450, 449.]), 'group2': array([490, 489.]), 'group3': array([568, 567.])}
I have to iterate over a txt file that I have loaded using numpy.loadtxt() with many values:
subjects =
[1.0, -1.0
2.0, 1.0
3.0, 2.0
...
565.0, 564.0
566.0, 565.0
567.0, 566.0
568.0, 567.0]
What ... | [
"You have to make it by parts\nNote: I've done partitally. Analyze this code. Expected result is colse. I've observed array is splitted. I'm redaing dcoumention & looking way to split. Meanwhile explore this logic.Modify accordingly.\nimport numpy as np\nfrom numpy import array\n\n\ngroups = {'group1': array([450,... | [
0
] | [] | [] | [
"append",
"arrays",
"dictionary",
"python"
] | stackoverflow_0074412969_append_arrays_dictionary_python.txt |
Q:
Plotly express order label with a pie chart
Let's take this sample dataframe :
df = pd.DataFrame({"Day":['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
'Proportion':[0.24495486, 0.17300189, 0.23019185, 0.15408692, 0.17827757,0.01100911, 0.0084778]})
Day Proportion
0 M... | Plotly express order label with a pie chart | Let's take this sample dataframe :
df = pd.DataFrame({"Day":['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
'Proportion':[0.24495486, 0.17300189, 0.23019185, 0.15408692, 0.17827757,0.01100911, 0.0084778]})
Day Proportion
0 Monday 0.244955
1 Tuesday 0.173002
2 Wed... | [
"Just add\nfig.update_traces(sort=False) \n\nafter you create the figure and before you save/show the figure.\n",
"Thanks for @Pascalco answer! If you use go (plotly.graph_objects), you can use this\ngo.Pie(labels=x, values=y, sort=False)\n\n"
] | [
3,
0
] | [] | [] | [
"pie_chart",
"plotly",
"plotly_express",
"plotly_python",
"python"
] | stackoverflow_0070353091_pie_chart_plotly_plotly_express_plotly_python_python.txt |
Q:
Get percentage and count in dataframe after group by
Let's say i have a dataframe like this:
name level finished
0 name1 TOP 1
1 name1 NON-TOP 1
2 name1 NON-TOP 1
3 name1 TOP 1
4 name1 TOP 0
5 name1 NON-TOP 0
6 name1 TOP 0
7 ... | Get percentage and count in dataframe after group by | Let's say i have a dataframe like this:
name level finished
0 name1 TOP 1
1 name1 NON-TOP 1
2 name1 NON-TOP 1
3 name1 TOP 1
4 name1 TOP 0
5 name1 NON-TOP 0
6 name1 TOP 0
7 name1 TOP 1
8 name2 TOP 1
9 na... | [
"Let's first calculate the level column. Let's group according to the name column and calculate the distribution of the level column with the value_counts function.\ntop=df.groupby([\"name\"]).agg({\"level\": \"value_counts\"}).unstack(fill_value=0)\ntop.columns = top.columns.to_flat_index()\ntop.columns=[i[1] for ... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074413385_dataframe_pandas_python_python_3.x.txt |
Q:
find highest value in group, and add value of other column to a new row in python pandas
i have the table:
person
score
Job type
person 1
6.5
job 1
person 1
4.3
job 2
person 2
1.2
job 1
person 2
3.4
job 2
person 2
4.3
job 3
i want to ad a column with the job type, with highest score, like this:
person
scor... | find highest value in group, and add value of other column to a new row in python pandas | i have the table:
person
score
Job type
person 1
6.5
job 1
person 1
4.3
job 2
person 2
1.2
job 1
person 2
3.4
job 2
person 2
4.3
job 3
i want to ad a column with the job type, with highest score, like this:
person
score
Job type
Higest score
person 1
6.5
job 1
job 1
person 1
4.3
job 2
job ... | [
"One approach could be as follows:\n\nUse df.groupby on column person, and get idxmax for column score, wrapped inside transform.\nUse the result inside df.loc to select the correct entries from Job type, and add Series.to_numpy to keep only the values (dropping the index values, which won't match).\nAssign to the ... | [
2,
0,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074413419_dataframe_pandas_python.txt |
Q:
Remove duplicate rows based on values in every column using pandas
I have a pandas df of different permutations of values: (toy version below, but my actual df contains more columns and rows)
My goal is to remove the rows that contain duplicate values across rows but critically with also checking all columns.
impo... | Remove duplicate rows based on values in every column using pandas | I have a pandas df of different permutations of values: (toy version below, but my actual df contains more columns and rows)
My goal is to remove the rows that contain duplicate values across rows but critically with also checking all columns.
import itertools
check = list(itertools.permutations([1, 2, 3]))
test = pd.D... | [
"I'm sorry I couldn't find a way without loop\nfor i in test.index:\n if test.loc[i].eq(test.loc[:i-1]).sum().sum() > 0:\n test.drop(i, inplace=True)\n\noutput(test):\n A B C\n0 1 2 3\n3 2 3 1\n4 3 1 2\n\n",
"Here's an alternative, which also doesn't look nice, but is a lot fast... | [
0,
0
] | [] | [] | [
"combinations",
"drop_duplicates",
"pandas",
"python"
] | stackoverflow_0074398684_combinations_drop_duplicates_pandas_python.txt |
Q:
Firebase credentials as Python environment variables: Could not deserialize key data
I'm developing a Python web app with a Firestore realtime database using the firebase_admin library. The Firestore key comes in form of a .json file containing 10 variables. However, I want to store some of these variables as envi... | Firebase credentials as Python environment variables: Could not deserialize key data | I'm developing a Python web app with a Firestore realtime database using the firebase_admin library. The Firestore key comes in form of a .json file containing 10 variables. However, I want to store some of these variables as environment variables so they are not visible publicly. So, I don't use a Firebase SDK .json f... | [
"I HAVE SOLVED THE PROBLEM:\nTo solve the problem with \"\\n\" I had to replace the raw string \"\\n\" with \"\\n\", as (presumably) the environment variables return a raw string, which treats backslash () as a literal character. The solution looks as follows:\nmy_credentials = {\n \"type\": \"service_account\",... | [
0
] | [] | [] | [
"firebase",
"firebase_admin",
"oauth",
"python",
"python_cryptography"
] | stackoverflow_0073917887_firebase_firebase_admin_oauth_python_python_cryptography.txt |
Q:
How to split data from standard input?
I have some number of lines in data for input:
data = sys.stdin.readlines()
Find out the number of lines:
l = len(data)
How can I split this data into variables?
For example I have the following input:
1 0
2 2
0 0 1 1
0 1 1 0
First come 2 numbers - n, m
Then m lines with 4... | How to split data from standard input? | I have some number of lines in data for input:
data = sys.stdin.readlines()
Find out the number of lines:
l = len(data)
How can I split this data into variables?
For example I have the following input:
1 0
2 2
0 0 1 1
0 1 1 0
First come 2 numbers - n, m
Then m lines with 4 values - x1, y1, x2, y2
I tried to do this:... | [
"just handle it section by section\ndata = sys.stdin.readlines()\nindexer = 0\nwhile indexer < len(data) - 1:\n n, m = map(int, data[indexer].split(\" \"))\n indexer = indexer + 1\n some_list = []\n for _ in range(m):\n x1, y1, x2, y2 = map(int, data[indexer].split(\" \"))\n some_list.appe... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"stdin"
] | stackoverflow_0074413626_python_python_3.x_stdin.txt |
Q:
Getting all arguments and values passed to a function
I have a Python function, fetch_data, that goes and hits a remote API, grabs some data, and returns it wrapped in a response object. It looks a bit like the below:
def fetch_data(self, foo, bar, baz, **kwargs):
response = Response()
# Do various things,... | Getting all arguments and values passed to a function | I have a Python function, fetch_data, that goes and hits a remote API, grabs some data, and returns it wrapped in a response object. It looks a bit like the below:
def fetch_data(self, foo, bar, baz, **kwargs):
response = Response()
# Do various things, get some data
return response
Now, it's possible that... | [
"\nEssentially, I'm trying to work out how to, from within a function, get a completely populated *args and **kwargs, including the function's named parameters.\n\nHow about saving the arguments via locals() at the beginning of the function?\ndef my_func(a, *args, **kwargs):\n saved_args = locals()\n print(\"... | [
150,
50,
30,
15,
12,
10,
6,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0010724495_python.txt |
Q:
Opencv imshow is right whereas imwrite is wrong?
I just want to cover an png image with another png image, cv2.imshow got the right result, cv2.imwrite got the strange result.
coverImg = cv2.imread('./images/cover.png', cv2.IMREAD_UNCHANGED)
back = cv2.imread('./images/back.png', cv2.IMREAD_UNCHANGED)
x_offset = ... | Opencv imshow is right whereas imwrite is wrong? | I just want to cover an png image with another png image, cv2.imshow got the right result, cv2.imwrite got the strange result.
coverImg = cv2.imread('./images/cover.png', cv2.IMREAD_UNCHANGED)
back = cv2.imread('./images/back.png', cv2.IMREAD_UNCHANGED)
x_offset = y_offset = 0
y1, y2 = y_offset, y_offset + coverImg.s... | [
"The problem occurs because you're modifying a copy of the original background image, which you loaded as BGRA, but do not modify the alpha channel on the result. Since the background image is mostly transparent (other than the shadows), so is the result when viewed by something that supports alpha.\nTo fix this an... | [
6
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074411256_opencv_python.txt |
Q:
How to split an array according to a condition in numpy?
For example, I have a ndarray that is:
a = np.array([1, 3, 5, 7, 2, 4, 6, 8])
Now I want to split a into two parts, one is all numbers <5 and the other is all >=5:
[array([1,3,2,4]), array([5,7,6,8])]
Certainly I can traverse a and create two new array. Bu... | How to split an array according to a condition in numpy? | For example, I have a ndarray that is:
a = np.array([1, 3, 5, 7, 2, 4, 6, 8])
Now I want to split a into two parts, one is all numbers <5 and the other is all >=5:
[array([1,3,2,4]), array([5,7,6,8])]
Certainly I can traverse a and create two new array. But I want to know does numpy provide some better ways?
Similarl... | [
"import numpy as np\n\ndef split(arr, cond):\n return [arr[cond], arr[~cond]]\n\na = np.array([1,3,5,7,2,4,6,8])\nprint split(a, a<5)\n\na = np.array([[1,2,3],[4,5,6],[7,8,9],[2,4,7]])\nprint split(a, a[:,0]<3)\n\nThis produces the following output:\n[array([1, 3, 2, 4]), array([5, 7, 6, 8])]\n\n[array([[1, 2, 3],... | [
44,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007662458_numpy_python.txt |
Q:
How to scrape values from a dropdown list? ("Li") tag
I'm trying to scrape the countries with their rates from this page: https://www.bossrevolution.ca/en-ca. The webpage has a drop down list which shows all the countries. Once you click on the country you are redirected to a next page and on that webpage you can ... | How to scrape values from a dropdown list? ("Li") tag | I'm trying to scrape the countries with their rates from this page: https://www.bossrevolution.ca/en-ca. The webpage has a drop down list which shows all the countries. Once you click on the country you are redirected to a next page and on that webpage you can see the rate of the country in question. What I basically w... | [
"The data you see on the page is loaded via JavaScript, so beautifulsoup doesn't see them. To get all rates for all countries in Json format you can use next example:\nimport json\nimport requests\n\ncountry_list = \"https://www.bossrevolution.com/en-us/rates/ajax/countries_list\"\nrates_api = \"https://www.bossrev... | [
0
] | [] | [] | [
"html",
"python",
"web_scraping"
] | stackoverflow_0074413708_html_python_web_scraping.txt |
Q:
Format LaTeX expression using Python
I have a poorly formatted LaTeX which needs to be formatted in specific manner to render in Jupyter Notebook correctly:
# Supporting Libraries:
from qiskit.visualization import array_to_latex
from IPython.display import display, Markdown
# Unsuitable LaTeX
latex_baad = '$QFT ... | Format LaTeX expression using Python | I have a poorly formatted LaTeX which needs to be formatted in specific manner to render in Jupyter Notebook correctly:
# Supporting Libraries:
from qiskit.visualization import array_to_latex
from IPython.display import display, Markdown
# Unsuitable LaTeX
latex_baad = '$QFT = \\frac{1}{\\sqrt{32}} \n\n\\begin{bmatri... | [
"use replace to modify it in place, <your_string>.replace('substring to remove','substring to replace')\nI would suggest making all \"\\n\\n\" into \"\\n\", then all \"\\n\" into \" \"\nyour_string.replace(\"\\n\\n\",\"\\n\")\nyour_string.replace(\"\\n\", \" \")\nyour_string.replace(\"////\",\"//\")\n\nFor raw (no ... | [
1,
1
] | [] | [] | [
"jupyter_notebook",
"latex",
"python"
] | stackoverflow_0074413619_jupyter_notebook_latex_python.txt |
Q:
How to install psycopg2 with pg_config error?
I've tried to install psycopg2 (PostgreSQL Database adapater) from this site, but when I try to install after I cd into the package and write
python setup.py install
I get the following error:
Please add the directory containing pg_config to the PATH
or specify th... | How to install psycopg2 with pg_config error? | I've tried to install psycopg2 (PostgreSQL Database adapater) from this site, but when I try to install after I cd into the package and write
python setup.py install
I get the following error:
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python set... | [
"Debian/Ubuntu\n\nPython 2\nsudo apt install libpq-dev python-dev\n\nPython 3\nsudo apt install libpq-dev python3-dev\n\nAdditional\nIf none of the above solve your issue, try\n\nsudo apt install build-essential\nor\n\nsudo apt install postgresql-server-dev-all\n\nWith pip\nInstall the psycopg2-binary PyPI package ... | [
98,
42,
25,
16,
4,
3,
1,
1,
0,
0,
0,
0
] | [
"For people building postgres and psycopg2 from source like me, another solution is here:\nsudo su\nexport PATH=/usr/local/pgsql/bin:$PATH #or path to your pg_config\n\nNow setup.py from psycopg2 could find pg_config correctly.\npython3 setup.py install\n\nor if you just want to use pip3, pip3 install psycopg2 shou... | [
-2
] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0035104097_postgresql_psycopg2_python.txt |
Q:
Installation always stuck on PyCaret 2.2.2 + Package problems
I'm stuck on an issue that I can't seem to solve. I was fine using PyCaret on my other PC and had recently got a new desktop.
I was working on one dataset on my old PC and had no problems with setup() and PyCaret preprocessed my data without any issues.... | Installation always stuck on PyCaret 2.2.2 + Package problems | I'm stuck on an issue that I can't seem to solve. I was fine using PyCaret on my other PC and had recently got a new desktop.
I was working on one dataset on my old PC and had no problems with setup() and PyCaret preprocessed my data without any issues. When I worked on my the same dataset with my new desktop and Jupyt... | [
"I've encountered the very same issues and solved as follows.\nAccording to the documentation, there are a few problems with your setup:\n\nPyCaret is not yet compatible with sklearn>=0.23.2\n\nPyCaret is tested and supported on the following 64-bit systems:\nPython 3.6 – 3.8\nPython 3.9 for Ubuntu only\n\n\nSo if ... | [
0,
0
] | [] | [] | [
"anaconda",
"jupyter",
"pycaret",
"python",
"scikit_learn"
] | stackoverflow_0073491958_anaconda_jupyter_pycaret_python_scikit_learn.txt |
Q:
Splitting the columns and append the values in the dataframe
I have a dataframe which has column as follows:
|REGION/CATEGORY|
|--|-|
|NORTHERN REGION|
|THERMAL|
|HYDRO|
|NUCLEAR|
|WESTERN REGION|
|THERMAL|
|HYDRO|
|NUCLEAR|
|SOUTHERN REGION|
|THERMAL|
|HYDRO|
|NUCLEAR|
|EASTERN REGION|
|THERMAL|
|HYDRO|
|NORTH EA... | Splitting the columns and append the values in the dataframe | I have a dataframe which has column as follows:
|REGION/CATEGORY|
|--|-|
|NORTHERN REGION|
|THERMAL|
|HYDRO|
|NUCLEAR|
|WESTERN REGION|
|THERMAL|
|HYDRO|
|NUCLEAR|
|SOUTHERN REGION|
|THERMAL|
|HYDRO|
|NUCLEAR|
|EASTERN REGION|
|THERMAL|
|HYDRO|
|NORTH EASTERN REGION|
|THERMAL|
|HYDRO|
|ALL INDIA REGION|
|THERMAL|
|HYDR... | [
"For the sake of simplicity I have used a list for the initial data.\ndata = ['NORTHERN REGION','THERMAL','NUCLEAR','HYDRO',\n 'WESTERN REGION','THERMAL','NUCLEAR','HYDRO',\n 'SOUTHERN REGION','THERMAL','NUCLEAR','HYDRO',\n 'EASTERN REGION','THERMAL','HYDRO'\n ]\n\ntransformed = []\n\nfor... | [
0,
0
] | [] | [] | [
"data_cleaning",
"dataframe",
"pandas",
"python",
"split"
] | stackoverflow_0074413628_data_cleaning_dataframe_pandas_python_split.txt |
Q:
Finding minimum number of steps to reach (x,y) from (1,1) : we can increment number by using condition (x,y+x)or(x+y,x)
a = 1
b = 1
x=int(input())
y=int(input())
def minsteps(x,y):
if x==a and y==b:
print(1)
return 1
if x<a and y<b:
print(2)
return 20
count = 1 + ... | Finding minimum number of steps to reach (x,y) from (1,1) : we can increment number by using condition (x,y+x)or(x+y,x) | a = 1
b = 1
x=int(input())
y=int(input())
def minsteps(x,y):
if x==a and y==b:
print(1)
return 1
if x<a and y<b:
print(2)
return 20
count = 1 + min(minsteps(x,x+y),minsteps(x+y,y))
return count
print(minsteps(x,y))
Test case:
(3,2) (input)
2 (output)
Explanation... | [
"Problem statement is quite unclear and you do not really ask a clear question... Of course we understand you get an infinite loop, for the simple reason you don't have a real \"breaking\" statement, in most cases.\nGenerally speaking, I don't understand the algo goal: you start at (1,1) and you want to reach (x,y)... | [
0,
0,
0
] | [] | [] | [
"dynamic",
"dynamic_programming",
"python",
"recursion"
] | stackoverflow_0073623528_dynamic_dynamic_programming_python_recursion.txt |
Q:
Cx_freeze converted executable is not working for ttkbootstrap scripts
After converting my ttkbootstrap project file into exe by using cx_freeze.
When I run the executable file. I get this error and my program does not execute.
File "C:\Users\KANWAR\AppData\Local\Programs\Python\Python310\Lib\site-packages\cx_F... | Cx_freeze converted executable is not working for ttkbootstrap scripts | After converting my ttkbootstrap project file into exe by using cx_freeze.
When I run the executable file. I get this error and my program does not execute.
File "C:\Users\KANWAR\AppData\Local\Programs\Python\Python310\Lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 120, in run
module_init.run(name... | [
"Below is not a real solution.\nOnly first aid.\nIn your environment's Bootstrap folder (site-packages\\ttkbootstrap\\localization),\nPlease rewrite msgcat.py as follows.\nfrom ttkbootstrap.window import get_default_root\n\n\nclass MessageCatalog:\n @staticmethod\n\n def translate(src):\n return src\n\... | [
1,
1
] | [] | [] | [
"cx_freeze",
"python",
"tkinter"
] | stackoverflow_0074326192_cx_freeze_python_tkinter.txt |
Q:
Changing color and marker of dataset using seaborn jointplot
I want to add an additional variable to the plot listed below. At the moment I have a different colour of marker corresponding to a different metal. But for every metal, there is a different geometry, so I would like to add a marker for every colour (e.g... | Changing color and marker of dataset using seaborn jointplot | I want to add an additional variable to the plot listed below. At the moment I have a different colour of marker corresponding to a different metal. But for every metal, there is a different geometry, so I would like to add a marker for every colour (e.g. red dot and red square). When I add "style=POM" I get this error... | [
"style=POM tries to set the parameter style to POM. In seaborn jointplot, the style parameter does not exist \nRef : https://seaborn.pydata.org/generated/seaborn.jointplot.html\nIf you want 1 plot with different colors corresponding to different metals and different markers corresponding to different POM values the... | [
0
] | [] | [] | [
"legend",
"matplotlib",
"python",
"scatter_plot",
"seaborn"
] | stackoverflow_0074412695_legend_matplotlib_python_scatter_plot_seaborn.txt |
Q:
How do I print a value without any brackets or commas or parenthesis?
I want to print out only the value without any brackets or commas or parenthesis. I am using MySQL with python with mysql.connector.
When I run this code I get "('esrvgf',)". But I want to just get "esrvg".
import mysql.connector
mydb = mysql.... | How do I print a value without any brackets or commas or parenthesis? | I want to print out only the value without any brackets or commas or parenthesis. I am using MySQL with python with mysql.connector.
When I run this code I get "('esrvgf',)". But I want to just get "esrvg".
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password"... | [
"cursor.fetchall() returns a list of tuples (see this question), not a string. If you try to print a tuple you Python will add parentheses, and if you try to print a list Python will add brackets. All you need to do is print the first element with x[0]. Like this:\nfor x in myresult:\n print(x[0])\n\nAlternatively... | [
1,
0
] | [] | [] | [
"mysql",
"mysql_connector",
"mysql_python",
"python"
] | stackoverflow_0074413954_mysql_mysql_connector_mysql_python_python.txt |
Q:
Can't set Art Layer Kind in Photoshop
I'm trying to create a tool in Photoshop through python that creates a gradient map layer. When searching through the Adobe VBScript Reference Documentation, the coder is supposed to be able to create a new layer and set its "kind" by executing the following code:
GMapLayer = ... | Can't set Art Layer Kind in Photoshop | I'm trying to create a tool in Photoshop through python that creates a gradient map layer. When searching through the Adobe VBScript Reference Documentation, the coder is supposed to be able to create a new layer and set its "kind" by executing the following code:
GMapLayer = self.doc.artLayers.Add()
GMapLayer.Kind = 1... | [
"I'm not sure why that's happening.\nHowever, there is a scriptlistener workaround. Agreed, it's ugly; but it works!\nTo add a new gradient adjustment layer:\nDim appRef\nSet appRef = CreateObject( \"Photoshop.Application\" )\n\n' Switch off any dialog boxes\nappRef.displayDialogs = 3 \n\nappRef.BringToFront\n\n\n\... | [
0,
0
] | [] | [] | [
"adobe",
"photoshop",
"python",
"vbscript"
] | stackoverflow_0050807584_adobe_photoshop_python_vbscript.txt |
Q:
Is it possible to merge Plotly traces into a single one?
The following code presents a way to add two traces to a Plotly figure:
import plotly.graph_objs as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x = [0, 1, 2, 3], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace 0",
))
fig.add_trace(go.S... | Is it possible to merge Plotly traces into a single one? | The following code presents a way to add two traces to a Plotly figure:
import plotly.graph_objs as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x = [0, 1, 2, 3], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace 0",
))
fig.add_trace(go.Scatter(
x = [5,6,7,8], y = [1, 2, 3, 4],
mode = 'lines... | [
"The other answer here is excellent, but I'll post an alternative solution for those interested. If for some reason you don't want to add another column to your dataframe (or maybe you're not using dataframes), you can specify the color of each trace and put your traces in the same legend group to ensure they toggl... | [
2,
1
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074413330_plotly_python.txt |
Q:
Issue getting OpenCV stream to work with flask on Raspberry Pi Zero 2 W
I am attempting to get an OpenCV video stream running on my Raspberry Pi Zero 2 W using Flask.
The code is as follows:
from flask import Flask, render_template, Response
import cv2
import time
# Initialize the Flask App
app = Flask(__name__)
... | Issue getting OpenCV stream to work with flask on Raspberry Pi Zero 2 W | I am attempting to get an OpenCV video stream running on my Raspberry Pi Zero 2 W using Flask.
The code is as follows:
from flask import Flask, render_template, Response
import cv2
import time
# Initialize the Flask App
app = Flask(__name__)
def gen_frames():
camera = cv2.VideoCapture(0)
while True:
... | [
"One probable cause is the internal debugger conflicting with the reloader. Suggest enabling debug without the reloader:\napp.run(host=\"192.168.7.80\", port=\"5000\", debug=True, use_reloader=False)\n\n"
] | [
0
] | [] | [] | [
"flask",
"opencv",
"python",
"raspberry_pi_zero",
"video_streaming"
] | stackoverflow_0072059909_flask_opencv_python_raspberry_pi_zero_video_streaming.txt |
Q:
Why does `python setup.py sdist` copy the entire directory into the dist file?
I am perplexed why this setup.py file
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst', 'r', encoding='utf-8') as file:
readme = file.read()
setup(
name = 'PDIpy',
package_dir = ... | Why does `python setup.py sdist` copy the entire directory into the dist file? | I am perplexed why this setup.py file
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst', 'r', encoding='utf-8') as file:
readme = file.read()
setup(
name = 'PDIpy',
package_dir = {'pdi':'pdipy'},
packages = find_packages(),
package_data = {
'pdipy':... | [
"I have a similar issues. Tried using the following steps:\n\nRemove dist and *.egg-info folders.\nInstead of using python setup.py sdist, use python -m build --sdist.\n\nMore explanations are explained at this issues\n"
] | [
0
] | [] | [] | [
"pypi",
"python",
"sdist",
"setup.py"
] | stackoverflow_0071731551_pypi_python_sdist_setup.py.txt |
Q:
How to create a column that evaluates the output in 3 other columns in a pandas data frame?
I've the following data frame (df).
GovKeepSecure
BankKeepSecure
OtherKeepSecure
Secure
Yes
Yes
Yes
Yes
No
No
Yes
No
No
Neutral
Yes
Neutral
I'm looking to write a python function that evaluates the first 3 columns, and... | How to create a column that evaluates the output in 3 other columns in a pandas data frame? | I've the following data frame (df).
GovKeepSecure
BankKeepSecure
OtherKeepSecure
Secure
Yes
Yes
Yes
Yes
No
No
Yes
No
No
Neutral
Yes
Neutral
I'm looking to write a python function that evaluates the first 3 columns, and returns the value that occurs more than 2 times in the "Secure"/4th column.
For examp... | [
"You can use np.select for that\na = df[['GovKeepSecure', 'BankKeepSecure', 'OtherKeepSecure']]\n\nyes_counts = a.eq('Yes').sum(1)\nno_counts = a.eq('No').sum(1)\ndf['Secure'] = np.select([yes_counts > no_counts,\n yes_counts < no_counts],\n ['Yes', 'No'],\n ... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074413978_dataframe_pandas_python.txt |
Q:
Show only 2-vowel words from word list; only getting the first one
def vowels(list):
res = []
for word in list:
vowel_n = 0
for x in word:
if x in 'aeiou':
vowel_n+=1
if vowel_n== 2:
res.append(word)
... | Show only 2-vowel words from word list; only getting the first one | def vowels(list):
res = []
for word in list:
vowel_n = 0
for x in word:
if x in 'aeiou':
vowel_n+=1
if vowel_n== 2:
res.append(word)
return res
print(vowels(['tragedy', 'proof', 'dog', 'bug', 'b... | [
"It's probably a good idea to normalise the words to lowercase and work on that. Also, don't use built-in function names as variables:\nVSET = {'a', 'e', 'i', 'o', 'u'}\n\ndef vowels(lst):\n res = []\n for word in map(str.lower, lst):\n if sum(c in VSET for c in word) == 2:\n res.append(word... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074413865_python.txt |
Q:
Python's argparse to show program's version with prog and version string formatting
What's the preferred way of specifying program name and version info within argparse?
__version_info__ = ('2013','03','14')
__version__ = '-'.join(__version_info__)
...
parser.add_argument('-V', '--version', action='version', vers... | Python's argparse to show program's version with prog and version string formatting | What's the preferred way of specifying program name and version info within argparse?
__version_info__ = ('2013','03','14')
__version__ = '-'.join(__version_info__)
...
parser.add_argument('-V', '--version', action='version', version="%(prog)s ("+__version__+")")
http://argparse.googlecode.com/svn/trunk/doc/Argument... | [
"Yes, that's the accepted way. From http://docs.python.org/dev/library/argparse.html#action:\n>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')\n\nYou should of course be embedding the version number in your package in a standard way: Standard way to embed version into python package?\... | [
101,
0
] | [] | [] | [
"argparse",
"python",
"version"
] | stackoverflow_0015405636_argparse_python_version.txt |
Q:
Use of ast.literal_eval
I really do not understand the difference between the output of the two function that I've given below.
What is the use of lambda x: ast.literal_eval(x) if isinstance(x,str) else np.nan here ?
A:
Next time, please do not post pictures of code or data; edit it into the question as text.
B... | Use of ast.literal_eval | I really do not understand the difference between the output of the two function that I've given below.
What is the use of lambda x: ast.literal_eval(x) if isinstance(x,str) else np.nan here ?
| [
"Next time, please do not post pictures of code or data; edit it into the question as text.\nBefore the apply call, the dataframe contains strings that look like Python objects. After the apply call, it contains actual Python objects. Unfortunately, Pandas pretty-prints dataframes in a way that makes it impossible ... | [
1
] | [] | [] | [
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074413899_data_science_dataframe_pandas_python.txt |
Q:
'pyrcc5' is not recognized as an internal or external command (Python PyQt5 & LabelImg)
Installed pyqt5 and lxml via pip for labelimg but receiving the error when trying to execute pyrcc5:
'pyrcc5' is not recognized as an internal or external command,
operable program or batch file.
Using anaconda therefore it has... | 'pyrcc5' is not recognized as an internal or external command (Python PyQt5 & LabelImg) | Installed pyqt5 and lxml via pip for labelimg but receiving the error when trying to execute pyrcc5:
'pyrcc5' is not recognized as an internal or external command,
operable program or batch file.
Using anaconda therefore it has installed to miniconda3\envs\tf\Lib\site-packages\pyqt5. Adding the directory to system path... | [
"Something similar to this : labelImg: 'pyrcc5' is not recognized as an internal or external command\nAre you sure that what you set in PATH is the full directory pointing to where pyrcc5.exe is found?\n"
] | [
0
] | [] | [] | [
"labelimg",
"lxml",
"pyqt5",
"python"
] | stackoverflow_0074414052_labelimg_lxml_pyqt5_python.txt |
Q:
I get an Error 400 on Google when using the authorization link for my Python Google API programs, including ones I know worked for others
I'm working on a code that requires the use of google_auth_oauthlib, but the authorization link that my code produces sends me to a
"400. That’s an error.
The server cannot proc... | I get an Error 400 on Google when using the authorization link for my Python Google API programs, including ones I know worked for others | I'm working on a code that requires the use of google_auth_oauthlib, but the authorization link that my code produces sends me to a
"400. That’s an error.
The server cannot process the request because it is malformed. It should not be retried. That’s all we know."
page.
So I switched tracks and moved to a tutorial and ... | [
"Apparently, you can't use Brave for this because it requires cookies. After switching to Chrome it works fine.\n"
] | [
0
] | [] | [] | [
"google_api",
"google_oauth",
"python"
] | stackoverflow_0074410731_google_api_google_oauth_python.txt |
Q:
How to get the content of 2 lists into 1 tuple
I have
l1 = [1,2,3,4]
and
l2 = [5,6,7,8]
Having that how can I create this tuple ([1, 2, 3, 4], [5, 6, 7, 8])?
The tuple() function only works with 1 argument at max
A:
Consider using surrounding parentheses for clarity:
>>> l1 = [1, 2, 3, 4]
>>> l2 = [5, 6, 7, 8]... | How to get the content of 2 lists into 1 tuple | I have
l1 = [1,2,3,4]
and
l2 = [5,6,7,8]
Having that how can I create this tuple ([1, 2, 3, 4], [5, 6, 7, 8])?
The tuple() function only works with 1 argument at max
| [
"Consider using surrounding parentheses for clarity:\n>>> l1 = [1, 2, 3, 4]\n>>> l2 = [5, 6, 7, 8]\n>>> (l1, l2)\n([1, 2, 3, 4], [5, 6, 7, 8])\n\nHowever, they are not required:\n>>> l1, l2\n>>> ([1, 2, 3, 4], [5, 6, 7, 8])\n\n"
] | [
1
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0074414124_list_python_tuples.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.