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:
python: why can't a series's dtype is datetime64[ns] user apply(lambda x:x-x.max())/np.timedelta64(1,'D') but (x-x.max)/np.timedelta64(1,'D')
I have a pd.Series as follows:
I want to calculate difference value between a and a.max and at the same time transfer the difference value format to float. I can use pictur... | python: why can't a series's dtype is datetime64[ns] user apply(lambda x:x-x.max())/np.timedelta64(1,'D') but (x-x.max)/np.timedelta64(1,'D') | I have a pd.Series as follows:
I want to calculate difference value between a and a.max and at the same time transfer the difference value format to float. I can use picture 2 to do what I want, but why does the approach in picture 3 fail?
Picture 2 (correct):
Picture 3 (wrong):
Error message:
| [
"The problem with a.apply(lambda x:x-x.max())/np.timedelta64(1,'D') is that you are trying to get the max from a Timestamp (i.e. x). However, as mentioned in the error message, a \"'Timestamp' object is not callable\". So, in this particular case, it is trying to tell you that a Timestamp, understandably, does not ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074163415_pandas_python.txt |
Q:
How to create multiple columns in Pandas Dataframe?
I have data as you can see in the terminal. I need it to be converted to the Excel sheet format as you can see in the Excel sheet file by creating multi-levels in columns.
I researched this and reached many different things but cannot achieve my goal then, I reac... | How to create multiple columns in Pandas Dataframe? | I have data as you can see in the terminal. I need it to be converted to the Excel sheet format as you can see in the Excel sheet file by creating multi-levels in columns.
I researched this and reached many different things but cannot achieve my goal then, I reached "transpose", and it gave me the shape that I need but... | [
"This can be done with unstack after setting player__number as index. You have to reorder the Multiindex columns and fill missing values/delete duplicates though:\nimport pandas as pd\n\ndata = {\"player__number\": [2, 10 , 2, 10, 2, 10],\n \"cel1\": [0, 2, 0, 1, 0, 1],\n \"cel2\": [0, 5, 0, 1, 0, 2],... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074163768_dataframe_pandas_python.txt |
Q:
Weird behaviors on interactive imshow plot in Python
I'm trying to construct a grid of black squares, and everytime you click on one it turns white. Now for some reason my code does very weird things:
The coordinates I input doesn't correspond to the array coordinates. I tried to change that by letting i = y - (N... | Weird behaviors on interactive imshow plot in Python | I'm trying to construct a grid of black squares, and everytime you click on one it turns white. Now for some reason my code does very weird things:
The coordinates I input doesn't correspond to the array coordinates. I tried to change that by letting i = y - (N-1) and j = x with (x,y) the mouse coordinates. But only t... | [
"Well I found the issues:\n\nIt was N - 1 - int(gy)\nMatplotlib normalizes the values for me when they aren't specified. So a grid of all zeros is the same as a grid of all ones to it (each cell is equal to the mean, in both cases).\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python",
"python_interactive"
] | stackoverflow_0074164661_matplotlib_python_python_interactive.txt |
Q:
Uploading file to Anonfiles using anonfile module and FastAPI
I am currently creating a website where the user sends the file and gets uploaded to anonfile website (I am using anofile python module). Before anonfile module, I was using mediafire module but it didn't work with video files so I moved to anonfile mod... | Uploading file to Anonfiles using anonfile module and FastAPI | I am currently creating a website where the user sends the file and gets uploaded to anonfile website (I am using anofile python module). Before anonfile module, I was using mediafire module but it didn't work with video files so I moved to anonfile modul.
Here is the code:
app.py
from typing import List
import uvicorn... | [
"The package your are using to upload the file doesn't seem to support passing a file-like object (which is the result of calling the .file attribute of the UploadFile object). As can been in the source code here, the upload function instead accepts a path to the file in either str or Path format.\nHence, you can e... | [
1
] | [] | [] | [
"dropzone",
"fastapi",
"python"
] | stackoverflow_0074164831_dropzone_fastapi_python.txt |
Q:
How to toggle onboard LED on Raspberry Pi Pico H and inputting number of time that it blinks?
I am trying to write a program where I input how many times I would like the onboard LED on a Raspberry Pi Pico H to blink, and then the LED blinking that number of times. However, when I run the attached code, I receive ... | How to toggle onboard LED on Raspberry Pi Pico H and inputting number of time that it blinks? | I am trying to write a program where I input how many times I would like the onboard LED on a Raspberry Pi Pico H to blink, and then the LED blinking that number of times. However, when I run the attached code, I receive the following error:
File "<stdin>", line 19, in <module>
TypeError: unsupported types for __lt__... | [
"The problem is that the default type of input() is string ('str') and you can't iterate from 0 to string, so you need to convert your input to integer value by using int(input()). The solution is:\nimport time\n\nnumber = int(input('How many times would you like the LED to blink?'))\n\nfor i in range(0, number):\n... | [
0
] | [] | [] | [
"micropython",
"python",
"raspberry_pi",
"raspberry_pi_pico",
"typeerror"
] | stackoverflow_0074165327_micropython_python_raspberry_pi_raspberry_pi_pico_typeerror.txt |
Q:
How to turn rows into columns grouped?
I have a dataframe:
id1 id2 val type
"a1" "a2" 10 "a"
"a1" "b2" 11 "b"
"a1" "c2" 9 "c"
"k1" "p2" 6 "a"
"k1" "f2" 5 "b"
"k1" "d2" 2 "c"
i want for each unique id1 put each id2 on same row with val and t... | How to turn rows into columns grouped? | I have a dataframe:
id1 id2 val type
"a1" "a2" 10 "a"
"a1" "b2" 11 "b"
"a1" "c2" 9 "c"
"k1" "p2" 6 "a"
"k1" "f2" 5 "b"
"k1" "d2" 2 "c"
i want for each unique id1 put each id2 on same row with val and type. so desired result is:
id1 id2_a v... | [
"# pivot \ndf2=df.pivot(index=['id1'], columns='type')\n\n# sort on second level, to obtained the intended sequence\ndf2=df2.sort_index(axis=1, level=1)\n\n# merge column index level, while stripping off the quotes\ndf2.columns=[col[0]+\"_\"+col[1].lstrip('\"\"').rstrip('\"\"') for col in df2]\n\n# remove the axis ... | [
0
] | [] | [] | [
"dataframe",
"function",
"python",
"python_3.x"
] | stackoverflow_0074165250_dataframe_function_python_python_3.x.txt |
Q:
Filter DataFrame rows by multiple columns and add them together
So I have a dataframe structured like:
Date Metric Value
2020-01-01 Low 34.5
2020-01-01 High 36.5
2020-01-01 Open 23.5
2020-01-02 Low 32.5
...
I am trying to create another frame, where for every date there is a new 'Volume'... | Filter DataFrame rows by multiple columns and add them together | So I have a dataframe structured like:
Date Metric Value
2020-01-01 Low 34.5
2020-01-01 High 36.5
2020-01-01 Open 23.5
2020-01-02 Low 32.5
...
I am trying to create another frame, where for every date there is a new 'Volume' column which is the High-low for that specific date. The frame is no... | [
"One approach could be as follows:\n\nFirst, select only from df the rows which have High and Low in column Metric using Series.isin.\nNext, use df.pivot to reshape the df and assign a new column Volume, containing the result of values in column Low subtracted from those in column High (see: Series.sub).\nFinally, ... | [
1,
0
] | [] | [] | [
"dataframe",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074164546_dataframe_matplotlib_pandas_python.txt |
Q:
How would I fix error "AttributeError: 'Window' object has no attribute 'submit_button'"
I keep getting an error for checking the text of a button. Error is "AttributeError: 'Window' object has no attribute 'submit_button'". I tried to add it elsewhere however still Code:
def creation(self):
if self.s... | How would I fix error "AttributeError: 'Window' object has no attribute 'submit_button'" | I keep getting an error for checking the text of a button. Error is "AttributeError: 'Window' object has no attribute 'submit_button'". I tried to add it elsewhere however still Code:
def creation(self):
if self.submit_button['text'] != "Create a file":
time.sleep(3)
self.submit_but... | [
"You need to define the attribute before you use it. The very first line of code in your function uses self.submit_button, but you don't define self.submit_button until several lines later.\n"
] | [
0
] | [] | [] | [
"class",
"python",
"tkinter"
] | stackoverflow_0074164976_class_python_tkinter.txt |
Q:
"None" keeps popping up in my output of a calculator program
Problem showcase
I've just started to code in python and coded a calculator (its unfinished atm) it works fine except for the fact that "none" keeps popping up in the output. Here is my code.
num1 = float(input(print("Enter the first value ")))
num2 = f... | "None" keeps popping up in my output of a calculator program | Problem showcase
I've just started to code in python and coded a calculator (its unfinished atm) it works fine except for the fact that "none" keeps popping up in the output. Here is my code.
num1 = float(input(print("Enter the first value ")))
num2 = float(input(print("Enter the second value ")))
operator = input("En... | [
"You code should look like this:\nnum1 = float(input(\"Enter the first value \")) \nnum2 = float(input(\"Enter the second value \"))\noperator = input(\"Enter the operator you want to calculate with;+,-,* \")\nsumm = num1+num2\nproduct = num1*num2\ndifference = num1-num2\nif operator == \"+\":\n print(summ)\neli... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074164854_python.txt |
Q:
use of attributes in python
This is kind of a high level question. I'm not sure what you'd do with code like this:
class Object(object):
pass
obj = Object
obj.a = lambda: None
obj.d = lambda: dict
setattr(obj.d, 'dictionary', {4,3,5})
setattr(obj.a, 'somefield', 'somevalue')
If I'm going to call obj.a.somefi... | use of attributes in python | This is kind of a high level question. I'm not sure what you'd do with code like this:
class Object(object):
pass
obj = Object
obj.a = lambda: None
obj.d = lambda: dict
setattr(obj.d, 'dictionary', {4,3,5})
setattr(obj.a, 'somefield', 'somevalue')
If I'm going to call obj.a.somefield, why would I use print? It fe... | [
"First about your print question. Print is used more for debugging or for attributes that are an output from an object that gives you information when you create it.\nFor example, there might be an object that you create by passing it data and it finds all of the basic statistics information of that data. You could... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074165324_python_python_3.x.txt |
Q:
Roman to Integer, return -1 if the input roman numeral is invalid? (Non-regex check)
So I have this code here that returns the matching integer to the input Roman Numeral, and uses regex to check for validity of the input, if it's an invalid Roman Numeral like "VVIV" or "IIII", returns -1.
def ValidationOfRomanNum... | Roman to Integer, return -1 if the input roman numeral is invalid? (Non-regex check) | So I have this code here that returns the matching integer to the input Roman Numeral, and uses regex to check for validity of the input, if it's an invalid Roman Numeral like "VVIV" or "IIII", returns -1.
def ValidationOfRomanNumerals(string):
import re
boolean = bool(re.search(r"^M{0,3}(CM|CD|D?C{0,3}... | [
"If you don't want a regex to check you can use a simple if condition to check if it's valid or not.\nLike this:\nif s[i] not in roman or i + 1 < len(s) and s[i+1] not in roman:\n return -1\n\nIt will return -1 if the character is not among of roman keys defined above.\nComplete Code:\ndef romanToInt(s):\nro... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074165210_python_python_3.x.txt |
Q:
Pass value from function to another one without overwriting it
I have an image, I'm trying to let the user chose the proper rgb values for its desired function. So the user is allowed to click on the image in the desired area and than he presses a button to save that clicked value.
I have the following code where ... | Pass value from function to another one without overwriting it | I have an image, I'm trying to let the user chose the proper rgb values for its desired function. So the user is allowed to click on the image in the desired area and than he presses a button to save that clicked value.
I have the following code where the function click gets the color value and stores it in an array, a... | [
"I did not get exactly what you are trying to do. And what \"pass value without overwriting\" means.\nBut I suspect that your real problem is here:\nselected_color = np.empty([0,3]) #color to be passed to the button\ndef click(event):\n # yada yada yada...\n selected_color = [r,g,b] #saving the clicked color\... | [
1
] | [] | [] | [
"arrays",
"bind",
"python",
"tkinter"
] | stackoverflow_0074165168_arrays_bind_python_tkinter.txt |
Q:
TypeError: expected token to be a str, received instead
I'm wanting to make a simple discord bot. What it does isn't too important other than the fact that I want it to send messages at certain times. The code below is very basic and is not the finished product.
# bot.py
import os
import discord
from dotenv impo... | TypeError: expected token to be a str, received instead | I'm wanting to make a simple discord bot. What it does isn't too important other than the fact that I want it to send messages at certain times. The code below is very basic and is not the finished product.
# bot.py
import os
import discord
from dotenv import load_dotenv
intents = discord.Intents().all()
intents.mess... | [
"While having the full traceback would be useful in general, the error\n\nTypeError: expected token to be a str, received <class 'NoneType'> instead\n\nhints that the token passed in is None, not a string.\nYour code\nload_dotenv()\nTOKEN = os.getenv(\"FAKETOKENBLAHBLAHBLAH\")\n\ntries to load a .env file (to load ... | [
1,
1,
0
] | [] | [] | [
"bots",
"discord.py",
"python"
] | stackoverflow_0073440592_bots_discord.py_python.txt |
Q:
Prophet model in scikit-hts package is not working
I'm exploring hierarchal forecasting for time series in python and came across scikit-hts library. I installed the package using pip install scikit-hts. I followed the steps mentioned in this tutorial. I created the hierarchal tree and came to the modelling part. ... | Prophet model in scikit-hts package is not working | I'm exploring hierarchal forecasting for time series in python and came across scikit-hts library. I installed the package using pip install scikit-hts. I followed the steps mentioned in this tutorial. I created the hierarchal tree and came to the modelling part. I want to predict bottom level forecast using Facebook p... | [
"I've just tried with the same parameters. It worked without any errors. May be they've fixed this issue in the later versions of 0.5.4. Try checking the same once after upgrading your package. If you haven't done that so far.\n",
"In Jupyter, you need to escape the brackets like this to install the dependencies\... | [
1,
0
] | [] | [] | [
"forecasting",
"machine_learning",
"python",
"scikit_learn",
"time_series"
] | stackoverflow_0067096136_forecasting_machine_learning_python_scikit_learn_time_series.txt |
Q:
content from multiple txt files into single excel file with separate sheets using python
this question is similar to content from multiple txt files into single excel file using python.
Can i have those data in separate sheets instead of one sheet ?
If I have for example 3 txt files that looks as follows:
file1.tx... | content from multiple txt files into single excel file with separate sheets using python | this question is similar to content from multiple txt files into single excel file using python.
Can i have those data in separate sheets instead of one sheet ?
If I have for example 3 txt files that looks as follows:
file1.txt:
a 10
b 20
c 30
file2.txt:
d 40
e 50
f 60
file3.txt:
g 70
h 80
i 90
i would like to have ... | [
"The logic is slightly different than my other answer, but the basics are the same. Biggest change is loading the files inside a loop, and naming the sheets...\nrequirements.txt\npandas\nopenpyxl\n\ncode\n# we use pandas for easy saving as XSLX\nimport pandas as pd\n\n\nfilelist = [\"file01.txt\", \"file02.txt\", \... | [
0
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0074165167_openpyxl_python.txt |
Q:
[Python], How to calculate 'service response time' per conversation id
I would like to calculate the average 'service response time' per conversation id as a variable in a dataframe (in minutes).
The 'service response time' is calculated by the difference between the 'created_at' variable from Y and X in minutes:
... | [Python], How to calculate 'service response time' per conversation id | I would like to calculate the average 'service response time' per conversation id as a variable in a dataframe (in minutes).
The 'service response time' is calculated by the difference between the 'created_at' variable from Y and X in minutes:
X = the first row where owner_type == "User" and is_interaction == 1.
Y = th... | [
"Update 04.11.2022\nIf you had a unique ID for each event, then it would be easier. And more: 'X = the first row where owner_type == \"User\" and is_interaction == 1.' This is not the first row at all, but the last one before 'Y = the first row after X where owner_type == \"Agent\" and owner_id != 1'.\nI offer two ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074144179_pandas_python.txt |
Q:
I am trying to write a function which takes in a string as a parameter, and changes the case of each letter at every odd index in the string
It should leave all punctuation and numbers unchanged.
This is what I have written so far:
def mock(string):
s = ""
index = 0
for character in string:
if ... | I am trying to write a function which takes in a string as a parameter, and changes the case of each letter at every odd index in the string | It should leave all punctuation and numbers unchanged.
This is what I have written so far:
def mock(string):
s = ""
index = 0
for character in string:
if index % 2 == 0:
if character.islower():
s += character.upper()
index += 1
elif character.i... | [
"You can use swapcase and join:\ndef mock(s):\n return ''.join(x if i % 2 else x.swapcase() for i, x in enumerate(s))\n\nprint(mock(\"Abcd. Efgh.. Ijkl!\")) # abCd. efGh.. IJkL!\n\nTo (minimally) correct your code, try:\ndef mock(string):\n s = \"\"\n index = 0\n for character in string:\n if ind... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074165432_python.txt |
Q:
How can I loop through an XML file and parse tag content if each Sibling tag has different child tags?
Is there a loop that will iterate through the siblings elements, if it gets to one of the studentscreening(see below) and that student does not have the tag being used, then input null/na ??
Below is what is in m... | How can I loop through an XML file and parse tag content if each Sibling tag has different child tags? | Is there a loop that will iterate through the siblings elements, if it gets to one of the studentscreening(see below) and that student does not have the tag being used, then input null/na ??
Below is what is in my xml file [studentinfo.xml]:
<?xml version="1.0" encoding="UTF-8"?>
<StudentBreakdown>
<Studentdata>
<S... | [
"While using pandas simply use its pandas.read_xml():\npd.read_xml(xml, xpath='.//StudentScreening')\n\nExample\nimport pandas as pd\n\nxml = '''\n<StudentBreakdown>\n<Studentdata>\n <StudentScreening>\n <name>Sam Davies</name>\n <age>15</age>\n <hair>Black</hair>\n <eyes>Blue</eyes>\... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"pandas",
"parsing",
"python",
"xml"
] | stackoverflow_0074165015_beautifulsoup_pandas_parsing_python_xml.txt |
Q:
How to prevent random function printing the same row more than once from xslx file in python
So I'm a python beginner and don't really know the gist of random functions. The following is my code (but only partially so it may not make sense but it has the point of what I wanted to ask. I put the conclusion of my co... | How to prevent random function printing the same row more than once from xslx file in python | So I'm a python beginner and don't really know the gist of random functions. The following is my code (but only partially so it may not make sense but it has the point of what I wanted to ask. I put the conclusion of my code on the beginning of the paragraph after the code though. P.S. the code works):
if (1 <= numb_qu... | [
"So random just generates a number in that range you want. Computers don't generate numbers totally randomly. They use a \"seed\" to get started. If you pass the library the same seed each time (set it via random.seed(seedNo)), it will generate the same numbers in the same order. This can be useful for testing but ... | [
1
] | [] | [] | [
"openpyxl",
"python",
"random"
] | stackoverflow_0074165368_openpyxl_python_random.txt |
Q:
How to open huge parquet file using Pandas without enough RAM
I am trying to read a decently large Parquet file (~2 GB with about ~30 million rows) into my Jupyter Notebook (in Python 3) using the Pandas read_parquet function. I have also installed the pyarrow and fastparquet libraries which the read_parquet funct... | How to open huge parquet file using Pandas without enough RAM | I am trying to read a decently large Parquet file (~2 GB with about ~30 million rows) into my Jupyter Notebook (in Python 3) using the Pandas read_parquet function. I have also installed the pyarrow and fastparquet libraries which the read_parquet function uses as the engine for parquet files. Unfortunately, it seems t... | [
"Do you need all the columns? You might be able to save memory by just loading the ones you actually use. \nA second possibility is to use an online machine (like google colab) to load the parquet file and then save it as hdf. Once you have it, you can use it in chunks.\n",
"You can use Dask instead of pandas. It... | [
3,
2,
0
] | [] | [] | [
"fastparquet",
"pandas",
"parquet",
"pyarrow",
"python"
] | stackoverflow_0060161821_fastparquet_pandas_parquet_pyarrow_python.txt |
Q:
How to access an object while looping python
Hey I am scraping an HTML site and getting issues when wanting to access some objects.
products = BeautifulSoup(response.text, "html.parser").findAll("div", {"data-rubrik":"Cars"})
^This results in an array of 100+ objects. Each of these objects contains an aria-label ... | How to access an object while looping python | Hey I am scraping an HTML site and getting issues when wanting to access some objects.
products = BeautifulSoup(response.text, "html.parser").findAll("div", {"data-rubrik":"Cars"})
^This results in an array of 100+ objects. Each of these objects contains an aria-label looking like that:
<div class="art artikelid an" d... | [
"Try:\nfor cars in products:\n a = cars.find(\"a\")\n if a:\n print(a.get(\"aria-label\"))\n\n"
] | [
1
] | [] | [] | [
"for_loop",
"loops",
"python",
"python_3.x"
] | stackoverflow_0074165535_for_loop_loops_python_python_3.x.txt |
Q:
How to exclude a single number in while loops. (Begginer question)
I have a pretty simple task where i need to generate every integer below 15 that isn't 10.
I know that this is a pretty basic question but i don't know how to solve it.
i = 0
while i < 16 and i != 10:
print(i)
i += 1
I tried this but it just ... | How to exclude a single number in while loops. (Begginer question) | I have a pretty simple task where i need to generate every integer below 15 that isn't 10.
I know that this is a pretty basic question but i don't know how to solve it.
i = 0
while i < 16 and i != 10:
print(i)
i += 1
I tried this but it just loops 0 forever.
Any help would be appreciated!
| [
"Your issue is that your incrementing of i is not indented properly so the condition for ending the loop is never reached.\nA for loop is probably easier to understand:\nfor i in range(16): # range(16) = [0,1, ... 14, 15]\n if i == 10:\n continue # skip to next iteration\n print(i)\n\n",
"If you us... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074165509_python.txt |
Q:
AttributeError at /callback/ module 'zeep.client' has no attribute 'service'
when I want to use the zeep package in django for the payment gateway, I face an error.
error image,
code image
callback function in views.py in shop app:
# Callback function
def callback(request):
if request.GET.get('Status') == 'NOK... | AttributeError at /callback/ module 'zeep.client' has no attribute 'service' | when I want to use the zeep package in django for the payment gateway, I face an error.
error image,
code image
callback function in views.py in shop app:
# Callback function
def callback(request):
if request.GET.get('Status') == 'NOK':
authority = request.GET.get('authority')
invoice = get_object_o... | [
"The zeep documentation shows that the object client must be initialized as shown in the example listed on the site:\nfrom zeep import Client, Settings\n\nsettings = Settings(strict=False, xml_huge_tree=True)\nclient = Client('http://my-wsdl/wsdl', settings=settings)\n\nI suspect you either made a typo in defining ... | [
0
] | [] | [] | [
"django",
"python",
"zeep"
] | stackoverflow_0074164489_django_python_zeep.txt |
Q:
How to get parameter hints in VSCode for pyd files in general and confluent_kafka specifically?
I am new to kafka, and trying work some basic examples via VScode. The problem is I can't seem to make parameter hints work at all for all the artefacts imported via confluent_kafka. The module itself is a wrapper, and ... | How to get parameter hints in VSCode for pyd files in general and confluent_kafka specifically? | I am new to kafka, and trying work some basic examples via VScode. The problem is I can't seem to make parameter hints work at all for all the artefacts imported via confluent_kafka. The module itself is a wrapper, and I was wondering if there was a way to get parameter hinting the same way other python classes and mod... | [
"It's impossible. Because what you want was stored in the file of cimpl.cp39-win_amd64.pyd.\nThe Language Server can not provide Intellisense from the file with pyd filename extension.\nYou can have a look at the cimply with PyCharm, as it can decompilation it.\n",
"Currently, it is not supported by VScode. One w... | [
2,
1
] | [] | [] | [
"confluent_kafka_python",
"parameters",
"python",
"visual_studio_code"
] | stackoverflow_0068883854_confluent_kafka_python_parameters_python_visual_studio_code.txt |
Q:
Unable to install dbus-python. Ninja version error?
I'm trying to build dbus-python from source since I'm unable to install through pip when running pip3 install dbus-python:
error: metadata-generation-failed
Once the repo cloned, I run python3 setup.py build and get the following error:
ERROR: Could not detect N... | Unable to install dbus-python. Ninja version error? | I'm trying to build dbus-python from source since I'm unable to install through pip when running pip3 install dbus-python:
error: metadata-generation-failed
Once the repo cloned, I run python3 setup.py build and get the following error:
ERROR: Could not detect Ninja v1.8.2 or newer
pip3 list returns: ninja 1.10.2.4
| [
"I know that sometimes the issue is fixed, when you reinstall ninja via pip. You could try that.\npip install --force-reinstall ninja\n"
] | [
0
] | [] | [] | [
"dbus_python",
"meson_build",
"ninja",
"python"
] | stackoverflow_0074165572_dbus_python_meson_build_ninja_python.txt |
Q:
Permanently change the default Python3 version in Linux (Ubuntu on Windows)
I'm using WSL2 with Ubuntu on Windows 11 v2004.2022.10 and I have both Python 3.8 and 3.9 installed. I want to make the 3.9 version the default, and I'm happy to remove Python 3.8 altogether if necessary.
If I type python --version in Ubun... | Permanently change the default Python3 version in Linux (Ubuntu on Windows) | I'm using WSL2 with Ubuntu on Windows 11 v2004.2022.10 and I have both Python 3.8 and 3.9 installed. I want to make the 3.9 version the default, and I'm happy to remove Python 3.8 altogether if necessary.
If I type python --version in Ubuntu, I get Python 3.8.10.
I tried the following:
sudo update-alternatives --instal... | [
"I managed to solve it!\nI had to do add alias python3='/usr/bin/python3.9' in my ~/.bash_aliases file (or you can add it directly in ~/.bash_rc) with no spaces, and including the number 3, to my bash script, following the video I linked above. And then I had to close and re-open the terminal - typing clear was not... | [
1,
0
] | [] | [] | [
"linux",
"python",
"python_3.x",
"ubuntu",
"wsl_2"
] | stackoverflow_0072381940_linux_python_python_3.x_ubuntu_wsl_2.txt |
Q:
Foreign key associated with column could not find
i am trying to create the relationship between the following two tables. but the code is raising the error.
class TeacherModel(db.Model):
__Tablename__="Teacher"
id=db.Column(db.Integer, primary_key=True)
name=db.Column(db.String(80),unique=True,nullabl... | Foreign key associated with column could not find | i am trying to create the relationship between the following two tables. but the code is raising the error.
class TeacherModel(db.Model):
__Tablename__="Teacher"
id=db.Column(db.Integer, primary_key=True)
name=db.Column(db.String(80),unique=True,nullable=False)
Course_id=db.Column(db.Integer,db.ForeignK... | [
"there is a typo, it should be __tablename__ lowercase. I recommend to always use lowercase and snake_case, except for class names where its ok to use CapWords convention as recommended by PEP-8.\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074146037_python_sqlalchemy.txt |
Q:
haveing some problem with cog cant run it(discord.py)
soo My cog is not working no commands or anything
the code (main.py)
import os, discord
from discord.ext import commands
import asyncio
import re
from discord import Colour as C
import json
from discord.ext.commands import has_permissions
import logging
intents... | haveing some problem with cog cant run it(discord.py) | soo My cog is not working no commands or anything
the code (main.py)
import os, discord
from discord.ext import commands
import asyncio
import re
from discord import Colour as C
import json
from discord.ext.commands import has_permissions
import logging
intents= discord.Intents.default()
intents.message_content = True
... | [
"There's a lot of problems here:\n\nYour cog class is not subclassing commands.Cog\nYou're not awaiting load_extension\nYour setup is not async\nYou're not awaiting add_cog\nYour kick command is not indented inside if your cog\nDon't change presence in on_ready (preferably, don't do anything at all)\n\nIf you want ... | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074164852_discord_discord.py_python.txt |
Q:
Why isn't "SELECT" query run in Django?
I have person table as shown below:
# "store/models.py"
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=30)
And, I have test view with print(Person.objects.all()) as shown below:
# "store/views.py"
from django.http import H... | Why isn't "SELECT" query run in Django? | I have person table as shown below:
# "store/models.py"
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=30)
And, I have test view with print(Person.objects.all()) as shown below:
# "store/views.py"
from django.http import HttpResponse
from .models import Person
def t... | [
"QuerySets are lazy says as shown below so SELECT query isn't run when you run test view:\n\nDjango won’t actually run the query until the QuerySet is evaluated.\n\nIn addition, there is also the example which SELECT query is not run. I have person table as shown below:\n# \"store/models.py\"\n\nfrom django.db impo... | [
1
] | [] | [] | [
"django",
"python",
"python_3.x",
"select",
"sql"
] | stackoverflow_0074156359_django_python_python_3.x_select_sql.txt |
Q:
AttributeError: 'list' object has no attribute 'find_element'
AttributeError Traceback (most recent call last)
Input In [200], in <cell line: 17>()
15 sleep(3)
17 for match in matches:
---> 18 team = matches.find_element(By.XPATH,('//span[@class="team"]')).text
19 ... | AttributeError: 'list' object has no attribute 'find_element' | AttributeError Traceback (most recent call last)
Input In [200], in <cell line: 17>()
15 sleep(3)
17 for match in matches:
---> 18 team = matches.find_element(By.XPATH,('//span[@class="team"]')).text
19 scores = matches.find_element(By.XPATH,('//span[@class="score"]')).... | [
"the problem is here:\nfor match in matches:\nteam = **matches**.find_element(By.XPATH,('//span[@class=\"team\"]')).text\nscores = **matches**.find_element(By.XPATH,('//span[@class=\"score\"]')).text\nprint(team,scores)\n\nyou loop over the matches, and instead of writing match.find_elements, you wrote matches.find... | [
0
] | [] | [] | [
"attributeerror",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074165664_attributeerror_python_selenium_web_scraping.txt |
Q:
How to map a lambda function to variable that can be a float, int, or list
I'm trying to map a lambda function to variable that can be a float, int, or list.
Test #1, this works:
val = [0.1]
test = list(map(lambda x: max(x, 1 - x), val))
Test #2, this throws TypeError: 'float' object is not iterable:
val = 0.1
t... | How to map a lambda function to variable that can be a float, int, or list | I'm trying to map a lambda function to variable that can be a float, int, or list.
Test #1, this works:
val = [0.1]
test = list(map(lambda x: max(x, 1 - x), val))
Test #2, this throws TypeError: 'float' object is not iterable:
val = 0.1
test = list(map(lambda x: max(x, 1 - x), val))
I tried to solve it with list(va... | [
"You can handle this case using if condition inside your map function. Try like this:\nval = 0.1\ntest = list(map(lambda x: max(x, 1 - x), val if isinstance(val, list) else [val]))\n\nit will handle your all cases like list, int and decimal.\n",
"You get the error, because in Test #2 val variable is not iterable ... | [
2,
0
] | [] | [] | [
"dictionary",
"lambda",
"list",
"python"
] | stackoverflow_0074165636_dictionary_lambda_list_python.txt |
Q:
How to extract and delete text between two titles: Chorus and Verse Using regex
I have this sample string in the variable test_string. I want to delete chorus text. It is situated in this format: [chorus etc..] chorus_text [verse etc..]. I tried some regex patterns in python but nothing. Any idea? The pattern I am... | How to extract and delete text between two titles: Chorus and Verse Using regex | I have this sample string in the variable test_string. I want to delete chorus text. It is situated in this format: [chorus etc..] chorus_text [verse etc..]. I tried some regex patterns in python but nothing. Any idea? The pattern I am providing doesn't give me what i need. The chorus_text includes punctuation and char... | [
"test_string = \"\"\"Cordae,RNP,2019.0,\"RNP Lyrics[Chorus: Anderson .Paak] text text text text text text te'all tean' tean' text text text [Verse 1: YBN Cordae].\"\"\"\n\nre.sub('(?<=\\])(.*)(?=\\[)','',test_string)\n\n# (?<=\\]) : positive lookbehind for ]\n# (?=\\[ : positive look ahead for [\n\n'Cordae,RNP,2019... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074164687_python_regex.txt |
Q:
Error opening csv file in jupyter notebook
I created a csv file and closed it.
But, when I try to cast it into a list it gives me an error 'list' object is not callable.
Below is the codes for creating and opening the csv file:
file_to_output = open('to_save.csv',mode='w',newline='')
csv_writer = csv.writer(file_... | Error opening csv file in jupyter notebook | I created a csv file and closed it.
But, when I try to cast it into a list it gives me an error 'list' object is not callable.
Below is the codes for creating and opening the csv file:
file_to_output = open('to_save.csv',mode='w',newline='')
csv_writer = csv.writer(file_to_output,delimiter=',')
csv_writer = csv.write... | [
"Actually, your code working fine with me... However, this error usually happens when you have variables inside your code that resembles built-in objects in python ... so try to make some modifications in variable names ..\nGood Luck\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074165654_python.txt |
Q:
Python capture mouse inside 3D environment
I'm trying to create data files for behavorial cloning in reinforcement learning and I need to capture mouse movement inside a first person 3D game. I've researched in multiple sites already and only found mouse functions (like from pyautogui and mouse libraries) that cap... | Python capture mouse inside 3D environment | I'm trying to create data files for behavorial cloning in reinforcement learning and I need to capture mouse movement inside a first person 3D game. I've researched in multiple sites already and only found mouse functions (like from pyautogui and mouse libraries) that capture the mouse movement in 2D environments, like... | [
"Forget it, got it: \n\nimport win32api\n\nx, y = win32api.GetCursorPos()\nmouse_x, mouse_y = 0, 0\nfor j in range(5):\n last_x, last_y = win32api.GetCursorPos()\n if (x, y) != (last_x, last_y):\n #count = count +1\n #print(\"Pos:, \", (last_x - x),(last_y - y))\n mouse_x += last_x - x... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074164278_python.txt |
Q:
python iterate nested classes for module
I am trying to create a module that wraps all classes, and use them somewhere else.
class Mixins:
class B:
pass
class C:
pass
b = Mixins.B()
print(Mixins.__all_subclasses__())
# [Mixins.B, Mixins.C]
I mean, I can stack all subclasses in a list aft... | python iterate nested classes for module | I am trying to create a module that wraps all classes, and use them somewhere else.
class Mixins:
class B:
pass
class C:
pass
b = Mixins.B()
print(Mixins.__all_subclasses__())
# [Mixins.B, Mixins.C]
I mean, I can stack all subclasses in a list after I created one, but not elegant.
is there a... | [
"You can do this by subclassing the Mixin class directly and then accessing the __subclasses__ method on the Mixin class\nclass Mixin:\n pass\n\n\nclass B(Mixin):\n pass\n\n\nclass C(Mixin):\n pass\n\n\nprint(Mixin.__subclasses__())\n\nwhich prints\n[<class '__main__.B'>, <class '__main__.C'>]\n\nany class... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074165552_python.txt |
Q:
curses fails when calling addch on the bottom right corner
I am starting to learn curses in Python. I am using Python 3.5 on Mac OS X. When I try to write in the bottom-right corner, the program crashes with the following error:
$ python ex_curses.py
[...]
File "ex_curses.py", line 19, in do_curses
screen.ad... | curses fails when calling addch on the bottom right corner | I am starting to learn curses in Python. I am using Python 3.5 on Mac OS X. When I try to write in the bottom-right corner, the program crashes with the following error:
$ python ex_curses.py
[...]
File "ex_curses.py", line 19, in do_curses
screen.addch(mlines, mcols, 'c')
_curses.error: add_wch() returned ERR
... | [
"That is expected behavior (a quirk) because addch attempts to wrap to the next line after adding a character. There is a comment in lib_addch.c dealing with this:\n/*\n * The _WRAPPED flag is useful only for telling an application that we've just\n * wrapped the cursor. We don't do anything with this flag except... | [
7,
5,
4,
0,
0
] | [] | [] | [
"ncurses",
"python",
"python_curses"
] | stackoverflow_0036387625_ncurses_python_python_curses.txt |
Q:
Python conditional triggering twice
I am practicing functions. I made a short game to practice functions. I use the input() to interact.
When I enter "End" is where the confusion begins.
def endgame():
if input("Are you sure you want to exit?") == "yes" or input("Are you sure you want to exit?") == "y":
... | Python conditional triggering twice | I am practicing functions. I made a short game to practice functions. I use the input() to interact.
When I enter "End" is where the confusion begins.
def endgame():
if input("Are you sure you want to exit?") == "yes" or input("Are you sure you want to exit?") == "y":
return 1
else:
... | [
"Conditions like this in Python are evaluated from left to right, until the required condition is met or the end of the statement has been reached. Calling the same method in an or statement will result in the method being called multiple times until the condition is met, or not.\nExample,\nif 1 == 1 or 2 == 2 or 3... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074165683_python.txt |
Q:
How to put annotation in rest-auth user
I am trying to add some annotation in authenticated User using rest-auth
Here is my code in serializers.py
class CustomUserSerializer(UserDetailsSerializer):
test = serializers.IntegerField()
class Meta:
model=User
fields='__all__'
... | How to put annotation in rest-auth user | I am trying to add some annotation in authenticated User using rest-auth
Here is my code in serializers.py
class CustomUserSerializer(UserDetailsSerializer):
test = serializers.IntegerField()
class Meta:
model=User
fields='__all__'
And here is my code in views.py
class CustomU... | [
"In this context, queryset is ignored.\nWhy? In your program, you're subclassing UserDetailsView from django-rest-auth. That implements get_object() like so:\n def get_object(self):\n return self.request.user\n\nWith no reference to the queryset variable.\nYou need to override get_object() in CustomUserVi... | [
0
] | [] | [] | [
"django_rest_auth",
"django_rest_framework",
"python"
] | stackoverflow_0074165617_django_rest_auth_django_rest_framework_python.txt |
Q:
Get color of specific pixel in image using python
is it possible to get color of specific pixel from image using python?
Something like:
colorOfPixel = pixel(1, 9)
A:
Looking at another answer I found, on a similar question, it appears as though 'It's probably best to use the Python Image Library to do this whi... | Get color of specific pixel in image using python | is it possible to get color of specific pixel from image using python?
Something like:
colorOfPixel = pixel(1, 9)
| [
"Looking at another answer I found, on a similar question, it appears as though 'It's probably best to use the Python Image Library to do this which I'm afraid is a separate download.'\nIt's quite a good answer, I'd recommend checking it out!\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074165829_python.txt |
Q:
Django File " Error
I just started djnago. Learning all it's stuff, from official django 4.0 documentation.
Documentation link > https://docs.djangoproject.com/en/4.0/intro/tutorial01/
django officially installed version 4.2
python version 10
using vs-code
So in this tutorial we are creating a poll application bas... | Django File " Error | I just started djnago. Learning all it's stuff, from official django 4.0 documentation.
Documentation link > https://docs.djangoproject.com/en/4.0/intro/tutorial01/
django officially installed version 4.2
python version 10
using vs-code
So in this tutorial we are creating a poll application basically it will show some ... | [
"check https://stackoverflow.com/a/63762009/14389541\nCheck your imports and look where you're importing polls and fix that accordingly (rename if it's a misspell or change it to the correct name).\nI found that for my case; Rename project root caused this error after creating the project. After renaming the import... | [
1
] | [] | [] | [
"django",
"django_views",
"python",
"python_3.x"
] | stackoverflow_0073184020_django_django_views_python_python_3.x.txt |
Q:
Date difference in a column
everyone.
I have been trying to create a function that can help me find a difference between 2 date in either python or R. The issue is that the date are in a single column of a data frame.
Basically, I am trying to subtract a date in one row of the data frame from the the other row in ... | Date difference in a column | everyone.
I have been trying to create a function that can help me find a difference between 2 date in either python or R. The issue is that the date are in a single column of a data frame.
Basically, I am trying to subtract a date in one row of the data frame from the the other row in the data frame for multiple row.
... | [
"Please do no use screenshots of data, provide a reproducible example.\nYou likely want:\ndf['interval'] = (pd.to_datetime(df['STATEMENT_FROM_DD'], dayfirst=False)\n .diff().dt.days\n )\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"date",
"python",
"r"
] | stackoverflow_0074165808_dataframe_date_python_r.txt |
Q:
(Only) some dates in date index get interpreted wrong after import from csv
I want to analyse a dataframe in python. I loaded a csv which consists of two columns, one date/time and one mean value.
I loaded the data like this:
df = pd.read_csv('L_strom_30974_gerundet.csv', sep=';', names=['Timestamp', 'Mean'])
df['... | (Only) some dates in date index get interpreted wrong after import from csv | I want to analyse a dataframe in python. I loaded a csv which consists of two columns, one date/time and one mean value.
I loaded the data like this:
df = pd.read_csv('L_strom_30974_gerundet.csv', sep=';', names=['Timestamp', 'Mean'])
df['Timestamp'] = pd.to_datetime(df.Timestamp,format= '%d.%m.%y %H:%M', infer_datetim... | [
"The assumed need for infer_datetime_format=True gives away that you are not passing the correct format. Have a look at the strftime documentation. You are using:\nformat='%d.%m.%y %H:%M'\n# %y = Year without century as a zero-padded decimal number: 09, 10\n\nBut the format required is:\nformat='%d.%m.%Y %H:%M'\n# ... | [
0
] | [] | [] | [
"dataframe",
"datetime",
"indexing",
"pandas",
"python"
] | stackoverflow_0074165377_dataframe_datetime_indexing_pandas_python.txt |
Q:
How to make Python keylogger work in background
I'm trying to create a keylogger using the Python keyboard library. Currently I have a start function like this:
def start(self):
# record the start datetime
self.start_dt = datetime.now()
# start the keylogger
keyboard.on_release(callback=self.callba... | How to make Python keylogger work in background | I'm trying to create a keylogger using the Python keyboard library. Currently I have a start function like this:
def start(self):
# record the start datetime
self.start_dt = datetime.now()
# start the keylogger
keyboard.on_release(callback=self.callback)
# make a simple message
print(f"{datetime... | [
"You can simply use \"Thread\".\nStep 1: import \"Thread\" library\nimport thread\n\nStep 2: Define a function for the thread\nsome function that each time user presses a key, will generate that Keylogger object\n\nStep 3: Create as many threads as user click\nthread.start_new_thread( functionName, (parameter1, par... | [
0,
0
] | [] | [] | [
"keyboard",
"keylogger",
"multithreading",
"python"
] | stackoverflow_0074050457_keyboard_keylogger_multithreading_python.txt |
Q:
Using Scikit-Learn's SVR, how do you combine categorical and continuous features in predicting the target?
I want to use support vector machine to solve a regression problem to predict the income of teachers based on a few features which is a mixture of categorical and continuous. For example, I have [white, asian... | Using Scikit-Learn's SVR, how do you combine categorical and continuous features in predicting the target? | I want to use support vector machine to solve a regression problem to predict the income of teachers based on a few features which is a mixture of categorical and continuous. For example, I have [white, asian, hispanic, black], # years teaching, and years of education.
For the categorical, I utilized sci-kit's preproc... | [
"You can use scikit-learn's OneHotEncoder. If your data are in numpy array \"racearray\" and the columns are\n\n[ contionus_feature1, contious_feature2, categorical,\n continous_feature3]\n\nyour code should look like (keep in mind that numpy enumeration starts with 0)\nfrom sklearn.preprocessing import OneHotEnco... | [
3,
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0029835810_python_scikit_learn.txt |
Q:
Is there a way to be less redundant?
So I've been working on this little project of mine which involves building simple TCP reverse shell from "scratch" using sockets. Is there a way for the code below to be less redundant?
elif command == "camera":
try:
open_camera()
exce... | Is there a way to be less redundant? | So I've been working on this little project of mine which involves building simple TCP reverse shell from "scratch" using sockets. Is there a way for the code below to be less redundant?
elif command == "camera":
try:
open_camera()
except:
pass
elif comm... | [
"So you can use Python's helpful getattr method.\nExample: getattr(some_object, command)()\nSo you may end up with something that looks like:\nclass SomeClass:\n def __init__(self):\n # possibly start loop here?\n def open_camera(self):\n pass # ...\n def fullscreen(self):\n pass # ...... | [
0,
0,
0
] | [] | [] | [
"network_programming",
"python",
"python_3.x",
"sockets"
] | stackoverflow_0074165939_network_programming_python_python_3.x_sockets.txt |
Q:
how to iterare over list of words with regular expression?
I have a regular expression to find a specific word and the filters some text.
But now I want to iterate over a list of words and filter then some text.
So this is my regular expression:
def regex_fruit_cost(subst):
return r"(?<=" + subst + r").*?(?P<n... | how to iterare over list of words with regular expression? | I have a regular expression to find a specific word and the filters some text.
But now I want to iterate over a list of words and filter then some text.
So this is my regular expression:
def regex_fruit_cost(subst):
return r"(?<=" + subst + r").*?(?P<number>[0-9,.]*)\n"
and this is my list of words:
fruit_words =... | [
"single_fruit in your code is a list. You need to iterate over its elements to be able to use in in re.findall as it requires a string:\nfruit_cost_found = []\n\nfor fruit in single_fruit:\n m = re.findall(regex_fruit_cost(fruit), text)\n if m:\n fruit_cost_found.append(m)\n\nfruit_cost_found = [item f... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074165766_python.txt |
Q:
Adding letter grades to existing .txt list
I'm working on a project where I need to take an existing .txt file containing student names and number grades, assign letter grades to each student, and output name, grade, letter grade separated by commas. Then send the new output to a new file.
Example of text:
name_o... | Adding letter grades to existing .txt list | I'm working on a project where I need to take an existing .txt file containing student names and number grades, assign letter grades to each student, and output name, grade, letter grade separated by commas. Then send the new output to a new file.
Example of text:
name_one, 85
name_two, 76.5
Desired Output:
name_one,... | [
"Try:\ndef letter_grade(value):\n if value > 95:\n return \"A\"\n elif value > 91:\n return \"A-\"\n elif value > 87:\n return \"B+\"\n elif value > 83:\n return \"B\"\n elif value > 80:\n return \"B-\"\n elif value > 78:\n return \"C+\"\n elif value > ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074165811_python.txt |
Q:
How to find a movie name in a list, which there was a part of 2 of the movie?
There is an array of movies, with tuples in it:
films = [(film_name,film_rating),...]
How do I find a film name which has the same name, but the number 2 added to it (like a part 2)?
A:
Consider utilizing str.startswith:
>>> films = [... | How to find a movie name in a list, which there was a part of 2 of the movie? | There is an array of movies, with tuples in it:
films = [(film_name,film_rating),...]
How do I find a film name which has the same name, but the number 2 added to it (like a part 2)?
| [
"Consider utilizing str.startswith:\n>>> films = [('Kill Bill: Vol. 1', 8.2), ('Pulp Fiction', 8.9), ('Kill Bill: Vol. 2', 8.0)]\n>>> kill_bill_films = [(film, rating) for (film, rating) in films if film.startswith('Kill Bill')]\n>>> kill_bill_films\n[('Kill Bill: Vol. 1', 8.2), ('Kill Bill: Vol. 2', 8.0)]\n\nOr st... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074165928_python.txt |
Q:
(Python) my script gets stuck at root.mainloop(), how do I make it run alongside my script?
what my code basically does is copying .txt files from source_path to dest_path, you can test it without all the tkinter code to see that it works.
Now, I wanted to make a GUI for this little script I created, and looking a... | (Python) my script gets stuck at root.mainloop(), how do I make it run alongside my script? | what my code basically does is copying .txt files from source_path to dest_path, you can test it without all the tkinter code to see that it works.
Now, I wanted to make a GUI for this little script I created, and looking at tutorials they tell me that I have to write down root.mainloop() to create a window that stays.... | [
"Soo, root.mainloop() will wait for you to press esc to exit the window.\nto make the script work without pause. you can use root.update() to update you code and the script will work fine.\n"
] | [
0
] | [] | [] | [
"python",
"scripting",
"shutil"
] | stackoverflow_0040932439_python_scripting_shutil.txt |
Q:
overwrites data issue: Trying to store multicolumn data from a data frame into one work sheet in an excel file
I am trying to store data from data frames and write it into in an excel sheet (same work sheet) without overwriting. But my script just overwrites the entire sheet. I want all the data to be stored with ... | overwrites data issue: Trying to store multicolumn data from a data frame into one work sheet in an excel file | I am trying to store data from data frames and write it into in an excel sheet (same work sheet) without overwriting. But my script just overwrites the entire sheet. I want all the data to be stored with same column names as it is in the data frames.
Data Sample:
TO_NAME DURATION_H DIST_KM Municipality
Kri... | [
"You can use Column to add up multi data into the same work sheet in an excel sheet.\nThis should work:\nRegular_Ambulance_TT. to_excel(r'/Users/an2178/Desktop/Jupyter Notebook/Regular-Ambulance-Complete-TT.xlsx', columns = ['column1','column2','column3','column4'], index = False)\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"excel",
"openpyxl",
"pandas",
"python"
] | stackoverflow_0074165945_dataframe_excel_openpyxl_pandas_python.txt |
Q:
Zero_Division_Error I think there is no 0 at denominator and numarator
It is constantly showing the error that ZeroDivisionError.
start= 11
end = 75
print("Prime numbers between ",start," and ",end," are : ")
for i in range (start, end+1):
if i > 1:
c = 2*i
for j in range(c):
if i//j == 0:
... | Zero_Division_Error I think there is no 0 at denominator and numarator | It is constantly showing the error that ZeroDivisionError.
start= 11
end = 75
print("Prime numbers between ",start," and ",end," are : ")
for i in range (start, end+1):
if i > 1:
c = 2*i
for j in range(c):
if i//j == 0:
break
else:
print(i)
| [
"range(c) specifies that the loop should start at 0.\nrange(1,c) specifies that the loop should start at 1.\n",
"You get the error because in python, when you use for loop, it iterates from 0 to c, and since you're making a division (i // j), you're dividing by 0 in the first loop iteration.\nHere is how it shoul... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074166058_python.txt |
Q:
Is there a way to switch the "python [filename].py to a shortcut
Is there a way to switch the "python [filename].py to a shortcut like "shutdown" for example?
A:
If you're on Linux, then go to the end of your bash configuration file (found at ~/.bashrc), and add the line:
alias shutdown="python filename.py"
If ... | Is there a way to switch the "python [filename].py to a shortcut | Is there a way to switch the "python [filename].py to a shortcut like "shutdown" for example?
| [
"If you're on Linux, then go to the end of your bash configuration file (found at ~/.bashrc), and add the line:\nalias shutdown=\"python filename.py\"\n\nIf you're on Windows, then create a file with the following line:\npython filename.py\n\nThen save the file as shutdown.bat and put it in your Windows directory (... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074166041_python.txt |
Q:
Highest Scoring Word on CodeWars not correct testcase
I have problem in my testcase on CodeWars. I fail here:
print(high('what time are we climbing up the volcano'))
Instead of 'volcano', I got the what in my new_dictionary variable the w at place 23 and v is on place 22 , and i got what as a result because the w... | Highest Scoring Word on CodeWars not correct testcase | I have problem in my testcase on CodeWars. I fail here:
print(high('what time are we climbing up the volcano'))
Instead of 'volcano', I got the what in my new_dictionary variable the w at place 23 and v is on place 22 , and i got what as a result because the word have greater letter than the another. Did i understand ... | [
"your new_dictionary is using a str for it's score value not an int\nfrom string import ascii_lowercase\n\ndef score_word(word):\n score_table = {letter: index for index, letter in enumerate(ascii_lowercase, start=1)}\n score = 0\n for letter in word:\n score += score_table[letter]\n return score... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074165864_python.txt |
Q:
Pygame subsurface rectangle outside surface area
def screenshot():
scrnsht_t = datetime.now().strftime("%y.%m.%d-%H:%M:%S")
if not os.path.exists("screenshots"):
os.makedirs("screenshots")
screenshot_zone = screen.subsurface(pg.Rect(0, HEIGHT/5+5, WIDTH, HEIGHT))
pg.image.save(screenshot_zone, f"screenshots\{s... | Pygame subsurface rectangle outside surface area | def screenshot():
scrnsht_t = datetime.now().strftime("%y.%m.%d-%H:%M:%S")
if not os.path.exists("screenshots"):
os.makedirs("screenshots")
screenshot_zone = screen.subsurface(pg.Rect(0, HEIGHT/5+5, WIDTH, HEIGHT))
pg.image.save(screenshot_zone, f"screenshots\{scrnsht_t}.png")
Error:
screenshot_zone = screen.subsu... | [
"A rectangle of size and position (0, HEIGHT/5+5, WIDTH, HEIGHT) cannot lie completely in the surface, because if the rectangle starts at HEIGHT/5+5, the height of the subsurface cannot be HEIGHT. The maximum height of the subsurface is HEIGHT - (HEIGHT/5+5).\nChange the subsurface rectangle:\noffset_y = HEIGHT//5 ... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074166114_pygame_python.txt |
Q:
How can I create this struct?
I want to create a struct like this:
import ctypes
class MyStruct(ctypes.Structure):
_fields_ = [('field1', /* size of 16 bytes */),
('field2', /* size of 4 bytes */)
('field3', /* size of 8 bytes */)]
What is the types that i need to write here f... | How can I create this struct? | I want to create a struct like this:
import ctypes
class MyStruct(ctypes.Structure):
_fields_ = [('field1', /* size of 16 bytes */),
('field2', /* size of 4 bytes */)
('field3', /* size of 8 bytes */)]
What is the types that i need to write here for these sizes of fields ? I want t... | [
"Two ways. The 16-bit field makes it a bit tricky:\nimport ctypes\n\nclass MyStruct(ctypes.Structure):\n _pack_ = 1\n _fields_ = (('field1', ctypes.c_ubyte * 16), # C char[16] field1\n ('field2', ctypes.c_uint32), # C uint32_t field2\n ('field3', ctypes.c_uint64)) # C ui... | [
1
] | [] | [] | [
"ctypes",
"python",
"struct"
] | stackoverflow_0074165906_ctypes_python_struct.txt |
Q:
Adding Tkinter Entry into SQLite Database
I am currently having trouble trying to make my SQLite database update its records using values entered by the user in my tkinter entry boxes. This is my code:
from tkinter import ttk
import sqlite3
from tkinter import *
import mysql.connector
root = Tk()
root.title("Play... | Adding Tkinter Entry into SQLite Database | I am currently having trouble trying to make my SQLite database update its records using values entered by the user in my tkinter entry boxes. This is my code:
from tkinter import ttk
import sqlite3
from tkinter import *
import mysql.connector
root = Tk()
root.title("Player Statistics DBMS")
root.geometry('700x400')
r... | [
"The ) before the \\ in the following line:\ncur.execute(\"insert into player_stats values('%s', '%s', '%s', '%s', '%s', '%s')\") \\\n %(first_name.get(), points.get(), assists.get(), rebounds.get(), shots_made.get(), shots_missed.get())\n\nshould be moved to the end of the statement like below:\ncur.execute(\"i... | [
0
] | [] | [] | [
"python",
"sqlite",
"tkinter"
] | stackoverflow_0074160965_python_sqlite_tkinter.txt |
Q:
Python concurrent futures multiprocessing Pool does not scale with the number of processors
I have written a simple function to demonstrate this behavior which iteratively creates a list and I pass that function to the concurrent.futures.ProcessPoolExecutor. The actual function isn't important as this seems to hap... | Python concurrent futures multiprocessing Pool does not scale with the number of processors | I have written a simple function to demonstrate this behavior which iteratively creates a list and I pass that function to the concurrent.futures.ProcessPoolExecutor. The actual function isn't important as this seems to happen for a wide variety of functions I've tested. As I increase the number of processors it takes... | [
"yes there is, and it's called MEMORY BANDWIDTH.\nwhile the memory controller is good at pipelining read/write instructions to improve throughput for parallel programs, if too many applications are reading/writing to your RAM sticks then you are going to see a slowdown because the RAM pipeline is being bombarded fr... | [
0
] | [] | [] | [
"concurrent.futures",
"multiprocessing",
"python",
"python_multiprocessing"
] | stackoverflow_0074142802_concurrent.futures_multiprocessing_python_python_multiprocessing.txt |
Q:
How do I keep a loop going with a variable that changes in every loop
So I'm new to coding and I'm struggling with the following exercise
So we start with a random number and we have to count the even numbers and the odd numbers. With this, we make a second number that starts with the amount of the even numbers, a... | How do I keep a loop going with a variable that changes in every loop | So I'm new to coding and I'm struggling with the following exercise
So we start with a random number and we have to count the even numbers and the odd numbers. With this, we make a second number that starts with the amount of the even numbers, amount of the odd numbers, and the amount of numbers in total. We should con... | [
"You need your variable initialization to be inside the while loop, and remove the input(print(... on the final line.\nnumber = '567421'\nwhile number != '123':\n print(number)\n evennumbers = ''\n oddnumbers = ''\n a = len(number)\n for i in str(number):\n if int(i) % 2 == 0:\n eve... | [
1
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074166146_loops_python.txt |
Q:
Why does os.system() not open a file after retrieving its path from a text file
My program stores its configuration in a text file and retrieves it when you restart the program. When I first enter the configuration, it opens the program in the config, but when I restart the program it suddenly doesn't work and say... | Why does os.system() not open a file after retrieving its path from a text file | My program stores its configuration in a text file and retrieves it when you restart the program. When I first enter the configuration, it opens the program in the config, but when I restart the program it suddenly doesn't work and says the file path cannot be found. Any help is appreciated
Full code:
import os
datai... | [
"You likely need to remove the newline at the end of the filename:\ndef Run1():\n os.system('\"%s\"' % filename1.strip())\n\nAlso, please note that in general, you should avoid the use of os.system and use the appropriate function from the subprocess module instead.\n"
] | [
0
] | [] | [] | [
"os.system",
"python",
"python_3.x"
] | stackoverflow_0074165782_os.system_python_python_3.x.txt |
Q:
How to convert LIGHTGBM to PMML?
I would like to know if there exist a way to convert a LightGBM model to a PMML. Starting from the lightgbm.basic.Booster object I would like to know how to convert it to a PMML or MOJO/POJO object. If is not possible, i would like to know if it is possible to save the LGBM model a... | How to convert LIGHTGBM to PMML? | I would like to know if there exist a way to convert a LightGBM model to a PMML. Starting from the lightgbm.basic.Booster object I would like to know how to convert it to a PMML or MOJO/POJO object. If is not possible, i would like to know if it is possible to save the LGBM model as Pickle and than convert it to a PMML... | [
"For now, there are at least two ways to create PMML from lightGBM, such as sklearn2pmml and Nyoka, but both cannot create PMML from a learned Booster.\nTo create PMML, we need to use a Scikit-learn API such as LGBMClassifier and Pipeline. Both packages can create PMML in almost the same way. The detailed usage is ... | [
1
] | [] | [] | [
"lightgbm",
"mojo",
"pmml",
"pojo",
"python"
] | stackoverflow_0072432995_lightgbm_mojo_pmml_pojo_python.txt |
Q:
How do I select a random object from a list of objects?
I have a list of 10 x 10, with objects like this:
self.taula = [[casella() for i in range(10)] for j in range(10)]
How do I select a random object from this list?
I've been trying but of course I don't have any integer to use as an index, I'm pretty new to c... | How do I select a random object from a list of objects? | I have a list of 10 x 10, with objects like this:
self.taula = [[casella() for i in range(10)] for j in range(10)]
How do I select a random object from this list?
I've been trying but of course I don't have any integer to use as an index, I'm pretty new to coding so I might be doing something wrong.
| [
"Assuming you want to select a random single element, you can use random.choice twice: first to select a list within the list of lists at random, then to randomly choose from that list.\nimport random\n\nrand = random.choice(random.choice(self.taula))\n\nNote this works well when the nested lists are of equal lengt... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0074166221_python.txt |
Q:
Python print() displays data in scientific format
I have an existing data given in matrix form (class 'numpy.ndarray'). I have noticed something interesting.
If I do this:
print(X_train[1:4,:])
the result is:
[[1947. 3. 2. 17.]
[1725. 3. 2. 42.]
[1959. 3. 2. 15.]]
But if I do this:
p... | Python print() displays data in scientific format | I have an existing data given in matrix form (class 'numpy.ndarray'). I have noticed something interesting.
If I do this:
print(X_train[1:4,:])
the result is:
[[1947. 3. 2. 17.]
[1725. 3. 2. 42.]
[1959. 3. 2. 15.]]
But if I do this:
print(X_train[0:4,:])
the result is the following:
[[1... | [
"You can use set_printoptions to change the way output is displayed.\nnumpy.set_printoptions(suppress=True)\n\n\nIf False, then scientific notation is used when absolute value of the\nsmallest number is < 1e-4 or the ratio of the maximum absolute value\nto the minimum is > 1e3. The default is False.\n\nBecause the ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074165557_python.txt |
Q:
How to replace a checked pattern in a PNG image with transparent in Python?
I am trying to remove the checkered background (which represents transparent background in Adobe Illustrator and Photoshop) with transparent color (alpha channel) in some PNGs with Python script.
First, I use template matching:
import cv2
... | How to replace a checked pattern in a PNG image with transparent in Python? | I am trying to remove the checkered background (which represents transparent background in Adobe Illustrator and Photoshop) with transparent color (alpha channel) in some PNGs with Python script.
First, I use template matching:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img_rgb = cv2.imread('te... | [
"Here is one way to do that in Python/OpenCV simply by thresholding on the checks color range.\nInput:\n\nimport cv2\nimport numpy as np\n\n# read input\nimg = cv2.imread(\"fake.png\")\n\n# threshold on checks\nlow = (230,230,230)\nhigh = (255,255,255)\nmask = cv2.inRange(img, low, high)\n\n# invert alpha\nalpha = ... | [
2,
1,
1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074134195_opencv_python.txt |
Q:
Python if/elif statement not working correctly
Please help understand what is wrong with the code below. The code works fine if I pass values up to 34. Once I pass 35 or higher, the output is incorrect.
tuk=0
if tuk <= 24:
print ('The text is very easy to read.')
elif tuk >= 25 & tuk <= 34:
print('The text... | Python if/elif statement not working correctly | Please help understand what is wrong with the code below. The code works fine if I pass values up to 34. Once I pass 35 or higher, the output is incorrect.
tuk=0
if tuk <= 24:
print ('The text is very easy to read.')
elif tuk >= 25 & tuk <= 34:
print('The text is easy to read.')
elif tuk >= 35 & tuk <= 44:
... | [
"Your code is correct, but changing the \"&\" to \"and\" because \"&\" is a bitwise logical operator, not a logical one.\nFor example:\n\n\nz = 0 := 0b000\na = 1 := 0b001\nb = 2 := 0b010\nc = 3 := 0b011\nd = 4 := 0b100 \n\n\n\nnow the result of the expression (a & c) is 0b001 or 1\nbut in logical expression (a and ... | [
0
] | [] | [] | [
"nlp",
"python"
] | stackoverflow_0074166201_nlp_python.txt |
Q:
How to drop multiple rows with datetime index?
I have the pandas data frame as below with a datetime index. The dataframe shows the data for the month of April and May. (The original dataframe has many more columns).
I want to remove all the rows for the month of May i.e. starting from index 2022-05-01 00:00:00 a... | How to drop multiple rows with datetime index? | I have the pandas data frame as below with a datetime index. The dataframe shows the data for the month of April and May. (The original dataframe has many more columns).
I want to remove all the rows for the month of May i.e. starting from index 2022-05-01 00:00:00 and ending at 2022-05-31 23:45:00. Currently, I am do... | [
"you may want to include the year when choosing month, to avoid deleting same month from other year\n# assumption: date field is an index \n# and is already converted to datetime using pd.to_datetime\n\ndf.drop(df.loc[df.index.strftime('%Y%m') == '202205'].index)\n\n\nconverting index to datetime\ndf.index=pd.to_da... | [
1
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074165961_dataframe_datetime_pandas_python.txt |
Q:
Tell if a specific function is called with Python AST
Given a Python AST, is it possible to tell if a specific function is being called regardless of the function's name?
In Python, I could do the following:
def identity(x):
return x
def print_id(func):
print(hash(func))
if __name__ == "__main__":
pr... | Tell if a specific function is called with Python AST | Given a Python AST, is it possible to tell if a specific function is being called regardless of the function's name?
In Python, I could do the following:
def identity(x):
return x
def print_id(func):
print(hash(func))
if __name__ == "__main__":
print(hash(identity))
x = identity
print(hash(x))
... | [
"It's not possible to statically determine this.\nAs you point out, at run time the scope could bind that function name in a manner you can't easily determine form the AST (ie, without running it). Consider this example:\ndef func1():\n print(\"func1\")\n\ndef func2():\n print(\"func2\")\n\nfunc2 = func1\nfu... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074166025_python_python_3.x.txt |
Q:
Link Conda environment with Jupyter Notebook
I'm trying to set a good environnement for doing some scientific stuff with python. To do so, I installed Jupyter & miniconda.
Then I want to be able to have different environnement and use them with Jupyter notebooks. So I created two custom envs with conda : py27 and ... | Link Conda environment with Jupyter Notebook | I'm trying to set a good environnement for doing some scientific stuff with python. To do so, I installed Jupyter & miniconda.
Then I want to be able to have different environnement and use them with Jupyter notebooks. So I created two custom envs with conda : py27 and py35.
> conda env list
# conda environments:
#
py2... | [
"For Anaconda I suggest you a much easier and proper solution;\njust give a look at the nb_conda_kernels package.\nIt allows you to \"manage your conda environment-based kernels inside the Jupyter Notebook\".\nIs should be included since Anaconda version 4.1.0, otherwise simply use\nconda install nb_conda\n\nNow yo... | [
121,
31,
10,
6,
1,
0,
0
] | [] | [] | [
"ipython",
"jupyter",
"jupyter_notebook",
"miniconda",
"python"
] | stackoverflow_0037433363_ipython_jupyter_jupyter_notebook_miniconda_python.txt |
Q:
generator with conditions in python
which is taken from the predefined interval [a=10000, b=99999]
will fill the list (lst) with a random value, taking into account the following principle: on an even index
The sum of the standing digits is equal to the sum of the standing digits on the odd index
A:
Here is a hi... | generator with conditions in python | which is taken from the predefined interval [a=10000, b=99999]
will fill the list (lst) with a random value, taking into account the following principle: on an even index
The sum of the standing digits is equal to the sum of the standing digits on the odd index
| [
"Here is a hit-or-miss generator that works well for numbers in your range:\nimport random\n\ndef even_odd_places(n):\n evens = []\n odds = []\n for i,d in enumerate(str(n),start = 1):\n if i % 2 == 0:\n evens.append(int(d))\n else:\n odds.append(int(d))\n return even... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074165825_python.txt |
Q:
How to run my Python code using Spyder, without the error "the following arguments are required: -p/--shape-predictor"?
How can I run this?
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True,
help="path to facial landmark predictor")
ap.add_argument("-a", "--alarm", typ... | How to run my Python code using Spyder, without the error "the following arguments are required: -p/--shape-predictor"? | How can I run this?
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True,
help="path to facial landmark predictor")
ap.add_argument("-a", "--alarm", type=str, default="",
help="path alarm .WAV file")
ap.add_argument("-w", "--webcam", type=int, default=0,
help="index of... | [
"From @hiroprotagonist's comment posted above:\n\nIn spyder ctrl+F6 should allow you to pass command-line args when you execute your script. see here https://stackoverflow.com/a/26766414/4954037.\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0063970283_python.txt |
Q:
Check certain Popen is running at first (==Checking variable is assigned)
I got a running Thread p in a function
and trying to check at first, whether it's already running or not
if p wasn't running it spits reference before the assignment error
from subprocess import check_output,Popen
from asyncio.subprocess imp... | Check certain Popen is running at first (==Checking variable is assigned) | I got a running Thread p in a function
and trying to check at first, whether it's already running or not
if p wasn't running it spits reference before the assignment error
from subprocess import check_output,Popen
from asyncio.subprocess import PIPE
from threading import Thread
def th():
p= Popen([r'C:\Users\dow\D... | [
"It looks like you want to run your exe exactly once from this program. To do that you could keep some global state to let you know whether the process has been executed. Wrap that state in a lock to avoid race conditions and your code could be:\nfrom subprocess import Popen, PIPE, STDOUT\nfrom threading import Thr... | [
1
] | [] | [] | [
"popen",
"process",
"python",
"subprocess"
] | stackoverflow_0074165162_popen_process_python_subprocess.txt |
Q:
Create JSON from specific lines of data
I have this test data that I am trying to use to create a JSON for just select items. I have the items listed and would just like to output a JSON list with select item.
What I have:
import json
# Data to be written
dictionary ={
"id": "04",
"name": "sunil",
"d... | Create JSON from specific lines of data | I have this test data that I am trying to use to create a JSON for just select items. I have the items listed and would just like to output a JSON list with select item.
What I have:
import json
# Data to be written
dictionary ={
"id": "04",
"name": "sunil",
"department": "HR"
}
# Serializing json
x... | [
"If you don't need to save the department key you can use this:\ndel y['department']\n\nThen your y variable will print what you wanted:\n{\"id\": \"04\", \"name\": \"sunil\"}\n\nOther ways to solve the same issue\n",
"for key in list(y.keys()):\n#add all potential keys you want to remain in the final dictionary\... | [
2,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074165188_json_python.txt |
Q:
insert plot from pandas to excel file
How can I add the plot of pandas to the second worksheet,I checked Putting multiple matplotlib graphs into Excel using Python 3, but they use a different module to write to the excel file. everything is working in code(the bars shows correct output), I just want to add the plo... | insert plot from pandas to excel file | How can I add the plot of pandas to the second worksheet,I checked Putting multiple matplotlib graphs into Excel using Python 3, but they use a different module to write to the excel file. everything is working in code(the bars shows correct output), I just want to add the plot to graph1 sheet.
here is my code so far
i... | [
"I know it's a bit late, but I'd suggest creating a pandas/matplotlib graph, save the image and insert it to excel using openpyxl and Pillow.\nfrom openpyxl import Workbook\nfrom openpyxl.drawing.image import Image\nimport matplotlib.pyplot as plt\n\n\ndef create_graph():\n # create your image, then save it as a... | [
0
] | [] | [] | [
"excel",
"matplotlib",
"python"
] | stackoverflow_0056108294_excel_matplotlib_python.txt |
Q:
How to take a nested list as input from user?
I want to take a nested list like this from user.
[(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Write a Python program to get a list, sorted in increasing order by the last element
in each tuple from a given list of non-empty tuples. Go to the editor
Sample List : [(2, 5... | How to take a nested list as input from user? | I want to take a nested list like this from user.
[(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Write a Python program to get a list, sorted in increasing order by the last element
in each tuple from a given list of non-empty tuples. Go to the editor
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result... | [
"This line:\nui1 = list(map(int,input(\"Enter elements: \").split(',')))\n\nturns each user input line of the form x,y into the 2-list [x,y]. But your problem statement says it should be a tuple:\nui1 = tuple(map(int,input(\"Enter elements: \").split(',')))\n\nThis line:\nulst += ui1\n\ndoes not append the user's i... | [
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0044601958_python_python_3.x.txt |
Q:
Why is this not returning 3 as a prime?
def isItPrime(n):
p='true'
if not n==2:
for x in range(2,round(math.sqrt(n))+1):#I'm taking the square root to make the program more efficient, and adding the one so it doesn't create ranges like: range(2,2)
if n%x==0:
p='false'
... | Why is this not returning 3 as a prime? | def isItPrime(n):
p='true'
if not n==2:
for x in range(2,round(math.sqrt(n))+1):#I'm taking the square root to make the program more efficient, and adding the one so it doesn't create ranges like: range(2,2)
if n%x==0:
p='false'
break
return p
def findPri... | [
"\n if isItPrime(x)=='true':\n primes.append(x)\n x+=1\n x+=1\n\n\n2 is a prime so it appends 2 to primes, then changes x to 3 then finishes the if then changes x to 4. Then starts the loop again.\nThus 3 is skipped.\nDon't increment x inside the if.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074166480_python.txt |
Q:
Getting "TypeError: fit() missing 1 required positional argument: 'y'" for linear regression in python
What I'm trying to do:
Fit a linear regression model on data from PCA transformation
Use that linear regression model to perform cross-validation
ks = [1,2,3,4,5,6,8,10,12,15,20]
mean_val_mse = []
# loop throug... | Getting "TypeError: fit() missing 1 required positional argument: 'y'" for linear regression in python | What I'm trying to do:
Fit a linear regression model on data from PCA transformation
Use that linear regression model to perform cross-validation
ks = [1,2,3,4,5,6,8,10,12,15,20]
mean_val_mse = []
# loop through all k values
for k in ks:
# instantiate pca and set n_components = k
pca = PCA(n_components=k)
... | [
"I have never dealt with Machine Learning, but the error message says you didn't supply y into that last line, so maybe try\ncv = cross_validate(lr, X=x_train_pca, y=y_train, cv=10, return_train_score=True, scoring='neg_mean_squared_error', error_score='raise')\n\nsource:\nhttps://scikit-learn.org/stable/modules/ge... | [
3
] | [] | [] | [
"cross_validation",
"data_science",
"linear_regression",
"python"
] | stackoverflow_0074166291_cross_validation_data_science_linear_regression_python.txt |
Q:
Generate a dataframe from a string
Inspired by this solution I have been using the following code to clean-up some data that I obtain using Beautiful Soup:
nfl = soup.findAll('li', "player")
lines = ("{}. {}\n".format(ind,span.get_text(strip=True).rstrip("+"))
for ind, span in enumerate(nfl,1))
print("".j... | Generate a dataframe from a string | Inspired by this solution I have been using the following code to clean-up some data that I obtain using Beautiful Soup:
nfl = soup.findAll('li', "player")
lines = ("{}. {}\n".format(ind,span.get_text(strip=True).rstrip("+"))
for ind, span in enumerate(nfl,1))
print("".join(lines))
The problem is that the out... | [
"Try:\nnfl = soup.findAll(\"li\", \"player\")\n\nall_data = []\nfor span in nfl:\n all_data.append({\"player\": span.get_text(strip=True).rstrip(\"+\")})\n\ndf = pd.DataFrame(all_data)\nprint(df)\n\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"data_cleaning",
"python",
"string"
] | stackoverflow_0074166469_beautifulsoup_data_cleaning_python_string.txt |
Q:
Best way to create pivot tables for multiple dataframes?
I have 4 data frames and trying to create pivot tables for each data frame. Instead of combining or concatenating into one large table, I'd like to create a pivot table for each dataframe, which means I would end up with 4 separate pivot tables. I am trying ... | Best way to create pivot tables for multiple dataframes? | I have 4 data frames and trying to create pivot tables for each data frame. Instead of combining or concatenating into one large table, I'd like to create a pivot table for each dataframe, which means I would end up with 4 separate pivot tables. I am trying to create a loop and pass it through each data frame. Can some... | [
"As said in comments, you can use:\nout = []\nfor df in df_list:\n out.append(df.pivot_table(values='Score', index='Measure_ID',\n aggfunc=[fiftieth,sixtieth,seventieth,\n seventy_fifth,eightieth,ninetieth],\n dropna=... | [
1
] | [] | [] | [
"pandas",
"pivot",
"python"
] | stackoverflow_0074162014_pandas_pivot_python.txt |
Q:
Use list of derived class as list of base class in Python
I have a function which takes a list of a base class as argument, and I have a variable which is a list of a derived class. Using this variable as the argument gives mypy error: Argument 1 to "do_stuff" has incompatible type "List[DerivedClass]"; expected "... | Use list of derived class as list of base class in Python | I have a function which takes a list of a base class as argument, and I have a variable which is a list of a derived class. Using this variable as the argument gives mypy error: Argument 1 to "do_stuff" has incompatible type "List[DerivedClass]"; expected "List[BaseClass]".
class BaseClass(TypedDict):
base_field: s... | [
"It depends on what exactly do_stuff is doing, but nine times out of ten the best solution is to use Sequence instead of List:\nfrom typing import Sequence\n\ndef do_stuff(data: Sequence[BaseClass]) -> None:\n pass\n\nThe reason you can't use List[BaseClass] here is that do_stuff would be allowed to add BaseClas... | [
3,
0
] | [] | [] | [
"mypy",
"python",
"python_typing"
] | stackoverflow_0074166494_mypy_python_python_typing.txt |
Q:
How to create a new dataframe and add new variables in Python?
I created two random variables (x and y) with certain properties. Now, I want to create a dataframe from scratch out of these two variables. Unfortunately, what I type seems to be wrong. How can I do this correctly?
# creating variable x with Bernoulli... | How to create a new dataframe and add new variables in Python? | I created two random variables (x and y) with certain properties. Now, I want to create a dataframe from scratch out of these two variables. Unfortunately, what I type seems to be wrong. How can I do this correctly?
# creating variable x with Bernoulli distribution
from scipy.stats import bernoulli, binom
x = bernoulli... | [
"There are a lot of ways to go about this.\nAccording to the documentation pd.DataFrame accepts ndarray (structured or homogeneous), Iterable, dict, or DataFrame. Your issue is that x and y are 2d numpy array\n>>> x.shape\n(100, 1)\n\nwhere it expects either one 1d array per column or a single 2d array.\nOne way wo... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074165698_pandas_python.txt |
Q:
Why is it not return any sequence within the string?
So for this code I want to input any string and I want it to return true if there's a sequence of 3 same consecutive characters in n.
This code works however, it only counts the first three consecutive numbers in n, but I want it to count any sequence in n.
def ... | Why is it not return any sequence within the string? | So for this code I want to input any string and I want it to return true if there's a sequence of 3 same consecutive characters in n.
This code works however, it only counts the first three consecutive numbers in n, but I want it to count any sequence in n.
def consec(n):
for i in range(len(n)):
if n[i] == n[i+... | [
"your for loop only iterates one time that's why you are getting incorrect responses? Try like this:\ndef consec(n):\n result = False\n for i in range(len(n)):\n if result:\n return result\n if n[i] == n[i + 1] == n[i + 2]:\n result = True\n else:\n result... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074165951_python.txt |
Q:
Heroku: ImportError: No module named site
After some changes in my repo and deploy to heroku I am receiving the following error:
ImportError: No module named site
I not have idea what can cause the problem because I only change some Django templates in the last 2 commits.
Best Regards
A:
Take a look at your Proc... | Heroku: ImportError: No module named site | After some changes in my repo and deploy to heroku I am receiving the following error:
ImportError: No module named site
I not have idea what can cause the problem because I only change some Django templates in the last 2 commits.
Best Regards
| [
"Take a look at your Procfile. It should show something like this:\nweb: gunicorn site:app\n\nMake sure site is the name of your app. \n",
"Heroku has an article for this: https://help.heroku.com/BWJ7QYTF/why-am-i-seeing-importerror-no-module-named-site-when-deploying-a-python-app\nUpdates to the Python buildpack... | [
7,
4
] | [
"Add the following to your proc file\nweb: gunicorn site:app\n\nAlso check your gitignore and make sure site isnt included\n"
] | [
-1
] | [
"heroku",
"importerror",
"python"
] | stackoverflow_0012703388_heroku_importerror_python.txt |
Q:
How to get filename of file downloaded with Youtube-dl
I am using youtube-dl with a flask app to download a file and return the file. When I download the filename is changed slightly from the video title. Looking through the source code I thought I found it with the function encodeFilename in utils.py. However, th... | How to get filename of file downloaded with Youtube-dl | I am using youtube-dl with a flask app to download a file and return the file. When I download the filename is changed slightly from the video title. Looking through the source code I thought I found it with the function encodeFilename in utils.py. However, this is still not a match and I can't return the file.
How cou... | [
"class FilenameCollectorPP(youtube_dl.postprocessor.common.PostProcessor):\n def __init__(self):\n super(FilenameCollectorPP, self).__init__(None)\n self.filenames = []\n\n def run(self, information):\n self.filenames.append(information['filepath'])\n return [], information\n \n... | [
6,
2
] | [] | [] | [
"python",
"youtube_dl"
] | stackoverflow_0064759263_python_youtube_dl.txt |
Q:
Do you query database data in model or view, Django
This is probably a dumb question here but bran new to Python/Django.
I've worked with many other frameworks and how the MVC works is in the model is where you make all your queries and then you grab them from the controller to send to the view.
In Django it's tel... | Do you query database data in model or view, Django | This is probably a dumb question here but bran new to Python/Django.
I've worked with many other frameworks and how the MVC works is in the model is where you make all your queries and then you grab them from the controller to send to the view.
In Django it's telling me to make these queries in the view.py file(a contr... | [
"According to Django's documentation the models.py file's purpose is to only declare tables. For example\nfrom django.db import models\n\nclass Person(models.Model):\n first_name = models.CharField(max_length=30)\n last_name = models.CharField(max_length=30)\n\nThis file would create the following SQL command... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074166513_django_python.txt |
Q:
Momentum does not work in my Gradient Descent algorithm
I am developing my ANN from scratch which is supposed to classify MNIST database of handwritten digits (0-9). My feed-forward fully connected ANN has to be composed of:
One input layer, with 28x28=784 nodes (that is, features of each image)
One hidden layer,... | Momentum does not work in my Gradient Descent algorithm | I am developing my ANN from scratch which is supposed to classify MNIST database of handwritten digits (0-9). My feed-forward fully connected ANN has to be composed of:
One input layer, with 28x28=784 nodes (that is, features of each image)
One hidden layer, with any number of neurons (shallow network)
One output laye... | [
"As mentioned by @xdurch0 the update rule is invalid\ndef update_weights(self, l_rate, momentum):\n self.weights = self.weights - l_rate * self.dE_dW + momentum * self.diff_w\n self.diff_w = np.copy(self.weights)\n\ndef update_bias(self, l_rate, momentum):\n self.bias = self.bias - l_rate * self.dE_db + mo... | [
1
] | [] | [] | [
"deep_learning",
"gradient_descent",
"machine_learning",
"neural_network",
"python"
] | stackoverflow_0074164897_deep_learning_gradient_descent_machine_learning_neural_network_python.txt |
Q:
Get absolute path of application from nested import
My application structure looks as followed:
main.py
modules
-- module.py
main.py imports module.py.
In module.py I want to fetch the absolute file path of main.py. What is the best and most efficient way to do this?
A:
If its always the same structure you can... | Get absolute path of application from nested import | My application structure looks as followed:
main.py
modules
-- module.py
main.py imports module.py.
In module.py I want to fetch the absolute file path of main.py. What is the best and most efficient way to do this?
| [
"If its always the same structure you can do:\nfrom pathlib import Path\n\nmain_script = Path(__file__).parent.parent / \"main.py\"\n\nIf it can be any level deep, you can iteratively go up parent folders until you find it\nsearch_dir = Path(__file__).parent\n\nwhile not (search_dir / \"main.py\").exists():\n se... | [
1
] | [] | [] | [
"path",
"python"
] | stackoverflow_0074166590_path_python.txt |
Q:
Lexing Lisp in Python
I have been interested by the Lisp language, and I decided to create my own dialect. This is going to be the most simple one to ever exist.
As you know, everything in Lisp is a list (or at least this dialect). A list consists of a command that comes at the start of it, and maybe arguments whi... | Lexing Lisp in Python | I have been interested by the Lisp language, and I decided to create my own dialect. This is going to be the most simple one to ever exist.
As you know, everything in Lisp is a list (or at least this dialect). A list consists of a command that comes at the start of it, and maybe arguments which are lists themselves. Us... | [
"A simple Lisp parser can be easy to implement, you can basically write a recursive descent top-down parser.\nYou have individual readers, like readers for integers, strings, symbols, whatever you want:\nclass Reader:\n\n def read_integer(self, stream):\n pass\n\n def read_string(self, stream):\n ... | [
1
] | [] | [] | [
"lisp",
"python"
] | stackoverflow_0074165987_lisp_python.txt |
Q:
How to store variables as unsigned 1024 bit integers and a function to add them in python
I know that the maximum size of integers modern machines can accommodate is
limited to 64 bits in unsigned long form. I need to implement a method that can add two 1024 bit unsigned
big integer numbers. Tried to construct an ... | How to store variables as unsigned 1024 bit integers and a function to add them in python | I know that the maximum size of integers modern machines can accommodate is
limited to 64 bits in unsigned long form. I need to implement a method that can add two 1024 bit unsigned
big integer numbers. Tried to construct an abstract data type (ADT) in the form of a class named MyBigInteger. Then addition method
def ad... | [
"As @Joanis said, Python integers may have infinite-size.\nFor example:\n (1<<1024).bit_length() returns 1025 \n (1<<1023)*2 == (1<<1024) returns True \n (1<<1024) / 1000 returns 1.797693134862316e+305 \n (1<<1024) returns 'OverflowError: int too large to convert to float' \n\nYou can do arithmetic operat... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074165520_python.txt |
Q:
Create a list using Python conditioning on a table column
I'm trying to create a list which have a values which are either zero or one (if the values in the table's column is Null or not). But my list only contains ones.
list = []
for i in range(len(df['DefaultDate'])):
if df['DefaultDate'][i] == 'nan':
list... | Create a list using Python conditioning on a table column | I'm trying to create a list which have a values which are either zero or one (if the values in the table's column is Null or not). But my list only contains ones.
list = []
for i in range(len(df['DefaultDate'])):
if df['DefaultDate'][i] == 'nan':
list.append(0)
else:
list.append(1)
print(list)
print(df['Def... | [
"You are checking for the string \"nan\", not for the special NaN values. You can replace that ENTIRE code sequence with:\nvalid = ~df['DefaultDate'].isnull()\n\n",
"Right now you compare your dataframe element with the string \"nan\". To check whether it is \"Not a Number\" (NaN) you have to compare it with num... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074166587_python.txt |
Q:
What is the time complexity of math.factorial() function in python?
Is there any way to reduce the time complexity of the factorial function below O(n), and what is the time complexity of its implementation in the math library in python?
Also, is any memorization done for some set of inputs (in Python 3), to furth... | What is the time complexity of math.factorial() function in python? | Is there any way to reduce the time complexity of the factorial function below O(n), and what is the time complexity of its implementation in the math library in python?
Also, is any memorization done for some set of inputs (in Python 3), to further reduce its runtime?
| [
"Python uses the divide-and-conquer method for computing factorials.\nSee if this helps.\n",
"If you do not mind floating point precision, math.lgamma(n+1) returns the natural logarithm of the factorial of n.\n"
] | [
3,
2
] | [] | [] | [
"algorithm",
"caching",
"python",
"python_3.x",
"time_complexity"
] | stackoverflow_0074162668_algorithm_caching_python_python_3.x_time_complexity.txt |
Q:
Django REST browser interface
I'm writing a set of REST services for a Django project. I've been using django-rest-framework for a while. Because of its limited functionality I had to switch to django-piston which I quite enjoy.
However, django-rest-framework had one really nice feature - it was able to display an... | Django REST browser interface | I'm writing a set of REST services for a Django project. I've been using django-rest-framework for a while. Because of its limited functionality I had to switch to django-piston which I quite enjoy.
However, django-rest-framework had one really nice feature - it was able to display an admin-like interface for testing t... | [
"This may seem obvious, but: \nWhy not just use Django's testing client (django.test.client.Client)? then instead of manually 'debugging' in your browser, you can write unit tests with expectations and get leverage out of those further down the track. \ne.g.\nfrom django.test.client import Client\nclient = Client... | [
8,
3,
0
] | [] | [] | [
"django",
"python",
"rest",
"testing",
"web_services"
] | stackoverflow_0005736868_django_python_rest_testing_web_services.txt |
Q:
ImportError: Couldn't import Django ... Did you forget to activate a virtual environment?
I know there are several questions/answers about this, but I can;t figure out what I should do.
I wanted to get started with Django and installed it with pip install and added Python37 and Python37-32 to my environmental var... | ImportError: Couldn't import Django ... Did you forget to activate a virtual environment? | I know there are several questions/answers about this, but I can;t figure out what I should do.
I wanted to get started with Django and installed it with pip install and added Python37 and Python37-32 to my environmental variables, and I guess it worked, because I can run several Python commands in my shell.
But ever... | [
"On the Windows machine, you should activate venv by this command .\\venv\\Scripts\\activate (please note, you should be in the folder where this venv is)\nThen inside activated venv install Django pip install django and in the same terminal run the server python manage.py runserver \n",
"I had similar issue in m... | [
6,
5,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"django",
"python",
"virtualenv"
] | stackoverflow_0057449908_django_python_virtualenv.txt |
Q:
How can one make a code that graphs an ellipse based on user input using matplotlib
I am a beginner in python and we currently have a required assessment that involves conic sections and matplotlib and I am trying to make a code that accepts user inputs(eg.The equation) and using those inputs it then outputs a gra... | How can one make a code that graphs an ellipse based on user input using matplotlib | I am a beginner in python and we currently have a required assessment that involves conic sections and matplotlib and I am trying to make a code that accepts user inputs(eg.The equation) and using those inputs it then outputs a graph of the input.
Here is my progress so far:
import sympy as sp
import matplotlib.pyplot ... | [
"\nAn ellipse can be drawn in different ways, I'll leave to the OP to find the relationship between the parameter they used and what I am using in the following code.\nIn [126]: from matplotlib.pyplot import show, subplots\n ...: from numpy import cos, linspace, pi, sin\n ...: \n ...: fig, ax = subplots... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074132265_matplotlib_python.txt |
Q:
Joining two dataframe df1 and df2 where date in df2 should be first date after date in df1 i.e earliest date after date in df1
--Problem statement description :-
I have two df - df1 and df2 . df1 contains data of quantity buy of id=7 and df2 contain data
of quantity sold of same id=7. Both df1 and df2 is sorted ac... | Joining two dataframe df1 and df2 where date in df2 should be first date after date in df1 i.e earliest date after date in df1 | --Problem statement description :-
I have two df - df1 and df2 . df1 contains data of quantity buy of id=7 and df2 contain data
of quantity sold of same id=7. Both df1 and df2 is sorted according to date i.e from
oldest to latest date and every time only 1 quantity is bought or sold.
--df1
date_buy
id
qty_buy
rolli... | [
"I cannot get the complete answer, but it might help a little:\npd.merge_asof is essentially merging on the closest datetime. If you format you DataFrame as datetime64[ns]\ndf1[\"date_sold\"] = pd.to_datetime(df1[\"date_sold\"], format=\"%d-%m-%Y\", exact=False)\ndf2[\"date_sold\"] = pd.to_datetime(df2[\"date_sold\... | [
1
] | [] | [] | [
"dataframe",
"date",
"for_loop",
"pandas",
"python"
] | stackoverflow_0074165087_dataframe_date_for_loop_pandas_python.txt |
Q:
how do i get the frame to fill the screen om tkinter
im creating a quiz for my computer science project and i am unable to get the customtkinter background to fill the whole screen
here is a screenshotenter image description here
and here is my code:
from tkinter import*
import customtkinter
import tkinter as tk
f... | how do i get the frame to fill the screen om tkinter | im creating a quiz for my computer science project and i am unable to get the customtkinter background to fill the whole screen
here is a screenshotenter image description here
and here is my code:
from tkinter import*
import customtkinter
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
cl... | [
"Why don't you try to put inside pack(): fill and expand options? Here is the change.\nfrom tkinter import*\nimport customtkinter\nimport tkinter as tk\nfrom tkinter import ttk\nfrom PIL import ImageTk, Image\n\n\nclass homepage(customtkinter.CTkFrame):\n def __init__(self, master):\n customtkinter.CT... | [
1
] | [] | [] | [
"customtkinter",
"python",
"tkinter"
] | stackoverflow_0073680886_customtkinter_python_tkinter.txt |
Q:
pyenv: poetry itself, running on older python version, what to do?
Update:
Which Python should I use to install poetry?
System Python: That is an excellent idea. Once, however, poetry self update was trying to update a system package without the necessary permissions.
Pyenv: A good solution. Nonetheless, if Pytho... | pyenv: poetry itself, running on older python version, what to do? | Update:
Which Python should I use to install poetry?
System Python: That is an excellent idea. Once, however, poetry self update was trying to update a system package without the necessary permissions.
Pyenv: A good solution. Nonetheless, if Python is updated and the old installation is deleted, poetry will stop worki... | [
"By default Poetry will use the Python version used during it installation to create a new venv.\nSet the (experimental) config option virtualenvs.prefer-active-python to true, if you want Poetry to pick up the current activated Python version.\nAs an alternative to this option, run poetry env use </path/to/python>... | [
1,
0
] | [] | [] | [
"pyenv",
"python",
"python_3.x",
"python_poetry"
] | stackoverflow_0074044291_pyenv_python_python_3.x_python_poetry.txt |
Q:
Select DateTime mysql query in python
I have the following table in my MySQL database:
id
teplota
created_at
1
12.521
2017-02-01 17:49:53
1
12.852
2017-02-02 17:50:53
1
12.852
2017-02-03 17:50:53
...
...
...
Column created_at has type timestamp, here is the column definition in my CREATE TABLE statement:
cre... | Select DateTime mysql query in python | I have the following table in my MySQL database:
id
teplota
created_at
1
12.521
2017-02-01 17:49:53
1
12.852
2017-02-02 17:50:53
1
12.852
2017-02-03 17:50:53
...
...
...
Column created_at has type timestamp, here is the column definition in my CREATE TABLE statement:
created_at TIMESTAMP DEFAULT CURRE... | [
"I had the same problem and used ' around %s to solve it:\nsql_query = \"select * from ts2 where created_at >= '%s' and created_at < '%s';\" % (t1, t2)\nc.execute(sql_query)\n\n",
"You missed '' on the %s\nShould be\nc.execute(\"select * from ts2 where created_at >= '%s' and created_at < '%s';\" % (t1, t2)) \n",
... | [
1,
1,
0
] | [
"Try Converting to iso format :\nt1 = datetime.datetime(2017, 2, 1)\nt2 = datetime.datetime(2017, 2, 2)\nt1 = str(t1.isoformat())\nt2 = str(t2.isoformat())\nc.execute(\"select * from ts2 where created_at >= %s and created_at < %s;\" % (t1, t2)) \nisoformat\n\n",
"t1 = datetime.datetime(2017, 2, 1)\nt2 = datetime.... | [
-1,
-1
] | [
"datetime",
"mysql",
"python",
"sql"
] | stackoverflow_0042045634_datetime_mysql_python_sql.txt |
Q:
Persisting data between script execution
I was wondering if python has a simple method for caching a sequence of values, where the sequence can be updated each time the script is run. For example, let's say I have a list of tuples where each tuple is a datetime and a float. The datetime represents the time a speed... | Persisting data between script execution | I was wondering if python has a simple method for caching a sequence of values, where the sequence can be updated each time the script is run. For example, let's say I have a list of tuples where each tuple is a datetime and a float. The datetime represents the time a speed was recorded by an anemometer and the float i... | [
"You can append to pickle files. I don't know if that is simple enough:\nimport pickle\nimport datetime\n\ndb_path = \"speeds.p\"\n\ndef data_from_endpoint():\n data = (\n (datetime.datetime(2022, 10, 22, 21, 15), 13),\n (datetime.datetime(2022, 10, 22, 21, 30), 24),\n (datetime.datetime(202... | [
1,
1
] | [
"There is no real \"standard\" way for Python to store data.\nConsider that:\n\nYour program needs a location for its file.\nIt needs write permissions in that location.\nIf you use the current working directory, it will fail to find the file when it is started from another location.\nIf your program needs to work ... | [
-1
] | [
"python"
] | stackoverflow_0074166231_python.txt |
Q:
Create a function to remove punctuation from the left and right of a string. Ex: "_cat's_" becomes "cat's"
I already have started the function as seen below. At first i didn't include the .strip() module but after research I did because i thought it would remove the characters from the beginning and end of the str... | Create a function to remove punctuation from the left and right of a string. Ex: "_cat's_" becomes "cat's" | I already have started the function as seen below. At first i didn't include the .strip() module but after research I did because i thought it would remove the characters from the beginning and end of the string.
import string
def detect_word(source, word):
source = source.strip().lower()
word = word.strip().l... | [
"str.strip() strips whitespace by default. Pass string.punctuation as an argument to make it strip punctuation instead.\n>>> \"_cat's_\".strip()\n\"_cat's_\"\n>>> \"_cat's_\".strip(string.punctuation)\n\"cat's\"\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074166866_python.txt |
Q:
My break function isn't working and i dont know why its outside the loop
I am relatively new to code and have been messing around with some functions, i am currently using it for school work and have been practicing code for my course work, however when i tried to do this random code the break function was outside... | My break function isn't working and i dont know why its outside the loop | I am relatively new to code and have been messing around with some functions, i am currently using it for school work and have been practicing code for my course work, however when i tried to do this random code the break function was outside of the loop somehow but i dont know why, any ideas?
var=input("what name woul... | [
"The code you actually wanted to write goes as follows:\ndef rep():\n for i in range(0, varf):\n print(var[:i])\n \n for x in range(0, varf):\n print(var[x:])\n\nwhile True: \n var=input(\"what name would you like to use?: \")\n varf= len(var) + 1\n rep()\n repeat=input(\"Would you like to go... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074166782_python.txt |
Q:
NotImplementedError: Initial conditions produced too many solutions for constants [SymPy]
I attempted to solve this differential equation by adapting the code found here.
import sympy as sp
t = sp.symbols('t', real=True)
x = sp.Function('x', real=True)
diffeq = sp.Eq(x(t).diff(t), sp.sqrt(1 - x(t)**2))
res = sp... | NotImplementedError: Initial conditions produced too many solutions for constants [SymPy] | I attempted to solve this differential equation by adapting the code found here.
import sympy as sp
t = sp.symbols('t', real=True)
x = sp.Function('x', real=True)
diffeq = sp.Eq(x(t).diff(t), sp.sqrt(1 - x(t)**2))
res = sp.dsolve(diffeq, ics={x(0): 0})
The math.se post suggests that a piecewise function satisfies t... | [
"First, the solver treats the equation as algebraic, that is, it solves x'²=1-x², and it does not get the piecewise solution that are possible, only the fully analytical.\nFor some reason returning a tuple of possible solutions is not implemented, you can do that manually, see https://stackoverflow.com/a/46979535/3... | [
1
] | [] | [] | [
"differential_equations",
"equation_solving",
"math",
"python",
"sympy"
] | stackoverflow_0074165228_differential_equations_equation_solving_math_python_sympy.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.