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: django.db.utils.InterfaceError: (0, '') when using django model I have django.db.utils.InterfaceError: (0, '') error on django. I googled around and found this error is related with django mysql connection. What I have done is just like this , from django.core.management.base import BaseCommand from ...models impo...
django.db.utils.InterfaceError: (0, '') when using django model
I have django.db.utils.InterfaceError: (0, '') error on django. I googled around and found this error is related with django mysql connection. What I have done is just like this , from django.core.management.base import BaseCommand from ...models import Issue class Command(BaseCommand): def handle(self, *args, **op...
[ "My code was very similar to what is in the question:\nclass Command(BaseCommand):\n help = \"Check order\"\n\n def add_arguments(self, parser):\n parser.add_argument(\"--order-no\", nargs=\"?\", type=str)\n\n def handle(self, *args, **options):\n order = Orders.objects.get(order_no=options[\...
[ 1, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0060852406_django_mysql_python.txt
Q: Does the mean() function in python create a list? I saw a code that does a mean calculation for a column using another column as a group for groupby() function. I want to know what it means by total_acc_avg[6]. Is total_acc_avg a list? Is 6 the index of the list? import pandas as pd data = pd.DataFrame({'mort_acc...
Does the mean() function in python create a list?
I saw a code that does a mean calculation for a column using another column as a group for groupby() function. I want to know what it means by total_acc_avg[6]. Is total_acc_avg a list? Is 6 the index of the list? import pandas as pd data = pd.DataFrame({'mort_acc':[6, None, 3, None, 2, None, 9, 8], # Create pandas D...
[ "total_acc_avg is a pandas Series object that contains the average of the mort_acc column, grouped by the total_acc column. In this case, the 6th index of the total_acc_avg Series contains the average value of the mort_acc column for the group with total_acc value of 6.\n" ]
[ 1 ]
[]
[]
[ "list", "mean", "pandas", "python" ]
stackoverflow_0074679258_list_mean_pandas_python.txt
Q: Tkinter make a frame fill whole column I'm trying to create a simple GUI using Tkinter module. I have a layout consisting of two columns (with weights 1 and 2). Now, I'd like my two widgets that I add (cfg and cfgx) to fill up the whole column in which they are placed. How could I achieve such a thing with my curr...
Tkinter make a frame fill whole column
I'm trying to create a simple GUI using Tkinter module. I have a layout consisting of two columns (with weights 1 and 2). Now, I'd like my two widgets that I add (cfg and cfgx) to fill up the whole column in which they are placed. How could I achieve such a thing with my current setup? Thanks in advance import tkinter ...
[ "You've configured the weight on the columns, but you haven't given any weight to any rows. Because of that, and because the frames by default are only 1 pixel tall, the columns will be virtually invisible.\nTo fix this you can give non-zero weight to one or more rows. For example, self.rowconfigure(0, weight=1)\nY...
[ 2 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0074677698_python_tkinter_user_interface.txt
Q: import matplotlib.pyplot as plt i have python 3.2.3 on windows. installed matplotlib i'm trying to do this: import matplotlib.pyplot as plt i get this: Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> import matplotlib.pyplot as plt File "E:\programs\python 3.2.3\lib\site-packages\matpl...
import matplotlib.pyplot as plt
i have python 3.2.3 on windows. installed matplotlib i'm trying to do this: import matplotlib.pyplot as plt i get this: Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> import matplotlib.pyplot as plt File "E:\programs\python 3.2.3\lib\site-packages\matplotlib\pyplot.py", line 24, in <module...
[ "You need to install urllib.\nThis is required by matplotlib\n", "Install Python 3.10 and update pip and then try to install Matplotlib and also install urllib using pip install urllib\n" ]
[ 0, 0 ]
[ "Look Install urllib from : https://pypi.python.org/pypi/urllib2_file/0.2.1\nOr if you was instaled pip you can use sudo pip install urllib\n" ]
[ -1 ]
[ "matplotlib", "python", "python_3.x" ]
stackoverflow_0023370715_matplotlib_python_python_3.x.txt
Q: Check if two columns are having matching values, but values are not in the same index places(Python, Pandas) So, I have this data frame about Super Store Sales. I have 2 sheets: First is named "Orders" Second one is named "Returns" In both sheets we have a matching column called "Order ID", but in the Return shee...
Check if two columns are having matching values, but values are not in the same index places(Python, Pandas)
So, I have this data frame about Super Store Sales. I have 2 sheets: First is named "Orders" Second one is named "Returns" In both sheets we have a matching column called "Order ID", but in the Return sheet we have less rows in "Order ID" of returned purchases and what I basically want to do is make a new column and ...
[ "You can use pandas.DataFrame.merge with pandas.Series.fillna :\ndf_order = pd.read_excel(\"SuperStoreUS.xlsx\", sheet_name=\"Orders\")\ndf_return = pd.read_excel(\"SuperStoreUS.xlsx\", sheet_name=\"Returns\")\n\nUse either :\n# --- To create a new dataframe\nout = df_order.merge(df_return, on=\"Order ID\", how=\"l...
[ 1, 1 ]
[]
[]
[ "matching", "multiple_columns", "pandas", "python" ]
stackoverflow_0074679052_matching_multiple_columns_pandas_python.txt
Q: read entire folder and extract multiple lines and append to new file I'm very new to python and this is far beyond what I'm capable of. I have multiple text files test01.txt test02.txt test03.txt test*.txt Each file has same # of lines and same structure i want to extract lines 20-25 and put that into a text file ...
read entire folder and extract multiple lines and append to new file
I'm very new to python and this is far beyond what I'm capable of. I have multiple text files test01.txt test02.txt test03.txt test*.txt Each file has same # of lines and same structure i want to extract lines 20-25 and put that into a text file that i can manipulate in excel. since there are 100s of files, it would be...
[ "Here is a script where you can read all files in a directory and write the name of the file and the content into a another file like you did.\nimport os\n\nValuesTextFile = open(\"values.txt\",\"a\")\nPath = './files/'\nfor Filename in os.listdir(Path):\n print (Filename)\n ValuesTextFile.writelines(Filename)\...
[ 0 ]
[]
[]
[ "new_operator", "python" ]
stackoverflow_0074679114_new_operator_python.txt
Q: pandas how to avoid iterations on rows? using python 3.7+ want to split paragraphs into new rows. need to use Spicy on each row to get the relevant result (not just split('.')). Is it possible with pandas vectorization? any help would be much appreciated have this df - >>> df = pd.DataFrame({'num_legs': [2, 4, 8, ...
pandas how to avoid iterations on rows?
using python 3.7+ want to split paragraphs into new rows. need to use Spicy on each row to get the relevant result (not just split('.')). Is it possible with pandas vectorization? any help would be much appreciated have this df - >>> df = pd.DataFrame({'num_legs': [2, 4, 8, 0], ... 'num_wings': [2, 0...
[ "a = 'some_description'\ndf.assign(some_description=df[a].str.split(r'\\. ')).explode(a)\n\nresult:\n num_legs num_wings some_description\nfalcon 2 2 falcons have wings\nfalcon 2 2 falcons fly\ndog 4 0 dog have 4 legs\ndog 4 ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "vectorization" ]
stackoverflow_0074679289_dataframe_pandas_python_vectorization.txt
Q: Get specific values out of dictionary with multiple keys in Python I want to extract multiple ISINs out of a output.json file in python. The output.json file looks like the following: {'A1J780': {'ter': '0.20%', 'wkn': 'A1J780', 'isin': 'IE00B88DZ566'}, 'A1J7W9': {' 'ter': '0.20%', 'isin': 'IE00B8KMSQ34'}, 'LYX0VQ...
Get specific values out of dictionary with multiple keys in Python
I want to extract multiple ISINs out of a output.json file in python. The output.json file looks like the following: {'A1J780': {'ter': '0.20%', 'wkn': 'A1J780', 'isin': 'IE00B88DZ566'}, 'A1J7W9': {' 'ter': '0.20%', 'isin': 'IE00B8KMSQ34'}, 'LYX0VQ': {'isin': 'LU1302703878'}, 'A2AMYP': {'ter': '0.22%', 'savingsPlan': ...
[ "Use data.values() as target in for loop to iterate over the JSON objects. Doing a loop over data iterates over the keys which is a string value (e.g. \"A1J780\").\ndata = {\n 'A1J780': {'ter': '0.20%', 'wkn': 'A1J780', 'isin': 'IE00B88DZ566'},\n 'A1J7W9': {'ter': '0.20%', 'isin': 'IE00B8KMSQ34'}\n}\nvalue_li...
[ 0, 0 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0074679216_dictionary_json_python.txt
Q: Disable `pip install` Timeout For Slow Connections I recently moved to a place with terrible internet connection. Ever since then I have been having huge issues getting my programming environments set up with all the tools I need - you don't realize how many things you need to download until each one of those thin...
Disable `pip install` Timeout For Slow Connections
I recently moved to a place with terrible internet connection. Ever since then I have been having huge issues getting my programming environments set up with all the tools I need - you don't realize how many things you need to download until each one of those things takes over a day. For this post I would like to try t...
[ "Use option --timeout <sec> to set socket time out.\nAlso, as @Iain Shelvington mentioned, timeout = <sec> in pip configuration will also work.\nTIP: Every time you want to know something (maybe an option) about a command (tool), before googling, check the manual page of the command by using man <command> or use <c...
[ 10, 0 ]
[]
[]
[ "pip", "python", "request_timed_out" ]
stackoverflow_0059796680_pip_python_request_timed_out.txt
Q: How do I make an event listener with decorators in Python? I want to make an event listener like this: @some.event async def on_ready(some_info): print(some_info) @some.event async def on_error(err): print(err) So for when something is ready, or if a message is received in like WebSockets, using this for...
How do I make an event listener with decorators in Python?
I want to make an event listener like this: @some.event async def on_ready(some_info): print(some_info) @some.event async def on_error(err): print(err) So for when something is ready, or if a message is received in like WebSockets, using this for Discord since some info is only available for when the Bot is I...
[ "Quick example :\n################################################################################\n# the code for the \"framework\"\nevent1_listeners = []\nevent2_listeners = []\n\ndef listen_event1(func):\n event1_listeners.append(func)\n return func\n\ndef listen_event2(func):\n event2_listeners.append(...
[ 1, 0 ]
[]
[]
[ "decorator", "discord", "python" ]
stackoverflow_0070982565_decorator_discord_python.txt
Q: SQL injection vulnerability? I have this simple website put together for learning purposes implementing a minor sanitization function ` def sqlescape(txt): return (str(txt).replace(";","&semi;").replace("'","&apos;")) def get_cipher(key): cipher = crypt.new(str.encode(salt+key)) return cipher def enc...
SQL injection vulnerability?
I have this simple website put together for learning purposes implementing a minor sanitization function ` def sqlescape(txt): return (str(txt).replace(";","&semi;").replace("'","&apos;")) def get_cipher(key): cipher = crypt.new(str.encode(salt+key)) return cipher def encode_body(body, key): if key =...
[ "It looks like your code is vulnerable to SQL injection attacks in the addrec function. In particular, the following line of code concatenates user input directly into the SQL query string, which can allow an attacker to inject arbitrary SQL commands:\ncur.executescript(\"INSERT INTO tasks (title,body) VALUES (\" +...
[ 1 ]
[]
[]
[ "python", "sql", "sql_injection" ]
stackoverflow_0074679347_python_sql_sql_injection.txt
Q: `TypeError: 'str' object is not callable` when a decorator function is caleld I get a TypeError: 'str' object is not callable error when a decorator function is caleld. E.g. I call the function msgReturnAsList, which is actually meant to return a list and therefore I do not understand why is it throwing an error t...
`TypeError: 'str' object is not callable` when a decorator function is caleld
I get a TypeError: 'str' object is not callable error when a decorator function is caleld. E.g. I call the function msgReturnAsList, which is actually meant to return a list and therefore I do not understand why is it throwing an error that a str object is not callable. I read at FreeCodeCamp that this TypeError occurs...
[ "A decorator method should return a method:\ndef wrapThis(func):\n def wrapper_func(msg):\n msg = str(msg).upper()\n return func(msg)\n return wrapper_func\n\n@wrapThis\ndef msgReturnAsList(msg):\n msg = list(msg)\n return msg\n\nb = \"Convert to upper and output it as a list of letters.\"...
[ 1 ]
[]
[]
[ "python", "python_decorators" ]
stackoverflow_0074679394_python_python_decorators.txt
Q: Plot one series for one column with Polars dataframe and Plotly I can't find how to plot these two series A and B with time on X. from numpy import linspace import polars as pl import plotly.express as px import plotly.io as pio pio.renderers.default = 'browser' times = linspace(1, 6, 10) df = pl.DataFrame({ ...
Plot one series for one column with Polars dataframe and Plotly
I can't find how to plot these two series A and B with time on X. from numpy import linspace import polars as pl import plotly.express as px import plotly.io as pio pio.renderers.default = 'browser' times = linspace(1, 6, 10) df = pl.DataFrame({ 'time': times, 'A': times**2, 'B': times**3, }) fig = px.li...
[ "You use Polars Dataframe instead of Pandas dataframe and indexing is a little different here and what is why you have this error. In order to plot it, one way to do it is to convert the dataframe from Polars to Pandas on the fly by using to_pandas():\nfig = px.line(df.to_pandas(),x='time', y=['A', 'B'])\n\nOutput\...
[ 1, 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074678281_plotly_python.txt
Q: Can I interrogate a PySpark DataFrame to get the list of referenced columns? Given a PySpark DataFrame is it possible to obtain a list of source columns that are being referenced by the DataFrame? Perhaps a more concrete example might help explain what I'm after. Say I have a DataFrame defined as: import pyspark.s...
Can I interrogate a PySpark DataFrame to get the list of referenced columns?
Given a PySpark DataFrame is it possible to obtain a list of source columns that are being referenced by the DataFrame? Perhaps a more concrete example might help explain what I'm after. Say I have a DataFrame defined as: import pyspark.sql.functions as func from pyspark.sql import SparkSession spark = SparkSession.bu...
[ "There is an object for that unfortunately its a java object, and not translated to pyspark.\nYou can still access it with Spark constucts:\n>>> df._jdf.queryExecution().executedPlan().apply(0).output().apply(0).toString()\nu'department#1621'\n>>> df._jdf.queryExecution().executedPlan().apply(0).output().apply(1).t...
[ 4, 0 ]
[ "You can try the below codes, this will give you a column list and its data type in the data frame.\nfor field in df.schema.fields:\n print(field.name +\" , \"+str(field.dataType))\n\n" ]
[ -1 ]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0074598689_apache_spark_pyspark_python.txt
Q: How do I copy all folder contents from one location to another location in Python? I have been trying to make a python file that will copy contents from one folder to another. I would like it to work on any Windows system that I run it on. It must copy ALL things ... i need solution to this problem. A: Here is o...
How do I copy all folder contents from one location to another location in Python?
I have been trying to make a python file that will copy contents from one folder to another. I would like it to work on any Windows system that I run it on. It must copy ALL things ... i need solution to this problem.
[ "Here is one way to do this using the shutil module in Python:\nimport shutil\n\n# Replace the source and destination paths with the appropriate paths on your system\nsrc_dir = \"C:\\\\source\\\\folder\"\ndst_dir = \"C:\\\\destination\\\\folder\"\n\n# Use the shutil.copytree function to copy everything from the sou...
[ 0, 0 ]
[]
[]
[ "coding_style", "copy", "paste", "python", "windows" ]
stackoverflow_0074679356_coding_style_copy_paste_python_windows.txt
Q: The problem of not being able to change the background color, thickness and position of the texts in the Streamlit Multiple Page App's Side Bar Streamlit Version: 1.13.0 in Homepage.py: import streamlit as st st.set_page_config( page_title= "Multipage App", page_icon="") st.title("Main Page") st...
The problem of not being able to change the background color, thickness and position of the texts in the Streamlit Multiple Page App's Side Bar
Streamlit Version: 1.13.0 in Homepage.py: import streamlit as st st.set_page_config( page_title= "Multipage App", page_icon="") st.title("Main Page") st.markdown('<style>div[class="css-6qob1r e1fqkh3o3"] {color:black; font-weight: 900; background: url("https://media2.giphy.com/media/46hpy8xB3MiHfrui...
[ "You can do this via inline CSS and st.markdown, although it's admittedly hacky.\ndef _set_block_container_style(\n max_width: int = 1200,\n max_width_100_percent: bool = False,\n padding_top: int = 1,\n padding_right: int = 1,\n padding_left: int = 1,\n padding_bottom: int = 1,\n):\n\nif max_widt...
[ 0, 0 ]
[]
[]
[ "css", "html", "python", "python_3.x", "streamlit" ]
stackoverflow_0074551058_css_html_python_python_3.x_streamlit.txt
Q: Plotly imshow reversing y labels reverses the image I'd like to visualize a 20x20 matrix, where top left point is (-10, 9) and lower right point is (9, -10). So the x is increasing from left to right and y is decreasing from top to bottom. So my idea was to pass x labels as a list: [-10, -9 ... 9, 9] and y labels ...
Plotly imshow reversing y labels reverses the image
I'd like to visualize a 20x20 matrix, where top left point is (-10, 9) and lower right point is (9, -10). So the x is increasing from left to right and y is decreasing from top to bottom. So my idea was to pass x labels as a list: [-10, -9 ... 9, 9] and y labels as [9, 8 ... -9, -10]. This worked as intended in seaborn...
[ "To get the desired visualization in plotly, you will need to specify the x and y values manually. Instead of passing in the labels as a list, you should specify the x and y values as a list of tuples, like so:\nx = [(-10, 9), (-9, 8), ... (9, -10)]\ny = [(-10, 9), (-9, 8), ... (9, -10)]\n\nThis should produce the ...
[ 2, 2, 0 ]
[ "import plotly.graph_objects as go\nimport plotly.express as px\n\nimg = np.arange(20**2).reshape((20, 20))\nfig = px.imshow(img,\n x=list(range(-10, 10)),\n y=list(range(10, 30, 1)),\n)\n\nfig.show()\n\nOutput:\n\n" ]
[ -1 ]
[ "plotly", "plotly_python", "python" ]
stackoverflow_0074601283_plotly_plotly_python_python.txt
Q: How to I assign values to letters that come from a csv file? I am calculating the gpa of a given curriculum. I want to multiply the number of credits by the grade that the student achieved. I want to make the program know that A in the csv file is equal to 4, B is equal to 3 and so on. enter image description here...
How to I assign values to letters that come from a csv file?
I am calculating the gpa of a given curriculum. I want to multiply the number of credits by the grade that the student achieved. I want to make the program know that A in the csv file is equal to 4, B is equal to 3 and so on. enter image description here I tried telling the program that the letters on the slice of data...
[ "I'd initialize a dict that maps letters to grades and then apply it to a new column.\nvals = { \"A\" : 4, \"B\" : 3, \"C\" : 2, \"D\" : 1, \"F\" : 0 }\ndf['Grade number'] = df['Grade'].apply(lambda x: vals.get(x))\n\n" ]
[ 0 ]
[]
[]
[ "assign", "python" ]
stackoverflow_0074679411_assign_python.txt
Q: How can I make the movement faster if I press the key? I'm making a Tetris game now. I want to implement it so that if I press the down key , the block falls quickly, and if I press the left and right keys, the block moves quickly. Pressing the key used the pygame.key.get_pressed() function and used pygame.time.se...
How can I make the movement faster if I press the key?
I'm making a Tetris game now. I want to implement it so that if I press the down key , the block falls quickly, and if I press the left and right keys, the block moves quickly. Pressing the key used the pygame.key.get_pressed() function and used pygame.time.set_timer() function to make speed change. The game speed was ...
[ "It looks to me that the reason your piece is dropping faster when you press a button is because if the user doesn't press a button the timer is set to 600ms. If they do press a button then the timer is set to 100ms.\nAs for how to fix this, you'll need to decouple the downward piece movement and user-input movemen...
[ 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074673028_pygame_python.txt
Q: Why do I get "Pickle - EOFError: Ran out of input" reading an empty file? I am getting an interesting error while trying to use Unpickler.load(), here is the source code: open(target, 'a').close() scores = {}; with open(target, "rb") as file: unpickler = pickle.Unpickler(file); scores = unpickler.load(); ...
Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?
I am getting an interesting error while trying to use Unpickler.load(), here is the source code: open(target, 'a').close() scores = {}; with open(target, "rb") as file: unpickler = pickle.Unpickler(file); scores = unpickler.load(); if not isinstance(scores, dict): scores = {}; Here is the traceback...
[ "Most of the answers here have dealt with how to mange EOFError exceptions, which is really handy if you're unsure about whether the pickled object is empty or not.\nHowever, if you're surprised that the pickle file is empty, it could be because you opened the filename through 'wb' or some other mode that could hav...
[ 297, 176, 27, 11, 3, 2, 1, 1, 0, 0, 0 ]
[ "from os.path import getsize as size\nfrom pickle import *\nif size(target)>0:\n with open(target,'rb') as f:\n scores={i:j for i,j in enumerate(load(f))}\nelse: scores={}\n\n#line 1.\nwe importing Function 'getsize' from Library 'OS' sublibrary 'path' and we rename it with command 'as' for shorter style ...
[ -1 ]
[ "file", "pickle", "python" ]
stackoverflow_0024791987_file_pickle_python.txt
Q: How to Exclude a column in a row of data in sqlalchemy and fastapi I am trying to load only AuthUser.id and AuthUser.username from the below result statement = select(func.count(UserCountry.id).label("uid"), AuthUser.id,AuthUser.username).\ join(CountryTool, CountryTool.id =...
How to Exclude a column in a row of data in sqlalchemy and fastapi
I am trying to load only AuthUser.id and AuthUser.username from the below result statement = select(func.count(UserCountry.id).label("uid"), AuthUser.id,AuthUser.username).\ join(CountryTool, CountryTool.id == UserCountry.country_tool_id).\ join(Country, Count...
[ "You can do it like this:\nresult = statement.all()\nresponse = []\n\nfor r in result:\n\n response.append({\n \"id\": r[1],\n \"username\": r[2]\n })\n\nThis code will iterate over the query result, and create a dictionary object with only the id and username fields, and append it to the respon...
[ 0 ]
[]
[]
[ "fastapi", "python", "python_3.x", "sqlalchemy" ]
stackoverflow_0074679473_fastapi_python_python_3.x_sqlalchemy.txt
Q: Create New rows from a multiple columns of lists I am scraping a website:- https://spfpharmacy.com/ I have successfully scraped this using selenium using the below code. test_list = [] test_list = list(string.ascii_uppercase) med_url = [] for i in tqdm(test_ list): driver.get(...
Create New rows from a multiple columns of lists
I am scraping a website:- https://spfpharmacy.com/ I have successfully scraped this using selenium using the below code. test_list = [] test_list = list(string.ascii_uppercase) med_url = [] for i in tqdm(test_ list): driver.get(f'https://spfpharmacy.com/search/?drugName={i}') ...
[ "It looks like you are appending the values to the list within the try block, which means that if an exception occurs, the list will not be updated. Instead, you should append the values to the list outside of the try block, and use a default value within the except block. For example, instead of this:\ntry:\n m...
[ 0 ]
[]
[]
[ "data_preprocessing", "dataframe", "pandas", "python", "selenium" ]
stackoverflow_0074679389_data_preprocessing_dataframe_pandas_python_selenium.txt
Q: Timeseries - group data by specific time period slices I am working with a csv file that has a dataset of 13 years worth of 5m time intervals. I am trying to slice sections of this dataset into specific time periods. example time_period = (df['time'] >= '01:00:00') & (df['time']<='5:00:00') time_period_df = df.loc...
Timeseries - group data by specific time period slices
I am working with a csv file that has a dataset of 13 years worth of 5m time intervals. I am trying to slice sections of this dataset into specific time periods. example time_period = (df['time'] >= '01:00:00') & (df['time']<='5:00:00') time_period_df = df.loc[time_period] I would expect an output of only the time bet...
[ "It looks like you are using the comparison operators >= and <= to try and specify the time range you want to include in your time period dataframe. However, these comparison operators will not work as expected on string values like the ones you have in your time column. Instead of using these operators, you can us...
[ 0 ]
[]
[]
[ "group_by", "pandas", "python", "python_datetime", "time_series" ]
stackoverflow_0074679543_group_by_pandas_python_python_datetime_time_series.txt
Q: How to make my function take less time in python? I am trying to do this problem: https://www.chegg.com/homework-help/questions-and-answers/blocks-pyramid-def-pyramidblocks-n-m-h-pyramid-structure-although-ancient-mesoamerican-fam-q38542637 This is my code: def pyramid_blocks(n, m, h): return sum((n+i)*(m+i) f...
How to make my function take less time in python?
I am trying to do this problem: https://www.chegg.com/homework-help/questions-and-answers/blocks-pyramid-def-pyramidblocks-n-m-h-pyramid-structure-although-ancient-mesoamerican-fam-q38542637 This is my code: def pyramid_blocks(n, m, h): return sum((n+i)*(m+i) for i in range(h)) But the problem is that whenever I t...
[ "You should use math to understand the components that are part of the answer. you need to calculate sum of all numbers until h, denote s, and the sum of all squares 1^2+2^2+3+2+... denotes sum_power\nit comes down to: h*m*n + s*n + s*m + sum_power\nthis is a working solution:\nimport time\n\ndef pyramid_blocks(n, ...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074664728_list_python.txt
Q: Filtering on multiple fields in an Elasticsearch ObjectField() I am having trouble figuring out the filtering syntax for ObjectFields() in django-elasticsearch-dsl. In particular, when I try to filter on multiple subfields of the same ObjectField(), I'm getting incorrect results. For example, consider the followin...
Filtering on multiple fields in an Elasticsearch ObjectField()
I am having trouble figuring out the filtering syntax for ObjectFields() in django-elasticsearch-dsl. In particular, when I try to filter on multiple subfields of the same ObjectField(), I'm getting incorrect results. For example, consider the following document class ItemDocument(Document): product = fields.Object...
[ "You can use the nested query in Elasticsearch to filter on multiple subfields of the same ObjectField. Here is an example of how you can do this in django-elasticsearch-dsl:\nx = ItemDocument.search().query(\n \"nested\",\n path=\"details\",\n query=Q(\"match\", details__category_id=3) & Q(\"range\", deta...
[ 1 ]
[]
[]
[ "django", "elasticsearch", "elasticsearch_dsl_py", "python" ]
stackoverflow_0074679018_django_elasticsearch_elasticsearch_dsl_py_python.txt
Q: Python web client to access API of an online supermarket Suppose you are writing a python web client to access an API of an online supermarket. Given below are the API details. Base URL= http://host1.open.uom.lk:8080 enter image description here``` Write a python program to retrieve all the products from the API S...
Python web client to access API of an online supermarket
Suppose you are writing a python web client to access an API of an online supermarket. Given below are the API details. Base URL= http://host1.open.uom.lk:8080 enter image description here``` Write a python program to retrieve all the products from the API Server and print the total number of products currently stored ...
[ "Here is an example of how you could write a Python program to retrieve all the products from the API server and print the total number of products currently stored in the server:\nimport requests\n\n# Define the base URL of the API\nBASE_URL = \"http://host1.open.uom.lk:8080\"\n\n# Use the requests library to make...
[ 0 ]
[]
[]
[ "api", "python" ]
stackoverflow_0074679483_api_python.txt
Q: Use trained ML to classify new dataset I have save my ML model that have been train. ML that I chose is SVM and I'm using pickle to save it. How can I use this model to classify new dataset which in csv file that have no sentiment label in it? I'm using Jupyter Notebook to do this project A: It would be useful t...
Use trained ML to classify new dataset
I have save my ML model that have been train. ML that I chose is SVM and I'm using pickle to save it. How can I use this model to classify new dataset which in csv file that have no sentiment label in it? I'm using Jupyter Notebook to do this project
[ "It would be useful to know what library (sklearn, pytorch, tensorflow, etc.) you used to train the model, but for this example I'm going to assume you used the pickle library to pickle and the sklearn library to train the model.\nAt some point you used something like pickle.dump(model, open(filename, 'wb')) to sav...
[ 0 ]
[]
[]
[ "jupyter_notebook", "machine_learning", "python", "sentiment_analysis" ]
stackoverflow_0074679490_jupyter_notebook_machine_learning_python_sentiment_analysis.txt
Q: How to find the position of a Rect in python? I was trying to make a code that moves a rect object (gotten with the get_rect function) but I need its coordinates to make it move 1 pixel away (if there are any other ways to do this, let me know.) Here is the code: import sys, pygame pygame.init() size = width, heig...
How to find the position of a Rect in python?
I was trying to make a code that moves a rect object (gotten with the get_rect function) but I need its coordinates to make it move 1 pixel away (if there are any other ways to do this, let me know.) Here is the code: import sys, pygame pygame.init() size = width, height = 1920, 1080 black = 0, 0, 0 screen = pygame.dis...
[ "If I am correct I think it is rect.left or rect.top that gives it. Another method is to create another rectangle and check if the rectangle is in that.\n", "#To move a rect object in Pygame, you can use the move_ip() method. This method takes two arguments, the x and y coordinates to move the rect by. For exampl...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074679565_python.txt
Q: Making a sliding puzzle game using turtle (not tkinter or pygame) So I'm currently trying to program a slidepuzzle game without importing tkinter or pygame. So far i've generated a board and populated it with working buttons (quit,load,reset) but I'm really lost on how to program the actual slide puzzle game with ...
Making a sliding puzzle game using turtle (not tkinter or pygame)
So I'm currently trying to program a slidepuzzle game without importing tkinter or pygame. So far i've generated a board and populated it with working buttons (quit,load,reset) but I'm really lost on how to program the actual slide puzzle game with the images i've been provided. This code generates the screen and butto...
[ "\nI've only seen turtle used to draw lines, not shapes, much less\nmovable game pieces. I think pygame would definitely be better for\nthis – OneCricketeer\n\nBelow is an example slide game simplified from an earlier answer I wrote about creating numbered tiles using turtle:\nfrom turtle import Screen, Turtle\nfr...
[ 0 ]
[]
[]
[ "game_development", "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074672476_game_development_python_python_turtle_turtle_graphics.txt
Q: How can I encryption Acii code using a Caesar method I want to use the same program # Caesar Cipher # http://inventwithpython.com/hacking (BSD Licensed) import pyperclip # the string to be encrypted/decrypted message = 'This is my secret message.' # the encryption/decryption key key = 13 # tells the program to e...
How can I encryption Acii code using a Caesar method I want to use the same program
# Caesar Cipher # http://inventwithpython.com/hacking (BSD Licensed) import pyperclip # the string to be encrypted/decrypted message = 'This is my secret message.' # the encryption/decryption key key = 13 # tells the program to encrypt or decrypt mode = 'encrypt' # set to 'encrypt' or 'decrypt' # every possible symbo...
[ "To encrypt the ASCII code of each symbol in the message using a Caesar cipher, you will need to modify the code as follows:\nReplace the LETTERS string with a string containing all the ASCII characters that you want to encrypt. For example, you could use the string string.printable from the string module, which in...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074679603_python.txt
Q: Outer minimum vectorization in numpy follow up This is a follow-up to my previous question. Given an NxM matrix A, I want to efficiently obtain the NxN matrix whose ith row is the sum along the 2nd axis of the result of applying np.minimum between A and the ith row of A. Using a for loop, > A = np.array([[1, 2], [...
Outer minimum vectorization in numpy follow up
This is a follow-up to my previous question. Given an NxM matrix A, I want to efficiently obtain the NxN matrix whose ith row is the sum along the 2nd axis of the result of applying np.minimum between A and the ith row of A. Using a for loop, > A = np.array([[1, 2], [3, 4], [5,6]]) > output = np.zeros(shape=(A.shape[0]...
[ "instead of a for loop. Using the NumPy minimum and sum functions, you can compute the desired matrix output as follows:\noutput = np.sum(np.minimum(A[:, None], A), axis=2)\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "vectorization" ]
stackoverflow_0074679407_numpy_python_vectorization.txt
Q: Regular Expression with Python (pattern with character exception) Please I tried to create a pattern that can index some references, but I have a case that is hard for me to separate. line = "thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38)." line = re.sub(r'(...
Regular Expression with Python (pattern with character exception)
Please I tried to create a pattern that can index some references, but I have a case that is hard for me to separate. line = "thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38)." line = re.sub(r'([^–])(\d+):(\d+)([^\\|–|\}|\d])(\d+)', r'\1\2:\3\4\5\\index[KT]{?@?!0\2...
[ "Does this do what you want? It's not clear what the conversion requirements are, but this matches your target strings:\nimport re\n\nline = \"thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 việc này đã thật sự xảyra như thế nào (37:36-38).\"\nwant1 = 'thiêu (30:33). chương 36-37 ghi lại tất cả những 2:6 vi...
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074679413_python_regex.txt
Q: colors are wrong numpy array for pillow image when I use txt firstly I am transforming an image into numpy array and writing it to a text file and this part is working the problem is when i copy the txt content and dynamically paste it as vector and display the image. the colors are showing wrong. enter image desc...
colors are wrong numpy array for pillow image when I use txt
firstly I am transforming an image into numpy array and writing it to a text file and this part is working the problem is when i copy the txt content and dynamically paste it as vector and display the image. the colors are showing wrong. enter image description here enter image description here ` import cv2 import sys ...
[]
[]
[ "It looks like the problem is that the image array is being saved in a text file as an array of strings rather than an array of integers. When you read the text file and convert it back into an array, the values are being interpreted as strings, resulting in the wrong colors when the image is displayed.\nOne soluti...
[ -1 ]
[ "numpy", "python", "python_3.x", "python_imaging_library" ]
stackoverflow_0074679658_numpy_python_python_3.x_python_imaging_library.txt
Q: subprocess.call can't find file/shutil.which failed in pycharm I am trying to transform a mp3 to a wav file in pycharm using subprocess import subprocess subprocess.call(['ffmpeg', '-i','test.mp3','test.wav']) It returns error of not finding file, so I change the 'ffmpeg' to its path on my pc and it work. The pro...
subprocess.call can't find file/shutil.which failed in pycharm
I am trying to transform a mp3 to a wav file in pycharm using subprocess import subprocess subprocess.call(['ffmpeg', '-i','test.mp3','test.wav']) It returns error of not finding file, so I change the 'ffmpeg' to its path on my pc and it work. The problem is that I am making an app and others might install ffpmeg on o...
[ "If you can make \"everyone\" to install using my ffmpeg-downloader then all of you can install FFmpeg by:\npip install ffmpeg-downloader\nffdl install\n\nThen in Python your package could use\nimport ffmpeg_downloader as ffdl\n\nsp.run([ffdl.ffmpeg_path, '-i', 'input.mp4', 'output.mkv'])\n\nAlternately, you can us...
[ 0 ]
[]
[]
[ "ffmpeg", "python", "shutil", "subprocess" ]
stackoverflow_0074678072_ffmpeg_python_shutil_subprocess.txt
Q: plt.legend() when plotting multiple dataframes in a for loop suppose i have three dataframes df1 = pd.DataFrame({"A" : [1,2,3], "B" : [4,5,6]}) df2 = pd.DataFrame({"A" : [2,5,3], "B" : [7,3,1]}) df3 = pd.DataFrame({"A" : [1,2,1], "B" : [5,3,6]}) I put all three dataframes in a list to perform an identical operati...
plt.legend() when plotting multiple dataframes in a for loop
suppose i have three dataframes df1 = pd.DataFrame({"A" : [1,2,3], "B" : [4,5,6]}) df2 = pd.DataFrame({"A" : [2,5,3], "B" : [7,3,1]}) df3 = pd.DataFrame({"A" : [1,2,1], "B" : [5,3,6]}) I put all three dataframes in a list to perform an identical operation on all three dataframes dframes = [df1, df2, df3] for frame in ...
[ "As mentioned in the message you've received after trying plt.legend(), the function is looking for labels. So, let's supply them inside plt.plot by setting the label parameter.\nWe can use enumerate to get index values for the dfs in your list dframes as well, to be used inside the f-strings.\ndframes = [df1, df2,...
[ 1 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "python" ]
stackoverflow_0074679576_dataframe_matplotlib_pandas_python.txt
Q: selenium python element select from dropdown menu Trying to select multiple elements from dropdown menu via selenium in python. Website from URL. But Timeoutexception error is occurring. I have tried Inspect menu from GoogleChrome. //label[@for="inputGenre"]/parent::div//select[@placeholder="Choose a Category"] g...
selenium python element select from dropdown menu
Trying to select multiple elements from dropdown menu via selenium in python. Website from URL. But Timeoutexception error is occurring. I have tried Inspect menu from GoogleChrome. //label[@for="inputGenre"]/parent::div//select[@placeholder="Choose a Category"] gives exactly the select tag that I need. But unfortunat...
[ "That Select element is hidden and can't be used by Selenium as we use normal Select elements to select drop-down menu items.\nHere we need to open the drop-down as we open any other elements by clicking them, select the desired options and click the Search button.\nSo, these lines are opening that drop down and se...
[ 2 ]
[]
[]
[ "drop_down_menu", "python", "select", "selenium", "xpath" ]
stackoverflow_0074679519_drop_down_menu_python_select_selenium_xpath.txt
Q: How to set turtle tracer false using tkinter? I have to generate two turtle windows and draw in each one, so I'm using tkinter to create and show the windows. My code currently opens the right screen and draws in it, but the turtle is really slow so I want to set the turtle tracer to false to use the update functi...
How to set turtle tracer false using tkinter?
I have to generate two turtle windows and draw in each one, so I'm using tkinter to create and show the windows. My code currently opens the right screen and draws in it, but the turtle is really slow so I want to set the turtle tracer to false to use the update function, but I can't figure out how to. This is my turtl...
[ "Since you didn't provide all your code, I can't test this, so I'm guessing a good start would be changing this:\nself.turtle = turtle.RawTurtle(turtle.TurtleScreen(self.canvas))\n\nto something like:\nscreen = turtle.TurtleScreen(self.canvas)\nscreen.tracer(False)\nself.turtle = turtle.RawTurtle(screen)\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_turtle", "tkinter", "turtle_graphics" ]
stackoverflow_0074670230_python_python_turtle_tkinter_turtle_graphics.txt
Q: Why does my pyrogram bot keep turning off? For some reason my bot always turns off without printing any output to the command line or showing any kind of error. The bot functions properly for a few hours after being turned on. Basic code looks like this: app = Client("my_account", '123456', '123456789abcd') TESTIN...
Why does my pyrogram bot keep turning off?
For some reason my bot always turns off without printing any output to the command line or showing any kind of error. The bot functions properly for a few hours after being turned on. Basic code looks like this: app = Client("my_account", '123456', '123456789abcd') TESTING = "321" USER_ID = "123" chat_mapping = {TESTI...
[ "if str(message.chat.id) not in chat_mapping\nin this lane, your statement will check if message.chat.id is equal one of the keys of dictionary, not values.\nMeans your message.chat.id can't be 123 or 321.\nUSER_ID = some id\nchat_mapping = [some ids] \n@app.on_message()\ndef my_handler(client, message):\n if st...
[ 0 ]
[]
[]
[ "pyrogram", "python" ]
stackoverflow_0071444813_pyrogram_python.txt
Q: Python : compare data frame row value with previous row value I am trying to create a new Column by comparing the value row with its previous value error that I get is ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I have checked the data type of colum...
Python : compare data frame row value with previous row value
I am trying to create a new Column by comparing the value row with its previous value error that I get is ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I have checked the data type of columns. All of them are float64 But I am getting an error CODE: col...
[ "No need for an if.. else statement here. You can use numpy.where instead.\n\nnumpy.where(condition, [x, y, ]/)\n\nReplace this :\nif df[df['HIST_60_100'] > df['HIST_60_100'].shift(+1)]: # check if the valus is > previous row value\n df['COLOR-60-100'] = \"GREEN\"\nelse:\n df['COLOR-60-100'] = \"RED\"\n\nBy t...
[ 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074679598_dataframe_numpy_pandas_python.txt
Q: How to append csv data as a ROW to another existing csv and move to 1st row. When i try to append all the data is at the bottom of the first column I have a csv with one row of data. It represents legacy headers that I am trying to append as 1 new row (or consider it as many columns) in a second csv. I need to com...
How to append csv data as a ROW to another existing csv and move to 1st row. When i try to append all the data is at the bottom of the first column
I have a csv with one row of data. It represents legacy headers that I am trying to append as 1 new row (or consider it as many columns) in a second csv. I need to compare the legacy header with the second csv's current headers, so after i append the data from the first csv i want to move it so that it's the first row ...
[ "You could use pandas to import the csv files, combine the two, and then overwrite the original mainfile.csv.\nI have created some dummy data to demonstrate. Here are the test files that I used:\nmainfile.csv\nFruit,Animals,Numbers\nApple,Cat,5\nBanana,Dog,8\nCherry,Goat,2\nDurian,Horse,4\n\nfilewith1row.csv\nFruta...
[ 1, 0 ]
[]
[]
[ "append", "csv", "python", "row" ]
stackoverflow_0074678018_append_csv_python_row.txt
Q: How to convert a number into words based on a dictionary? First, the user inputs a number. Then I want to print a word for each digit in the number. Which word is determined by a dictionary. When a digit is not in the dictionary, then I want the program to print "!". Here is an example of how the code should work:...
How to convert a number into words based on a dictionary?
First, the user inputs a number. Then I want to print a word for each digit in the number. Which word is determined by a dictionary. When a digit is not in the dictionary, then I want the program to print "!". Here is an example of how the code should work: Enter numbers : 12345 Result: one two three ! ! Because 4 and...
[ "# Consider the input as an int\nindata = input('Enter Ur Number: ')\n\nfor x in indata: print(DictN.get(x,'!'))\n\n", "a dict works like this:\n# the alphabetical letters are the keys, and the numbers are the values which belong to the keys\na = {'a': 1, 'b': 2}\n\n# if you want to have value from a it would be ...
[ 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074679274_python_python_3.x.txt
Q: Selenium Webdriver not able to locate and click button I am trying to create a scraper, and for accessing the page I need to click on the Accept Cookies button. The HTML referring to the button is: <div class="qc-cmp2-summary-buttons"> <button mode="secondary" size="large" class=" css-1hy2vtq"> <span>M...
Selenium Webdriver not able to locate and click button
I am trying to create a scraper, and for accessing the page I need to click on the Accept Cookies button. The HTML referring to the button is: <div class="qc-cmp2-summary-buttons"> <button mode="secondary" size="large" class=" css-1hy2vtq"> <span>MORE OPTIONS</span> </button><button mode="primary" size=...
[ "The error you received caused by a space before the class name value.\nSpaces between class names are used to separate between multiple class names.\nSo, to use this specific class name you could try this (without the space):\ndriver.find_element(By.CLASS_NAME, \"css-47sehv\").click()\n\nBut css-47sehv seems to ...
[ 1, 0 ]
[]
[]
[ "css_selectors", "python", "selenium_chromedriver", "selenium_webdriver", "xpath" ]
stackoverflow_0074679681_css_selectors_python_selenium_chromedriver_selenium_webdriver_xpath.txt
Q: why form.is_valid() is always false? I tried to create a contact us form in django but i got always false when i want to use .is_valid() function. this is my form: from django import forms from django.core import validators class ContactForm(forms.Form): first_name = forms.CharField( widget=forms.Text...
why form.is_valid() is always false?
I tried to create a contact us form in django but i got always false when i want to use .is_valid() function. this is my form: from django import forms from django.core import validators class ContactForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': ...
[ "you can use CBVs to easily save data on form valid\n\nviews.py\n\nfrom django.views import generic\n\nclass ContactCreateView(generic.CreateView,):\n model = Contact\n fields = \"__all__\" \n success_url = reverse_lazy(url_name)\n\nthen in in your templates\n\ntemplates/contact_form.html\n\n\n<form acti...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074677222_django_python.txt
Q: Issues creating basic password system in python I need to create a basic password system that reads from a text file for a school project, however I can't get new passwords and usernames to append into a text file and with my current system I have the problem that any account can be accessed with any preexisting p...
Issues creating basic password system in python
I need to create a basic password system that reads from a text file for a school project, however I can't get new passwords and usernames to append into a text file and with my current system I have the problem that any account can be accessed with any preexisting password. I've tried a couple different ways of trying...
[ "This is not an answer to the question yet.\nIt is a suggestion on how to monitor state changes for the files, since that\nseems to be the main issue.\nAdded code to create the initial files.\nAdded a function to be called before and after desired state changes.\n# Initialize the files\nprint('*' * 20, 'passwords.t...
[ 0 ]
[]
[]
[ "passwords", "python", "text_files" ]
stackoverflow_0074679154_passwords_python_text_files.txt
Q: Python Dataframe Split the list into 2 columns on a single space Im looking for help Splitting this list into 2 columns. The split needs to happen between the two words inside the comas. [JJL108995.161270128.23630-02.YF.JABI , NORMAL ROTATION MODE , +27.0 DARKNESS , 8 IPS PRINT SPEED , 8 IPS SLEW SPEED , 2 IPS BA...
Python Dataframe Split the list into 2 columns on a single space
Im looking for help Splitting this list into 2 columns. The split needs to happen between the two words inside the comas. [JJL108995.161270128.23630-02.YF.JABI , NORMAL ROTATION MODE , +27.0 DARKNESS , 8 IPS PRINT SPEED , 8 IPS SLEW SPEED , 2 IPS BACKFEED SPEED , +040 TEAR OFF , APPLICATOR PRINT MODE , MODE 2 APPLICAT...
[ "I went about it a different way . turns out the pre element can be predictable in length.\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup as bs\n \nr = requests.get('LINK')\nsoup = bs(r.content, 'lxml')\npre = soup.select_one('pre').text\nresults = []\n \nfor line in pre.split('\\n')[1:-...
[ 0 ]
[]
[]
[ "mysql", "pandas", "parsing", "python", "selenium" ]
stackoverflow_0074679276_mysql_pandas_parsing_python_selenium.txt
Q: Invalid Python SDK in PyCharm Since this morning, I'm no longer able to run projects in PyCharm. When generating a new virtual environment, I get an "Invalid Python SDK" error. Cannot set up a python SDK at Python 3.11... The SDK seems invalid. What I noticed: No matter what base interpreter I select (3.8, 3.9, 3....
Invalid Python SDK in PyCharm
Since this morning, I'm no longer able to run projects in PyCharm. When generating a new virtual environment, I get an "Invalid Python SDK" error. Cannot set up a python SDK at Python 3.11... The SDK seems invalid. What I noticed: No matter what base interpreter I select (3.8, 3.9, 3.10) Pycharm always generates a Pyth...
[ "I had the same problem on Linux. Solved it by invalidating caches as suggested here:\nhttps://stackoverflow.com/a/45099651/3990607\nIn pycharm click on File menu, then choose Invalidate caches..., tick all 4 boxes and then restart PyCharm. Solved the problem for me.\n", "Dealt with the same issue despite using p...
[ 7, 4, 0, 0, 0, 0, 0, 0 ]
[ "on Pycharm, click on up right corner search button --> wrire swştch python interpreter --> add new interpreter --> add local interpreter --> hit OK\n" ]
[ -1 ]
[ "pycharm", "python" ]
stackoverflow_0070664467_pycharm_python.txt
Q: Python-CSV write column(s) at given indices to new file I am trying to write the column(s) in a csv file where a word is present. the example shown here is for "car". NOTE: CANNOT USE PANDAS here is the sample in_file: 12,life,car,good,exellent 10,gift,truck,great,great 11,time,car,great,perfect the desired outpu...
Python-CSV write column(s) at given indices to new file
I am trying to write the column(s) in a csv file where a word is present. the example shown here is for "car". NOTE: CANNOT USE PANDAS here is the sample in_file: 12,life,car,good,exellent 10,gift,truck,great,great 11,time,car,great,perfect the desired output for out_file is: car truck car This is the current code: d...
[ "cat car.csv \n12,life,car,good,exellent\n10,gift,truck,great,great\n11,time,car,great,perfect\n\nimport csv\n\nwith open('car.csv') as car_file:\n r = cs...
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074671720_csv_python.txt
Q: python: How can I check if user input is in dataframe I am building a S&P500 app using streamlit, the functionality of the app prompts user to either choose number of plots to be shown from the slider or to type a specific symbol to show its plot, however, I am facing problems in trying to check if the symbol exis...
python: How can I check if user input is in dataframe
I am building a S&P500 app using streamlit, the functionality of the app prompts user to either choose number of plots to be shown from the slider or to type a specific symbol to show its plot, however, I am facing problems in trying to check if the symbol exists in the pandas series which contains all the symbols,(not...
[ "You should use pandas.Series.tolist (that returns a list) instead of pandas.Series.items (that returns an iterable).\nReplace this :\nif(spec_symbol == (a for a in df['Symbol'].items())):\n\nBy this :\nif(spec_symbol == (a for a in df['Symbol'].tolist())):\n\nOr simply :\nif spec_symbol in df['Symbol'].tolist():\n...
[ 0 ]
[]
[]
[ "pandas", "python", "streamlit" ]
stackoverflow_0074679765_pandas_python_streamlit.txt
Q: How to read excel line by line in pandas I want to ask how can How to read excel line by line in pandas. I want it to be in a loop that will get line by line information for facebook login with selenium. Hope everyone is easygoing because I'm a newbie import pandas as pd pd.options.display.max_rows = 28 data = pd...
How to read excel line by line in pandas
I want to ask how can How to read excel line by line in pandas. I want it to be in a loop that will get line by line information for facebook login with selenium. Hope everyone is easygoing because I'm a newbie import pandas as pd pd.options.display.max_rows = 28 data = pd.read_excel(r'file.xlsx') #load data into a D...
[ "Is it important that you read your Excel file line-by-line? Or is it also okay for you to read the entirety of your Excel file into a Dataframe and just iterate through that?\n", "since you're new to programming, a good counsel I can give is to read and search the documentation when doubts first appear.\nMany to...
[ 0, 0 ]
[]
[]
[ "excel", "pandas", "python", "python_3.x", "selenium" ]
stackoverflow_0074679803_excel_pandas_python_python_3.x_selenium.txt
Q: Is there a way to simplify the last three lines of code? race = "The rabbit will run with the turtle in the race." first_r = race.find("r") last_r = race.rfind("r") result1 = race[:first_r + 1] + race[first_r + 1:last_r].replace("r", "R") + race[last_r:] print(result1) A: One way are regular expressions: impo...
Is there a way to simplify the last three lines of code?
race = "The rabbit will run with the turtle in the race." first_r = race.find("r") last_r = race.rfind("r") result1 = race[:first_r + 1] + race[first_r + 1:last_r].replace("r", "R") + race[last_r:] print(result1)
[ "One way are regular expressions:\nimport re\n\nrace = \"The rabbit will run with the turtle in the race.\"\n\nm = re.match(r'([^r]*r)(.*)(r[^r]*)$', race)\n\nresult1 = m.group(1) + m.group(2).replace('r', 'R') + m.group(3)\n\nprint(result1)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074679782_python.txt
Q: Python Panda problems with group by and regularexpression A Table Sample like bellows- Product Price P1,Luxary product 2000 P2: Cosmetics product 1700 P1::Plastic product 600 P3/P1,Mobile phone 3300 P2:headphones 200 P3,Tri...
Python Panda problems with group by and regularexpression
A Table Sample like bellows- Product Price P1,Luxary product 2000 P2: Cosmetics product 1700 P1::Plastic product 600 P3/P1,Mobile phone 3300 P2:headphones 200 P3,Trimmer 150 P2,Camera 22...
[ "Assuming that your \"hidden signs\" always contain two characters, simply create new columns containing these prefixes:\ndf['Prefix'] = df['Product'].str[:2]\n\nYou may then group by prefix:\ndf.groupby('Prefix').sum()\n\n", "Here is a proposition using pandas.Series.str.extract :\nout = (\n df\n ...
[ 0, 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074679857_group_by_pandas_python.txt
Q: Delete all vowels from a string using a list-comprehension I'm trying to solve a challenge on Codewars. Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. Your task is to write a function that tak...
Delete all vowels from a string using a list-comprehension
I'm trying to solve a challenge on Codewars. Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. Your task is to write a function that takes a string and return a new string with all vowels removed. F...
[ "You're trying to make a list within your list-comprehension; you can just use the existing list:\nreturn \"\".join([char for char in x if char not in \"aeiouAEIOU\"])\n\nNote that we could even omit the list comprehension and just use a generator expression (by omitting the square brackets), but join() works inter...
[ 4, 0, 0 ]
[]
[]
[ "list", "list_comprehension", "python", "python_3.x", "string" ]
stackoverflow_0060169364_list_list_comprehension_python_python_3.x_string.txt
Q: Can we reduce the time complexity here? I have an AoC problem where I have been given the data below: data = """2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8""" I need to find the number of pairs which fully contain another pair. For example, 2-8 fully contains 3-7, and 6-6 is fully containe...
Can we reduce the time complexity here?
I have an AoC problem where I have been given the data below: data = """2-4,6-8 2-3,4-5 5-7,7-9 2-8,3-7 6-6,4-6 2-6,4-8""" I need to find the number of pairs which fully contain another pair. For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6. I have solved it using the below co...
[ "Your solution looks pretty complicated. Why not do something like:\ndata = \"\"\"2-4,6-8\n2-3,4-5\n5-7,7-9\n2-8,3-7\n6-6,4-6\n2-6,4-8\n\"\"\"\n\ndef included(line):\n (a1, b1), (a2, b2) = (map(int, pair.split(\"-\")) for pair in line.strip().split(\",\"))\n return (a1 <= a2 and b2 <= b1) or (a2 <= a1 and b1 ...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074675785_python_python_3.x.txt
Q: How I can assign value to variable using a button? I'm trying to write a graphic calculator using buttons. How I can assign value to variable using a button? I wrote the code: from tkinter import * a=0 def button_0a(): a=0 return 0 button0= Button(kalkulator, text="0", command=przycisk_0a) button0.gri...
How I can assign value to variable using a button?
I'm trying to write a graphic calculator using buttons. How I can assign value to variable using a button? I wrote the code: from tkinter import * a=0 def button_0a(): a=0 return 0 button0= Button(kalkulator, text="0", command=przycisk_0a) button0.grid(row=1, column=0) Of course, it is only a fragment of ...
[ "przycisk_0a is your callback function bind to the button0 button, so you must define your function, but you have defined the button0 button which is nonsense. \nIt must be like this:\ndef przycisk_0a():\n\n", "This changes the value of a and then changes the value of b the next time you press the button.\nfrom t...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0038443208_python_python_3.x_tkinter.txt
Q: Unable to update the discount command to subclass value since bas class value is set to 0 I've been trying to see if I can change the discount of an item that is necessary for computation. My challenge is that, I cannot update the discount since it was set to 0. class Dog: def __init__(self, food, amount, cost...
Unable to update the discount command to subclass value since bas class value is set to 0
I've been trying to see if I can change the discount of an item that is necessary for computation. My challenge is that, I cannot update the discount since it was set to 0. class Dog: def __init__(self, food, amount, cost, discount=0): self.food = food self.amount = amount self.cost = cost ...
[ "You might need to try the technique of walking through your program and speaking it out loud.\nFor example, this is how I read your listing and how I can detect an issue.\n\nI create a new GoldenDog\nThe GoldenDog calls the super.__init\nThe super init calculates the cost based on the discount of zero\nI then run ...
[ 0 ]
[]
[]
[ "attributes", "class", "object", "oop", "python" ]
stackoverflow_0074677411_attributes_class_object_oop_python.txt
Q: How to display two different return values from if/elif in Python? I'm reading a csv file and appending the data into a list and later using another function, I'm calculating these numbers and try to return two values using if/elif statements. To display the result I have created a procedure called displayData(num...
How to display two different return values from if/elif in Python?
I'm reading a csv file and appending the data into a list and later using another function, I'm calculating these numbers and try to return two values using if/elif statements. To display the result I have created a procedure called displayData(numbers) and here I'm struggling to show the calculated values from previou...
[ "Your seyrogus function needs to return a list rather than returning a single value. The reason you're only getting 4 as the result is that every time you call it, it iterates over numbers from the beginning and then returns the first converted value rather than iterating over the entire list.\nBoth getData and se...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0074679896_python.txt
Q: How can I convert Pine-script to Python? (QQE signal) enter image description here Pine-script code //@version=4 // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © colinmck study("QQE signals", overlay=true) RSI_Period = input(14, title='RSI Length'...
How can I convert Pine-script to Python? (QQE signal)
enter image description here Pine-script code //@version=4 // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © colinmck study("QQE signals", overlay=true) RSI_Period = input(14, title='RSI Length') SF = input(5, title='RSI Smoothing') QQE = input(4.238, t...
[ "#qqe signal\n df[\"RSI_Period\"]=ta.rsi (df['close'],14)\n SF = 5\n QQE = 4.238\n ThreshHold = input(10, title=\"Thresh-hold\")\n\n src = df['close']\n Wilders_Period = df[\"RSI2\"] * 2 - 1\n\n Rsi = rsi(src, RSI_Period)\n RsiMa = ta.ema(Rsi, SF)\n AtrRsi = abs(RsiMa[1] - RsiMa)\n Ma...
[ 0, 0 ]
[]
[]
[ "pine_script", "python", "tradingview_api" ]
stackoverflow_0074604279_pine_script_python_tradingview_api.txt
Q: Im a python beginner, is there any way i can repeat this simple calculator code infinity times? x=int(input("please type in any number: ")) y=input("please type operation: +,-,*,/: ") z=int(input("please type in your 2nd number: ")) if(y=="+"): print("your answer is: ", x+z) print("thanks for using thi...
Im a python beginner, is there any way i can repeat this simple calculator code infinity times?
x=int(input("please type in any number: ")) y=input("please type operation: +,-,*,/: ") z=int(input("please type in your 2nd number: ")) if(y=="+"): print("your answer is: ", x+z) print("thanks for using this calculator!") print("goodbye") elif(y=="-"): print("your answer is: ", x-z) print("tha...
[ "Start the loop\nwhile True:\n x=int(input(\"please type in any number: \"))\n y=input(\"please type operation: +,-,*,/: \")\n z=int(input(\"please type in your 2nd number: \"))\n if(y==\"+\"):\n print(\"your answer is: \", x+z)\n print(\"thanks for using this calculator!\")\n p...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074679948_python.txt
Q: Working with a python array full of array Ok so I have an array of arrays. I'm currently wondering if I'm better to export all of it in my mysql database and do the sorting once there, or work with the array itself. Here is part of the array: datas = [['Anonymous User-b82a42', 'DYDXUSDT', 'Short', 20, 258.2, 2.332...
Working with a python array full of array
Ok so I have an array of arrays. I'm currently wondering if I'm better to export all of it in my mysql database and do the sorting once there, or work with the array itself. Here is part of the array: datas = [['Anonymous User-b82a42', 'DYDXUSDT', 'Short', 20, 258.2, 2.332, 2.333, -0.26, -0.8573, '2022-11-16 14:02:28']...
[ "I solved this storing in 2 database tables and comparing them after.\n" ]
[ 0 ]
[]
[]
[ "arrays", "mysql", "python", "sorting" ]
stackoverflow_0074465997_arrays_mysql_python_sorting.txt
Q: Quit button assistance needed I'm trying to make a code for this topic i'm doing and I've manage to get some of it done but when it comes to quiting my tkinter menu it doesn't close unless I manually close it, I've got the the button for the option to close it but it doesn't work. Can anyone help with my problem. ...
Quit button assistance needed
I'm trying to make a code for this topic i'm doing and I've manage to get some of it done but when it comes to quiting my tkinter menu it doesn't close unless I manually close it, I've got the the button for the option to close it but it doesn't work. Can anyone help with my problem. Here's my code below. import sys im...
[ "For Tkinter you can just pass gen.quit to the command of a button widget, like so:\nclose = Button(gen, text = 'Close', command = gen.quit).pack()\n\n", "You can use sys.exit() to close the program.\nclose(gen, text=\"Close\", command = lambda: sys.exit()).pack()\n\n" ]
[ 0, 0 ]
[]
[]
[ "button", "python", "tkinter" ]
stackoverflow_0039767084_button_python_tkinter.txt
Q: Is there any feasible solution to read WOT battle results .dat files? I am new here to try to solve one of my interesting questions in World of Tanks. I heard that every battle data is reserved in the client's disk in the Wargaming.net folder because I want to make a batch of data analysis for our clan's battle pe...
Is there any feasible solution to read WOT battle results .dat files?
I am new here to try to solve one of my interesting questions in World of Tanks. I heard that every battle data is reserved in the client's disk in the Wargaming.net folder because I want to make a batch of data analysis for our clan's battle performances. image It is said that these .dat files are a kind of json fil...
[ "Here's how you can parse some parts of it.\nimport pickle\nimport zlib\n\nfile = '4402905758116487.dat'\ncache_file = open(file, 'rb') # This can be improved to not keep the file opened.\n\n# Converting pickle items from python2 to python3 you need to use the \"bytes\" encoding or \"latin1\". \nlegacyBattleResultV...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0071003839_python.txt
Q: How to concatenate dataframes considering column orders I want to combine two dataframes: df1=pd.DataFrame({'A':['a','a',],'B':['b','b']}) df2=pd.DataFrame({'B':['b','b'],'A':['a','a']}) pd.concat([df1,df2],ignore_index=True) result: But I want the output to be like this (I want the same code as SQL's union/unio...
How to concatenate dataframes considering column orders
I want to combine two dataframes: df1=pd.DataFrame({'A':['a','a',],'B':['b','b']}) df2=pd.DataFrame({'B':['b','b'],'A':['a','a']}) pd.concat([df1,df2],ignore_index=True) result: But I want the output to be like this (I want the same code as SQL's union/union all):
[ "Another way is to use numpy to stack the two dataframes and then use pd.DataFrame constructor:\npd.DataFrame(np.vstack([df1.values,df2.values]), columns = df1.columns)\n\nOutput:\n A B\n0 a b\n1 a b\n2 b a\n3 b a\n\n", "Here is a proposition to do an SQL UNION ALL with pandas by using pandas.concat :\...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074677671_pandas_python.txt
Q: What does it really mean real time object detection? So here is the context. I created an script in python, YOLOv4, OpenCV, CUDA and CUDNN, for object detection and object tracking to count the objects in a video. I intend to use it in real time, but what real time really means? The video I'm using is 1min long an...
What does it really mean real time object detection?
So here is the context. I created an script in python, YOLOv4, OpenCV, CUDA and CUDNN, for object detection and object tracking to count the objects in a video. I intend to use it in real time, but what real time really means? The video I'm using is 1min long and 60FPS originally, but the video after processing is 30FP...
[ "First, learn what \"real-time\" means. Wikipedia: https://en.wikipedia.org/wiki/Real-time_computing\nUnderstand the terms \"hard\" and \"soft\" real-time. Understand which aspects of your environment are soft and which require hard real-time.\nUnderstand the response times that your environment requires. Understan...
[ 1, 0 ]
[]
[]
[ "computer_vision", "object_detection", "object_tracking", "python", "real_time" ]
stackoverflow_0074677722_computer_vision_object_detection_object_tracking_python_real_time.txt
Q: UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c I have a socket server that is supposed to receive UTF-8 valid characters from clients. The problem is some clients (mainly hackers) are sending all the wrong kind of data over it. I can easily distinguish the genuine client, but I am logging to files all the...
UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c
I have a socket server that is supposed to receive UTF-8 valid characters from clients. The problem is some clients (mainly hackers) are sending all the wrong kind of data over it. I can easily distinguish the genuine client, but I am logging to files all the data sent so I can analyze it later. Sometimes I get charact...
[ "http://docs.python.org/howto/unicode.html#the-unicode-type\nstr = unicode(str, errors='replace')\n\nor\nstr = unicode(str, errors='ignore')\n\nNote: This will strip out (ignore) the characters in question returning the string without them.\nFor me this is ideal case since I'm using it as protection against non-ASC...
[ 420, 132, 76, 38, 37, 30, 18, 3, 2, 1, 0 ]
[ "\ndjango-storage is implicitly supported read byte file in text mode till django-storage == 1.8\nRemoved support in https://github.com/jschneier/django-storages/pull/657\nNeed to specify the binary mode for reading byte files.\n\n" ]
[ -1 ]
[ "linux", "python", "python_unicode" ]
stackoverflow_0012468179_linux_python_python_unicode.txt
Q: python formulas returning 0s so I have basic formulas setup to recive numbers and then covert them but when running the program the converted formulas aren't calculating dollars = 0 pounds = 0 tempF = 0 tempC = 0 globe = "\U0001F30D" euros = dollars*.95 kilograms = pounds/2.2 tempF = tempC* 9/5+32 print ("How m...
python formulas returning 0s
so I have basic formulas setup to recive numbers and then covert them but when running the program the converted formulas aren't calculating dollars = 0 pounds = 0 tempF = 0 tempC = 0 globe = "\U0001F30D" euros = dollars*.95 kilograms = pounds/2.2 tempF = tempC* 9/5+32 print ("How many U.S dollars can you afford t...
[ "Try calculating the results after you input the data, not before that\n", "How I would do it\ndef get_input():\n print (\"How many U.S dollars can you afford to spend on your trip?: \")\n dollars = float(input())\n\n print(\"How many pounds of chocoloate will you be buying?:\")\n pounds = float(input...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074679904_python_python_3.x.txt
Q: Getting "Failed to convert a NumPy array to a Tensor (Unsupported object type list)." From the whole week I'm training my AI model but it is facing some this issue of Failed to convert Numpy array to a tensor my I'm using the dataset I created for this model containing 100k+ movie plots but again and again its sho...
Getting "Failed to convert a NumPy array to a Tensor (Unsupported object type list)."
From the whole week I'm training my AI model but it is facing some this issue of Failed to convert Numpy array to a tensor my I'm using the dataset I created for this model containing 100k+ movie plots but again and again its showing the same issue when I call "model.fit(...)" Error This is the code I'm using # Importi...
[ "there are many possible ways one of them is to create as a dataset as your error message indicated a mismatched datatype for model.fit()\nSample: Transform input word by vocab and match their string bytes, or tokenize them.\nimport tensorflow as tf\nimport tensorflow_text as tft\n\nimport json\n\ninput_word = tf.c...
[ 0 ]
[]
[]
[ "artificial_intelligence", "deep_learning", "neural_network", "python", "tensorflow" ]
stackoverflow_0074677664_artificial_intelligence_deep_learning_neural_network_python_tensorflow.txt
Q: Neural Networks Extending Learning Domain I have a simple function f : R->R, f(x) = x2 + a, and would like to create a neural network to learn that function, as entirely as it can. Currently, I have a pytorch implementation that takes in inputs of a limited range of course, from x0 to xN with a particular number o...
Neural Networks Extending Learning Domain
I have a simple function f : R->R, f(x) = x2 + a, and would like to create a neural network to learn that function, as entirely as it can. Currently, I have a pytorch implementation that takes in inputs of a limited range of course, from x0 to xN with a particular number of points. Each epoch, the training data is rand...
[ "What you want is called extrapolation (as opposed to interpolation which is predicting a value that is inside the trained domain / range). There is never a good solution for extrapolation and using higher powers can give you a better fit for a specific problem, but if you change the fitted curve slightly (either c...
[ 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074679929_python_pytorch.txt
Q: TypeError: 'list' object is not callable, on a function I am struggling to understand why is python throwing this error, to a function: Traceback (most recent call last): File "/home/arksdf/Repos/alura/Iesb_DeepLearning/tentativas/teste.py", line 40, in <module> model, train_loss, valid_loss = r.classificaca...
TypeError: 'list' object is not callable, on a function
I am struggling to understand why is python throwing this error, to a function: Traceback (most recent call last): File "/home/arksdf/Repos/alura/Iesb_DeepLearning/tentativas/teste.py", line 40, in <module> model, train_loss, valid_loss = r.classificacao(optimizer, criterion) File "/home/arksdf/Repos/alura/Iesb...
[ "As @Michael Butcher answered there was a variable with the same name as my function, train, renaming the function fixed the issue.\n" ]
[ 1 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0074679583_function_list_python.txt
Q: Align a 3D line A to the line B I want to align a line A (blue), which is defined with a 3D start (S) and 3D end point (E) to the other 3D line B (red), so that the line A (does not matter, how it is originally positioned) is parallel to the line B, as shown in Fig.B I know that I have to calculate the angle betw...
Align a 3D line A to the line B
I want to align a line A (blue), which is defined with a 3D start (S) and 3D end point (E) to the other 3D line B (red), so that the line A (does not matter, how it is originally positioned) is parallel to the line B, as shown in Fig.B I know that I have to calculate the angle between two them for that I do: def calcA...
[ "Ok, here's a working answer. Note that if A and B have the same lengths, part of the code is unnecessary (but I'll leave it anyway to make it more portable):\nimport numpy as np\n\ndef makeAparalleltoB(pointSA, pointEA, pointSB, pointEB):\n# pointSA... are np.arrays of the 3 coordinates\n\n # Calculating the co...
[ 1 ]
[]
[]
[ "math", "numpy", "python" ]
stackoverflow_0074679790_math_numpy_python.txt
Q: BGR to RGB for CUB_200 images by Image.split() I am creating a PyTorch dataset and dataloader from CUB_200. When reading the images as pill, I need to change the BGR channels to RGB and I use the following code: def _read_images_from_list(imagefile_list): imgs = [] mean=[0.485, 0.456, 0.406] std= [0.229,...
BGR to RGB for CUB_200 images by Image.split()
I am creating a PyTorch dataset and dataloader from CUB_200. When reading the images as pill, I need to change the BGR channels to RGB and I use the following code: def _read_images_from_list(imagefile_list): imgs = [] mean=[0.485, 0.456, 0.406] std= [0.229, 0.224, 0.225] Transformations = transforms.Comp...
[ "I would strongly recommend you use skimage.io to load your images, not opencv. It opens the images in RGB format by default, removing your shuffling overhead, but if you want to convert BGR to RGB you can use this:\nimport numpy as np\n\nimg = np.arange(27).reshape(3,3,3)\nb = img[:,:,0]\ng = img[:,:,1]\nr = img[:...
[ 1 ]
[]
[]
[ "image", "python", "pytorch", "pytorch_dataloader" ]
stackoverflow_0074679922_image_python_pytorch_pytorch_dataloader.txt
Q: Convert Float to Time I am trying to convert a DataFrame series with floats like "1200" into 12:00:00. My initial DataFrame is this one: import pandas as pd df = pd.DataFrame([1200.0, 0.0, 1536.0, 1530.0, 0.0], columns=['Occurred Time']) print(df) Occurred Time 0 1200.0 1 0.0 2 1536....
Convert Float to Time
I am trying to convert a DataFrame series with floats like "1200" into 12:00:00. My initial DataFrame is this one: import pandas as pd df = pd.DataFrame([1200.0, 0.0, 1536.0, 1530.0, 0.0], columns=['Occurred Time']) print(df) Occurred Time 0 1200.0 1 0.0 2 1536.0 3 1530.0 4 ...
[ "This should work if you convert to strings, pad with zeros and provide a format to to_datetime:\ndf['time'] = pd.to_datetime(df['Occurred Time'].astype(int)\n .astype(str).str.zfill(4),\n format='%H%M')\n\nOutput:\n Occurred Time time\n0 ...
[ 2 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074680074_dataframe_datetime_pandas_python.txt
Q: PyInstaller problem making exe files that using transformers and PyQt5 library So I'm working on an AI project using huggingface library, and I need to convert it into an exe file. I'm using PyQt5 for the interface, and transformers and datasets library from huggingface. I tried using PyInstaller to convert it int...
PyInstaller problem making exe files that using transformers and PyQt5 library
So I'm working on an AI project using huggingface library, and I need to convert it into an exe file. I'm using PyQt5 for the interface, and transformers and datasets library from huggingface. I tried using PyInstaller to convert it into an exe file, it does finish building the exe files of the project, but it gives me...
[ "First, pip install tqdm if you haven't already. Second, specify the path to your Lib/site-packages. You can do this by either:\n\nAdding an argument to pathex in your .spec file\n(.venv for a virtual environment at some folder .venv in your local directory, or the absolute path to your global Python install Lib/si...
[ 1 ]
[ "Hi is this the accepted answer still valid? I have the exact same problem but the solution doesn't work for me.\n" ]
[ -2 ]
[ "huggingface_transformers", "pyqt", "pyside", "python" ]
stackoverflow_0069874436_huggingface_transformers_pyqt_pyside_python.txt
Q: Toastr messages to show without refresh in flask-dash I am using Plotly-Dash in my Flask application to display some graphs. And have Toastr setup in the app to handle notifications. What I want to do, is that upon a dash button click, an event handler runs a function, and upon any error in the function, I flash t...
Toastr messages to show without refresh in flask-dash
I am using Plotly-Dash in my Flask application to display some graphs. And have Toastr setup in the app to handle notifications. What I want to do, is that upon a dash button click, an event handler runs a function, and upon any error in the function, I flash the error, and expect that error to be thrown at me using To...
[ "It sounds like you are trying to use the Flask flash function to show a message to the user in real time, but the message is only being displayed after the page is refreshed.\nThe reason this is happening is that the Flask flash function stores messages in the user's session, and those messages are only displayed ...
[ 0 ]
[]
[]
[ "flask", "notifications", "plotly_dash", "python", "toastr" ]
stackoverflow_0074666045_flask_notifications_plotly_dash_python_toastr.txt
Q: How to improve Julia's performance using just in time compilation (JIT) I have been playing with JAX (automatic differentiation library in Python) and Zygote (the automatic differentiation library in Julia) to implement Gauss-Newton minimisation method. I came upon the @jit macro in Jax that runs my Python code in...
How to improve Julia's performance using just in time compilation (JIT)
I have been playing with JAX (automatic differentiation library in Python) and Zygote (the automatic differentiation library in Julia) to implement Gauss-Newton minimisation method. I came upon the @jit macro in Jax that runs my Python code in around 0.6 seconds compared to ~60 seconds for the version that does not use...
[ "Your Julia code doing a number of things that aren't idiomatic and are worsening your performance. This won't be a full overview, but it should give you a good idea to start.\nThe first thing is passing params as a Vector is a bad idea. This means it will have to be heap allocated, and the compiler doesn't know ho...
[ 4, 2 ]
[]
[]
[ "jax", "julia", "optimization", "python" ]
stackoverflow_0074678931_jax_julia_optimization_python.txt
Q: How can "cursor.callproc" of MySQL be replaced in MariaDB? I have found examples how to call stored procedures in MySQL from Python using cursor.callproc. But cursor.callproc seems not to be defined in MariaDB. I am using version 10.3. How can I solve this? A: I am learning how to write stored procedures in Mari...
How can "cursor.callproc" of MySQL be replaced in MariaDB?
I have found examples how to call stored procedures in MySQL from Python using cursor.callproc. But cursor.callproc seems not to be defined in MariaDB. I am using version 10.3. How can I solve this?
[ "I am learning how to write stored procedures in Mariadb. I have done a test procedure which insert data in a Mariadb database. This test works from Mariadb terminal. Trying to follow an example from internet I wrote following simple code:\n import mariadb\n connection = mariadb.connect(host='localhost',\n ...
[ 0 ]
[]
[]
[ "mariadb", "python", "stored_procedures" ]
stackoverflow_0074679068_mariadb_python_stored_procedures.txt
Q: Function can print tokens, but no lemmas I have a function to run occurrence for tokens/lemmas in a sentence. I want to take a sentence, remove all the annoying bits (punctuation, space, stop), count whats left, then divide that number by how many times those tokens appear in the sentence. Token / count. When I ru...
Function can print tokens, but no lemmas
I have a function to run occurrence for tokens/lemmas in a sentence. I want to take a sentence, remove all the annoying bits (punctuation, space, stop), count whats left, then divide that number by how many times those tokens appear in the sentence. Token / count. When I run this function, I can get the user_token to p...
[ "See the following lines:\nuser_lemmas = [token.lemma_ for token in sentence if token_isolation(token)]\nuser_token = [token for token in sentence if token_isolation(token)]\n\nthe user_lemmas is a list of strings (picked up from lemma_ string attribute), the user_token is a list of spacy tokens, i.e., spacy object...
[ 0 ]
[]
[]
[ "nlp", "python" ]
stackoverflow_0074679117_nlp_python.txt
Q: Get row when value is higher than a given row value in Pandas Sorry for the confusing title, I'm trying to figure out something that's a bit hard to explain. I have a dataframe that looks like this (link to csv) time value is_critical 0:00 1 false 0:01 9 true 0:02 2 false 0:03 4 f...
Get row when value is higher than a given row value in Pandas
Sorry for the confusing title, I'm trying to figure out something that's a bit hard to explain. I have a dataframe that looks like this (link to csv) time value is_critical 0:00 1 false 0:01 9 true 0:02 2 false 0:03 4 false 0:04 6 true 0:05 5 false 0:06 1 false ...
[ "It's a bit messy, and not very efficient but here's a solution:\nIn [3]: df[df[\"is_critical\"]].apply(lambda critical_row: df[\"time\"][(df[\"time\"] > critical_row[\"time\"]) & (df[\"value\"] >= critical_row[\"value\"])].min(), axis=1)\nOut[3]:\n1 0:10\n4 0:08\n8 0:10\ndtype: object\n\nWorks by first fi...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074680131_pandas_python.txt
Q: add a clear button to the GUI which clears the output formatted by the user I am trying to clear the output displayed When clicked the CLEAR button should 'clear' or remove any text written in the Entry box and any text displayed on the Label. While attempting this on my own I tried using the delete method and del...
add a clear button to the GUI which clears the output formatted by the user
I am trying to clear the output displayed When clicked the CLEAR button should 'clear' or remove any text written in the Entry box and any text displayed on the Label. While attempting this on my own I tried using the delete method and del both of which did not remove the output when the button is pressed from tkinter ...
[ "To clear the text in the Entry widget, you can use the delete method and specify the indices of the characters that you want to delete. For example, to delete all the text in the Entry widget, you can use the following code:\ndef clear_name_box():\n input_entry.delete(0, 'end')\n\nThis code will delete all the ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074680220_python.txt
Q: Django forms: how to use optional arguments in form class I'm building a Django web-app which has page create and edit functionality. I create the page and edit the pages using 2 arguments: page title and page contents. Since the edit and create code is very similar except that the edit code doesn't let you change...
Django forms: how to use optional arguments in form class
I'm building a Django web-app which has page create and edit functionality. I create the page and edit the pages using 2 arguments: page title and page contents. Since the edit and create code is very similar except that the edit code doesn't let you change the title of the page I want to make some code that can do bot...
[ "You can work with:\nclass CreatePageForm(forms.Form):\n page_name = forms.CharField()\n page_contents = forms.CharField(widget=forms.Textarea())\n\n def __init__(self, *args, disabled=False, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['page_contents'].disabled = disabled\nan...
[ 0, 0 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0074680120_django_forms_python.txt
Q: Problem with pymunk while running in Virtual Studio I tried using the code so I can run a simulation of an object hitting on the ground but it just says draw_polygon ([Vec2d(55.0, -4779353554820.233), Vec2d(55.0, -4779353554810.233), Vec2d(45.0, -4779353554810.233), Vec2d(45.0, -4779353554820.233)], 0.0, SpaceDebu...
Problem with pymunk while running in Virtual Studio
I tried using the code so I can run a simulation of an object hitting on the ground but it just says draw_polygon ([Vec2d(55.0, -4779353554820.233), Vec2d(55.0, -4779353554810.233), Vec2d(45.0, -4779353554810.233), Vec2d(45.0, -4779353554820.233)], 0.0, SpaceDebugColor(r=44.0, g=62.0, b=80.0, a=255.0), SpaceDebugColor(...
[ "Yes, by default the debug drawing will just print out the result (its made in this way so that you can use it without installing anything else and even run it from the terminal).\nHowever, it also comes with a module for the two libraries pygame and pyglet that are documented here:\nhttp://www.pymunk.org/en/latest...
[ 0 ]
[]
[]
[ "pymunk", "python" ]
stackoverflow_0074670356_pymunk_python.txt
Q: How can I make a dictionary (dict) from separate lists of keys and values? I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'} A: Like this: keys = ['a', 'b', 'c'] values = [1, 2, 3] dictionary = dict(zip(k...
How can I make a dictionary (dict) from separate lists of keys and values?
I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}
[ "Like this:\nkeys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\ndictionary = dict(zip(keys, values))\nprint(dictionary) # {'a': 1, 'b': 2, 'c': 3}\n\nVoila :-) The pairwise dict constructor and zip function are awesomely useful.\n", "\nImagine that you have:\nkeys = ('name', 'age', 'food')\nvalues = ('Monty', 42, 'spam...
[ 2791, 220, 134, 40, 31, 19, 15, 11, 10, 3, 3, 2, 2, 1, 1, 0, 0, 0, 0 ]
[ "method without zip function\nl1 = [1,2,3,4,5]\nl2 = ['a','b','c','d','e']\nd1 = {}\nfor l1_ in l1:\n for l2_ in l2:\n d1[l1_] = l2_\n l2.remove(l2_)\n break \n\nprint (d1)\n\n\n{1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}\n\n", "Although there are multiple ways of doing this but i think most...
[ -1, -1 ]
[ "dictionary", "list", "python" ]
stackoverflow_0000209840_dictionary_list_python.txt
Q: modify fasta file with a function using biopython I should do this command for thounsands of fasta file, so I'm wondering if there is a function to accelerate the process from Bio import SeqIO new= open("new.fasta", "w") for rec in SeqIO.parse("old.fasta","fasta"): print(rec.id) print(rec.seq.reverse_...
modify fasta file with a function using biopython
I should do this command for thounsands of fasta file, so I'm wondering if there is a function to accelerate the process from Bio import SeqIO new= open("new.fasta", "w") for rec in SeqIO.parse("old.fasta","fasta"): print(rec.id) print(rec.seq.reverse_complement()) new.write(">rc_"+rec.id+"\n") new...
[ "I rewrote you code into a function that can be called using each filename you have, possibly collected into a list using os.listdir().\nfrom Bio import SeqIO\n\ndef parse_file(filename):\n new_name = f\"rc_{filename}\"\n with open(new_name, \"w\") as new:\n for rec in SeqIO.parse(filename, \"fasta\"):...
[ 0 ]
[]
[]
[ "biopython", "python" ]
stackoverflow_0074671147_biopython_python.txt
Q: How do I store a variable in a function so I can access it from a different file I am trying to make a program that allows you to select a day, and then store a value for the day with a separate file. However, I can't find a way to store the selected day in a variable that I can use. from tkinter import * from tkc...
How do I store a variable in a function so I can access it from a different file
I am trying to make a program that allows you to select a day, and then store a value for the day with a separate file. However, I can't find a way to store the selected day in a variable that I can use. from tkinter import * from tkcalendar import * main = Tk() main.title('Calendar') main.geometry('600x400') cal = C...
[ "I can't tell exactly what you want because of how you worded it, but I'm pretty sure this is what you want\ndef set_date():\n my_label.config(text=cal.get_date())\n today = cal.get_date()\n return today\n\nIf you then import this function in another file and call it like this\nselected_date = set_date()\n...
[ 1 ]
[ "a = 5\n\ndef set_a(val):\n global a\n a = val\n \nprint(a)\nset_a(0)\nprint(a)\n\nWhat you are doing is a very bad practice (you can use the global keyword before your variable to update it, but never do this). Instead either store it in a mutable data object for example a dictionary or as a pickle file(d...
[ -2 ]
[ "python", "tkcalendar", "tkinter" ]
stackoverflow_0074680264_python_tkcalendar_tkinter.txt
Q: Pythonic way of checking if a condition holds for any element of a list I have a list in Python, and I want to check if any elements are negative. Is there a simple function or syntax I can use to apply the "is negative" check to all the elements, and see if any of them is negative? I looked through the documentat...
Pythonic way of checking if a condition holds for any element of a list
I have a list in Python, and I want to check if any elements are negative. Is there a simple function or syntax I can use to apply the "is negative" check to all the elements, and see if any of them is negative? I looked through the documentation and couldn't find anything similar. The best I could come up with was: i...
[ "any():\nif any(t < 0 for t in x):\n # do something\n\nAlso, if you're going to use \"True in ...\", make it a generator expression so it doesn't take O(n) memory:\nif True in (t < 0 for t in x):\n\n", "Use any().\nif any(t < 0 for t in x):\n # do something\n\n", "Python has a built in any() function for ...
[ 246, 37, 11 ]
[ "a=x.copy()\na.sort()\nif a[0]<0:\n # do something\n\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0001342601_list_python.txt
Q: Instapy problem,why doesnt the code work? from instapy import InstaPy from instapy import smart_run import time my_username = '_georgekazaras' my_password = 'mypassword' def job(): session = InstaPy(username=my_username, password=my_password) with smart_run(session): sessio...
Instapy problem,why doesnt the code work?
from instapy import InstaPy from instapy import smart_run import time my_username = '_georgekazaras' my_password = 'mypassword' def job(): session = InstaPy(username=my_username, password=my_password) with smart_run(session): session.set_relationship_bounds(enabled=True, ...
[ "You have a typo in set_do_follow(percentage not precentage)\n" ]
[ 0 ]
[]
[]
[ "function", "instagram", "instapy", "module", "python" ]
stackoverflow_0074680374_function_instagram_instapy_module_python.txt
Q: How to scale QImage to a small size with good quality I have eight different videos. And I am trying to show these videos in a split window. My video quality is 720p. But I need to fit in small frame. When I resize the video with p = convert_to_Qt_format.scaled(256, 450, Qt.KeepAspectRatio) as a 256x450 I couldn't...
How to scale QImage to a small size with good quality
I have eight different videos. And I am trying to show these videos in a split window. My video quality is 720p. But I need to fit in small frame. When I resize the video with p = convert_to_Qt_format.scaled(256, 450, Qt.KeepAspectRatio) as a 256x450 I couldn't get good quality of video. How can I resize as a good qual...
[ "Note that QImage::scaled() has an optional parameter transformMode that defaults to Qt::FastTransformation. If you pass Qt::SmoothTransformation the results should be better, because bilinear filtering is used.\n" ]
[ 0 ]
[]
[]
[ "pyqt5", "python", "qimage", "qt", "video_processing" ]
stackoverflow_0074679910_pyqt5_python_qimage_qt_video_processing.txt
Q: How to match group of lines between two matches? So, I have a result of a tool that goes like this: >Cluster 1 0 1967nt, >001126F:363892-365859... * 1 1676nt, >Aag2_family_100_all/000015F:2300484-2302160... at -/100.00% 2 1544nt, >Aag2_family_100_all/000453F:1675071-1676615... at +/100.00% 3 1208nt, >Aag2_...
How to match group of lines between two matches?
So, I have a result of a tool that goes like this: >Cluster 1 0 1967nt, >001126F:363892-365859... * 1 1676nt, >Aag2_family_100_all/000015F:2300484-2302160... at -/100.00% 2 1544nt, >Aag2_family_100_all/000453F:1675071-1676615... at +/100.00% 3 1208nt, >Aag2_family_100_all/000453F:1675260-1676468... at +/100.00%...
[ "I think you missed .read() for cluster.\n" ]
[ 0 ]
[]
[]
[ "python", "python_re" ]
stackoverflow_0074680389_python_python_re.txt
Q: Obtaining data from both token and word objects in a Stanza Document / Sentence I am using a Stanford STANZA pipeline on some (italian) text. Problem I'm grappling with is that I need data from BOTH the Token and Word objects. While I'm able to access one or the other separately I'm not wrapping my head on how to ...
Obtaining data from both token and word objects in a Stanza Document / Sentence
I am using a Stanford STANZA pipeline on some (italian) text. Problem I'm grappling with is that I need data from BOTH the Token and Word objects. While I'm able to access one or the other separately I'm not wrapping my head on how to get data from both in a single loop over the Document -> Sentence Specifically I need...
[ "To access data from both the Word and Token objects in a single loop, you can simply loop through the Sentence objects in the document, and then within each sentence loop through the Word objects. For each Word object, you can access its associated Token object through the .token attribute. Here is an example of h...
[ 0, 0 ]
[]
[]
[ "nlp", "python", "stanford_nlp" ]
stackoverflow_0074668152_nlp_python_stanford_nlp.txt
Q: Python Add 2 Lists (Arrays) in Python How can i add 2 numbers in a List. I am trying to add 2 numbers in an array, it just shows None on the response box. The code is looking thus : def add2NumberArrays(a,b): res = [] for i in range(0,len(a)): return res.append(a[i] + b[i]) a = [4,4,7] b = [2,1,2]...
Python Add 2 Lists (Arrays) in Python
How can i add 2 numbers in a List. I am trying to add 2 numbers in an array, it just shows None on the response box. The code is looking thus : def add2NumberArrays(a,b): res = [] for i in range(0,len(a)): return res.append(a[i] + b[i]) a = [4,4,7] b = [2,1,2] print(add2NumberArrays(a,b)) Why does t...
[ "You can use itertools.zip_longest to handle different length of two lists.\nfrom itertools import zip_longest\ndef add2NumberArrays(a,b):\n # Explanation: \n # list(zip_longest(a, b, fillvalue=0))\n # [(4, 2), (4, 1), (7, 2), (0, 2)]\n return [i+j for i,j in zip_longest(a, b, fillvalue=0)]\n \n\na =...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074680339_python.txt
Q: Stop urllib.request from raising exceptions on HTTP errors Python's urllib.request.urlopen() will raise an exception if the HTTP status code of the request is not OK (e.g., 404). This is because the default opener uses the HTTPDefaultErrorHandler class: A class which defines a default handler for HTTP error respo...
Stop urllib.request from raising exceptions on HTTP errors
Python's urllib.request.urlopen() will raise an exception if the HTTP status code of the request is not OK (e.g., 404). This is because the default opener uses the HTTPDefaultErrorHandler class: A class which defines a default handler for HTTP error responses; all responses are turned into HTTPError exceptions. Even ...
[]
[]
[ "I'll be very clear, I'm answering this question to test GPT. That's not my answer, I don't know the anwser. But I asked GPT.\nIf this offends anyone, feel free to delete my message.\n\nTo disable the automatic raising of exceptions for non-OK HTTP status codes, you can create your own HTTPErrorProcessor class that...
[ -2 ]
[ "python", "urllib" ]
stackoverflow_0074680393_python_urllib.txt
Q: python keyboard - how to deal with multiple keys? Im trying to do a simple bot with using python keyboard lib. i can send key presses with keyobard.send however if player presses and holds w for movement keyboard.send is not working. What should i do? A: If you want to simulate a key press and hold using the key...
python keyboard - how to deal with multiple keys?
Im trying to do a simple bot with using python keyboard lib. i can send key presses with keyobard.send however if player presses and holds w for movement keyboard.send is not working. What should i do?
[ "If you want to simulate a key press and hold using the keyboard library in Python, you can use the keyboard.press_and_release method instead of the keyboard.send method. This method simulates a press and release of a key, so if you want to simulate holding down a key, you can use a loop to repeatedly call this met...
[ 0 ]
[]
[]
[ "keyboard", "python" ]
stackoverflow_0074680454_keyboard_python.txt
Q: Navigate in JSON with nultiple keys I'm trying to get a key from a JSON from a website using the following code: import json import requests from bs4 import BeautifulSoup url = input('Enter url:') html = requests.get(url) soup = BeautifulSoup(html.text,'html.parser') data = json.loads(soup.find('script', type='a...
Navigate in JSON with nultiple keys
I'm trying to get a key from a JSON from a website using the following code: import json import requests from bs4 import BeautifulSoup url = input('Enter url:') html = requests.get(url) soup = BeautifulSoup(html.text,'html.parser') data = json.loads(soup.find('script', type='application/json').text) print(data) print...
[ "You can access it like this:\ndata[\"props\"][\"XYZ\"][\"ABC\"][0][\"current\"]\n\nWhy? Key current is inside a list of dictionaries. ABC is of type list, and we access the elements using their location in the list (0 in your example).\n", "As the other answers have already explained, you need to add [0] between...
[ 1, 1, 0 ]
[]
[]
[ "beautifulsoup", "json", "python", "python_3.x", "python_requests" ]
stackoverflow_0074678361_beautifulsoup_json_python_python_3.x_python_requests.txt
Q: Conflicts with relationship between tables I've been constantly getting a warning on the console and I'm going crazy from how much I've been reading but I haven't been able to resolve this: SAWarning: relationship 'Book.users' will copy column user.uid to column user_book.uid, which conflicts with relationship(s)...
Conflicts with relationship between tables
I've been constantly getting a warning on the console and I'm going crazy from how much I've been reading but I haven't been able to resolve this: SAWarning: relationship 'Book.users' will copy column user.uid to column user_book.uid, which conflicts with relationship(s): 'User.books' (copies user.uid to user_book.uid...
[ "As the warning message suggests, you are missing the back_populates= attributes in your relationships:\nclass User(db.Model):\n# …\n books = db.relationship('Book', secondary=user_book, back_populates=\"users\")\n# …\n \nclass Book(db.Model):\n# …\n users = db.relationship('User', secondary=user_book, bac...
[ 6, 1 ]
[]
[]
[ "postgresql", "python", "sqlalchemy" ]
stackoverflow_0068322485_postgresql_python_sqlalchemy.txt
Q: Convert a string of characters into a hex variable input I have output as in below Hello I use "list" to separate it to characters MS=list(MS) output: ['H', 'e', 'l', 'l', 'o'] I attempted to make it as input in hex format, as shown below: p = (0x48, 0x65, 0x6c, 0x6c, 0x6f) I tried to use the code below to c...
Convert a string of characters into a hex variable input
I have output as in below Hello I use "list" to separate it to characters MS=list(MS) output: ['H', 'e', 'l', 'l', 'o'] I attempted to make it as input in hex format, as shown below: p = (0x48, 0x65, 0x6c, 0x6c, 0x6f) I tried to use the code below to convert it to hex: p = tuple(hex(x) for x in MS) However, it d...
[ "The hex() function expects an integer, that's the reason why it complains about the str object.\nYou can use help(hex) to obtain the documentation : \"Return the hexadecimal representation of an integer.\"\nIn the loop you can convert each letter to an integer thanks to the ord() function that \"returns the Unicod...
[ 0 ]
[]
[]
[ "hex", "python" ]
stackoverflow_0074679916_hex_python.txt
Q: How to write numbers and strings to csv file in Python I'm new to coding so this may seem a trifle basic ... I'm trying to write three data elements to each record of a csv file. Two of the elements (flow_temp and return_temp) are floating point numbers while the third (flame) is a string ("on" or "off"). Here is ...
How to write numbers and strings to csv file in Python
I'm new to coding so this may seem a trifle basic ... I'm trying to write three data elements to each record of a csv file. Two of the elements (flow_temp and return_temp) are floating point numbers while the third (flame) is a string ("on" or "off"). Here is my write statement: f.write(str(flow_temp)+","+str(return_te...
[]
[]
[ "Try to add str() to flame as well\nf.write(str(flow_temp)+\",\"+str(return_temp)+str(flame)+\"\\n\")\n\nor you could alternativaly write row using csv lib in python\nimport csv\n\n# create a csv.writer object\nwriter = csv.writer(f)\n\n# write the data to the CSV file\nwriter.writerow([flow_temp, return_temp, flam...
[ -1 ]
[ "concatenation", "csv", "python" ]
stackoverflow_0074680497_concatenation_csv_python.txt
Q: lambda function returning a list of None elements does anyone know why the function fill the list with "None"? I can not find the problem, everything looks true. my_lis = [] l = lambda m : [my_lis.append(x) for x in range(m)] l(10) output : [None, None, None, None, None, None, None, None, None, None] if i prin...
lambda function returning a list of None elements
does anyone know why the function fill the list with "None"? I can not find the problem, everything looks true. my_lis = [] l = lambda m : [my_lis.append(x) for x in range(m)] l(10) output : [None, None, None, None, None, None, None, None, None, None] if i print the x instead of append, i get 1 to 10 and the Non...
[ "A simple list comprehension\nlst = [i**2 for i in range(3)]\n\nis interpreted as:\nlst = []\nfor i in range(3):\n lst.append(i**2)\n\nNow back to your example: So your code is currently like this:\nmy_lis = []\n\ndef l(m):\n result = []\n for x in range(m):\n result.append(my_lis.append(x))\n re...
[ 2 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0074680509_lambda_python.txt
Q: robobrowser won't change cookies I have a POST request sent to server from robobrowser, and the server responds with no data. The response headers are as follows (this is the response from Chrome browser and it's the way it supposed to be): Cache-Control:no-cache, no-store, must-revalidate Content-Length:335 Conte...
robobrowser won't change cookies
I have a POST request sent to server from robobrowser, and the server responds with no data. The response headers are as follows (this is the response from Chrome browser and it's the way it supposed to be): Cache-Control:no-cache, no-store, must-revalidate Content-Length:335 Content-Type:application/json; charset=utf-...
[ "You can use the update_state() method and pass in the new cookies that were set in the server response. \nFor example:\nbrowser=RoboBrowser()\nbrowser.session.headers['X-Requested-With']='XMLHttpRequest'\nbrowser.open('https://example.com/test/Users/set-role?id='+role_id+'&__RequestVerificationToken='+token,method...
[ 0 ]
[]
[]
[ "http", "python", "python_2.7", "python_requests", "urllib2" ]
stackoverflow_0045467986_http_python_python_2.7_python_requests_urllib2.txt
Q: How to make Python CUDA atomicAdd to work with long int How can I make Python CUDA atomicAdd works with long int? I tried with the below code, and it does not work as long as I use long *result_count or atomicAdd(&InitianCount,1);, with compilation error such as below. import os _path = r"C:\Program Files\Micr...
How to make Python CUDA atomicAdd to work with long int
How can I make Python CUDA atomicAdd works with long int? I tried with the below code, and it does not work as long as I use long *result_count or atomicAdd(&InitianCount,1);, with compilation error such as below. import os _path = r"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\...
[ "First, on windows, long (or long int) is a (signed) 32-bit (integer) type. So when asking for \"how to use atomics with long\" while at the same time allocating for 64-bit types in your code:\nresult_count = np.zeros(1, dtype=np.int64)\n\nbegs the question are you really asking about how to use atomics with long,...
[ 1 ]
[]
[]
[ "cuda", "python" ]
stackoverflow_0074678342_cuda_python.txt
Q: How to disable Teacher Forcing RNN model I have the following Teacher forcing RNN model where I'm implicitly passing the entire input sequence (inputs = ids[:, i:i+seq_length] to the model at once. What should I modify to disable teacher forcing training and get the original model. ids = corpus.get_data('data/trai...
How to disable Teacher Forcing RNN model
I have the following Teacher forcing RNN model where I'm implicitly passing the entire input sequence (inputs = ids[:, i:i+seq_length] to the model at once. What should I modify to disable teacher forcing training and get the original model. ids = corpus.get_data('data/train.txt', batch_size) model = RNNLM(vocab_size...
[ "To disable teacher forcing in the model, you need to modify the code that generates the input and target sequences. Currently, the input sequence is constructed by taking a contiguous block of seq_length tokens from the ids tensor, starting at position i and ending at position i + seq_length. The target sequence i...
[ 0 ]
[]
[]
[ "python", "recurrent_neural_network" ]
stackoverflow_0074680569_python_recurrent_neural_network.txt
Q: Are Python coroutines stackless or stackful? I've seen conflicting views on whether Python coroutines (I primarily mean async/await) are stackless or stackful. Some sources say they're stackful: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2074r0.pdf 'Python coroutines are stackful.' How do coroutin...
Are Python coroutines stackless or stackful?
I've seen conflicting views on whether Python coroutines (I primarily mean async/await) are stackless or stackful. Some sources say they're stackful: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2074r0.pdf 'Python coroutines are stackful.' How do coroutines in Python compare to those in Lua? Yes, Pytho...
[ "It seems that the sources are using different terminology and definitions for \"stackful\" and \"stackless\" coroutines.\nIn the first source, \"stackful\" means that the coroutine has its own stack, which is separate from the calling function's stack. This allows the coroutine to have its own local variables and ...
[ 0 ]
[]
[]
[ "coroutine", "python", "python_asyncio" ]
stackoverflow_0070339355_coroutine_python_python_asyncio.txt