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:
Frida python redirect outpout to file
I'm using frida-python to hook android function and I'm trying to redirect the output to a file.
I've tried to redirect stdout to a file :
sys.stdout = open(os.path.join(self.dump_path,'apk_hook.txt'), 'w')
before calling
script = self.session.create_script(open("java_hook.j... | Frida python redirect outpout to file | I'm using frida-python to hook android function and I'm trying to redirect the output to a file.
I've tried to redirect stdout to a file :
sys.stdout = open(os.path.join(self.dump_path,'apk_hook.txt'), 'w')
before calling
script = self.session.create_script(open("java_hook.js").read())
script.load()
But this redirec... | [
"Use send\nJava.use('java.net.URL').$init.overload('java.lang.String').implementation = function(str1) {\n send(dynamic_variable);\n return this.$init(str1);\n};\n\nIn the python side \nf = open('/tmp/log', 'w') \n# ...\ndef on_message(msg, _data):\n f.write(msg['payload'] + '\\n')\n# ...\nscript.on('... | [
2,
0
] | [] | [] | [
"frida",
"python"
] | stackoverflow_0062072031_frida_python.txt |
Q:
Pandas how to group specific column rows together based off another columns values, and show rows that do not have a group
For example, I have this dataFrame,
plates
food
1
eggs
1
bacon
2
waffles
2
toast
3
3
4
cereal
4
milk
The result I want is...
food
eggs bacon
waffles toast
None
cereal milk
This... | Pandas how to group specific column rows together based off another columns values, and show rows that do not have a group | For example, I have this dataFrame,
plates
food
1
eggs
1
bacon
2
waffles
2
toast
3
3
4
cereal
4
milk
The result I want is...
food
eggs bacon
waffles toast
None
cereal milk
This is what I have
result = df['food'].groupby(df['plates'].agg('sum')
but obviously the rows that a... | [
"I'm assuming, the missing values in food column are empty strings (\"\"):\nThen:\nx = df.groupby(\"plates\")[\"food\"].agg(lambda x: \" \".join(x).strip() or np.nan)\nprint(x)\n\nPrints:\nplates\n1 eggs bacon\n2 waffles toast\n3 NaN\n4 cereal milk\nName: food, dtype: object\n\n",
"Try ... | [
1,
0
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074323404_dataframe_group_by_pandas_python.txt |
Q:
Crypto attack on AES ECB
This is a school challenge. Given an encrypted file (which is an audio file) I need to figure out how I can decrypt it. Don't have a key, of course.
Now the clue is that I have a small part of the original plain audio file, but I do not know from which part of the encrypted file it is alig... | Crypto attack on AES ECB | This is a school challenge. Given an encrypted file (which is an audio file) I need to figure out how I can decrypt it. Don't have a key, of course.
Now the clue is that I have a small part of the original plain audio file, but I do not know from which part of the encrypted file it is aligned to. I also know the byte s... | [
"Given a window of 20kb, break it into 16 chunks. If the 20kb of plaintext is not exactly a multiple of 16 bytes, truncate the end of it. Generate a vector of length 20kb/16 = 1280 numbers as follows: assign 0 to the first block. Store it in a dictionary keyed by the block and whose value is the index 0. Move on to... | [
1
] | [] | [] | [
"aes",
"ecb",
"python"
] | stackoverflow_0074322399_aes_ecb_python.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'content' in discord.py (pycord)
I'm trying To make a function that waits for someone message in pycord. And when I'm trying to check it it tells me this error discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: '... | AttributeError: 'NoneType' object has no attribute 'content' in discord.py (pycord) | I'm trying To make a function that waits for someone message in pycord. And when I'm trying to check it it tells me this error discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'content
Here's my code
def check(ctx):
c.e... | [
"Your check receives a Message as its input, not Context. Message.message doesn't exist, the argument passed into that check is already the message.\ndef check(message):\n ...\n return message.content...\n # ^ There is no ctx, \"message\" is the message\n\nYour invocation is also incorrect:\nawait bot... | [
0
] | [] | [] | [
"discord",
"discord.py",
"pycord",
"python"
] | stackoverflow_0074318740_discord_discord.py_pycord_python.txt |
Q:
FFMpeg error while converting from MP4 to MP3 in Python
When I try converting videos from a YouTube playlist, it gives me an error:
"File "C:\Users\fonti\AppData\Local\Programs\Python\Python310\lib\site-packages\ffmpy.py", line 106, in run
raise FFRuntimeError(self.cmd, self.process.returncode, out[0], out[1])
ffm... | FFMpeg error while converting from MP4 to MP3 in Python | When I try converting videos from a YouTube playlist, it gives me an error:
"File "C:\Users\fonti\AppData\Local\Programs\Python\Python310\lib\site-packages\ffmpy.py", line 106, in run
raise FFRuntimeError(self.cmd, self.process.returncode, out[0], out[1])
ffmpy.FFRuntimeError: C:/ffmpeg/bin/ffmpeg.exe -i "Nightcore - T... | [
"We may use full path so FFmpeg can find the files.\nWe may join downloadDirectory with videoTitle for creating full path:\ndef MP3():\n ...\n videoTitle = video.title\n\n videoTitle = os.path.join(downloadDirectory, videoTitle)\n\n new_filename = videoTitle + '.mp3'\n ...\n\n\nCo... | [
1
] | [] | [] | [
"ffmpeg",
"python",
"pytube"
] | stackoverflow_0074318785_ffmpeg_python_pytube.txt |
Q:
How to select one specific parameter from csv file loaded into Python in single row?
I'm trying to get a single parameter from csv file loaded into python.
I created rows and appended into row variable
File is saved like Column : Fruit, Amount, Price
Apple, 30, 0.5
rows = []
with open("practice_file.csv", 'r') as... | How to select one specific parameter from csv file loaded into Python in single row? | I'm trying to get a single parameter from csv file loaded into python.
I created rows and appended into row variable
File is saved like Column : Fruit, Amount, Price
Apple, 30, 0.5
rows = []
with open("practice_file.csv", 'r') as file:
csvreader = csv.reader(file)
header = next(csvreader)
for row in csvrea... | [
"In your code rows[i] represents an entire row of values. To get an individual column value from any particular row you would need to index into your row (row[i][j])\nIn your case (assuming your data is exactly as your image shows), this should work:\nrows = []\nwith open(\"practice_file.csv\", 'r') as file:\n ... | [
0,
0
] | [] | [] | [
"csv",
"file",
"list",
"python"
] | stackoverflow_0074322756_csv_file_list_python.txt |
Q:
I'm trying to build a chatbot, code returns only one error "Intents.JSON" file not found in directory
I attached the image for reference. When I tested the model.py for the bot, it returns 0.0012 loss in epoch. I'm not very familiar with the language, so need some help
I'm trying to resolve that one issue. I need ... | I'm trying to build a chatbot, code returns only one error "Intents.JSON" file not found in directory |
I attached the image for reference. When I tested the model.py for the bot, it returns 0.0012 loss in epoch. I'm not very familiar with the language, so need some help
I'm trying to resolve that one issue. I need someone to review my code. I can share the git URL if requested
| [
"I found the answer to it. When you open the file by using only ./intents.json or intents.json sometimes it can't find it because it runs the code from other directory.\nTry this, I have adapted code from https://stackoverflow.com/a/65174822/11839142:\nfrom pathlib import Path\n\np = Path(__file__).with_name('inten... | [
0
] | [] | [] | [
"chatbot",
"javascript",
"python"
] | stackoverflow_0074323468_chatbot_javascript_python.txt |
Q:
Fastest implementation of a way to adjust pyplot overlapping annotation text? Preferably one that can utilize multi-core and/or GPU resources?
I usually use adjustText to produce labels (annotations) that do not overlap in pyplot.
https://github.com/Phlya/adjustText
But at 10,000 data points for a scatter plot, it... | Fastest implementation of a way to adjust pyplot overlapping annotation text? Preferably one that can utilize multi-core and/or GPU resources? | I usually use adjustText to produce labels (annotations) that do not overlap in pyplot.
https://github.com/Phlya/adjustText
But at 10,000 data points for a scatter plot, it because very slow.
I was wondering if there's anything faster, that perhaps takes advantage of multi-core and/or GPU resources?
| [
"Just created a package for this purpose that is fast due to a more brute force implementation with broadcasting in numpy, textalloc.\nIt generates a plot like below (scattertext design) with ~2000 points in 2.9s on a laptop. Here I use the base setting not to plot texts that end up overlapping after running the al... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0051237359_matplotlib_python.txt |
Q:
How to convert hex str into int array
I have strings of hex, for exemple '01ff6fee32785e366f710df10cc542B4' and I am trying to convert them (efficiently) into an int array 2 characters by 2 characters like [1,255,...].
I tried
c = '8db6796fee32785e366f710df10cc542B4'
c2=[int(x,16) for x in c]
but it only takes ... | How to convert hex str into int array | I have strings of hex, for exemple '01ff6fee32785e366f710df10cc542B4' and I am trying to convert them (efficiently) into an int array 2 characters by 2 characters like [1,255,...].
I tried
c = '8db6796fee32785e366f710df10cc542B4'
c2=[int(x,16) for x in c]
but it only takes the characters one by one.
Can i do it with... | [
"You could range(..) over substrings of length 2:\nc = '8db6796fee32785e366f710df10cc' \nc2=[int(c[i:i+2],16) for i in range(0,len(c),2)]\n\nSo i iterates of the string with steps of 2 and you take a substring of length 2 from i to i+2 (exclusive) with c[i:i+2]. These you convert by taking int(..,16).\nFor your sam... | [
5,
2,
0,
0
] | [] | [] | [
"arrays",
"hex",
"python"
] | stackoverflow_0041848722_arrays_hex_python.txt |
Q:
Why does the player in my pygame game not move?
I'm having an issue where I'm trying to get player controls set up, however when I run the game, the "image" stays the same, so the player doesn't move.
The thing with this is that I've added print functions to see where it doesn't work, but it looks like there shoul... | Why does the player in my pygame game not move? | I'm having an issue where I'm trying to get player controls set up, however when I run the game, the "image" stays the same, so the player doesn't move.
The thing with this is that I've added print functions to see where it doesn't work, but it looks like there should be no issues, so I have no idea why it doesn't work... | [
"You have to set the position of the rectangle from self.player_x instead self.x:\nself.rect.x = self.x\nself.rect.x = self.player_x\n\n"
] | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074292434_pygame_python.txt |
Q:
Trying to attach files PDF one by one
I have some files that i need send to some companies and i'm trying send one by one, but for some reason he is attaching all the files together. How can i fix that?
import os
import pandas as pd
import win32com.client as win32
tabela = pd.read_excel('SepEmpresa.xlsx')
olApp ... | Trying to attach files PDF one by one | I have some files that i need send to some companies and i'm trying send one by one, but for some reason he is attaching all the files together. How can i fix that?
import os
import pandas as pd
import win32com.client as win32
tabela = pd.read_excel('SepEmpresa.xlsx')
olApp = win32.Dispatch('Outlook.Application')
olN... | [
"Assuming that your list of companies is contained in table['Vencidos'], then for each company in that table, you are looping over all files in the path specified (path = \"C:/ArquivosPDF/OK\").\nIn other words, this:\n for files in dirs:\n mailItem.Attachments.Add(os.path.join(os.getcwd(), caminho, f... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074320440_python.txt |
Q:
Efficiently sample batches from only one class at each iteration with PyTorch
I want to train a classifier on ImageNet dataset (1000 classes) and I need each batch to contain 64 images from the same class and consecutive batches from different classes. So far based on @shai's suggestion and this post I have
import... | Efficiently sample batches from only one class at each iteration with PyTorch | I want to train a classifier on ImageNet dataset (1000 classes) and I need each batch to contain 64 images from the same class and consecutive batches from different classes. So far based on @shai's suggestion and this post I have
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from ... | [
"Your code seems fine. The issue here is not the sampler but the preprocessing step you are required to perform in order to sort out the instance indices by their class. Since this is always the same sort, I recommend you cache this information (the data contained inside of self.indices) on your file system such th... | [
3,
2
] | [] | [] | [
"python",
"pytorch",
"pytorch_dataloader"
] | stackoverflow_0074252067_python_pytorch_pytorch_dataloader.txt |
Q:
Python fill empty cells in dataframe based on the values of other column values and conditions
I have the following problem set which I have spent days on trying to find the optimal solution:
giving a country evaluating process having 3 parameters (V1,V2,V3), which may be recorded in sperate dates (Date1,Date2,Dat... | Python fill empty cells in dataframe based on the values of other column values and conditions | I have the following problem set which I have spent days on trying to find the optimal solution:
giving a country evaluating process having 3 parameters (V1,V2,V3), which may be recorded in sperate dates (Date1,Date2,Date3) repsectively, each record of a single parameter is stored in one row, with date and value, as il... | [
"There's no way I can think of without looping over the whole dataset each time you encounter an empty value. With that in mind, this could take a while to run if the file size is large. You may have to switch out date formats if excel auto formats the date differently.\nimport pandas\nfrom datetime import datetime... | [
0
] | [] | [] | [
"dataframe",
"for_loop",
"python"
] | stackoverflow_0074270302_dataframe_for_loop_python.txt |
Q:
chromedriver-autoinstaller from behind a firewall
Is there a way to use chromedriver-autoinstaller behind a firewall ?
Or is there any other better suited solution for maintaining the ChromeDriver when you are behind a firewall ?
A:
This is how I used webdriver manager to solve my issue:
from selenium import we... | chromedriver-autoinstaller from behind a firewall | Is there a way to use chromedriver-autoinstaller behind a firewall ?
Or is there any other better suited solution for maintaining the ChromeDriver when you are behind a firewall ?
| [
"This is how I used webdriver manager to solve my issue:\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom webdriver_manager.core.download_manager import WDMDownloadManager\nfrom webdriver_manager.core.http import HttpClient\nfrom selenium.webdriver.chrome.service impo... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0074311466_python_selenium_selenium_chromedriver.txt |
Q:
Transferring variable's data from one class to another
So I recently started experimenting with oop's and getting the hang of them but I encountered a problem, when the functions from the class "character" are called from the function "dsiplay" only the first function(set_character_type) is excuted and then the p... | Transferring variable's data from one class to another | So I recently started experimenting with oop's and getting the hang of them but I encountered a problem, when the functions from the class "character" are called from the function "dsiplay" only the first function(set_character_type) is excuted and then the program stops without excuting the rest of the functions, I t... | [
"dif is set to an empty String in your Character Object\ndis=Character(\"\",\"\")\n\nSo when you get to these methods, dif is neither true nor false.\ndis.Set_Character_attack()\ndis.Set_Character_defense()\ndis.Set_Character_health()\n\nI tried to debug it with adding an arbitrary True to Character initialization ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074323395_python.txt |
Q:
Discord.py Command signature requires at least 0 parameter(s)
I wanna make a price alert bot. It's just for the fun btw I dın't have any purpose about it but also I wanna run certain code every n minutes. Anyway the most import thing is I am gettin the bellow error rightnow I hope you guys can guide me and help me... | Discord.py Command signature requires at least 0 parameter(s) | I wanna make a price alert bot. It's just for the fun btw I dın't have any purpose about it but also I wanna run certain code every n minutes. Anyway the most import thing is I am gettin the bellow error rightnow I hope you guys can guide me and help me about run certain code every n min. Thank you for ur info.
from di... | [
"The accepted answer is just wrong so I'll leave the actual solution here.\nCorrect answer to the problem\n\n@bot.commands()\n\nThe decorator is bot.command, not commandS.\n\nbot.add_command(start_count)\n\nThis line is unnecessary. @bot.command() already adds the command, as its name suggests. Unnecessarily using ... | [
1
] | [
"There are three problems in you code:\n\ncommand name\n\nIn your code, @bot.command(name=\"\") requires a name in it which is the command name. In order to fix your code, change it to\n@bot.command(name=\"MY_COMMAND_NAME\")\n\n\non ready\n\nIn your code, on_ready() is defined as a bot command, it should be a bot e... | [
-1
] | [
"discord.py",
"python"
] | stackoverflow_0074314984_discord.py_python.txt |
Q:
Python "if" statement does not equal
I am trying to create a function that accepts 5, 10, and 25 as input, re-prompting the user if one of those numbers is not inputted.
def get_paid(y):
while True:
n = int(input("Insert Coin: "))
if n != 5 or 10 or 25:
print(f"Amount Due: {y}")
... | Python "if" statement does not equal | I am trying to create a function that accepts 5, 10, and 25 as input, re-prompting the user if one of those numbers is not inputted.
def get_paid(y):
while True:
n = int(input("Insert Coin: "))
if n != 5 or 10 or 25:
print(f"Amount Due: {y}")
continue
else:
... | [
"if n != 5 or 10 or 25:\n\nmust be spelled as\nif n != 5 or n != 10 or n != 25:\n\n-- or more pythonically as\nif n not in (5, 10, 25):\n\n"
] | [
0
] | [] | [] | [
"equality",
"if_statement",
"python"
] | stackoverflow_0074323633_equality_if_statement_python.txt |
Q:
Pandas DataFrame from nested list of dict
I'm recieving data from facebook api to list of dictionaries. I want to create pandas DataFrame from this list.
data = [{'account_id': '1234', 'account_name': 'account1', 'adset_id': '238', 'adset_name': 'Audio-Video', 'impressions': '24140', 'actions': [{'action_type': 'o... | Pandas DataFrame from nested list of dict | I'm recieving data from facebook api to list of dictionaries. I want to create pandas DataFrame from this list.
data = [{'account_id': '1234', 'account_name': 'account1', 'adset_id': '238', 'adset_name': 'Audio-Video', 'impressions': '24140', 'actions': [{'action_type': 'onsite_conversion.post_save', 'value': '1'}, {'a... | [
"IIUC, you can try to json_normalize and pivot:\ndf = pd.DataFrame(data)\n\ns = df.pop('actions').explode()\n\ndf = df.join(pd\n .json_normalize(s).set_axis(s.index)\n .reset_index()\n .pivot_table(index='index', columns='action_type', values='value', fill_value=0)\n )\n\nprint(df)\n\nOutput:\n account_id ac... | [
0
] | [] | [] | [
"dataframe",
"nested_lists",
"pandas",
"python"
] | stackoverflow_0074323291_dataframe_nested_lists_pandas_python.txt |
Q:
How to translate the route system in django 1 to django 2,3?
In tutorial the author used an old version of urls.py in urlpatterns and I cannot translate
url(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$')
this into
path()
Thanks a lot
I would like to resolve this issue
A:
Use re_path:
re_path(r'^image/(?P<wi... | How to translate the route system in django 1 to django 2,3? | In tutorial the author used an old version of urls.py in urlpatterns and I cannot translate
url(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$')
this into
path()
Thanks a lot
I would like to resolve this issue
| [
"Use re_path:\nre_path(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$')\n\nAlternatively, translate this into a path. This is your view:\ndef something(request, width, height): ...\n\nand in urls.py:\npath(\"image/<int:width>x<int:height>/\", views.something)\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074321137_django_python.txt |
Q:
I want to alter bin ranges format in pandas
I have a data frame and i am creating bins with pd.qcut as following:
us_counties['bins'] = pd.qcut(us_counties['economic connectedness'], q=10,precision=2)
The bins are:
us_counties.bins.cat.categories
IntervalIndex([(0.27999999999999997, 0.58], (0.58, 0.67], (0.67, 0.... | I want to alter bin ranges format in pandas | I have a data frame and i am creating bins with pd.qcut as following:
us_counties['bins'] = pd.qcut(us_counties['economic connectedness'], q=10,precision=2)
The bins are:
us_counties.bins.cat.categories
IntervalIndex([(0.27999999999999997, 0.58], (0.58, 0.67], (0.67, 0.72], (0.72, 0.76], (0.76, 0.81], (0.81, 0.85], (0... | [
"How about something like this?\nmybinlabels = [f'{i.left} - {i.right}' for i in us_counties.bins.cat.categories]\nmybinlabels[0] = [\"<\"+str(i.right) for i in [us_counties.bins.cat.categories[0]]]\nmybinlabels[-1] = [\">\"+str(i.left) for i in [us_counties.bins.cat.categories[-1]]]\nus_counties.bins.cat.categorie... | [
2,
0
] | [] | [] | [
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074318369_jupyter_notebook_pandas_python.txt |
Q:
How to pass Django variable to Vue prop
I'm trying to pass a Django template boolean variable to a Vue component.
At the component I added the variable to the props and specified the type:
Vue.component('my-component', {
props: {
id: {type: Number, required: true},
static_url: {type: String, requir... | How to pass Django variable to Vue prop | I'm trying to pass a Django template boolean variable to a Vue component.
At the component I added the variable to the props and specified the type:
Vue.component('my-component', {
props: {
id: {type: Number, required: true},
static_url: {type: String, required: true},
the_boolean_variable: {typ... | [
"Oh.. I found this ugly work around ..\n{% if client.show_price %}\n<my-component v-bind:id={{ job.pk }}\n static_url=\"{{STATIC_URL}}\"\n v-bind:the_boolean_variable=true>\n</my-component>\n{% else %}\n<my-component v-bind:id={{ job.pk }}\n static_url=\"{{STATIC_URL}}\"\n ... | [
3,
0
] | [] | [] | [
"django",
"javascript",
"python",
"vue.js"
] | stackoverflow_0056445311_django_javascript_python_vue.js.txt |
Q:
Updating a value in a multiple object JSON file
JSON file:
{
"data": [
{
"id": "ec35139e-60b9-458e-95c6-0aa1db7d30d4",
"name": "Jeffrey",
"last_ping": "2022-11-02 17:42:00.765568",
"last_ping_timestamp": 1667407320,
"status": "ok",
... | Updating a value in a multiple object JSON file | JSON file:
{
"data": [
{
"id": "ec35139e-60b9-458e-95c6-0aa1db7d30d4",
"name": "Jeffrey",
"last_ping": "2022-11-02 17:42:00.765568",
"last_ping_timestamp": 1667407320,
"status": "ok",
"secret_key": "BigBook32"
},
{
... | [
"One way is to use jq and edit the json directly\nAnother is to convert into object/array in python, modify it programmatically, then convert it back to JSON. There are plenty of examples online. Have you tried any? Any specific errors you encounter?\n",
"we take data then we edit the last_ping to the current tim... | [
0,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074323710_json_python.txt |
Q:
Droping a column value based on another column condition
I want to compare one column to another, and if a value repeats itself then the code will drop it. Problem is, since all values are repeated between columns, theoretically one column will run out of values and then the code does not run. Anyone knows how can... | Droping a column value based on another column condition | I want to compare one column to another, and if a value repeats itself then the code will drop it. Problem is, since all values are repeated between columns, theoretically one column will run out of values and then the code does not run. Anyone knows how can I fix this?
Here's my df:
df=pd.DataFrame(
{
'col... | [
"You should not combine inplace=True and assignment of the output as this will be None.\nThat said, it looks like you're needing:\nout = df.query('col1 != col2')\n\nOutput:\n col1 col2\n1 blue green\n2 red orange\n3 red None\n4 green None\n5 red None\n6 yellow None\n7 ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074323571_dataframe_pandas_python.txt |
Q:
Trying to extract specific lines of text
{
"username": "testuser",
"votecount": "42",
"votesclaimed": "0",
"lastvotetime": "2022-11-04 09:08:29",
"steamid": "000000000000001"
},
If I have a text file full of these seperated values. I woul... | Trying to extract specific lines of text |
{
"username": "testuser",
"votecount": "42",
"votesclaimed": "0",
"lastvotetime": "2022-11-04 09:08:29",
"steamid": "000000000000001"
},
If I have a text file full of these seperated values. I would like to extract just the line that contains... | [
"\nIt looks like your input file is a JSON file, so you should parse it with ConvertFrom-Json, as follows:\nGet-Content -Raw file.json |\n ConvertFrom-Json | \n ForEach-Object { \n '{0} {1}{2}' -f $_.username, \n $_.votecount, \n ('', 'D')[[int] $_.votecount -gt 25]\n }\n... | [
1
] | [] | [] | [
"powershell",
"python"
] | stackoverflow_0074323529_powershell_python.txt |
Q:
Scipy Delaunay doesn't create faces for all points
When running Delaunay on a set of four points, I expect at least two triangles to be produced. Instead I am returned only one. How can I have all faces produced?
from scipy.spatial import Delaunay
points = [(0, 0, -8), (1, 0, -24), (0, 1, 0), (1, 1, 0)]
triangulat... | Scipy Delaunay doesn't create faces for all points | When running Delaunay on a set of four points, I expect at least two triangles to be produced. Instead I am returned only one. How can I have all faces produced?
from scipy.spatial import Delaunay
points = [(0, 0, -8), (1, 0, -24), (0, 1, 0), (1, 1, 0)]
triangulation = Delaunay(points)
triangulation.simplices
out: [[... | [
"The result is to be expected. You have four points in 3-d. The n-dimensional \"triangulation\" produced by Delaunay is a collection of simplexes, and a simplex in 3-d is a tetrahedron. With just four points, the Delaunay triangulation is a single tetrahedron.\nThe convex hull might be what you want. For that, ... | [
0
] | [] | [] | [
"delaunay",
"python",
"scipy"
] | stackoverflow_0074322709_delaunay_python_scipy.txt |
Q:
how to create a list of new objects in python
I am trying to create a list of new objects in python (as in separate memory locations, not references)
class example:
_name = ""
_words = []
def __init__(self,name):
_name = name
def add_words(self,new_words):
for i in new_words:
... | how to create a list of new objects in python | I am trying to create a list of new objects in python (as in separate memory locations, not references)
class example:
_name = ""
_words = []
def __init__(self,name):
_name = name
def add_words(self,new_words):
for i in new_words:
self._words.append(i)
examples = [example("... | [
"_words = [] at the top of the class makes _words a class variable, not an instance one. All classes instances share _words with how you have it now.\nMake it an instance variable instead:\nclass example:\n def __init__(self,name):\n self._words = []\n\n . . .\n\nYou'll likely want to fix _name as well... | [
1,
0
] | [] | [] | [
"memory",
"oop",
"python",
"reference"
] | stackoverflow_0074323772_memory_oop_python_reference.txt |
Q:
Why is this Python prime number print code not working?
I'm trying to make a simple few lines to print prime numbers between 1000 - 10,000
Shouldn't this code work? I'm taking i and dividing by 2 and saying if it does not equal remainder 0 then print the number as it would be prime.
for i in range(1000, 10000):
... | Why is this Python prime number print code not working? | I'm trying to make a simple few lines to print prime numbers between 1000 - 10,000
Shouldn't this code work? I'm taking i and dividing by 2 and saying if it does not equal remainder 0 then print the number as it would be prime.
for i in range(1000, 10000):
if (i % 2) != 0:
print(i)
| [
"You attempt only prints all odd numbers from 1000 to 10000.\nA naive is_prime function should check all numbers between 2 and sqrt(n) to see if n is evenly divisible by any of them.\nimport math\n\ndef is_prime(n):\n return all(n % i != 0 for i in range(2, int(math.sqrt(n)) + 1))\n\nNow, if you wish to print all ... | [
0,
0
] | [
"Hope this helps:\nfor i in range(1000, 10000):\n for j in range(2, i):\n if i % j == 0:\n break\n else:\n print(i)\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074323763_python.txt |
Q:
Sort one inside another
I have a class Person that contains names and hobbies. Then there's a list that contains people.
person1 = Person("MarySmith", ["dancing", "biking", "cooking"])
person2 = ...
people = [person1, person2,..]
I need to return a list of people sorted alphabetically by their name, and also sor... | Sort one inside another | I have a class Person that contains names and hobbies. Then there's a list that contains people.
person1 = Person("MarySmith", ["dancing", "biking", "cooking"])
person2 = ...
people = [person1, person2,..]
I need to return a list of people sorted alphabetically by their name, and also sort their list of hobbies alpha... | [
"Sort of hobbies can be done in the class itself, You can do an approach like this.\nclass Person:\n def __init__(self, name, hobbies):\n self.name = name\n self.hobbies = sorted(hobbies)\n\ndef sort_people(people: list) -> list:\n name_list = [p.name for p in people]\n return sorted(name_lis... | [
1,
0
] | [] | [] | [
"list",
"oop",
"python",
"sorting"
] | stackoverflow_0074323773_list_oop_python_sorting.txt |
Q:
Is there a way to split data from a cell in a .xlsm to individual arrays in python?
I have .xlsm files that contain 4 values that I want to be able to separate into columns of data. These values are all in a single cell in .xlsm files along with the column names.
I tried reading in the file as
pd.read_excel("1.xls... | Is there a way to split data from a cell in a .xlsm to individual arrays in python? | I have .xlsm files that contain 4 values that I want to be able to separate into columns of data. These values are all in a single cell in .xlsm files along with the column names.
I tried reading in the file as
pd.read_excel("1.xlsm", delimiter = ",")
, but am not able to separate each value into a new column. I want... | [
"That's not working because cell A3 for example contains that entire string. What you can do is split the string at the , which will return a list of Time(s), A, B, C, D.\ndf['A'].str.split(\",\", n=-1, expand=True)\n\nThe n=-1 means to do it for every comma it sees. And expand = True means it will create new colum... | [
0
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"python"
] | stackoverflow_0074323808_dataframe_excel_pandas_python.txt |
Q:
Python 3.10 is the default PyCharm update for pyspark/spark 3.0.0.preview - are these two compatible?
There is documentation that indicates Python 3.9 is the last version compatible with Spark 3.0.0.preview. For someone new at setting up compatibility on Windows using Hadoop, Spark, Scala, Python, and PyCharm, t... | Python 3.10 is the default PyCharm update for pyspark/spark 3.0.0.preview - are these two compatible? | There is documentation that indicates Python 3.9 is the last version compatible with Spark 3.0.0.preview. For someone new at setting up compatibility on Windows using Hadoop, Spark, Scala, Python, and PyCharm, the number of possibilities for compatibility is daunting and while browsing through the first few, given th... | [
"First, don't use preview releases. It's been over 2 years since Spark 3 was released; use at least the latest minor release.\nThat being said, Spark 3 mostly is meant to be used with Hadoop 3. All should work fine on Windows, using Java 11 (your logs say 17)\nYou can use Scala 2.12 or 2.13 for Spark.\nPyspark supp... | [
2
] | [] | [] | [
"hadoop",
"java",
"pyspark",
"python",
"scala"
] | stackoverflow_0074318197_hadoop_java_pyspark_python_scala.txt |
Q:
how to work with dict() when using depth first search tree
Given:
class NoName:
def __init__(self):
self.some_dict = {}
def add_new_node(self, label):
self.some_dict[label] = {}
Consider I call the class how would I use the add_new_node method ? what prams will I need to pass in the add_new_node met... | how to work with dict() when using depth first search tree | Given:
class NoName:
def __init__(self):
self.some_dict = {}
def add_new_node(self, label):
self.some_dict[label] = {}
Consider I call the class how would I use the add_new_node method ? what prams will I need to pass in the add_new_node method ?
NoName.add_new_node('a':1)
obviously, this will not work.... | [
"It's this what you are looking for?\nclass NoName:\n def __init__(self):\n self.some_dict = {}\n\n def add_new_pair_key_value(self, node, value):\n self.some_dict[node] = value\n\n def add_new_whole_node(self, whole_node):\n self.some_dict.update(whole_node)\n\nnoname = NoName()\nnoname.add_new_pair_k... | [
0
] | [] | [] | [
"algorithm",
"depth_first_search",
"python"
] | stackoverflow_0074323820_algorithm_depth_first_search_python.txt |
Q:
I want to reverse a string that has negative numbers by preserving it's format
I stuck at this simple scenario & not able to find smart solution to Reverse a string that has negative number.
Example 1: str = "stack-1flow" #Expected output- wolf-1kcats
#Note may input contain multiple negative like
Example 2: ... | I want to reverse a string that has negative numbers by preserving it's format | I stuck at this simple scenario & not able to find smart solution to Reverse a string that has negative number.
Example 1: str = "stack-1flow" #Expected output- wolf-1kcats
#Note may input contain multiple negative like
Example 2: str = "-1-2stack-1flow" #Expected output - wolf-1kcats-2-1
I want to reverse th... | [
"You can do with re,\nimport re\nre.search(r'-\\d', s).group().join(map(lambda x:x[::-1], re.split(r'-\\d', s)[::-1]))\n\n# 'wolf-1kcats'\n\nSplit the string with re.split (using a regex) and revere the list of elements and join the values with the same regex.\nEDIT\nFor the updated requirements you can do this,\n'... | [
2,
1,
1
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074323479_list_python_python_3.x.txt |
Q:
How would I add to an integer within a dict?
test = {"poop":{"okay":[10]}}
print(test)
For example, I want the 10 within["okay"], to now be 20.
A:
You just need to use square brackets to perform a look up on each level, then once you're at the 10 you can update it.
>>> test = {"poop":{"okay":[10]}}
>>> test
{'p... | How would I add to an integer within a dict? | test = {"poop":{"okay":[10]}}
print(test)
For example, I want the 10 within["okay"], to now be 20.
| [
"You just need to use square brackets to perform a look up on each level, then once you're at the 10 you can update it.\n>>> test = {\"poop\":{\"okay\":[10]}}\n>>> test\n{'poop': {'okay': [10]}}\n\n>>> test['poop']\n{'okay': [10]}\n\n>>> test['poop']['okay']\n[10] # note that this is a list w/ 1 element\n\n>>> test... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074323872_python.txt |
Q:
Finding consecutive numbers from multiple lists in python
Consider, for example, that I have 3 python lists of numbers, like this:
a = [1,5,7]
b = [2,6,8]
c = [4,9]
I need to be able to check if there are consecutive numbers from these lists, one number from each list, and return true if there are.
In the above e... | Finding consecutive numbers from multiple lists in python | Consider, for example, that I have 3 python lists of numbers, like this:
a = [1,5,7]
b = [2,6,8]
c = [4,9]
I need to be able to check if there are consecutive numbers from these lists, one number from each list, and return true if there are.
In the above example, 7 from list a, 8 from list b and 9 from list c are cons... | [
"Can you assume\n\nlists are sorted?\nO(n) memory usage is acceptable?\n\nAs a start, you could merge the lists and then check for consecutive elements. This isn't a complete solution because it would match consecutive elements that all appear in a single list (see comments).\nfrom itertools import chain, pairwise\... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074323805_python_python_3.x.txt |
Q:
Read file content from S3 bucket with boto3
I read the filenames in my S3 bucket by doing
objs = boto3.client.list_objects(Bucket='my_bucket')
while 'Contents' in objs.keys():
objs_contents = objs['Contents']
for i in range(len(objs_contents)):
filename = objs_contents[i]['Key']
N... | Read file content from S3 bucket with boto3 | I read the filenames in my S3 bucket by doing
objs = boto3.client.list_objects(Bucket='my_bucket')
while 'Contents' in objs.keys():
objs_contents = objs['Contents']
for i in range(len(objs_contents)):
filename = objs_contents[i]['Key']
Now, I need to get the actual content of the file,... | [
"boto3 offers a resource model that makes tasks like iterating through objects easier. Unfortunately, StreamingBody doesn't provide readline or readlines. \ns3 = boto3.resource('s3')\nbucket = s3.Bucket('test-bucket')\n# Iterates through all the objects, doing the pagination for you. Each obj\n# is an ObjectSummary... | [
140,
40,
39,
23,
15,
1,
1,
0,
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"boto3",
"python"
] | stackoverflow_0036205481_amazon_s3_amazon_web_services_boto3_python.txt |
Q:
What's the Time Complexity for 'abcde' * 100?
In Python 3, what's the Time Complexity for
'abcde' * 100 ? Is it 100 or 500?
In other words, for a string s of length n, concatenating it m times like:
new_s = s * m
Is the Time Complexity O(mn) or O(m)? Thanks!
A:
A naive implementation such as
new_s = s + s + s +... | What's the Time Complexity for 'abcde' * 100? | In Python 3, what's the Time Complexity for
'abcde' * 100 ? Is it 100 or 500?
In other words, for a string s of length n, concatenating it m times like:
new_s = s * m
Is the Time Complexity O(mn) or O(m)? Thanks!
| [
"A naive implementation such as\nnew_s = s + s + s + s + s . . .\n\nwould be O(m^2 * len(s)). However one hopes that the Python internals are clever and can use the O(m * len(s)) algorithm: Create a buffer of the right length, fill it repeatedly with s, and then create a single result string from the buffer.\n"
] | [
0
] | [] | [] | [
"python",
"time_complexity"
] | stackoverflow_0074323673_python_time_complexity.txt |
Q:
Python How to vectorize this nested loop with pandas | numpy
I have a stock dataset which for the sake of simplicity of this question only has a 'close' column and looks like this:
import pandas as pd
df = pd.DataFrame({'close': [1, 1.01, 1.015, 1.0, 0.98]})
print(df)
close
0 1.000
1 1.010
2 1.015
3 1.00... | Python How to vectorize this nested loop with pandas | numpy | I have a stock dataset which for the sake of simplicity of this question only has a 'close' column and looks like this:
import pandas as pd
df = pd.DataFrame({'close': [1, 1.01, 1.015, 1.0, 0.98]})
print(df)
close
0 1.000
1 1.010
2 1.015
3 1.000
4 0.980
Now I want to classify all datapoints wether they woul... | [
"IIUC, you can use a cumulated min/max and numpy.select:\nimport numpy as np\n\nprofit_pct = 0.01\nloss_pct = 0.01\n\nm1 = df['close'].mul(1+profit_pct).ge(df.loc[::-1,'close'].cummax())\nm2 = df['close'].mul(1-loss_pct).le(df.loc[::-1,'close'].cummin())\n\ndf['long_opportunities'] = np.select([m2, m1], [0, -1], 1)... | [
1,
1
] | [] | [] | [
"numpy",
"pandas",
"python",
"vectorization"
] | stackoverflow_0074322570_numpy_pandas_python_vectorization.txt |
Q:
Total Gini impurity or entropy gain for a scikit-learn decision tree
How can I get the total weighted Gini impurity (or entropy) on a trained decision tree in scikit-learn? For instance, the following code on the titanic dataset,
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import tree
df_titan... | Total Gini impurity or entropy gain for a scikit-learn decision tree | How can I get the total weighted Gini impurity (or entropy) on a trained decision tree in scikit-learn? For instance, the following code on the titanic dataset,
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import tree
df_titanic = pd.read_csv('titanic_data.csv') # a popular dataset
feat_list = ['... | [
"What I ended up doing--to continue with the example in the question posting:\n# determine starting gini impurity (without any decision tree)\nsurv_clss = df_titanic['Survived'][:] # 0=did not survive; 1=survived\np_0 = sum((surv_clss==0))/len(surv_clss)\ngini_start = 1-(p_0**2+(1-p_0)**2)\nprint(\"impurity befor... | [
0
] | [] | [] | [
"entropy",
"python",
"scikit_learn",
"tree"
] | stackoverflow_0074280540_entropy_python_scikit_learn_tree.txt |
Q:
Modify days counter on datetime [Python]
I have this code and I want to count the days between 2 dates.
from datetime import date, datetime
checkin= datetime(2022, 1, 30, 1, 15, 00)
checkout= datetime(2022, 1, 31, 0, 0, 00)
count_days= (checkout - checkin).days
In this case, the result of count_days result is 0,... | Modify days counter on datetime [Python] | I have this code and I want to count the days between 2 dates.
from datetime import date, datetime
checkin= datetime(2022, 1, 30, 1, 15, 00)
checkout= datetime(2022, 1, 31, 0, 0, 00)
count_days= (checkout - checkin).days
In this case, the result of count_days result is 0, because in an operation with 2 datetimes, it ... | [
"Convert them to dates first, with the date method.\nfrom datetime import date, datetime\n\ncheckin = datetime(2022, 1, 30, 1, 15, 00)\ncheckout = datetime(2022, 1, 31, 0, 0, 00)\ncount_days = (checkout.date() - checkin.date()).days\n\n",
"Could you do something like this?\n(assuming you want a minimum since the ... | [
1,
0
] | [] | [] | [
"date",
"datetime",
"python"
] | stackoverflow_0074323902_date_datetime_python.txt |
Q:
How do I create a function/method out of this code and then call it to the main()?
enter code hereThis is the original code that I wrote:
while True:
user_input = (input(">>",))
try:
user_input = int(user_input)
except ValueError:
pass
if user_input in range(1, len(something):
... | How do I create a function/method out of this code and then call it to the main()? | enter code hereThis is the original code that I wrote:
while True:
user_input = (input(">>",))
try:
user_input = int(user_input)
except ValueError:
pass
if user_input in range(1, len(something):
break
I want to put in a method:
`get_user_answer(n: int, p: str) -> int` # This is ... | [
"# get user answer function\ndef get_user_answer():\n while True:\n user_input = (input(\">>\",))\n try:\n user_input = int(user_input)\n except ValueError:\n pass\n if user_input in range(1, len(something):\n break\n\n# main function \ndef main():\n ... | [
0,
0,
0
] | [] | [] | [
"except",
"methods",
"program_entry_point",
"python",
"try_catch"
] | stackoverflow_0074320884_except_methods_program_entry_point_python_try_catch.txt |
Q:
Loop over lines in file, create list from 2nd column
I'm trying to loop over the lines in an output file I created that looks like this:
2020-03-19, 22.0
2020-03-20, 6.0
2020-03-21, 5.0
And then create and print a list with the numbers in the 2nd column.
This is just my main and the function I'm having trouble wi... | Loop over lines in file, create list from 2nd column | I'm trying to loop over the lines in an output file I created that looks like this:
2020-03-19, 22.0
2020-03-20, 6.0
2020-03-21, 5.0
And then create and print a list with the numbers in the 2nd column.
This is just my main and the function I'm having trouble with:
def main():
for file in FILE_PATH_INPUT:
... | [
"If you just want to print the list, you don't need manually add \",\" to each element. Instead, you can write fReadOutputFile in the following way:\ndef fReadOutputFile(pFile):\n casesList = []\n with open(pFile, 'r') as fi:\n lines = fi.readlines()\n for line in lines:\n line = line... | [
1,
1
] | [] | [] | [
"file",
"for_loop",
"list",
"output",
"python"
] | stackoverflow_0074323757_file_for_loop_list_output_python.txt |
Q:
How to concatenate row value with column name
My input table
index
income
Education
age1to_20
age21to_30
1
1
0
1
0
2
2
2
1
0
3
1
0
1
0
4
3
1
0
1
5
1
3
1
0
6
2
0
0
1
Required output table
index
income
Education
age1to_20
age21to_30
1
income_1
Education_0
1
0
2
income_2
Education_2
1
0
3
income_1
Educati... | How to concatenate row value with column name | My input table
index
income
Education
age1to_20
age21to_30
1
1
0
1
0
2
2
2
1
0
3
1
0
1
0
4
3
1
0
1
5
1
3
1
0
6
2
0
0
1
Required output table
index
income
Education
age1to_20
age21to_30
1
income_1
Education_0
1
0
2
income_2
Education_2
1
0
3
income_1
Education_0
1
0
4
income_3
Educati... | [
"The problem with your approach is that you're trying to change the entries of an int column to a string. One solution is to simply add df['income'] = df['income'].astype(str) before your loop. For example, you should find that\ndf['income'] = df['income'].astype(str)\nfor index, row in df.iterrows():\n df.at[in... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074323908_python.txt |
Q:
opencv-python how to detect regions of interest in the same image and split them using opencv?
I am trying to detect ROI's in the same image using opencv with python. I can boundering the all image but I can't split the regions inside the image (the blocks of numbers) in two regions, for example.
My origin image i... | opencv-python how to detect regions of interest in the same image and split them using opencv? | I am trying to detect ROI's in the same image using opencv with python. I can boundering the all image but I can't split the regions inside the image (the blocks of numbers) in two regions, for example.
My origin image is :
Actually, I have this following result:
I want to arrive in this following result:
My code:
i... | [
"Here is one way to do that in Python/OpenCV.\n\nRead the input\nThreshold on red using cv2.inRange()\nApply a horizontal rectangle closing morphology operation wide and tall enough to connect the letters and the rows, but not the two regions.\nSort the contours largest first\nLoop over the top two contours and pri... | [
0
] | [] | [] | [
"computer_vision",
"image_processing",
"opencv",
"python"
] | stackoverflow_0074323630_computer_vision_image_processing_opencv_python.txt |
Q:
DrawRectangleBrick() missing 1 required positional argument: 'y'
I am trying to create a brick wall using turtle for my python coding class and I cannot figure out why I am receiving the error
"DrawRectangleBrick() missing 1 required positional argument: 'y'"
here is where the issue is:
def DrawRectangleBrick(x,y)... | DrawRectangleBrick() missing 1 required positional argument: 'y' | I am trying to create a brick wall using turtle for my python coding class and I cannot figure out why I am receiving the error
"DrawRectangleBrick() missing 1 required positional argument: 'y'"
here is where the issue is:
def DrawRectangleBrick(x,y):
global SQUARE_SIZE
for i in range(4):
if i% 2 == 0:... | [
"Since your DrawRectangleBrick takes to parameters x and y. You need to call the function with 2 parameters as well.\nSo, change all your\nDrawRectangleBrick(xPos)\n\nto\nDrawRectangleBrick(xPos, yPos)\n\n"
] | [
0
] | [] | [] | [
"python",
"python_turtle"
] | stackoverflow_0074323996_python_python_turtle.txt |
Q:
Overriding Token class in Django Rest Framework
New to Django, but here goes, in our use case we need token based authentication but require the token to be linked to a model other than the default 'User' model (django.contrib.auth.models.User). Now to do this, we can rewrite the Token model/class, or we can inher... | Overriding Token class in Django Rest Framework | New to Django, but here goes, in our use case we need token based authentication but require the token to be linked to a model other than the default 'User' model (django.contrib.auth.models.User). Now to do this, we can rewrite the Token model/class, or we can inherit the Token model and add the new field and set the ... | [
"Not sure whether this question is still relevant to you, but for anyone still curious, you should create a subclass of the rest_framework.authentication.TokenAuthentication class in an authentication.py file in your app (user in my case) package, like:\nfrom rest_framework.authentication import TokenAuthentication... | [
0
] | [] | [] | [
"django",
"inheritance",
"python"
] | stackoverflow_0048021343_django_inheritance_python.txt |
Q:
Determine batch size during `tensorflow.keras` Custom Class `call` method
I already asked this question here, but I thought StackOverflow would have more traffic/people that might know the answer.
I'm building a custom keras Layer similar to an example found here. I want the call method inside the class to be abl... | Determine batch size during `tensorflow.keras` Custom Class `call` method | I already asked this question here, but I thought StackOverflow would have more traffic/people that might know the answer.
I'm building a custom keras Layer similar to an example found here. I want the call method inside the class to be able to know what the batch_size of the inputs data flowing through the method is,... | [
"TL;DR --> Use tf.shape(inputs)[0] if you want to capture dynamic batch size in call method, or you can just use static batch size which can be specified in model creation.\n\nUnder the hood TensorFlow decorates call and __call__ (that's what call method calls) method with tf.function. Using print and .shape will n... | [
1
] | [] | [] | [
"keras",
"layer",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0074323570_keras_layer_neural_network_python_tensorflow.txt |
Q:
Checking for value in key-value pair returns false, but its there
relatively new to using Python and the dict structure.
I have imported a CSV file from online and turned it to a dictionary. I use the first row as the Key, and then any other subsequent rows are used as the value.
So for example
becomes
Date {0: '... | Checking for value in key-value pair returns false, but its there | relatively new to using Python and the dict structure.
I have imported a CSV file from online and turned it to a dictionary. I use the first row as the Key, and then any other subsequent rows are used as the value.
So for example
becomes
Date {0: '04-Nov-22', 1: '05-Nov-22'}
USD {0: 0.9872, 1: 2.9872}
JPY {0: 145.19, ... | [
"For a number (int, float) you would not need to put '' around it. '' or \"\" is declaring a string, which means the compiler thinks you're searching for a string when in reality you're searching for a number. Take the image provided below as an example:\nExample\nHere, we have a list of numeric values (ints/floats... | [
3,
0,
0
] | [] | [] | [
"csv",
"dictionary",
"key",
"pandas",
"python"
] | stackoverflow_0074323874_csv_dictionary_key_pandas_python.txt |
Q:
How can I use threading in Python?
I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them.
How do you clearly show tasks being divided for multi-threading?
A:
Since this ques... | How can I use threading in Python? | I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them.
How do you clearly show tasks being divided for multi-threading?
| [
"Since this question was asked in 2010, there has been real simplification in how to do simple multithreading with Python with map and pool.\nThe code below comes from an article/blog post that you should definitely check out (no affiliation) - Parallelism in one line: A Better Model for Day to Day Threading Tasks.... | [
1602,
751,
282,
117,
101,
52,
27,
27,
23,
23,
20,
19,
19,
16,
15,
14,
9,
5,
2,
1,
1,
0
] | [] | [] | [
"concurrency",
"multithreading",
"python",
"python_multithreading"
] | stackoverflow_0002846653_concurrency_multithreading_python_python_multithreading.txt |
Q:
Python Socket Server Window not Opening
I'm trying to make a chat server and I've managed to get the client side working but the host side wont work and I don't know why. There's no errors but the windows just not opening, I've used tkinter many times and have never had this error. I've tried making it into a sepa... | Python Socket Server Window not Opening | I'm trying to make a chat server and I've managed to get the client side working but the host side wont work and I don't know why. There's no errors but the windows just not opening, I've used tkinter many times and have never had this error. I've tried making it into a separate function but it seems to be going to the... | [
"The while loop inside recieve() will make it a blocking function which in turn making main() and universal() blocking functions as well. So window.mainloop() will never be executed and no window will be shown.\nOne of the way is to execute universal() in a thread:\n...\n\nthreading.Thread(target=universal, daemon=... | [
1
] | [] | [] | [
"chatbot",
"python",
"sockets",
"tkinter"
] | stackoverflow_0074323566_chatbot_python_sockets_tkinter.txt |
Q:
Is there a way to track CPU and memory usage of sub processes from another sub process
I want to start a celery process that always runs in the background. I want these running process to be able to track system resource (CPU, RAM, etc) usage of all other processes that will be started when a new task is needed to... | Is there a way to track CPU and memory usage of sub processes from another sub process | I want to start a celery process that always runs in the background. I want these running process to be able to track system resource (CPU, RAM, etc) usage of all other processes that will be started when a new task is needed to be executed in parallel. And then I want the tracking process to log the data to file at a ... | [
"\nhave read about psutil and py-spy. But I am not sure if they can be used to track processes from another parallel process.\n\nYes, they can.\nThey are similar to forking off a $ ps axup ${PID} child.\nIf ps can obtain a statistic, then so can psutil.\n\nUsing wait4() clearly only works for a child.\nUsing getrus... | [
1,
0
] | [] | [] | [
"celery",
"monitoring",
"performance",
"process",
"python"
] | stackoverflow_0074322632_celery_monitoring_performance_process_python.txt |
Q:
Powershell python wrapper: how to get functions to allow arbitrary parameters when using a param block
If a powershell function is wrapping a python function, so long as no param block is specified, its possible to easily pass all arbitrary args through with $args:
Function scl-hython {
& "$pythonDir\python.ex... | Powershell python wrapper: how to get functions to allow arbitrary parameters when using a param block | If a powershell function is wrapping a python function, so long as no param block is specified, its possible to easily pass all arbitrary args through with $args:
Function scl-hython {
& "$pythonDir\python.exe" myscript.py --some-arg hython $args
}
However as soon as I specify a param block (with multiple optional... | [
"To get around this issue you can use the metadata attribute of ValueFromRemainingArguments.\nFunction scl-hython {\n Param(\n [parameter(ValueFromRemainingArguments)]\n $Arguments\n )\n & \"$pythonDir\\python.exe\" myscript.py --some-arg hython $Arguments\n}\n\nAlternatively, you can just us... | [
1
] | [] | [] | [
"arguments",
"powershell",
"python",
"wrapper"
] | stackoverflow_0074324117_arguments_powershell_python_wrapper.txt |
Q:
Python 1 of 2 stop conditions gets ignored in a loop
I am writing this simple function to use power iteration for the dominant eigenvalue. I want to put 2 stop conditionals. One for iterations and one for a precision threshold. But this error calculation does not work.
What a i doing wrong here in principle ?
#pow... | Python 1 of 2 stop conditions gets ignored in a loop | I am writing this simple function to use power iteration for the dominant eigenvalue. I want to put 2 stop conditionals. One for iterations and one for a precision threshold. But this error calculation does not work.
What a i doing wrong here in principle ?
#power ite. vanilla
A = np.random.uniform(low=-5.0, high=10.0,... | [
"Seems to work much better like this.\ndef power_it(matrix, iterations, threshold):\n domeigenvector = np.random.rand(matrix.shape[1])\n counter = np.random.rand(matrix.shape[1])\n it = 0\n error = 0\n for i in range(iterations):\n k1 = np.dot(A, domeigenvector)\n k1norm = np.linalg.nor... | [
0
] | [] | [] | [
"loops",
"math",
"numpy",
"python"
] | stackoverflow_0074324056_loops_math_numpy_python.txt |
Q:
Is there a Python command to convert a string to an integer?
I am a newbie, please forgive my ignorance. I tried researching and reading other articles and questions, but nothing seems to give a proper answer.
If the answer is simply no, please just tell me.
Basically, I'm working on a project for school, and I wa... | Is there a Python command to convert a string to an integer? | I am a newbie, please forgive my ignorance. I tried researching and reading other articles and questions, but nothing seems to give a proper answer.
If the answer is simply no, please just tell me.
Basically, I'm working on a project for school, and I want to be able to take someone's input (i.e. their name) and conver... | [
"The most efficient way of doing this would be to make a for loop over the string and then use sum function to add them all up.\nstring = \"Rob\"\nord_sum = sum(ord(c) for c in string)\nprint(ord_sum)\n\n",
"Try with this:\nname = input()\nnumber = 0\n\nfor letter in name:\n number += ord(letter) \n\nIterate th... | [
3,
2,
1
] | [] | [] | [
"data_conversion",
"integer",
"python",
"string",
"text"
] | stackoverflow_0074323754_data_conversion_integer_python_string_text.txt |
Q:
Problem while creating SparkSession using pyspark
I am new to Spark. I am trying to create a Spark session from pyspark.sql in order to load a .csv file. However, every time I am trying to execute the 2nd line (as shown below), the command keeps on executing for hours & never seems to generate the other lines of t... | Problem while creating SparkSession using pyspark | I am new to Spark. I am trying to create a Spark session from pyspark.sql in order to load a .csv file. However, every time I am trying to execute the 2nd line (as shown below), the command keeps on executing for hours & never seems to generate the other lines of the code.
The code is as follows:
from pyspark.sql impor... | [
"I had same issue and even I wasn't able to create a spark context so through some research I got to know that our installed Spark version should match with our Pyspark version which is pretty weird but it is true and I did the same in my laptop and surprisingly it worked.\nTo check the spark version you have enter... | [
1,
1
] | [] | [] | [
"apache_spark",
"jupyter_notebook",
"pyspark",
"python"
] | stackoverflow_0063053945_apache_spark_jupyter_notebook_pyspark_python.txt |
Q:
How to change a square's color with tkinter
Doing a minesweeper on python using tkinter. I'm trying to make a square white when you click on it but it only makes the first square white.
import random
import tkinter as tk
import time
def init_grille(m, n, n_mines): # Creates the grid with the mines and the numbers... | How to change a square's color with tkinter | Doing a minesweeper on python using tkinter. I'm trying to make a square white when you click on it but it only makes the first square white.
import random
import tkinter as tk
import time
def init_grille(m, n, n_mines): # Creates the grid with the mines and the numbers
grille = []
for i in range(m) :
... | [
"You passed incorrect region (j, i, j, i) to canvas.find_overlapping() inside creuser(), region (*C, *C) should be used instead:\ndef creuser(i, j):\n ...\n #case_id = canvas.find_overlapping(j, i, j, i) # incorrect region\n case_id = canvas.find_overlapping(*C, *C) # correct region\n ...\n\n"
] | [
0
] | [] | [] | [
"minesweeper",
"python",
"tkinter"
] | stackoverflow_0074319518_minesweeper_python_tkinter.txt |
Q:
AttributeError: module 'tweepy' has no attribute 'Client'
I am working with the tweepy library and cannot get past authentication. For some reason, I keep getting the error:
AttributeError: module 'tweepy' has no attribute 'Client'
I have the latest version of tweepy installed.
Code:
import time
import tweepy
cli... | AttributeError: module 'tweepy' has no attribute 'Client' | I am working with the tweepy library and cannot get past authentication. For some reason, I keep getting the error:
AttributeError: module 'tweepy' has no attribute 'Client'
I have the latest version of tweepy installed.
Code:
import time
import tweepy
client = tweepy.Client(consumer_key=api_key,
... | [
"I had the same issue, then I installed a later version and my error got resolved.\npip install tweepy==4.10.1\n\n"
] | [
0
] | [] | [] | [
"python",
"tweepy",
"twitter"
] | stackoverflow_0070980723_python_tweepy_twitter.txt |
Q:
How to merge rows in Pandas dataframe?
I have the following dataset:
I want the result to be :
How do I do this?
I tried groupby JVNo but it didnt give the desired result
A:
df1 = pd.read_csv('a.csv', index_col='JVNo')
print(df1) # will show your first table (your dataset)
df1_cleaned = df1.select_dtypes(objec... | How to merge rows in Pandas dataframe? | I have the following dataset:
I want the result to be :
How do I do this?
I tried groupby JVNo but it didnt give the desired result
| [
"df1 = pd.read_csv('a.csv', index_col='JVNo')\nprint(df1) # will show your first table (your dataset)\ndf1_cleaned = df1.select_dtypes(object).groupby(level=0).first()\nprint(df1_cleaned) # will show your second table (what you want)\n"
] | [
0
] | [] | [] | [
"dataframe",
"merge",
"python",
"unique"
] | stackoverflow_0074306562_dataframe_merge_python_unique.txt |
Q:
Getting Error loading layout while using Dash Framework in Python
While running this code, I get "Error loading layout".
I'm using the dash framework in python.
What I'm trying to do is a dashboard with a set of parameters (ex: choosing the x-axis, y-axis)
I tried setting debug to true, but it shows me 0 errors.
a... | Getting Error loading layout while using Dash Framework in Python | While running this code, I get "Error loading layout".
I'm using the dash framework in python.
What I'm trying to do is a dashboard with a set of parameters (ex: choosing the x-axis, y-axis)
I tried setting debug to true, but it shows me 0 errors.
app.layout = html.Div(
children=[
html.Div(
chi... | [
"Comment each div out until you find the one that causes the problem.\nThe answer is that dcc.Dropdown was given the wrong type for options. It expects a dictionary.\n dcc.Dropdown(\n id=\"x-axis\",\n options=([x] for x in newCountry), <-- Error\n ... | [
0
] | [] | [] | [
"html",
"plotly_dash",
"python"
] | stackoverflow_0074312352_html_plotly_dash_python.txt |
Q:
Using random.choice() in elif statements
Im currently working on a command in discord.py that involves using many elif statements, and random.choice() inside of each. heres a snippet of my code:
if size == -1:
sizetext = random.choice(negativetexts)
elif size == 0 or size == 1:
sizetext = random.choice(mic... | Using random.choice() in elif statements | Im currently working on a command in discord.py that involves using many elif statements, and random.choice() inside of each. heres a snippet of my code:
if size == -1:
sizetext = random.choice(negativetexts)
elif size == 0 or size == 1:
sizetext = random.choice(microtexts)
elif size == 2 or size == 3 or size =... | [
"There are two things I can assume.\nOne is that (as far as I can see from the code provided) you are declaring the \"sizetext\" variable from within the if statement, and as a local variable, it can't be accessed from outside the if statement. The only thing is that I would assume the compiler would give an error ... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074323697_discord.py_python.txt |
Q:
How to implement Rolling Regression in Python
I'm trying to predict the Adjusted Closing Price for the next day for a stock using Rolling Regression.
Open High Low Close Adj Close
0 26.629999 27.000000 26.290001 26.600000 26.599386
1 26.670000 27.450001 26.5400... | How to implement Rolling Regression in Python | I'm trying to predict the Adjusted Closing Price for the next day for a stock using Rolling Regression.
Open High Low Close Adj Close
0 26.629999 27.000000 26.290001 26.600000 26.599386
1 26.670000 27.450001 26.540001 27.350000 27.349369
2 27.340000 27.44... | [
"You could transform your window into separate columns, like so:\n\n# == Necessary Imports ====================================\n# Note: to install ``sklearn`` run: ``pip install scikit-learn``\n\nimport pandas as pd\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.prep... | [
0
] | [] | [] | [
"pandas",
"python",
"regression"
] | stackoverflow_0074322560_pandas_python_regression.txt |
Q:
If condition in for loop messing up pandas dataframe
I am trying to mutate a data frame in a for loop based on an if condition.
import pandas as pd
#read the read.csv file
def write_csv(email, info):
df1 = pd.read_csv('/Users/thavas/Downloads/write.csv')
#iterate over df1 and look for email
for index,... | If condition in for loop messing up pandas dataframe | I am trying to mutate a data frame in a for loop based on an if condition.
import pandas as pd
#read the read.csv file
def write_csv(email, info):
df1 = pd.read_csv('/Users/thavas/Downloads/write.csv')
#iterate over df1 and look for email
for index, row in df1.iterrows():
print(index)
if ro... | [
"I've simplified the question to make my explanation easier. I've used only three columns in read.csv (eid, name, and email) and write.csv has (email1, and email2).\nThe goal is to create out.csv which is a copy of write.csv with the email2 field filled up for all emails that exist in read.csv.\nThe following code ... | [
1
] | [] | [] | [
"csv",
"if_statement",
"pandas",
"python"
] | stackoverflow_0074296716_csv_if_statement_pandas_python.txt |
Q:
Python multiprocess not getting queued items
I am passing a Queue object to a function that has been started as a Process. In the main loop, I add items to the queue expecting the process function to print out the size of the queue... but it just keeps reporting zero.
from queue import Queue
from multiprocessing i... | Python multiprocess not getting queued items | I am passing a Queue object to a function that has been started as a Process. In the main loop, I add items to the queue expecting the process function to print out the size of the queue... but it just keeps reporting zero.
from queue import Queue
from multiprocessing import Process
from time import sleep
def x(q):
... | [
"I have figured it out, you need to use the Queue() from the multiprocessing library and not from the queue library.\nfrom multiprocessing import Process, Queue\nfrom time import sleep\n\ndef x(q):\n while(1):\n print(q.qsize())\n sleep(1)\n\nq = Queue()\np = Process(target=x, args=(q,))\np.start()... | [
0
] | [] | [] | [
"multiprocessing",
"python",
"python_3.x",
"queue"
] | stackoverflow_0074323480_multiprocessing_python_python_3.x_queue.txt |
Q:
Why does this bleak module give such an error
I have trouble when I try connect a BLE esp-32 device. I'm using the template provided by the module to use it but I'm getting an error. Can you help me?
Below is the code I use written by the module manufacturer. I plan to use it to check if the code is working or not... | Why does this bleak module give such an error | I have trouble when I try connect a BLE esp-32 device. I'm using the template provided by the module to use it but I'm getting an error. Can you help me?
Below is the code I use written by the module manufacturer. I plan to use it to check if the code is working or not
import asyncio
from bleak import BleakClient
from ... | [
"It's a bug\nThis seems to be a bug in either the Bleak or PyWinRT module. There is an open issue for PyWinRT (#14) which says that the bug first appeared with Python 3.11. The latest bleak code added a FutureLike class to wrap IAsyncOperation and uses it at lines 578-586 of the same file backends/winrt/client.py. ... | [
0
] | [] | [] | [
"bluetooth_lowenergy",
"esp32",
"module",
"python",
"python_3.x"
] | stackoverflow_0074311841_bluetooth_lowenergy_esp32_module_python_python_3.x.txt |
Q:
'float' object has no attribute 'sqrt'
I am trying to obtain the gumbel_r of this input list using gumbel_r.fit() and gumbel_r.ppf()
contoh1 = pd.read_excel('data.xlsx',header=None,sheet_name='Sheet7'
dn=contoh1.columns
y1 =contoh1[dn[1]][37:43]
y2 =contoh1[dn[2]][21:43]
y3 =contoh1[dn[3]][21:43]
y4 =contoh1[dn[4]... | 'float' object has no attribute 'sqrt' | I am trying to obtain the gumbel_r of this input list using gumbel_r.fit() and gumbel_r.ppf()
contoh1 = pd.read_excel('data.xlsx',header=None,sheet_name='Sheet7'
dn=contoh1.columns
y1 =contoh1[dn[1]][37:43]
y2 =contoh1[dn[2]][21:43]
y3 =contoh1[dn[3]][21:43]
y4 =contoh1[dn[4]][1:43]
y5 =contoh1[dn[5]][22:44]
gmb=[y1,y2... | [
"Not all functions in SciPy are designed to handle object arrays. Instead of creating object arrays to pass to gumbel_r.fit(), create arrays of numpy.float64. Change this line:\n ch_res[i] = np.array(gmb,dtype=object)\n\nto\n ch_res[i] = np.array(gmb, dtype=np.float64)\n\nActually, I think that should be\... | [
0
] | [] | [] | [
"numpy",
"python",
"sqrt"
] | stackoverflow_0074324351_numpy_python_sqrt.txt |
Q:
Python Iterating over a list
Assign sum_extra with the total extra credit received given list test_grades. Full credit is 100, so anything over 100 is extra credit. For the given program, sum_extra is 8 because 1 + 0 + 7 + 0 is 8. Sample output for the given program:
Sum extra: 8
Forgive me I am a starter on codin... | Python Iterating over a list | Assign sum_extra with the total extra credit received given list test_grades. Full credit is 100, so anything over 100 is extra credit. For the given program, sum_extra is 8 because 1 + 0 + 7 + 0 is 8. Sample output for the given program:
Sum extra: 8
Forgive me I am a starter on coding and really bad at it!
And this i... | [
"user_input = input()\ntest_grades = list(map(int, user_input.split())) # contains test scores\n\nsum_extra = -999 # Initialize 0 before your loop\nsum_extra = 0\ncount = 0\n\nfor num in test_grades:\n if num > 100:\n sum_extra += num\n count += 1\nsum_extra = sum_extra - (100 * count)\n \nprint... | [
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0040231917_python.txt |
Q:
python Django ASP.NET Identity password hasher equivalent
I have setup task to authenticate django application users against .NET Identity database. I found many related topics, but they was either too old or not solving exaclty what I need - password hasher equivalent for Django.
A:
So I end up learning this so... | python Django ASP.NET Identity password hasher equivalent | I have setup task to authenticate django application users against .NET Identity database. I found many related topics, but they was either too old or not solving exaclty what I need - password hasher equivalent for Django.
| [
"So I end up learning this source https://github.com/aspnet/AspNetIdentity/blob/master/src/Microsoft.AspNet.Identity.Core/Crypto.cs\nAnd did write my django version. The code works for me with django 2.1.1 and .NET 4.5\nfrom django.contrib.auth.hashers import pbkdf2\nimport hashlib\nfrom base64 import b64decode\n\... | [
1,
0
] | [] | [] | [
"asp.net",
"asp.net_identity",
"authentication",
"django",
"python"
] | stackoverflow_0053611664_asp.net_asp.net_identity_authentication_django_python.txt |
Q:
updating data in a file
I'm trying to write a code to do the following:
I have a text file named students, each line(record) has: id,name,grade,number and gpa
i'm trying to update the file and change the gpa(according to what the user enters in another function) I need first to find the id number of the student an... | updating data in a file | I'm trying to write a code to do the following:
I have a text file named students, each line(record) has: id,name,grade,number and gpa
i'm trying to update the file and change the gpa(according to what the user enters in another function) I need first to find the id number of the student and then change his gpa.. When ... | [
"Each function should have one well-defined role. Then, you can combine and reuse them in many different ways.\ndef read_all(fn=\"students.txt\"):\n students=[]\n for line in open(fn,'r'):\n students.append(line.strip().split(\",\"))\n return students\n\ndef write_all(rows, fn=\"students.txt\"):\n ... | [
0
] | [] | [] | [
"file",
"python",
"writefile"
] | stackoverflow_0074324116_file_python_writefile.txt |
Q:
Pandas Plotting Legend and Colormap Question (Much Appreciated)
Data:
import numpy as np
import pandas as pd
#Data creation
d1 = pd.DataFrame({"Date" : ['1/1/2022', '12/15/2010', '6/1/2015', '1/31/2022', '12/31/2010', '3/10/2009', '1/7/2022', '12/9/2010','12/20/2010','1/13/2022'],
"... | Pandas Plotting Legend and Colormap Question (Much Appreciated) | Data:
import numpy as np
import pandas as pd
#Data creation
d1 = pd.DataFrame({"Date" : ['1/1/2022', '12/15/2010', '6/1/2015', '1/31/2022', '12/31/2010', '3/10/2009', '1/7/2022', '12/9/2010','12/20/2010','1/13/2022'],
"Item": ['Food', 'Food', 'Gasoline', 'Coffee', 'Coffee', 'PayPal', 'Ga... | [
"d1_sorted.unstack().droplevel(level=0,axis=1).plot(kind = 'bar', title = 'Total Expense', stacked = True, figsize = (15,10), colormap = 'Pastel2')\n\n1 and 2. Remove multiIndex with droplevel.\n\nNot sure how to adjust the range on the colorscale within the a bar plot. I would consider using a discrete colormap.\n... | [
0
] | [] | [] | [
"group_by",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074324251_group_by_matplotlib_pandas_python.txt |
Q:
Elegant way to check if a nested key exists in a dict?
Is there are more readable way to check if a key buried in a dict exists without checking each level independently?
Lets say I need to get this value in a object buried (example taken from Wikidata):
x = s['mainsnak']['datavalue']['value']['numeric-id']
To ma... | Elegant way to check if a nested key exists in a dict? | Is there are more readable way to check if a key buried in a dict exists without checking each level independently?
Lets say I need to get this value in a object buried (example taken from Wikidata):
x = s['mainsnak']['datavalue']['value']['numeric-id']
To make sure that this does not end with a runtime error it is ne... | [
"To be brief, with Python you must trust it is easier to ask for forgiveness than permission\ntry:\n x = s['mainsnak']['datavalue']['value']['numeric-id']\nexcept KeyError:\n pass\n\n\nThe answer\nHere is how I deal with nested dict keys:\ndef keys_exists(element, *keys):\n '''\n Check if *keys (nested)... | [
203,
28,
13,
12,
10,
6,
4,
3,
2,
2,
2,
1,
1,
1,
0,
0,
0
] | [
"There are many great answers. here is my humble take on it. Added check for array of dictionaries as well. Please note that I am not checking for arguments validity. I used part Arnot's code above. I added this answer because a I got a use case that requires checking array or dictionaries in my data.\nHere is the ... | [
-1
] | [
"object",
"python",
"variables"
] | stackoverflow_0043491287_object_python_variables.txt |
Q:
Swipe or turn data for stacked bar chart in Matplotlib
I'm trying to create or generate some graphs in stacked bar I'm using this data:
index 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
0 No 94 123 96 108 122 106.0 95.0 124 104 118 73 82 106 124 109 70 59
1 Yes 34 4 3... | Swipe or turn data for stacked bar chart in Matplotlib | I'm trying to create or generate some graphs in stacked bar I'm using this data:
index 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
0 No 94 123 96 108 122 106.0 95.0 124 104 118 73 82 106 124 109 70 59
1 Yes 34 4 33 21 5 25.0 34.0 5 21 9 55 46 21 3 19 5... | [
"Here is an example:\ndata = [{0:1,1:2,2:3},{0:3,1:2,2:1},{0:1,1:1,2:1}]\nindex = [\"yes\",\"no\",\"dont know\"]\ndf = pd.DataFrame(data,index=index)\ndf.T.plot.bar(stacked=True) # Note .T is used to transpose the DataFrame\n\n\n"
] | [
1
] | [] | [] | [
"graph",
"matplotlib",
"python",
"stacked_bar_chart",
"swap"
] | stackoverflow_0074324427_graph_matplotlib_python_stacked_bar_chart_swap.txt |
Q:
Choropleth plot with plotly produces unexpected output
I devise an interactive map of Germany using official shape files as provided here http://www.bkg.bund.de. The plotting works perfectly with geopandas but for some reason the plotly figure is off.
Minimal example for a geopandas dataframe -df- of length 1, whe... | Choropleth plot with plotly produces unexpected output | I devise an interactive map of Germany using official shape files as provided here http://www.bkg.bund.de. The plotting works perfectly with geopandas but for some reason the plotly figure is off.
Minimal example for a geopandas dataframe -df- of length 1, where the shape information are contained in column geometry an... | [
"Since Plotly uses (long, lat) in degrees for choropleth mapping. Your data in the form:-\nPOLYGON ((3531713.337678026 6077121.156487568, ...))\n\nis clearly not ready but needs conversion to EPSG:4326 for what plotly requires. For geodataframe, here is the snippet code that you may need for such conversion.\ndf_4... | [
1
] | [] | [] | [
"choropleth",
"geopandas",
"plotly",
"plotly_python",
"python"
] | stackoverflow_0074318942_choropleth_geopandas_plotly_plotly_python_python.txt |
Q:
How to check if a tensor is on cuda or send it to cuda in Pytorch?
I have a tensor
t = torch.zeros((4, 5, 6))
How to check if it is on gpu or not, and send it to gpu and back?
A:
From the pytorch forum
use t.is_cuda, t.cuda(), t.cpu()
t = torch.randn(2,2)
t.is_cuda # returns False
t = torch.randn(2,2).cuda()
t.... | How to check if a tensor is on cuda or send it to cuda in Pytorch? | I have a tensor
t = torch.zeros((4, 5, 6))
How to check if it is on gpu or not, and send it to gpu and back?
| [
"From the pytorch forum\nuse t.is_cuda, t.cuda(), t.cpu()\nt = torch.randn(2,2)\nt.is_cuda # returns False\nt = torch.randn(2,2).cuda()\nt.is_cuda # returns True\nt = t.cpu()\nt.is_cuda # returns False\n\nWhen passing to and from gpu and cpu, new arrays are allocated on the relevant device.\n",
"@Gulzar only t... | [
26,
0
] | [] | [] | [
"gpu",
"python",
"pytorch",
"tensor"
] | stackoverflow_0065381244_gpu_python_pytorch_tensor.txt |
Q:
Unknown column 'label_column' in 'order clause'\" SQLAlchemy when I use limit() in the query that has labels
I have a query that was too big so I added limit(), but now it's breaking, it's not recognizing the column I create with label().
When i use the labels:
query = self.session.query(
Model,
(
Model.da... | Unknown column 'label_column' in 'order clause'\" SQLAlchemy when I use limit() in the query that has labels | I have a query that was too big so I added limit(), but now it's breaking, it's not recognizing the column I create with label().
When i use the labels:
query = self.session.query(
Model,
(
Model.date_example == Model.date_example_two
).label("label_column_one"),
(
Model.date_example_three < Model.date_... | [
"Maybe try reusing the labeled special columns like this:\n col1 = (\n Model.date_example_1 == Model.date_example_2\n ).label(\"label_column_one\")\n col2 = (\n Model.date_example_3 < Model.date_example_4\n ).label(\"label_column_two\")\n col3 = (\n Model.date_example_5 > Model.d... | [
0
] | [] | [] | [
"falconframework",
"python",
"sqlalchemy"
] | stackoverflow_0074310423_falconframework_python_sqlalchemy.txt |
Q:
Find a key inside a deeply nested dictionary
I have a lot of nested dictionaries, I am trying to find a certain key nested inside somewhere.
e.g. this key is called "fruit". How do I find the value of this key?
A:
@Håvard's recursive solution is probably going to be OK... unless the level of nesting is too high,... | Find a key inside a deeply nested dictionary | I have a lot of nested dictionaries, I am trying to find a certain key nested inside somewhere.
e.g. this key is called "fruit". How do I find the value of this key?
| [
"@Håvard's recursive solution is probably going to be OK... unless the level of nesting is too high, and then you get a RuntimeError: maximum recursion depth exceeded. To remedy that, you can use the usual technique for recursion removal: keep your own stack of items to examine (as a list that's under your control... | [
6,
2,
0,
0,
0
] | [] | [] | [
"dictionary",
"nested",
"python"
] | stackoverflow_0002522651_dictionary_nested_python.txt |
Q:
How to change colors of specific points in a lineplot
I'd like to plot a timeseries and show outliers in a different color than the rest of the points. How can I used seaborn lineplot to show a different color for specific points?
When I use `sns.lineplot(data=df, x='datetime', y='y', hue='outlier_label') I get s... | How to change colors of specific points in a lineplot | I'd like to plot a timeseries and show outliers in a different color than the rest of the points. How can I used seaborn lineplot to show a different color for specific points?
When I use `sns.lineplot(data=df, x='datetime', y='y', hue='outlier_label') I get separate series for each category (outlier or inlier). I wo... | [
"You could first plot the curve without taking the outlier status into account, and then add a scatter plot with the positions of the outliers.\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\n\nx = np.arange(100)\nerrors = np.random.normal(size=len(x))\ny = np.sin(x... | [
3
] | [] | [] | [
"python",
"seaborn"
] | stackoverflow_0074324146_python_seaborn.txt |
Q:
NameError: name 'glPushMatrix' is not defined
Try to run a test code for stable baselines gym
import gym
from stable_baselines3 import A2C
env = gym.make("CartPole-v1")
model = A2C("MlpPolicy", env, verbose=1)
model.learn(total_timesteps=10_000)
obs = env.reset()
for i in range(100):
action, _state = model... | NameError: name 'glPushMatrix' is not defined | Try to run a test code for stable baselines gym
import gym
from stable_baselines3 import A2C
env = gym.make("CartPole-v1")
model = A2C("MlpPolicy", env, verbose=1)
model.learn(total_timesteps=10_000)
obs = env.reset()
for i in range(100):
action, _state = model.predict(obs, deterministic=True)
obs, reward, ... | [
"Just had the same problem. Fixed it by installing an older version of pyglet:\n$ pip install pyglet==1.5.27\n\nI don't know if this is the latest version that avoids the problem, but it works.\n"
] | [
6
] | [] | [] | [
"opengl",
"python",
"render"
] | stackoverflow_0074314778_opengl_python_render.txt |
Q:
Adding plot and axes title to histogram subplots
I am trying to add individual plot title and axes title. I tried axes.set_xlabel() but getting an error. I used the following code
import matplotlib.pyplot as plt
import pandas as pd
uid_df = pd.read_excel('myexcel.xlsx', sheet_name='UID')
sid_df = pd.read_excel('m... | Adding plot and axes title to histogram subplots | I am trying to add individual plot title and axes title. I tried axes.set_xlabel() but getting an error. I used the following code
import matplotlib.pyplot as plt
import pandas as pd
uid_df = pd.read_excel('myexcel.xlsx', sheet_name='UID')
sid_df = pd.read_excel('myexcel.xlsx', sheet_name='SID')
fig, axes = plt.subp... | [
"axes is a 2x3 array if you use plt.subplots(2,3). You have to set the xlabel and ylabel for each element in the array. e.g for the plot in the top left:\naxes[0,0].set_xlabel('x-label')\naxes[0,0].set_ylabel('y-label')\n\nhttps://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html\n"
] | [
1
] | [] | [] | [
"histogram",
"matplotlib",
"python"
] | stackoverflow_0074324444_histogram_matplotlib_python.txt |
Q:
How to convert an integer to a string in any base?
Python allows easy creation of an integer from a string of a given base via
int(str, base).
I want to perform the inverse: creation of a string from an integer,
i.e. I want some function int2base(num, base), such that:
int(int2base(x, b), b) == x
The function... | How to convert an integer to a string in any base? | Python allows easy creation of an integer from a string of a given base via
int(str, base).
I want to perform the inverse: creation of a string from an integer,
i.e. I want some function int2base(num, base), such that:
int(int2base(x, b), b) == x
The function name/argument order is unimportant.
For any number x a... | [
"Surprisingly, people were giving only solutions that convert to small bases (smaller than the length of the English alphabet). There was no attempt to give a solution which converts to any arbitrary base from 2 to infinity.\nSo here is a super simple solution:\ndef numberToBase(n, b):\n if n == 0:\n retu... | [
193,
118,
114,
100,
55,
30,
22,
14,
5,
3,
3,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"def dec_to_radix(input, to_radix=2, power=None):\n if not isinstance(input, int):\n raise TypeError('Not an integer!')\n elif power is None:\n power = 1\n\n if input == 0:\n return 0\n else:\n remainder = input % to_radix**power\n digit = str(int(remainder/to_radix**(... | [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1
] | [
"base",
"python",
"radix"
] | stackoverflow_0002267362_base_python_radix.txt |
Q:
Pipenv throws and error when installing in docker
Pipenv throws and error when installing in docker
[python-deps 5/5] RUN PIPENV_VENV_IN_PROJECT=1 pipenv install --deploy:
#10 7.577 Creating a virtualenv for this project... ... | Pipenv throws and error when installing in docker | Pipenv throws and error when installing in docker
[python-deps 5/5] RUN PIPENV_VENV_IN_PROJECT=1 pipenv install --deploy:
#10 7.577 Creating a virtualenv for this project...
#10 7.578 Pipfile: /Pipfile ... | [
"I encountered the same issue tonight. After looking around for a while (including finding this question at first), I tried an older version of pipenv than the one that was published ~5 hours ago and building my Docker image worked.\nUntil they publish a new version and fix the issue (it is being worked on : https:... | [
1
] | [] | [] | [
"docker",
"pipenv",
"python"
] | stackoverflow_0074324063_docker_pipenv_python.txt |
Q:
Plot dataset below using python datafram
I have dataset as below each row represent a customer ID and column is time and value for a month for every 30 min, I can't plot that in time line graph
I want to convert it as below
any advise
trying...............
A:
You can use pandas.wide_to_long to make this kind o... | Plot dataset below using python datafram | I have dataset as below each row represent a customer ID and column is time and value for a month for every 30 min, I can't plot that in time line graph
I want to convert it as below
any advise
trying...............
| [
"You can use pandas.wide_to_long to make this kind of reshape :\ndf.columns= df.columns.str.replace(\"\\s+\", \"\", regex=True)\n\nout = (\n pd.wide_to_long(df, stubnames=['Time', 'value'], i='ID', j='_')\n .droplevel(1, axis=0)\n .reset_index()\n .sort_values(by='ID')... | [
0
] | [] | [] | [
"dataframe",
"plot",
"python"
] | stackoverflow_0074324518_dataframe_plot_python.txt |
Q:
Pandas: Groupby and sum customer profit, for every 6 months, starting from users first transaction
I have a dataset like this:
Customer ID
Date
Profit
1
4/13/2018
10.00
1
4/26/2018
13.27
1
10/23/2018
15.00
2
1/1/2017
7.39
2
7/5/2017
9.99
2
7/7/2017
10.01
3
5/4/2019
30.30
I'd like to groupby and sum profit... | Pandas: Groupby and sum customer profit, for every 6 months, starting from users first transaction | I have a dataset like this:
Customer ID
Date
Profit
1
4/13/2018
10.00
1
4/26/2018
13.27
1
10/23/2018
15.00
2
1/1/2017
7.39
2
7/5/2017
9.99
2
7/7/2017
10.01
3
5/4/2019
30.30
I'd like to groupby and sum profit, for every 6 months, starting at each users first transaction.
The output ideally should... | [
"I can get you the first of the month until you find a more perfect solution.\ndf[\"Date\"] = pd.to_datetime(df[\"Date\"], format=\"%m/%d/%Y\")\ndf = (\n df\n .set_index(\"Date\")\n .groupby([\"Customer ID\"])\n .Profit\n .resample(\"6MS\")\n .sum()\n .reset_index(name=\"Profit\")\n)\nprint(df)... | [
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074324394_dataframe_group_by_pandas_python.txt |
Q:
How to get rid of space between period
import datetime
from datetime import date
today = date.today()
user_name = input('What is your name? ')
user_age = int(input('How old are you? '))
print('Hello ' + user_name + '! You were born in', today.year - user_age, '.')
What is your name? Tyler
How old are you? 31
Hel... | How to get rid of space between period | import datetime
from datetime import date
today = date.today()
user_name = input('What is your name? ')
user_age = int(input('How old are you? '))
print('Hello ' + user_name + '! You were born in', today.year - user_age, '.')
What is your name? Tyler
How old are you? 31
Hello Tyler! You were born in 1991 .
Process f... | [
"Use an f string, just like this!\nimport datetime\nfrom datetime import date\ntoday = date.today()\nuser_name = input('What is your name? ')\nuser_age = int(input('How old are you? '))\nprint(f\"Hello {user_name}! You were born in {today.year - user_age}.\")\n\n",
"You can convert the year into a string by wrapp... | [
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074324600_python.txt |
Q:
Put an append list into a table with python
I'm trying to put my append list into a table. I only can print one line of the list but not the others since the amount of numbers and words can varie from 1 to infinity
everthing = []
option = 0
while option < 5:
Mainmenue = ["Main menue", "1. ADD AN ITEM", "4. GE... | Put an append list into a table with python | I'm trying to put my append list into a table. I only can print one line of the list but not the others since the amount of numbers and words can varie from 1 to infinity
everthing = []
option = 0
while option < 5:
Mainmenue = ["Main menue", "1. ADD AN ITEM", "4. GENERATE A REPORT"]
for i in (Mainmenue):
... | [
"You were very close. However, you do have some redundant code.\nI added a 5. QUIT option to clarify the method to exit the program.\nI tried to keep it within your specifications, however you may want to consider some error checking code to handle the issue if they do not enter a number when asked to select an opt... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074324193_python_python_3.x.txt |
Q:
Want to create a new column named 'sum_columns', which is the sum of all numeric columns in df
I have a DataFrame. I want to create a new column, named sum_columns, which is the sum of all existing numeric columns. When I try this:
df["sum_columns"] = df.select_dtypes(include="number").apply(np.sum)
The column co... | Want to create a new column named 'sum_columns', which is the sum of all numeric columns in df | I have a DataFrame. I want to create a new column, named sum_columns, which is the sum of all existing numeric columns. When I try this:
df["sum_columns"] = df.select_dtypes(include="number").apply(np.sum)
The column contains only NaNs.
Obviously I'm missing something.
| [
"import pandas as pd\n\ndf = pd.DataFrame({\"col1\": ['a', 'b', 'c'],\n \"col2\": [1, 2, 3],\n \"col3\": ['d', '1', 2],\n \"col4\": [4, 5, 6]})\n\ndf['sum_col'] = df.select_dtypes(include='number').sum(axis=1)\nprint(df)\n\n\n col1 col2 col3 col4 sum_col\n0 ... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074324627_dataframe_pandas_python.txt |
Q:
No module named "Torch"
I successfully installed pytorch via conda:
conda install pytorch-cpu torchvision-cpu -c pytorch
I also successfully installed pytorch via pip:
pip3 install https://download.pytorch.org/whl/cpu/torch-1.0.1-cp36-cp36m-win_amd64.whl
pip3 install torchvision
But, it only works in a jupyter n... | No module named "Torch" | I successfully installed pytorch via conda:
conda install pytorch-cpu torchvision-cpu -c pytorch
I also successfully installed pytorch via pip:
pip3 install https://download.pytorch.org/whl/cpu/torch-1.0.1-cp36-cp36m-win_amd64.whl
pip3 install torchvision
But, it only works in a jupyter notebook. Whenever I try to ex... | [
"Try to install PyTorch using pip:\nFirst create a Conda environment using:\nconda create -n env_pytorch python=3.6\n\nActivate the environment using:\nconda activate env_pytorch\n\nNow install PyTorch using pip:\npip install torchvision \n\nNote: This will install both torch and torchvision.\nNow go to Python shel... | [
69,
17,
8,
3,
2,
2,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"Create the environment:\nconda create -n env_pytorch python=3.6\n\nInstall your modules. For example: \nconda install pytorch torchvision cudatoolkit=10.2 -c pytorch\n\nNext time you want to use pytorch:\nconda activate env_pytorch\n\nand when finished:\nconda deactivate\n\n"
] | [
-2
] | [
"conda",
"pip",
"python",
"pytorch"
] | stackoverflow_0054843067_conda_pip_python_pytorch.txt |
Q:
Import could not be resolved/could not be resolved from source Pylance in VS Code using Python 3.9.2 on Windows 10
My Flask App server is running but I have three imports that cannot be resolved.
I have tried:
reinstalling the imports individually
reinstalling requirements.txt
I configured VSCode Workspace with ... | Import could not be resolved/could not be resolved from source Pylance in VS Code using Python 3.9.2 on Windows 10 | My Flask App server is running but I have three imports that cannot be resolved.
I have tried:
reinstalling the imports individually
reinstalling requirements.txt
I configured VSCode Workspace with an extra path to my project folder (there is now a .vscode file within the root of my project folder where it was not be... | [
"\nOpen the Command Palette (Ctrl+Shift+P), then select the Python: Select Interpreter. From the list, select the virtual environment in your project folder that starts with .env.\n\nRun Terminal: Create New Integrated Terminal (Ctrl+Shift+` or from the Command Palette), which creates a terminal and automatically a... | [
97,
44,
9,
4,
4,
0,
0,
0
] | [] | [] | [
"flask",
"pylance",
"python",
"visual_studio_code"
] | stackoverflow_0068486207_flask_pylance_python_visual_studio_code.txt |
Q:
How do I solve this problem with leap year function?
Question:
A common year in the modern Gregorian Calendar consists of 365 days. In reality, Earth takes longer to rotate around the sun. To account for the difference in time, every 4 years, a leap year takes place. A leap year is when a year has 366 days: An ext... | How do I solve this problem with leap year function? | Question:
A common year in the modern Gregorian Calendar consists of 365 days. In reality, Earth takes longer to rotate around the sun. To account for the difference in time, every 4 years, a leap year takes place. A leap year is when a year has 366 days: An extra day, February 29th. The requirements for a given year t... | [
"Actually, when I copied and ran the above code, it was printing out a result, but not always a correct one as the leap year test was actually lacking in some logic.\nReviewing the requirements of the assignment, it would actually look like the testing for a leap year would be in the \"days_in_feb\" function. So w... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074324525_python.txt |
Q:
How to get all child elements using BeautifulSoup framework
I have such an HTML document and I want to get the content inside the section
<body>
<section class="post-content">
<h1>title</h1>
<div>balabala</div>
</section>
<body>
When I use the following code
soup.find_all("section", {"class": "post-co... | How to get all child elements using BeautifulSoup framework | I have such an HTML document and I want to get the content inside the section
<body>
<section class="post-content">
<h1>title</h1>
<div>balabala</div>
</section>
<body>
When I use the following code
soup.find_all("section", {"class": "post-content"})
I get
<section class="post-content">
<h1>title</h1>
... | [
"You can use the .findChildren() method and a list comphrension:\nimport bs4\n\nsoup = bs4.BeautifulSoup(\"\"\"\n<body>\n <section class=\"post-content\">\n <h1>title</h1>\n <div>part one</div>\n </section>\n <section class=\"post-content\">\n <h1>title2</h1>\n <div>part two</di... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074324705_beautifulsoup_python.txt |
Q:
Can anyone explain (def equalFrequency(self, word: str) -> bool:) this python function?
this is the full code:
class Solution:
def equalFrequency(self, word: str) -> bool:
I want to know what is word:str -> bool: means in python
Can anyone explain this with examples. I only want to know what is word:... | Can anyone explain (def equalFrequency(self, word: str) -> bool:) this python function? | this is the full code:
class Solution:
def equalFrequency(self, word: str) -> bool:
I want to know what is word:str -> bool: means in python
Can anyone explain this with examples. I only want to know what is word: str -> bool: means in python.
| [
"This is python typing.\nword: str says that the argument word is expected to be of type str (string)\ndef equalFrequency(self, word: str) -> bool says that function equalFrequency is expected to return a bool (boolean), so we should get a true or false values from the function\nExamples:\nequalFrequency('hello') =... | [
0
] | [] | [] | [
"class",
"function",
"python"
] | stackoverflow_0074324747_class_function_python.txt |
Q:
How to make a simple celsius to farenheit conversion table within a specific range of temperatures in PYTHON?
Blockquote
[1]I have not seen an answer for python. Not sure how to display a table.
I tried a for loop for the range and am stuck on displaying in a table.
[How would I be able to display my numbers like ... | How to make a simple celsius to farenheit conversion table within a specific range of temperatures in PYTHON? | Blockquote
[1]I have not seen an answer for python. Not sure how to display a table.
I tried a for loop for the range and am stuck on displaying in a table.
[How would I be able to display my numbers like this][2]
}
celsius = 0
for i in range (20,50):
farenheit = celsius*(9/5)+32
print ()
{
[2]: https://i.stack... | [
"First off, there are a multitude of ways one might approach producing a table such as this. The following snippet of code is just one way and probably isn't even the most elegant way to do this.\nlow = int(input(\"Enter the low temparature starting point in Degrees Celcius: \"))\nhigh = int(input(\"Enter the high... | [
0
] | [] | [] | [
"for_loop",
"if_statement",
"python",
"range"
] | stackoverflow_0074324374_for_loop_if_statement_python_range.txt |
Q:
Linked List, can't acess the data from NEXT NODE
My problem is at the display function, I can't access the value cur_node.data which is a reference to node.next.data. I'm new to python and I'm trying to learn Linked LISTS, this code is from an old VIDEO which is why it probably isn't working
My code below:
class n... | Linked List, can't acess the data from NEXT NODE | My problem is at the display function, I can't access the value cur_node.data which is a reference to node.next.data. I'm new to python and I'm trying to learn Linked LISTS, this code is from an old VIDEO which is why it probably isn't working
My code below:
class node:
def __init__(self,data=None):
self.da... | [
"Fala Brazuca,\nThe problem is with your while condition.\nwhile cur_node != None\n cur_node = cur_node.next\n\nSee carefully,\n\nWhen your loop is iterating on the last element, cur_node still have data on it, but its next element does not.\nWhat your code is saying is -> If the last element has data, then assum... | [
1
] | [] | [] | [
"class",
"data_structures",
"linked_list",
"nodes",
"python"
] | stackoverflow_0074324611_class_data_structures_linked_list_nodes_python.txt |
Q:
Python logger output not matching logger and handler level
I have created a custom Python Logger with a StreamHandler, initially set to logging.INFO level. This correctly hides DEBUG level logs and outputs INFO level logs.
I also created a function that changes the level of both the logger and handler to logging.D... | Python logger output not matching logger and handler level | I have created a custom Python Logger with a StreamHandler, initially set to logging.INFO level. This correctly hides DEBUG level logs and outputs INFO level logs.
I also created a function that changes the level of both the logger and handler to logging.DEBUG. Printing out logger.getEffectiveLevel() and handler.level ... | [
"It's because the standard logging module is not designed for that pattern. A Logger instance should be created by the logging.getLogger().(See the reference. It says 'NEVER'.)\nUse the logging.setLoggerClass() to register your CustomLogger and call the logging.getLogger().\nAnd you can manipulate existing loggers ... | [
1
] | [] | [] | [
"python",
"python_logging"
] | stackoverflow_0074323695_python_python_logging.txt |
Q:
How to export Python printed output to txt file at the end of code
I have several thousand lines of code that all ultimately results in a few strings being printed using print() calls. Is there a way to, at the bottom of my code, export everything that has been printed to a text file?
A:
This will help.
python m... | How to export Python printed output to txt file at the end of code | I have several thousand lines of code that all ultimately results in a few strings being printed using print() calls. Is there a way to, at the bottom of my code, export everything that has been printed to a text file?
| [
"This will help.\npython main.py > output.txt\n\nThe operator > redirects the output of main.py from stdout to the regular file output.txt.\n",
"You can do this with redirection in your shell or reopening sys.stdout. Here are both ways:\n\nReopen sys.stdout:\n\nAt the beginning of your code, you can use this code... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074324797_python.txt |
Q:
How to merge two nested dict in python?
I have two nested dictionary data. I want to merge them to create one dictionary in python.
Dictionary data :
dict1 = {'employee':{'dev1': 'Roy'}}
dict2 = {'employee':{'dev2': 'Biswas'}}
Now I trying to create a dictionary like bellow from them.Required Output
dict_output ... | How to merge two nested dict in python? | I have two nested dictionary data. I want to merge them to create one dictionary in python.
Dictionary data :
dict1 = {'employee':{'dev1': 'Roy'}}
dict2 = {'employee':{'dev2': 'Biswas'}}
Now I trying to create a dictionary like bellow from them.Required Output
dict_output = {'employee':{
'dev1': '... | [
"This code is to support slightly different meaning of \"merge\". Let's say we have a nested dictionary:\ndict1 = {'employee':{'devs':{'python':{'dev1':'Roy'}}}}\ndict2 = {'employee':{'devs':{'cpp':{'dev1':'Biswas'}}}}\n\nIn this case the simple loop solution returns:\n{'employee': {'devs': {'cpp': {'dev1': 'Biswas... | [
8,
7,
4,
1,
0
] | [
"[key1 == key2 and dict1.get(key1).update(dict2.get(key2)) \n for key1, key2 in zip(dict1, dict2)]\nprint dict1\n\n"
] | [
-1
] | [
"dictionary",
"python"
] | stackoverflow_0043797333_dictionary_python.txt |
Q:
how to grab a specific line after the line I found by parsing in python
I am currently parsing an xml file to find the a pattern and extract what i need from inside it.
is there a way so that when i find the line i am looking for to count two lines down and grab that line.
with open(filepath) as f:
for line in... | how to grab a specific line after the line I found by parsing in python | I am currently parsing an xml file to find the a pattern and extract what i need from inside it.
is there a way so that when i find the line i am looking for to count two lines down and grab that line.
with open(filepath) as f:
for line in f:
if pattern.search(line):
#parse each line returned an... | [
"I created an example.xml file containing the exact example contents you specified:\n<Computer3Properties name=\"UH25\">\n <Description property=\"Description\">\n <DescriptionValue value=\"lab\" type=\"VTR\" />\n\nThis code:\nimport re\n\npattern = \"UH25\"\n\nwith open(\"path\",\"r\") as file:\n ... | [
1
] | [] | [] | [
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074324764_pandas_python_web_scraping.txt |
Q:
Building a custom class decorator
I thought I understood this, but clearly I don't.
I have a context manager that wraps suites of code inside some metadata handling. The details of that don't matter, suffice to say the code needs to be between a push_job() and pop_job(). That all works, so I can say:
with JobManag... | Building a custom class decorator | I thought I understood this, but clearly I don't.
I have a context manager that wraps suites of code inside some metadata handling. The details of that don't matter, suffice to say the code needs to be between a push_job() and pop_job(). That all works, so I can say:
with JobManager(*config) as job:
<Processing Goe... | [
"Doing this:\n@some_decorator\ndef func(...):\n ...\n\nIs same as doing this:\ndef func(...):\n ...\n\nfunc = some_decorator(func)\n\nSo what you are doing is basically process_job = JobManager(process_job). In other words, you just created an instance of JobManager. This clearly cannot work, as now process_j... | [
2,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074324660_python_python_3.x.txt |
Q:
How do getters and setters work in Python?
I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def get_age(sel... | How do getters and setters work in Python? | I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def get_age(self):
return self._age
def set_age(se... | [
"You need to tell python how to associate the getter and setter with the actual variable name. To do this you can use the builtin property function like so:\nclass Person\n def __init__(self, name, age):\n self._name = name\n self._age = age\n\n def get_age(self):\n return self._age\n\n ... | [
1,
0,
0,
0,
0
] | [] | [] | [
"getter_setter",
"python"
] | stackoverflow_0071078674_getter_setter_python.txt |
Q:
How to merge nested dictionaries?
I have a list of nested dictionaries (python 3.9) that looks something like this:
records = [
{'Total:': {'Owner:': {'Available:': {'15 to 34 years': 1242}}}},
{'Total:': {'Owner:': {'Available:': {'35 to 64 years': 5699}}}},
{'Total:': {'Owner:': {'Available:': {'65 y... | How to merge nested dictionaries? | I have a list of nested dictionaries (python 3.9) that looks something like this:
records = [
{'Total:': {'Owner:': {'Available:': {'15 to 34 years': 1242}}}},
{'Total:': {'Owner:': {'Available:': {'35 to 64 years': 5699}}}},
{'Total:': {'Owner:': {'Available:': {'65 years and over': 2098}}}},
{'Total:'... | [
"Recursion is an easy way to navigate and operate on arbitrarily nested structures:\ndef combine_into(d: dict, combined: dict) -> None:\n for k, v in d.items():\n if isinstance(v, dict):\n combine_into(v, combined.setdefault(k, {}))\n else:\n combined[k] = v\n\ncombined = {}\n... | [
4,
0
] | [] | [] | [
"dictionary",
"merge",
"python",
"python_3.x"
] | stackoverflow_0070310388_dictionary_merge_python_python_3.x.txt |
Q:
Checking a list to make sure a user inputted item is in there
condition = True
classes = []
print("Welcome to class registration!")
def printClasses():
print("You are currently taking these courses: ")
for item in range(0, len(classes)):
print(item+1, ".", classes[item])
while condition:
i... | Checking a list to make sure a user inputted item is in there | condition = True
classes = []
print("Welcome to class registration!")
def printClasses():
print("You are currently taking these courses: ")
for item in range(0, len(classes)):
print(item+1, ".", classes[item])
while condition:
if(len(classes) < 5):
course = str(input("What course(s) wou... | [
"There were numerous mistakes in your code. Instead of pointing then all out I have fixed them and will allow you to figure it out on your own.\nglobal classes\nclasses = []\n \nprint(\"Welcome to class registration!\")\n \ndef printClasses():\n print(\"You are currently taking these courses: \")\n coun... | [
0,
0,
0
] | [] | [] | [
"arrays",
"list",
"python",
"string"
] | stackoverflow_0074324585_arrays_list_python_string.txt |
Q:
Flask-Sqlalchemy doesn't work as expected when use filter by
Hello I am triying the following querie
record = Record().query.filter(
Record.id == record_id,
Record.status.isnot(Status.COMPLETE)
).one()
print(record)
status is a str and id is a int
class Status(str, Enum):
SCHEDULED = 'SCHEDULED'
... | Flask-Sqlalchemy doesn't work as expected when use filter by | Hello I am triying the following querie
record = Record().query.filter(
Record.id == record_id,
Record.status.isnot(Status.COMPLETE)
).one()
print(record)
status is a str and id is a int
class Status(str, Enum):
SCHEDULED = 'SCHEDULED'
RECORDING = 'RECORDING'
UPLOADING = 'UPLOADING'
COMPLET... | [
"sorry to be five months late and also point out something that's pretty minor\nin flask-sqlalchemy, you use a singular = when filtering. i know in regular sqlalchemy they use == but i think that's your issue\n"
] | [
0
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"python",
"sqlalchemy"
] | stackoverflow_0072303249_flask_flask_sqlalchemy_python_sqlalchemy.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.