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: How to determine whether a variable belongs to a class or an instance of the class in python? class A: def __init__(self): self.one = 1 two = 2 a = A() >>> A.__dict__ mappingproxy({'__dict__': <attribute '__dict__' of 'A' objects>, '__doc__': None, '__init__': <functio...
How to determine whether a variable belongs to a class or an instance of the class in python?
class A: def __init__(self): self.one = 1 two = 2 a = A() >>> A.__dict__ mappingproxy({'__dict__': <attribute '__dict__' of 'A' objects>, '__doc__': None, '__init__': <function A.__init__ at 0x0000021520A2A290>, '__module__': '__main__', '__weakr...
[ "As you already found, you can find instance attributes in an instance's __dict__, and class attributes will not be present there (unless they were overridden for a particular instance).\nIf a given class uses __slots__ instead of __dict__, then the names of instance attributes can be discovered by examining that c...
[ 1 ]
[]
[]
[ "introspection", "python", "python_3.x", "reflection" ]
stackoverflow_0074419721_introspection_python_python_3.x_reflection.txt
Q: How to make Button with image same size as the other Buttons? In this short program for understanding, i have 2 buttons as you can see in the image, the first one starting from the top has an image of a Recycle Bin and the second one is a normal button with width = 4. After resizing the image with ImageTk, how can...
How to make Button with image same size as the other Buttons?
In this short program for understanding, i have 2 buttons as you can see in the image, the first one starting from the top has an image of a Recycle Bin and the second one is a normal button with width = 4. After resizing the image with ImageTk, how can i make the first button the same size of the second? If i don't se...
[ "Does this help?\nimport tkinter as tk\n#from PIL import Image, ImageTk\n#from ctypes import windll\n#windll.shcore.SetProcessDpiAwareness(1)\n\nwin = tk.Tk()\nwin.geometry('500x400') \n\n#immagine_cancella = Image.open('cestino2.png')\n#immagine_cancella = immagine_cancella.resize((33, 39))\n#immagine_cancella = I...
[ 0 ]
[]
[]
[ "button", "python", "tkinter" ]
stackoverflow_0074421013_button_python_tkinter.txt
Q: Write new metadata I'm trying to overwrite an existing file with new metadata on python. So, I'm looking for a method that we can apply to any type of files (doc, docx, pdf, pptx, xlsx and so on, and so on) I tried to do this using os.setxattr as it was here but I don't want to add additional attributes Also I hav...
Write new metadata
I'm trying to overwrite an existing file with new metadata on python. So, I'm looking for a method that we can apply to any type of files (doc, docx, pdf, pptx, xlsx and so on, and so on) I tried to do this using os.setxattr as it was here but I don't want to add additional attributes Also I have to say that the metada...
[ "There have been numerous attempts at this desire over the centuries.\nWindows uses several means like AD or other file meta-attachments\nEarlier versions had better access to edit details\n\n\nOpen the folder that contains the file you want to change.\nRight-click the file, and then click Properties.\nIn the Prope...
[ 0 ]
[]
[]
[ "file", "metadata", "python", "winapi" ]
stackoverflow_0074396031_file_metadata_python_winapi.txt
Q: Why does mypy error if I assign only one of two generic typevars in a classmethod? (python 3.10.6, mypy 0.990) The following examples are all accepted by mypy: from typing import Generic, TypeVar T = TypeVar('T') class Maybe(Generic[T]): def __init__(self, val: T): self._val = val @classmetho...
Why does mypy error if I assign only one of two generic typevars in a classmethod?
(python 3.10.6, mypy 0.990) The following examples are all accepted by mypy: from typing import Generic, TypeVar T = TypeVar('T') class Maybe(Generic[T]): def __init__(self, val: T): self._val = val @classmethod def empty(cls): return cls(None) from typing import Generic, TypeVar U =...
[ "tl;dr what if I call type(Example(0, 0)).first(0)? We can't infer cls as type[Example[int, None]] in that case.\nA rambling explanation\nIt's typically not type-safe to call a class in Python. The first two examples actually allow type errors because I can subclass them and change the __init__. This type checks bu...
[ 2 ]
[]
[]
[ "generics", "mypy", "python" ]
stackoverflow_0074417503_generics_mypy_python.txt
Q: Update Bokeh figure Inside a Jupyter Notebook I draw 3 circles. fig = figure(plot_width = 300, plot_height = 300) fig.circle(x = [1, 2, 3], y = [3, 7, 5], size = 20, color ="green", alpha = 0.6) show(fig) I would like to change one circle color I can do: fig.circle(x = 2, y = 7, size = 20, color ="blue", alpha = ...
Update Bokeh figure
Inside a Jupyter Notebook I draw 3 circles. fig = figure(plot_width = 300, plot_height = 300) fig.circle(x = [1, 2, 3], y = [3, 7, 5], size = 20, color ="green", alpha = 0.6) show(fig) I would like to change one circle color I can do: fig.circle(x = 2, y = 7, size = 20, color ="blue", alpha = 0.6) show(fig) Let say I...
[ "You can pass single values to color as you did. But color does also accepts lists or names of a ColumnDataSource.\nfig = figure(plot_width = 300, plot_height = 300)\nfig.circle(\n x = [1, 2, 3],\n y = [3, 7, 5],\n size = 20,\n color = [\"green\", \"blue\", \"green\"],\n alpha = 0.6\n)\nshow(fig)\n\nW...
[ 0 ]
[]
[]
[ "bokeh", "python" ]
stackoverflow_0074421632_bokeh_python.txt
Q: Selenium python - CORS Issue - "No 'Access-Control-Allow-Origin" I gave built a webscraper in python using selenium that runs perfectly fine. But I need to run it in headless mode, for a certain reason, however, when I do this I am getting the following error (a bunch of times). "[1113/144449.454:INFO:CONSOLE(0)] ...
Selenium python - CORS Issue - "No 'Access-Control-Allow-Origin"
I gave built a webscraper in python using selenium that runs perfectly fine. But I need to run it in headless mode, for a certain reason, however, when I do this I am getting the following error (a bunch of times). "[1113/144449.454:INFO:CONSOLE(0)] "Access to fetch at 'https://price-api.crypto.com/price/v1/tags' from ...
[ "Maybe you can set it like this\n\nself.options = webdriver.ChromeOptions()\nself.options.add_experimental_option('excludeSwitches', ['enable-automation'])\nself.browser = webdriver.Chrome(options=self.options)\n\n" ]
[ 0 ]
[]
[]
[ "chrome_options", "cors", "python", "selenium", "web_scraping" ]
stackoverflow_0074422060_chrome_options_cors_python_selenium_web_scraping.txt
Q: Python ERROR TypeError: a bytes-like object is required, not 'str' I don't understand what is the problem please help when run in console it gives the following error : TypeError: a bytes-like object is required, not 'str' #!/usr/bin/env python import socket import subprocess def execute_system_command(command...
Python ERROR TypeError: a bytes-like object is required, not 'str'
I don't understand what is the problem please help when run in console it gives the following error : TypeError: a bytes-like object is required, not 'str' #!/usr/bin/env python import socket import subprocess def execute_system_command(command): return subprocess.check_output(command, shell = True) connectio...
[ "You need to send your message as bytes and not as str.\nJust do this:\nconnection.send(bytes(<Your Message>, \"utf-8\"))\n\nParse your message as first parameter for the bytes function.\n" ]
[ 0 ]
[]
[]
[ "python", "string", "typeerror" ]
stackoverflow_0074421664_python_string_typeerror.txt
Q: Round based on number of decimal places of scientific notation float I would like to return the rounded values of num, where the number of decimal places passed to round() are the number of decimal places of the floats in [scis]. scis = [5e-05, 5e-06, 5e-07, 5e-08] num = 0.0123456789 returns: 0.01235 0.012346 0.0...
Round based on number of decimal places of scientific notation float
I would like to return the rounded values of num, where the number of decimal places passed to round() are the number of decimal places of the floats in [scis]. scis = [5e-05, 5e-06, 5e-07, 5e-08] num = 0.0123456789 returns: 0.01235 0.012346 0.0123457 0.01234568 In order for something like this to work, I need to der...
[ "You could do some math transformations on the numbers using log10\nfrom math import log10, ceil\n\nfor sci in scis:\n z = round(num, int(ceil(abs(log10(sci)))))\n print(z)\n0.01235\n0.012346\n0.0123457\n0.01234568\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074422130_python.txt
Q: Fastest way to write in an numpy array at specific indexes? I would like to get the fastest solution to write data in a 2D numpy array using an array of indexes. I have a large 2D boolean numpy array buffer import numpy as np n_rows = 100000 n_cols = 250 shape_buf = (n_rows, n_cols) row_indexes = np.arange(n_row...
Fastest way to write in an numpy array at specific indexes?
I would like to get the fastest solution to write data in a 2D numpy array using an array of indexes. I have a large 2D boolean numpy array buffer import numpy as np n_rows = 100000 n_cols = 250 shape_buf = (n_rows, n_cols) row_indexes = np.arange(n_rows,dtype=np.uint32) w_idx = np.random.randint(n_cols, size=n_rows,...
[ "The timing result you got makes sense given the fact that the first assignment fills in all 800 rows for each column, while the second one actually places the individual elements you want into the array. The reason the first version appears to be ~100x faster instead of ~800x faster is that the overhead of a call ...
[ 2 ]
[]
[]
[ "matrix_indexing", "numpy", "python" ]
stackoverflow_0074421931_matrix_indexing_numpy_python.txt
Q: Group conversations of 2 speakers from timestamps into a dataframe: Pandas I have the conversation between two speakers "A" and "B" with their timestamps. Successive A until B makes a Question and the trailing Bs until an A makes the answer for the question. I want to make a Question- Answer pair, where A asks th...
Group conversations of 2 speakers from timestamps into a dataframe: Pandas
I have the conversation between two speakers "A" and "B" with their timestamps. Successive A until B makes a Question and the trailing Bs until an A makes the answer for the question. I want to make a Question- Answer pair, where A asks the question and B answers( this will be one row of the dataframe) Note: A word is...
[ "After you simply mark each trail related to a distinct speaker a groupby operation without sorting would deliver the result.\nimport pandas as pd\nimport itertools\ndf = pd.read_excel('dataset.xlsx')\nstring_groups = sum([['%s_%s' % (i,n) for i in g] for n,(k,g) in enumerate(itertools.groupby(df.Speaker))],[])\ndf...
[ 1 ]
[]
[]
[ "azure", "dataframe", "pandas", "python", "timestamp" ]
stackoverflow_0074419767_azure_dataframe_pandas_python_timestamp.txt
Q: When trying to install python 3.6.6 in Google Colab, I get error When trying to install python 3.6.6 in Google Colab, I get error as mentioned below. ERROR: Could not find a version that satisfies the requirement python==3.6.6 (from versions: none) ERROR: No matching distribution found for python==3.6.6 The code I...
When trying to install python 3.6.6 in Google Colab, I get error
When trying to install python 3.6.6 in Google Colab, I get error as mentioned below. ERROR: Could not find a version that satisfies the requirement python==3.6.6 (from versions: none) ERROR: No matching distribution found for python==3.6.6 The code I am using to install in the Colab Notebook is: !pip install -r '/<path...
[ "As per Python Official Documentation Python Version - 3.6.6 is no longer supported. Apart from that currently Google Colab supports python version - 3.7.15.\nSo you can upgrade library version and then work on your project.\nA few developers suggest forced installation of a particular python version( in your case ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074338514_python.txt
Q: Click on link only with href Task: using selenium in Pyhton, I need to click on link, which consists only href: My solution: from selenium import webdriver from credentials import DRIVER_PATH, LINK from selenium.webdriver.common.by import By import time DRIVER_PATH = 'C:\\Program Files (x86)\\Microsoft\\Edge\\App...
Click on link only with href
Task: using selenium in Pyhton, I need to click on link, which consists only href: My solution: from selenium import webdriver from credentials import DRIVER_PATH, LINK from selenium.webdriver.common.by import By import time DRIVER_PATH = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedgedriver.exe' LINK =...
[ "\nThe href value of that element is dynamically changing, so you need to locate that element by fixed part of href attribute.\nYou need to wait for element to become clickable.\nThis should work better:\n\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom se...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "webdriverwait", "xpath" ]
stackoverflow_0074422309_python_selenium_selenium_webdriver_webdriverwait_xpath.txt
Q: ChatterBot error- OSError: [E941] Can't find model 'en' I tried running my first Chatterbot program (its from the PyPi page of Chatterbot), and when I run it, I get an error. The error is related to Spacy, but I am unable to find a solution. Here is the code: from chatterbot.trainers import ChatterBotCorpusTrainer...
ChatterBot error- OSError: [E941] Can't find model 'en'
I tried running my first Chatterbot program (its from the PyPi page of Chatterbot), and when I run it, I get an error. The error is related to Spacy, but I am unable to find a solution. Here is the code: from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot('Ron Obvious') trainer = ChatterBotCorpu...
[ "Make sure you actually have the right spacy model installed. For example, install en_core_web_sm with the python -m spacy download en_core_web_sm command in the terminal.\nNext, fix this error:\nFile \"C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\chatterbot\\tagging.py\", line 1...
[ 14, 4, 3, 0, 0, 0, 0, 0 ]
[]
[]
[ "chatterbot", "python", "python_3.x", "spacy", "windows" ]
stackoverflow_0066087475_chatterbot_python_python_3.x_spacy_windows.txt
Q: Decimal library and round() function Difference between rounding using Decimal library and rounding using round() function in Python 3. I don't know whether to use the round() function or use the Decimal library to round numbers Decimal from decimal import* getcontext().prec = 3 print(Decimal(10)/3) 3,33 round()...
Decimal library and round() function
Difference between rounding using Decimal library and rounding using round() function in Python 3. I don't know whether to use the round() function or use the Decimal library to round numbers Decimal from decimal import* getcontext().prec = 3 print(Decimal(10)/3) 3,33 round() print(round(10/3,2)) 3,33 I hope everyo...
[ "from decimal import *\nprint(Decimal(\"3.33\"))\n#output\nDecimal('3.33')\n# These Decimal objects can be converted to float(), int(), etc. and can be fed to round functions as well.\n\nprint(round(Decimal(\"3.33\")))\n#ouput\n3\n\nprint(round('3.33'))\n#output\nTypeError: type str doesn't define __round__ method\...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "python_decimal" ]
stackoverflow_0074422238_python_python_3.x_python_decimal.txt
Q: Combination of two fields to be unique in Python Eve In Python Eve framework, is it possible to have a condition which checks combination of two fields to be unique? For example the below definition restricts only firstname and lastname to be unique for items in the resource. people = { # 'title' tag used in i...
Combination of two fields to be unique in Python Eve
In Python Eve framework, is it possible to have a condition which checks combination of two fields to be unique? For example the below definition restricts only firstname and lastname to be unique for items in the resource. people = { # 'title' tag used in item links. 'item_title': 'person', 'schema': { ...
[ "You can probably achieve what you want by overloading the _validate_unique and implementing custom logic there, taking advantage of self.document in order to retrieve the other field value. \nHowever, since _validate_unique is called for every unique field, you would end up performing your custom validation twice,...
[ 3, 1, 0 ]
[]
[]
[ "eve", "python" ]
stackoverflow_0030623201_eve_python.txt
Q: Pygame. Sprite is still drawing after killing itself I want to remove the sprite and not display it on screen after click. The screenshot show that the sprite is successfully removed from the group, but it is still drawn on the screen. I would be happy to get help on this matter. import pygame as pg class Figure1...
Pygame. Sprite is still drawing after killing itself
I want to remove the sprite and not display it on screen after click. The screenshot show that the sprite is successfully removed from the group, but it is still drawn on the screen. I would be happy to get help on this matter. import pygame as pg class Figure1(pg.sprite.Sprite): def __init__(self, width: int, he...
[ "The sprite doesn't disappear just because you stop drawing it. Of course, you need to clear the screen. You have to clear the screen in every frame. The typical PyGame application loop has to:\n\nlimit the frames per second to limit CPU usage with pygame.time.Clock.tick\nhandle the events by calling either pygame....
[ 0 ]
[]
[]
[ "pygame", "python", "sprite" ]
stackoverflow_0074422320_pygame_python_sprite.txt
Q: Retrieving a specific value from a column and store it in a new column depending on the conditions that has been set I am new to pandas and I need help. I have a set of data as given: Index sensor timestamp 0 temperature 10/09/2019 10:49:00 1 humidity 10/09/2019 10:50:00 2 light 10/09/2019 10:50:00 3 motion 1...
Retrieving a specific value from a column and store it in a new column depending on the conditions that has been set
I am new to pandas and I need help. I have a set of data as given: Index sensor timestamp 0 temperature 10/09/2019 10:49:00 1 humidity 10/09/2019 10:50:00 2 light 10/09/2019 10:50:00 3 motion 10/09/2019 10:50:00 4 temperature 10/09/2019 11:19:00 5 humidity 10/09/2019 11:20:00 6 light 10/09/2019 11:2...
[ "You can use np.where() to give values on a condition. So for example you can use the command as below to say:\n1- if df['sensor'] == 'temperature', then get the corresponding value from df['timestamp'].\n2- If not, then set the value to 'not related'.\n3- Finally, save the result to a new column in the dataframe a...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074422195_dataframe_pandas_python.txt
Q: ValueError: Classification metrics can't handle a mix of continuous and binary targets i get this error from sklearn.metrics import accuracy_score print ("Accuracy : ", accuracy_score(y_test, y_pred)) ValueError: Classification metrics can't handle a mix of continuous and binary targets i been changing the metric...
ValueError: Classification metrics can't handle a mix of continuous and binary targets
i get this error from sklearn.metrics import accuracy_score print ("Accuracy : ", accuracy_score(y_test, y_pred)) ValueError: Classification metrics can't handle a mix of continuous and binary targets i been changing the metrics im using logistic regression that using binary classification
[ "The error itself is quite descriptive enough. Are you sure y_pred is purely integer values because accuracy_score wont work on continuous values (float)\n" ]
[ 0 ]
[]
[]
[ "logistic_regression", "python" ]
stackoverflow_0074419531_logistic_regression_python.txt
Q: Sorting a pivot table with win32com using Python I would like to sort an Excel pivot table created by using the win32com module with Python. As I understood, I should use the function AutoSort() and according to the official documentation, there are four fields, two of which are optional. Therefore, I am specifyin...
Sorting a pivot table with win32com using Python
I would like to sort an Excel pivot table created by using the win32com module with Python. As I understood, I should use the function AutoSort() and according to the official documentation, there are four fields, two of which are optional. Therefore, I am specifying only the "Order" and "Field" fields. AutoSort(Order=...
[ "I don't know if this is your case, but you need to pass a row field in the .PivotFields(\"\"\"Row field\"\"\").\n", "Have you tried sorting with ascending=true instead? As in https://stackoverflow.com/a/60778942/18247317\n" ]
[ 0, 0 ]
[]
[]
[ "excel", "pivot_table", "python", "win32com" ]
stackoverflow_0074221480_excel_pivot_table_python_win32com.txt
Q: How do I stop the scatter plot from whiting out the heatmap when I overlay them in Altair? So I want to overlay a heatmap with a scatter plot. I've managed to create the subplots and to overlay them, but when I overlay them the scatter plot whites out the columns and rows of each of the nodes it scatters when disp...
How do I stop the scatter plot from whiting out the heatmap when I overlay them in Altair?
So I want to overlay a heatmap with a scatter plot. I've managed to create the subplots and to overlay them, but when I overlay them the scatter plot whites out the columns and rows of each of the nodes it scatters when displayed on the heatmap. Here is my code: import random as r import numpy as np import pandas as pd...
[ "From what I could understand, there is a mismatch between the ticks of the heatmap and the scatter plot. Therefore, it creates a white cross around scatter plot points.\nI modified your code test this as follows:\nsource1 =source2.sample(5).drop(columns='Z')\n\n#Scatter plot\nscatter1 = alt.Chart(source1).mark_poi...
[ 1 ]
[]
[]
[ "altair", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074421721_altair_jupyter_notebook_pandas_python.txt
Q: unable to understand how the group name is defined based on the chat room name while making a chat application using channels self.room_group_name = "chat_%s" % self.room_name This is the line of code that defines the room group name from the room_name in the official tutorial on the channels website. (https://cha...
unable to understand how the group name is defined based on the chat room name while making a chat application using channels
self.room_group_name = "chat_%s" % self.room_name This is the line of code that defines the room group name from the room_name in the official tutorial on the channels website. (https://channels.readthedocs.io/en/stable/tutorial/part_2.html) I am unable to understand what "chat_%s" % self.room_name" means. Would apprec...
[ "\"chat_%s\" % self.room_name\n\nis an expression for formatting strings. The %s is a replaceable parameter which gets populated with the values passed after the %.\nPython3 has other formatting methods available that are roughly equivalent:\nf\"chat_{self.room_name}\"\n\nf\"chat_{self.room_name}\" is an f-string....
[ 2, 1 ]
[]
[]
[ "django", "django_channels", "python" ]
stackoverflow_0074422468_django_django_channels_python.txt
Q: Web scrape table with large amounts of data I am looking to web scrape a table consiting of 4000+ rows from the following website: https://www.nasdaq.com/market-activity/stocks/aapl/institutional-holdings Preferably I need someone to show how to use the Nasdaq api if possible. I believe the way I'd normally webscr...
Web scrape table with large amounts of data
I am looking to web scrape a table consiting of 4000+ rows from the following website: https://www.nasdaq.com/market-activity/stocks/aapl/institutional-holdings Preferably I need someone to show how to use the Nasdaq api if possible. I believe the way I'd normally webscrape (using beautifulSoup) would be very inefficie...
[ "The table is paginated, and every page is a new XHR call bringing 15 new records (offset by previous entries). Let's manipulate the url in our advantage - let's request, say, 7k records at once, with 0 offset (there are approx 4k entries total):\nimport requests\nimport pandas as pd\nheaders = {\n 'accept': 'ap...
[ 1 ]
[]
[]
[ "api", "python", "web_scraping" ]
stackoverflow_0074422517_api_python_web_scraping.txt
Q: How solve: (is deprecated; in a future version this will raise TypeError. Select only valid columns before calling the reduction. )? I am trying to fill null values in df['total_income'] column, but i am recieving the error: is deprecated; in a future version this will raise TypeError. Select only valid columns ...
How solve: (is deprecated; in a future version this will raise TypeError. Select only valid columns before calling the reduction. )?
I am trying to fill null values in df['total_income'] column, but i am recieving the error: is deprecated; in a future version this will raise TypeError. Select only valid columns before calling the reduction. The values to fill total_income are based on the age, education and income type of the users, here are the ...
[ "Use\n.median(numeric_only=True)\n\ninstead of\nmedian()\n\n\nDataFrame reductions (with 'numeric_only=None') is deprecated;\n\nsince None is the default value\n" ]
[ 1 ]
[]
[]
[ "database", "dataframe", "pandas", "python", "typeerror" ]
stackoverflow_0074422252_database_dataframe_pandas_python_typeerror.txt
Q: How to update a property in an Entity in Cosmos table API using Python I have the below table in CosmosDB. PartitionKey Rowkey Group Salary John HR A 100000 Mark DOC B 200000 I want to update the Salary property in the first entity. When I tried to update the salary propert...
How to update a property in an Entity in Cosmos table API using Python
I have the below table in CosmosDB. PartitionKey Rowkey Group Salary John HR A 100000 Mark DOC B 200000 I want to update the Salary property in the first entity. When I tried to update the salary property in the first entity, the complete entity is being replaced instead of upda...
[ "Please try by changing the following lines of code:\ncreated = table.get_entity(partition_key=my_entity[\"PartitionKey\"], row_key=my_entity[\"RowKey\"])\ncreated[\"Salary\"] = \"200\"\ntable.update_entity(mode=UpdateMode.REPLACE, entity=created)\n\nwith\ncreated = table_client.get_entity(partition_key=my_entity[\...
[ 0 ]
[]
[]
[ "azure_cosmosdb", "azure_cosmosdb_tables", "python" ]
stackoverflow_0074418404_azure_cosmosdb_azure_cosmosdb_tables_python.txt
Q: Doing simple operations with itertools combinatorics? I have a python dataset that has the following structure: cluster pts lon lat 0 5 45 24 1 6 47 23 2 10 45 20 As you can see, I have a column that refers to a cluster, the number of points within a cluster, the ...
Doing simple operations with itertools combinatorics?
I have a python dataset that has the following structure: cluster pts lon lat 0 5 45 24 1 6 47 23 2 10 45 20 As you can see, I have a column that refers to a cluster, the number of points within a cluster, the representative latitude of the cluster and the representat...
[ "As you mentioned, to do the combinations, you can use itertools.\nTo calculate the distance you can use geopy.distance.distance. Refer to the documentation for details: https://geopy.readthedocs.io/en/stable/#module-geopy.distance\nThis should work:\nfrom itertools import combinations\nfrom geopy.distance import d...
[ 0, 0 ]
[]
[]
[ "coordinates", "haversine", "python" ]
stackoverflow_0074422233_coordinates_haversine_python.txt
Q: How to plot stacked bars within grouped bars within further grouped bars in a bar-chart using Python (or R) I have the following Pandas df I would like to plot: Segment length Parameter Parameter value Train score Test score 0 16 n_estimators 5.0 0.975414 0.807823 1 ...
How to plot stacked bars within grouped bars within further grouped bars in a bar-chart using Python (or R)
I have the following Pandas df I would like to plot: Segment length Parameter Parameter value Train score Test score 0 16 n_estimators 5.0 0.975414 0.807823 1 16 n_estimators 10.0 0.982342 0.756803 2 16 n_estimators ...
[ "Here is a suggestion using R:\nWe can switch the grouping dynamics: e.g. fill and faceting.\nWhat we do here:\n\nBring Score in long format\nGroup and calculate the mean and sd\nplot with ggplot\n\nlibrary(tidyverse) \nlibrary(ggsci)\ndf %>% \n pivot_longer(ends_with(\"score\")) %>% \n group_by(name, Segment_len...
[ 2 ]
[]
[]
[ "bar_chart", "matplotlib", "python", "r" ]
stackoverflow_0074422416_bar_chart_matplotlib_python_r.txt
Q: Running Django development server from Git Bash gets stuck in windows 10 I'm new to Django and now getting stuck in running up the server. I've installed the following components on Windows 10: Python 3.7.0 Django 1.11.14 Geckodriver 0.21.0 I can successfully create a project using django-admin.py startprojec...
Running Django development server from Git Bash gets stuck in windows 10
I'm new to Django and now getting stuck in running up the server. I've installed the following components on Windows 10: Python 3.7.0 Django 1.11.14 Geckodriver 0.21.0 I can successfully create a project using django-admin.py startproject {project_name} . but when I run python manage.py runserver, the Git Bash...
[ "Thing is when you run python manage.py runserver by default it will run with auto reload.\nMeans when you change any file it will re-run or relaod again where it might be needed to kill and start port e.g 8080. \nUnfortunately GitBash is more lighter one which is not capable to kill process.Have one workaround to ...
[ 1, 0, 0, 0 ]
[]
[]
[ "django", "manage.py", "python" ]
stackoverflow_0051477001_django_manage.py_python.txt
Q: error in python : index 0 is out of bounds for axis 0 with size 0 Today i want to learn about how to code a content based filtering in python, and so i search some code and i apply it. I have a simple dataset contains a hotel dataset, with the name, address, and description. After i tried the code, its said index ...
error in python : index 0 is out of bounds for axis 0 with size 0
Today i want to learn about how to code a content based filtering in python, and so i search some code and i apply it. I have a simple dataset contains a hotel dataset, with the name, address, and description. After i tried the code, its said index 0 is out of bounds for axis 0 with size 0 at the end of the code. Here'...
[ "From what I understand you are trying to build a kind of search engine, which given a search vector will return the 10 best matching results.\nIf this is the case, you'll need to modify your rekomendasi function so that it will :\n\nprocess the input query vector\ncompute the similarity scores with the corpus (cor...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074421571_python.txt
Q: OSError: cannot load library '/opt/homebrew/lib/libsndfile.dylib': dlopen(/opt/homebrew/lib/libsndfile.dylib, 0x0002) I was using librosa with conda virtual environment in MAC M1 silicon machine. But it doesn't allow to run even import librosa code snippet and popping up this error message. OSError: cannot load li...
OSError: cannot load library '/opt/homebrew/lib/libsndfile.dylib': dlopen(/opt/homebrew/lib/libsndfile.dylib, 0x0002)
I was using librosa with conda virtual environment in MAC M1 silicon machine. But it doesn't allow to run even import librosa code snippet and popping up this error message. OSError: cannot load library '/opt/homebrew/lib/libsndfile.dylib': dlopen(/opt/homebrew/lib/libsndfile.dylib, 0x0002): tried: '/opt/homebrew/lib/l...
[ "This error popped up because I had three separate python environment in my M1 machine and python interpreter unable to locate the lib directory and load it to the code.\nMy advice to any person who will going to refer this question is, If you own a Mac m1 environment, setup only a one Conda environment, if you are...
[ 0 ]
[]
[]
[ "conda", "librosa", "python" ]
stackoverflow_0074386679_conda_librosa_python.txt
Q: How to rotate seaborn barplot x-axis tick labels I'm trying to get a barplot to rotate it's X Labels in 45° to make them readable (as is, there's overlap). len(genero) is 7, and len(filmes_por_genero) is 20 I'm using a MovieLens dataset and making a graph counting the number of movies in each individual genre. Her...
How to rotate seaborn barplot x-axis tick labels
I'm trying to get a barplot to rotate it's X Labels in 45° to make them readable (as is, there's overlap). len(genero) is 7, and len(filmes_por_genero) is 20 I'm using a MovieLens dataset and making a graph counting the number of movies in each individual genre. Here's my code as of now: import seaborn as sns import ma...
[ "\nData from MovieLens 25M Dataset at MovieLens\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\n\n# data\ndf = pd.read_csv('ml-25m/movies.csv')\n\nprint(df.head())\n\n movieId title ge...
[ 18, 1 ]
[]
[]
[ "matplotlib", "pandas", "python", "seaborn" ]
stackoverflow_0061368851_matplotlib_pandas_python_seaborn.txt
Q: How to retrieve array of dictionary data in a html table? First of all, I am new at Python(flask) and programming in general. So... here I am. To keep learning from big mistakes. I need to retrieve the data of an array of dictionaries to an HTML table. The Array contains Dictionaries of reservations. Each reservat...
How to retrieve array of dictionary data in a html table?
First of all, I am new at Python(flask) and programming in general. So... here I am. To keep learning from big mistakes. I need to retrieve the data of an array of dictionaries to an HTML table. The Array contains Dictionaries of reservations. Each reservation (dictionary) have the keys 'day', 'time', 'courttype', 'nam...
[ "You can create a grouped structure consisting of two nested dictionaries that represent the two axes of the table.\nThe first dictionary contains the times used as a key and dictionaries as a value.\nThe respective nested dictionary contains the days used as a key and a list of all entries that match this hour-day...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074419976_flask_python.txt
Q: How can I multiply a vector with a matrix without numpy in Python I'm trying to multiply a matrix with a vector but I can't find a way to make a vector without using NumPy I need to find a way to create a vector without numpy so I can multiply it with a matrix I tried an answer I have found here but it doesn't see...
How can I multiply a vector with a matrix without numpy in Python
I'm trying to multiply a matrix with a vector but I can't find a way to make a vector without using NumPy I need to find a way to create a vector without numpy so I can multiply it with a matrix I tried an answer I have found here but it doesn't seem to work when I try to use it.It doesn't do anything when I run it no ...
[ "class noNumpy:\n def multiply(self,v,G):\n rMatrix = len(G[0]) #This gives us the number of elements inside a row of matrix.\n rVector = len(v) #This gives us the number of elements in vector\n nMatrix = len(G) #This gives us the number of rows of the matrix.\n totalList = []\n\n ...
[ 0 ]
[]
[]
[ "multiplication", "python", "vector" ]
stackoverflow_0074422061_multiplication_python_vector.txt
Q: search multiple words in a string (python) New learner here... i just trying to find word in a string. can i search multiple words in one string using .find/.index or any other method? ex = "welcome to my question. you are welcome to be here" print(ex.find("welcome")) result = 0 and if i try get the second word i...
search multiple words in a string (python)
New learner here... i just trying to find word in a string. can i search multiple words in one string using .find/.index or any other method? ex = "welcome to my question. you are welcome to be here" print(ex.find("welcome")) result = 0 and if i try get the second word i will get -1 which mean not found ex = "welcome ...
[ "You look like you were on the right track but got some of the parameters incorrect in using the find operation. Using your sample string, following is a tweaked version of the code.\nex = \"welcome to my question. you are welcome to be here\"\n\nx = 0\n\nwhile True:\n x = ex.find(\"welcome\", x, len(ex))\n ...
[ 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074422605_python_string.txt
Q: Unable to get related data from ManyToManyField I'm trying to fetch related objects from below two models. Following django models with ManyToManyField relationship. Book class Book(models.Model): authors = models.ManyToManyField( to=Author, verbose_name="Authors", related_name="books_author" ) bookshelves = m...
Unable to get related data from ManyToManyField
I'm trying to fetch related objects from below two models. Following django models with ManyToManyField relationship. Book class Book(models.Model): authors = models.ManyToManyField( to=Author, verbose_name="Authors", related_name="books_author" ) bookshelves = models.ManyToManyField( to=Bookshelf, verbose_name...
[ "Prefetching is not necessary, but can be used to boost efficiency, you can work with:\nclass AuthorListAPIView(APIErrorsMixin, generics.ListAPIView):\n serializer_class = AuthorWithBooksSerializer\n queryset = Author.objects.exclude(name=None).prefetch_related('books_author')\nIn the AuthorWithBooksSerialize...
[ 2 ]
[]
[]
[ "django", "django_models", "orm", "python", "relational_database" ]
stackoverflow_0074421841_django_django_models_orm_python_relational_database.txt
Q: How to search for specific fields in a document in marqo i am looking for a way to search for specific fields in a document using marqo because whenever i use the .search() method the _highlights returns a random field either the title, description or any other field but it is usually random. this is an example of...
How to search for specific fields in a document in marqo
i am looking for a way to search for specific fields in a document using marqo because whenever i use the .search() method the _highlights returns a random field either the title, description or any other field but it is usually random. this is an example of what i mean: { 'hits': [ { 'Title'...
[ "i think the best way of getting specific fields when using marqo is by add a keyword argument to the search method which is searchable_attributes=[] then you pass the fields you want to list as a string.\neg.\nresult = mq.index(\"your_index\").search('query', searchable_attributes=['Title', 'Description'])\n\n" ]
[ 0 ]
[]
[]
[ "marqo", "python" ]
stackoverflow_0074422723_marqo_python.txt
Q: not able to get the search button with selenium python I am trying to scrap articles from this website. I manage to do the login part but when I try to click on the search button and send the values I got a timeout error. I try running the selenium with start-maximize option and I noticed the page don't seem to lo...
not able to get the search button with selenium python
I am trying to scrap articles from this website. I manage to do the login part but when I try to click on the search button and send the values I got a timeout error. I try running the selenium with start-maximize option and I noticed the page don't seem to load. WebDriverWait(driver, 20).until(EC.element_to_be_clickab...
[ "There are 2 elements on that page matching //*[@id=\"search__input\"] XPath locator, while you need the second one.\nYou have to use unique locator.\nThis should work better:\ntext_input = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, \"//div[@class='header__search']//*[@id='search__input']...
[ 2 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "web_scraping", "xpath" ]
stackoverflow_0074422680_python_selenium_selenium_chromedriver_web_scraping_xpath.txt
Q: How to efficiently insert multiple rows to a pandas DF with a missing value? I have a DF: df = pd.DataFrame({"A":[0,1,3,5,6], "B":['B0','B1','B3','B5','B6'], "C":['C0','C1','C3','C5','C6']}) I’m trying to insert 10 empty rows at the position where the number is missed from the continuous sequence of column A. For...
How to efficiently insert multiple rows to a pandas DF with a missing value?
I have a DF: df = pd.DataFrame({"A":[0,1,3,5,6], "B":['B0','B1','B3','B5','B6'], "C":['C0','C1','C3','C5','C6']}) I’m trying to insert 10 empty rows at the position where the number is missed from the continuous sequence of column A. For the 10 rows, values of column A, B and C's are the missed number, Nan, and Nan, r...
[ "One approach could be as follows:\n\nFirst, use df.set_index to make column A the index.\nNext, use range for a range that runs from 0 through to the max of A (i.e. 6).\nNow, apply df.reindex based on np.repeat. We use a loop to feed a 1 to the repeats parameter for all the values that exist in A, for all the ones...
[ 2, 2 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074422325_numpy_pandas_python.txt
Q: Why is my turtle code only drawing three rectangles when it is supposed to draw four? Starts bugging on its second function call This is a branch from my main code of a lottery ticket generator. The purpose of these two functions: (1) drawButton(length) to create rectangular buttons. (2) createMenu() to call drawB...
Why is my turtle code only drawing three rectangles when it is supposed to draw four? Starts bugging on its second function call
This is a branch from my main code of a lottery ticket generator. The purpose of these two functions: (1) drawButton(length) to create rectangular buttons. (2) createMenu() to call drawButton(length) and to fill the buttons with labels. My issue is when the main code attempts to return to the main menu, it runs turtle....
[ "There is a Simple fix, just change turtle.clearscreen() to t1.clear().\nThey are two different commands and work differently. https://stackoverflow.com/a/42260054/18554284 This Answer has a better explanation of their working\n", "Try using turtle.resetscreen() to also reset the state of the turtle.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "python_turtle", "turtle_graphics" ]
stackoverflow_0074422597_python_python_3.x_python_turtle_turtle_graphics.txt
Q: I am making a computer vision code with python and i got stuck everytime i try to run the code i get the following --> cap = cv2.VideoCapture(0) ^ IndentationError: expected an indented block I tried moving the "def hands():" and the error just keeps occurring A: You need to indent one time cap variab...
I am making a computer vision code with python and i got stuck
everytime i try to run the code i get the following --> cap = cv2.VideoCapture(0) ^ IndentationError: expected an indented block I tried moving the "def hands():" and the error just keeps occurring
[ "You need to indent one time cap variable and all code that you what to be executed when calling hands.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074422768_python_python_3.x.txt
Q: I want to loop this format using python I have 3 lists a = ["1", "2", "3", "4", "5", "6"] b = ['a', 'b', 'c'] c = ["13", "14"] and the format is: 1 3 a 2 13 b 3 13 c 4 14 a 5 14 b 6 14 c How do I get the above format? A: You can use itertools.cycle to get the list b to cycle round and have an adapter with...
I want to loop this format using python
I have 3 lists a = ["1", "2", "3", "4", "5", "6"] b = ['a', 'b', 'c'] c = ["13", "14"] and the format is: 1 3 a 2 13 b 3 13 c 4 14 a 5 14 b 6 14 c How do I get the above format?
[ "You can use itertools.cycle to get the list b to cycle round and have an adapter with itertools.repeat to get c to repeat its items:\nfrom itertools import repeat, cycle\n\ndef repeat_elements(iterable, repeat_count):\n for element in cycle(iterable):\n yield from repeat(element, repeat_count)\n\na = [\"...
[ 0 ]
[ "Below Code will print the required sequence with all characters in new line.\nfor i in c:\n for j in b:\n for k in a:\n print(k,i,j,sep='\\n')\n\n" ]
[ -1 ]
[ "loops", "nested", "python" ]
stackoverflow_0074422677_loops_nested_python.txt
Q: Intermittent ConnectTimeoutError from within Docker, but only when accessing AWS SSM My app uses SSM Parameter Store from within a Docker container both on Fargate instances and locally. I'm accessing it with Boto3 from Python. Multiple developers on my team, in different countries, have seen an intermittent issue...
Intermittent ConnectTimeoutError from within Docker, but only when accessing AWS SSM
My app uses SSM Parameter Store from within a Docker container both on Fargate instances and locally. I'm accessing it with Boto3 from Python. Multiple developers on my team, in different countries, have seen an intermittent issue, cropping up maybe a few times a day during continuous development, where for 10 minutes ...
[ "This turned out to be a Docker Desktop issue. You can work around it by using an older version of Docker Desktop, 4.5.0 (Mac) or 4.5.1 (Win).\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_ssm", "boto3", "docker", "python" ]
stackoverflow_0074033735_amazon_web_services_aws_ssm_boto3_docker_python.txt
Q: PyQt A problem of wait() in QThread using moveToThread() method I'm trying to write a multi-thread program with QThread in PyQt6. The example code is below. I create two threads by moveToThread() method and expect to join both of them after finish, but the result is crushing. I know the other way is create subclas...
PyQt A problem of wait() in QThread using moveToThread() method
I'm trying to write a multi-thread program with QThread in PyQt6. The example code is below. I create two threads by moveToThread() method and expect to join both of them after finish, but the result is crushing. I know the other way is create subclass of QThread, it's easier to write, but I still want to understand wh...
[ "What you're seeing is caused by the fact that cross-thread signals call their connected functions in the thread of the receiver.\nRemember that a QThread (just like a Thread object in python) is not \"the thread\", but the interface to access and run it.\nWhen you do this:\nwo1.finished.connect(th1.quit)\n\nthe re...
[ 1 ]
[]
[]
[ "concurrency", "pyqt", "python", "qthread" ]
stackoverflow_0074418100_concurrency_pyqt_python_qthread.txt
Q: Creating a dataframe from dbscan clustering results I have performed a clustering with geospatial data with the dbscan algorithm. You can see the project and the code in more detail here: https://notebook.community/gboeing/urban-data-science/15-Spatial-Cluster-Analysis/cluster-analysis I would like to calculate th...
Creating a dataframe from dbscan clustering results
I have performed a clustering with geospatial data with the dbscan algorithm. You can see the project and the code in more detail here: https://notebook.community/gboeing/urban-data-science/15-Spatial-Cluster-Analysis/cluster-analysis I would like to calculate the following in a dataframe: the area of each cluster. It...
[ "The code is something like\nimport pandas as pd\n\ndf = pd.DataFrame({\n 'cluster': [0, 1, 2],\n 'pts': [5, 6, 10],\n 'lat': [45, 47, 45],\n 'lon': [24, 23, 20],\n})\n\ndf = df.groupby('cluster').agg(\n min_lat=('lat', 'min'),\n max_lat=('lat', 'max'),\n min_lon=('lon', 'min'),\n max_lon=('...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074417436_python.txt
Q: TypeError: must provide a stream to wrap When I type pipenv shell in my command line to activate virtual environment I got this error: Traceback (most recent call last): File "c:\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\python39\lib\runpy....
TypeError: must provide a stream to wrap
When I type pipenv shell in my command line to activate virtual environment I got this error: Traceback (most recent call last): File "c:\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\python39\lib\runpy.py", line 87, in _run_code exec(code, run_...
[ "I think what your problem is, that you're missing stdout. I've had a similar problem with a script that was invoked from KDE. It kind of failed with a similar error message.\nMy fix for the moment was to simply redirect the stdout to /dev/null. I assume that this won't quite work, considering you are working from ...
[ 0 ]
[]
[]
[ "pipenv", "python" ]
stackoverflow_0068660300_pipenv_python.txt
Q: How to spot mistake in code (TypeError: 'int' object is not iterable)? block = [(1, 2), (6, 6), (8, 10), (13, 14)] def add_line(block, y): added_line = [] for (x1, x2) in block: added_line += zip((x1, x2), y) return added_line It is supposed to add y to (x1, x2) tuple. Instead it produces Ty...
How to spot mistake in code (TypeError: 'int' object is not iterable)?
block = [(1, 2), (6, 6), (8, 10), (13, 14)] def add_line(block, y): added_line = [] for (x1, x2) in block: added_line += zip((x1, x2), y) return added_line It is supposed to add y to (x1, x2) tuple. Instead it produces TypeError: 'int' object is not iterable. What did I do wrong and where?
[ "This is because you provide an int object(y) in the zip function. zip function takes iterable objects.\nYou can do this\n\nblock = [(1, 2), (6, 6), (8, 10), (13, 14)]\n\ndef add_line(block, y):\n added_line = []\n for (x1, x2) in block:\n added_line += ((x1, x2, y),)\n\n return added_line\n\nOr try...
[ 0, 0 ]
[]
[]
[ "python", "typeerror" ]
stackoverflow_0074422788_python_typeerror.txt
Q: How to create reproducible RandomForestClassifier in Python using jobs=-1? I've read at https://towardsdatascience.com/random-seeds-and-reproducibility-933da79446e3 to create reproducible machine learning models in Python, you need to set the random seed and pin the package versions. I would like to be able to sav...
How to create reproducible RandomForestClassifier in Python using jobs=-1?
I've read at https://towardsdatascience.com/random-seeds-and-reproducibility-933da79446e3 to create reproducible machine learning models in Python, you need to set the random seed and pin the package versions. I would like to be able to save models after training, that is, e.g. using pickle.dump(), load them up again a...
[ "According to the documentation, you must also set the random_state parameter in the RandomForestClassifier:\n\nrandom_state: int, RandomState instance or None, default=None\nControls both the randomness of the bootstrapping of the samples used when\nbuilding trees (if bootstrap=True) and the sampling of the featur...
[ 1 ]
[]
[]
[ "multithreading", "python", "random_forest", "random_seed" ]
stackoverflow_0074422806_multithreading_python_random_forest_random_seed.txt
Q: Fit an equation to data by minimizing mean squared error by minimizing sum of the squared error I am trying the estimate fitting parameters that can minimize sum of the squared error between the predicted and test values. To do this, I am using scipy.optimize.minimize Below is my code: import numpy as np import pa...
Fit an equation to data by minimizing mean squared error by minimizing sum of the squared error
I am trying the estimate fitting parameters that can minimize sum of the squared error between the predicted and test values. To do this, I am using scipy.optimize.minimize Below is my code: import numpy as np import pandas as pd import math import scipy.optimize as spo # Initial guess of the parameters LOGGMIN = 12...
[ "You are not recalculating your objective actually.\nThe code should be something like this.\nimport numpy as np\nimport pandas as pd\nimport math\nimport scipy.optimize as spo\n\n# Initial guess of the parameters\nLOGGMIN = 120 # variable 1\nLOGGMAX = 104 # variable 2\nBETA = 0 # variable 3\nGAMMA = 50 # varia...
[ 0 ]
[]
[]
[ "optimization", "python", "scipy" ]
stackoverflow_0074422241_optimization_python_scipy.txt
Q: converting JSON string into a python dictionary I have been tasked to create a JSON string which I then need to convert into a python dictionary. I am just getting errors about extra data and I am unsure what to do next import json company = '{"Name": "George", "Manages": ["James", "Jamilia"]}, {"Name": "James", ...
converting JSON string into a python dictionary
I have been tasked to create a JSON string which I then need to convert into a python dictionary. I am just getting errors about extra data and I am unsure what to do next import json company = '{"Name": "George", "Manages": ["James", "Jamilia"]}, {"Name": "James", "Manages": ["Jill", "Jenny"]}, {"Name": "Jamilia", "M...
[ "\n... each item has a name field and a field called manages which contains an array of the people managed by that person. If a person does not manage anybody, they have no field called manages.\n\nThat sounds like an organization tree. Each employee has a name and optionally who they manage:\nimport json\nfrom pp...
[ 1 ]
[]
[]
[ "arrays", "dictionary", "json", "python" ]
stackoverflow_0074422413_arrays_dictionary_json_python.txt
Q: Get max value from every index in a dictionary in python I was wondering how to get the max value from every key from a dictionary. Let's say I have this: dict={(1,1,True):[-1, 0.26], (2,1,True):[0.1, 0],(1,2,True):[0.01, -1],(2,2,True):[1, -0.11],} And this is the expected output: new_dict={(1,1,True):0, (2,1,Tru...
Get max value from every index in a dictionary in python
I was wondering how to get the max value from every key from a dictionary. Let's say I have this: dict={(1,1,True):[-1, 0.26], (2,1,True):[0.1, 0],(1,2,True):[0.01, -1],(2,2,True):[1, -0.11],} And this is the expected output: new_dict={(1,1,True):0, (2,1,True):0,(1,2,True):1,(2,2,True):0,} The new 0 and 1 values means ...
[ "You can write a simple argmax function, and do the rest with simple list/dict comprehensions.\ndef argmax(lst):\n return max(range(len(lst)), key=lambda i: lst[i])\n\n\nmy_dict = {(1, 1, True): [-1, 0.26], (2, 1, True): [0.1, 0], (1, 2, True): [0.01, -1], (2, 2, True): [1, -0.11], }\nprint({k: argmax([abs(v_) f...
[ 1, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074422973_dictionary_python.txt
Q: The sum of two columns and only show the third column I am trying to write and execute the SQL query that returns the top three records with the highest "score", where the "score" is the sum of two columns (let's call them X and Y). The result should have one column named score. Here is what I did %%sql select X,...
The sum of two columns and only show the third column
I am trying to write and execute the SQL query that returns the top three records with the highest "score", where the "score" is the sum of two columns (let's call them X and Y). The result should have one column named score. Here is what I did %%sql select X,Y,(X + Y) as score from survey ORDER BY score DESC LIMIT 3 ...
[ "SELECT X, Y, (X+Y) ... \n\ngives the 3 columns since you have SELECT 3 things. Instead just SELECT what you need in your case,\nSELECT (X + Y) as score from survey\nORDER BY score DESC\nLIMIT 3\n\n" ]
[ 1 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0074422957_python_sql.txt
Q: Slack Bot - Python slack send markdown messages I'm trying to send markdown messages in slack using SlackBot but I'm unable to find the documentation, All I got is this: response = client.chat_postMessage( ...: channel='#testing-bot', ...: text="Hello world! <@USerID> \n\n - a \n-b" ...: ...
Slack Bot - Python slack send markdown messages
I'm trying to send markdown messages in slack using SlackBot but I'm unable to find the documentation, All I got is this: response = client.chat_postMessage( ...: channel='#testing-bot', ...: text="Hello world! <@USerID> \n\n - a \n-b" ...: ...: ) I want to send MArkdown MEssages,...
[ "You need to send in the channel id (it will be alpha-numeric string) in instead of channel name (#testing-bot). \nUpdate:\nYou can also use block kit which is a UI framework for slack apps. It comes with a block kit builder which can be used for real-time view of block code. Added the references below for both.\nr...
[ 3, 1 ]
[]
[]
[ "bots", "markdown", "python", "slack" ]
stackoverflow_0059485300_bots_markdown_python_slack.txt
Q: Loop Invariant for Cut Rod Implementation CLRS I was wondering what the loop invariant would be for the loop present in lines 4 - 6 of this code and how to prove it during intialization, mantience, and termination. def cut_rod(p, n): if n == 0: return 0 q = -inf for i = 1 to n: q = max(...
Loop Invariant for Cut Rod Implementation CLRS
I was wondering what the loop invariant would be for the loop present in lines 4 - 6 of this code and how to prove it during intialization, mantience, and termination. def cut_rod(p, n): if n == 0: return 0 q = -inf for i = 1 to n: q = max(q, p[i] + cut_rod(p, n-i)) return q I wasn't r...
[ "I would say that after each iteration\nq = min price of rod with len n cut containing at least 1 piece of len <= i.\nThis can be proven inductively.\n" ]
[ 0 ]
[]
[]
[ "loop_invariant", "python" ]
stackoverflow_0074422150_loop_invariant_python.txt
Q: Plotting Monte Carlo Simulations for option pricing in Python I am trying to show the monte carlo barrier prices for different number of simultations in the x axis. This is what i tried so far but i'm getting the error -> ValueError: x and y must have same first dimension, but have shapes (10,) and (5,). I am new ...
Plotting Monte Carlo Simulations for option pricing in Python
I am trying to show the monte carlo barrier prices for different number of simultations in the x axis. This is what i tried so far but i'm getting the error -> ValueError: x and y must have same first dimension, but have shapes (10,) and (5,). I am new to python and as hard as i try i cannot find the error import numpy...
[ "in your function definition you used:\ndef sim_iterator(max_sample, N, S0, T, r, vol, K, H, method):\n\nwhile when using the function you used:\nMC_price_estimates = sim_iterator(S0, T, r, vol, K, H, max_sample, N, method='MC')\n\npython has positional arguments, which means the arguments are mapped according to t...
[ 0 ]
[]
[]
[ "matplotlib", "montecarlo", "python", "simulation" ]
stackoverflow_0074422904_matplotlib_montecarlo_python_simulation.txt
Q: Try / except not working with a specific exception in Python I'm trying to solve a specific error from a library (pycountry_convert) in a code with try / except, but when I use the except to avoid this case it just doesn't work. I've tried so many things to solve this. Here is the code import pycountry_convert as ...
Try / except not working with a specific exception in Python
I'm trying to solve a specific error from a library (pycountry_convert) in a code with try / except, but when I use the except to avoid this case it just doesn't work. I've tried so many things to solve this. Here is the code import pycountry_convert as pc def pegacontinente(nomepais): nomepais = nom...
[ "I just found the answer even though I didn't understand it. The solution for my problem found here .\nI don't know why but when I use repr(e) == \"KeyError(\\\"Invalid Country Alpha-2 code: \\'TL\\'\\\")\" instead of e == \"\\\"Invalid Country Alpha-2 code: \\'TL\\'\\\"\" it works. If any person could explain me w...
[ 0, 0 ]
[]
[]
[ "pycountry_convert", "python", "try_except" ]
stackoverflow_0074420190_pycountry_convert_python_try_except.txt
Q: Python- How to convert a string to float ( i know what float() function is my question is different) I have a problem converting string to float. For example, I want to get an input like 10**2 and I want the program to save the result of 10**2 in the variable. like this : Number = float(input("Enter the number : "...
Python- How to convert a string to float ( i know what float() function is my question is different)
I have a problem converting string to float. For example, I want to get an input like 10**2 and I want the program to save the result of 10**2 in the variable. like this : Number = float(input("Enter the number : ")) print(number * 2) something like this and when i run and it says : Enter the number : and I give it 1...
[ "You can use eval to parse general arithmetic expressions:\nNumber = eval(input(\"Enter the number : \"))\nprint(Number * 2)\n\nYou can even provide formulas, such as 10**2 + 5, etc.\n" ]
[ 2 ]
[ "Change \"number\" to Number\", and format the print as follows:\nMac_3.2.57$cat readIn.py\nNumber = float(input(\"Enter the number : \"))\nprint(\"%.0f\\n\" % (Number * 2))\nMac_3.2.57$python readIn.py\nEnter the number : 10**2\n200\n\nMac_3.2.57$\n\n" ]
[ -1 ]
[ "floating_point", "python", "string" ]
stackoverflow_0074422630_floating_point_python_string.txt
Q: return highest value of lists Hello I have a few lists and im trying to create a new list of the highest values repsectively. for an example, these are the lists: list1 = 5, 1, 4, 3 list2 = 3, 4, 2, 1 list3 = 10, 2, 5, 4 this is what I would like it to return: [10, 4, 5, 4] I thought that I could do a something ...
return highest value of lists
Hello I have a few lists and im trying to create a new list of the highest values repsectively. for an example, these are the lists: list1 = 5, 1, 4, 3 list2 = 3, 4, 2, 1 list3 = 10, 2, 5, 4 this is what I would like it to return: [10, 4, 5, 4] I thought that I could do a something like this: largest = list(map(max(l...
[ "This is the \"zip splat\" trick:\n>>> lists = [list1, list2, list3]\n>>> [max(col) for col in zip(*lists)]\n[10, 4, 5, 4]\n\nYou could also use numpy arrays:\n>>> import numpy as np\n>>> np.array(lists).max(axis=0)\narray([10, 4, 5, 4])\n\n", "You have used map incorrectly. Replace that last line with this:\n...
[ 8, 6, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0067783563_list_python.txt
Q: optimizer got an empty parameter list while using adam I was creating conv nets for cifar100 and code is give below but I have encounted the error mentioned in the title while initializing optimizer. Code for model class CNN(nn.Module): def __init__(self,k): super(CNN,self).__init__() #Convolutional laye...
optimizer got an empty parameter list while using adam
I was creating conv nets for cifar100 and code is give below but I have encounted the error mentioned in the title while initializing optimizer. Code for model class CNN(nn.Module): def __init__(self,k): super(CNN,self).__init__() #Convolutional layer conv1=nn.Conv2d(3,32,kernel_size=3,padding='same') ...
[ "Your submodules must be registered as attributes of your parent nn.Module:\nclass CNN(nn.Module):\n def __init__(self,k):\n super(CNN,self).__init__()\n # convolutional layer\n self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding='same')\n self.conv2 = nn.Conv2d(32, 64, kernel_size=3...
[ 1 ]
[]
[]
[ "conv_neural_network", "deep_learning", "optimization", "python", "pytorch" ]
stackoverflow_0074422830_conv_neural_network_deep_learning_optimization_python_pytorch.txt
Q: Pandas Create Dataframe I want to create new dataframe with using pandas. The table has value name and how many row that value appear In SQL I can create the table that I want like this SELECT start_station_name, COUNT(*) as total_number FROM table GROUP BY start_station_name; But when I used Pandas with assign f...
Pandas Create Dataframe
I want to create new dataframe with using pandas. The table has value name and how many row that value appear In SQL I can create the table that I want like this SELECT start_station_name, COUNT(*) as total_number FROM table GROUP BY start_station_name; But when I used Pandas with assign function I tried in this way c...
[ "You can directy pass the data (as a dictionary) while creating the dataFrame:\ncasual_station_name = pd.DataFrame(dict(station_name = casual_filter['start_station_name'], total_ride = casual_filter['start_station_name'].value_counts()))\n\n\nSource:\nhttps://www.geeksforgeeks.org/different-ways-to-create-pandas-da...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074422929_pandas_python.txt
Q: Python: Variable not re-initializing after each iteration I am learning about data handling in python, trying to handle weather data from each day of October. The data is from a local csv. I Iterate for day of the month and iterating for each hour inside of it. I have a class object handling data for each day. Th...
Python: Variable not re-initializing after each iteration
I am learning about data handling in python, trying to handle weather data from each day of October. The data is from a local csv. I Iterate for day of the month and iterating for each hour inside of it. I have a class object handling data for each day. The class object is being initialized right after the iteration o...
[ "\n...are intended to be re-initialized in each iteration\n\nVejrData.timeData is a class attribute and because it has a mutable default, every instance of VejrData will point-to the exact same list.\n>>> v = VejrData() \n>>> w = VejrData()\n>>> v.timeData.append('x')\n>>> v.timeData\n['x']\n>>> w.timeData \n...
[ 0, 0 ]
[]
[]
[ "class", "csv", "iteration", "loops", "python" ]
stackoverflow_0074379850_class_csv_iteration_loops_python.txt
Q: imread returns None, violating assertion !_src.empty() in function 'cvtColor' error I am trying to do a basic colour conversion in python however I can't seem to get past the below error. I have re-installed python, opencv and tried on both python 3.4.3 (latest) and python 2.7 (which is on my Mac). I installed ope...
imread returns None, violating assertion !_src.empty() in function 'cvtColor' error
I am trying to do a basic colour conversion in python however I can't seem to get past the below error. I have re-installed python, opencv and tried on both python 3.4.3 (latest) and python 2.7 (which is on my Mac). I installed opencv using python's package manager opencv-python. Here is the code that fails: frame = c...
[ "This error happened because the image didn't load properly. So you have a problem with the previous line cv2.imread. My suggestion is :\n\ncheck if the image exists in the path you give\n\ncheck if the count variable has a valid number\n\n\n", "If anyone is experiencing this same problem when reading a frame fro...
[ 187, 19, 12, 4, 4, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "The solution os to ad './' before the name of image before reading it...\n" ]
[ -1 ]
[ "opencv", "python" ]
stackoverflow_0052676020_opencv_python.txt
Q: Set and call object instance in Python Not sure what I am doing wrong here when trying to initiate instance of object and set a name to the instance... class Person: def Person(self, name): def __init__(self, name): self.name = name m = Person.Person('James') m.name Any help with an expl...
Set and call object instance in Python
Not sure what I am doing wrong here when trying to initiate instance of object and set a name to the instance... class Person: def Person(self, name): def __init__(self, name): self.name = name m = Person.Person('James') m.name Any help with an explanation? I've personally not encountered a s...
[ "The problem here is correlated to the function definition. Basically, you are calling Person function that define but doesn't call the init one. So, you can solve like that:\nclass Person:\n def __init__(self, name):\n self.name = name\n \nm = Person('James')\nm.name\n\n" ]
[ 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0074423085_oop_python.txt
Q: All nameservers failed to answer UDP port 53 Google cloud functions python 3.7 atlas mongodb i can connect locally to my mongodb server with the address 0.0.0.0/0. However, when I deploy my code to the cloud I get the error deploy to google cloud function. google cloud function with python 3.7 (beta) atlas mongo d...
All nameservers failed to answer UDP port 53 Google cloud functions python 3.7 atlas mongodb
i can connect locally to my mongodb server with the address 0.0.0.0/0. However, when I deploy my code to the cloud I get the error deploy to google cloud function. google cloud function with python 3.7 (beta) atlas mongo db python lib: -pymongo -dnspython Error: function crashed. Details: All nameservers failed to answ...
[ "finally after stuck 2 day, goblok banget semaleman\njust change connection \nfrom \n\nSRV connection string (3.6+ driver)\n\nto \n\nStandard connection string (3.4+ driver)\n\nmongodb://<USERNAME>:<PASSWORD>@<DATABASE>-shard-00-00-r091o.gcp.mongodb.net:27017,<COLLECTION>-shard-00-01-r091o.gcp.mongodb.net:27017,<CO...
[ 4, 1, 0 ]
[]
[]
[ "google_cloud_functions", "mongodb", "mongodb_atlas", "python" ]
stackoverflow_0053576199_google_cloud_functions_mongodb_mongodb_atlas_python.txt
Q: cannot catch SQLAlchemy IntegrityError Try as I might, I can't seem to catch the sqlalchemy IntegrityError correctly: from sqlalchemy import exc try: insert_record() except exc.IntegrityError, exc: print exc # this is never called handle_elegantly() # this is never called As what one might expect: In...
cannot catch SQLAlchemy IntegrityError
Try as I might, I can't seem to catch the sqlalchemy IntegrityError correctly: from sqlalchemy import exc try: insert_record() except exc.IntegrityError, exc: print exc # this is never called handle_elegantly() # this is never called As what one might expect: IntegrityError: (IntegrityError) insert or upd...
[ "I have the same need in my Flask application, I handle it like below and it works:\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import exc\n\ndb = SQLAlchemy(Flask(__name__))\n\ntry:\n db.session.add(resource)\n return db.session.commit()\nexcept exc.IntegrityError:\n ...
[ 61, 36, 1, 0 ]
[ "SQLALCHEMY_COMMIT_ON_TEARDOWN = False\n\n" ]
[ -4 ]
[ "error_handling", "exception", "exception_handling", "python", "sqlalchemy" ]
stackoverflow_0024522290_error_handling_exception_exception_handling_python_sqlalchemy.txt
Q: How to split the contents of a column into multiple columns inside a polars dataframe If I have string column namely, 'Cabin' in my dataframe, containing values as shown below: Series: 'Cabin' [str] [ "B/0/P" "F/0/S" "A/0/S" "A/0/S" "F/1/S" ] I want to know the process of splitting the 'Cabin'...
How to split the contents of a column into multiple columns inside a polars dataframe
If I have string column namely, 'Cabin' in my dataframe, containing values as shown below: Series: 'Cabin' [str] [ "B/0/P" "F/0/S" "A/0/S" "A/0/S" "F/1/S" ] I want to know the process of splitting the 'Cabin' column into multiple columns as shown below: A B C str i8 str "B" 0 "P" "F" 0 ...
[ "You are getting close. Either you could could index into this list to create new columns, or use split_exact to create a struct instead.\n>>> s = pl.Series(\"Cabin\", [\"B/0/P\", \"F/0/S\", \"A/0/S\"])\n>>> train = s.to_frame()\n>>> train\nshape: (3, 1)\n┌───────┐\n│ Cabin │\n│ --- │\n│ str │\n╞═══════╡\n│ B/0...
[ 0 ]
[]
[]
[ "data_preprocessing", "data_science", "dataframe", "python", "python_polars" ]
stackoverflow_0074419049_data_preprocessing_data_science_dataframe_python_python_polars.txt
Q: How do I get text from an text input using a button? I am trying to make it so the buttons function returns whatever is in the entry boxes when it is pressed. I know how to do it without using a .kv file but I’d rather use one as it is nicer. from kivy.app import App from kivy.uix.widget import Widget class MainW...
How do I get text from an text input using a button?
I am trying to make it so the buttons function returns whatever is in the entry boxes when it is pressed. I know how to do it without using a .kv file but I’d rather use one as it is nicer. from kivy.app import App from kivy.uix.widget import Widget class MainWidget(Widget): def get_input(self): pass clas...
[ "For me the best solution is always to add an id (just like you did) to the TextField in the .kv file:\nTextInput:\n id: my_text\n size: \"250\", \"30\"\n multiline: False\n pos: root.width / 2 - 125, root.height / 2 + 32\n\nand then the text written in it can be accessed in this way:\n...
[ 0 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0074421942_kivy_python.txt
Q: patent download, PermissionError: [WinError 32] The process cannot access the file because it is being used by another process I am trying to run this piece of code (https://github.com/ryanwhalen/patentsview_data_download/blob/master/patentsview_download.py), and got the following error: Traceback (most recent cal...
patent download, PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
I am trying to run this piece of code (https://github.com/ryanwhalen/patentsview_data_download/blob/master/patentsview_download.py), and got the following error: Traceback (most recent call last): File "...\patentsview_data_download-master\221113\patentsview_download_221113.py", line 285, in <module> download_and...
[ "It's because at line 142 the intermediate file is opened but never closed. This is the line:\ninfile = open(os.getcwd()+'/'+cleaned_file, 'r', encoding = 'utf-8')\n\nI'd suggest to rewrite it like this:\nwith open(os.getcwd()+'/'+cleaned_file, 'r', encoding = 'utf-8') as infile:\n # here goes the rest of file p...
[ 0 ]
[]
[]
[ "permissionerror", "python" ]
stackoverflow_0074423192_permissionerror_python.txt
Q: How to override Integer in Python? I want to inherit from integers and only redefine some methods. The goal is to have this behaviour: >>> i = Iter() >>> i == 0 True >>> next(i) Iter<1> >>> next(i) Iter<2> >>> i + 10 12 The naive approach would be to inherit from int: class Iter(int): def __new__(cls, start=0...
How to override Integer in Python?
I want to inherit from integers and only redefine some methods. The goal is to have this behaviour: >>> i = Iter() >>> i == 0 True >>> next(i) Iter<1> >>> next(i) Iter<2> >>> i + 10 12 The naive approach would be to inherit from int: class Iter(int): def __new__(cls, start=0, increment=1): return super()._...
[ "Are you aware that itertools.count exists? It does most of what you are trying to do, except for being able to use the instance itself as an integer.\nIt is not possible to extend either int or itertools.count for this purpose.\nRegarding the methods for operators, the reason you would need to define them is beca...
[ 0 ]
[]
[]
[ "abc", "inheritance", "integer", "overriding", "python" ]
stackoverflow_0074416410_abc_inheritance_integer_overriding_python.txt
Q: use plain text as a Data Parameter in a POST request with Python I'm new to Python/rest API the above screenshot is a sample POST request that running fine via 3rd party SandBox, and I want to be able run this POST Request via Python so I can do more personalization on it (e.g. run multiple taskid at one shot, ou...
use plain text as a Data Parameter in a POST request with Python
I'm new to Python/rest API the above screenshot is a sample POST request that running fine via 3rd party SandBox, and I want to be able run this POST Request via Python so I can do more personalization on it (e.g. run multiple taskid at one shot, output pre/post result, etc...): 1- Issue Description: I'm using this sc...
[ "use 'payload' in request body and it works now :\npayload = \"taskId=125918\"\nr2 = requests.request(\"POST\",DisableSchedule, headers=headers, data = payload )\n\n" ]
[ 0 ]
[]
[]
[ "api", "python", "rest" ]
stackoverflow_0074417509_api_python_rest.txt
Q: Q-Q plot in python eror in the theorical quantile axe I need to plot a QQ graph with the following information: spcs2k = np.array([[ 49, 524, 16, 87, 157, 58, 4, 41, 110, 90, 2, 41, 136, 495, 249, 40, 48, 3, 72, 294, 49, 28, 163, 61, 89, 2, 168, 286, 23, 67, 19, 11, 63, ...
Q-Q plot in python eror in the theorical quantile axe
I need to plot a QQ graph with the following information: spcs2k = np.array([[ 49, 524, 16, 87, 157, 58, 4, 41, 110, 90, 2, 41, 136, 495, 249, 40, 48, 3, 72, 294, 49, 28, 163, 61, 89, 2, 168, 286, 23, 67, 19, 11, 63, 4, 246, 130, 2, 378, 176, 251, 78, 138, 97, 34...
[ "The code works fine, it does what it should. QQ plot show if the data that you pass to it is normally distributed or not. In your case this means that the values are not even vaguely normally distributed in spcs2k.\nIf you run this code, you can see what it looks like on a dataset that came from normal distributio...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0066294719_python.txt
Q: BeautifultSoup Python get content I don't usually play with BeautifulSoup in Python so I am struggling to find the value 8.133,00 that matches with the Ibex 35 in the web page: https://es.investing.com/indices/indices-futures So far I am getting all the info of the page, but I can't filter to get that value: site ...
BeautifultSoup Python get content
I don't usually play with BeautifulSoup in Python so I am struggling to find the value 8.133,00 that matches with the Ibex 35 in the web page: https://es.investing.com/indices/indices-futures So far I am getting all the info of the page, but I can't filter to get that value: site = 'https://es.investing.com/indices/ind...
[ "Here is a way of getting that bit of information - a dataframe with all the info in that table containing IBEX 35, DAX, and so on, you can then slice that dataframe as you wish.\nimport pandas as pd\nfrom bs4 import BeautifulSoup as bs\nimport cloudscraper\n\nscraper = cloudscraper.create_scraper(disableCloudflare...
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074420517_beautifulsoup_python.txt
Q: How can I append these word to array without \r\n how to add each word in this structure to an array? I want to remove the extra quotations an (\r\n) for item in most_common_list: print(item[0]) A: Use the strip() method on your strings to remove whitespace (includes \r and \n) If it is the case that you ha...
How can I append these word to array without \r\n
how to add each word in this structure to an array? I want to remove the extra quotations an (\r\n) for item in most_common_list: print(item[0])
[ "Use the strip() method on your strings to remove whitespace (includes \\r and \\n)\n\nIf it is the case that you have literal \\r and \\n strings in your text (as opposed to carriage return and newline characters), you should figure out why these are being generated and put into your most_common_lost and fix it at...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074423263_python.txt
Q: How to extract a value after colon in all the rows from a pandas dataframe column? Edit: the dummy dataframe is edited I have a pandas data frame with the below kind of column with 200 rows. Let's say the name of df is data. -----------------------------------| B -----------------------------------| {'animal':'cat...
How to extract a value after colon in all the rows from a pandas dataframe column?
Edit: the dummy dataframe is edited I have a pandas data frame with the below kind of column with 200 rows. Let's say the name of df is data. -----------------------------------| B -----------------------------------| {'animal':'cat', 'bird':'peacock'...} I want to extract the value of animal to a separate column C f...
[ "I'm not totally sure of the structure of your data. Does this look right?\nimport pandas as pd\nimport re\ndf = pd.DataFrame({\n \"B\": [\"'animal':'cat'\", \"'bird':'peacock'\"]\n})\n\ndf[\"C\"] = df.B.apply(lambda x: re.sub(r\".*?\\:(.*$)\", r\"\\1\", x))\n\n", "The dictionary is unpacked with pd.json_normal...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074422720_dataframe_pandas_python.txt
Q: What is the difference between __init__ and __call__? I want to know the difference between __init__ and __call__ methods. For example: class test: def __init__(self): self.a = 10 def __call__(self): b = 20 A: The first is used to initialise newly created object, and receives arguments used to d...
What is the difference between __init__ and __call__?
I want to know the difference between __init__ and __call__ methods. For example: class test: def __init__(self): self.a = 10 def __call__(self): b = 20
[ "The first is used to initialise newly created object, and receives arguments used to do that:\nclass Foo:\n def __init__(self, a, b, c):\n # ...\n\nx = Foo(1, 2, 3) # __init__\n\nThe second implements function call operator.\nclass Foo:\n def __call__(self, a, b, c):\n # ...\n\nx = Foo()\nx(1, ...
[ 992, 326, 111, 35, 33, 20, 18, 14, 9, 8, 5, 4, 4, 2, 1, 1, 1 ]
[]
[]
[ "callable_object", "class", "object", "oop", "python" ]
stackoverflow_0009663562_callable_object_class_object_oop_python.txt
Q: Generate table with predefined parameters I want to create a table with these parameters: # Setting parameters for table initial_year=2020 last_year=2030 # Setting column names ## First two columns' names The first two columns must have columns with the nam...
Generate table with predefined parameters
I want to create a table with these parameters: # Setting parameters for table initial_year=2020 last_year=2030 # Setting column names ## First two columns' names The first two columns must have columns with the names 'Wages' and 'Payment' ### C...
[ "You can use:\ninitial_year=2020\nlast_year=2030\n\ncols = ['Wages', 'Payment']\nlistName = ['column1','column2','column3','column4']\n\ndf = (pd.DataFrame({'Year': range(initial_year, last_year+1)})\n .reindex(columns=['Year']+cols+listName, fill_value=1)\n )\n\nprint(df)\n\nOutput:\n Year Wages Pa...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074423132_pandas_python.txt
Q: Fitting a model taking too long on Colab (Tensorflow) with a GPU i am following a course on TensorFlow. and while trying to fit a model on Colab with a GPU, it shows ETA: 96:45:07. usually it doesn't take this long. The dataset is larger than i am used to work with, but it's not supposed to take this much time acc...
Fitting a model taking too long on Colab (Tensorflow) with a GPU
i am following a course on TensorFlow. and while trying to fit a model on Colab with a GPU, it shows ETA: 96:45:07. usually it doesn't take this long. The dataset is larger than i am used to work with, but it's not supposed to take this much time according to the video i was trying to fit the model, but i was not expec...
[ "First off, welcome to Stack Overflow :D\nOne of the reasons you may be seeing this is because in line 3 you are using the entirety of your train_data for your steps_per_epoch.\nThis means that for each of your 3 epochs, you are taking the entire length of your train data to pass through your dataset.\nWould you be...
[ 0 ]
[]
[]
[ "google_colaboratory", "python", "tensorflow" ]
stackoverflow_0074423185_google_colaboratory_python_tensorflow.txt
Q: How to iterate through letters in a list I am trying to iterate through all the letters in the list, although i am not making much progress. EX: L = ["pizza","burger","shawarma","nuggets"] the program should output p b s n i u h u z r a g and so on, basically iterating the words by their indexes. I tried doing i...
How to iterate through letters in a list
I am trying to iterate through all the letters in the list, although i am not making much progress. EX: L = ["pizza","burger","shawarma","nuggets"] the program should output p b s n i u h u z r a g and so on, basically iterating the words by their indexes. I tried doing it by a for loop like this: newlist = [i[0] for...
[ "Try this:\n>>> list(zip(*lst))\n[('p', 'b', 's', 'n'),\n ('i', 'u', 'h', 'u'),\n ('z', 'r', 'a', 'g'),\n ('z', 'g', 'w', 'g'),\n ('a', 'e', 'a', 'e')]\n\n# If you want a string with space between chars use \"' '.join\"\n>>> list(map(' '.join, zip(*lst)))\n['p b s n', 'i u h u', 'z r a g', 'z g w g', 'a e a e']\n\n...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0074423248_python.txt
Q: How to check if there is a picture on a website or not with Python and Selenium I want to check with a boolean request, if there is a picture on the website: https://portal.dnb.de/opac/mvb/cover?isbn=9783442472352 or not: https://portal.dnb.de/opac/mvb/cover?isbn=3499239663 I don`t know how that is possible. Thank...
How to check if there is a picture on a website or not with Python and Selenium
I want to check with a boolean request, if there is a picture on the website: https://portal.dnb.de/opac/mvb/cover?isbn=9783442472352 or not: https://portal.dnb.de/opac/mvb/cover?isbn=3499239663 I don`t know how that is possible. Thank you for your help!!
[ "Looks like you should deal with response status - for selenium, take a read:\nHow to get status code by using selenium.py (python code)\nAlternative approach, get the status with requests:\nimport requests\nurls = ['https://portal.dnb.de/opac/mvb/cover?isbn=9783442472352','https://portal.dnb.de/opac/mvb/cover?isbn...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "selenium" ]
stackoverflow_0074423161_beautifulsoup_python_selenium.txt
Q: How can i convert the index of a string that is marked as a string in an integer number? I am trying to code a Caesar cipher and i am trying to make a loop around the alphabet so that even if a put a high number as a shifter it doesn't give me an error. The problem is it tells me i can't compare a string with a nu...
How can i convert the index of a string that is marked as a string in an integer number?
I am trying to code a Caesar cipher and i am trying to make a loop around the alphabet so that even if a put a high number as a shifter it doesn't give me an error. The problem is it tells me i can't compare a string with a number, so when i put the new index like this "int(new_index)" i still get an error. The teacher...
[ "set new_index = index + shifter then after the while statement put encrypted_message += alphabet[new_index]\nthe full else statement:\nindex = alphabet.index(letter)\nnew_index = index + shifter\nwhile new_index > 25:\n new_index -= 25\nencrypted_message += alphabet[new_index]\n\n" ]
[ 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074423289_list_python_python_3.x.txt
Q: Issue with daisychaining MCP3008 SPI on Raspberry Pi with Python At the moment I am trying to let two MCP3008's communicate through SPI with my raspberry pi and a Python script. A potentiometer should send a certain analog value to the MCP3008 input channel. Here is my setup in Fritzing: Breadboard Schematic and h...
Issue with daisychaining MCP3008 SPI on Raspberry Pi with Python
At the moment I am trying to let two MCP3008's communicate through SPI with my raspberry pi and a Python script. A potentiometer should send a certain analog value to the MCP3008 input channel. Here is my setup in Fritzing: Breadboard Schematic and here is the schematic overview: Schematic Overview The SPI wiring is ba...
[ "Might be a late response, but according to the data sheet this chip can't be daisy-chained at all.\nI am also looking for an ADC which can be daisy-chained.\n" ]
[ 0 ]
[]
[]
[ "chain", "python", "spi" ]
stackoverflow_0052067470_chain_python_spi.txt
Q: How do I increase the dimension size of a dataset in a HDF5 file using H5PY? The Current dimension size is set to 32 characters. Is there any way to increase this using H5PY? I am having a problem where the values in my datasets are getting cut off because they are too long. A: To understand what you see in HDFV...
How do I increase the dimension size of a dataset in a HDF5 file using H5PY?
The Current dimension size is set to 32 characters. Is there any way to increase this using H5PY? I am having a problem where the values in my datasets are getting cut off because they are too long.
[ "To understand what you see in HDFView, an explanation of the HDF5 schema is in order. In your figure above, \"Data Type: Compound\" means this data set is heterogeneous data and \"Dimension Size: 32\" means there 32 rows of data. It DOES NOT tell you the type of each field (column) or the allocated size of any str...
[ 0, 0 ]
[]
[]
[ "h5py", "hdf5", "python" ]
stackoverflow_0074404059_h5py_hdf5_python.txt
Q: How can I use sys.argv to ask for user input instead of input How can I use sys.argv to ask for user input instead of input? I started this program using input but I want the program to use sys.argv instead. here is my code: import turtle import random import statistics name=input("Please enter Pa,Mi-Ma,Reg, or A...
How can I use sys.argv to ask for user input instead of input
How can I use sys.argv to ask for user input instead of input? I started this program using input but I want the program to use sys.argv instead. here is my code: import turtle import random import statistics name=input("Please enter Pa,Mi-Ma,Reg, or All: ") stepper=int(input("Please enter number of steps: ")) reps=in...
[ "With input function you can ask a user for input during the script execution. On the other hand data in sys.argv are passed in the command line and not used later. Both approached are ok, depending on what you need.\nYou can check how to use sys.argv on this tutorial or in Python docs.\nA good extension to it woul...
[ 0, 0 ]
[]
[]
[ "python", "sys" ]
stackoverflow_0074423320_python_sys.txt
Q: How to avoid SQL Injection in Python for Upsert Query to SQL Server? I have a sql query I'm executing that I'm passing variables into. In the current context I'm passing the parameter values in as f strings, but this query is vulnerable to sql injection. I know there is a method to use a stored procedure and restr...
How to avoid SQL Injection in Python for Upsert Query to SQL Server?
I have a sql query I'm executing that I'm passing variables into. In the current context I'm passing the parameter values in as f strings, but this query is vulnerable to sql injection. I know there is a method to use a stored procedure and restrict permissions on the user executing the query. But is there a way to avo...
[ "Fortunately, most database connectors have query parameters in which you pass the variable instead of giving in the string inside the query yourself for the risks you mentioned.\nYou can read more on this here: https://realpython.com/prevent-python-sql-injection/#understanding-python-sql-injection\nExample:\n# Vul...
[ 0, 0 ]
[]
[]
[ "parsing", "python", "sql_injection" ]
stackoverflow_0074420254_parsing_python_sql_injection.txt
Q: How do i calculate a rolling sum by group with monthly data in Python? I am trying to use rolling().sum() to create a dataframe with 2-month rolling sums within each 'type'. Here's what my data looks like: import pandas as pd df = pd.DataFrame({'type': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'], ...
How do i calculate a rolling sum by group with monthly data in Python?
I am trying to use rolling().sum() to create a dataframe with 2-month rolling sums within each 'type'. Here's what my data looks like: import pandas as pd df = pd.DataFrame({'type': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'], 'date': ['2022-01-01', '2022-02-01', '2022-03-01', '2022-...
[ "Here's a way to do it:\nrolling_sum = (\n df.assign(value=df.groupby(['type'])['value']\n .rolling(2, min_periods=1).sum().reset_index()['value'])\n)\n\nOutput:\n type date value\n0 A 2022-01-01 1.0\n1 A 2022-02-01 3.0\n2 A 2022-03-01 5.0\n3 A 2022-04-01 7.0\n4 B...
[ 3, 0, 0 ]
[]
[]
[ "pandas", "python", "rolling_computation" ]
stackoverflow_0072955109_pandas_python_rolling_computation.txt
Q: Can't plot comparative (double) histogram from Pandas table Here's the table from the dataframe: Points_groups Qty Contracts Qty Gones 1 350+ 108 275 2 300-350 725 1718 3 250-300 885 3170 4 200-250 2121 10890 5 150-200 3120 7925 6 100-150 653 1318 7 50-100 101 247 8 0-50 45 137 I'd like to get something ...
Can't plot comparative (double) histogram from Pandas table
Here's the table from the dataframe: Points_groups Qty Contracts Qty Gones 1 350+ 108 275 2 300-350 725 1718 3 250-300 885 3170 4 200-250 2121 10890 5 150-200 3120 7925 6 100-150 653 1318 7 50-100 101 247 8 0-50 45 137 I'd like to get something like this out of it: But that the columns corre...
[ "Since you already have the distribution in your pandas dataframe, the plot you need can be achieved with the following code:\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nDf = pd.DataFrame({'key': ['red', 'green', 'blue'], 'A': [1, 2, 1], 'B': [2, 4, 3]})\n\nX_axis = np.arange(len(Df...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074423095_python.txt
Q: Flask curl -d dont print in the console on windows I'm starting learn Flask and i testing the http request for the console, and when i try to print a form.request on flask using the curl -d and print it on the code, the console is not printing the form request (here is where is expected to print this and is not p...
Flask curl -d dont print in the console on windows
I'm starting learn Flask and i testing the http request for the console, and when i try to print a form.request on flask using the curl -d and print it on the code, the console is not printing the form request (here is where is expected to print this and is not printing it and heres the code Like the code print it j...
[ "from flask import Flask,request\napp=Flask(__name__)\n\n@app.route(\"/lele\",methods=[\"GET\",\"POST\"])\ndef lele():\n \"\"\" You can test this in postman by selecting `form-data` in the\n `Body` and giving the `name` as key and value michael (let's say).\"\"\"\n user=request.form['name'] \n return st...
[ 0 ]
[]
[]
[ "curl", "flask", "python" ]
stackoverflow_0074423296_curl_flask_python.txt
Q: How to fix JSON with python? my JSON file looks something like this: { "key": "test", "expiry": "test", "key": "eb467ff5-da95-47b5-b2d4-d5d6e9141a47", "expiry": "2022-12-13", "key": "17fd8fd1-b920-4e42-8e81-450757f9c79a", "expiry": "2022-12-13", "key": "91a969af-263f-46c1-a2f3-12e876403de6", "expir...
How to fix JSON with python?
my JSON file looks something like this: { "key": "test", "expiry": "test", "key": "eb467ff5-da95-47b5-b2d4-d5d6e9141a47", "expiry": "2022-12-13", "key": "17fd8fd1-b920-4e42-8e81-450757f9c79a", "expiry": "2022-12-13", "key": "91a969af-263f-46c1-a2f3-12e876403de6", "expiry": "2022-12-13", } I want it to ...
[ "Your code works fine:\nimport json\n\nx = '''{\n \"key\": \"test\", \"expiry\": \"test\",\n \"key\": \"eb467ff5-da95-47b5-b2d4-d5d6e9141a47\", \"expiry\": \"2022-12-13\",\n \"key\": \"17fd8fd1-b920-4e42-8e81-450757f9c79a\", \"expiry\": \"2022-12-13\",\n \"key\": \"91a969af-263f-46c1-a2f3-12e876403de6\"...
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074423492_json_python.txt
Q: Read specific columns from a csv file with csv module? I'm trying to parse through a csv file and extract the data from only specific columns. Example csv: ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 | I'm trying to capture on...
Read specific columns from a csv file with csv module?
I'm trying to parse through a csv file and extract the data from only specific columns. Example csv: ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS | 10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 | I'm trying to capture only specific columns, say ID, Name, Zip and Phone. Code I've ...
[ "The only way you would be getting the last column from this code is if you don't include your print statement in your for loop. \nThis is most likely the end of your code:\nfor row in reader:\n content = list(row[i] for i in included_cols)\nprint content\n\nYou want it to be this:\nfor row in reader:\n c...
[ 220, 129, 33, 21, 19, 7, 5, 3, 1, 1, 1, 0, 0, 0 ]
[ "To fetch column name, instead of using readlines() better use readline() to avoid loop & reading the complete file & storing it in the array.\nwith open(csv_file, 'rb') as csvfile:\n\n # get number of columns\n\n line = csvfile.readline()\n\n first_item = line.split(',')\n\n" ]
[ -2 ]
[ "csv", "python" ]
stackoverflow_0016503560_csv_python.txt
Q: Python: To check whether a given year is a leap year or not? I wanted to create a python program with user defined function which should read a year entered by user and return True/False by checking whether the entered year is a leap year or not. This is what I tried def is_leap(year): leap = False if(year...
Python: To check whether a given year is a leap year or not?
I wanted to create a python program with user defined function which should read a year entered by user and return True/False by checking whether the entered year is a leap year or not. This is what I tried def is_leap(year): leap = False if(year%4==0): if(year%100!=0): if(year%400==0): ...
[ "Handling the exceptions first yields clearer code.\ndef is_leap(year):\n if year % 400 == 0:\n return True # an exception to the century rule\n if year % 100 == 0:\n return False # centuries aren't leap years\n return year % 4 == 0\n\n", "By nesting the if/else, you act as an AND while y...
[ 2, 0, 0 ]
[]
[]
[ "function", "python", "python_3.x" ]
stackoverflow_0074423412_function_python_python_3.x.txt
Q: Dropping specific elements from lists I have data stored in the list. Below you can see my data. listName = ['column1','column2','column3','column4'] Now I want to drop elements with titles 'column2' and 'column3' I tried this command but is not work. listName=listName.drop(['column2','column3'],axis=1) Can any...
Dropping specific elements from lists
I have data stored in the list. Below you can see my data. listName = ['column1','column2','column3','column4'] Now I want to drop elements with titles 'column2' and 'column3' I tried this command but is not work. listName=listName.drop(['column2','column3'],axis=1) Can anybody help me how to solve this problem?
[ "If you need to remove them by value, I would create a list of elements to remove and filter the former list via list-comprehension:\nto_remove = ['column2','column3']\n\nfiltered = [x for x in listName if x not in to_remove]\n\nReturning:\n['column1','column4']\n\n", "You can try list.remove() to drop elements f...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074423473_python.txt
Q: Python GIL/Race conditions I'm trying to understand the Python GIL. My understanding is that since Python is compiled down into Python bytecode, when I have two threads decrementing a variable at the same time, theoretically, a race condition could occur. I'm wondering if this is the case, because I have been runn...
Python GIL/Race conditions
I'm trying to understand the Python GIL. My understanding is that since Python is compiled down into Python bytecode, when I have two threads decrementing a variable at the same time, theoretically, a race condition could occur. I'm wondering if this is the case, because I have been running the following code: from thr...
[ "Among other things, the GIL ensures that only one thread at a time is executing Python bytecode. So operations that take one bytecode cannot be interrupted.\nLet's use the dis module to look at your function:\nIn [1]: import dis\n\nIn [2]: def dec(n):\n ...: global count\n ...: for _ in range(n):\n ....
[ 1, 0, 0 ]
[]
[]
[ "gil", "python" ]
stackoverflow_0072071251_gil_python.txt
Q: I have a few categories and I would like to list the products per category I have a few categories and I would like to list the products per category in the format below (categories is an FK to products): Category 1 bunch of products .... Category N bunch of products I have tried many ways but so far I only get th...
I have a few categories and I would like to list the products per category
I have a few categories and I would like to list the products per category in the format below (categories is an FK to products): Category 1 bunch of products .... Category N bunch of products I have tried many ways but so far I only get the categories but not the products to show in my HTML. I m new in django cant fin...
[ "To do it, I think you should change the ForeignKey to a OnetoOneField in the Product class. Then you can access it from the Category and Sub_Category class.\nBut to do it with the current setup, you would have to go through each category and filter the products by it.\nSo…\ncategories = Category.objects.all()\nlis...
[ 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074411562_django_django_templates_python.txt
Q: double grouping data and output the first three for the first Pandas I have data with 1000 rows. Example structure: enter image description here i need to find: determine the winners (surnames and names of children) in each age group for boys and for girls (3 first places) for each species. Keep in mind that the w...
double grouping data and output the first three for the first Pandas
I have data with 1000 rows. Example structure: enter image description here i need to find: determine the winners (surnames and names of children) in each age group for boys and for girls (3 first places) for each species. Keep in mind that the winners can be more than 3, as the results may coincide I tried to do a do...
[ "Can you provide more information about the columns? Please try to share the real format.\nWith the data that I see I could use this.\ndf[\"ranking\"] = df.groupby([\"year\",'sex'])[\"run\"].rank(method=\"dense\", ascending=True)\nprint(df[df.ranking <= 3])\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074423570_dataframe_group_by_pandas_python.txt
Q: os Path "FileNotFoundError: [Errno 2] No such file or directory:" I'm trying to open files from this path C:\Users\Usuario\Llamas\llamas-python\face but I'm getting FileNotFoundError: [Errno 2] No such file or directory: im1 = Image.open(f' ./llamas-python/face/{face_files[item["Face"]]}.png').convert('RGBA') A...
os Path "FileNotFoundError: [Errno 2] No such file or directory:"
I'm trying to open files from this path C:\Users\Usuario\Llamas\llamas-python\face but I'm getting FileNotFoundError: [Errno 2] No such file or directory: im1 = Image.open(f' ./llamas-python/face/{face_files[item["Face"]]}.png').convert('RGBA') Any help¡?
[ "Try something like\nim1 = Image.open(f'.\\\\llamas-python\\\\face\\\\{face_files[item[\"Face\"]]}.png').convert('RGBA')\n\n" ]
[ 0 ]
[]
[]
[ "operating_system", "path", "python" ]
stackoverflow_0074423555_operating_system_path_python.txt
Q: How can I solve this indentation problem in my Django project I'm a beginner in Django. I was trying to add a method inside the OrderItem class. But the visual studio code is showing an indentation error. I'm not sure what is wrong here. Anyone can help me, please? Here is the code: from django.db import models fr...
How can I solve this indentation problem in my Django project
I'm a beginner in Django. I was trying to add a method inside the OrderItem class. But the visual studio code is showing an indentation error. I'm not sure what is wrong here. Anyone can help me, please? Here is the code: from django.db import models from django.contrib.auth.models import User # Create your models here...
[ "The @property decorator should be indented at the same level of the method and fields, so:\nclass OrderItem(models.Model):\n product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)\n order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)\n quantity = models.IntegerField(...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074423669_django_python.txt
Q: Problem with keyboard.read_key() in Python I want to capture the pressed key and do different tasks if it for example is '1' or '2', etc. This is my sample code: import keyboard key = keyboard.read_key() if key == '1': print('something') elif key == '2': print('something') else: print('something') ...
Problem with keyboard.read_key() in Python
I want to capture the pressed key and do different tasks if it for example is '1' or '2', etc. This is my sample code: import keyboard key = keyboard.read_key() if key == '1': print('something') elif key == '2': print('something') else: print('something') str = input('Type something: ') It works fine...
[ "You could try swapping keyboard.read_key() for the keyboard.is_pressed() function to process the input, depending on the keys pressed\nThe post below might help more:\nHow to detect key presses?\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074423541_python.txt
Q: How can I download an audio mp3 file and save it? My View: class UserSearchView(APIView): def get(self, request, link): url = config('BASE_URL') querystring = {"track_url": f'{link}'} headers = { "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('AP...
How can I download an audio mp3 file and save it?
My View: class UserSearchView(APIView): def get(self, request, link): url = config('BASE_URL') querystring = {"track_url": f'{link}'} headers = { "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('API_HOST') } response = requests.request...
[ "You got this far, good.\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n\nNow, just save the mp3.\n with open(\"music.mp3\", \"wb\") as fout:\n fout.write(response.content)\n\nEDIT\nHere's a demo.\n#! /usr/bin/env python3\nfrom pathlib import Path\n\nimpor...
[ 0 ]
[]
[]
[ "api", "django", "python" ]
stackoverflow_0074423351_api_django_python.txt
Q: module 'sys' has no attribute 'setExecutionLimit' import sys sys.setExecutionLimit(60000) this code gives me this error: sys.setExecutionLimit(60000) Traceback (most recent call last): File "<ipython-input-6-6f700cfa2531>", line 1, in <module> sys.setExecutionLimit(60000) AttributeError: module 'sys' has ...
module 'sys' has no attribute 'setExecutionLimit'
import sys sys.setExecutionLimit(60000) this code gives me this error: sys.setExecutionLimit(60000) Traceback (most recent call last): File "<ipython-input-6-6f700cfa2531>", line 1, in <module> sys.setExecutionLimit(60000) AttributeError: module 'sys' has no attribute 'setExecutionLimit' Why I am seeing this...
[ "There is no such thing as sys.setExecutionLimit in standard Python. That function is part of Skulpt, a Javascript-based implementation of something somewhat resembling Python 2.\nIn Skulpt, sys.setExecutionLimit manages execution time limits, which standard Python does not have.\nPython does have the completely un...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0066003046_python.txt
Q: What process is using a given file? I'm having trouble with one of my scripts, where it erratically seems to have trouble writing to its own log, throwing the error "This file is being used by another process." I know there are ways to handle this with try excepts, but I'd like to find out why this is happening ra...
What process is using a given file?
I'm having trouble with one of my scripts, where it erratically seems to have trouble writing to its own log, throwing the error "This file is being used by another process." I know there are ways to handle this with try excepts, but I'd like to find out why this is happening rather than just papering over it. Nothing ...
[ "You can use Microsoft's handle.exe command-line utility. For example: \nimport re\nimport subprocess\n\n_handle_pat = re.compile(r'(.*?)\\s+pid:\\s+(\\d+).*[0-9a-fA-F]+:\\s+(.*)')\n\ndef open_files(name):\n \"\"\"return a list of (process_name, pid, filename) tuples for\n open files matching the given nam...
[ 3, 0 ]
[]
[]
[ "file", "python", "windows" ]
stackoverflow_0039570207_file_python_windows.txt
Q: legend in python networkx I have the following code to draw a graph with nodes but i am failing to add a proper legend: (sorry, i can't post an image it seems i don't have enough reputation) I want a legend with the 4 colors, such as "light blue = obsolese, red = Draft, Yellow = realease, dark blue = init". I have...
legend in python networkx
I have the following code to draw a graph with nodes but i am failing to add a proper legend: (sorry, i can't post an image it seems i don't have enough reputation) I want a legend with the 4 colors, such as "light blue = obsolese, red = Draft, Yellow = realease, dark blue = init". I have seen some solutions with "scat...
[ "It seems that there is some kind of error when you are using nx.draw. Try to use nx.draw_networkx instead. \nAnd then use an axis from matplotlib to pass it when drawing the graph. This axis should contain the labels and colors of your nodes while plotting a point in (0,0) --> This is the tricky part.\nHope it hel...
[ 8, 8, 0 ]
[]
[]
[ "legend", "networkx", "python" ]
stackoverflow_0022992009_legend_networkx_python.txt
Q: How to make field names in prettytable auto switch lines? I am using prettytable to generate tables. But when the feild name is too long, it won't switch lines. The example code is like below: import prettytable x = prettytable.PrettyTable() x.max_table_width = 50 x.hrules = prettytable.ALL x.vrules = prettytable...
How to make field names in prettytable auto switch lines?
I am using prettytable to generate tables. But when the feild name is too long, it won't switch lines. The example code is like below: import prettytable x = prettytable.PrettyTable() x.max_table_width = 50 x.hrules = prettytable.ALL x.vrules = prettytable.ALL x.add_column("Field 1 is too long", ['Cell data also too ...
[ "seen it now and you have probably already solved it. I post it here for any other people looking for the same answer.\nAdd to the table after\ntab = PrettyTable()\ntab.header = False\n\nyou should solve it like this. Bye\n" ]
[ 0 ]
[]
[]
[ "prettytable", "python" ]
stackoverflow_0071432653_prettytable_python.txt