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:
Combine several columns into one column when there is only one value per row
I have this df with only one value per column between y1 and y4
x y1 y2 y3 y4
0 -17.7 -0.785430 NaN NaN NaN
1 -15.0 NaN NaN NaN -3820.085000
2 -12.... | Combine several columns into one column when there is only one value per row | I have this df with only one value per column between y1 and y4
x y1 y2 y3 y4
0 -17.7 -0.785430 NaN NaN NaN
1 -15.0 NaN NaN NaN -3820.085000
2 -12.5 NaN NaN 2.138833 NaN
I want to combine all y columns i... | [
"Let us try groupby with first\nout = df.groupby(df.columns.str[0],axis=1).first()\nOut[60]: \n x y\n0 -17.7 -0.785430\n1 -15.0 -3820.085000\n2 -12.5 2.138833\n\n",
"Another possible solution:\ndf.assign(y = df.iloc[:,1:].sum(axis=1)).dropna(axis=1)\n\nOutput:\n x y\n0 -17.7... | [
4,
3,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074495928_dataframe_pandas_python.txt |
Q:
python interpreter from spyder works but python from console has no modules found
I need to run Python 3.8 for my ROS2 installation on Ubuntu 22.04.
When I open Spyder it defaults to Python 3.10.6 and all the scripts work, however when I run Python from the console it uses Python 3.8.15 and no modules are found.
H... | python interpreter from spyder works but python from console has no modules found | I need to run Python 3.8 for my ROS2 installation on Ubuntu 22.04.
When I open Spyder it defaults to Python 3.10.6 and all the scripts work, however when I run Python from the console it uses Python 3.8.15 and no modules are found.
How do I ensure that all pip installations can be seen by Python 3.8?
update-alternative... | [
"I've found a solution that works for me.\nFrom the console, install each module specifically for the required python version:\npython3.8 -m pip install <module>\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"python_3.8"
] | stackoverflow_0074497339_pip_python_python_3.8.txt |
Q:
Syntax confusion with class
This is the given code:
class Person:
def __init__(self, name):
self.name = name
def greeting(self):
return "hi, my name is " + self.name
some_person = Person("yeabsira")
print(some_person.greeting())
However, I was expecting the syntax in which the constructo... | Syntax confusion with class | This is the given code:
class Person:
def __init__(self, name):
self.name = name
def greeting(self):
return "hi, my name is " + self.name
some_person = Person("yeabsira")
print(some_person.greeting())
However, I was expecting the syntax in which the constructor method uses like:
class Name:
... | [
"some_person.name returns the value of the person's name, while some_person.greeting() returns a greeting with the name, it is just a function defined within the class Person and works normally like any other function. You could use some_person.name if you only need the name.\nHowever, by using some_person.greeting... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074497540_python.txt |
Q:
Scraping what's inside the links
I don't really have code for this problem. But I will try my best to actually explain everything.
alright, say you are scraping a website, and in the website there are 3 different links and you want to scrape what is inside each and everyone one of them without having to manually ... | Scraping what's inside the links | I don't really have code for this problem. But I will try my best to actually explain everything.
alright, say you are scraping a website, and in the website there are 3 different links and you want to scrape what is inside each and everyone one of them without having to manually do it. Is this possible for just Beaut... | [
"you can scrape the links via tag. The html template will have the hyperlink listed and the actual website it links you to should be listed in href. Ex:\n<li href=“https://google.com > Site 1 </li> \nThe href would be the destination link and the site 1 is just the text shown in page\n",
"\nscrape the website, an... | [
0,
0
] | [
"You can do it with only requests and BeautifulSoup. Just add the links to a list or a dict and iterate the list.\n"
] | [
-1
] | [
"python",
"web_scraping"
] | stackoverflow_0074420235_python_web_scraping.txt |
Q:
SQLAlchemy: AttributeError: 'Connection' object has no attribute 'commit'
When using SQLAlchemy (version 1.4.44) to create, drop or otherwise modify tables, the updates don't appear to be committing. Attempting to solve this, I'm following the docs and using the commit() function. Here's a simple example
from sq... | SQLAlchemy: AttributeError: 'Connection' object has no attribute 'commit' | When using SQLAlchemy (version 1.4.44) to create, drop or otherwise modify tables, the updates don't appear to be committing. Attempting to solve this, I'm following the docs and using the commit() function. Here's a simple example
from sqlalchemy import create_engine, text
engine = create_engine("postgresql://user:... | [
"The comment on the question is correct you are looking at the 2.0 docs but all you need to do is set future=True when calling create_engine() to use the \"commit as you go\" functionality provided in 2.0.\nSEE migration-core-connection-transaction\n\nWhen using 2.0 style with the create_engine.future flag, “commit... | [
2
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074495598_python_sqlalchemy.txt |
Q:
Keep the row for which the values of two columns match by group otherwise keep the first row by group
I wanted to left join df2 on df1 and then keep the row that matches by group and if there is no matching group then I would like to keep the first row of the group in order to achieve df3 (the desired result). I w... | Keep the row for which the values of two columns match by group otherwise keep the first row by group | I wanted to left join df2 on df1 and then keep the row that matches by group and if there is no matching group then I would like to keep the first row of the group in order to achieve df3 (the desired result). I was hoping you guys could help me with finding the optimal solution.
Here is my code to create the two dataf... | [
"Store the first value (a groupby might not be necessary if every single one in market is 'SP'), merge and fill with the first value:\nfill_value = df2.groupby('market').client.first()\n\n# if you are interested in filtering for None:\nfill_value = df2.set_index('market').loc[lambda df: df.underlying.isna(), 'clien... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074495249_numpy_pandas_python.txt |
Q:
f(x)= number of ones in x . find the highest and average fitness for genetic algorithm , Alternate option to Map and reduce in python
i am trying to write a code which takes input as below and then find the highest and average where f(x)= number of ones in x .
['00111110011001010011', '01111101001101110010', '0110... | f(x)= number of ones in x . find the highest and average fitness for genetic algorithm , Alternate option to Map and reduce in python | i am trying to write a code which takes input as below and then find the highest and average where f(x)= number of ones in x .
['00111110011001010011', '01111101001101110010', '01100110111110000000', '01101101100111001001']
def fitness(genome):
return reduce((lambda x, y: int(x) + int(y)), list(genome))
# referen... | [
"A way using numpy.\nimport numpy as np\nlst = ['00111110011001010011', '01111101001101110010', '01100110111110000000', '01101101100111001001']\npopulation = np.fromiter(''.join(lst), dtype=np.int).reshape(len(lst), -1)\nmax_sum_over_row = population.sum(1).max()\navg_sum_over_row = population.mean(0).sum()\n\n"
] | [
0
] | [] | [] | [
"fitness",
"genetic_algorithm",
"python"
] | stackoverflow_0074497629_fitness_genetic_algorithm_python.txt |
Q:
Cumulative sum based on date not working as expected
My target on daily basis is 250. For any given date, if the cum-daily_result has reached 250 then subsequent rows should have only 250 as expected results
Input table:
col1 col2 col3
0 a 250 250
1 a 250 500
2 a -1290 -... | Cumulative sum based on date not working as expected | My target on daily basis is 250. For any given date, if the cum-daily_result has reached 250 then subsequent rows should have only 250 as expected results
Input table:
col1 col2 col3
0 a 250 250
1 a 250 500
2 a -1290 -790
3 b -1392 -1392
4 b 250 -1142
5 ... | [
"I have a less elegant solution, but it worked for me.\nidx = df[df['col3'] >= 250].groupby('col1').head(1).index\ndf.loc[idx, 'col4'] = 1\ndf['col4']=df['col3']*df['col4']\ndf['col4'] = df.groupby('col1')['col4'].ffill()\ndf['col4']=df['col4'].fillna(df['col3']).astype('int')\n\n"
] | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074497085_numpy_pandas_python.txt |
Q:
Django manage.py migrate errors
I've been working on a project for CS50-Web for a while now and I was changing some of my models trying to add a unique attribute to some things. Long story short it wasn't working how I wanted so I went back to how I had it previously and now something is wrong and I can get it to ... | Django manage.py migrate errors | I've been working on a project for CS50-Web for a while now and I was changing some of my models trying to add a unique attribute to some things. Long story short it wasn't working how I wanted so I went back to how I had it previously and now something is wrong and I can get it to migrate the changes to the model. I d... | [
"Just try these 3 commands for migrations:\npython manage.py makemigrations appname\n\npython manage.py sqlmigrate appname 0001 #This value will generate afte makemigrations. it can be either 0001, 0002 or more.\n\npython manage.py migrate\n\nAnd see if it solves this error\n"
] | [
0
] | [] | [] | [
"cs50",
"django",
"python"
] | stackoverflow_0074497270_cs50_django_python.txt |
Q:
bash: worker:: command not found on koyeb
I tried to deploy this botto koyeb but I got this error
bash: worker:: command not found
ERROR: failed to determine the run command to launch your application: add a run command in your Service configuration or create a procfile in your git repository.
procfile in bot rep... | bash: worker:: command not found on koyeb | I tried to deploy this botto koyeb but I got this error
bash: worker:: command not found
ERROR: failed to determine the run command to launch your application: add a run command in your Service configuration or create a procfile in your git repository.
procfile in bot repo
worker: python -m bot
I have no idea what to... | [
"\nbash: worker:: command not found\n\n\nThe double : colon suggests that\nyou intended to run e.g. /usr/bin/worker\nbut bash attempted to execute /usr/bin/worker:\nand found no file by that name.\nRevise your command so it has fewer colons.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074497684_python.txt |
Q:
How to automatically unpack list that contains some 0 values?
When I try to unpack a list data for a MySQL database query that has some columns with value 0, I get an error.
Name (varchar)
Apples(int)
Candies(int)
Color (varchar)
John
5
0
Blue
If I unpack my query result like:
name, apples, candies, color = myl... | How to automatically unpack list that contains some 0 values? | When I try to unpack a list data for a MySQL database query that has some columns with value 0, I get an error.
Name (varchar)
Apples(int)
Candies(int)
Color (varchar)
John
5
0
Blue
If I unpack my query result like:
name, apples, candies, color = mylist
I'll get a NoneType error because candies values (in t... | [
"You can still using unpacking, just fix up the None values afterward.\nname, apples, candies, color = mylist\nif apples is None:\n apples = 0\nif candies is None:\n candies = 0\n\nIf you have lots of columns to fix, you can use a list comprehension to fix up all the None values in the list.\nmylist = [0 if x... | [
1
] | [] | [] | [
"iterable_unpacking",
"mysql",
"python"
] | stackoverflow_0074497706_iterable_unpacking_mysql_python.txt |
Q:
got ZeroDivisionError: float division by zero
So i make a streamlit app and implemented some math formula
import streamlit as st
st.title("SISTEM PERSAMAAN LINEAR DUA VARIABEL")
st.subheader("Persamaan 1: ax+by=c")
a = st.number_input("Masukan Nilai Variabel a")
b = st.number_input("Masukan Nilai Variabel b")
c =... | got ZeroDivisionError: float division by zero | So i make a streamlit app and implemented some math formula
import streamlit as st
st.title("SISTEM PERSAMAAN LINEAR DUA VARIABEL")
st.subheader("Persamaan 1: ax+by=c")
a = st.number_input("Masukan Nilai Variabel a")
b = st.number_input("Masukan Nilai Variabel b")
c = st.number_input("Masukan Nilai Variabel c")
st.sub... | [
"The default value of number_input is 0. Hence, when you first start the app, c, q, r, b, a, q, p, b is all 0. It would be quite obvious to see that (a*q-p*b) is 0, and hence it will result a Zero Division Error.\nA solution to this is to add an if statement to check if the value of (a*q-p*b) is 0. Refer to the cod... | [
1
] | [] | [] | [
"python",
"streamlit"
] | stackoverflow_0074497484_python_streamlit.txt |
Q:
determine if datetime index is within a list of date ranges
i have the following code data...
import pandas as pd, numpy as np
from datetime import datetime
end_dt = datetime.today()
st_dt = (end_dt + pd.DateOffset(-10)).date()
df_index = pd.date_range(st_dt, end_dt)
df = pd.DataFrame(index=df_index, columns=['in_... | determine if datetime index is within a list of date ranges | i have the following code data...
import pandas as pd, numpy as np
from datetime import datetime
end_dt = datetime.today()
st_dt = (end_dt + pd.DateOffset(-10)).date()
df_index = pd.date_range(st_dt, end_dt)
df = pd.DataFrame(index=df_index, columns=['in_range'])
data = [pd.to_datetime(['2022-11-08','2022-11-10']), pd... | [
"Use merge_asof and boolean indexing:\ns = df.index.to_series()\nm = (pd.merge_asof(s.rename('st_dt'), dt_ranges)\n ['end_dt'].ge(s.to_numpy()).to_numpy()\n )\n\ndf.loc[m, 'in_range'] = True\n\nNB. The intervals in dt_ranges should be non-overlapping.\nOutput:\n in_range\n2022-11-08 True\n2022... | [
4,
3
] | [] | [] | [
"data_science",
"numpy",
"pandas",
"python"
] | stackoverflow_0074495142_data_science_numpy_pandas_python.txt |
Q:
xml parsing with extra '\n' and whitespaces using lxml library
I wrote a python program with lxml library to parse a xml file using its xpath. The value and xpath are all correct but it returns many '\n' and white spaces just like the xml file's formatting.
here is my code:
from lxml import etree
from xml.dom imp... | xml parsing with extra '\n' and whitespaces using lxml library | I wrote a python program with lxml library to parse a xml file using its xpath. The value and xpath are all correct but it returns many '\n' and white spaces just like the xml file's formatting.
here is my code:
from lxml import etree
from xml.dom import minidom
#data = minidom.parse('D:/LocalSpark/bitmap.xml')
sigx... | [
"There are many ways to strip spaces and newlines, however, a simple technique would be to use regex to remove them.\nThe critical line is this one:\nint(re.sub(r'[\\\\n\\s]*', '', node.text))\n\nWhich searches and substitutes all carriage returns and spaces in node.text and converts them to '' nothing. Then cast t... | [
0
] | [] | [] | [
"elementtree",
"lxml",
"python",
"python_3.x",
"xml_parsing"
] | stackoverflow_0074497687_elementtree_lxml_python_python_3.x_xml_parsing.txt |
Q:
Copying columns into from worksheet into separate Excel files with Python
Sorry I am new to openpyxl and pandas and I am looking to take the columns of one excel sheet and create separate workbooks containing the first column and one column from the sheet.
| Column A | Column B |Column C |
| -------- | -------- |-... | Copying columns into from worksheet into separate Excel files with Python | Sorry I am new to openpyxl and pandas and I am looking to take the columns of one excel sheet and create separate workbooks containing the first column and one column from the sheet.
| Column A | Column B |Column C |
| -------- | -------- |-------- |
| Cell 1 | Cell 2 | Cell 5 |
| Cell 3 | Cell 4 | Cell 6 |
... | [
"If my assumption of your requirement is correct, the usual way is to copy the required columns to a new excel file and save. There are many questions/answers on how to do this on SO just need to search.\n\nThis is an example uses the different angle of deleting the unwanted columns so that only the two columns you... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"pandas",
"python"
] | stackoverflow_0074493230_excel_openpyxl_pandas_python.txt |
Q:
NTEventLogHandler and "The description cannot be found"
When trying to log something using NTEventLogHandler, I get the following message in "View Events":
"The description for Event ID ( 1 ) in Source ( Python Logging Test ) cannot be found. The local computer may not have the necessary registry information or me... | NTEventLogHandler and "The description cannot be found" | When trying to log something using NTEventLogHandler, I get the following message in "View Events":
"The description for Event ID ( 1 ) in Source ( Python Logging Test ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. .... | [
"As mentioned in the documentation about the dllname parameter:\n\nThe dllname should give the fully qualified pathname of a .dll or .exe which contains message definitions to hold in the log (if not specified, 'win32service.pyd' is used - this is installed with the Win32 extensions and contains some basic placehol... | [
0
] | [] | [] | [
"event_log",
"logging",
"python",
"windows"
] | stackoverflow_0074490112_event_log_logging_python_windows.txt |
Q:
Function does not print the randomness of two other functions. NameError: the name 'x' is not defined
I have a problem with the All function. I would like to use the random result of the Template1 function and the random result of the Template2 function. Then I apply another random to the two functions inside All,... | Function does not print the randomness of two other functions. NameError: the name 'x' is not defined | I have a problem with the All function. I would like to use the random result of the Template1 function and the random result of the Template2 function. Then I apply another random to the two functions inside All, but I get the error:
NameError: the name 'Template1' is not defined
How can I fix? By solving the definit... | [
"Remove all the print() calls from your methods. They're setting the return variables to None, since print() prints its argument, it doesn't return it.\nTo see the result, use print(final.All()) at the end.\nimport random\n\nclass Main:\n\n def __init__(self):\n self.templ1 = (\"aaa\", \"bbb\", \"ccc\")\n... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074497758_python_python_3.x.txt |
Q:
CSRF verification failed when used csrf_token and CSRF_TRUSTED_ORIGINS
I try to change my profile but when i subbmit my form, it shows CSRF verification failed even when i used csrf_token and CSRF_TRUSTED_ORIGINS.
Here is my models:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=... | CSRF verification failed when used csrf_token and CSRF_TRUSTED_ORIGINS | I try to change my profile but when i subbmit my form, it shows CSRF verification failed even when i used csrf_token and CSRF_TRUSTED_ORIGINS.
Here is my models:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
avatar = mod... | [
"Simply try to add type to button tag because when you set action to form tag then you must add type to button tag or input tag.\nchange this:\n<button name=\"submit\">save changes</button>\n\nTo this:\n <button type=\"submit\">save changes</button>\n\nAnd see if it solves\n"
] | [
0
] | [] | [] | [
"csrf",
"django",
"html",
"post",
"python"
] | stackoverflow_0074497521_csrf_django_html_post_python.txt |
Q:
Checking if an element exists with Python Selenium
I have a problem; I am using the Selenium (Firefox) web driver to open a webpage, click a few links, etc., and then capture a screenshot.
My script runs fine from the CLI, but when run via a cron job it is not getting past the first find_element() test. I need to ... | Checking if an element exists with Python Selenium | I have a problem; I am using the Selenium (Firefox) web driver to open a webpage, click a few links, etc., and then capture a screenshot.
My script runs fine from the CLI, but when run via a cron job it is not getting past the first find_element() test. I need to add some debug, or something to help me figure out why i... | [
"For a):\nfrom selenium.common.exceptions import NoSuchElementException\ndef check_exists_by_xpath(xpath):\n try:\n webdriver.find_element_by_xpath(xpath)\n except NoSuchElementException:\n return False\n return True\n\nFor b): Moreover, you can take the XPath expression as a standard through... | [
165,
106,
68,
26,
8,
6,
2,
1,
1,
1,
0,
0,
0
] | [
"el = WebDriverWait(driver, timeout=3).until(lambda d: d.find_element(By.TAG_NAME,\"p\"))\n\ndoc\n"
] | [
-1
] | [
"html",
"python",
"selenium",
"webdriver"
] | stackoverflow_0009567069_html_python_selenium_webdriver.txt |
Q:
import janitor as jn TypeError: 'type' object is not subscriptable
after sucessfully downloading the module
!pip install pyjanitor # works successfully
import janitor as jn # which worked just fine in the past, but suddenly throwing the following TypeError
TypeError: 'type' object is not subscriptable
I am usi... | import janitor as jn TypeError: 'type' object is not subscriptable | after sucessfully downloading the module
!pip install pyjanitor # works successfully
import janitor as jn # which worked just fine in the past, but suddenly throwing the following TypeError
TypeError: 'type' object is not subscriptable
I am using google colab.
I also tried just import janitor instead of import jani... | [
"I think that's the package's error.\nAnother person also reported the error that he can't import the package.\nhttps://github.com/pyjanitor-devs/pyjanitor/issues/1201\nWait for the fix.\nUntil the fix is released, use the previous package.\nTo remove the current pyjanitor in jupyter\n!pip uninstall pyjanitor --yes... | [
1
] | [] | [] | [
"pyjanitor",
"python"
] | stackoverflow_0074497801_pyjanitor_python.txt |
Q:
How to group list items based on a specific condition?
I have this text:
>A1
KKKKKKKK
DDDDDDDD
>A2
FFFFFFFF
FFFFOOOO
DAA
>A3
OOOZDDD
KKAZAAA
A
When I split it and remove the line jumps, I get this list:
It gives me a list that looks like this:
['>A1', 'KKKKKKKK', 'DDDDDDDD', '>A2', 'FFFFFFFF', 'FFFFOOOO', 'DAA'... | How to group list items based on a specific condition? | I have this text:
>A1
KKKKKKKK
DDDDDDDD
>A2
FFFFFFFF
FFFFOOOO
DAA
>A3
OOOZDDD
KKAZAAA
A
When I split it and remove the line jumps, I get this list:
It gives me a list that looks like this:
['>A1', 'KKKKKKKK', 'DDDDDDDD', '>A2', 'FFFFFFFF', 'FFFFOOOO', 'DAA', '>A3', 'OOOZDDD', 'KKAZAAA', 'A']
I'm trying to merge all... | [
"You can use itertools.groupby for the task:\nfrom itertools import groupby\n\nlst = [\n \">A1\",\n \"KKKKKKKK\",\n \"DDDDDDDD\",\n \">A2\",\n \"FFFFFFFF\",\n \"FFFFOOOO\",\n \"DAA\",\n \">A3\",\n \"OOOZDDD\",\n \"KKAZAAA\",\n \"A\",\n]\n\nout = []\nfor k, g in groupby(lst, lambda s... | [
1,
1,
0
] | [] | [] | [
"list",
"python",
"split"
] | stackoverflow_0074497110_list_python_split.txt |
Q:
Seven segment display in Tkinter
I am trying to create a GUI using Tkinter with Python 2.7. This must have a seven segment display or something similar to dynamically display values in accordance with a variable. Is there any way to create a seven segment display apart from a manual graphical design (that would sl... | Seven segment display in Tkinter | I am trying to create a GUI using Tkinter with Python 2.7. This must have a seven segment display or something similar to dynamically display values in accordance with a variable. Is there any way to create a seven segment display apart from a manual graphical design (that would slow down the entire system)?
| [
"I don't know what you mean by 'maunal graphical design' but here is a single hex diget display designed to be easily upgraded to more digits. It will not slow the system noticeably.\n'''Seven segment display of hex digits.'''\nimport tkinter as tk\nroot = tk.Tk()\nscreen = tk.Canvas(root)\nscreen.grid()\n\n# Orde... | [
9,
0
] | [] | [] | [
"python",
"python_2.7",
"tkinter"
] | stackoverflow_0035551962_python_python_2.7_tkinter.txt |
Q:
auto remove value or string from list if it start with
how can i remove the similar value from list if it start with and keep
one of the value if it has alot of
for example this is my code
list_ph = ['8002378990','8001378990','8202378990','8002378920','8002375990','8002378990','8001378890','8202398990']
so this ... | auto remove value or string from list if it start with | how can i remove the similar value from list if it start with and keep
one of the value if it has alot of
for example this is my code
list_ph = ['8002378990','8001378990','8202378990','8002378920','8002375990','8002378990','8001378890','8202398990']
so this value sould return 3 value when it will remove the value
if ... | [
"Here is how I would approach this problem.\nI would first create two empty lists, one for comparing the first five digits, and the other to save your result, say\nfirst_five = []\nres = []\n\nNow, I would loop through all the entries in your list_ph and add the number to res if the first five digits are not alread... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074497888_python_python_3.x.txt |
Q:
downloading CSV file in python using pandas
I am trying to download a csv file to python. For some reason I can not do it. I suppose I need to add an additional argument to read_csv?
import pandas as pd
url = "https://raw.githubusercontent.com/UofGAnalyticsData/"\
"DPIP/main/assesment_datasets/assessmen... | downloading CSV file in python using pandas | I am trying to download a csv file to python. For some reason I can not do it. I suppose I need to add an additional argument to read_csv?
import pandas as pd
url = "https://raw.githubusercontent.com/UofGAnalyticsData/"\
"DPIP/main/assesment_datasets/assessment3/starwars.csv"
df = pd.read_csv(url)
| [
"The code you attempt is downloading the content from the url and pasting it in the data frame named 'df'.\nYou need to save the output csv by using the following line. You will find the output file in the same directory where the python script is saved.\nimport pandas as pd\n\nurl = \"https://raw.githubusercontent... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074492049_pandas_python.txt |
Q:
Using pycryptodome to decrypt encrypted data
I'm new to encryption/decryption, but I have sensitive data that I need to store as encrypted data. Our ETL has a built in encryption process which outputs the following
{
"data":{
"transformation":"AES/GCM/noPadding",
"iv":"jlemHiOD8uiyMsqY",
"type... | Using pycryptodome to decrypt encrypted data | I'm new to encryption/decryption, but I have sensitive data that I need to store as encrypted data. Our ETL has a built in encryption process which outputs the following
{
"data":{
"transformation":"AES/GCM/noPadding",
"iv":"jlemHiOD8uiyMsqY",
"type":"JSON",
"ciphertext":"TOtsmTYG1jKCZXewFNPB... | [
"You need to pass the data in bytes format. Your aes_iv and test_encrypted_value is in the base64 format, while your aes_key is in the hex format. In order to use it, you must first convert those to bytes.\nbyte_key = codecs.decode(aes_key, 'hex_codec')\nbase64_iv = base64.b64decode(aes_iv)\nbase64_encrypted_value ... | [
1
] | [] | [] | [
"aes",
"encryption",
"pycryptodome",
"python"
] | stackoverflow_0074497776_aes_encryption_pycryptodome_python.txt |
Q:
Capturing columns with similar patterns with Python regex
I'm scraping a pdf using regex and Python. The patterns repeat through each column. I don't understand how to target each column of information separately.
Text string:
2000 2001 2002 2003\n
14,756 10,922 9,745 12,861\n
9,882 11,568 8,176 10,483\n
13,925 1... | Capturing columns with similar patterns with Python regex | I'm scraping a pdf using regex and Python. The patterns repeat through each column. I don't understand how to target each column of information separately.
Text string:
2000 2001 2002 2003\n
14,756 10,922 9,745 12,861\n
9,882 11,568 8,176 10,483\n
13,925 10,724 10,032 8,927\n
I need to return the data by year like:
[... | [
"I am afraid it is impossible to capture columns, but you can combine regex with matching the groups of the columns and transpose with zip.\n(?:^|\\n)([\\d,]+)\\s([\\d,]+)\\s([\\d,]+)\\s([\\d,]+)(?:$|\\n)\n\nSee how this regex works.\nimport re\n\ntext = \"\"\"2000 2001 2002 2003\n14,756 10,922 9,745 12,861\n9,882 ... | [
1
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074497037_python_web_scraping.txt |
Q:
Why does my Pygame window flicker when animating objects?
So my pygame window just won't stop flickering. I know if only one item is in snake.snakearray, it won't flicker.
#class for the array
class snake:
snakearray = [[ScreenConfigs.width / 2,ScreenConfigs.height / 2],[ScreenConfigs.width / 2,ScreenConfigs.hei... | Why does my Pygame window flicker when animating objects? | So my pygame window just won't stop flickering. I know if only one item is in snake.snakearray, it won't flicker.
#class for the array
class snake:
snakearray = [[ScreenConfigs.width / 2,ScreenConfigs.height / 2],[ScreenConfigs.width / 2,ScreenConfigs.height / 2]]
direction = "up"
increment = 0.1
#loop to draw t... | [
"Multiple calls to pygame.display.update() or pygame.display.flip() causes flickering. Updating the display once at the end of the application loop is sufficient. But you also need to clear the display only once before drawing the scene:\nwhile Running:\n # [...]\n\n # clear display \n pygame.draw.rect(dis... | [
3
] | [] | [] | [
"flicker",
"pygame",
"python",
"python_3.x"
] | stackoverflow_0074496592_flicker_pygame_python_python_3.x.txt |
Q:
ValueError: Could not find matching concrete function to call loaded from the SavedModel
I am trying to build a model for crop identification and keep getting this error:
import tensorflow as tf
import tensorflow_hub as hub
#Read crop details
import pandas as pd
crop_details_csv = pd.read_excel('/content/drive/... | ValueError: Could not find matching concrete function to call loaded from the SavedModel | I am trying to build a model for crop identification and keep getting this error:
import tensorflow as tf
import tensorflow_hub as hub
#Read crop details
import pandas as pd
crop_details_csv = pd.read_excel('/content/drive/MyDrive/Crop Identification/Crop_details.xlsx')
crop_details_csv.head()
#Get imamges filepat... | [
"I was able to replicate the error using Agriculture crop images dataset.\nYou must change the image size from 224 to 128 because the mobilenet_v2_035_128 model takes an input size of (128, 128, 3).\nKindly refer to this gist for working code. Thank you!\n",
"The error means the model's input shape should be (Non... | [
0,
0
] | [] | [] | [
"classification",
"keras",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0070706671_classification_keras_machine_learning_python_tensorflow.txt |
Q:
How to copy one class function variable value in another class window in pyqt5
this is the small part of source code of the project
i want to copy user variable from userlogin class to usermain class
tried to make a userlogin object in usermain class but no working
from ftplib import parse150
import time
import s... | How to copy one class function variable value in another class window in pyqt5 | this is the small part of source code of the project
i want to copy user variable from userlogin class to usermain class
tried to make a userlogin object in usermain class but no working
from ftplib import parse150
import time
import sys
import sqlite3
from PyQt5 import QtWidgets
from PyQt5.uic import loadUi
from PyQt... | [] | [] | [
"I think signal/slot helps you, using signal and slot you can connect objects to each other and any value you want can transfer\n"
] | [
-2
] | [
"pyqt5",
"python"
] | stackoverflow_0074497829_pyqt5_python.txt |
Q:
How can I code a timer to run simultaneously with my code?
import time
import threading
import random
#declare variables and constant
guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"]
nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]
wrong... | How can I code a timer to run simultaneously with my code? | import time
import threading
import random
#declare variables and constant
guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"]
nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]
wronganswers = ["Wrong answer...", "Nope", "Try again next time.", "W... | [
"In the code you've shown, you haven't assigned a value to my_timer.\nmy_timer = 5\nBy assigning the global within countdown() you've merely allowed countdown to change the value of my_timer. You still need to assign a value.\n"
] | [
0
] | [] | [] | [
"countdowntimer",
"python"
] | stackoverflow_0074497971_countdowntimer_python.txt |
Q:
Webpage not loading while scrapping in Python
I have a dataset which contains URL of Just Dial website for which I am trying to extract few information like seller name. Below I have attached a sample data
dict_test = {"Id" : [1000, 1001, 1002],
"Online_url" : ['https://www.justdial.com/Mumbai/Sunris... | Webpage not loading while scrapping in Python | I have a dataset which contains URL of Just Dial website for which I am trying to extract few information like seller name. Below I have attached a sample data
dict_test = {"Id" : [1000, 1001, 1002],
"Online_url" : ['https://www.justdial.com/Mumbai/Sunrise-Info-Solutions-Pvt-Ltd-Near-Airtel-Gallery/022PXX... | [
"you should not close the driver at the end of webpage_extract.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"selenium"
] | stackoverflow_0074492832_python_python_3.x_selenium.txt |
Q:
How to plot 2 variables against each other using a bar chart in python?
In a pandas dataframe, I have three columns:
Column
Value
Educational level
Bachelors , Masters , PHD , ...
Education-num
1 , 2 , 3 , ...
salary
1 , 0
I want to plot a barchart with count on the y-axis. And on the x-axis, educational leve... | How to plot 2 variables against each other using a bar chart in python? | In a pandas dataframe, I have three columns:
Column
Value
Educational level
Bachelors , Masters , PHD , ...
Education-num
1 , 2 , 3 , ...
salary
1 , 0
I want to plot a barchart with count on the y-axis. And on the x-axis, educational level with salary. How can I do so with matplotlib or seaborn?
I have... | [
"You need to do some manipulation to generate count that is in your chart. Is it from 'EDUCATION-NUM'?\nOnce generated:\nx = 'Education level'\ny = 'count'\nto segment, you use hue = 'SALARY'\ndocumentation is here: https://seaborn.pydata.org/generated/seaborn.barplot.html\n"
] | [
0
] | [] | [] | [
"bar_chart",
"matplotlib",
"plot",
"python",
"seaborn"
] | stackoverflow_0074498254_bar_chart_matplotlib_plot_python_seaborn.txt |
Q:
How can I restrict users to delete other's posts in django using class based views?
my views.py file:
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixi... | How can I restrict users to delete other's posts in django using class based views? | my views.py file:
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixin,
)
from .models import Post
# Create your views here.
class PostListView(ListView):
... | [
"you can use get_queryset() to restrict query in database\nclass PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin):\n model = Post\n success_url = \"blog-home\"\n\n def form_valid(self, form):\n form.instance.author = self.request.user\n return super().form_valid(form)\n\n ... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0070692162_django_python.txt |
Q:
AttributeError: module '__main__' has no attribute 'cleaner'
We are creating web-site with ai assistant. We trained our model in Google Colab and now we are trying to upload it to our project. But we get the following error:
AttributeError: module '__main__' has no attribute 'cleaner'
In our file views.py declare... | AttributeError: module '__main__' has no attribute 'cleaner' | We are creating web-site with ai assistant. We trained our model in Google Colab and now we are trying to upload it to our project. But we get the following error:
AttributeError: module '__main__' has no attribute 'cleaner'
In our file views.py declared the class VoiceAssistant and the function cleaner for pipeline. ... | [
"To solve this problem, I just added cleaner function to the manage.py, because there is the module main. It solved the problem.\n",
"Just change the name of your module from \"main\" to anything else, and it should work\n"
] | [
1,
0
] | [] | [] | [
"django",
"joblib",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0073209533_django_joblib_machine_learning_python_scikit_learn.txt |
Q:
Extract content from a page that renders it with javascript using Beautifulsoup
I started programming not long ago and came across this problem. I want to collect stock data from the website: https://statusinvest.com.br/acoes/petr4. But apparently they are rendered with javascript and BeautifulSoup does not collec... | Extract content from a page that renders it with javascript using Beautifulsoup | I started programming not long ago and came across this problem. I want to collect stock data from the website: https://statusinvest.com.br/acoes/petr4. But apparently they are rendered with javascript and BeautifulSoup does not collect, if you can help I appreciate it
My soup code
Example of information loaded with ja... | [
"Hoping that OP's next questions will contain a minimal, reproducible example, here is one way of getting some data from that page using Requests and BeautifulSoup:\nfrom bs4 import BeautifulSoup as bs\nimport requests\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, lik... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074497235_beautifulsoup_python_web_scraping.txt |
Q:
how to avoid TO_TENSOR() clips values to 1
I have a black and white image that needs to be converted into tensor.
The shape of the image is (400, 600, 3).
Originally, the values of the image have max = 255; for example:
org_img[0]
# result:
array([[255, 255, 255],
[255, 255, 255],
[... | how to avoid TO_TENSOR() clips values to 1 | I have a black and white image that needs to be converted into tensor.
The shape of the image is (400, 600, 3).
Originally, the values of the image have max = 255; for example:
org_img[0]
# result:
array([[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
... | [
"The images are not clipped but instead re-scaled from uint8 0..255 to float32 [0, 1] by ToTensor. Library such as matplotlib can naturally handle RGB images with single-precision pixel values within [0, 1] after re-scaling.\n"
] | [
0
] | [] | [] | [
"python",
"pytorch",
"tensor"
] | stackoverflow_0074498111_python_pytorch_tensor.txt |
Q:
Celery Tasks are not getting added to database
I am trying to run my django application using docker which involves celery. I am able to set everything on local and it works perfectly fine. However, when I run it docker, and my task gets executed, it throws me the following error:
myapp.models.mymodel.DoesNotExist... | Celery Tasks are not getting added to database | I am trying to run my django application using docker which involves celery. I am able to set everything on local and it works perfectly fine. However, when I run it docker, and my task gets executed, it throws me the following error:
myapp.models.mymodel.DoesNotExist: mymodel matching query does not exist.
I am partic... | [
"The exception is telling you that you are looking for an entry in your database, that does not exist (yet). Look for any function where you query the database and make sure you create the needed entry before looking for it. I'm assuming you have a table in your database for some configuration, that is read in a fu... | [
0,
0
] | [] | [] | [
"celery",
"celery_task",
"django",
"docker",
"python"
] | stackoverflow_0074475991_celery_celery_task_django_docker_python.txt |
Q:
Getting much output from the number of user input in Javascript
In Python I use "for x in range(j)" and j is defined from user input, for example
j = int(input())
for x in range(j)
print(j)
if I input j as 3, the output will be
3
3
3
My question is, how do i do it with javascript?
I tried to do it with array, et... | Getting much output from the number of user input in Javascript | In Python I use "for x in range(j)" and j is defined from user input, for example
j = int(input())
for x in range(j)
print(j)
if I input j as 3, the output will be
3
3
3
My question is, how do i do it with javascript?
I tried to do it with array, etc. Nothing seems to work, sorry im really new at coding and need to l... | [
"You can do it with prompt function\n\n\nconst printData = () =>{\n\n let num = prompt(\"Please input a number\", \"3\") // second parameter is the default value\n if(isNaN(num)){\n console.error(`${num} is an invalid number`)\n return\n }\n\n for(let i=0;i<num;i++){\n console.log(num)\n }\n}\n\nprintD... | [
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0074498452_javascript_python.txt |
Q:
Trying to create a filled dataframe from pandas crosstab
I've got a numpy array that looks like this, in general (it was created from a pd crosstable if that's of any significance)
Person
1to1 Person Attribute
Circumstance
Outcome A Count
Outcome B Count
ABC1
1
X
100
25
DEF2
2
X
1
2
Y
0
2
XYZ1
1
X
33
5
Y
5
1... | Trying to create a filled dataframe from pandas crosstab | I've got a numpy array that looks like this, in general (it was created from a pd crosstable if that's of any significance)
Person
1to1 Person Attribute
Circumstance
Outcome A Count
Outcome B Count
ABC1
1
X
100
25
DEF2
2
X
1
2
Y
0
2
XYZ1
1
X
33
5
Y
5
10
that I'd like to turn into a pandas datafr... | [
"pd.DataFrame(your ndarray).fillna(method = 'ffill')\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"pivot_table",
"python"
] | stackoverflow_0074498391_dataframe_numpy_pandas_pivot_table_python.txt |
Q:
Multiprocessing in python. Can a multiprocessed function call functions as multiprocesses?
Recently I have started using the multiprocessor pool executor in python to accelerate my processing.
So instead of doing a
list_of_res=[]
for n in range(a_number):
res=calculate_something(list_of sources[n])
list_of... | Multiprocessing in python. Can a multiprocessed function call functions as multiprocesses? | Recently I have started using the multiprocessor pool executor in python to accelerate my processing.
So instead of doing a
list_of_res=[]
for n in range(a_number):
res=calculate_something(list_of sources[n])
list_of_res.append(res)
joint_results=pd.concat(list_of_res)
I do
with ProcessPoolExecutor(max_workers... | [
"yes you can have a worker process spawn another pool of workers, but it is not optimal.\neach time you launch a new process it takes a few hundred milliseconds to a few seconds for this new process to initialize and start executing work (OS, disk and code dependent.)\nlaunching a worker from a worker is just wasti... | [
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0074498451_multiprocessing_python.txt |
Q:
textblob .detect_language() function not working
So I have been trying out coding and am currently finding some language detection packages and found out about textblob, but I am having some sort of proble.
This is my code:
# - *- coding: utf- 8 - *-
from textblob import TextBlob
blob = TextBlob("Comment vas-tu?"... | textblob .detect_language() function not working | So I have been trying out coding and am currently finding some language detection packages and found out about textblob, but I am having some sort of proble.
This is my code:
# - *- coding: utf- 8 - *-
from textblob import TextBlob
blob = TextBlob("Comment vas-tu?")
print(blob.detect_language())
print(blob.translate... | [
"You can make it working by doing some changes in your translate.py file as mentioned below:\nOriginal:\nurl = \"http://translate.google.com/translate_a/t?client=webapp&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&otf=2&ssel=0&tsel=0&kc=1\"\n\nChange above code to:\nurl = \"http://t... | [
0,
0
] | [] | [] | [
"language_detection",
"python",
"textblob"
] | stackoverflow_0069207838_language_detection_python_textblob.txt |
Q:
Python - Mandatory 3 decimal places
I'm stuck on a subject.
I have a float number with a value of 0.150. Except that in my program in python, my value displays 0.15.
I want to force the display of 0.150 without converting the number into a character string.
Do you know a function, a library that could help me?
Tha... | Python - Mandatory 3 decimal places | I'm stuck on a subject.
I have a float number with a value of 0.150. Except that in my program in python, my value displays 0.15.
I want to force the display of 0.150 without converting the number into a character string.
Do you know a function, a library that could help me?
Thanks for your help !
EDIT :
Here my field ... | [
"Float 0,15 or 0,150 are exactly the same number for python. You can only show the extra 0 in Odoo nieuws and on pdf reports but not store it in the python variable.\nFor the views and pdf you can use this code:\n <t t-esc=\"'{0:,.3f}'.format(int(values.posX))\" />\n\n"
] | [
0
] | [] | [] | [
"odoo",
"python",
"python_3.x"
] | stackoverflow_0074478265_odoo_python_python_3.x.txt |
Q:
python function: how to unset a default argument value
if i have
def (a=10, b=2): ...
how do I unset a=1? I was told I need to not set 'a' but I can't find how to do that on google, it just sets itself to the default value if I don't have it, and I need to completely unset it
the library is madmom and the instruc... | python function: how to unset a default argument value | if i have
def (a=10, b=2): ...
how do I unset a=1? I was told I need to not set 'a' but I can't find how to do that on google, it just sets itself to the default value if I don't have it, and I need to completely unset it
the library is madmom and the instruction was "If look_ahead is not set, a constant tempo through... | [
"Simply pass new values to your function on call:\ndef func(a=10, b=2)\n print(a, b)\n\nCall with default arguments:\nfunc()\n\nCall with non-default arguments:\nfunc(20, 3)\n\n",
"answer is that I had to set it to None and it worked\n"
] | [
0,
-1
] | [] | [] | [
"default",
"function",
"python"
] | stackoverflow_0074498204_default_function_python.txt |
Q:
I am getting an error of: not enough values to unpack (Expected 2, got 1) im following a tutorial but it just wont work
This is the code I have used from a tutorial
def view():
with open('My coding stuff\\passwords.txt', 'r') as f:
for line in f.readlines():
data = line.rstrip()
... | I am getting an error of: not enough values to unpack (Expected 2, got 1) im following a tutorial but it just wont work | This is the code I have used from a tutorial
def view():
with open('My coding stuff\\passwords.txt', 'r') as f:
for line in f.readlines():
data = line.rstrip()
user, passw = data.split("|")
print("User:",user, ", password:", passw)
I have no idea what is wrong with the c... | [
"Please save data in password.txt in below format\nUser|pwd\n",
"The problem in your code that you are assigning one value in tuple user, passw instead of 2 values which is returned by data.split(\"|\").\nI think that the file you are reading doesn't contain data in the format user | pass (each record seperated b... | [
0,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0074498485_python_syntax.txt |
Q:
Pandas - convert integer to bytestring and update single fields
Problem: I receive from a machine errorcodes as integer (every minute). This errorcode represents a bytestring and every bit stands for a specific error. For analytics I need this bits
inside pandas as separate columns. I'm struggling doing this.
def ... | Pandas - convert integer to bytestring and update single fields | Problem: I receive from a machine errorcodes as integer (every minute). This errorcode represents a bytestring and every bit stands for a specific error. For analytics I need this bits
inside pandas as separate columns. I'm struggling doing this.
def converttobinary(num, length=3):
binary_string_list = list(format(... | [
"You can use another apply call to extract the element of the list:\ndf['errorcode01'] = df.apply(lambda row : row['errorcodelist'][2], axis = 1)\ndf['errorcode02'] = df.apply(lambda row : row['errorcodelist'][1], axis = 1)\ndf['errorcode03'] = df.apply(lambda row : row['errorcodelist'][0], axis = 1)\n\nOr you coul... | [
1
] | [] | [] | [
"arrays",
"pandas",
"python"
] | stackoverflow_0074498555_arrays_pandas_python.txt |
Q:
Pythonic approach to keeping track of cached variable/function dependencies
I have a system with a library which includes many functions/methods that are slow, for example SQL queries or computational expensive algorithms. Therefore, I have identified those that can benefit from caching and use the lru_cache or ca... | Pythonic approach to keeping track of cached variable/function dependencies | I have a system with a library which includes many functions/methods that are slow, for example SQL queries or computational expensive algorithms. Therefore, I have identified those that can benefit from caching and use the lru_cache or cache decorators from functools. I additionally use cache_clear() to clear caches w... | [
"I think the idea of using the cache decorators on non-idempotent functions is a bit of an abuse of the API. The idea is generally that you can cache the values on the objects because there are no side-effects which would require the outputs to change on subsequent calls.\nIn the example for class A you provide a m... | [
3
] | [] | [] | [
"caching",
"dependencies",
"dependency_management",
"lru",
"python"
] | stackoverflow_0074386469_caching_dependencies_dependency_management_lru_python.txt |
Q:
How to method-chain `ffill(axis=1)` in a dataframe
I would like to fill column b of a dataframe with values from a in case b is nan, and I would like to do it in a method chain, but I cannot figure out how to do this.
The following works
import numpy as np
import pandas as pd
df = pd.DataFrame(
{"a": [1, 2, 3... | How to method-chain `ffill(axis=1)` in a dataframe | I would like to fill column b of a dataframe with values from a in case b is nan, and I would like to do it in a method chain, but I cannot figure out how to do this.
The following works
import numpy as np
import pandas as pd
df = pd.DataFrame(
{"a": [1, 2, 3, 4], "b": [10, np.nan, np.nan, 40], "c": ["a", "b", "c"... | [
"df = pd.DataFrame({\"a\": [1, 2, 3, 4], \"b\": [10, np.nan, np.nan, 40], \"c\": [\"a\", \"b\", \"c\", \"d\"]})\ndf['b'] = df.b.fillna(df.a)\n \n| | a | b | c |\n|---:|----:|----:|:----|\n| 0 | 1 | 10 | a |\n| 1 | 2 | 2 | b |\n| 2 | 3 | 3 | c |\n| 3 | 4 | 40 | d |\n\n",
"One ... | [
0,
0
] | [] | [] | [
"method_chaining",
"pandas",
"python"
] | stackoverflow_0074493618_method_chaining_pandas_python.txt |
Q:
python Scrapy amazon fails to return all reviews
I want to scrape the amazon review from amazon, the return result is always none,however,there are product review can correctly returned. what is the problem?
import scrapy
from scrapy import Selector, Request
from test1.items import Test1Item
class hiSpider(scrapy... | python Scrapy amazon fails to return all reviews | I want to scrape the amazon review from amazon, the return result is always none,however,there are product review can correctly returned. what is the problem?
import scrapy
from scrapy import Selector, Request
from test1.items import Test1Item
class hiSpider(scrapy.Spider):
name = 'hello'
def start_requests... | [
"Test this code.\nimport scrapy\nfrom scrapy import Request\nfrom test1.items import Test1Item\n\nclass hiSpider(scrapy.Spider):\n\n\n name = 'hello'\n\n # if you use ( statr_urls ) you don't need start_request() function \n\n def start_requests(self):\n url = 'https://www.amazon.com/s?k=t-shirts+f... | [
0
] | [] | [] | [
"amazon",
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0074486673_amazon_python_scrapy_web_crawler.txt |
Q:
check if a string has any other character than '*'
I'd like to check whether a certain string contains any character other than '*'. for example:
str1 = "aaa*bbb" will return false
str2= "***" will return true
how can I do that?
this is what I tried and it didn't work
A:
You can use all() to perform the check:... | check if a string has any other character than '*' | I'd like to check whether a certain string contains any character other than '*'. for example:
str1 = "aaa*bbb" will return false
str2= "***" will return true
how can I do that?
this is what I tried and it didn't work
| [
"You can use all() to perform the check:\ndef check(s, char=\"*\"):\n return all(ch == char for ch in s)\n\n\nprint(check(\"aaa*bbb\"))\nprint(check(\"***\"))\n\nPrints:\nFalse\nTrue\n\n"
] | [
2
] | [] | [] | [
"function",
"python",
"string"
] | stackoverflow_0074498625_function_python_string.txt |
Q:
How to define multiple API endpoints in FastAPI with different paths but the same path parameter?
I'm working on a project which uses FastAPI. My router file looks like the following:
# GET API Endpoint 1
@router.get("/project/{project_id}/{employee_id}")
async def method_one(
project_id: str, organization_id:... | How to define multiple API endpoints in FastAPI with different paths but the same path parameter? | I'm working on a project which uses FastAPI. My router file looks like the following:
# GET API Endpoint 1
@router.get("/project/{project_id}/{employee_id}")
async def method_one(
project_id: str, organization_id: str, session: AsyncSession = Depends(get_db)
):
try:
return await CustomController.method... | [
"In FastAPI, as described in this answer, because endpoints are evaluated in order (see order matters), it makes sure that the endpoint you defined first in your app—in this case, that is, /project/{project_id}/...—will be evaluated first. Hence, every time you call one of the other two endpoints, i.e., /project/de... | [
1
] | [] | [] | [
"fastapi",
"fastapi_crudrouter",
"fastapiusers",
"python",
"rest"
] | stackoverflow_0074498191_fastapi_fastapi_crudrouter_fastapiusers_python_rest.txt |
Q:
How to run Oracle PL/SQL in python
I'm using Jupyter notebook to run a PL/SQL script but I get an error. The code block in the notebook is as follows:
%%sql
DECLARE BEGIN
FOR record_item IN (
SELECT
*
FROM
duplicated_records
) LOOP
EXECUTE IMMEDIATE 'UPDATE ... | How to run Oracle PL/SQL in python | I'm using Jupyter notebook to run a PL/SQL script but I get an error. The code block in the notebook is as follows:
%%sql
DECLARE BEGIN
FOR record_item IN (
SELECT
*
FROM
duplicated_records
) LOOP
EXECUTE IMMEDIATE 'UPDATE table_name SET record_id ='|| record_ite... | [
"I don't know Python so I can't assist about that, but - as far as Oracle is concerned - you don't need DECLARE (as you didn't declare anything), and you certainly don't need dynamic SQL (EXECUTE IMMEDIATE) as there's nothing dynamic there.\nRewritten:\nBEGIN\n FOR record_item IN (SELECT * FROM duplicated_records)... | [
2,
1
] | [] | [] | [
"jupyter_notebook",
"oracle",
"plsql",
"python"
] | stackoverflow_0074498105_jupyter_notebook_oracle_plsql_python.txt |
Q:
What does "splitter" attribute in sklearn's DecisionTreeClassifier do?
The sklearn DecisionTreeClassifier has a attribute called "splitter" , it is set to "best" by default, what does setting it to "best" or "random" do? I couldn't find enough information from the official documentation.
A:
There is 2 things to ... | What does "splitter" attribute in sklearn's DecisionTreeClassifier do? | The sklearn DecisionTreeClassifier has a attribute called "splitter" , it is set to "best" by default, what does setting it to "best" or "random" do? I couldn't find enough information from the official documentation.
| [
"There is 2 things to consider, the criterion and the splitter. During all the explaination, I'll use the wine dataset example:\nCriterion:\nIt is used to evaluate the feature importance. The default one is gini but you can also use entropy. Based on this, the model will define the importance of each feature for th... | [
11,
3,
3,
2,
0
] | [] | [] | [
"machine_learning",
"python",
"python_3.x",
"scikit_learn"
] | stackoverflow_0046756606_machine_learning_python_python_3.x_scikit_learn.txt |
Q:
convert string response to array of json objects
I am receiving a response that I need to save as CSV file. So I would like to convert the response string as an array of json objects then access all the objects and convert each to json and push to another array to write to a csv with csv.writerow(). Probably this ... | convert string response to array of json objects | I am receiving a response that I need to save as CSV file. So I would like to convert the response string as an array of json objects then access all the objects and convert each to json and push to another array to write to a csv with csv.writerow(). Probably this is too much steps and can be reduced. But I am current... | [
"json.dumps is for getting string dump from a json. Here You have a string already, so you don't need to dump it.\nIf You just use loads, It will give You a list of dicts:\n...\njeson_converted = json.loads(response_object)\nprint(jeson_converted)\n\nOutput:\n[{'a': '1', 'b': '2', 'c': 'null'}, {'d': '3', 'e': '4',... | [
2,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074498690_json_python.txt |
Q:
Forbidden (403) CSRF verification failed. Request aborted-Real time chat application with Django Channels
I'm doing a course from YouTube "Python Django Realtime Chat Project - Full Course" and I'm new to django.My problem is, When I try to send message in room chat (submit form) I get this error Forbidden (403) C... | Forbidden (403) CSRF verification failed. Request aborted-Real time chat application with Django Channels | I'm doing a course from YouTube "Python Django Realtime Chat Project - Full Course" and I'm new to django.My problem is, When I try to send message in room chat (submit form) I get this error Forbidden (403) CSRF verification failed. We don't have CSRFtoken in our form in room.html but The instructor fixed the error by... | [
"Simply you can add csrf_token inside form tag of template.\nIn template:\n<form>\n {% csrf_token %} \n</form>\n\nAnd that error will solve.\n"
] | [
1
] | [] | [] | [
"channels",
"django",
"django_channels",
"python",
"websocket"
] | stackoverflow_0074498749_channels_django_django_channels_python_websocket.txt |
Q:
Is there a ready-made function for http_wait in telethon?
I need to use http_wait link with telethon, are there already made functions in the library to use that specific method?
I need to receive messages as soon as they occur is large broadcast channels, now the updates come 5-20 seconds late
A:
Clients using ... | Is there a ready-made function for http_wait in telethon? | I need to use http_wait link with telethon, are there already made functions in the library to use that specific method?
I need to receive messages as soon as they occur is large broadcast channels, now the updates come 5-20 seconds late
| [
"Clients using the Telegram API, such as Telethon, connect to the Telegram servers directly via a TCP socket. While connected, Telegram decides when and where to deliver the updates. Telegram's API doesn't really offer a way to \"poll\" for these updates.\nIf Telegram is delivering them slowly, it's probably to red... | [
0
] | [] | [] | [
"python",
"telethon"
] | stackoverflow_0074463994_python_telethon.txt |
Q:
ufunc 'sqrt' not supported for the input types
Im trying to plot a scatter with values from my array, everything is working till im trying to scale the size of the dots with an value of my array.
For example my array looks like this:
['50', ' 50', ' 0.6352952']
First value is x, second y and the third one is whi... | ufunc 'sqrt' not supported for the input types | Im trying to plot a scatter with values from my array, everything is working till im trying to scale the size of the dots with an value of my array.
For example my array looks like this:
['50', ' 50', ' 0.6352952']
First value is x, second y and the third one is which i want to scale with
My plots currently looks lik... | [
"The data in convertedResults is of type string, so you are trying to pass a string into s. Even when you multiply convertedResults[i][2] by 1, the result is also a string according to the Python standard. You need to use s = float(convertedResults[i][2]) in the scatter call\n"
] | [
1
] | [] | [] | [
"matplotlib",
"plot",
"python",
"scatter_plot"
] | stackoverflow_0074498600_matplotlib_plot_python_scatter_plot.txt |
Q:
How do I make a turtle disapear if touched by another turtle?
Me and my buddy are making a sorta zombie shooting game on Python, we've gotten almost the basic gameplay done except with one issue, we can't find a way to make one turtle disappear after being touched by a different turtle. We have 3 turtles, one for ... | How do I make a turtle disapear if touched by another turtle? | Me and my buddy are making a sorta zombie shooting game on Python, we've gotten almost the basic gameplay done except with one issue, we can't find a way to make one turtle disappear after being touched by a different turtle. We have 3 turtles, one for our player model, one for a bullet, and one for a zombie, we're try... | [
"That code is not working because the code that detects if a turtle touches turtle cannot only use it's own position, because for example if every frame the bullet moves 10 pixels so when it is at the point it needs to hit the zombie the zombie x is 5 and the bullet x is 0 at the next game it is going to 10, so it ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074380930_python.txt |
Q:
How to generate a normally distributed variable in Python?
I have a list of 10 values:
variable=[2.1, 5.3, 4.1, 6.7, 2, 6.6, 1.9, 4.51, 4, 7.15]
Its length:
>>> len(variable)
10
Its average:
>>> mean(variable)
4.436
Its standard deviation:
>>> np.std(variable)
1.8987269419271429
From it I want to generate a ne... | How to generate a normally distributed variable in Python? | I have a list of 10 values:
variable=[2.1, 5.3, 4.1, 6.7, 2, 6.6, 1.9, 4.51, 4, 7.15]
Its length:
>>> len(variable)
10
Its average:
>>> mean(variable)
4.436
Its standard deviation:
>>> np.std(variable)
1.8987269419271429
From it I want to generate a new_variable having len(new_variable)==100 and normally distribute... | [
"You can use the random.gauss function:\n1 sample:\nimport random\nx = random.gauss(4.436, 1.898)\n\nor 100 samples:\nimport random\nx = [random.gauss(4.436, 1.898) for _ in range(100)]\n\nThis is standard library, you don't need to install anything. You may also be interested in the statistics library.\n",
"This... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0074498546_python.txt |
Q:
discord.py dming/pinging random members in a server as a chat revive system
Is there a way I can dm or ping random members in a server to revive chat? I don't know if dming random people in a server will flag the bot but just in case perhaps I can ping in a channel? If so, How can I make it pick a certain amount o... | discord.py dming/pinging random members in a server as a chat revive system | Is there a way I can dm or ping random members in a server to revive chat? I don't know if dming random people in a server will flag the bot but just in case perhaps I can ping in a channel? If so, How can I make it pick a certain amount of random members in a server? For example 5 random members in a server.
@client.h... | [
"Change these lines:\nfor members in ctx.guild.members:\n member = random.choice(members)\n\nto the following:\nmember = random.choice(ctx.guild.members)\n\nAlso remember to import random\n"
] | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074496462_discord_discord.py_python.txt |
Q:
Elegant way to concat all dict values together with a string carrier as a single string in Python
The objective is to concat all values in a dict into a single str.
Additionally, the \r\n also will be appended.
The code below demonstrates the end result.
However, I am looking for a more elegant alternative than th... | Elegant way to concat all dict values together with a string carrier as a single string in Python | The objective is to concat all values in a dict into a single str.
Additionally, the \r\n also will be appended.
The code below demonstrates the end result.
However, I am looking for a more elegant alternative than the proposed code below.
d=dict(idx='1',sat='so',sox=[['x1: y3'],['x2: y1'],['x3: y3']],mul_sol='my love ... | [
"following code have more control over what might have in the dictionary:\ndef conca(li):\n ret=''\n for ele in li:\n if isinstance(ele,str):\n ret += ele + '\\r\\n'\n else:\n ret += conca(ele) \n return ret\n\nprint(conca([d[e] for e in list(d)]))\n\nor if want a more versatile solution:\nde... | [
2,
2,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074498573_dictionary_python.txt |
Q:
Create a date column and assign value from a condition based on an existing date column in pandas
I have the following:
import pandas as pd
file = pd.DataFrame()
file['CASH RECIEVED DATE'] = ['2018-07-23', '2019-09-26', '2017-05-02']
and I need to create a column called Cash Received Date
file['... | Create a date column and assign value from a condition based on an existing date column in pandas | I have the following:
import pandas as pd
file = pd.DataFrame()
file['CASH RECIEVED DATE'] = ['2018-07-23', '2019-09-26', '2017-05-02']
and I need to create a column called Cash Received Date
file['Cash Received Date']
such as if [CASH_RECIEVED_DATE] is not null && [CASH RECIEVED_DATE] <= 2022-09-01... | [
"def compare_date(x):\n if pd.to_datetime(x) > pd.to_datetime('2019-09-01'):\n return pd.to_datetime(x)\n else:\n return pd.to_datetime('2019-09-01')\n\nfile['Cash Received Date'] = file['CASH RECIEVED DATE'].apply(lambda x: compare_date(x))\n\ngives file as :\n CASH RECIEVED DATE Cash Received... | [
0,
0
] | [] | [] | [
"dataframe",
"jupyter",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074494806_dataframe_jupyter_jupyter_notebook_pandas_python.txt |
Q:
bot event has stopped all my commands from working
this is the code which is stopping all my bot commands:
@client.event
async def on_message(message):
if message.author == client.user:
return
phrases = open("D:/code/code/DIscord bot/myFile.txt").readlines()
phrases = list(map(lambda item: it... | bot event has stopped all my commands from working | this is the code which is stopping all my bot commands:
@client.event
async def on_message(message):
if message.author == client.user:
return
phrases = open("D:/code/code/DIscord bot/myFile.txt").readlines()
phrases = list(map(lambda item: item.strip(), phrases))
if message.content in phrases:... | [
"Take a look at the discord.py FAQ:\nYou need to change your @client.event to @client.listen('on_message') and that should fix your issue\n"
] | [
0
] | [] | [] | [
"discord",
"nextcord",
"python"
] | stackoverflow_0074496371_discord_nextcord_python.txt |
Q:
TypeError: 'generator' object is not callable when using pandas' date_range
I'm using pandas' date_range to generate datetime arrays:
time_array = pd.date_range(start='2020-6-1 00:00:00', end='2021-10-31 00:00:00', freq='H')
And when I start to debug my code, my IDE tells me this error:
past_predict_single.py::tes... | TypeError: 'generator' object is not callable when using pandas' date_range | I'm using pandas' date_range to generate datetime arrays:
time_array = pd.date_range(start='2020-6-1 00:00:00', end='2021-10-31 00:00:00', freq='H')
And when I start to debug my code, my IDE tells me this error:
past_predict_single.py::test_gen_line_model FAILED
past_predict_single.py:83 (test_ge... | [
"I cut my code to another python file and the problem disappeared.\n"
] | [
0
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074486778_dataframe_datetime_pandas_python_python_3.x.txt |
Q:
My discord.py bot is not responding to commands or events
import discord
from discord.ext import commands
from discord import Embed
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
#Prints bot is online to console
@bot.event
async def on_ready():
print("PythonBot is online")
#Replies He... | My discord.py bot is not responding to commands or events | import discord
from discord.ext import commands
from discord import Embed
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
#Prints bot is online to console
@bot.event
async def on_ready():
print("PythonBot is online")
#Replies Hey! if a user says Hello
@bot.event
async def on_message(message... | [
"Take a look at the discord.py FAQ:\nYou need to change your following 2 lines\n@bot.event\nasync def on_message(message):\n\nto\n@bot.listen('on_message')\nasync def on_message(message):\n\nand that should fix your issue\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074495400_discord_discord.py_python.txt |
Q:
Unable to process large amount of data using for loop
I am downloading 2 years worth of OHLC for 10k symbols and writing it to database. When I try to pull the entire list it crashes (but doesn't if I download 20%):
import config
from alpaca_trade_api.rest import REST, TimeFrame
import sqlite3
import pandas as pd... | Unable to process large amount of data using for loop | I am downloading 2 years worth of OHLC for 10k symbols and writing it to database. When I try to pull the entire list it crashes (but doesn't if I download 20%):
import config
from alpaca_trade_api.rest import REST, TimeFrame
import sqlite3
import pandas as pd
import datetime
from dateutil.relativedelta import relativ... | [
"Since you mentioned that you are able to make it work for 2000 records of df_dict at a time, a possible simple approach could be:\napi = REST(config.api_key_id, config.api_secret, base_url=config.base_url)\n\nnum_records = len(df_dict)\nchunk_size = 2000\nnum_passes = num_records // chunk_size + int(num_records % ... | [
2
] | [] | [] | [
"numpy",
"pandas",
"python",
"sqlite"
] | stackoverflow_0074498448_numpy_pandas_python_sqlite.txt |
Q:
Can not install pykd using pip
I get an error when I want to install pykd using pip.
The error says:
ERROR: Could not find a version that satisfies the requirement pykd (from versions: none)
ERROR: No matching distribution found for pykd
When I try to download the .whl file of pykd and install it with pip, I get ... | Can not install pykd using pip | I get an error when I want to install pykd using pip.
The error says:
ERROR: Could not find a version that satisfies the requirement pykd (from versions: none)
ERROR: No matching distribution found for pykd
When I try to download the .whl file of pykd and install it with pip, I get this error:
ERROR: pykd-0.3.4.15-cp3... | [
"pykd-0.3.4.15-cp39-none-win_amd64.whl\nit is not surprising what this wheel built special for python 3.9, so it can installed only for python 3.9\npykd build for 3.10 or 3.11 does not exsist. And there is no unversal pykd build. Sorry.\nI recommend you use 3.8 python with pykd.\n"
] | [
0
] | [] | [] | [
"pip",
"pykd",
"python"
] | stackoverflow_0074494461_pip_pykd_python.txt |
Q:
Trying to create an function which allows users to go back to a previous question
so I'm making a text-based game in python and I'm trying to create an option which allows the user to return to the question if their answer was incorrect. It works like this:
There are three options to a question, 1,2,3. 1 and 3 are... | Trying to create an function which allows users to go back to a previous question | so I'm making a text-based game in python and I'm trying to create an option which allows the user to return to the question if their answer was incorrect. It works like this:
There are three options to a question, 1,2,3. 1 and 3 are the incorrect option which will fail the user, then they will have the option to go ba... | [
"this maybe overkill but if it was me I would probably implement a scene graph... something like what follows\nclass Scene:\n graph_map = {}\n def __init__(self,id,message,options):\n self.message = message \n self.opts = options\n self.id = id or len(Scene.graph)\n Scene.graph_map... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074497867_python.txt |
Q:
PyCharm auto suggestion doesn't appear
No Suggestion Appears:
My Setting:
Suddenly PyCharm auto suggestion doesn't appear.
For instance, to make a class, when I type just 'init', PyCharm used to suggest __init__(self).
I am begginer of Python and have little knowledge about pycharm interpreter.
Is this problem h... | PyCharm auto suggestion doesn't appear | No Suggestion Appears:
My Setting:
Suddenly PyCharm auto suggestion doesn't appear.
For instance, to make a class, when I type just 'init', PyCharm used to suggest __init__(self).
I am begginer of Python and have little knowledge about pycharm interpreter.
Is this problem happening because of interpreter?
| [
"Had the same in Visual studio code. Removed Pylance extention and got it back.\n"
] | [
0
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0070631204_pycharm_python.txt |
Q:
Issues plotting a histogram of a csv file on google colab
I am new to google colab and I am trying to plot a histogram of a csv file using matplotlib, but getting error.
This code is able to read and show my data
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import pylab... | Issues plotting a histogram of a csv file on google colab | I am new to google colab and I am trying to plot a histogram of a csv file using matplotlib, but getting error.
This code is able to read and show my data
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import pylab as pl
df = pd.read_csv('tree_result.csv')
df
but when I try ... | [
"To solve this I changed the datatype to string. That fixed it issue\nfig, ax = plt.subplots(figsize = (50,10))\nx = df['spc_common'].astype(str)\ny = df['count']\nplt.bar(x, height=y,align = 'center', width = 0.8)\nplt.xlabel('Name of Trees (common name)', size = 10)\nplt.ylabel('Number of Trees', size = 10)\npl.x... | [
0
] | [] | [] | [
"google_colaboratory",
"python"
] | stackoverflow_0074491808_google_colaboratory_python.txt |
Q:
error with notification of a new server to me in private messages
A couple of days ago the code worked, but now it gives an error, please help
`
#оповищение о новом сервере
@client.event
async def on_guild_join( guild ):
me = client.get_user(404915501727219723)
emb = discord.Embed( title = f'Я пришел на ... | error with notification of a new server to me in private messages | A couple of days ago the code worked, but now it gives an error, please help
`
#оповищение о новом сервере
@client.event
async def on_guild_join( guild ):
me = client.get_user(404915501727219723)
emb = discord.Embed( title = f'Я пришел на новый сервер' )
for guild in client.guilds:
category = gu... | [
"The error is probably occuring because the first category in the guild doesn't have any channels or your bot doesn't have access to it.\nI would suggest looping through all channels until you find one that you can create the invite in. Also you would still need a code for the case that there are no channels your b... | [
0,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074497887_discord_discord.py_python.txt |
Q:
What is the time complexity of the following algorithms, as a function of the number N of elements of mylist from position first to position last?
def mystery(mylist, first, last):
if (first == last):
return mylist[first]
mid = (first + last) // 2
return min(mystery(mylist, first, mid), myst... | What is the time complexity of the following algorithms, as a function of the number N of elements of mylist from position first to position last? | def mystery(mylist, first, last):
if (first == last):
return mylist[first]
mid = (first + last) // 2
return min(mystery(mylist, first, mid), mystery(mylist, mid+1, last))
Is it $O(logN)$ because every time the array size becomes half and called again?
| [
"You can count exactly the operations in this function. First, one must observe that this function finds the smallest element in mylist between first and last.\nWe can see that return mylist[first] happens exactly once for each element of the input array, so happens exactly N times overall.\nThe second return (ie: ... | [
0
] | [] | [] | [
"algorithm",
"data_structures",
"python",
"recursion"
] | stackoverflow_0074496989_algorithm_data_structures_python_recursion.txt |
Q:
Multi-User & parallel & Dynamic workflow in Django
I'm looking for the best solution for the development of workflow engine in Django (Django-Rest-Framework) by this requirement :
permission checking/task assignment options
Parallel workflows allow to have several active tasks at once and probably have some sort ... | Multi-User & parallel & Dynamic workflow in Django | I'm looking for the best solution for the development of workflow engine in Django (Django-Rest-Framework) by this requirement :
permission checking/task assignment options
Parallel workflows allow to have several active tasks at once and probably have some sort of parallel sync/join functionality
dynamic workflows ty... | [
"I solved this problem by django goflow package (github).\nthis package supports :\n\npermission checking by user Group\ntask assignment to specific user or a group (push and pull strategeis)\ndynamic design allow changes in workflow steps, transitions, permissions ,...\nExclusive gateway (xor gateway) and Parallel... | [
0
] | [] | [] | [
"bpmn",
"django",
"python"
] | stackoverflow_0073551571_bpmn_django_python.txt |
Q:
Beautiful Soup scraping Realtor.com. Four elements have same class. How to search using data-label?
I'm attempting my first web scraping using realtor.com.
While trying to extract property card info I ran into an issue searching by class. # bedrooms/#bathrooms/home square feet, and property square feet have the ex... | Beautiful Soup scraping Realtor.com. Four elements have same class. How to search using data-label? | I'm attempting my first web scraping using realtor.com.
While trying to extract property card info I ran into an issue searching by class. # bedrooms/#bathrooms/home square feet, and property square feet have the exact same class name.
When doing a find_all search I am unable to print "text only" because find_all print... | [
"While you can use something like .find('li', {'data-label': 'pc-meta-beds'}), I think you should look into the .select method and CSS Selectors - they're awesome.\n.select_one('li[data-label=\"pc-meta-beds\"] span[data-label=\"meta-value\"]').text [or just 'li[data-label=\"pc-meta-beds\"]' as the selector if you'r... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074483760_beautifulsoup_python_web_scraping.txt |
Q:
import throw ModuleNotFoundError
The import is working just fine from main.py outside of the scripts directory.
but when I use import in test directory, it doesn't work.. why?
from scripts.helpful_scripts import *
from scripts.print_something import *
print(add(1, 2))
print_something()
the Code inside main.py an... | import throw ModuleNotFoundError | The import is working just fine from main.py outside of the scripts directory.
but when I use import in test directory, it doesn't work.. why?
from scripts.helpful_scripts import *
from scripts.print_something import *
print(add(1, 2))
print_something()
the Code inside main.py and test_scripts.py is exactly the same... | [
"The test package donot have any package or module named scripts because the scripts is one step outside from where you are trying to execute the script.\nWhile in main.py the directory from where you are executing the code has the package named scripts from where you can import the modules.\nYou may not be able to... | [
1
] | [] | [] | [
"modulenotfounderror",
"python"
] | stackoverflow_0074498720_modulenotfounderror_python.txt |
Q:
Python: errno2 No such file or directory
I am learning Python from "Learn Python the Hard Way" and searched up quite a bit on it with no solutions as of yet.
I configured the path for python to work on the command prompt. But whenever I type in
"python ex1.py"
it comes up with an error: Errno2 No such file or ... | Python: errno2 No such file or directory | I am learning Python from "Learn Python the Hard Way" and searched up quite a bit on it with no solutions as of yet.
I configured the path for python to work on the command prompt. But whenever I type in
"python ex1.py"
it comes up with an error: Errno2 No such file or directory!
The code is a simple print code, no... | [
"In general, windows defaults to the user directory in the command prompt. Saying \"python ex1.py\" is trying to find ex1.py in the C:\\User\\Username directory. Try moving your python script there or moving to the python projects folder using cd. Either way should fix the issue.\n",
"Are you in the right directo... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0017635269_python.txt |
Q:
trying to move robot using the distance from camera to face
So, i am trying to move a dc motor using the distance from my face to a raspberry camera.
I have the raspberry connected to an arduino mega via serial comunication.
Currently i am testing only one dc motor.
I should say that i am using an raspberry pi 3b... | trying to move robot using the distance from camera to face | So, i am trying to move a dc motor using the distance from my face to a raspberry camera.
I have the raspberry connected to an arduino mega via serial comunication.
Currently i am testing only one dc motor.
I should say that i am using an raspberry pi 3b+ with 1 gb of ram.
This is the raspberry pi code:
`import numpy ... | [
"Try using 1 character like '1' or '0' (use single quote instead of double, Serial.read() in arduino instead of Serial.readString(), and char instead of String.\nchar command = Serial.read();\nif (command == '1') {\n\nThen usb.write(b'1') and usb.write(b'0') in Python\nFrom my past experience, I had arduino readSt... | [
0
] | [] | [] | [
"arduino",
"arduino_c++",
"python",
"raspberry_pi3",
"serial_port"
] | stackoverflow_0074498667_arduino_arduino_c++_python_raspberry_pi3_serial_port.txt |
Q:
Parse list to get new list with same structure
I applied a previous code for a log, to get the following list
log = ['',
'',
'ABC KLSC: XYZ',
'',
'some text',
'some text',
'%%ABC KLSC: XYZ',
'some text',
'',
'ID = 5',
'TME = KRE',
'DDFFLE = SOFYU',
'QWWRTYA = GRRZNY'... | Parse list to get new list with same structure | I applied a previous code for a log, to get the following list
log = ['',
'',
'ABC KLSC: XYZ',
'',
'some text',
'some text',
'%%ABC KLSC: XYZ',
'some text',
'',
'ID = 5',
'TME = KRE',
'DDFFLE = SOFYU',
'QWWRTYA = GRRZNY',
'',
'some text',
'--------------------... | [
"Finding the = is straight-forward. One way to find the column values might be, as follows, to identify header rows that contain the headings, and then zipping the following rows when splitting by white-space.\nitems_list = []\nfor item in log:\n if '=' in item:\n items_list.append(item)\n elif len(it... | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074498676_list_python.txt |
Q:
Finding the maximum digit in an integer
I want to find the max value of a number that consists of
for example:
123 (max digit is 3)
346 (max digit is 6)
like that.
I know how to find among several numbers:
numbers = [9, 34, 11, -4, 27]
# find the maximum number
max_number = max(numbers)
print(max_number)
But I... | Finding the maximum digit in an integer | I want to find the max value of a number that consists of
for example:
123 (max digit is 3)
346 (max digit is 6)
like that.
I know how to find among several numbers:
numbers = [9, 34, 11, -4, 27]
# find the maximum number
max_number = max(numbers)
print(max_number)
But I can't find in a number.
| [] | [] | [
"#this is just an example for maximum numbers\nnumb = [11,21,211,5,-7,0]\ntemp = max(numb)\nprint(temp)\n"
] | [
-2
] | [
"python"
] | stackoverflow_0074498942_python.txt |
Q:
How to set up SFTPSensor in Airflow to react on any file appearing on the server?
I am pretty new to Airflow. I am trying to set up SFTPSensor to look on the folder on the SFTP server for any file appear. It sounds for me like a regular expression "*" in the file_pattern property:
import airflow
import logging
fro... | How to set up SFTPSensor in Airflow to react on any file appearing on the server? | I am pretty new to Airflow. I am trying to set up SFTPSensor to look on the folder on the SFTP server for any file appear. It sounds for me like a regular expression "*" in the file_pattern property:
import airflow
import logging
from airflow import DAG
from airflow.operators.dummy import DummyOperator
from airflow.ope... | [
"You probably mixed up the order of your keyword arguments\nHave a look at the signature:\nSFTPSensor(*, path, file_pattern='', newer_than=None, sftp_conn_id='sftp_default', **kwargs)\n\nYou'll see that certain arguments (path, file_pattern, newer_than and sftp_conn_id) have their own, explicit argument. If you pas... | [
0
] | [] | [] | [
"airflow",
"filepattern",
"python"
] | stackoverflow_0074498822_airflow_filepattern_python.txt |
Q:
What is the fastest way to generate 100 000 000 normally distributed values?
I am struggling with generating a large list having normal values mean=5.357 and std-dev=2.37
Original list
org_list=[3.65, 4.11, 1.63, 6.7, 9, 7.61, 5.5, 2.9, 3.99, 8.48]
Candidates methods
Currently I am trying to use the following mod... | What is the fastest way to generate 100 000 000 normally distributed values? | I am struggling with generating a large list having normal values mean=5.357 and std-dev=2.37
Original list
org_list=[3.65, 4.11, 1.63, 6.7, 9, 7.61, 5.5, 2.9, 3.99, 8.48]
Candidates methods
Currently I am trying to use the following modules: random.normalvariate, random.gauss and np.normal
Tryings and goal
First I tr... | [
"If you use the size argument of np.normal, it is pretty fast. I.e. np.random.normal(5.357, 2.37, size=(10000000)) executes in less than half a second on my machine, compared to 24 seconds for the list comprehension approach\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0074499032_python.txt |
Q:
Button object not callable in Tkinter
I am trying to create a calculator app using Tkinter in python.
However, when I am trying to input my text in entry box i am getting the following error.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Optimus\anaconda3\envs\virtual_enviournme... | Button object not callable in Tkinter | I am trying to create a calculator app using Tkinter in python.
However, when I am trying to input my text in entry box i am getting the following error.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Optimus\anaconda3\envs\virtual_enviournment\lib\tkinter\__init__.py", line 1892, in ... | [
"You have a function button_click whereas you also have a button with the same name. Hence when you are passing a function in the command, the button calls by that name but by that time the button_click is just a Button that isn't callable.\nRename the function to Click_Button or rename the button in case the funct... | [
1,
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074498888_python_tkinter.txt |
Q:
PermissionError: [Errno 1] Operation not permitted after macOS Catalina Update
After installing macOS 10.15 Catalina I am getting the following error for simple file and directory operations in Python 3.x: "PermissionError: [Errno 1] Operation not permitted"
Several operations trigger this error including opening ... | PermissionError: [Errno 1] Operation not permitted after macOS Catalina Update | After installing macOS 10.15 Catalina I am getting the following error for simple file and directory operations in Python 3.x: "PermissionError: [Errno 1] Operation not permitted"
Several operations trigger this error including opening an existing file from the cwd using open(...,'rb'), listdir() and getcwd().
After up... | [
"Go to System Preference->Security and Privacy.\nIn the below image, see Label 1\nOn the left side click on Full Disk Access see Label 2\nNow click on bottom left lock icon and enter password to make changes, see Label 3\nNow click on + sign button, see Label 4\nBrowse the terminal app from Application -> Utilities... | [
75,
11,
2,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"macos_catalina",
"permissions",
"python"
] | stackoverflow_0058479686_macos_catalina_permissions_python.txt |
Q:
How to use pylint as a bazel run/build command?
I have seen some threads that show me how to use Pylint as a test inside bazel.
However, I want to use Pylint with one of the following commands:
bazel run --config=pylint
or
bazel build --config=pylint
What would be the best strategy here?
In the future, I will us... | How to use pylint as a bazel run/build command? | I have seen some threads that show me how to use Pylint as a test inside bazel.
However, I want to use Pylint with one of the following commands:
bazel run --config=pylint
or
bazel build --config=pylint
What would be the best strategy here?
In the future, I will use the same strategy to also implement black and build... | [
"This is explained in the documentation. You have to setup an alias() rule that points to the correct entry_point():\nload(\"@pip_deps//:requirements.bzl\", \"entry_point\")\n\nalias(\n name = \"pylint\",\n actual = entry_point(\"pylint\"),\n)\n\nThis should then be executable via bazel run :pylint.\n"
] | [
0
] | [] | [] | [
"bazel",
"pylint",
"python"
] | stackoverflow_0074293557_bazel_pylint_python.txt |
Q:
Step-by-step debugging with IPython
From what I have read, there are two ways to debug code in Python:
With a traditional debugger such as pdb or ipdb. This supports commands such as c for continue, n for step-over, s for step-into etc.), but you don't have direct access to an IPython shell which can be extremely... | Step-by-step debugging with IPython | From what I have read, there are two ways to debug code in Python:
With a traditional debugger such as pdb or ipdb. This supports commands such as c for continue, n for step-over, s for step-into etc.), but you don't have direct access to an IPython shell which can be extremely useful for object inspection.
Using IP... | [
"What about ipdb.set_trace() ? In your code :\nimport ipdb; ipdb.set_trace()\nupdate: now in Python 3.7, we can write breakpoint(). It works the same, but it also obeys to the PYTHONBREAKPOINT environment variable. This feature comes from this PEP.\nThis allows for full inspection of your code, and you have access ... | [
120,
81,
40,
19,
13,
7,
6,
4,
4,
3,
2,
2,
2,
1,
1,
0
] | [] | [] | [
"debugging",
"emacs",
"ipython",
"pdb",
"python"
] | stackoverflow_0016867347_debugging_emacs_ipython_pdb_python.txt |
Q:
I want different authentication system for normal user and admin user in Django?
I create a website where there is a normal user and admin. They both have different log in system.But the problem is when a user logged in as a user, he also logged in into admin page. Also when a admin logged in, he also logged in in... | I want different authentication system for normal user and admin user in Django? | I create a website where there is a normal user and admin. They both have different log in system.But the problem is when a user logged in as a user, he also logged in into admin page. Also when a admin logged in, he also logged in into user page.
def userlogin(request):
error = ""
if request.method == 'POST':
... | [
"Make some roles explicitly in SignUp model as follows as Django provides that too:\n\nadmin\nstaff\nsimple user/regular user\n\nDefine the role of each user in the SignUp model. If a regular user is logged in it will definitely be filtered from the signUp model and that will return him/her as a regular/simple user... | [
0,
0
] | [] | [] | [
"authentication",
"django",
"django_models",
"python"
] | stackoverflow_0074498025_authentication_django_django_models_python.txt |
Q:
Python; TypeError: 'str' object is not callable
So basically I don't understand why my code is giving me this error, I tried looking it up, but I do not understand the error or how it affects me. This is my code for a simple shop simulator.
isBuying = True
#Create a map for our store's inventory. Each item in our... | Python; TypeError: 'str' object is not callable | So basically I don't understand why my code is giving me this error, I tried looking it up, but I do not understand the error or how it affects me. This is my code for a simple shop simulator.
isBuying = True
#Create a map for our store's inventory. Each item in our store will have a string name and a floating point n... | [
"You redefine the input builtin function\ninput = input('What would you like to buy?\\n')\n\nand now it's just a string. After that you call the input\nanswer = input('Would you like to continue shopping?\\n')\n\nbut it is just a string (str) not a function. This is why you shouldn't use builtin functions as variab... | [
1
] | [] | [] | [
"input",
"python",
"string",
"typeerror"
] | stackoverflow_0074499086_input_python_string_typeerror.txt |
Q:
How do you split an array into specific intervals in Num.py for Python?
The question follows a such:
x = np.arange(100)
Write Python code to split the following array at these intervals: 10, 25, 45, 75, 95
I have used the split function and unable to get at these specific intervals, can anyone enlighten me on anot... | How do you split an array into specific intervals in Num.py for Python? | The question follows a such:
x = np.arange(100)
Write Python code to split the following array at these intervals: 10, 25, 45, 75, 95
I have used the split function and unable to get at these specific intervals, can anyone enlighten me on another method or am i doing it wrongly?
| [
"Here's both the manual way and the numpy way with split.\n# Manual method\nx = np.arange(100)\nsplit_indices = [10, 25, 45, 75, 95]\n\nsplit_arrays = []\nfor i, j in zip([0]+split_indices[:-1], split_indices):\n split_arrays.append(x[i:j])\n\nprint(split_arrays)\n\n# Numpy method\nsplit_arrays_np = np.split(x, ... | [
0
] | [] | [] | [
"arrays",
"concatenation",
"numpy",
"python",
"split"
] | stackoverflow_0074499101_arrays_concatenation_numpy_python_split.txt |
Q:
How is the value assigned to Dictionary?
This is a very simple problem where it reads file from a CSV with first column header as "title" and then counts how many times the title appears in side the dictionary. But I am not understanding in which step it is assigning the "title" to "titles" dictionary.
The code is... | How is the value assigned to Dictionary? | This is a very simple problem where it reads file from a CSV with first column header as "title" and then counts how many times the title appears in side the dictionary. But I am not understanding in which step it is assigning the "title" to "titles" dictionary.
The code is:
import csv
titles = {}
with open("movies.c... | [
"In your second version, you have this line titles[title], which is not adding the title to your titles dictionary as you do in your first version. Since the title is missing in the dictionary, accessing it will give you a key value error. Why do you have a line titles[title] that does nothing?\nBut I think there's... | [
1,
0
] | [] | [] | [
"cs50",
"csv",
"dictionary",
"python",
"title"
] | stackoverflow_0074499036_cs50_csv_dictionary_python_title.txt |
Q:
accessing private websocket data from tradingview in python
I am able to get live ticker data and the prior 500-100 candle chart data with this code but I am unable to get data that isn't delayed for CME_MINI:ESH2021. TradingView puts a 600 second delay I believe on the public stream. I do pay for the data and I c... | accessing private websocket data from tradingview in python | I am able to get live ticker data and the prior 500-100 candle chart data with this code but I am unable to get data that isn't delayed for CME_MINI:ESH2021. TradingView puts a 600 second delay I believe on the public stream. I do pay for the data and I can pull it up on the web client but I am unable to get the non-de... | [
"This post is quite old, and the OP probably has the answer already, but regardless, I'm posting for people who visit this page in the future.\nThis solution comes from the Github page here: https://github.com/rushic24/tradingview-scraper\nIn fact, what I'm about to post is literally on the front page of that link.... | [
3,
0
] | [] | [] | [
"python",
"tradingview_api",
"websocket"
] | stackoverflow_0065731895_python_tradingview_api_websocket.txt |
Q:
How to remove only the last letter in string, python?
I am making a "Wordle" type of game in Python and wanted to remove the last letters you wrote when you press backspace and it worked in most cases but I have a problem if your word has the letter that are the same for example "start".
I tried using the .replace... | How to remove only the last letter in string, python? | I am making a "Wordle" type of game in Python and wanted to remove the last letters you wrote when you press backspace and it worked in most cases but I have a problem if your word has the letter that are the same for example "start".
I tried using the .replace() function like this:
word = 'start'
new_word = word.repla... | [] | [] | [
"Extract from the total length of the word the last character, like this for example:\nword = 'start'\nnew_word = word[:len(word)-1]\nprint(new_word)\n",
"word = 'start'\nnew_word = word.replace(word[1], word[4]) #replaces letter 1 with letter 4\nnew_word = new_word[:-1] #removes last letter\nprint(new_word)\n\n"... | [
-2,
-2
] | [
"letter",
"python",
"replace",
"string"
] | stackoverflow_0074498947_letter_python_replace_string.txt |
Q:
How to get a dict lookup by adjacent value
I have the following object:
ancestorTitles': [{
u 'contentType': u 'SERIES',
u 'titleId': u 'B00ERMZZRA',
u 'title': u 'Criminal Minds'
}, {
u 'contentType': u 'SEASON',
u 'number': 10,
u 'titleId': u 'B00SSFZWB6',
u 'title': u 'Criminal Minds... | How to get a dict lookup by adjacent value | I have the following object:
ancestorTitles': [{
u 'contentType': u 'SERIES',
u 'titleId': u 'B00ERMZZRA',
u 'title': u 'Criminal Minds'
}, {
u 'contentType': u 'SEASON',
u 'number': 10,
u 'titleId': u 'B00SSFZWB6',
u 'title': u 'Criminal Minds Staffel 10'
}]
How would I get the titleId of ... | [
">>> [item.get('titleId') for item in t if item.get('contentType') == 'SERIES'][0]\n'B00ERMZZRA'\n\n",
"I reverse engineered your answer to make a reusable function\ndef get_dict_by_value(dict_list, field, value):\n \"\"\"returns dictionary with specific value in given field\"\"\"\n for d in dict_list:\n ... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0032729949_python.txt |
Q:
Python create multiple dictionaries from values read from a list
I have the following list of values: Numbers = [1,2,3,4].
Is it possible to create a dictionary with the same name as the values contained in the list?
Example: dictionary_1 = {}
dictionary_2 = {}
....
dictionary_Number.. {}
I would like to create... | Python create multiple dictionaries from values read from a list | I have the following list of values: Numbers = [1,2,3,4].
Is it possible to create a dictionary with the same name as the values contained in the list?
Example: dictionary_1 = {}
dictionary_2 = {}
....
dictionary_Number.. {}
I would like to create these dictionaries automatically, without creating them manually, read... | [
"You may use the keyword exec in python. Here is an example of your solution,\nList = [1, 2,3]\nfor ele in List:\n dic = f\"Dictionary_{ele}\"\n exec(dic+\" = {}\")\nprint(Dictionary_1, Dictionary_2, Dictionary_3, sep='\\n') \n\nyou may use it according to you, but the disadvantage for it is that you will nee... | [
1,
0
] | [] | [] | [
"arrays",
"dictionary",
"python"
] | stackoverflow_0074499073_arrays_dictionary_python.txt |
Q:
How to sup up rows within a dictionary?
I have a dictionary:
{
"account": "x*", 'amount': 300, 'day': 3, 'month': 'June',
"account": "y*", 'amount': 550, 'day': 9, 'month': 'May',
"account": 'z*', 'amount': -200, 'day': 21, 'month': 'June'
"account" : "g", "amount" : 80" "day" : 10" month" : "May"
}
How do I find... | How to sup up rows within a dictionary? | I have a dictionary:
{
"account": "x*", 'amount': 300, 'day': 3, 'month': 'June',
"account": "y*", 'amount': 550, 'day': 9, 'month': 'May',
"account": 'z*', 'amount': -200, 'day': 21, 'month': 'June'
"account" : "g", "amount" : 80" "day" : 10" month" : "May"
}
How do I find the total amount for each month June and May... | [
"You can filter which elements to sum, by adding an if statement at the end of the one-liner for-loop:\nsum(d['amount'] for d in my_dict if d['month'] == month)\n\nThen, we can wrap this line of code inside a small function to compute the results for May and June:\nmy_dict = [{'account': 'x*', 'amount': 300, 'day'... | [
1
] | [] | [] | [
"dictionary",
"python",
"sum"
] | stackoverflow_0074499128_dictionary_python_sum.txt |
Q:
convert elements in list of lists by another list of lists
Hi there I have 2 list of lists as the example below:
list1=[['a','b','c'],
['d','e','f'],
['g','h','d'],
['n','m','j']]
list2 is list of lists of indice of list1
list2=[[0,2],
[1,3]]
#output :
list2=[[['a','b','c'],['g','h','d... | convert elements in list of lists by another list of lists | Hi there I have 2 list of lists as the example below:
list1=[['a','b','c'],
['d','e','f'],
['g','h','d'],
['n','m','j']]
list2 is list of lists of indice of list1
list2=[[0,2],
[1,3]]
#output :
list2=[[['a','b','c'],['g','h','d']],
[['d','e','f'],['n','m','j']]]
i want to convert ele... | [
"This simple code works:\nfor lis in list2:\n for i in range(len(lis)):\n lis[i] = list1[lis[i]]\n\nAnother more convoluted version, that works for more depths of list embedding:\ndef lreplace(l2, l1):\n for obj in l2:\n if type(obj)==list:\n lreplace(obj, l1)\n else:\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074499194_python.txt |
Q:
APK app is crashing when I use mysql Localhost
I just finish with designing the app interface and connect it to MySql db for send and retrieve data,
I was excited to convert it to an APK file and test it on my Android, application works fine but whenever I try to communicate with my database, app is crashing, Even... | APK app is crashing when I use mysql Localhost | I just finish with designing the app interface and connect it to MySql db for send and retrieve data,
I was excited to convert it to an APK file and test it on my Android, application works fine but whenever I try to communicate with my database, app is crashing, Even I am using Try ,Except statement
at this point I gu... | [
"I Solved this issue, and It was Stupid mistake, but I want to share the problem because anyone new with this like me could fall to same mistake,\nI created remote user in MySQL and give it password contain special character (&), for some reason you can't access to sever with special character.\nThat was the whole ... | [
0
] | [] | [] | [
"kivy",
"mysql",
"python"
] | stackoverflow_0074148767_kivy_mysql_python.txt |
Q:
Send email at specific time with millisecond precision
I would like to send email at given time preferably using gmail. The rationale behind this is that the school I am applying is ordering candidates based on when they receive the participation email after given time.
I could use gmail schedule send feature but ... | Send email at specific time with millisecond precision | I would like to send email at given time preferably using gmail. The rationale behind this is that the school I am applying is ordering candidates based on when they receive the participation email after given time.
I could use gmail schedule send feature but there is X delay between sending email from gmail server to ... | [
"You need to supply the login to the account, as well as an apps password. You cant just send an email without being authenticated to the mail server.\nwith smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:\n print( 'waiting to login...')\n server.login(sender_email, password)\n print( '... | [
0
] | [] | [] | [
"gmail",
"python",
"smtp"
] | stackoverflow_0074496302_gmail_python_smtp.txt |
Q:
How to Vectorize for loop/pandad iterrows with condition outside of loop python
I am trying to make a set of code I have faster using vectorization in Pandas (or NumPy). I basically need to have a "trailing" condition as I loop through each row of a dataframe so that I can create a condition based on that.
exampl... | How to Vectorize for loop/pandad iterrows with condition outside of loop python | I am trying to make a set of code I have faster using vectorization in Pandas (or NumPy). I basically need to have a "trailing" condition as I loop through each row of a dataframe so that I can create a condition based on that.
example code:
lst1 = pd.DataFrame([[1, 2, 3],
[4, 5, 6],
... | [
"Although I mentioned in my comment that programs like these aren't usually vectorizable, your code doesn't actually have the read-after-write dependency. In pure NumPy, we can simplify your code to something of the form:\nimport numpy as np\n\ndef process_arrays(A, B):\n C = np.zeros_like(A, dtype=np.bool)\n ... | [
0
] | [] | [] | [
"loops",
"numpy",
"pandas",
"python",
"vectorization"
] | stackoverflow_0074497979_loops_numpy_pandas_python_vectorization.txt |
Q:
How to show exe file in right click context menu in Python for desktop software / app?
I wrote a python script and then convert it into executable file.
In below image you can see my exe file.
my exe file.
Now, I want to show my exe file in context menu after right click only on the folder, I also want to take fol... | How to show exe file in right click context menu in Python for desktop software / app? | I wrote a python script and then convert it into executable file.
In below image you can see my exe file.
my exe file.
Now, I want to show my exe file in context menu after right click only on the folder, I also want to take folder name as an argument, than user click the exe file which I want to show in a right click ... | [
"This is what I used for a simple app I wrote, it has stupid logic to check if it's run with or without arguments, and tries to add an entry to the context menu when it's run without arguments (eg. directly, not from context menu)\nJust for simple explanation:\n\nRunning the EXE directly will create a .reg file and... | [
0
] | [] | [] | [
"desktop",
"desktop_application",
"python",
"windows"
] | stackoverflow_0074498564_desktop_desktop_application_python_windows.txt |
Q:
Sweep a table in Python in a particular way
I have a table such as:
Groups SP1 SP2 SP3 SP4_1 SP4_2 SP5_1 SP5_2
G1 3 4 NA 2 4 2 1
G2 NA 1 NA 3 NA NA NA
G3 1 2 NA NA NA 8 NA
G4 4 6 NA NA NA NA NA
G5 8 9 NA NA NA NA 2
And ... | Sweep a table in Python in a particular way | I have a table such as:
Groups SP1 SP2 SP3 SP4_1 SP4_2 SP5_1 SP5_2
G1 3 4 NA 2 4 2 1
G2 NA 1 NA 3 NA NA NA
G3 1 2 NA NA NA 8 NA
G4 4 6 NA NA NA NA NA
G5 8 9 NA NA NA NA 2
And I would like to sweep that table into:
G1 ... | [
"so this is my attempt, doesn't look nice but seems working:\nt = df.melt('Groups')\nt['val'] = t['variable'].str.cat(t['value'].dropna().astype(str),sep='-')\nt['col'] = t['variable'].str[:3]\n\ndef f(x):\n return x.dropna().str.cat(sep=';') or pd.NA\n\nres = t.pivot_table('val','col','Groups',f)\n\nprint(res)\... | [
1
] | [] | [] | [
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074498398_numpy_pandas_python_python_3.x.txt |
Q:
How to filter for rows with close values across columns
I have columns of probabilities in a pandas dataframe as an output from multiclass machine learning.
I am looking to filter rows for which the model had very close probabilities between the classes for that row, and ideally only care about similar values that... | How to filter for rows with close values across columns | I have columns of probabilities in a pandas dataframe as an output from multiclass machine learning.
I am looking to filter rows for which the model had very close probabilities between the classes for that row, and ideally only care about similar values that are similar to the highest value in that row, but I'm not su... | [
"Here is an example using numpy and itertools.combinations to get the pairs of similar rows with at least N matches with 0.05:\nfrom itertools import combinations\nimport numpy as np\n\ndf2 = df.set_index('ID')\n\nN = 2\n\nout = [(a, b) for a,b in combinations(df2.index, r=2)\n if np.isclose(df2.loc[a], df2.l... | [
2,
1
] | [] | [] | [
"machine_learning",
"pandas",
"python"
] | stackoverflow_0074452015_machine_learning_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.